Files
nym/wasm/client/src/helpers.rs
T
mfahampshire cf3fd00350 Max/crates io prep v2 (#6270)
* - standardise versions for all nym-sdk workspace dependencies
- prepend sqlx-pool-guard with 'nym-'

* Test remove nym-api from deps

* Add oneliner to client_pool doc comments

* Add note to commented out docs.rs link in sdk

* remove nym-api from script

* add publishing file

* bring non-binary / contract / tools into workspace version

* added more info to publishing.md

* make deps workspace version

* remove uploaded sphinx-types crate from script

* remove erroueously included ignore-defaults

* add zeroise to feature

* chore: Release

* add topology to batch

* more cargo versioning

* more cargo versioning - wasm utils

* more cargo versioning - wasm utils

* Add publish=false to manifest for cargo workspaces / crates.io
publishing exclusion

* remove script now switched to manifest based exclusion

* rename import based on rename of contracts-common dep

* Making workspace versions for publication + removing unnecessary crates
from publication

* Remove OOD info from publishing sdk guide

* rename contract imports + remove package

* temp commit: continuing with removal of path from cargo manifest and
replacing with workspace version import for publication

* continuing with cargo.toml updates

* dryrun only erroring on known version problem crates

* remove old published-crates file

* Minor comment change

* remove default features warning

* Additional info on workspace dep comment re publish list

* Add missing description to cargo.toml

* Fix missing feature flags

* Add missing descriptions

* Fix remaining path import

* Add workspace repo / homepage / documentation links to cargo.toml files

* remove workspace version from excluded crate

* Remove todo descriptions

* Minor comment change

* add homepage etc

* move from bls git import to nym_bls_fork crate

* Modify rest of imports from path to workspace import, excluding binaries

* add directory/homepage info

* fix cargo fmt

* add notes to gitignore

* better solution to contracts/ experiment

* wasm -> nym_wasm crate renaming

* fix fatfinger

* add metadata to ecash cargo.toml

* stub publishing guide

* fix misrevolved netlink- version

* Fixes and block publication of rebase re: LP

* first pass @ workflows
2026-01-19 13:19:45 +00:00

165 lines
5.6 KiB
Rust

// Copyright 2022-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use js_sys::Promise;
use nym_wasm_client_core::client::base_client::{ClientInput, ClientState};
use nym_wasm_client_core::client::inbound_messages::InputMessage;
use nym_wasm_client_core::error::WasmCoreError;
use nym_wasm_client_core::topology::{Role, WasmFriendlyNymTopology};
use nym_wasm_client_core::NymTopology;
use nym_wasm_utils::error::simple_js_error;
use nym_wasm_utils::{check_promise_result, console_log};
use std::sync::Arc;
use wasm_bindgen::JsValue;
use wasm_bindgen_futures::future_to_promise;
#[cfg(feature = "node-tester")]
use nym_node_tester_wasm::types::{NodeTestMessage, WasmTestMessageExt};
#[cfg(feature = "node-tester")]
use wasm_bindgen::prelude::wasm_bindgen;
#[cfg(feature = "node-tester")]
pub(crate) const DEFAULT_TEST_PACKETS: u32 = 20;
#[cfg(feature = "node-tester")]
#[wasm_bindgen]
pub struct NymClientTestRequest {
// serialized NodeTestMessage
pub(crate) test_msgs: Vec<Vec<u8>>,
// specially constructed network topology that only contains the target
// node on the tested layer
pub(crate) testable_topology: NymTopology,
}
#[cfg(feature = "node-tester")]
#[wasm_bindgen]
impl NymClientTestRequest {
pub fn injectable_topology(&self) -> WasmFriendlyNymTopology {
self.testable_topology.clone().into()
}
}
// defining helper trait as we could directly call the method on the wrapper
pub(crate) trait InputSender {
fn send_message(&self, message: InputMessage) -> Promise;
fn send_messages(&self, messages: Vec<InputMessage>) -> Promise;
}
impl InputSender for Arc<ClientInput> {
fn send_message(&self, message: InputMessage) -> Promise {
let this = Arc::clone(self);
future_to_promise(async move {
match this.input_sender.send(message).await {
Ok(_) => Ok(JsValue::null()),
Err(_) => Err(simple_js_error(
"InputMessageReceiver has stopped receiving!",
)),
}
})
}
fn send_messages(&self, messages: Vec<InputMessage>) -> Promise {
let this = Arc::clone(self);
future_to_promise(async move {
for message in messages {
if this.input_sender.send(message).await.is_err() {
return Err(simple_js_error(
"InputMessageReceiver has stopped receiving!",
));
}
}
Ok(JsValue::null())
})
}
}
pub(crate) trait WasmTopologyExt {
/// Changes the current network topology to the provided value.
fn change_hardcoded_topology(&self, topology: WasmFriendlyNymTopology) -> Promise;
/// Returns the current network topology.
fn current_topology(&self) -> Promise;
}
#[cfg(feature = "node-tester")]
pub(crate) trait WasmTopologyTestExt {
/// Creates a `NymClientTestRequest` with a variant of `this` topology where the target node is the only one on its layer.
fn mix_test_request(
&self,
test_id: u32,
mixnode_identity: String,
num_test_packets: Option<u32>,
) -> Promise;
}
impl WasmTopologyExt for Arc<ClientState> {
fn change_hardcoded_topology(&self, topology: WasmFriendlyNymTopology) -> Promise {
let nym_topology: NymTopology = check_promise_result!(topology.try_into());
let this = Arc::clone(self);
future_to_promise(async move {
console_log!("changing topology to {nym_topology:?}");
this.topology_accessor
.manually_change_topology(nym_topology)
.await;
Ok(JsValue::null())
})
}
fn current_topology(&self) -> Promise {
let this = Arc::clone(self);
future_to_promise(async move {
match this.topology_accessor.current_route_provider().await {
Some(route_provider) => Ok(serde_wasm_bindgen::to_value(
&WasmFriendlyNymTopology::from(route_provider.topology.clone()),
)
.expect("WasmFriendlyNymTopology failed serialization")),
None => Err(WasmCoreError::UnavailableNetworkTopology.into()),
}
})
}
}
#[cfg(feature = "node-tester")]
impl WasmTopologyTestExt for Arc<ClientState> {
fn mix_test_request(
&self,
test_id: u32,
mixnode_identity: String,
num_test_packets: Option<u32>,
) -> Promise {
let num_test_packets = num_test_packets.unwrap_or(DEFAULT_TEST_PACKETS);
let this = Arc::clone(self);
future_to_promise(async move {
let Some(current_topology) = this.topology_accessor.current_route_provider().await
else {
return Err(WasmCoreError::UnavailableNetworkTopology.into());
};
let Ok(node_identity) = mixnode_identity.parse() else {
return Err(WasmCoreError::NonExistentMixnode { mixnode_identity }.into());
};
let Some(mix) = current_topology.node_by_identity(node_identity) else {
return Err(WasmCoreError::NonExistentMixnode { mixnode_identity }.into());
};
let mut updated = current_topology.topology.clone();
updated.set_testable_node(Role::Layer2, mix.clone());
let ext = WasmTestMessageExt::new(test_id);
let test_msgs = NodeTestMessage::mix_plaintexts(mix, num_test_packets, ext)
.map_err(crate::error::WasmClientError::from)?;
Ok(JsValue::from(NymClientTestRequest {
test_msgs,
testable_topology: updated,
}))
})
}
}