Skip to content

Commit

Permalink
Feature/multi surbs basic wasm interface (#1846)
Browse files Browse the repository at this point in the history
* Added builder to wasm client

* missing wasm_bindgen macros

* Added constructor macro on GatewayEndpointConfig

* Attempting to use updated wasm client api

* Removing dead code

* Exposed other messages types in wasm client

* cleanup in js-example

* Changed 'self_address' to be a method call

* Removed needless borrow when cloning an Arc

* Improving arguments in 'on_message' callback

* fixed wasm-client dependency/features
  • Loading branch information
jstuczyn committed Dec 8, 2022
1 parent 83af0d4 commit 825791f
Show file tree
Hide file tree
Showing 17 changed files with 344 additions and 257 deletions.
58 changes: 30 additions & 28 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 18 additions & 3 deletions clients/client-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ serde = { version = "1.0", features = ["derive"] }
tap = "1.0.1"
thiserror = "1.0.34"
url = { version ="2.2", features = ["serde"] }
sqlx = { version = "0.6.2", features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"], optional = true }
tokio = { version = "1.21.2", features = ["time", "macros"]}
time = "0.3"
tokio = { version = "1.21.2", features = ["macros"]}
time = "0.3.17"

# internal
config = { path = "../../common/config" }
Expand All @@ -40,6 +39,15 @@ task = { path = "../../common/task" }
version = "0.1.9"
features = ["time"]

[target."cfg(not(target_arch = \"wasm32\"))".dependencies.tokio]
version = "1.21.2"
features = ["time"]

[target."cfg(not(target_arch = \"wasm32\"))".dependencies.sqlx]
version = "0.6.2"
features = ["runtime-tokio-rustls", "sqlite", "macros", "migrate"]
optional = true

[target."cfg(target_arch = \"wasm32\")".dependencies.wasm-bindgen-futures]
version = "0.4"

Expand All @@ -54,6 +62,13 @@ rev = "b9d1a54ad514c2f230a026afe0dde341e98cd7b6"
version = "0.2.4"
features = ["futures"]

[target."cfg(target_arch = \"wasm32\")".dependencies.wasm-utils]
path = "../../common/wasm-utils"

[target."cfg(target_arch = \"wasm32\")".dependencies.time]
version = "0.3.17"
features = ["wasm-bindgen"]

[dev-dependencies]
tempfile = "3.1.0"

Expand Down
2 changes: 1 addition & 1 deletion clients/client-core/src/client/inbound_messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub enum InputMessage {
lane: TransmissionLane,
},

/// Create a message used for a duplex anonymous communication where the recipient
/// Creates a message used for a duplex anonymous communication where the recipient
/// will never learn of our true identity. This is achieved by carefully sending `reply_surbs`.
///
/// Note that if reply_surbs is set to zero then
Expand Down
2 changes: 1 addition & 1 deletion clients/client-core/src/client/replies/reply_controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,7 @@ where
to_remove.push(*pending_reply_target);
continue
};

let diff = now - last_received_time;

if diff > self.config.max_surb_waiting_period {
Expand All @@ -548,7 +549,6 @@ where
.surbs_storage_ref()
.reset_pending_reception(&pending_reply_target)
}

for to_remove in to_remove {
self.pending_replies.remove(&to_remove);
}
Expand Down
16 changes: 16 additions & 0 deletions clients/client-core/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,22 @@ pub struct GatewayEndpointConfig {
pub gateway_listener: String,
}

#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
impl GatewayEndpointConfig {
#[cfg_attr(target_arch = "wasm32", wasm_bindgen(constructor))]
pub fn new(
gateway_id: String,
gateway_owner: String,
gateway_listener: String,
) -> GatewayEndpointConfig {
GatewayEndpointConfig {
gateway_id,
gateway_owner,
gateway_listener,
}
}
}

impl From<topology::gateway::Node> for GatewayEndpointConfig {
fn from(node: topology::gateway::Node) -> GatewayEndpointConfig {
let gateway_listener = node.clients_address();
Expand Down
12 changes: 7 additions & 5 deletions clients/webassembly/js-example/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ async function main() {
*
* Message and recipient are taken from the values in the user interface.
*
* @param {Client} nymClient the nym client to use for message sending
*/
async function sendMessageTo() {
const message = document.getElementById('message').value;
Expand Down Expand Up @@ -96,10 +95,13 @@ function displaySend(message) {
/**
* Display received text messages in the browser. Colour them green.
*
* @param {string} message
* @param {Uint8Array} raw
*/
function displayReceived(message) {
const content = message;
function displayReceived(raw, sender_tag) {
const content = new TextDecoder().decode(raw);
if (sender_tag !== undefined) {
console.log("this message also contained some surbs from", sender_tag)
}

let timestamp = new Date().toISOString().substr(11, 12);
let receivedDiv = document.createElement('div');
Expand All @@ -116,7 +118,7 @@ function displayReceived(message) {
/**
* Display the nymClient's sender address in the user interface
*
* @param {Client} nymClient
* @param {String} address
*/
function displaySenderAddress(address) {
document.getElementById('sender').value = address;
Expand Down
60 changes: 18 additions & 42 deletions clients/webassembly/js-example/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,38 +17,7 @@ importScripts('nym_client_wasm.js');
console.log('Initializing worker');

// wasm_bindgen creates a global variable (with the exports attached) that is in scope after `importScripts`
const { default_debug, get_gateway, NymClient, set_panic_hook, Config } = wasm_bindgen;

class ClientWrapper {
constructor(config, onMessageHandler) {
this.rustClient = new NymClient(config);
this.rustClient.set_on_message(onMessageHandler);
this.rustClient.set_on_gateway_connect(this.onConnect);
}

selfAddress = () => {
return this.rustClient.self_address();
};

onConnect = () => {
console.log('Established (and authenticated) gateway connection!');
};

start = async () => {
// this is current limitation of wasm in rust - for async methods you can't take self by reference...
// I'm trying to figure out if I can somehow hack my way around it, but for time being you have to re-assign
// the object (it's the same one)
this.rustClient = await this.rustClient.start();
};

sendMessage = async (recipient, message) => {
this.rustClient = await this.rustClient.send_message(recipient, message);
};

sendBinaryMessage = async (recipient, message) => {
this.rustClient = await this.rustClient.send_binary_message(recipient, message);
};
}
const { default_debug, NymClientBuilder, set_panic_hook, Config, GatewayEndpointConfig } = wasm_bindgen;

let client = null;

Expand All @@ -62,11 +31,12 @@ async function main() {
set_panic_hook();

// validator server we will use to get topology from
const validator = 'https://validator.nymtech.net/api'; //"http://localhost:8081";
const preferredGateway = 'E3mvZTHQCdBvhfr178Swx9g4QG3kkRUun7YnToLMcMbM';

const gatewayEndpoint = await get_gateway(validator, preferredGateway);
gatewayEndpoint.gateway_listener = "wss://gateway1.nymtech.net:443"; // this is needed if we want it to work on the web. However this gateway is a v1 gateway, we will need to change for v2 once we get there
const validator = 'https://qwerty-validator-api.qa.nymte.ch/api';

const gatewayId = 'EVupP2tRUeZo5Y6RpBHAbm8kSntpgNyZNL6yCr7BDEoG';
const gatewayOwner = 'n1rmlew3euapuq7rs4s4j9apv00whrsazr764kl7';
const gatewayListener = 'ws://176.58.120.72:9000';
const gatewayEndpoint = new GatewayEndpointConfig(gatewayId, gatewayOwner, gatewayListener)

// only really useful if you want to adjust some settings like traffic rate
// (if not needed you can just pass a null)
Expand Down Expand Up @@ -94,12 +64,17 @@ async function main() {
};

console.log('Instantiating WASM client...');
client = new ClientWrapper(config, onMessageHandler);

let clientBuilder = new NymClientBuilder(config, onMessageHandler)
console.log('Web worker creating WASM client...');
await client.start();
let local_client = await clientBuilder.start_client();
console.log('WASM client running!');

const selfAddress = client.rustClient.self_address();

const selfAddress = local_client.self_address();

// set the global (I guess we don't have to anymore?)
client = local_client;

console.log(`Client address is ${selfAddress}`);
self.postMessage({
kind: 'Ready',
Expand All @@ -114,7 +89,8 @@ async function main() {
switch (event.data.kind) {
case 'SendMessage': {
const { message, recipient } = event.data.args;
await client.sendMessage(message, recipient);
let uint8Array = new TextEncoder().encode(message);
await client.send_regular_message(uint8Array, recipient);
}
}
}
Expand Down
Loading

0 comments on commit 825791f

Please sign in to comment.