Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ffe9084566 |
@@ -26,7 +26,7 @@ jobs:
|
||||
path: .github/workflows/support-files/notifications/deny.message
|
||||
notification:
|
||||
needs: cargo-deny
|
||||
runs-on: custom-runner-linux
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- name: Check out repository code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
name: Daily security audit
|
||||
|
||||
on: workflow_dispatch
|
||||
jobs:
|
||||
cargo-deny:
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- name: Checkout repository code
|
||||
uses: actions/checkout@v2
|
||||
- name: Install rust toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
- name: Install cargo deny
|
||||
run: cargo install --locked cargo-deny
|
||||
- name: Run cargo deny
|
||||
run: |
|
||||
find . -name Cargo.toml -exec cargo deny --manifest-path {} check \
|
||||
advisories -A advisory-not-detected --hide-inclusion-graph \; &> \
|
||||
>(uniq &> .github/workflows/support-files/notifications/deny.message )
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: report
|
||||
path: .github/workflows/support-files/notifications/deny.message
|
||||
notification:
|
||||
needs: cargo-deny
|
||||
runs-on: custom-runner-linux
|
||||
steps:
|
||||
- name: Check out repository code
|
||||
uses: actions/checkout@v2
|
||||
- name: Download report from previous job
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: report
|
||||
path: .github/workflows/support-files/notifications
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
- name: Keybase - Node Install
|
||||
run: npm install
|
||||
working-directory: .github/workflows/support-files
|
||||
- name: Keybase - Send Notification
|
||||
env:
|
||||
NYM_NOTIFICATION_KIND: security
|
||||
NYM_PROJECT_NAME: "Daily security report"
|
||||
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
|
||||
KEYBASE_NYMBOT_USERNAME: "${{ secrets.KEYBASE_NYMBOT_USERNAME }}"
|
||||
KEYBASE_NYMBOT_PAPERKEY: "${{ secrets.KEYBASE_NYMBOT_PAPERKEY }}"
|
||||
KEYBASE_NYMBOT_TEAM: "${{ secrets.KEYBASE_NYMBOT_TEAM }}"
|
||||
KEYBASE_NYM_CHANNEL: "security"
|
||||
MATRIX_SERVER: "${{ secrets.MATRIX_SERVER }}"
|
||||
MATRIX_ROOM: "${{ secrets.MATRIX_ROOM }}"
|
||||
MATRIX_USER_ID: "${{ secrets.MATRIX_USER_ID }}"
|
||||
MATRIX_TOKEN: "${{ secrets.MATRIX_TOKEN }}"
|
||||
MATRIX_DEVICE_ID: "${{ secrets.MATRIX_DEVICE_ID }}"
|
||||
uses: docker://keybaseio/client:stable-node
|
||||
with:
|
||||
args: .github/workflows/support-files/notifications/entry_point.sh
|
||||
@@ -56,7 +56,6 @@ jobs:
|
||||
|
||||
- uses: actions-rs/clippy-check@v1
|
||||
name: Clippy checks
|
||||
continue-on-error: true
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
args: --workspace --all-features
|
||||
|
||||
@@ -45,7 +45,6 @@ jobs:
|
||||
|
||||
- uses: actions-rs/clippy-check@v1
|
||||
name: Clippy checks
|
||||
continue-on-error: true
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
args: --manifest-path nym-connect/Cargo.toml --workspace --all-features
|
||||
|
||||
@@ -83,7 +83,6 @@ jobs:
|
||||
|
||||
- uses: actions-rs/clippy-check@v1
|
||||
name: Clippy checks
|
||||
continue-on-error: true
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
args: --all-features
|
||||
@@ -161,7 +160,7 @@ jobs:
|
||||
|
||||
notification:
|
||||
needs: build
|
||||
runs-on: custom-runner-linux
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- name: Collect jobs status
|
||||
uses: technote-space/workflow-conclusion-action@v2
|
||||
|
||||
@@ -98,7 +98,6 @@ jobs:
|
||||
|
||||
- uses: actions-rs/clippy-check@v1
|
||||
name: Clippy checks
|
||||
continue-on-error: true
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
args: --all-features
|
||||
@@ -176,7 +175,7 @@ jobs:
|
||||
|
||||
notification:
|
||||
needs: [build,get_release]
|
||||
runs-on: custom-runner-linux
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- name: Collect jobs status
|
||||
uses: technote-space/workflow-conclusion-action@v2
|
||||
|
||||
@@ -98,7 +98,6 @@ jobs:
|
||||
|
||||
- uses: actions-rs/clippy-check@v1
|
||||
name: Clippy checks
|
||||
continue-on-error: true
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
args: --all-features
|
||||
@@ -176,7 +175,7 @@ jobs:
|
||||
|
||||
notification:
|
||||
needs: [build,get_release]
|
||||
runs-on: custom-runner-linux
|
||||
runs-on: ubuntu-20.04
|
||||
steps:
|
||||
- name: Collect jobs status
|
||||
uses: technote-space/workflow-conclusion-action@v2
|
||||
|
||||
@@ -48,7 +48,6 @@ jobs:
|
||||
|
||||
- uses: actions-rs/clippy-check@v1
|
||||
name: Clippy checks
|
||||
continue-on-error: true
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
args: --manifest-path nym-wallet/Cargo.toml --workspace --all-features
|
||||
|
||||
@@ -41,4 +41,3 @@ storybook-static
|
||||
envs/qwerty.env
|
||||
Cargo.lock
|
||||
nym-connect/Cargo.lock
|
||||
.parcel-cache
|
||||
|
||||
@@ -7,7 +7,6 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
|
||||
### Added
|
||||
|
||||
- nym-sdk: added initial version of a Rust client sdk
|
||||
- nym-api: added `/circulating-supply` endpoint ([#2814])
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -21,7 +20,6 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
|
||||
|
||||
[#2753]: https://github.com/nymtech/nym/pull/2753
|
||||
[#2762]: https://github.com/nymtech/nym/pull/2762
|
||||
[#2814]: https://github.com/nymtech/nym/pull/2814
|
||||
|
||||
## [v1.1.5] (2022-01-10)
|
||||
|
||||
|
||||
Generated
+926
-754
File diff suppressed because it is too large
Load Diff
@@ -20,7 +20,7 @@ serde_json = "1.0.89"
|
||||
tap = "1.0.1"
|
||||
thiserror = "1.0.34"
|
||||
url = { version ="2.2", features = ["serde"] }
|
||||
tokio = { version = "1.24.1", features = ["macros"]}
|
||||
tokio = { version = "1.21.2", features = ["macros"]}
|
||||
time = "0.3.17"
|
||||
|
||||
# internal
|
||||
@@ -38,11 +38,11 @@ validator-client = { path = "../../common/client-libs/validator-client", default
|
||||
task = { path = "../../common/task" }
|
||||
|
||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio-stream]
|
||||
version = "0.1.11"
|
||||
version = "0.1.9"
|
||||
features = ["time"]
|
||||
|
||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio]
|
||||
version = "1.24.1"
|
||||
version = "1.21.2"
|
||||
features = ["time"]
|
||||
|
||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.sqlx]
|
||||
@@ -75,7 +75,7 @@ features = ["wasm-bindgen"]
|
||||
tempfile = "3.1.0"
|
||||
|
||||
[build-dependencies]
|
||||
tokio = { version = "1.24.1", features = ["rt-multi-thread", "macros"] }
|
||||
tokio = { version = "1.21.2", features = ["rt-multi-thread", "macros"] }
|
||||
sqlx = { version = "0.6.2", features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"] }
|
||||
|
||||
[features]
|
||||
|
||||
@@ -9,9 +9,9 @@ async fn main() {
|
||||
use std::env;
|
||||
|
||||
let out_dir = env::var("OUT_DIR").unwrap();
|
||||
let database_path = format!("{out_dir}/fs-surbs-example.sqlite");
|
||||
let database_path = format!("{}/fs-surbs-example.sqlite", out_dir);
|
||||
|
||||
let mut conn = SqliteConnection::connect(&format!("sqlite://{database_path}?mode=rwc"))
|
||||
let mut conn = SqliteConnection::connect(&format!("sqlite://{}?mode=rwc", database_path))
|
||||
.await
|
||||
.expect("Failed to create SQLx database connection");
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ fn archive_corrupted_database<P: AsRef<Path>>(db_path: P) -> io::Result<()> {
|
||||
|
||||
let new_extension =
|
||||
if let Some(existing_extension) = db_path.extension().and_then(|ext| ext.to_str()) {
|
||||
format!("{existing_extension}.{suffix}")
|
||||
format!("{existing_extension}.{}", suffix)
|
||||
} else {
|
||||
suffix
|
||||
};
|
||||
|
||||
@@ -42,6 +42,9 @@ pub struct KeyManager {
|
||||
*/
|
||||
|
||||
impl KeyManager {
|
||||
// this is actually **NOT** dead code
|
||||
// I have absolutely no idea why the compiler insists it's unused. The call happens during client::init::execute
|
||||
#[allow(dead_code)]
|
||||
/// Creates new instance of a [`KeyManager`]
|
||||
pub fn new<R>(rng: &mut R) -> Self
|
||||
where
|
||||
@@ -127,6 +130,9 @@ impl KeyManager {
|
||||
Ok(key_manager)
|
||||
}
|
||||
|
||||
// this is actually **NOT** dead code
|
||||
// I have absolutely no idea why the compiler insists it's unused. The call happens during client::init::execute
|
||||
#[allow(dead_code)]
|
||||
/// Stores all available keys on the disk.
|
||||
// While perhaps there is no much point in storing the `AckKey` on the disk,
|
||||
// it is done so for the consistency sake so that you wouldn't require an rng instance
|
||||
@@ -205,6 +211,9 @@ impl KeyManager {
|
||||
Arc::clone(&self.ack_key)
|
||||
}
|
||||
|
||||
// this is actually **NOT** dead code
|
||||
// I have absolutely no idea why the compiler insists it's unused. The call happens during client::init::execute
|
||||
#[allow(dead_code)]
|
||||
/// After shared key with the gateway is derived, puts its ownership to this instance of a [`KeyManager`].
|
||||
pub fn insert_gateway_shared_key(&mut self, gateway_shared_key: Arc<SharedKeys>) {
|
||||
self.gateway_shared_key = Some(gateway_shared_key)
|
||||
|
||||
@@ -57,7 +57,7 @@ impl MixTrafficController {
|
||||
if self.consecutive_gateway_failure_count == MAX_FAILURE_COUNT {
|
||||
// todo: in the future this should initiate a 'graceful' shutdown or try
|
||||
// to reconnect?
|
||||
panic!("failed to send sphinx packet to the gateway {MAX_FAILURE_COUNT} times in a row - assuming the gateway is dead. Can't do anything about it yet :(")
|
||||
panic!("failed to send sphinx packet to the gateway {} times in a row - assuming the gateway is dead. Can't do anything about it yet :(", MAX_FAILURE_COUNT)
|
||||
}
|
||||
}
|
||||
Ok(_) => {
|
||||
|
||||
@@ -471,10 +471,14 @@ where
|
||||
let mult = self.sending_delay_controller.current_multiplier();
|
||||
let delay = self.current_average_message_sending_delay().as_millis();
|
||||
let status_str = if self.config.disable_poisson_packet_distribution {
|
||||
format!("Status: {lanes} lanes, backlog: {backlog:.2} kiB ({packets}), no delay")
|
||||
format!(
|
||||
"Status: {lanes} lanes, backlog: {:.2} kiB ({packets}), no delay",
|
||||
backlog
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"Status: {lanes} lanes, backlog: {backlog:.2} kiB ({packets}), avg delay: {delay}ms ({mult})"
|
||||
"Status: {lanes} lanes, backlog: {:.2} kiB ({packets}), avg delay: {}ms ({mult})",
|
||||
backlog, delay
|
||||
)
|
||||
};
|
||||
if packets > 1000 {
|
||||
|
||||
@@ -44,7 +44,8 @@ impl TryFrom<StoredSenderTag> for (RecipientBytes, AnonymousSenderTag) {
|
||||
let Ok(sender_tag_bytes) = value.tag.try_into() else {
|
||||
return Err(StorageError::CorruptedData {
|
||||
details: format!(
|
||||
"the retrieved sender tag has length of {tag_len} while {SENDER_TAG_SIZE} was expected",
|
||||
"the retrieved sender tag has length of {tag_len} while {} was expected",
|
||||
SENDER_TAG_SIZE
|
||||
),
|
||||
});
|
||||
};
|
||||
@@ -131,7 +132,8 @@ impl TryFrom<StoredSurbSender> for (AnonymousSenderTag, i64) {
|
||||
let Ok(sender_tag_bytes) = value.tag.try_into() else {
|
||||
return Err(StorageError::CorruptedData {
|
||||
details: format!(
|
||||
"the retrieved sender tag has length of {tag_len} while {SENDER_TAG_SIZE} was expected",
|
||||
"the retrieved sender tag has length of {tag_len} while {} was expected",
|
||||
SENDER_TAG_SIZE
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -88,7 +88,6 @@ impl<T> Config<T> {
|
||||
Config::default().with_id(id)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_id<S: Into<String>>(mut self, id: S) -> Self
|
||||
where
|
||||
T: NymConfig,
|
||||
|
||||
@@ -65,10 +65,8 @@ pub enum ClientCoreError {
|
||||
/// Set of messages that the client can send to listeners via the task manager
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum ClientCoreStatusMessage {
|
||||
// NOTE: The nym-connect frontend listens for these strings, so don't change them until we have a more robust mechanism in place
|
||||
#[error("The connected gateway is slow, or the connection to it is slow")]
|
||||
GatewayIsSlow,
|
||||
// NOTE: The nym-connect frontend listens for these strings, so don't change them until we have a more robust mechanism in place
|
||||
#[error("The connected gateway is very slow, or the connection to it is very slow")]
|
||||
GatewayIsVerySlow,
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ use url::Url;
|
||||
|
||||
pub(super) async fn query_gateway_details(
|
||||
validator_servers: Vec<Url>,
|
||||
chosen_gateway_id: Option<identity::PublicKey>,
|
||||
chosen_gateway_id: Option<String>,
|
||||
) -> Result<gateway::Node, ClientCoreError> {
|
||||
let nym_api = validator_servers
|
||||
.choose(&mut thread_rng())
|
||||
@@ -40,7 +40,7 @@ pub(super) async fn query_gateway_details(
|
||||
if let Some(gateway_id) = chosen_gateway_id {
|
||||
filtered_gateways
|
||||
.iter()
|
||||
.find(|gateway| gateway.identity_key == gateway_id)
|
||||
.find(|gateway| gateway.identity_key.to_base58_string() == gateway_id)
|
||||
.ok_or_else(|| ClientCoreError::NoGatewayWithId(gateway_id.to_string()))
|
||||
.cloned()
|
||||
} else {
|
||||
|
||||
@@ -69,38 +69,12 @@ pub fn new_client_keys() -> KeyManager {
|
||||
KeyManager::new(&mut rng)
|
||||
}
|
||||
|
||||
/// Authenticate and register with a gateway.
|
||||
/// Either pick one at random by querying the available gateways from the nym-api, or use the
|
||||
/// chosen one if it's among the available ones.
|
||||
/// The shared key is added to the supplied `KeyManager` and the endpoint details are returned.
|
||||
pub async fn register_with_gateway(
|
||||
key_manager: &mut KeyManager,
|
||||
nym_api_endpoints: Vec<Url>,
|
||||
chosen_gateway_id: Option<identity::PublicKey>,
|
||||
) -> Result<GatewayEndpointConfig, ClientCoreError> {
|
||||
// Get the gateway details of the gateway we will use
|
||||
let gateway = helpers::query_gateway_details(nym_api_endpoints, chosen_gateway_id).await?;
|
||||
log::debug!("Querying gateway gives: {}", gateway);
|
||||
|
||||
let our_identity = key_manager.identity_keypair();
|
||||
|
||||
// Establish connection, authenticate and generate keys for talking with the gateway
|
||||
let shared_keys = helpers::register_with_gateway(&gateway, our_identity).await?;
|
||||
key_manager.insert_gateway_shared_key(shared_keys);
|
||||
|
||||
Ok(gateway.into())
|
||||
}
|
||||
|
||||
/// Convenience function for setting up the gateway for a client given a `Config`. Depending on the
|
||||
/// arguments given it will do the sensible thing. Either it will
|
||||
///
|
||||
/// a. Reuse existing gateway configuration from storage.
|
||||
/// b. Create a new gateway configuration but keep existing keys. This assumes that the caller
|
||||
/// knows what they are doing and that the keys match the requested gateway.
|
||||
/// c. Create a new gateway configuration with a newly registered gateway and keys.
|
||||
pub async fn setup_gateway_from_config<C, T>(
|
||||
/// Convenience function for setting up the gateway for a client. Depending on the arguments given
|
||||
/// it will do the sensible thing.
|
||||
pub async fn setup_gateway<C, T>(
|
||||
register_gateway: bool,
|
||||
user_chosen_gateway_id: Option<identity::PublicKey>,
|
||||
// TODO: this should get refactored to instead take Option<identity::PublicKey>
|
||||
user_chosen_gateway_id: Option<String>,
|
||||
config: &Config<T>,
|
||||
) -> Result<GatewayEndpointConfig, ClientCoreError>
|
||||
where
|
||||
@@ -108,47 +82,89 @@ where
|
||||
T: NymConfig,
|
||||
{
|
||||
let id = config.get_id();
|
||||
|
||||
// If we are not going to register gateway, and an explicitly chosed gateway is not passed in,
|
||||
// load the existing configuration file
|
||||
if !register_gateway && user_chosen_gateway_id.is_none() {
|
||||
println!("Not registering gateway, will reuse existing config and keys");
|
||||
return load_existing_gateway_config::<C>(&id);
|
||||
if register_gateway {
|
||||
register_with_gateway_and_store(user_chosen_gateway_id, config).await
|
||||
} else if let Some(user_chosen_gateway_id) = user_chosen_gateway_id {
|
||||
config_gateway_with_existing_keys(user_chosen_gateway_id, config).await
|
||||
} else {
|
||||
reuse_existing_gateway_config::<C>(&id)
|
||||
}
|
||||
}
|
||||
|
||||
// Else, we preceed by querying the nym-api
|
||||
let gateway =
|
||||
helpers::query_gateway_details(config.get_nym_api_endpoints(), user_chosen_gateway_id)
|
||||
.await?;
|
||||
log::debug!("Querying gateway gives: {}", gateway);
|
||||
|
||||
// If we are not registering, just return this and assume the caller has the keys already and
|
||||
// wants to keep the,
|
||||
if !register_gateway && user_chosen_gateway_id.is_some() {
|
||||
println!("Using gateway provided by user, keeping existing keys");
|
||||
return Ok(gateway.into());
|
||||
}
|
||||
|
||||
// Create new keys and derive our identity
|
||||
let mut key_manager = new_client_keys();
|
||||
/// Get the gateway details by querying the validator-api. Either pick one at random or use
|
||||
/// the chosen one if it's among the available ones.
|
||||
pub async fn register_with_gateway(
|
||||
key_manager: &mut KeyManager,
|
||||
nym_api_endpoints: Vec<Url>,
|
||||
chosen_gateway_id: Option<String>,
|
||||
) -> Result<GatewayEndpointConfig, ClientCoreError> {
|
||||
// Our identity is derived from our key
|
||||
let our_identity = key_manager.identity_keypair();
|
||||
|
||||
// Get the gateway details of the gateway we will use
|
||||
let gateway = helpers::query_gateway_details(nym_api_endpoints, chosen_gateway_id).await?;
|
||||
log::debug!("Querying gateway gives: {}", gateway);
|
||||
|
||||
// Establish connection, authenticate and generate keys for talking with the gateway
|
||||
println!("Registering with new gateway");
|
||||
let shared_keys = helpers::register_with_gateway(&gateway, our_identity).await?;
|
||||
key_manager.insert_gateway_shared_key(shared_keys);
|
||||
|
||||
// Write all keys to storage and just return the gateway endpoint config. It is assumed that we
|
||||
// will load keys from storage when actually connecting.
|
||||
Ok(gateway.into())
|
||||
}
|
||||
|
||||
/// Get the gateway details by querying the validator-api. Either pick one at random or use
|
||||
/// the chosen one if it's among the available ones.
|
||||
/// Saves keys to disk, specified by the paths in `config`.
|
||||
pub async fn register_with_gateway_and_store<T>(
|
||||
chosen_gateway_id: Option<String>,
|
||||
config: &Config<T>,
|
||||
) -> Result<GatewayEndpointConfig, ClientCoreError>
|
||||
where
|
||||
T: NymConfig,
|
||||
{
|
||||
println!("Configuring gateway");
|
||||
let mut key_manager = new_client_keys();
|
||||
|
||||
let gateway = register_with_gateway(
|
||||
&mut key_manager,
|
||||
config.get_nym_api_endpoints(),
|
||||
chosen_gateway_id,
|
||||
)
|
||||
.await?;
|
||||
|
||||
helpers::store_keys(&key_manager, config)?;
|
||||
println!("Saved all generated keys");
|
||||
|
||||
Ok(gateway)
|
||||
}
|
||||
|
||||
/// Set the gateway using the usual procedue of querying the validator-api, but don't register or
|
||||
/// create any keys.
|
||||
/// This assumes that the user knows what they are doing, and that the existing keys are valid for
|
||||
/// the gateway being used
|
||||
pub async fn config_gateway_with_existing_keys<T>(
|
||||
user_chosen_gateway_id: String,
|
||||
config: &Config<T>,
|
||||
) -> Result<GatewayEndpointConfig, ClientCoreError>
|
||||
where
|
||||
T: NymConfig,
|
||||
{
|
||||
println!("Using gateway provided by user, keeping existing keys");
|
||||
let gateway = helpers::query_gateway_details(
|
||||
config.get_nym_api_endpoints(),
|
||||
Some(user_chosen_gateway_id),
|
||||
)
|
||||
.await?;
|
||||
log::debug!("Querying gateway gives: {}", gateway);
|
||||
Ok(gateway.into())
|
||||
}
|
||||
|
||||
/// Read and reuse the existing gateway configuration from a file that was generate earlier.
|
||||
pub fn load_existing_gateway_config<T>(id: &str) -> Result<GatewayEndpointConfig, ClientCoreError>
|
||||
pub fn reuse_existing_gateway_config<T>(id: &str) -> Result<GatewayEndpointConfig, ClientCoreError>
|
||||
where
|
||||
T: NymConfig + ClientCoreConfigTrait,
|
||||
{
|
||||
println!("Not registering gateway, will reuse existing config and keys");
|
||||
T::load_from_file(Some(id))
|
||||
.map(|existing_config| existing_config.get_gateway_endpoint().clone())
|
||||
.map_err(|err| {
|
||||
@@ -226,9 +242,9 @@ where
|
||||
pub fn output_to_json<T: Serialize>(init_results: &T, output_file: &str) {
|
||||
match std::fs::File::create(output_file) {
|
||||
Ok(file) => match serde_json::to_writer_pretty(file, init_results) {
|
||||
Ok(_) => println!("Saved: {output_file}"),
|
||||
Err(err) => eprintln!("Could not save {output_file}: {err}"),
|
||||
Ok(_) => println!("Saved: {}", output_file),
|
||||
Err(err) => eprintln!("Could not save {}: {err}", output_file),
|
||||
},
|
||||
Err(err) => eprintln!("Could not save {output_file}: {err}"),
|
||||
Err(err) => eprintln!("Could not save {}: {err}", output_file),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ rand = "0.7.3"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
thiserror = "1.0"
|
||||
url = "2.2"
|
||||
tokio = { version = "1.24.1", features = ["rt-multi-thread", "net", "signal", "macros"] } # async runtime
|
||||
tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal", "macros"] } # async runtime
|
||||
|
||||
coconut-interface = { path = "../../common/coconut-interface" }
|
||||
config = { path = "../../common/config" }
|
||||
|
||||
@@ -30,7 +30,7 @@ serde = { version = "1.0.104", features = ["derive"] } # for config serializatio
|
||||
serde_json = "1.0"
|
||||
thiserror = "1.0.34"
|
||||
tap = "1.0.1"
|
||||
tokio = { version = "1.24.1", features = ["rt-multi-thread", "net", "signal"] } # async runtime
|
||||
tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal"] } # async runtime
|
||||
tokio-tungstenite = "0.14" # websocket
|
||||
|
||||
## internal
|
||||
|
||||
@@ -85,7 +85,7 @@ async fn send_file_without_reply() {
|
||||
let (mut ws_stream, _) = connect_async(uri).await.unwrap();
|
||||
|
||||
let recipient = get_self_address(&mut ws_stream).await;
|
||||
println!("our full address is: {recipient}");
|
||||
println!("our full address is: {}", recipient);
|
||||
|
||||
let read_data = std::fs::read("examples/dummy_file").unwrap();
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ async fn send_text_with_reply() {
|
||||
let (mut ws_stream, _) = connect_async(uri).await.unwrap();
|
||||
|
||||
let recipient = get_self_address(&mut ws_stream).await;
|
||||
println!("our full address is: {recipient}");
|
||||
println!("our full address is: {}", recipient);
|
||||
|
||||
let send_request = json!({
|
||||
"type" : "send",
|
||||
@@ -45,7 +45,10 @@ async fn send_text_with_reply() {
|
||||
"withReplySurb": true,
|
||||
});
|
||||
|
||||
println!("sending {message:?} (*with* reply SURB) over the mix network...");
|
||||
println!(
|
||||
"sending {:?} (*with* reply SURB) over the mix network...",
|
||||
message
|
||||
);
|
||||
let response =
|
||||
send_message_and_get_json_response(&mut ws_stream, send_request.to_string()).await;
|
||||
|
||||
@@ -56,7 +59,10 @@ async fn send_text_with_reply() {
|
||||
"replySurb": response["replySurb"]
|
||||
});
|
||||
|
||||
println!("sending {reply_message:?} (using reply SURB!) over the mix network...");
|
||||
println!(
|
||||
"sending {:?} (using reply SURB!) over the mix network...",
|
||||
reply_message
|
||||
);
|
||||
|
||||
let response =
|
||||
send_message_and_get_json_response(&mut ws_stream, reply_request.to_string()).await;
|
||||
@@ -70,7 +76,7 @@ async fn send_text_without_reply() {
|
||||
let (mut ws_stream, _) = connect_async(uri).await.unwrap();
|
||||
|
||||
let recipient = get_self_address(&mut ws_stream).await;
|
||||
println!("our full address is: {recipient}");
|
||||
println!("our full address is: {}", recipient);
|
||||
|
||||
let send_request = json!({
|
||||
"type" : "send",
|
||||
@@ -79,7 +85,10 @@ async fn send_text_without_reply() {
|
||||
"withReplySurb": false,
|
||||
});
|
||||
|
||||
println!("sending {message:?} (*without* reply SURB) over the mix network...");
|
||||
println!(
|
||||
"sending {:?} (*without* reply SURB) over the mix network...",
|
||||
message
|
||||
);
|
||||
let response =
|
||||
send_message_and_get_json_response(&mut ws_stream, send_request.to_string()).await;
|
||||
|
||||
|
||||
@@ -120,9 +120,16 @@ impl SocketClient {
|
||||
|
||||
/// blocking version of `start_socket` method. Will run forever (or until SIGINT is sent)
|
||||
pub async fn run_socket_forever(self) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let shutdown = self.start_socket().await?;
|
||||
let mut shutdown = self.start_socket().await?;
|
||||
|
||||
let res = task::wait_for_signal_and_error(&mut shutdown).await;
|
||||
|
||||
log::info!("Sending shutdown");
|
||||
shutdown.signal_shutdown().ok();
|
||||
|
||||
log::info!("Waiting for tasks to finish... (Press ctrl-c to force)");
|
||||
shutdown.wait_for_shutdown().await;
|
||||
|
||||
let res = shutdown.catch_interrupt().await;
|
||||
log::info!("Stopping nym-client");
|
||||
res
|
||||
}
|
||||
|
||||
@@ -114,15 +114,16 @@ pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> {
|
||||
|
||||
let already_init = Config::default_config_file_path(Some(id)).exists();
|
||||
if already_init {
|
||||
println!("Client \"{id}\" was already initialised before");
|
||||
println!(
|
||||
"Client \"{}\" was already initialised before! \
|
||||
Config information will be overwritten (but keys will be kept)!",
|
||||
id
|
||||
);
|
||||
}
|
||||
|
||||
// Usually you only register with the gateway on the first init, however you can force
|
||||
// re-registering if wanted.
|
||||
let user_wants_force_register = args.force_register_gateway;
|
||||
if user_wants_force_register {
|
||||
println!("Instructed to force registering gateway. This might overwrite keys!");
|
||||
}
|
||||
|
||||
// If the client was already initialized, don't generate new keys and don't re-register with
|
||||
// the gateway (because this would create a new shared key).
|
||||
@@ -137,9 +138,9 @@ pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> {
|
||||
|
||||
// Setup gateway by either registering a new one, or creating a new config from the selected
|
||||
// one but with keys kept, or reusing the gateway configuration.
|
||||
let gateway = client_core::init::setup_gateway_from_config::<Config, _>(
|
||||
let gateway = client_core::init::setup_gateway::<Config, _>(
|
||||
register_gateway,
|
||||
user_chosen_gateway_id,
|
||||
user_chosen_gateway_id.map(|id| id.to_base58_string()),
|
||||
config.get_base(),
|
||||
)
|
||||
.await
|
||||
@@ -168,7 +169,7 @@ pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> {
|
||||
|
||||
fn print_saved_config(config: &Config) {
|
||||
let config_save_location = config.get_config_file_save_location();
|
||||
println!("Saved configuration file to {config_save_location:?}");
|
||||
println!("Saved configuration file to {:?}", config_save_location);
|
||||
println!("Using gateway: {}", config.get_base().get_gateway_id());
|
||||
log::debug!("Gateway id: {}", config.get_base().get_gateway_id());
|
||||
log::debug!("Gateway owner: {}", config.get_base().get_gateway_owner());
|
||||
|
||||
@@ -17,26 +17,36 @@ fn fail_upgrade<D1: Display, D2: Display>(from_version: D1, to_version: D2) -> !
|
||||
}
|
||||
|
||||
fn print_start_upgrade<D1: Display, D2: Display>(from: D1, to: D2) {
|
||||
println!("\n==================\nTrying to upgrade client from {from} to {to} ...");
|
||||
println!(
|
||||
"\n==================\nTrying to upgrade client from {} to {} ...",
|
||||
from, to
|
||||
);
|
||||
}
|
||||
|
||||
fn print_failed_upgrade<D1: Display, D2: Display>(from: D1, to: D2) {
|
||||
eprintln!("Upgrade from {from} to {to} failed!\n==================\n");
|
||||
eprintln!(
|
||||
"Upgrade from {} to {} failed!\n==================\n",
|
||||
from, to
|
||||
);
|
||||
}
|
||||
|
||||
fn print_successful_upgrade<D1: Display, D2: Display>(from: D1, to: D2) {
|
||||
println!("Upgrade from {from} to {to} was successful!\n==================\n");
|
||||
println!(
|
||||
"Upgrade from {} to {} was successful!\n==================\n",
|
||||
from, to
|
||||
);
|
||||
}
|
||||
|
||||
fn outdated_upgrade(config_version: &Version, package_version: &Version) -> ! {
|
||||
eprintln!(
|
||||
"Cannot perform upgrade from {config_version} to {package_version}. Your version is too old to perform the upgrade.!"
|
||||
"Cannot perform upgrade from {} to {}. Your version is too old to perform the upgrade.!",
|
||||
config_version, package_version
|
||||
);
|
||||
process::exit(1)
|
||||
}
|
||||
|
||||
fn unsupported_upgrade(current_version: &Version, config_version: &Version) -> ! {
|
||||
eprintln!("Cannot perform upgrade from {config_version} to {current_version}. Please let the developers know about this issue if you expected it to work!");
|
||||
eprintln!("Cannot perform upgrade from {} to {}. Please let the developers know about this issue if you expected it to work!", config_version, current_version);
|
||||
process::exit(1)
|
||||
}
|
||||
|
||||
@@ -55,7 +65,8 @@ fn parse_config_version(config: &Config) -> Version {
|
||||
|
||||
if version.is_prerelease() || !version.build.is_empty() {
|
||||
eprintln!(
|
||||
"Trying to upgrade from a non-released version {version}. This is not supported!"
|
||||
"Trying to upgrade from a non-released version {}. This is not supported!",
|
||||
version
|
||||
);
|
||||
process::exit(1)
|
||||
}
|
||||
@@ -70,7 +81,10 @@ fn parse_package_version() -> Version {
|
||||
// however, we are not using them ourselves at the moment and hence it should be fine.
|
||||
// if we change our mind, we could easily tweak this code
|
||||
if version.is_prerelease() || !version.build.is_empty() {
|
||||
eprintln!("Trying to upgrade to a non-released version {version}. This is not supported!");
|
||||
eprintln!(
|
||||
"Trying to upgrade to a non-released version {}. This is not supported!",
|
||||
version
|
||||
);
|
||||
process::exit(1)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::error::Error;
|
||||
|
||||
use clap::{crate_name, crate_version, Parser};
|
||||
use clap::{crate_version, Parser};
|
||||
use logging::setup_logging;
|
||||
use network_defaults::setup_env;
|
||||
|
||||
@@ -15,9 +15,26 @@ pub mod websocket;
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
setup_logging();
|
||||
println!("{}", logging::banner(crate_name!(), crate_version!()));
|
||||
println!("{}", banner());
|
||||
|
||||
let args = commands::Cli::parse();
|
||||
setup_env(args.config_env_file.as_ref());
|
||||
commands::execute(&args).await
|
||||
}
|
||||
|
||||
fn banner() -> String {
|
||||
format!(
|
||||
r#"
|
||||
|
||||
_ __ _ _ _ __ ___
|
||||
| '_ \| | | | '_ \ _ \
|
||||
| | | | |_| | | | | | |
|
||||
|_| |_|\__, |_| |_| |_|
|
||||
|___/
|
||||
|
||||
(client - version {:})
|
||||
|
||||
"#,
|
||||
crate_version!()
|
||||
)
|
||||
}
|
||||
|
||||
@@ -27,13 +27,17 @@ use tokio_tungstenite::{
|
||||
};
|
||||
use websocket_requests::{requests::ClientRequest, responses::ServerResponse};
|
||||
|
||||
#[derive(Default)]
|
||||
enum ReceivedResponseType {
|
||||
#[default]
|
||||
Binary,
|
||||
Text,
|
||||
}
|
||||
|
||||
impl Default for ReceivedResponseType {
|
||||
fn default() -> Self {
|
||||
ReceivedResponseType::Binary
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct HandlerBuilder {
|
||||
msg_input: InputMessageSender,
|
||||
client_connection_tx: ConnectionCommandSender,
|
||||
|
||||
@@ -84,7 +84,7 @@ impl TryFrom<u8> for ErrorKind {
|
||||
|
||||
n => Err(Error::new(
|
||||
ErrorKind::MalformedResponse,
|
||||
format!("invalid error code {n}"),
|
||||
format!("invalid error code {}", n),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ serde = { version = "1.0", features = ["derive"] } # for config serialization/de
|
||||
serde_json = "1.0.89"
|
||||
tap = "1.0.1"
|
||||
thiserror = "1.0.34"
|
||||
tokio = { version = "1.24.1", features = ["rt-multi-thread", "net", "signal"] }
|
||||
tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal"] }
|
||||
url = "2.2"
|
||||
|
||||
# internal
|
||||
|
||||
@@ -19,7 +19,7 @@ use gateway_client::bandwidth::BandwidthController;
|
||||
use log::*;
|
||||
use nymsphinx::addressing::clients::Recipient;
|
||||
use std::error::Error;
|
||||
use task::{TaskClient, TaskManager};
|
||||
use task::{wait_for_signal_and_error, TaskClient, TaskManager};
|
||||
|
||||
pub mod config;
|
||||
|
||||
@@ -147,9 +147,16 @@ impl NymClient {
|
||||
|
||||
/// blocking version of `start` method. Will run forever (or until SIGINT is sent)
|
||||
pub async fn run_forever(self) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let shutdown = self.start().await?;
|
||||
let mut shutdown = self.start().await?;
|
||||
|
||||
let res = wait_for_signal_and_error(&mut shutdown).await;
|
||||
|
||||
log::info!("Sending shutdown");
|
||||
shutdown.signal_shutdown().ok();
|
||||
|
||||
log::info!("Waiting for tasks to finish... (Press ctrl-c to force)");
|
||||
shutdown.wait_for_shutdown().await;
|
||||
|
||||
let res = shutdown.catch_interrupt().await;
|
||||
log::info!("Stopping nym-socks5-client");
|
||||
res
|
||||
}
|
||||
|
||||
@@ -124,15 +124,16 @@ pub(crate) async fn execute(args: &Init) -> Result<(), Socks5ClientError> {
|
||||
|
||||
let already_init = Config::default_config_file_path(Some(id)).exists();
|
||||
if already_init {
|
||||
println!("SOCKS5 client \"{id}\" was already initialised before");
|
||||
println!(
|
||||
"SOCKS5 client \"{}\" was already initialised before! \
|
||||
Config information will be overwritten (but keys will be kept)!",
|
||||
id
|
||||
);
|
||||
}
|
||||
|
||||
// Usually you only register with the gateway on the first init, however you can force
|
||||
// re-registering if wanted.
|
||||
let user_wants_force_register = args.force_register_gateway;
|
||||
if user_wants_force_register {
|
||||
println!("Instructed to force registering gateway. This might overwrite keys!");
|
||||
}
|
||||
|
||||
// If the client was already initialized, don't generate new keys and don't re-register with
|
||||
// the gateway (because this would create a new shared key).
|
||||
@@ -150,9 +151,9 @@ pub(crate) async fn execute(args: &Init) -> Result<(), Socks5ClientError> {
|
||||
|
||||
// Setup gateway by either registering a new one, or creating a new config from the selected
|
||||
// one but with keys kept, or reusing the gateway configuration.
|
||||
let gateway = client_core::init::setup_gateway_from_config::<Config, _>(
|
||||
let gateway = client_core::init::setup_gateway::<Config, _>(
|
||||
register_gateway,
|
||||
user_chosen_gateway_id,
|
||||
user_chosen_gateway_id.map(|id| id.to_base58_string()),
|
||||
config.get_base(),
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::error::Error;
|
||||
|
||||
use clap::{crate_name, crate_version, Parser};
|
||||
use clap::{crate_version, Parser};
|
||||
use logging::setup_logging;
|
||||
use network_defaults::setup_env;
|
||||
|
||||
@@ -15,9 +15,26 @@ pub mod socks;
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
setup_logging();
|
||||
println!("{}", logging::banner(crate_name!(), crate_version!()));
|
||||
println!("{}", banner());
|
||||
|
||||
let args = commands::Cli::parse();
|
||||
setup_env(args.config_env_file.as_ref());
|
||||
commands::execute(&args).await
|
||||
}
|
||||
|
||||
fn banner() -> String {
|
||||
format!(
|
||||
r#"
|
||||
|
||||
_ __ _ _ _ __ ___
|
||||
| '_ \| | | | '_ \ _ \
|
||||
| | | | |_| | | | | | |
|
||||
|_| |_|\__, |_| |_| |_|
|
||||
|___/
|
||||
|
||||
(socks5 proxy - version {:})
|
||||
|
||||
"#,
|
||||
crate_version!()
|
||||
)
|
||||
}
|
||||
|
||||
@@ -22,10 +22,8 @@ futures = "0.3"
|
||||
js-sys = "0.3"
|
||||
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
anyhow = "1.0"
|
||||
serde-wasm-bindgen = "0.4"
|
||||
tokio = { version = "1.24.1", features = ["sync"] }
|
||||
tokio = { version = "1.21.2", features = ["sync"] }
|
||||
url = "2.2"
|
||||
wasm-bindgen = { version = "=0.2.83", features = ["serde-serialize"] }
|
||||
wasm-bindgen-futures = "0.4"
|
||||
|
||||
@@ -16,7 +16,11 @@ They should be implemented soon. You can build your applications, but don't rely
|
||||
|
||||
## Using it
|
||||
|
||||
See the [SDK directory](../../sdk/typescript/examples) for examples on how to use it and the NPM packages available.
|
||||
See the [Nym docs](https://nymtech.net/docs).
|
||||
|
||||
### Demo
|
||||
|
||||
There's a demo web application in the `js-example` folder. To run it, first make sure you've got a recent `npm` installed, then follow the instructions in its README.
|
||||
|
||||
## Developing
|
||||
|
||||
@@ -32,13 +36,8 @@ To be clear, this is not something that most JS developers need to worry about,
|
||||
|
||||
### Packaging
|
||||
|
||||
If you're a Nym platform developer who's made changes to the Rust files and wants to re-publish the package to NPM, here's how you do it:
|
||||
If you're a Nym platform developer who's made changes to the Rust (or JS) files and wants to re-publish the package to NPM, here's how you do it:
|
||||
|
||||
1. bump version numbers as necessary for SemVer
|
||||
2. go the `sdk/typescript` directory (off the project root)
|
||||
3. run:
|
||||
```
|
||||
yarn
|
||||
yarn build
|
||||
yarn publish
|
||||
```
|
||||
2. `wasm-pack build --scope nymproject` builds the wasm binaries into the `pkg` directory (not in source control)
|
||||
3. `cd pkg && npm publish --access=public` will publish your changed package to NPM
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen::JsCast;
|
||||
|
||||
#[wasm_bindgen(typescript_custom_section)]
|
||||
const TS_DEFS: &'static str = r#"
|
||||
export interface BinaryMessage {
|
||||
kind: number,
|
||||
payload: Uint8Array;
|
||||
headers: string,
|
||||
}
|
||||
|
||||
export interface StringMessage {
|
||||
kind: number,
|
||||
payload: string;
|
||||
}
|
||||
"#;
|
||||
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(typescript_type = "BinaryMessage")]
|
||||
pub type IBinaryMessage;
|
||||
#[wasm_bindgen(typescript_type = "StringMessage")]
|
||||
pub type IStringMessage;
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct BinaryMessage {
|
||||
pub kind: u8,
|
||||
pub payload: Vec<u8>,
|
||||
pub headers: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct StringMessage {
|
||||
pub kind: u8,
|
||||
pub payload: String,
|
||||
}
|
||||
|
||||
/// Create a new binary message with a user-specified `kind`.
|
||||
#[wasm_bindgen]
|
||||
pub fn create_binary_message(kind: u8, payload: Vec<u8>) -> Vec<u8> {
|
||||
create_binary_message_with_headers(kind, payload, "".to_string())
|
||||
}
|
||||
|
||||
/// Create a new message with a UTF-8 encoded string `payload` and a user-specified `kind`.
|
||||
#[wasm_bindgen]
|
||||
pub fn create_binary_message_from_string(kind: u8, payload: String) -> Vec<u8> {
|
||||
create_binary_message_with_headers(kind, payload.as_bytes().to_vec(), "".to_string())
|
||||
}
|
||||
|
||||
/// Create a new binary message with a user-specified `kind`, and `headers` as a string.
|
||||
#[wasm_bindgen]
|
||||
pub fn create_binary_message_with_headers(kind: u8, payload: Vec<u8>, headers: String) -> Vec<u8> {
|
||||
let headers = headers.as_bytes().to_vec();
|
||||
let size = (headers.len() as u64).to_be_bytes().to_vec();
|
||||
vec![vec![kind], size, headers, payload].concat()
|
||||
}
|
||||
|
||||
/// Parse the `kind` and byte array `payload` from a byte array
|
||||
#[wasm_bindgen]
|
||||
pub async fn parse_binary_message(message: Vec<u8>) -> Result<IBinaryMessage, JsError> {
|
||||
if message.len() < 2 {
|
||||
return Err(JsError::new(
|
||||
"Could not parse message, as less than 2 bytes long",
|
||||
));
|
||||
}
|
||||
|
||||
let (kind, _headers, payload) = parse_binary_payload(&message);
|
||||
|
||||
Ok(serde_wasm_bindgen::to_value(&BinaryMessage {
|
||||
kind,
|
||||
payload: payload.to_vec(),
|
||||
headers: "".to_string(),
|
||||
})
|
||||
.unwrap()
|
||||
.unchecked_into::<IBinaryMessage>())
|
||||
}
|
||||
|
||||
/// Parse the `kind` and byte array `payload` from a byte array with headers
|
||||
#[wasm_bindgen]
|
||||
pub async fn parse_binary_message_with_headers(
|
||||
message: Vec<u8>,
|
||||
) -> Result<IBinaryMessage, JsError> {
|
||||
if message.len() < 2 {
|
||||
return Err(JsError::new(
|
||||
"Could not parse message, as less than 2 bytes long",
|
||||
));
|
||||
}
|
||||
|
||||
let (kind, headers, payload) = parse_binary_payload(&message);
|
||||
|
||||
Ok(serde_wasm_bindgen::to_value(&BinaryMessage {
|
||||
kind,
|
||||
payload: payload.to_vec(),
|
||||
headers,
|
||||
})
|
||||
.unwrap()
|
||||
.unchecked_into::<IBinaryMessage>())
|
||||
}
|
||||
|
||||
/// Parse the `kind` and UTF-8 string `payload` from a byte array with headers
|
||||
#[wasm_bindgen]
|
||||
pub async fn parse_string_message_with_headers(
|
||||
message: Vec<u8>,
|
||||
) -> Result<IStringMessage, JsError> {
|
||||
if message.len() < 2 {
|
||||
return Err(JsError::new(
|
||||
"Could not parse message, as less than 2 bytes long",
|
||||
));
|
||||
}
|
||||
|
||||
let (kind, _headers, payload) = parse_binary_payload(&message);
|
||||
let payload = String::from_utf8_lossy(payload).into_owned();
|
||||
|
||||
Ok(
|
||||
serde_wasm_bindgen::to_value(&StringMessage { kind, payload })
|
||||
.unwrap()
|
||||
.unchecked_into::<IStringMessage>(),
|
||||
)
|
||||
}
|
||||
pub(crate) fn parse_binary_payload(message: &[u8]) -> (u8, String, &[u8]) {
|
||||
// 1st byte is the kind
|
||||
let kind = message[0];
|
||||
|
||||
// then the size as u64 big endian
|
||||
let mut size = [0u8; 8];
|
||||
size.clone_from_slice(&message[1..9]);
|
||||
let size = u64::from_be_bytes(size) as usize;
|
||||
|
||||
// then the headers
|
||||
let headers = String::from_utf8_lossy(&message[9..9 + size]).into_owned();
|
||||
|
||||
// finally the payload
|
||||
let payload = &message[9 + size..];
|
||||
|
||||
(kind, headers, payload)
|
||||
}
|
||||
|
||||
/// Parse the `kind` and UTF-8 string `payload` from a byte array
|
||||
#[wasm_bindgen]
|
||||
pub async fn parse_string_message(message: Vec<u8>) -> Result<IStringMessage, JsError> {
|
||||
if message.len() < 2 {
|
||||
return Err(JsError::new(
|
||||
"Could not parse message, as less than 2 bytes long",
|
||||
));
|
||||
}
|
||||
|
||||
let kind = message[0];
|
||||
let payload = String::from_utf8_lossy(&message[1..]).into_owned();
|
||||
|
||||
Ok(
|
||||
serde_wasm_bindgen::to_value(&StringMessage { kind, payload })
|
||||
.unwrap()
|
||||
.unchecked_into::<IStringMessage>(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{create_binary_message_with_headers, parse_binary_payload};
|
||||
use wasm_bindgen_test::*;
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn test_binary_with_headers() {
|
||||
let message_as_bytes = create_binary_message_with_headers(
|
||||
42u8,
|
||||
vec![0u8, 1u8, 2u8],
|
||||
"test headers".to_string(),
|
||||
);
|
||||
|
||||
// calculate header size
|
||||
let headers = "test headers".as_bytes().to_vec();
|
||||
let size = headers.len();
|
||||
|
||||
// the expected size
|
||||
let expected_size = 12;
|
||||
assert_eq!(size, expected_size);
|
||||
|
||||
assert_eq!(message_as_bytes[0], 42u8);
|
||||
assert_eq!(message_as_bytes[1..9], 12u64.to_be_bytes());
|
||||
assert_eq!(
|
||||
message_as_bytes[9 + expected_size..9 + expected_size + 3],
|
||||
vec![0u8, 1u8, 2u8]
|
||||
);
|
||||
|
||||
let res = parse_binary_payload(&message_as_bytes);
|
||||
|
||||
assert_eq!(res.0, 42u8);
|
||||
assert_eq!(res.1, "test headers".to_string());
|
||||
assert_eq!(res.2, vec![0u8, 1u8, 2u8]);
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn test_binary_with_empty_headers() {
|
||||
let message_as_bytes =
|
||||
create_binary_message_with_headers(42u8, vec![0u8, 1u8, 2u8], "".to_string());
|
||||
|
||||
let expected_size = 0;
|
||||
|
||||
assert_eq!(message_as_bytes[0], 42u8);
|
||||
assert_eq!(message_as_bytes[1..9], 0u64.to_be_bytes());
|
||||
assert_eq!(
|
||||
message_as_bytes[9 + expected_size..9 + expected_size + 3],
|
||||
vec![0u8, 1u8, 2u8]
|
||||
);
|
||||
|
||||
let res = parse_binary_payload(&message_as_bytes);
|
||||
|
||||
assert_eq!(res.0, 42u8);
|
||||
assert_eq!(res.1, "".to_string());
|
||||
assert_eq!(res.2, vec![0u8, 1u8, 2u8]);
|
||||
}
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen::JsCast;
|
||||
|
||||
#[wasm_bindgen(typescript_custom_section)]
|
||||
const TS_DEFS: &'static str = r#"
|
||||
export interface EncodedPayload {
|
||||
mimeType: string,
|
||||
payload: Uint8Array;
|
||||
headers: string,
|
||||
}
|
||||
"#;
|
||||
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(typescript_type = "EncodedPayload")]
|
||||
pub type IEncodedPayload;
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EncodedPayload {
|
||||
pub mime_type: String,
|
||||
pub payload: Vec<u8>,
|
||||
pub headers: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EncodedPayloadMetadata {
|
||||
pub mime_type: String,
|
||||
pub headers: Option<String>,
|
||||
}
|
||||
|
||||
/// Encode a payload
|
||||
#[wasm_bindgen]
|
||||
pub fn encode_payload(mime_type: String, payload: Vec<u8>) -> Result<Vec<u8>, JsValue> {
|
||||
encode_payload_with_headers(mime_type, payload, None)
|
||||
}
|
||||
|
||||
/// Create a new binary message with a user-specified `kind`, and `headers` as a string.
|
||||
#[wasm_bindgen]
|
||||
pub fn encode_payload_with_headers(
|
||||
mime_type: String,
|
||||
payload: Vec<u8>,
|
||||
headers: Option<String>,
|
||||
) -> Result<Vec<u8>, JsValue> {
|
||||
match serde_json::to_string(&EncodedPayloadMetadata { mime_type, headers }) {
|
||||
Ok(metadata) => {
|
||||
let metadata = metadata.as_bytes().to_vec();
|
||||
let size = (metadata.len() as u64).to_be_bytes().to_vec();
|
||||
Ok(vec![size, metadata, payload].concat())
|
||||
}
|
||||
Err(e) => Err(JsValue::from(JsError::new(
|
||||
format!("Could not encode message: {}", e).as_str(),
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse the `kind` and byte array `payload` from a byte array
|
||||
#[wasm_bindgen]
|
||||
pub fn decode_payload(message: Vec<u8>) -> Result<IEncodedPayload, JsValue> {
|
||||
if message.len() < 8 {
|
||||
return Err(JsValue::from(JsError::new(
|
||||
"Could not parse message, as less than 8 bytes long",
|
||||
)));
|
||||
}
|
||||
|
||||
match parse_payload(&message) {
|
||||
Ok((metadata, payload)) => Ok(serde_wasm_bindgen::to_value(&EncodedPayload {
|
||||
mime_type: metadata.mime_type,
|
||||
payload: payload.to_vec(),
|
||||
headers: metadata.headers,
|
||||
})
|
||||
.unwrap()
|
||||
.unchecked_into::<IEncodedPayload>()),
|
||||
Err(e) => Err(JsValue::from(JsError::new(
|
||||
format!("Could not parse message: {}", e).as_str(),
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse_payload(message: &[u8]) -> anyhow::Result<(EncodedPayloadMetadata, &[u8])> {
|
||||
// 1st 8 bytes are the size (as u64 big endian)
|
||||
let mut size = [0u8; 8];
|
||||
size.clone_from_slice(&message[0..8]);
|
||||
let size = u64::from_be_bytes(size) as usize;
|
||||
|
||||
// then the metadata
|
||||
let metadata = String::from_utf8_lossy(&message[8..8 + size]).into_owned();
|
||||
let metadata: EncodedPayloadMetadata = serde_json::from_str(metadata.as_str())?;
|
||||
|
||||
// finally the payload
|
||||
let payload = &message[8 + size..];
|
||||
|
||||
Ok((metadata, payload))
|
||||
}
|
||||
|
||||
/// Try parse a UTF-8 string from an array of bytes
|
||||
#[wasm_bindgen]
|
||||
pub fn parse_utf8_string(payload: Vec<u8>) -> String {
|
||||
String::from_utf8_lossy(&payload).into_owned()
|
||||
}
|
||||
|
||||
/// Converts a UTF-8 string into an array of bytes
|
||||
///
|
||||
/// This method is provided as a replacement for the mess of `atob`
|
||||
/// (https://developer.mozilla.org/en-US/docs/Web/API/atob) helpers provided by browsers and NodeJS.
|
||||
///
|
||||
/// Feel free to use `atob` if you know you won't have problems with polyfills or encoding issues.
|
||||
#[wasm_bindgen]
|
||||
pub fn utf8_string_to_byte_array(message: String) -> Vec<u8> {
|
||||
message.into_bytes()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use wasm_bindgen_test::*;
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
async fn test_encode_payload_with_headers() {
|
||||
let message_as_bytes = encode_payload_with_headers(
|
||||
"text/plain".to_string(),
|
||||
vec![0u8, 1u8, 2u8],
|
||||
Some("test headers".to_string()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// the expected message size
|
||||
let size = message_as_bytes.len();
|
||||
let expected_size = 61;
|
||||
assert_eq!(size, expected_size);
|
||||
|
||||
let expected_header_size = 50usize;
|
||||
assert_eq!(
|
||||
message_as_bytes[0..8],
|
||||
(expected_header_size as u64).to_be_bytes()
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
message_as_bytes[8 + expected_header_size..8 + expected_header_size + 3],
|
||||
vec![0u8, 1u8, 2u8]
|
||||
);
|
||||
|
||||
let res = parse_payload(&message_as_bytes).unwrap();
|
||||
|
||||
assert_eq!(res.0.mime_type, "text/plain");
|
||||
assert_eq!(res.0.headers.unwrap(), "test headers".to_string());
|
||||
assert_eq!(res.1, vec![0u8, 1u8, 2u8]);
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
async fn test_encode_payload_with_empty_headers() {
|
||||
let message_as_bytes =
|
||||
encode_payload_with_headers("text/plain".to_string(), vec![0u8, 1u8, 2u8], None)
|
||||
.unwrap();
|
||||
|
||||
// the expected message size
|
||||
let size = message_as_bytes.len();
|
||||
let expected_size = 51;
|
||||
assert_eq!(size, expected_size);
|
||||
|
||||
let expected_header_size = 40usize;
|
||||
assert_eq!(
|
||||
message_as_bytes[0..8],
|
||||
(expected_header_size as u64).to_be_bytes()
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
message_as_bytes[8 + expected_header_size..8 + expected_header_size + 3],
|
||||
vec![0u8, 1u8, 2u8]
|
||||
);
|
||||
let res = parse_payload(&message_as_bytes).unwrap();
|
||||
|
||||
assert_eq!(res.0.mime_type, "text/plain");
|
||||
assert_eq!(res.0.headers, None);
|
||||
assert_eq!(res.1, vec![0u8, 1u8, 2u8]);
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
async fn test_encode_payload_with_empty_headers_and_empty_mime_type() {
|
||||
let message_as_bytes =
|
||||
encode_payload_with_headers("".to_string(), vec![0u8, 1u8, 2u8], None).unwrap();
|
||||
|
||||
// the expected message size
|
||||
let size = message_as_bytes.len();
|
||||
let expected_size = 41;
|
||||
assert_eq!(size, expected_size);
|
||||
|
||||
let expected_header_size = 30usize;
|
||||
assert_eq!(
|
||||
message_as_bytes[0..8],
|
||||
(expected_header_size as u64).to_be_bytes()
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
message_as_bytes[8 + expected_header_size..8 + expected_header_size + 3],
|
||||
vec![0u8, 1u8, 2u8]
|
||||
);
|
||||
let res = parse_payload(&message_as_bytes).unwrap();
|
||||
|
||||
assert_eq!(res.0.mime_type, "");
|
||||
assert_eq!(res.0.headers, None);
|
||||
assert_eq!(res.1, vec![0u8, 1u8, 2u8]);
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
async fn test_encode_payload_with_all_empty() {
|
||||
let empty: Vec<u8> = vec![];
|
||||
let message_as_bytes =
|
||||
encode_payload_with_headers("".to_string(), empty.clone(), None).unwrap();
|
||||
|
||||
// the expected message size
|
||||
let size = message_as_bytes.len();
|
||||
let expected_size = 38;
|
||||
assert_eq!(size, expected_size);
|
||||
|
||||
let expected_header_size = 30usize;
|
||||
assert_eq!(
|
||||
message_as_bytes[0..8],
|
||||
(expected_header_size as u64).to_be_bytes()
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
message_as_bytes[8 + expected_header_size..8 + expected_header_size],
|
||||
empty
|
||||
);
|
||||
let res = parse_payload(&message_as_bytes).unwrap();
|
||||
|
||||
assert_eq!(res.0.mime_type, "");
|
||||
assert_eq!(res.0.headers, None);
|
||||
assert_eq!(res.1, empty);
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,12 @@
|
||||
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod binary_message_helper;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod client;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod encoded_payload_helper;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod gateway_selector;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod validation;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn set_panic_hook() {
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
use nymsphinx::addressing::clients::Recipient;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn validate_recipient(recipient: String) -> Result<(), JsError> {
|
||||
match Recipient::try_from_base58_string(recipient) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => Err(JsError::new(format!("{}", e).as_str())),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::validate_recipient;
|
||||
use wasm_bindgen_test::*;
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn test_recipient_validation_ok() {
|
||||
let res = validate_recipient("DyQmXnst5NGGjzUZxRC5Bjs5bd7CBF3xMpsSmbRiizr2.GH6YTBP2NXU3AVqd8WjiTMVyeMjunXMEsp7gVCMEJqpD@336yuXAeGEgedRfqTJZsG2YV7P13QH1bHv1SjCZYarc9".to_string());
|
||||
assert!(res.is_ok())
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn test_recipient_validation_fails() {
|
||||
assert!(validate_recipient(" DyQmXnst5NGGjzUZxRC5Bjs5bd7CBF3xMpsSmbRiizr2.GH6YTBP2NXU3AVqd8WjiTMVyeMjunXMEsp7gVCMEJqpD@336yuXAeGEgedRfqTJZsG2YV7P13QH1bHv1SjCZYarc9".to_string()).is_err());
|
||||
assert!(validate_recipient(
|
||||
"DyQmXnst5NGGjzUZxRC5BjbRiizr2.GH6YTBP2NXU3AVqd8WD@336yuXAeGEgedRfqTJZQH1bHv1SjCZYarc9"
|
||||
.to_string()
|
||||
)
|
||||
.is_err());
|
||||
assert!(validate_recipient("🙀🙀🙀🙀".to_string()).is_err());
|
||||
assert!(validate_recipient("".to_string()).is_err());
|
||||
assert!(validate_recipient(" ".to_string()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ thiserror = "1.0"
|
||||
url = "2.2"
|
||||
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
|
||||
async-trait = { version = "0.1.51" }
|
||||
tokio = { version = "1.24.1", features = ["macros"] }
|
||||
tokio = { version = "1.21.2", features = ["macros"] }
|
||||
|
||||
# internal
|
||||
coconut-interface = { path = "../../coconut-interface", optional = true }
|
||||
@@ -36,11 +36,11 @@ default-features = false
|
||||
|
||||
# non-wasm-only dependencies
|
||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio]
|
||||
version = "1.24.1"
|
||||
version = "1.21.2"
|
||||
features = ["macros", "rt", "net", "sync", "time"]
|
||||
|
||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio-stream]
|
||||
version = "0.1.11"
|
||||
version = "0.1.9"
|
||||
features = ["net", "sync", "time"]
|
||||
|
||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio-tungstenite]
|
||||
|
||||
@@ -9,9 +9,8 @@ edition = "2021"
|
||||
[dependencies]
|
||||
futures = "0.3"
|
||||
log = "0.4.8"
|
||||
tokio = { version = "1.24.1", features = ["time", "net", "rt"] }
|
||||
tokio-util = { version = "0.7.4", features = ["codec"] }
|
||||
tokio = { version = "1.21.2", features = ["time", "net", "rt"] }
|
||||
tokio-util = { version = "0.7.3", features = ["codec"] }
|
||||
|
||||
# internal
|
||||
nymsphinx = { path = "../../nymsphinx" }
|
||||
task = { path = "../../task" }
|
||||
nymsphinx = {path = "../../nymsphinx" }
|
||||
|
||||
@@ -16,7 +16,6 @@ type MixForwardingReceiver = mpsc::UnboundedReceiver<MixPacket>;
|
||||
pub struct PacketForwarder {
|
||||
mixnet_client: Client,
|
||||
packet_receiver: MixForwardingReceiver,
|
||||
shutdown: task::TaskClient,
|
||||
}
|
||||
|
||||
impl PacketForwarder {
|
||||
@@ -26,7 +25,6 @@ impl PacketForwarder {
|
||||
initial_connection_timeout: Duration,
|
||||
maximum_connection_buffer_size: usize,
|
||||
use_legacy_version: bool,
|
||||
shutdown: task::TaskClient,
|
||||
) -> (PacketForwarder, MixForwardingSender) {
|
||||
let client_config = Config::new(
|
||||
initial_reconnection_backoff,
|
||||
@@ -42,35 +40,26 @@ impl PacketForwarder {
|
||||
PacketForwarder {
|
||||
mixnet_client: Client::new(client_config),
|
||||
packet_receiver,
|
||||
shutdown,
|
||||
},
|
||||
packet_sender,
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn run(&mut self) {
|
||||
while !self.shutdown.is_shutdown() {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.shutdown.recv() => {
|
||||
log::trace!("PacketForwarder: Received shutdown");
|
||||
}
|
||||
Some(mix_packet) = self.packet_receiver.next() => {
|
||||
trace!("Going to forward packet to {:?}", mix_packet.next_hop());
|
||||
while let Some(mix_packet) = self.packet_receiver.next().await {
|
||||
trace!("Going to forward packet to {:?}", mix_packet.next_hop());
|
||||
|
||||
let next_hop = mix_packet.next_hop();
|
||||
let packet_mode = mix_packet.packet_mode();
|
||||
let sphinx_packet = mix_packet.into_sphinx_packet();
|
||||
// we don't care about responses, we just want to fire packets
|
||||
// as quickly as possible
|
||||
let next_hop = mix_packet.next_hop();
|
||||
let packet_mode = mix_packet.packet_mode();
|
||||
let sphinx_packet = mix_packet.into_sphinx_packet();
|
||||
// we don't care about responses, we just want to fire packets
|
||||
// as quickly as possible
|
||||
|
||||
if let Err(err) =
|
||||
self.mixnet_client
|
||||
.send_without_response(next_hop, sphinx_packet, packet_mode)
|
||||
{
|
||||
debug!("failed to forward the packet - {err}")
|
||||
}
|
||||
}
|
||||
if let Err(err) =
|
||||
self.mixnet_client
|
||||
.send_without_response(next_hop, sphinx_packet, packet_mode)
|
||||
{
|
||||
debug!("failed to forward the packet - {err}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ reqwest = { version = "0.11", features = ["json"] }
|
||||
thiserror = "1"
|
||||
log = "0.4"
|
||||
url = { version = "2.2", features = ["serde"] }
|
||||
tokio = { version = "1.24.1", features = ["sync", "time"] }
|
||||
tokio = { version = "1.21.2", features = ["sync", "time"] }
|
||||
futures = "0.3"
|
||||
|
||||
coconut-interface = { path = "../../coconut-interface" }
|
||||
|
||||
@@ -6,7 +6,7 @@ use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum ValidatorClientError {
|
||||
#[error("nym api request failed - {source}")]
|
||||
#[error("There was an issue with the validator api request - {source}")]
|
||||
NymAPIError {
|
||||
#[from]
|
||||
source: nym_api::error::NymAPIError,
|
||||
@@ -16,7 +16,7 @@ pub enum ValidatorClientError {
|
||||
MalformedUrlProvided(#[from] url::ParseError),
|
||||
|
||||
#[cfg(feature = "nyxd-client")]
|
||||
#[error("nyxd request failed - {0}")]
|
||||
#[error("There was an issue with the Nyxd client - {0}")]
|
||||
NyxdError(#[from] crate::nyxd::error::NyxdError),
|
||||
|
||||
#[error("No validator API url has been provided")]
|
||||
|
||||
@@ -9,8 +9,10 @@ pub mod nym_api;
|
||||
#[cfg(feature = "nyxd-client")]
|
||||
pub mod nyxd;
|
||||
|
||||
#[cfg(feature = "nyxd-client")]
|
||||
pub use crate::client::{CoconutApiClient, NymApiClient};
|
||||
pub use crate::error::ValidatorClientError;
|
||||
pub use nym_api_requests::*;
|
||||
|
||||
#[cfg(feature = "nyxd-client")]
|
||||
pub use client::{Client, CoconutApiClient, Config, NymApiClient};
|
||||
pub use client::{Client, Config};
|
||||
|
||||
@@ -46,25 +46,25 @@ pub enum NyxdError {
|
||||
#[error("{0} is not a valid tx hash")]
|
||||
InvalidTxHash(String),
|
||||
|
||||
#[error("Tendermint RPC request failed - {0}")]
|
||||
#[error("There was an issue with a tendermint RPC request - {0}")]
|
||||
TendermintError(#[from] TendermintRpcError),
|
||||
|
||||
#[error("Failed when attempting to serialize data ({0})")]
|
||||
#[error("There was an issue when attempting to serialize data ({0})")]
|
||||
SerializationError(String),
|
||||
|
||||
#[error("Failed when attempting to deserialize data ({0})")]
|
||||
#[error("There was an issue when attempting to deserialize data ({0})")]
|
||||
DeserializationError(String),
|
||||
|
||||
#[error("Failed when attempting to encode our protobuf data - {0}")]
|
||||
#[error("There was an issue when attempting to encode our protobuf data - {0}")]
|
||||
ProtobufEncodingError(#[from] prost::EncodeError),
|
||||
|
||||
#[error("Failed to decode our protobuf data - {0}")]
|
||||
#[error("There was an issue when attempting to decode our protobuf data - {0}")]
|
||||
ProtobufDecodingError(#[from] prost::DecodeError),
|
||||
|
||||
#[error("Account {0} does not exist on the chain")]
|
||||
NonExistentAccountError(AccountId),
|
||||
|
||||
#[error("Failed on json serialization/deserialization - {0}")]
|
||||
#[error("There was an issue with the serialization/deserialization - {0}")]
|
||||
SerdeJsonError(#[from] serde_json::Error),
|
||||
|
||||
#[error("Account {0} is not a valid account address")]
|
||||
|
||||
@@ -17,13 +17,11 @@ use cosmrs::rpc::HttpClientUrl;
|
||||
use cosmrs::tx::Msg;
|
||||
use execute::execute;
|
||||
use log::debug;
|
||||
use mixnet_contract_common::MixId;
|
||||
use network_defaults::{ChainDetails, NymNetworkDetails};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::convert::TryInto;
|
||||
use std::time::SystemTime;
|
||||
use vesting_contract_common::ExecuteMsg as VestingExecuteMsg;
|
||||
use vesting_contract_common::PledgeCap;
|
||||
|
||||
pub use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
|
||||
pub use crate::nyxd::cosmwasm_client::signing_client::SigningCosmWasmClient;
|
||||
@@ -45,8 +43,10 @@ pub use cosmrs::Coin as CosmosCoin;
|
||||
pub use cosmrs::{bip32, AccountId, Decimal, Denom};
|
||||
pub use cosmwasm_std::Coin as CosmWasmCoin;
|
||||
pub use fee::{gas_price::GasPrice, GasAdjustable, GasAdjustment};
|
||||
use mixnet_contract_common::MixId;
|
||||
pub use signing_client::Client as SigningNyxdClient;
|
||||
pub use traits::{VestingQueryClient, VestingSigningClient};
|
||||
use vesting_contract_common::PledgeCap;
|
||||
|
||||
pub mod coin;
|
||||
pub mod cosmwasm_client;
|
||||
|
||||
@@ -80,7 +80,7 @@ pub fn create_signing_client(
|
||||
|
||||
match NyxdClient::connect_with_mnemonic(client_config, nyxd_url, mnemonic, None) {
|
||||
Ok(client) => Ok(client),
|
||||
Err(e) => Err(ContextError::NyxdError(format!("{e}"))),
|
||||
Err(e) => Err(ContextError::NyxdError(format!("{:?}", e))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ pub fn create_query_client(
|
||||
|
||||
match NyxdClient::connect(client_config, nyxd_url) {
|
||||
Ok(client) => Ok(client),
|
||||
Err(e) => Err(ContextError::NyxdError(format!("{e}"))),
|
||||
Err(e) => Err(ContextError::NyxdError(format!("{:?}", e))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ pub fn create_signing_client_with_nym_api(
|
||||
|
||||
match validator_client::client::Client::new_signing(client_config, mnemonic) {
|
||||
Ok(client) => Ok(client),
|
||||
Err(e) => Err(ContextError::NyxdError(format!("{e}"))),
|
||||
Err(e) => Err(ContextError::NyxdError(format!("{:?}", e))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,6 +134,6 @@ pub fn create_query_client_with_nym_api(
|
||||
|
||||
match validator_client::client::Client::new_query(client_config) {
|
||||
Ok(client) => Ok(client),
|
||||
Err(e) => Err(ContextError::NyxdError(format!("{e}"))),
|
||||
Err(e) => Err(ContextError::NyxdError(format!("{:?}", e))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ pub fn pretty_coin(coin: &Coin) -> String {
|
||||
} else {
|
||||
&coin.denom
|
||||
};
|
||||
format!("{amount} {denom}")
|
||||
format!("{} {}", amount, denom)
|
||||
}
|
||||
|
||||
pub fn pretty_cosmwasm_coin(coin: &CosmWasmCoin) -> String {
|
||||
@@ -25,12 +25,12 @@ pub fn pretty_cosmwasm_coin(coin: &CosmWasmCoin) -> String {
|
||||
} else {
|
||||
&coin.denom
|
||||
};
|
||||
format!("{amount} {denom}")
|
||||
format!("{} {}", amount, denom)
|
||||
}
|
||||
|
||||
pub fn pretty_decimal_with_denom(value: Decimal, denom: &str) -> String {
|
||||
// TODO: we might have to truncate the value here (that's why I moved it to separate function)
|
||||
format!("{value} {denom}")
|
||||
format!("{} {}", value, denom)
|
||||
}
|
||||
|
||||
pub fn show_error<E>(e: E)
|
||||
|
||||
@@ -57,7 +57,7 @@ pub async fn query_balance(
|
||||
if denom.is_empty() || denom.eq_ignore_ascii_case(&coin.denom) {
|
||||
if args.raw {
|
||||
if !args.hide_denom {
|
||||
println!("{coin}");
|
||||
println!("{}", coin);
|
||||
} else {
|
||||
println!("{}", coin.amount);
|
||||
}
|
||||
|
||||
@@ -77,12 +77,12 @@ pub async fn get_pubkey_from_chain(address: AccountId, client: &QueryClient) {
|
||||
if let Some(pubkey) = base_account.pubkey {
|
||||
println!("{}", pubkey.to_string());
|
||||
} else {
|
||||
println!("No account associated with address {address}");
|
||||
println!("No account associated with address {}", address);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
println!("No account associated with address {address}");
|
||||
println!("No account associated with address {}", address);
|
||||
}
|
||||
Err(e) => show_error(e),
|
||||
}
|
||||
|
||||
@@ -43,5 +43,5 @@ pub async fn generate(args: Args) {
|
||||
let res =
|
||||
serde_json::to_string(&instantiate_msg).expect("failed to convert instantiate msg to json");
|
||||
|
||||
println!("{res}")
|
||||
println!("{}", res)
|
||||
}
|
||||
|
||||
@@ -96,5 +96,5 @@ pub async fn generate(args: Args) {
|
||||
let res =
|
||||
serde_json::to_string(&instantiate_msg).expect("failed to convert instantiate msg to json");
|
||||
|
||||
println!("{res}")
|
||||
println!("{}", res)
|
||||
}
|
||||
|
||||
@@ -105,5 +105,5 @@ pub async fn generate(args: Args) {
|
||||
let res =
|
||||
serde_json::to_string(&instantiate_msg).expect("failed to convert instantiate msg to json");
|
||||
|
||||
println!("{res}")
|
||||
println!("{}", res)
|
||||
}
|
||||
|
||||
@@ -58,5 +58,5 @@ pub async fn generate(args: Args) {
|
||||
let res =
|
||||
serde_json::to_string(&instantiate_msg).expect("failed to convert instantiate msg to json");
|
||||
|
||||
println!("{res}")
|
||||
println!("{}", res)
|
||||
}
|
||||
|
||||
@@ -39,5 +39,5 @@ pub async fn generate(args: Args) {
|
||||
let res =
|
||||
serde_json::to_string(&instantiate_msg).expect("failed to convert instantiate msg to json");
|
||||
|
||||
println!("{res}")
|
||||
println!("{}", res)
|
||||
}
|
||||
|
||||
@@ -13,5 +13,5 @@ pub fn decode_mixnode_key(args: Args) {
|
||||
let b64_decoded = base64::decode(args.key).expect("failed to decode base64 string");
|
||||
let b58_encoded = bs58::encode(&b64_decoded).into_string();
|
||||
|
||||
println!("{b58_encoded}")
|
||||
println!("{}", b58_encoded)
|
||||
}
|
||||
|
||||
@@ -148,25 +148,6 @@ pub trait OptionalSet {
|
||||
}
|
||||
}
|
||||
|
||||
fn with_validated_optional<F, T, V, E>(
|
||||
self,
|
||||
f: F,
|
||||
value: Option<T>,
|
||||
validate: V,
|
||||
) -> Result<Self, E>
|
||||
where
|
||||
F: Fn(Self, T) -> Self,
|
||||
V: Fn(&T) -> Result<(), E>,
|
||||
Self: Sized,
|
||||
{
|
||||
if let Some(val) = value {
|
||||
validate(&val)?;
|
||||
Ok(f(self, val))
|
||||
} else {
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
fn with_optional_env<F, T>(self, f: F, val: Option<T>, env_var: &str) -> Self
|
||||
where
|
||||
F: Fn(Self, T) -> Self,
|
||||
|
||||
@@ -31,7 +31,7 @@ impl Display for ContractSafeBytes {
|
||||
write!(f, "0x")?;
|
||||
}
|
||||
for byte in self.0.iter().take(MAX_DISPLAY_SIZE) {
|
||||
write!(f, "{byte:02X}")?;
|
||||
write!(f, "{:02X}", byte)?;
|
||||
}
|
||||
// just some sanity safeguards
|
||||
if self.0.len() > MAX_DISPLAY_SIZE {
|
||||
|
||||
@@ -73,7 +73,7 @@ impl Percent {
|
||||
impl Display for Percent {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
let adjusted = Decimal::from_ratio(100u32, 1u32) * self.0;
|
||||
write!(f, "{adjusted}%")
|
||||
write!(f, "{}%", adjusted)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ impl ToString for MixnetEventType {
|
||||
MixnetEventType::DelegationOnUnbonding => "delegation_on_unbonding_node",
|
||||
};
|
||||
|
||||
format!("{EVENT_VERSION_PREFIX}{event_name}")
|
||||
format!("{}{}", EVENT_VERSION_PREFIX, event_name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@ use cosmwasm_std::{Decimal, StdError, StdResult, Uint128};
|
||||
pub fn compare_decimals(a: Decimal, b: Decimal, epsilon: Option<Decimal>) {
|
||||
let epsilon = epsilon.unwrap_or_else(|| Decimal::from_ratio(1u128, 100_000_000u128));
|
||||
if a > b {
|
||||
assert!(a - b < epsilon, "{a} != {b}")
|
||||
assert!(a - b < epsilon, "{} != {}", a, b)
|
||||
} else {
|
||||
assert!(b - a < epsilon, "{a} != {b}")
|
||||
assert!(b - a < epsilon, "{} != {}", a, b)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -241,30 +241,30 @@ impl ExecuteMsg {
|
||||
pub fn default_memo(&self) -> String {
|
||||
match self {
|
||||
ExecuteMsg::AssignNodeLayer { mix_id, layer } => {
|
||||
format!("assigning mix {mix_id} for layer {layer:?}")
|
||||
format!("assigning mix {} for layer {:?}", mix_id, layer)
|
||||
}
|
||||
ExecuteMsg::CreateFamily { .. } => "crating node family with".to_string(),
|
||||
ExecuteMsg::JoinFamily { family_head, .. } => {
|
||||
format!("joining family {family_head}")
|
||||
format!("joining family {}", family_head)
|
||||
}
|
||||
ExecuteMsg::LeaveFamily { family_head, .. } => {
|
||||
format!("leaving family {family_head}")
|
||||
format!("leaving family {}", family_head)
|
||||
}
|
||||
ExecuteMsg::KickFamilyMember { member, .. } => {
|
||||
format!("kicking {member} from family")
|
||||
format!("kicking {} from family", member)
|
||||
}
|
||||
ExecuteMsg::CreateFamilyOnBehalf { .. } => "crating node family with".to_string(),
|
||||
ExecuteMsg::JoinFamilyOnBehalf { family_head, .. } => {
|
||||
format!("joining family {family_head}")
|
||||
format!("joining family {}", family_head)
|
||||
}
|
||||
ExecuteMsg::LeaveFamilyOnBehalf { family_head, .. } => {
|
||||
format!("leaving family {family_head}")
|
||||
format!("leaving family {}", family_head)
|
||||
}
|
||||
ExecuteMsg::KickFamilyMemberOnBehalf { member, .. } => {
|
||||
format!("kicking {member} from family")
|
||||
format!("kicking {} from family", member)
|
||||
}
|
||||
ExecuteMsg::UpdateRewardingValidatorAddress { address } => {
|
||||
format!("updating rewarding validator to {address}")
|
||||
format!("updating rewarding validator to {}", address)
|
||||
}
|
||||
ExecuteMsg::UpdateContractStateParams { .. } => {
|
||||
"updating mixnet state parameters".into()
|
||||
@@ -273,14 +273,21 @@ impl ExecuteMsg {
|
||||
active_set_size,
|
||||
force_immediately,
|
||||
} => format!(
|
||||
"updating active set size to {active_set_size}. forced: {force_immediately}"
|
||||
"updating active set size to {}. forced: {}",
|
||||
active_set_size, force_immediately
|
||||
),
|
||||
ExecuteMsg::UpdateRewardingParams {
|
||||
force_immediately, ..
|
||||
} => format!("updating mixnet rewarding parameters. forced: {force_immediately}"),
|
||||
} => format!(
|
||||
"updating mixnet rewarding parameters. forced: {}",
|
||||
force_immediately
|
||||
),
|
||||
ExecuteMsg::UpdateIntervalConfig {
|
||||
force_immediately, ..
|
||||
} => format!("updating mixnet interval configuration. forced: {force_immediately}"),
|
||||
} => format!(
|
||||
"updating mixnet interval configuration. forced: {}",
|
||||
force_immediately
|
||||
),
|
||||
ExecuteMsg::AdvanceCurrentEpoch { .. } => "advancing current epoch".into(),
|
||||
ExecuteMsg::ReconcileEpochEvents { .. } => "reconciling epoch events".into(),
|
||||
ExecuteMsg::BondMixnode { mix_node, .. } => {
|
||||
@@ -309,30 +316,34 @@ impl ExecuteMsg {
|
||||
}
|
||||
ExecuteMsg::UnbondGateway { .. } => "unbonding gateway".into(),
|
||||
ExecuteMsg::UnbondGatewayOnBehalf { .. } => "unbonding gateway on behalf".into(),
|
||||
ExecuteMsg::DelegateToMixnode { mix_id } => format!("delegating to mixnode {mix_id}"),
|
||||
ExecuteMsg::DelegateToMixnode { mix_id } => format!("delegating to mixnode {}", mix_id),
|
||||
ExecuteMsg::DelegateToMixnodeOnBehalf { mix_id, .. } => {
|
||||
format!("delegating to mixnode {mix_id} on behalf")
|
||||
format!("delegating to mixnode {} on behalf", mix_id)
|
||||
}
|
||||
ExecuteMsg::UndelegateFromMixnode { mix_id } => {
|
||||
format!("removing delegation from mixnode {mix_id}")
|
||||
format!("removing delegation from mixnode {}", mix_id)
|
||||
}
|
||||
ExecuteMsg::UndelegateFromMixnodeOnBehalf { mix_id, .. } => {
|
||||
format!("removing delegation from mixnode {mix_id} on behalf")
|
||||
format!("removing delegation from mixnode {} on behalf", mix_id)
|
||||
}
|
||||
ExecuteMsg::RewardMixnode {
|
||||
mix_id,
|
||||
performance,
|
||||
} => format!("rewarding mixnode {mix_id} for performance {performance}"),
|
||||
} => format!(
|
||||
"rewarding mixnode {} for performance {}",
|
||||
mix_id, performance
|
||||
),
|
||||
ExecuteMsg::WithdrawOperatorReward { .. } => "withdrawing operator reward".into(),
|
||||
ExecuteMsg::WithdrawOperatorRewardOnBehalf { .. } => {
|
||||
"withdrawing operator reward on behalf".into()
|
||||
}
|
||||
ExecuteMsg::WithdrawDelegatorReward { mix_id } => {
|
||||
format!("withdrawing delegator reward from mixnode {mix_id}")
|
||||
}
|
||||
ExecuteMsg::WithdrawDelegatorRewardOnBehalf { mix_id, .. } => {
|
||||
format!("withdrawing delegator reward from mixnode {mix_id} on behalf")
|
||||
format!("withdrawing delegator reward from mixnode {}", mix_id)
|
||||
}
|
||||
ExecuteMsg::WithdrawDelegatorRewardOnBehalf { mix_id, .. } => format!(
|
||||
"withdrawing delegator reward from mixnode {} on behalf",
|
||||
mix_id
|
||||
),
|
||||
#[cfg(feature = "contract-testing")]
|
||||
ExecuteMsg::TestingResolveAllPendingEvents { .. } => {
|
||||
"resolving all pending events".into()
|
||||
|
||||
@@ -64,7 +64,7 @@ impl FromStr for PledgeCap {
|
||||
Ok(p) => Ok(PledgeCap::Percent(p)),
|
||||
Err(_) => match cap.parse::<u128>() {
|
||||
Ok(i) => Ok(PledgeCap::Absolute(Uint128::from(i))),
|
||||
Err(_e) => Err(format!("Could not parse {cap} as Percent or Uint128")),
|
||||
Err(_e) => Err(format!("Could not parse {} as Percent or Uint128", cap)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,9 +11,9 @@ async-trait = { version = "0.1.51" }
|
||||
log = "0.4"
|
||||
sqlx = { version = "0.5", features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"]}
|
||||
thiserror = "1.0"
|
||||
tokio = { version = "1.24.1", features = [ "rt-multi-thread", "net", "signal", "fs" ] }
|
||||
tokio = { version = "1.21.2", features = [ "rt-multi-thread", "net", "signal", "fs" ] }
|
||||
|
||||
|
||||
[build-dependencies]
|
||||
sqlx = { version = "0.5", features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"] }
|
||||
tokio = { version = "1.24.1", features = ["rt-multi-thread", "macros"] }
|
||||
tokio = { version = "1.21.2", features = ["rt-multi-thread", "macros"] }
|
||||
|
||||
@@ -9,9 +9,9 @@ use std::env;
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let out_dir = env::var("OUT_DIR").unwrap();
|
||||
let database_path = format!("{out_dir}/coconut-credential-example.sqlite");
|
||||
let database_path = format!("{}/coconut-credential-example.sqlite", out_dir);
|
||||
|
||||
let mut conn = SqliteConnection::connect(&format!("sqlite://{database_path}?mode=rwc"))
|
||||
let mut conn = SqliteConnection::connect(&format!("sqlite://{}?mode=rwc", database_path))
|
||||
.await
|
||||
.expect("Failed to create SQLx database connection");
|
||||
|
||||
|
||||
@@ -224,7 +224,10 @@ impl DecryptionKey {
|
||||
let mut dh = Vec::with_capacity(dh_len);
|
||||
for j in 0..dh_len {
|
||||
let dh_i = deserialize_g2(&bytes[i..i + 96]).ok_or_else(|| {
|
||||
DkgError::new_deserialization_failure(format!("Node.dh_{j}"), "invalid curve point")
|
||||
DkgError::new_deserialization_failure(
|
||||
format!("Node.dh_{}", j),
|
||||
"invalid curve point",
|
||||
)
|
||||
})?;
|
||||
|
||||
dh.push(dh_i);
|
||||
|
||||
@@ -60,7 +60,7 @@ pub fn setup() -> Params {
|
||||
let f0 = hash_g2(b"f0", SETUP_DOMAIN);
|
||||
|
||||
let fh = (0..HASH_SECURITY_PARAM)
|
||||
.map(|i| hash_g2(format!("fh{i}"), SETUP_DOMAIN))
|
||||
.map(|i| hash_g2(format!("fh{}", i), SETUP_DOMAIN))
|
||||
.collect();
|
||||
|
||||
let h = hash_g2(b"h", SETUP_DOMAIN);
|
||||
|
||||
@@ -21,7 +21,8 @@ pub fn validate_bech32_prefix(bech32_prefix: &str, address: &str) -> Result<(),
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Bech32Error::WrongPrefix(format!(
|
||||
"your bech32 address prefix should be {bech32_prefix}, not {prefix}"
|
||||
"your bech32 address prefix should be {}, not {}",
|
||||
bech32_prefix, prefix
|
||||
)))
|
||||
}
|
||||
}
|
||||
@@ -69,7 +70,8 @@ mod tests {
|
||||
fn wrong_prefix_fails() {
|
||||
assert_eq!(
|
||||
Err(Bech32Error::WrongPrefix(format!(
|
||||
"your bech32 address prefix should be {TEST_BECH32_PREFIX}, not punk"
|
||||
"your bech32 address prefix should be {}, not punk",
|
||||
TEST_BECH32_PREFIX
|
||||
))),
|
||||
validate_bech32_prefix(
|
||||
TEST_BECH32_PREFIX,
|
||||
|
||||
@@ -7,4 +7,4 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
log = "0.4.0"
|
||||
pretty_env_logger = "0.4.0"
|
||||
pretty_env_logger = "0.4.0"
|
||||
@@ -23,20 +23,3 @@ pub fn setup_logging() {
|
||||
.filter_module("sled", log::LevelFilter::Warn)
|
||||
.init();
|
||||
}
|
||||
|
||||
pub fn banner(crate_name: &str, crate_version: &str) -> String {
|
||||
format!(
|
||||
r#"
|
||||
|
||||
_ __ _ _ _ __ ___
|
||||
| '_ \| | | | '_ \ _ \
|
||||
| | | | |_| | | | | | |
|
||||
|_| |_|\__, |_| |_| |_|
|
||||
|___/
|
||||
|
||||
({:} - version {:})
|
||||
|
||||
"#,
|
||||
crate_name, crate_version
|
||||
)
|
||||
}
|
||||
|
||||
@@ -13,8 +13,8 @@ humantime-serde = "1.0"
|
||||
log = "0.4"
|
||||
rand = "0.8"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
tokio = { version = "1.24.1", features = ["time", "macros", "rt", "net", "io-util"] }
|
||||
tokio-util = { version = "0.7.4", features = ["codec"] }
|
||||
tokio = { version = "1.21.2", features = ["time", "macros", "rt", "net", "io-util"] }
|
||||
tokio-util = { version = "0.7.3", features = ["codec"] }
|
||||
url = "2.2"
|
||||
thiserror = "1.0.37"
|
||||
|
||||
|
||||
@@ -53,19 +53,19 @@ impl Display for RttError {
|
||||
write!(f, "The received reply packet had invalid signature")
|
||||
}
|
||||
RttError::UnreachableNode(id, err) => {
|
||||
write!(f, "Could not establish connection to {id} - {err}")
|
||||
write!(f, "Could not establish connection to {} - {err}", id)
|
||||
}
|
||||
RttError::UnexpectedConnectionFailureWrite(id, err) => {
|
||||
write!(f, "Failed to write echo packet to {id} - {err}")
|
||||
write!(f, "Failed to write echo packet to {} - {err}", id)
|
||||
}
|
||||
RttError::UnexpectedConnectionFailureRead(id, err) => {
|
||||
write!(f, "Failed to read reply packet from {id} - {err}")
|
||||
write!(f, "Failed to read reply packet from {} - {err}", id)
|
||||
}
|
||||
RttError::ConnectionReadTimeout(id) => {
|
||||
write!(f, "Timed out while trying to read reply packet from {id}")
|
||||
write!(f, "Timed out while trying to read reply packet from {}", id)
|
||||
}
|
||||
RttError::ConnectionWriteTimeout(id) => {
|
||||
write!(f, "Timed out while trying to write echo packet to {id}")
|
||||
write!(f, "Timed out while trying to write echo packet to {}", id)
|
||||
}
|
||||
RttError::UnexpectedReplySequence => write!(
|
||||
f,
|
||||
|
||||
@@ -153,7 +153,7 @@ impl Default for ConfigBuilder {
|
||||
fn default() -> Self {
|
||||
ConfigBuilder(Config {
|
||||
minimum_compatible_node_version: parse_version(MINIMUM_NODE_VERSION).unwrap(),
|
||||
listening_address: format!("[::]:{DEFAULT_VERLOC_PORT}").parse().unwrap(),
|
||||
listening_address: format!("[::]:{}", DEFAULT_VERLOC_PORT).parse().unwrap(),
|
||||
packets_per_node: DEFAULT_PACKETS_PER_NODE,
|
||||
packet_timeout: DEFAULT_PACKET_TIMEOUT,
|
||||
connection_timeout: DEFAULT_CONNECTION_TIMEOUT,
|
||||
|
||||
@@ -11,7 +11,7 @@ pub const STAKE_DENOM: DenomDetails = DenomDetails::new("unyx", "nyx", 6);
|
||||
|
||||
pub const MIXNET_CONTRACT_ADDRESS: &str =
|
||||
"n17srjznxl9dvzdkpwpw24gg668wc73val88a6m5ajg6ankwvz9wtst0cznr";
|
||||
pub const VESTING_CONTRACT_ADDRESS: &str =
|
||||
pub(crate) const VESTING_CONTRACT_ADDRESS: &str =
|
||||
"n1nc5tatafv6eyq7llkr2gv50ff9e22mnf70qgjlv737ktmt4eswrq73f2nw";
|
||||
pub(crate) const BANDWIDTH_CLAIM_CONTRACT_ADDRESS: &str =
|
||||
"n19lc9u84cz0yz3fww5283nucc9yvr8gsjmgeul0";
|
||||
@@ -36,7 +36,7 @@ const DEFAULT_SUFFIX: &str = "_MAINNET_DEFAULT";
|
||||
|
||||
fn set_var_to_default(var: &str, value: &str) {
|
||||
std::env::set_var(var, value);
|
||||
std::env::set_var(format!("{var}{DEFAULT_SUFFIX}"), "1")
|
||||
std::env::set_var(format!("{}{}", var, DEFAULT_SUFFIX), "1")
|
||||
}
|
||||
|
||||
fn set_var_conditionally_to_default(var: &str, value: &str) {
|
||||
@@ -46,7 +46,7 @@ fn set_var_conditionally_to_default(var: &str, value: &str) {
|
||||
}
|
||||
|
||||
pub fn uses_default(var: &str) -> bool {
|
||||
std::env::var(format!("{var}{DEFAULT_SUFFIX}")).is_ok()
|
||||
std::env::var(format!("{}{}", var, DEFAULT_SUFFIX)).is_ok()
|
||||
}
|
||||
|
||||
pub fn read_var_if_not_default(var: &str) -> Option<String> {
|
||||
|
||||
@@ -7,9 +7,9 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
tokio = { version = "1.24.1", features = [] }
|
||||
tokio-stream = "0.1.11" # this one seems to be a thing until `Stream` trait is stabilised in stdlib
|
||||
tokio-util = { version = "0.7.4", features = ["time"] }
|
||||
tokio = { version = "1.21.2", features = [] }
|
||||
tokio-stream = "0.1.9" # this one seems to be a thing until `Stream` trait is stabilised in stdlib
|
||||
tokio-util = { version = "0.7.3", features = ["time"] }
|
||||
|
||||
[target."cfg(target_arch = \"wasm32\")".dependencies.wasm-timer]
|
||||
git = "https://github.com/mmsinclair/wasm-timer"
|
||||
|
||||
@@ -7,17 +7,18 @@ use std::borrow::Borrow;
|
||||
use std::convert::TryInto;
|
||||
|
||||
use bls12_381::{G1Projective, G2Projective, Scalar};
|
||||
use digest::generic_array::typenum::Unsigned;
|
||||
use digest::Digest;
|
||||
use digest::generic_array::typenum::Unsigned;
|
||||
use group::GroupEncoding;
|
||||
use itertools::izip;
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::Attribute;
|
||||
use crate::error::{CoconutError, Result};
|
||||
use crate::scheme::issuance::compute_commitment_hash;
|
||||
use crate::scheme::setup::Parameters;
|
||||
use crate::scheme::VerificationKey;
|
||||
use crate::utils::{hash_g1, try_deserialize_scalar, try_deserialize_scalar_vec};
|
||||
use crate::Attribute;
|
||||
|
||||
// as per the reference python implementation
|
||||
type ChallengeDigest = Sha256;
|
||||
@@ -38,10 +39,10 @@ pub struct ProofCmCs {
|
||||
// and as per the bls12-381 library all elements are using big-endian form
|
||||
/// Generates a Scalar [or Fp] challenge by hashing a number of elliptic curve points.
|
||||
fn compute_challenge<D, I, B>(iter: I) -> Scalar
|
||||
where
|
||||
D: Digest,
|
||||
I: Iterator<Item = B>,
|
||||
B: AsRef<[u8]>,
|
||||
where
|
||||
D: Digest,
|
||||
I: Iterator<Item=B>,
|
||||
B: AsRef<[u8]>,
|
||||
{
|
||||
let mut h = D::new();
|
||||
for point_representation in iter {
|
||||
@@ -69,8 +70,8 @@ fn produce_response(witness: &Scalar, challenge: &Scalar, secret: &Scalar) -> Sc
|
||||
|
||||
// note: it's caller's responsibility to ensure witnesses.len() = secrets.len()
|
||||
fn produce_responses<S>(witnesses: &[Scalar], challenge: &Scalar, secrets: &[S]) -> Vec<Scalar>
|
||||
where
|
||||
S: Borrow<Scalar>,
|
||||
where
|
||||
S: Borrow<Scalar>,
|
||||
{
|
||||
debug_assert_eq!(witnesses.len(), secrets.len());
|
||||
|
||||
@@ -91,6 +92,7 @@ impl ProofCmCs {
|
||||
commitments: &[G1Projective],
|
||||
pedersen_commitments_openings: &[Scalar],
|
||||
private_attributes: &[Attribute],
|
||||
public_attributes: &[Attribute],
|
||||
) -> Self {
|
||||
// note: this is only called from `prepare_blind_sign` that already checks
|
||||
// whether private attributes are non-empty and whether we don't have too many
|
||||
@@ -104,7 +106,7 @@ impl ProofCmCs {
|
||||
let witness_attributes = params.n_random_scalars(private_attributes.len());
|
||||
|
||||
// recompute h
|
||||
let h = hash_g1(commitment.to_bytes());
|
||||
let h = compute_commitment_hash(*commitment, public_attributes);
|
||||
let hs_bytes = params
|
||||
.gen_hs()
|
||||
.iter()
|
||||
@@ -119,10 +121,10 @@ impl ProofCmCs {
|
||||
// Ccm = (wr * g1) + (wm[0] * hs[0]) + ... + (wm[i] * hs[i])
|
||||
let commitment_attributes = g1 * witness_commitment_opening
|
||||
+ witness_attributes
|
||||
.iter()
|
||||
.zip(params.gen_hs().iter())
|
||||
.map(|(wm_i, hs_i)| hs_i * wm_i)
|
||||
.sum::<G1Projective>();
|
||||
.iter()
|
||||
.zip(params.gen_hs().iter())
|
||||
.map(|(wm_i, hs_i)| hs_i * wm_i)
|
||||
.sum::<G1Projective>();
|
||||
|
||||
// zkp commitments for the individual attributes
|
||||
let commitments_attributes = witness_pedersen_commitments_openings
|
||||
@@ -186,7 +188,7 @@ impl ProofCmCs {
|
||||
}
|
||||
|
||||
// recompute h
|
||||
let h = hash_g1(commitment.to_bytes());
|
||||
let h = compute_commitment_hash(*commitment, public_attributes);
|
||||
let g1 = params.gen1();
|
||||
|
||||
let hs_bytes = params
|
||||
@@ -199,26 +201,26 @@ impl ProofCmCs {
|
||||
// Cw = (cm * c) + (rr * g1) + (rm[0] * hs[0]) + ... + (rm[n] * hs[n])
|
||||
let commitment_attributes = (commitment
|
||||
- public_attributes
|
||||
.iter()
|
||||
.zip(params.gen_hs().iter().skip(self.response_attributes.len()))
|
||||
.map(|(pub_attr, hs)| hs * pub_attr)
|
||||
.sum::<G1Projective>())
|
||||
.iter()
|
||||
.zip(params.gen_hs().iter().skip(self.response_attributes.len()))
|
||||
.map(|(pub_attr, hs)| hs * pub_attr)
|
||||
.sum::<G1Projective>())
|
||||
* self.challenge
|
||||
+ g1 * self.response_opening
|
||||
+ self
|
||||
.response_attributes
|
||||
.iter()
|
||||
.zip(params.gen_hs().iter())
|
||||
.map(|(res_attr, hs)| hs * res_attr)
|
||||
.sum::<G1Projective>();
|
||||
.response_attributes
|
||||
.iter()
|
||||
.zip(params.gen_hs().iter())
|
||||
.map(|(res_attr, hs)| hs * res_attr)
|
||||
.sum::<G1Projective>();
|
||||
|
||||
let commitments_attributes = izip!(
|
||||
commitments.iter(),
|
||||
self.response_openings.iter(),
|
||||
self.response_attributes.iter()
|
||||
)
|
||||
.map(|(cm_j, r_o_j, r_m_j)| cm_j * self.challenge + g1 * r_o_j + h * r_m_j)
|
||||
.collect::<Vec<_>>();
|
||||
.map(|(cm_j, r_o_j, r_m_j)| cm_j * self.challenge + g1 * r_o_j + h * r_m_j)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let commitments_bytes = commitments
|
||||
.iter()
|
||||
@@ -365,10 +367,10 @@ impl ProofKappaZeta {
|
||||
let commitment_kappa = params.gen2() * witness_blinder
|
||||
+ verification_key.alpha
|
||||
+ witness_attributes
|
||||
.iter()
|
||||
.zip(verification_key.beta_g2.iter())
|
||||
.map(|(wm_i, beta_i)| beta_i * wm_i)
|
||||
.sum::<G2Projective>();
|
||||
.iter()
|
||||
.zip(verification_key.beta_g2.iter())
|
||||
.map(|(wm_i, beta_i)| beta_i * wm_i)
|
||||
.sum::<G2Projective>();
|
||||
|
||||
// zeta is the public value associated with the serial number
|
||||
let commitment_zeta = params.gen2() * witness_serial_number;
|
||||
@@ -422,10 +424,10 @@ impl ProofKappaZeta {
|
||||
+ params.gen2() * self.response_blinder
|
||||
+ verification_key.alpha * (Scalar::one() - self.challenge)
|
||||
+ response_attributes
|
||||
.iter()
|
||||
.zip(verification_key.beta_g2.iter())
|
||||
.map(|(priv_attr, beta_i)| beta_i * priv_attr)
|
||||
.sum::<G2Projective>();
|
||||
.iter()
|
||||
.zip(verification_key.beta_g2.iter())
|
||||
.map(|(priv_attr, beta_i)| beta_i * priv_attr)
|
||||
.sum::<G2Projective>();
|
||||
|
||||
// zeta is the public value associated with the serial number
|
||||
let commitment_zeta = zeta * self.challenge + params.gen2() * self.response_serial_number;
|
||||
@@ -529,9 +531,18 @@ mod tests {
|
||||
let cms: [G1Projective; 1] = [G1Projective::random(&mut rng)];
|
||||
let rs = params.n_random_scalars(1);
|
||||
let private_attributes = params.n_random_scalars(1);
|
||||
let public_attributes = params.n_random_scalars(1);
|
||||
|
||||
// 0 public 1 private
|
||||
let pi_s = ProofCmCs::construct(¶ms, &cm, &r, &cms, &rs, &private_attributes);
|
||||
let pi_s = ProofCmCs::construct(
|
||||
¶ms,
|
||||
&cm,
|
||||
&r,
|
||||
&cms,
|
||||
&rs,
|
||||
&private_attributes,
|
||||
&public_attributes,
|
||||
);
|
||||
|
||||
let bytes = pi_s.to_bytes();
|
||||
assert_eq!(ProofCmCs::from_bytes(&bytes).unwrap(), pi_s);
|
||||
@@ -547,7 +558,15 @@ mod tests {
|
||||
let private_attributes = params.n_random_scalars(2);
|
||||
|
||||
// 0 public 2 privates
|
||||
let pi_s = ProofCmCs::construct(¶ms, &cm, &r, &cms, &rs, &private_attributes);
|
||||
let pi_s = ProofCmCs::construct(
|
||||
¶ms,
|
||||
&cm,
|
||||
&r,
|
||||
&cms,
|
||||
&rs,
|
||||
&private_attributes,
|
||||
&public_attributes,
|
||||
);
|
||||
|
||||
let bytes = pi_s.to_bytes();
|
||||
assert_eq!(ProofCmCs::from_bytes(&bytes).unwrap(), pi_s);
|
||||
|
||||
@@ -201,8 +201,16 @@ pub fn compute_pedersen_commitments_for_private_attributes(
|
||||
(commitments_openings, pedersen_commitments)
|
||||
}
|
||||
|
||||
pub fn compute_commitment_hash(commitment: G1Projective) -> G1Projective {
|
||||
hash_g1(commitment.to_bytes())
|
||||
pub fn compute_commitment_hash(
|
||||
commitment: G1Projective,
|
||||
public_attributes: &[Attribute],
|
||||
) -> G1Projective {
|
||||
let mut msg_bytes = Vec::with_capacity(public_attributes.len() * 32);
|
||||
msg_bytes.extend_from_slice(&commitment.to_affine().to_compressed());
|
||||
for attr in public_attributes {
|
||||
msg_bytes.extend_from_slice(&attr.to_bytes());
|
||||
}
|
||||
hash_g1(msg_bytes)
|
||||
}
|
||||
|
||||
/// Builds cryptographic material required for blind sign.
|
||||
@@ -230,7 +238,7 @@ pub fn prepare_blind_sign(
|
||||
compute_attributes_commitment(params, private_attributes, public_attributes, hs);
|
||||
|
||||
// Compute the challenge as the commitment hash
|
||||
let commitment_hash = compute_commitment_hash(commitment);
|
||||
let commitment_hash = compute_commitment_hash(commitment, public_attributes);
|
||||
|
||||
let (pedersen_commitments_openings, pedersen_commitments) =
|
||||
compute_pedersen_commitments_for_private_attributes(
|
||||
@@ -246,6 +254,7 @@ pub fn prepare_blind_sign(
|
||||
&pedersen_commitments,
|
||||
&pedersen_commitments_openings,
|
||||
private_attributes,
|
||||
public_attributes,
|
||||
);
|
||||
|
||||
Ok((
|
||||
@@ -276,7 +285,7 @@ pub fn blind_sign(
|
||||
}
|
||||
|
||||
// Verify the commitment hash
|
||||
let h = hash_g1(blind_sign_request.commitment.to_bytes());
|
||||
let h = compute_commitment_hash(blind_sign_request.commitment, public_attributes);
|
||||
if !(h == blind_sign_request.commitment_hash) {
|
||||
return Err(CoconutError::Issuance(
|
||||
"Failed to verify the commitment hash".to_string(),
|
||||
|
||||
@@ -68,7 +68,8 @@ impl TryFrom<&[u8]> for SecretKey {
|
||||
|
||||
if ys_len as usize != actual_ys_len {
|
||||
return Err(CoconutError::Deserialization(format!(
|
||||
"Tried to deserialize secret key with inconsistent ys len (expected {ys_len}, got {actual_ys_len})"
|
||||
"Tried to deserialize secret key with inconsistent ys len (expected {}, got {})",
|
||||
ys_len, actual_ys_len
|
||||
)));
|
||||
}
|
||||
|
||||
@@ -184,7 +185,8 @@ impl TryFrom<&[u8]> for VerificationKey {
|
||||
if betas_len as usize != actual_betas_len {
|
||||
return Err(
|
||||
CoconutError::Deserialization(
|
||||
format!("Tried to deserialize verification key with inconsistent betas len (expected {betas_len}, got {actual_betas_len})"
|
||||
format!("Tried to deserialize verification key with inconsistent betas len (expected {}, got {})",
|
||||
betas_len, actual_betas_len
|
||||
)));
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ impl Parameters {
|
||||
}
|
||||
|
||||
let hs = (1..=num_attributes)
|
||||
.map(|i| hash_g1(format!("h{i}")).to_affine())
|
||||
.map(|i| hash_g1(format!("h{}", i)).to_affine())
|
||||
.collect();
|
||||
|
||||
Ok(Parameters {
|
||||
|
||||
@@ -34,5 +34,5 @@ mixnet-contract-common = { path = "../cosmwasm-smart-contracts/mixnet-contract"
|
||||
path = "framing"
|
||||
|
||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio]
|
||||
version = "1.24.1"
|
||||
version = "1.21.2"
|
||||
features = ["sync"]
|
||||
|
||||
@@ -8,7 +8,7 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
bytes = "1.0"
|
||||
tokio-util = { version = "0.7.4", features = ["codec"] }
|
||||
tokio-util = { version = "0.7.3", features = ["codec"] }
|
||||
thiserror = "1.0.37"
|
||||
|
||||
nymsphinx-types = { path = "../types" }
|
||||
|
||||
@@ -11,11 +11,10 @@ pub struct InvalidPacketMode {
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PacketMode {
|
||||
/// Represents 'normal' packet sent through the network that should be delayed by an appropriate
|
||||
/// value at each hop.
|
||||
#[default]
|
||||
Mix = 0,
|
||||
|
||||
/// Represents a VPN packet that should not be delayed and ideally cached pre-computed keys
|
||||
@@ -44,3 +43,9 @@ impl TryFrom<u8> for PacketMode {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PacketMode {
|
||||
fn default() -> Self {
|
||||
PacketMode::Mix
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,10 +34,9 @@ pub enum InvalidPacketSize {
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PacketSize {
|
||||
// for example instant messaging use case
|
||||
#[default]
|
||||
RegularPacket = 1,
|
||||
|
||||
// for sending SURB-ACKs
|
||||
@@ -137,3 +136,9 @@ impl PacketSize {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PacketSize {
|
||||
fn default() -> Self {
|
||||
PacketSize::RegularPacket
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,8 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
bytes = "1.0"
|
||||
tokio = { version = "1.24.1", features = [ "net", "io-util", "sync", "macros", "time", "rt-multi-thread" ] }
|
||||
tokio-util = { version = "0.7.4", features = [ "io" ] } # reason for getting this guy is to to able to port to tokio 1.X more quickly by being able to use
|
||||
tokio = { version = "1.21.2", features = [ "net", "io-util", "sync", "macros", "time", "rt-multi-thread" ] }
|
||||
tokio-util = { version = "0.7.3", features = [ "io" ] } # reason for getting this guy is to to able to port to tokio 1.X more quickly by being able to use
|
||||
# their `read_buf` [from the util crate] replacement rather than having to rethink/reimplement `AvailableReader` with the new AsyncRead trait definition.
|
||||
# In the long run, the dependency should probably get removed in favour of pure-tokio implementation, but for time being it's fine.
|
||||
futures = "0.3"
|
||||
|
||||
@@ -54,7 +54,7 @@ where
|
||||
Some(data) => match data {
|
||||
Ok(data) => (data, false),
|
||||
Err(err) => {
|
||||
error!(target: &*format!("({connection_id}) socks5 inbound"), "failed to read request from the socket - {err}");
|
||||
error!(target: &*format!("({}) socks5 inbound", connection_id), "failed to read request from the socket - {err}");
|
||||
(Default::default(), true)
|
||||
}
|
||||
},
|
||||
@@ -62,7 +62,7 @@ where
|
||||
};
|
||||
|
||||
debug!(
|
||||
target: &*format!("({connection_id}) socks5 inbound"),
|
||||
target: &*format!("({}) socks5 inbound", connection_id),
|
||||
"[{} bytes]\t{} → local → mixnet → remote → {}. Local closed: {}",
|
||||
read_data.len(),
|
||||
local_destination_address,
|
||||
@@ -103,7 +103,7 @@ where
|
||||
|
||||
// Technically we already informed it when we sent the message to mixnet above
|
||||
debug!(
|
||||
target: &*format!("({connection_id}) socks5 inbound"),
|
||||
target: &*format!("({}) socks5 inbound", connection_id),
|
||||
"The local socket is closed - won't receive any more data. Informing remote about that..."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ async fn deal_with_message(
|
||||
connection_id: ConnectionId,
|
||||
) -> bool {
|
||||
debug!(
|
||||
target: &*format!("({connection_id}) socks5 outbound"),
|
||||
target: &*format!("({}) socks5 outbound", connection_id),
|
||||
"[{} bytes]\t{} → remote → mixnet → local → {} Remote closed: {}",
|
||||
connection_message.payload.len(),
|
||||
remote_source_address,
|
||||
@@ -33,11 +33,11 @@ async fn deal_with_message(
|
||||
|
||||
if let Err(err) = writer.write_all(&connection_message.payload).await {
|
||||
// the other half is probably going to blow up too (if not, this task also needs to notify the other one!!)
|
||||
error!(target: &*format!("({connection_id}) socks5 outbound"), "failed to write response back to the socket - {err}");
|
||||
error!(target: &*format!("({}) socks5 outbound", connection_id), "failed to write response back to the socket - {err}");
|
||||
return true;
|
||||
}
|
||||
if connection_message.socket_closed {
|
||||
debug!(target: &*format!("({connection_id}) socks5 outbound"),
|
||||
debug!(target: &*format!("({}) socks5 outbound", connection_id),
|
||||
"Remote socket got closed - closing the local socket too");
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -16,4 +16,4 @@ serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sqlx = { version = "0.5", features = ["runtime-tokio-rustls", "chrono"]}
|
||||
thiserror = "1"
|
||||
tokio = { version = "1.24.1", features = [ "time" ] }
|
||||
tokio = { version = "1.21.2", features = [ "time" ] }
|
||||
|
||||
@@ -16,7 +16,8 @@ pub async fn build_and_send_statistics_request(
|
||||
) -> Result<(), StatsError> {
|
||||
reqwest::Client::new()
|
||||
.post(format!(
|
||||
"{url}{STATISTICS_SERVICE_VERSION}/{STATISTICS_SERVICE_API_STATISTICS}"
|
||||
"{}{}/{}",
|
||||
url, STATISTICS_SERVICE_VERSION, STATISTICS_SERVICE_API_STATISTICS
|
||||
))
|
||||
.json(&msg)
|
||||
.send()
|
||||
@@ -31,7 +32,11 @@ pub fn build_statistics_request_bytes(msg: StatsMessage) -> Result<Vec<u8>, Stat
|
||||
let req = reqwest::Request::new(
|
||||
reqwest::Method::POST,
|
||||
reqwest::Url::parse(&format!(
|
||||
"http://{DEFAULT_STATISTICS_SERVICE_ADDRESS}:{DEFAULT_STATISTICS_SERVICE_PORT}{STATISTICS_SERVICE_VERSION}/{STATISTICS_SERVICE_API_STATISTICS}"
|
||||
"http://{}:{}{}/{}",
|
||||
DEFAULT_STATISTICS_SERVICE_ADDRESS,
|
||||
DEFAULT_STATISTICS_SERVICE_PORT,
|
||||
STATISTICS_SERVICE_VERSION,
|
||||
STATISTICS_SERVICE_API_STATISTICS
|
||||
))
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
@@ -9,10 +9,10 @@ edition = "2021"
|
||||
futures = "0.3"
|
||||
log = "0.4"
|
||||
thiserror = "1.0.37"
|
||||
tokio = { version = "1.24.1", features = ["macros", "sync"] }
|
||||
tokio = { version = "1.21.2", features = ["macros", "sync"] }
|
||||
|
||||
[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio]
|
||||
version = "1.24.1"
|
||||
version = "1.21.2"
|
||||
features = ["signal", "time"]
|
||||
|
||||
[target."cfg(target_arch = \"wasm32\")".dependencies.wasm-bindgen-futures]
|
||||
@@ -22,4 +22,4 @@ version = "0.4"
|
||||
version = "0.2.83"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.24.1", features = ["rt-multi-thread", "net", "signal", "test-util", "macros"] }
|
||||
tokio = { version = "1.21.2", features = ["rt-multi-thread", "net", "signal", "test-util", "macros"] }
|
||||
|
||||
@@ -8,6 +8,6 @@ pub mod spawn;
|
||||
|
||||
pub use manager::{StatusReceiver, StatusSender, TaskClient, TaskManager};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use signal::wait_for_signal_and_error;
|
||||
pub use signal::{wait_for_signal, wait_for_signal_and_error};
|
||||
|
||||
pub use spawn::spawn_with_report_error;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
use std::future::Future;
|
||||
use std::{error::Error, time::Duration};
|
||||
|
||||
use futures::{future::pending, FutureExt, SinkExt, StreamExt};
|
||||
@@ -93,19 +92,6 @@ impl TaskManager {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub async fn catch_interrupt(mut self) -> Result<(), SentError> {
|
||||
let res = crate::wait_for_signal_and_error(&mut self).await;
|
||||
|
||||
log::info!("Sending shutdown");
|
||||
self.signal_shutdown().ok();
|
||||
|
||||
log::info!("Waiting for tasks to finish... (Press ctrl-c to force)");
|
||||
self.wait_for_shutdown().await;
|
||||
|
||||
res
|
||||
}
|
||||
|
||||
pub fn subscribe(&self) -> TaskClient {
|
||||
TaskClient::new(
|
||||
self.notify_rx
|
||||
@@ -240,17 +226,6 @@ impl TaskClient {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run_future<Fut, T>(&mut self, fut: Fut) -> Option<T>
|
||||
where
|
||||
Fut: Future<Output = T>,
|
||||
{
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.recv() => None,
|
||||
res = fut => Some(res)
|
||||
}
|
||||
}
|
||||
|
||||
// Create a dummy that will never report that we should shutdown.
|
||||
pub fn dummy() -> TaskClient {
|
||||
let (_notify_tx, notify_rx) = watch::channel(());
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use crate::{manager::SentError, TaskManager};
|
||||
|
||||
#[cfg(unix)]
|
||||
#[deprecated]
|
||||
pub async fn wait_for_signal() {
|
||||
use tokio::signal::unix::{signal, SignalKind};
|
||||
let mut sigterm = signal(SignalKind::terminate()).expect("Failed to setup SIGTERM channel");
|
||||
|
||||
@@ -194,6 +194,10 @@ impl fmt::Display for MixnodeNodeDetailsResponse {
|
||||
"Mix Port: {}, Verloc port: {}, Http Port: {}\n",
|
||||
self.mix_port, self.verloc_port, self.http_api_port
|
||||
)?;
|
||||
writeln!(f, "You are bonding to wallet address: {wallet_address}\n\n")
|
||||
writeln!(
|
||||
f,
|
||||
"You are bonding to wallet address: {}\n\n",
|
||||
wallet_address
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -618,7 +618,7 @@ pub fn query(deps: Deps<'_>, env: Env, msg: QueryMsg) -> Result<QueryResponse, C
|
||||
QueryMsg::GetAccountsVestingCoinsPaged {
|
||||
start_next_after,
|
||||
limit,
|
||||
} => to_binary(&try_get_all_accounts_vesting_coins(
|
||||
} => to_binary(&try_get_all_accounts_locked_coins(
|
||||
deps,
|
||||
env,
|
||||
start_next_after,
|
||||
@@ -775,7 +775,7 @@ pub fn try_get_all_accounts(
|
||||
})
|
||||
}
|
||||
|
||||
pub fn try_get_all_accounts_vesting_coins(
|
||||
pub fn try_get_all_accounts_locked_coins(
|
||||
deps: Deps<'_>,
|
||||
env: Env,
|
||||
start_after: Option<String>,
|
||||
|
||||
+3204
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user