rings-node 0.7.0

Rings is a structured peer-to-peer network implementation using WebRTC, Chord algorithm, and full WebAssembly (WASM) support.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
#![warn(missing_docs)]
//! Browser Provider implementation
#![allow(non_snake_case, non_upper_case_globals, clippy::ptr_offset_with_cast)]
use std::convert::TryFrom;
use std::future::Future;
use std::pin::Pin;
use std::str::FromStr;
use std::sync::Arc;

use js_sys;
use js_sys::Uint8Array;
use rings_core::dht::Did;
use rings_core::ecc::PublicKey;
use rings_core::prelude::vnode;
use rings_core::prelude::vnode::VirtualNode;
use rings_core::storage::idb::IdbStorage;
use rings_core::utils::js_utils;
use rings_core::utils::js_value;
use rings_derive::wasm_export;
use rings_rpc::method::Method;
use rings_rpc::protos::rings_node::*;
use wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures;
use wasm_bindgen_futures::future_to_promise;
use wasm_bindgen_futures::JsFuture;

use crate::backend::browser::BackendBehaviour;
use crate::backend::types::BackendMessage;
use crate::backend::types::HttpRequest;
use crate::backend::types::ServiceMessage;
use crate::backend::Backend;
use crate::processor::ProcessorConfig;
use crate::provider::AsyncSigner;
use crate::provider::Provider;
use crate::provider::Signer;

/// AddressType enum contains `DEFAULT` and `ED25519`.
#[wasm_export]
pub enum AddressType {
    /// Default address type, hex string of sha1(pubkey)
    DEFAULT,
    /// Ed25519 style address type, hex string of pubkey
    Ed25519,
}

/// A wrapper of Arc Ref of Provider
#[derive(Clone)]
#[wasm_export]
pub struct ProviderRef {
    inner: Arc<Provider>,
}

impl ProviderRef {
    /// get wrapped arc, this is useful for wasm case
    pub fn inner(&self) -> Arc<Provider> {
        self.inner.clone()
    }
}

#[wasm_export]
impl Provider {
    /// make provider as an As arc ref
    pub fn as_ref(&self) -> ProviderRef {
        ProviderRef {
            inner: Arc::new(self.clone()),
        }
    }
}

#[wasm_export]
impl Provider {
    /// Create new instance of Provider, return Promise
    /// Ice_servers should obey forrmat: "[turn|strun]://<Address>:<Port>;..."
    /// Account is hex string
    /// Account should format as same as account_type declared
    /// Account_type is lowercase string, possible input are: `eip191`, `ed25519`, `bip137`, for more information,
    /// please check [rings_core::ecc]
    /// Signer should be `async function (proof: string): Promise<Unit8Array>`
    /// Signer should function as same as account_type declared, Eg: eip191 or secp256k1 or ed25519.
    #[wasm_bindgen(constructor)]
    pub fn new_instance(
        network_id: u32,
        ice_servers: String,
        stabilize_interval: u64,
        account: String,
        account_type: String,
        signer: js_sys::Function,
        backend_behaviour: Option<BackendBehaviour>,
    ) -> js_sys::Promise {
        fn wrapped_signer(signer: js_sys::Function) -> AsyncSigner {
            Box::new(
                move |data: String| -> Pin<Box<dyn Future<Output = Vec<u8>>>> {
                    let signer = signer.clone();
                    Box::pin(async move {
                        let signer = signer.clone();
                        let sig: js_sys::Uint8Array = Uint8Array::from(
                            JsFuture::from(js_sys::Promise::from(
                                signer
                                    .call1(&JsValue::NULL, &JsValue::from_str(&data))
                                    .expect("Failed on call external Js Function"),
                            ))
                            .await
                            .expect("Failed await call external Js Promise"),
                        );
                        sig.to_vec()
                    })
                },
            )
        }

        future_to_promise(async move {
            let signer = wrapped_signer(signer);

            let vnode_storage = Box::new(
                IdbStorage::new_with_cap_and_name(50000, "rings-node")
                    .await
                    .expect("Failed on create vnode storage"),
            );

            let measure_storage = Box::new(
                IdbStorage::new_with_cap_and_name(50000, "rings-node/measure")
                    .await
                    .expect("Failed on create measure storage"),
            );

            let provider = Provider::new_provider_internal(
                network_id,
                ice_servers,
                stabilize_interval,
                account,
                account_type,
                Signer::Async(Box::new(signer)),
                Some(vnode_storage),
                Some(measure_storage),
            )
            .await?;

            if let Some(cb) = backend_behaviour {
                let backend: Backend = Backend::new(Arc::new(provider.clone()), Box::new(cb));
                provider
                    .set_swarm_callback_internal(Arc::new(backend))
                    .expect("Failed on set swarm callback");
            }

            Ok(JsValue::from(provider))
        })
    }

    /// Create new provider instance with serialized config (yaml/json)
    pub fn new_provider_with_serialized_config(
        config: String,
        backend: Option<BackendBehaviour>,
    ) -> js_sys::Promise {
        let cfg: ProcessorConfig = serde_yaml::from_str(&config).unwrap();
        Self::new_provider_with_config(cfg, backend)
    }

    /// Create a new provider instance.
    pub fn new_provider_with_config(
        config: ProcessorConfig,
        backend: Option<BackendBehaviour>,
    ) -> js_sys::Promise {
        Self::new_provider_with_storage(config, backend, "rings-node".to_string())
    }

    /// get self web3 address
    #[wasm_bindgen(getter)]
    pub fn address(&self) -> String {
        self.processor.did().to_string()
    }

    ///  create new unsigned Provider
    pub fn new_provider_with_storage(
        config: ProcessorConfig,
        backend_behaviour: Option<BackendBehaviour>,
        storage_name: String,
    ) -> js_sys::Promise {
        future_to_promise(async move {
            let vnode_storage = Box::new(
                IdbStorage::new_with_cap_and_name(50000, &storage_name)
                    .await
                    .expect("Failed on create vnode storage"),
            );

            let measure_storage = Box::new(
                IdbStorage::new_with_cap_and_name(50000, &format!("{}/measure", storage_name))
                    .await
                    .expect("Failed on create measure storage"),
            );

            let provider = Self::new_provider_with_storage_internal(
                config,
                Some(vnode_storage),
                Some(measure_storage),
            )
            .await
            .map_err(JsError::from)?;
            if let Some(cb) = backend_behaviour {
                let backend: Backend = Backend::new(Arc::new(provider.clone()), Box::new(cb));
                provider
                    .set_swarm_callback_internal(Arc::new(backend))
                    .expect("Failed on set swarm callback");
            }
            Ok(JsValue::from(provider))
        })
    }

    /// Request local rpc interface
    pub fn request(&self, method: String, params: JsValue) -> js_sys::Promise {
        let ins = self.clone();
        future_to_promise(async move {
            let params =
                js_value::json_value(params).map_err(|e| JsError::new(e.to_string().as_str()))?;
            let ret = ins
                .request_internal(method, params)
                .await
                .map_err(JsError::from)?;
            Ok(js_value::serialize(&ret).map_err(JsError::from)?)
        })
    }

    /// listen message.
    pub fn listen(&self) -> js_sys::Promise {
        let p = self.processor.clone();

        future_to_promise(async move {
            p.listen().await;
            Ok(JsValue::null())
        })
    }

    /// connect peer with remote jsonrpc server url
    pub fn connect_peer_via_http(&self, remote_url: String) -> js_sys::Promise {
        log::debug!("remote_url: {}", remote_url);
        self.request(
            "ConnectPeerViaHttp".to_string(),
            js_value::serialize(&ConnectPeerViaHttpRequest { url: remote_url }).unwrap(),
        )
    }

    /// connect peer with web3 address
    /// example:
    /// ```typescript
    /// const provider1 = new Provider()
    /// const provider2 = new Provider()
    /// const provider3 = new Provider()
    /// await create_connection(provider1, provider2);
    /// await create_connection(provider2, provider3);
    /// await provider1.connect_with_did(provider3.address())
    /// ```
    pub fn connect_with_address(
        &self,
        address: String,
        addr_type: Option<AddressType>,
    ) -> js_sys::Promise {
        let p = self.processor.clone();
        future_to_promise(async move {
            let did = get_did(address.as_str(), addr_type.unwrap_or(AddressType::DEFAULT))?;
            p.connect_with_did(did).await.map_err(JsError::from)?;
            Ok(JsValue::null())
        })
    }

    /// get info for self, will return build version and inspection of swarm
    pub fn get_node_info(&self) -> js_sys::Promise {
        let p = self.processor.clone();
        future_to_promise(async move {
            let info = p.get_node_info().await.map_err(JsError::from)?;
            let v = js_value::serialize(&info).map_err(JsError::from)?;
            Ok(v)
        })
    }

    /// disconnect a peer with web3 address
    pub fn disconnect(&self, address: String, addr_type: Option<AddressType>) -> js_sys::Promise {
        let p = self.processor.clone();
        future_to_promise(async move {
            let did = get_did(address.as_str(), addr_type.unwrap_or(AddressType::DEFAULT))?;
            p.disconnect(did).await.map_err(JsError::from)?;

            Ok(JsValue::from_str(did.to_string().as_str()))
        })
    }

    /// send custom message to peer.
    pub fn send_message(&self, destination: String, msg: String) -> js_sys::Promise {
        let ins = self.clone();
        future_to_promise(async move {
            let did = get_did(destination.as_str(), AddressType::DEFAULT)?;
            let req: BackendMessage = BackendMessage::PlainText(msg);
            let params = req.into_send_backend_message_request(did)?;
            let ret = ins
                .request_internal(
                    Method::SendBackendMessage.to_string(),
                    serde_json::to_value(params).map_err(JsError::from)?,
                )
                .await?;
            Ok(js_value::serialize(&ret).map_err(JsError::from)?)
        })
    }

    /// Check local cache
    pub fn storage_check_cache(
        &self,
        address: String,
        addr_type: Option<AddressType>,
    ) -> js_sys::Promise {
        let p = self.processor.clone();
        future_to_promise(async move {
            let did = get_did(address.as_str(), addr_type.unwrap_or(AddressType::DEFAULT))?;
            let v_node = p.storage_check_cache(did).await;
            if let Some(v) = v_node {
                let data = js_value::serialize(&v).map_err(JsError::from)?;
                Ok(data)
            } else {
                Ok(JsValue::null())
            }
        })
    }

    /// fetch storage with given did
    pub fn storage_fetch(
        &self,
        address: String,
        addr_type: Option<AddressType>,
    ) -> js_sys::Promise {
        let p = self.processor.clone();
        future_to_promise(async move {
            let did = get_did(address.as_str(), addr_type.unwrap_or(AddressType::DEFAULT))?;
            p.storage_fetch(did).await.map_err(JsError::from)?;
            Ok(JsValue::null())
        })
    }

    /// store virtual node on DHT
    pub fn storage_store(&self, data: String) -> js_sys::Promise {
        let p = self.processor.clone();
        future_to_promise(async move {
            let vnode_info = vnode::VirtualNode::try_from(data).map_err(JsError::from)?;
            p.storage_store(vnode_info).await.map_err(JsError::from)?;
            Ok(JsValue::null())
        })
    }

    /// send http request message to remote
    /// - destination: did
    /// - service: service name
    /// - method: http method
    /// - path: http path like `/ipfs/abc1234` `/ipns/abc`
    /// - headers: headers of request
    /// - body: body of request
    #[allow(clippy::too_many_arguments)]
    pub fn send_http_request(
        &self,
        destination: String,
        service: String,
        method: String,
        path: String,
        headers: JsValue,
        body: Option<js_sys::Uint8Array>,
        rid: Option<String>,
    ) -> js_sys::Promise {
        let p = self.processor.clone();

        future_to_promise(async move {
            let destination = get_did(destination.as_str(), AddressType::DEFAULT)?;

            let method = http::Method::from_str(method.as_str())
                .map_err(JsError::from)?
                .to_string();

            let headers: Vec<(String, String)> = if headers.is_null() {
                Vec::new()
            } else if headers.is_object() {
                let mut header_vec: Vec<(String, String)> = Vec::new();
                let obj = js_sys::Object::from(headers);
                let entries = js_sys::Object::entries(&obj);
                for e in entries.iter() {
                    if js_sys::Array::is_array(&e) {
                        let arr = js_sys::Array::from(&e);
                        if arr.length() != 2 {
                            continue;
                        }
                        let k = arr.get(0).as_string().unwrap();
                        let v = arr.get(1);
                        if v.is_string() {
                            let v = v.as_string().unwrap();
                            header_vec.push((k, v))
                        }
                    }
                }
                header_vec
            } else {
                Vec::new()
            };

            let body = body.map(|item| item.to_vec());

            let req = HttpRequest {
                service,
                method,
                path,
                headers,
                body,
                rid,
            };

            let tx_id = p
                .send_backend_message(destination, ServiceMessage::HttpRequest(req).into())
                .await
                .map_err(JsError::from)?;

            Ok(JsValue::from_str(tx_id.to_string().as_str()))
        })
    }

    /// send simple text message to remote
    /// - destination: A did of destination
    /// - text: text message
    pub fn send_simple_text_message(&self, destination: String, text: String) -> js_sys::Promise {
        let p = self.processor.clone();

        future_to_promise(async move {
            let destination = get_did(destination.as_str(), AddressType::DEFAULT)?;
            let tx_id = p
                .send_backend_message(destination, BackendMessage::PlainText(text))
                .await
                .map_err(JsError::from)?;

            Ok(JsValue::from_str(tx_id.to_string().as_str()))
        })
    }

    /// lookup service did on DHT by its name
    /// - name: The name of service
    pub fn lookup_service(&self, name: String) -> js_sys::Promise {
        let p = self.processor.clone();

        future_to_promise(async move {
            let rid = VirtualNode::gen_did(&name).map_err(JsError::from)?;

            tracing::debug!("browser lookup_service storage_fetch: {}", rid);
            p.storage_fetch(rid).await.map_err(JsError::from)?;
            tracing::debug!("browser lookup_service finish storage_fetch: {}", rid);
            js_utils::window_sleep(500).await?;
            let result = p.storage_check_cache(rid).await;

            if let Some(vnode) = result {
                let dids = vnode
                    .data
                    .iter()
                    .map(|v| v.decode())
                    .filter_map(|v| v.ok())
                    .map(|x: String| JsValue::from_str(x.as_str()))
                    .collect::<js_sys::Array>();
                Ok(JsValue::from(dids))
            } else {
                Ok(JsValue::from(js_sys::Array::new()))
            }
        })
    }
}

fn get_did(address: &str, addr_type: AddressType) -> Result<Did, JsError> {
    let did = match addr_type {
        AddressType::DEFAULT => {
            Did::from_str(address).map_err(|_| JsError::new("invalid address"))?
        }
        AddressType::Ed25519 => PublicKey::try_from_b58t(address)
            .map_err(|_| JsError::new("invalid address"))?
            .address()
            .into(),
    };
    Ok(did)
}

/// Get address from hex pubkey
///  * pubkey: hex pubkey
#[wasm_export]
pub fn get_address_from_hex_pubkey(pubkey: String) -> Result<String, JsError> {
    Ok(Did::from(
        PublicKey::from_hex_string(pubkey.as_str())
            .map_err(JsError::from)?
            .address(),
    )
    .to_string())
}

/// Get address from other address
///   * address: source address
///   * addr_type: source address type
#[wasm_export]
pub fn get_address(address: &str, addr_type: AddressType) -> Result<String, JsError> {
    Ok(get_did(address, addr_type)?.to_string())
}