From 9b94e8e39cf13aa872757dc91c6f0d255ca37b00 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 17 Dec 2024 11:19:38 +0100 Subject: [PATCH 01/26] build: update wasm-bindgen-cli to 0.2.99 --- .devcontainer/Dockerfile | 2 +- .github/workflows/release.yml | 2 +- .github/workflows/tests-build-js.yml | 2 +- Dockerfile | 2 +- README.md | 2 +- packages/wasm-dpp/Cargo.toml | 2 +- packages/wasm-dpp/README.md | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index ce363420efb..f2373424b67 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -66,7 +66,7 @@ RUN set -ex; \ rm /tmp/cargo-binstall; \ cargo binstall -V -RUN cargo binstall wasm-bindgen-cli@0.2.86 --locked \ +RUN cargo binstall wasm-bindgen-cli@0.2.99 --locked \ --no-discover-github-token \ --disable-telemetry \ --no-track \ diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 269798a2ff6..0fd5f05672f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -70,7 +70,7 @@ jobs: if: ${{ steps.check-artifact.outputs.exists != 'true' }} - name: Install wasm-bindgen-cli - run: cargo binstall wasm-bindgen-cli@0.2.86 + run: cargo binstall wasm-bindgen-cli@0.2.99 if: ${{ steps.check-artifact.outputs.exists != 'true' }} - name: Build packages diff --git a/.github/workflows/tests-build-js.yml b/.github/workflows/tests-build-js.yml index a36bd91e2c0..0efd75fc7ce 100644 --- a/.github/workflows/tests-build-js.yml +++ b/.github/workflows/tests-build-js.yml @@ -50,7 +50,7 @@ jobs: if: ${{ steps.check-artifact.outputs.exists != 'true' }} - name: Install wasm-bindgen-cli - run: cargo binstall wasm-bindgen-cli@0.2.86 + run: cargo binstall wasm-bindgen-cli@0.2.99 if: ${{ steps.check-artifact.outputs.exists != 'true' }} - name: Build JS packages diff --git a/Dockerfile b/Dockerfile index 5c8ac67655e..671b488fff4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -313,7 +313,7 @@ RUN --mount=type=secret,id=AWS \ RUN --mount=type=secret,id=AWS \ source /root/env; \ - cargo binstall wasm-bindgen-cli@0.2.86 cargo-chef@0.1.67 \ + cargo binstall wasm-bindgen-cli@0.2.99 cargo-chef@0.1.67 \ --locked \ --no-discover-github-token \ --disable-telemetry \ diff --git a/README.md b/README.md index 5f4536c1769..d3bf8d7503d 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ this repository may be used on the following networks: in terminal run `echo 'export PATH="/opt/homebrew/opt/llvm/bin:$PATH"' >> ~/.zshrc` or `echo 'export PATH="/opt/homebrew/opt/llvm/bin:$PATH"' >> ~/.bash_profile` depending on your default shell. You can find your default shell with `echo $SHELL` - Reload your shell with `source ~/.zshrc` or `source ~/.bash_profile` - - `cargo install wasm-bindgen-cli@0.2.86` + - `cargo install wasm-bindgen-cli@0.2.99` - *double-check that wasm-bindgen-cli version above matches wasm-bindgen version in Cargo.lock file* - *Depending on system, additional packages may need to be installed as a prerequisite for wasm-bindgen-cli. If anything is missing, installation will error and prompt what packages are missing (i.e. clang, llvm, libssl-dev)* - essential build tools - example for Debian/Ubuntu: `apt install -y build-essential libssl-dev pkg-config clang cmake llvm` diff --git a/packages/wasm-dpp/Cargo.toml b/packages/wasm-dpp/Cargo.toml index 2b34c8af6ff..fc991dfe9d0 100644 --- a/packages/wasm-dpp/Cargo.toml +++ b/packages/wasm-dpp/Cargo.toml @@ -15,7 +15,7 @@ serde_json = { version = "1.0", features = ["preserve_order"] } # Meantime if you want to update wasm-bindgen you also need to update version in: # - packages/wasm-dpp/scripts/build-wasm.sh # - Dockerfile -wasm-bindgen = { version = "=0.2.86" } +wasm-bindgen = { version = "=0.2.99" } js-sys = "0.3.53" web-sys = { version = "0.3.6", features = ["console"] } thiserror = { version = "1.0.63" } diff --git a/packages/wasm-dpp/README.md b/packages/wasm-dpp/README.md index 73b3494c454..e16390f30ad 100644 --- a/packages/wasm-dpp/README.md +++ b/packages/wasm-dpp/README.md @@ -39,7 +39,7 @@ Library consumers must ignore class names minification for `@dashevo/wasm-dpp` l - Install [Rust](https://www.rust-lang.org/tools/install) v1.73+ - Add wasm32 target: `$ rustup target add wasm32-unknown-unknown` -- Install wasm-bingen-cli: `cargo install wasm-bindgen-cli@0.2.86` +- Install wasm-bingen-cli: `cargo install wasm-bindgen-cli@0.2.99` - *double-check that wasm-bindgen-cli version above matches wasm-bindgen version in Cargo.lock file* - *Depending on system, additional packages may need to be installed as a prerequisite for wasm-bindgen-cli. If anything is missing, installation will error and prompt what packages are missing (i.e. clang, llvm, libssl-dev)* From a27cdb379e2dc79ee3833b6029594e8154b0ec5c Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 17 Dec 2024 11:32:54 +0100 Subject: [PATCH 02/26] build: bump wasm-bindgen-futures to 0.4.49 --- Cargo.lock | 52 +++++++++++++++++++----------------- packages/wasm-dpp/Cargo.toml | 2 +- 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a7a7d564033..ea460381688 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "addr2line" @@ -2772,10 +2772,11 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.63" +version = "0.3.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f37a4a5928311ac501dee68b3c7613a1037d0edb30c8e5427bd832d55d1b790" +checksum = "6717b6b5b077764fb5966237269cb3c64edddde4b14ce42647430a78ced9e7b7" dependencies = [ + "once_cell", "wasm-bindgen", ] @@ -4397,7 +4398,7 @@ dependencies = [ [[package]] name = "serde-wasm-bindgen" version = "0.5.0" -source = "git+https://github.com/QuantumExplorer/serde-wasm-bindgen?branch=feat/not_human_readable#121d1f7fbf62cb97f74b91626a1b23851098cc82" +source = "git+https://github.com/QuantumExplorer/serde-wasm-bindgen?branch=feat%2Fnot_human_readable#121d1f7fbf62cb97f74b91626a1b23851098cc82" dependencies = [ "js-sys", "serde", @@ -4890,7 +4891,7 @@ dependencies = [ [[package]] name = "tenderdash-abci" version = "1.2.1+1.3.0" -source = "git+https://github.com/dashpay/rs-tenderdash-abci?tag=v1.2.1+1.3.0#aad72f4d25816bdf0f584ee4ba3cd383addf8a33" +source = "git+https://github.com/dashpay/rs-tenderdash-abci?tag=v1.2.1%2B1.3.0#aad72f4d25816bdf0f584ee4ba3cd383addf8a33" dependencies = [ "bytes", "futures", @@ -4911,7 +4912,7 @@ dependencies = [ [[package]] name = "tenderdash-proto" version = "1.2.1+1.3.0" -source = "git+https://github.com/dashpay/rs-tenderdash-abci?tag=v1.2.1+1.3.0#aad72f4d25816bdf0f584ee4ba3cd383addf8a33" +source = "git+https://github.com/dashpay/rs-tenderdash-abci?tag=v1.2.1%2B1.3.0#aad72f4d25816bdf0f584ee4ba3cd383addf8a33" dependencies = [ "bytes", "chrono", @@ -4930,7 +4931,7 @@ dependencies = [ [[package]] name = "tenderdash-proto-compiler" version = "1.2.1+1.3.0" -source = "git+https://github.com/dashpay/rs-tenderdash-abci?tag=v1.2.1+1.3.0#aad72f4d25816bdf0f584ee4ba3cd383addf8a33" +source = "git+https://github.com/dashpay/rs-tenderdash-abci?tag=v1.2.1%2B1.3.0#aad72f4d25816bdf0f584ee4ba3cd383addf8a33" dependencies = [ "fs_extra", "prost-build", @@ -5300,7 +5301,7 @@ dependencies = [ [[package]] name = "tower" version = "0.4.13" -source = "git+https://github.com/QuantumExplorer/tower?branch=fix/indexMap2OnV0413#5286f8c605d10f48d51254f2434c5ab3fc5d7779" +source = "git+https://github.com/QuantumExplorer/tower?branch=fix%2FindexMap2OnV0413#5286f8c605d10f48d51254f2434c5ab3fc5d7779" dependencies = [ "futures-core", "futures-util", @@ -5344,12 +5345,12 @@ dependencies = [ [[package]] name = "tower-layer" version = "0.3.2" -source = "git+https://github.com/QuantumExplorer/tower?branch=fix/indexMap2OnV0413#5286f8c605d10f48d51254f2434c5ab3fc5d7779" +source = "git+https://github.com/QuantumExplorer/tower?branch=fix%2FindexMap2OnV0413#5286f8c605d10f48d51254f2434c5ab3fc5d7779" [[package]] name = "tower-service" version = "0.3.2" -source = "git+https://github.com/QuantumExplorer/tower?branch=fix/indexMap2OnV0413#5286f8c605d10f48d51254f2434c5ab3fc5d7779" +source = "git+https://github.com/QuantumExplorer/tower?branch=fix%2FindexMap2OnV0413#5286f8c605d10f48d51254f2434c5ab3fc5d7779" [[package]] name = "tracing" @@ -5645,23 +5646,23 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.86" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bba0e8cb82ba49ff4e229459ff22a191bbe9a1cb3a341610c9c33efc27ddf73" +checksum = "a474f6281d1d70c17ae7aa6a613c87fce69a127e2624002df63dcb39d6cf6396" dependencies = [ "cfg-if", + "once_cell", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" -version = "0.2.86" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19b04bc93f9d6bdee709f6bd2118f57dd6679cf1176a1af464fca3ab0d66d8fb" +checksum = "5f89bb38646b4f81674e8f5c3fb81b562be1fd936d84320f3264486418519c79" dependencies = [ "bumpalo", "log", - "once_cell", "proc-macro2", "quote", "syn 2.0.75", @@ -5670,21 +5671,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.36" +version = "0.4.49" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d1985d03709c53167ce907ff394f5316aa22cb4e12761295c5dc57dacb6297e" +checksum = "38176d9b44ea84e9184eff0bc34cc167ed044f816accfe5922e54d84cf48eca2" dependencies = [ "cfg-if", "js-sys", + "once_cell", "wasm-bindgen", "web-sys", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.86" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14d6b024f1a526bb0234f52840389927257beb670610081360e5a03c5df9c258" +checksum = "2cc6181fd9a7492eef6fef1f33961e3695e4579b9872a6f7c83aee556666d4fe" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -5692,9 +5694,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.86" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e128beba882dd1eb6200e1dc92ae6c5dbaa4311aa7bb211ca035779e5efc39f8" +checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2" dependencies = [ "proc-macro2", "quote", @@ -5705,9 +5707,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.86" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed9d5b4305409d1fc9482fee2d7f9bcbf24b3972bf59817ef757e23982242a93" +checksum = "943aab3fdaaa029a6e0271b35ea10b72b943135afe9bffca82384098ad0e06a6" [[package]] name = "wasm-dpp" @@ -5746,9 +5748,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.63" +version = "0.3.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bdd9ef4e984da1187bf8110c5cf5b845fbc87a23602cdf912386a76fcd3a7c2" +checksum = "04dd7223427d52553d3702c004d3b2fe07c148165faa56313cb00211e31c12bc" dependencies = [ "js-sys", "wasm-bindgen", diff --git a/packages/wasm-dpp/Cargo.toml b/packages/wasm-dpp/Cargo.toml index fc991dfe9d0..ab0080a6924 100644 --- a/packages/wasm-dpp/Cargo.toml +++ b/packages/wasm-dpp/Cargo.toml @@ -49,7 +49,7 @@ hex = { version = "0.4" } paste = "1.0.14" anyhow = { version = "1.0.75" } # required, cargo-machete false positive -wasm-bindgen-futures = "0.4.33" +wasm-bindgen-futures = "0.4.49" async-trait = "0.1.59" bincode = "2.0.0-rc.3" [profile.release] From 7475b091887192e98960c52570f6e2006abe1853 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 17 Dec 2024 11:42:36 +0100 Subject: [PATCH 03/26] chore(wasm-dpp): fix build --- .../wasm-dpp/src/identity/factory_utils.rs | 12 +++---- .../state_transition/asset_lock_proof/mod.rs | 5 ++- .../identity_create_transition.rs | 19 +++++------- .../identity_update_transition.rs | 31 +++++++------------ 4 files changed, 26 insertions(+), 41 deletions(-) diff --git a/packages/wasm-dpp/src/identity/factory_utils.rs b/packages/wasm-dpp/src/identity/factory_utils.rs index 18e19428423..f14431ac8ee 100644 --- a/packages/wasm-dpp/src/identity/factory_utils.rs +++ b/packages/wasm-dpp/src/identity/factory_utils.rs @@ -9,7 +9,6 @@ use dpp::identity::{IdentityPublicKey, KeyID}; use dpp::serialization::ValueConvertible; use dpp::state_transition::public_key_in_creation::IdentityPublicKeyInCreation; use std::collections::BTreeMap; -use wasm_bindgen::__rt::Ref; use wasm_bindgen::{JsCast, JsValue}; pub fn parse_public_keys( @@ -47,11 +46,10 @@ pub fn parse_create_identity_update_transition_keys( let keys: Vec = add_public_keys_array .iter() .map(|key| { - let public_key: Ref = - generic_of_js_val::( - &key, - "IdentityPublicKeyWithWitness", - )?; + let public_key = generic_of_js_val::( + &key, + "IdentityPublicKeyWithWitness", + )?; Ok(public_key.clone().into()) }) @@ -74,7 +72,7 @@ pub fn parse_create_identity_update_transition_keys( let keys: Vec = disable_public_keys_array .iter() .map(|key| { - let public_key_wasm: Ref = + let public_key_wasm = generic_of_js_val::(&key, "IdentityPublicKey")?; Ok(public_key_wasm.get_id()) }) diff --git a/packages/wasm-dpp/src/identity/state_transition/asset_lock_proof/mod.rs b/packages/wasm-dpp/src/identity/state_transition/asset_lock_proof/mod.rs index 861188d0ca4..dd4fca03cd3 100644 --- a/packages/wasm-dpp/src/identity/state_transition/asset_lock_proof/mod.rs +++ b/packages/wasm-dpp/src/identity/state_transition/asset_lock_proof/mod.rs @@ -5,7 +5,6 @@ pub use chain::*; pub use instant::*; use std::convert::TryInto; use wasm_bindgen::JsCast; -use wasm_bindgen::__rt::Ref; use dpp::identity::errors::UnknownAssetLockProofTypeError; use wasm_bindgen::prelude::*; @@ -144,13 +143,13 @@ pub fn create_asset_lock_proof_from_wasm_instance( match lock_type { AssetLockProofType::Instant => { - let instant: Ref = + let instant = generic_of_js_val::(js_value, "InstantAssetLockProof")?; Ok(AssetLockProof::Instant(instant.clone().into())) } AssetLockProofType::Chain => { - let chain: Ref = + let chain = generic_of_js_val::(js_value, "ChainAssetLockProof")?; Ok(AssetLockProof::Chain(chain.clone().into())) diff --git a/packages/wasm-dpp/src/identity/state_transition/identity_create_transition/identity_create_transition.rs b/packages/wasm-dpp/src/identity/state_transition/identity_create_transition/identity_create_transition.rs index 86681592df3..9b5a402ddd2 100644 --- a/packages/wasm-dpp/src/identity/state_transition/identity_create_transition/identity_create_transition.rs +++ b/packages/wasm-dpp/src/identity/state_transition/identity_create_transition/identity_create_transition.rs @@ -1,6 +1,5 @@ use std::default::Default; -use wasm_bindgen::__rt::Ref; use wasm_bindgen::prelude::*; use crate::bls_adapter::BlsAdapter; @@ -101,11 +100,10 @@ impl IdentityCreateTransitionWasm { let public_keys = public_keys .iter() .map(|value| { - let public_key: Ref = - generic_of_js_val::( - value, - "IdentityPublicKeyWithWitness", - )?; + let public_key = generic_of_js_val::( + value, + "IdentityPublicKeyWithWitness", + )?; Ok(public_key.clone().into()) }) .collect::, JsValue>>()?; @@ -120,11 +118,10 @@ impl IdentityCreateTransitionWasm { let mut public_keys = public_keys .iter() .map(|value| { - let public_key: Ref = - generic_of_js_val::( - value, - "IdentityPublicKeyWithWitness", - )?; + let public_key = generic_of_js_val::( + value, + "IdentityPublicKeyWithWitness", + )?; Ok(public_key.clone().into()) }) .collect::, JsValue>>()?; diff --git a/packages/wasm-dpp/src/identity/state_transition/identity_update_transition/identity_update_transition.rs b/packages/wasm-dpp/src/identity/state_transition/identity_update_transition/identity_update_transition.rs index 1d8988ba6f9..5692dd63d3f 100644 --- a/packages/wasm-dpp/src/identity/state_transition/identity_update_transition/identity_update_transition.rs +++ b/packages/wasm-dpp/src/identity/state_transition/identity_update_transition/identity_update_transition.rs @@ -1,24 +1,12 @@ -use std::convert::TryInto; -use std::default::Default; - -use serde::{Deserialize, Serialize}; - -use wasm_bindgen::__rt::Ref; -use wasm_bindgen::prelude::*; - +use crate::bls_adapter::{BlsAdapter, JsBlsAdapter}; +use crate::errors::from_dpp_err; use crate::identifier::IdentifierWrapper; - +use crate::utils::{generic_of_js_val, WithJsError}; use crate::{ buffer::Buffer, identity::state_transition::identity_public_key_transitions::IdentityPublicKeyWithWitnessWasm, identity::IdentityPublicKeyWasm, with_js_error, }; - -use crate::bls_adapter::{BlsAdapter, JsBlsAdapter}; - -use crate::utils::{generic_of_js_val, WithJsError}; - -use crate::errors::from_dpp_err; use dpp::errors::consensus::signature::SignatureError; use dpp::errors::consensus::ConsensusError; use dpp::errors::ProtocolError; @@ -34,6 +22,10 @@ use dpp::state_transition::StateTransition; use dpp::state_transition::StateTransitionIdentitySigned; use dpp::version::PlatformVersion; use dpp::{identifier::Identifier, state_transition::StateTransitionLike}; +use serde::{Deserialize, Serialize}; +use std::convert::TryInto; +use std::default::Default; +use wasm_bindgen::prelude::*; #[wasm_bindgen(js_name=IdentityUpdateTransition)] #[derive(Clone)] @@ -93,11 +85,10 @@ impl IdentityUpdateTransitionWasm { keys_to_add = keys .iter() .map(|value| { - let public_key: Ref = - generic_of_js_val::( - value, - "IdentityPublicKeyWithWitness", - )?; + let public_key = generic_of_js_val::( + value, + "IdentityPublicKeyWithWitness", + )?; Ok(public_key.clone().into()) }) .collect::, JsValue>>()?; From 068a6fb0c7550d3da40e316b0e2263d599c5d3f9 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 19 Dec 2024 23:02:37 +0100 Subject: [PATCH 04/26] chore: dapi-grpc wasm feature --- .cargo/config-release.toml | 3 ++ .cargo/config.toml | 3 ++ packages/dapi-grpc/Cargo.toml | 25 ++++++++++--- packages/dapi-grpc/build.rs | 70 ++++++++++++++++++++++++++--------- packages/dapi-grpc/src/lib.rs | 17 +++++---- 5 files changed, 87 insertions(+), 31 deletions(-) diff --git a/.cargo/config-release.toml b/.cargo/config-release.toml index faab5e6c572..7229efc68bd 100644 --- a/.cargo/config-release.toml +++ b/.cargo/config-release.toml @@ -9,3 +9,6 @@ rustflags = ["-C", "target-feature=-crt-static"] [target.aarch64-unknown-linux-gnu] linker = "aarch64-linux-gnu-gcc" + +[target.wasm32-unknown-unknown] +rustflags = ['--cfg', 'getrandom_backend="wasm_js"'] diff --git a/.cargo/config.toml b/.cargo/config.toml index 18bc8e4064b..2ef8c318fc4 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -9,5 +9,8 @@ rustflags = ["-C", "target-feature=-crt-static", "--cfg", "tokio_unstable"] [target.aarch64-unknown-linux-gnu] linker = "aarch64-linux-gnu-gcc" +[target.wasm32-unknown-unknown] +rustflags = ['--cfg', 'getrandom_backend="wasm_js"'] + [build] rustflags = ["--cfg", "tokio_unstable"] diff --git a/packages/dapi-grpc/Cargo.toml b/packages/dapi-grpc/Cargo.toml index 6444245d9e9..0e6a8794530 100644 --- a/packages/dapi-grpc/Cargo.toml +++ b/packages/dapi-grpc/Cargo.toml @@ -20,6 +20,8 @@ platform = [] # Re-export Dash Platform protobuf types as `dapi_grpc::platform::proto` # Note: client needs tls and tls-roots to connect to testnet which uses TLS. tenderdash-proto = [] + +# Client support. client = [ "tonic/channel", "tonic/transport", @@ -27,12 +29,28 @@ client = [ "tonic/tls-roots", "tonic/tls-webpki-roots", "platform", + "tenderdash-proto/client", ] -server = ["tonic/channel", "tonic/transport", "platform"] -serde = ["dep:serde", "dep:serde_bytes"] + +# Specialized features for building the client in a wasm environment. +# Conflicts with `client` and `server` feature. +wasm = ["tenderdash-proto/client"] + +# Build tonic server code. Includes all client features and adds server-specific dependencies. +server = [ + "tonic/channel", + "tonic/transport", + "platform", + "tenderdash-proto/server", + "client", +] + +serde = ["dep:serde", "dep:serde_bytes", "tenderdash-proto/serde"] mocks = ["serde", "dep:serde_json"] [dependencies] +tenderdash-proto = { path = "../../../rs-tenderdash-abci/proto", default-features = false } + prost = { version = "0.13" } futures-core = "0.3.30" tonic = { version = "0.12.3", features = [ @@ -42,9 +60,6 @@ tonic = { version = "0.12.3", features = [ serde = { version = "1.0.197", optional = true, features = ["derive"] } serde_bytes = { version = "0.11.12", optional = true } serde_json = { version = "1.0", optional = true } -tenderdash-proto = { git = "https://github.com/dashpay/rs-tenderdash-abci", version = "1.2.1", tag = "v1.2.1+1.3.0", default-features = false, features = [ - "grpc", -] } dapi-grpc-macros = { path = "../rs-dapi-grpc-macros" } platform-version = { path = "../rs-platform-version" } diff --git a/packages/dapi-grpc/build.rs b/packages/dapi-grpc/build.rs index 642b614ab90..29f93be032e 100644 --- a/packages/dapi-grpc/build.rs +++ b/packages/dapi-grpc/build.rs @@ -2,7 +2,6 @@ use std::{ collections::HashSet, fs::{create_dir_all, remove_dir_all}, path::PathBuf, - process::exit, }; use tonic_build::Builder; @@ -14,9 +13,19 @@ const SERDE_WITH_STRING: &str = r#"#[cfg_attr(feature = "serde", serde(with = "crate::deserialization::from_to_string"))]"#; fn main() { + #[cfg(feature = "server")] + generate_code(ImplType::Server); + #[cfg(feature = "client")] + generate_code(ImplType::Client); + #[cfg(feature = "wasm")] + generate_code(ImplType::Wasm); +} + +fn generate_code(typ: ImplType) { let core = MappingConfig::new( PathBuf::from("protos/core/v0/core.proto"), PathBuf::from("src/core"), + &typ, ); configure_core(core) @@ -26,6 +35,7 @@ fn main() { let platform = MappingConfig::new( PathBuf::from("protos/platform/v0/platform.proto"), PathBuf::from("src/platform"), + &typ, ); configure_platform(platform) @@ -210,6 +220,43 @@ fn configure_core(core: MappingConfig) -> MappingConfig { core } +#[allow(unused)] +enum ImplType { + Server, + Client, + Wasm, +} + +impl ImplType { + // Configure the builder based on the implementation type. + pub fn configure(&self, builder: Builder) -> Builder { + match self { + Self::Server => builder + .build_client(true) + .build_server(true) + .build_transport(true), + Self::Client => builder + .build_client(true) + .build_server(false) + .build_transport(true), + Self::Wasm => builder + .build_client(true) + .build_server(false) + .build_transport(false), + } + } + + /// Get the directory name for the implementation type. + fn dirname(&self) -> String { + match self { + Self::Server => "server", + Self::Client => "client", + Self::Wasm => "wasm", + } + .to_string() + } +} + impl MappingConfig { /// Create a new MappingConfig instance. /// @@ -220,31 +267,18 @@ impl MappingConfig { /// /// Depending on the features, either `client`, `server` or `client_server` subdirectory /// will be created inside `out_dir`. - fn new(protobuf_file: PathBuf, out_dir: PathBuf) -> Self { + fn new(protobuf_file: PathBuf, out_dir: PathBuf, typ: &ImplType) -> Self { let protobuf_file = abs_path(&protobuf_file); - let build_server = cfg!(feature = "server"); - let build_client = cfg!(feature = "client"); - // Depending on the features, we need to build the server, client or both. // We save these artifacts in separate directories to avoid overwriting the generated files // when another crate requires different features. - let out_dir_suffix = match (build_server, build_client) { - (true, true) => "client_server", - (true, false) => "server", - (false, true) => "client", - (false, false) => { - println!("WARNING: At least one of the features 'server' or 'client' must be enabled; dapi-grpc will not generate any files."); - exit(0) - } - }; + let out_dir_suffix = typ.dirname(); let out_dir = abs_path(&out_dir.join(out_dir_suffix)); - let builder = tonic_build::configure() - .build_server(build_server) - .build_client(build_client) - .build_transport(build_server || build_client) + let builder = typ + .configure(tonic_build::configure()) .out_dir(out_dir.clone()) .protoc_arg("--experimental_allow_proto3_optional"); diff --git a/packages/dapi-grpc/src/lib.rs b/packages/dapi-grpc/src/lib.rs index 486ba8f3fce..4c33e157883 100644 --- a/packages/dapi-grpc/src/lib.rs +++ b/packages/dapi-grpc/src/lib.rs @@ -4,36 +4,37 @@ pub use prost::Message; pub mod core { #![allow(non_camel_case_types)] pub mod v0 { - #[cfg(all(feature = "server", not(feature = "client")))] + // Note: only one of the features can be analyzed at a time + #[cfg(feature = "server")] include!("core/server/org.dash.platform.dapi.v0.rs"); #[cfg(all(feature = "client", not(feature = "server")))] include!("core/client/org.dash.platform.dapi.v0.rs"); - #[cfg(all(feature = "server", feature = "client"))] - include!("core/client_server/org.dash.platform.dapi.v0.rs"); + #[cfg(all(feature = "wasm", not(any(feature = "server", feature = "client"))))] + include!("core/wasm/org.dash.platform.dapi.v0.rs"); } } #[cfg(feature = "platform")] pub mod platform { pub mod v0 { - #[cfg(all(feature = "server", not(feature = "client")))] + #[cfg(feature = "server")] include!("platform/server/org.dash.platform.dapi.v0.rs"); #[cfg(all(feature = "client", not(feature = "server")))] include!("platform/client/org.dash.platform.dapi.v0.rs"); - #[cfg(all(feature = "server", feature = "client"))] - include!("platform/client_server/org.dash.platform.dapi.v0.rs"); + #[cfg(all(feature = "wasm", not(any(feature = "server", feature = "client"))))] + include!("platform/wasm/org.dash.platform.dapi.v0.rs"); } #[cfg(feature = "tenderdash-proto")] pub use tenderdash_proto as proto; - #[cfg(any(feature = "server", feature = "client"))] + #[cfg(any(feature = "server", feature = "client", feature = "wasm"))] mod versioning; - #[cfg(any(feature = "server", feature = "client"))] + #[cfg(any(feature = "server", feature = "client", feature = "wasm"))] pub use versioning::{VersionedGrpcMessage, VersionedGrpcResponse}; } From 3f3f76d7417963caceac7748ac17d7f6a815e234 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 20 Dec 2024 11:43:40 +0100 Subject: [PATCH 05/26] chore: WIP --- Cargo.lock | 304 ++++++++++++++++-- Cargo.toml | 2 +- packages/rs-dapi-client/Cargo.toml | 28 +- packages/rs-dapi-client/src/address_list.rs | 2 +- .../rs-dapi-client/src/connection_pool.rs | 2 +- packages/rs-dapi-client/src/dapi_client.rs | 14 +- packages/rs-dapi-client/src/executor.rs | 8 +- packages/rs-dapi-client/src/lib.rs | 7 + .../rs-dapi-client/src/request_settings.rs | 4 + packages/rs-dapi-client/src/transport.rs | 13 +- packages/rs-dapi-client/src/transport/grpc.rs | 49 +-- .../src/transport/tonic_channel.rs | 57 ++++ .../src/transport/wasm_channel.rs | 67 ++++ packages/rs-dpp/src/balances/credits.rs | 4 - packages/rs-drive-abci/Cargo.toml | 5 +- packages/rs-drive-proof-verifier/Cargo.toml | 5 +- packages/rs-sdk/Cargo.toml | 23 +- .../platform/transition/broadcast_identity.rs | 29 +- packages/rs-sdk/src/sdk.rs | 8 +- packages/rs-sdk/src/sync.rs | 17 +- packages/wasm-sdk/Cargo.toml | 31 ++ packages/wasm-sdk/index.html | 59 ++++ packages/wasm-sdk/src/lib.rs | 11 + 23 files changed, 645 insertions(+), 104 deletions(-) create mode 100644 packages/rs-dapi-client/src/transport/tonic_channel.rs create mode 100644 packages/rs-dapi-client/src/transport/wasm_channel.rs create mode 100644 packages/wasm-sdk/Cargo.toml create mode 100644 packages/wasm-sdk/index.html create mode 100644 packages/wasm-sdk/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index ea460381688..d518d867684 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -183,17 +183,113 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" +[[package]] +name = "async-channel" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35" +dependencies = [ + "concurrent-queue", + "event-listener 2.5.3", + "futures-core", +] + +[[package]] +name = "async-channel" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89b47800b0be77592da0afd425cc03468052844aff33b84e33cc696f64e77b6a" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30ca9a001c1e8ba5149f91a74362376cc6bc5b919d92d988668657bd570bdcec" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "slab", +] + +[[package]] +name = "async-global-executor" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" +dependencies = [ + "async-channel 2.3.1", + "async-executor", + "async-io", + "async-lock", + "blocking", + "futures-lite", + "once_cell", +] + +[[package]] +name = "async-io" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43a2b323ccce0a1d90b449fd71f2a06ca7faa7c54c2751f06c9bd851fc061059" +dependencies = [ + "async-lock", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "tracing", + "windows-sys 0.59.0", +] + [[package]] name = "async-lock" version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" dependencies = [ - "event-listener", + "event-listener 5.3.1", "event-listener-strategy", "pin-project-lite", ] +[[package]] +name = "async-std" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c634475f29802fde2b8f0b505b1bd00dfe4df7d4a000f0b36f7671197d5c3615" +dependencies = [ + "async-channel 1.9.0", + "async-global-executor", + "async-io", + "async-lock", + "crossbeam-utils", + "futures-channel", + "futures-core", + "futures-io", + "futures-lite", + "gloo-timers", + "kv-log-macro", + "log", + "memchr", + "once_cell", + "pin-project-lite", + "pin-utils", + "slab", + "wasm-bindgen-futures", +] + [[package]] name = "async-stream" version = "0.3.5" @@ -216,6 +312,12 @@ dependencies = [ "syn 2.0.75", ] +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + [[package]] name = "async-trait" version = "0.1.83" @@ -309,9 +411,9 @@ dependencies = [ [[package]] name = "backon" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4fa97bb310c33c811334143cf64c5bb2b7b3c06e453db6b095d7061eff8f113" +checksum = "ba5289ec98f68f28dd809fd601059e6aa908bb8f6108620930828283d4ee23d7" dependencies = [ "fastrand", "gloo-timers", @@ -518,6 +620,19 @@ dependencies = [ "generic-array 0.14.7", ] +[[package]] +name = "blocking" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "703f41c54fc768e63e091340b424302bb1c29ef4aa0c7f10fe849dfb114d29ea" +dependencies = [ + "async-channel 2.3.1", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + [[package]] name = "bls-dash-sys" version = "1.2.5" @@ -1139,7 +1254,7 @@ dependencies = [ "serde", "serde_bytes", "serde_json", - "tenderdash-proto", + "tenderdash-proto 1.2.1+1.3.0", "tonic", "tonic-build", ] @@ -1791,6 +1906,12 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "event-listener" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" + [[package]] name = "event-listener" version = "5.3.1" @@ -1808,7 +1929,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f214dc438f977e6d4e3500aaa277f5ad94ca83fbbd9b1a15713ce2344ccc5a1" dependencies = [ - "event-listener", + "event-listener 5.3.1", "pin-project-lite", ] @@ -1841,8 +1962,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "531e46835a22af56d1e3b66f04844bed63158bc094a628bec1d321d9b4c44bf2" dependencies = [ "bit-set", - "regex-automata 0.4.7", - "regex-syntax 0.8.4", + "regex-automata 0.4.9", + "regex-syntax 0.8.5", ] [[package]] @@ -2025,6 +2146,19 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" +[[package]] +name = "futures-lite" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cef40d21ae2c515b51041df9ed313ed21e572df340ea58a922a0aefe7e8891a1" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + [[package]] name = "futures-macro" version = "0.3.30" @@ -2850,6 +2984,15 @@ dependencies = [ "cpufeatures", ] +[[package]] +name = "kv-log-macro" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f" +dependencies = [ + "log", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -2944,6 +3087,9 @@ name = "log" version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" +dependencies = [ + "value-bag", +] [[package]] name = "lru" @@ -3140,7 +3286,7 @@ dependencies = [ "crossbeam-channel", "crossbeam-epoch", "crossbeam-utils", - "event-listener", + "event-listener 5.3.1", "futures-util", "once_cell", "parking_lot", @@ -3566,6 +3712,17 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[package]] +name = "piper" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c8c490f422ef9a4efd2cb5b42b76c8613d7e7dfc1caf667b8a3350a5acc066" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + [[package]] name = "pkcs8" version = "0.10.2" @@ -3677,6 +3834,21 @@ dependencies = [ "plotters-backend", ] +[[package]] +name = "polling" +version = "3.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a604568c3202727d1507653cb121dbd627a58684eb09a820fd746bee38b4442f" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi 0.4.0", + "pin-project-lite", + "rustix", + "tracing", + "windows-sys 0.59.0", +] + [[package]] name = "portable-atomic" version = "1.7.0" @@ -3977,14 +4149,14 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.6" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4219d74c6b67a3654a9fbebc4b419e22126d13d2f3c4a07ee0cb61ff79a79619" +checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" dependencies = [ "aho-corasick", "memchr", - "regex-automata 0.4.7", - "regex-syntax 0.8.4", + "regex-automata 0.4.9", + "regex-syntax 0.8.5", ] [[package]] @@ -3998,13 +4170,13 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.7" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" +checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.4", + "regex-syntax 0.8.5", ] [[package]] @@ -4015,9 +4187,9 @@ checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" [[package]] name = "regex-syntax" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" +checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] name = "rend" @@ -4139,11 +4311,14 @@ dependencies = [ name = "rs-dapi-client" version = "1.7.0" dependencies = [ + "async-std", "backon", "chrono", "dapi-grpc", "futures", + "getrandom", "hex", + "http", "http-serde", "lru", "rand", @@ -4152,6 +4327,7 @@ dependencies = [ "sha2", "thiserror", "tokio", + "tonic-web-wasm-client", "tracing", ] @@ -4293,11 +4469,10 @@ dependencies = [ [[package]] name = "sanitize-filename" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ed72fbaf78e6f2d41744923916966c4fbe3d7c74e3037a8ee482f1115572603" +checksum = "bc984f4f9ceb736a7bb755c3e3bd17dc56370af2600c9780dcc48c66453da34d" dependencies = [ - "lazy_static", "regex", ] @@ -4899,7 +5074,7 @@ dependencies = [ "lhash", "semver", "serde_json", - "tenderdash-proto", + "tenderdash-proto 1.2.1+1.3.0 (git+https://github.com/dashpay/rs-tenderdash-abci?tag=v1.2.1%2B1.3.0)", "thiserror", "tokio", "tokio-util", @@ -4909,6 +5084,24 @@ dependencies = [ "uuid", ] +[[package]] +name = "tenderdash-proto" +version = "1.2.1+1.3.0" +dependencies = [ + "bytes", + "chrono", + "derive_more 1.0.0", + "flex-error", + "num-derive", + "num-traits", + "prost", + "serde", + "subtle-encoding", + "tenderdash-proto-compiler 1.2.1+1.3.0", + "time", + "tonic", +] + [[package]] name = "tenderdash-proto" version = "1.2.1+1.3.0" @@ -4923,11 +5116,25 @@ dependencies = [ "prost", "serde", "subtle-encoding", - "tenderdash-proto-compiler", + "tenderdash-proto-compiler 1.2.1+1.3.0 (git+https://github.com/dashpay/rs-tenderdash-abci?tag=v1.2.1%2B1.3.0)", "time", "tonic", ] +[[package]] +name = "tenderdash-proto-compiler" +version = "1.2.1+1.3.0" +dependencies = [ + "fs_extra", + "prost-build", + "regex", + "tempfile", + "tonic-build", + "ureq", + "walkdir", + "zip 2.2.0", +] + [[package]] name = "tenderdash-proto-compiler" version = "1.2.1+1.3.0" @@ -5298,6 +5505,31 @@ dependencies = [ "syn 2.0.75", ] +[[package]] +name = "tonic-web-wasm-client" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef5ca6e7bdd0042c440d36b6df97c1436f1d45871ce18298091f114004b1beb4" +dependencies = [ + "base64 0.22.1", + "byteorder", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "httparse", + "js-sys", + "pin-project", + "thiserror", + "tonic", + "tower-service", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + [[package]] name = "tower" version = "0.4.13" @@ -5554,6 +5786,12 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" +[[package]] +name = "value-bag" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ef4c4aa54d5d05a279399bfa921ec387b7aba77caf7a682ae8d86785b8fdad2" + [[package]] name = "vcpkg" version = "0.2.15" @@ -5746,6 +5984,28 @@ dependencies = [ "web-sys", ] +[[package]] +name = "wasm-sdk" +version = "0.1.0" +dependencies = [ + "dash-sdk", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-streams" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e072d4e72f700fb3443d8fe94a39315df013eef1104903cdb0a2abd322bbecd" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "web-sys" version = "0.3.76" diff --git a/Cargo.toml b/Cargo.toml index 02295b6b475..88767db3719 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ members = [ "packages/simple-signer", "packages/rs-json-schema-compatibility-validator", "packages/check-features", - "packages/wallet-utils-contract", + "packages/wallet-utils-contract", "packages/wasm-sdk", ] [workspace.package] diff --git a/packages/rs-dapi-client/Cargo.toml b/packages/rs-dapi-client/Cargo.toml index c6f32b443df..f3ad5aaa288 100644 --- a/packages/rs-dapi-client/Cargo.toml +++ b/packages/rs-dapi-client/Cargo.toml @@ -4,7 +4,8 @@ version = "1.7.0" edition = "2021" [features] -default = ["mocks", "offline-testing"] +# TODO we should not enable deps features in default +default = ["mocks", "offline-testing", "dapi-grpc/client", "backon/tokio-sleep"] mocks = [ "dep:sha2", "dep:hex", @@ -17,17 +18,34 @@ mocks = [ dump = ["mocks"] # skip tests that require connection to the platform; enabled by default offline-testing = [] +wasm = [ + "dapi-grpc/wasm", + "dapi-grpc/platform", + "dapi-grpc/core", + # "backon/gloo-timers-sleep", + # "backon/std-blocking-sleep", + "dep:async-std", + "dep:tonic-web-wasm-client", + "dep:http", + "getrandom/js", +] [dependencies] -backon = { version = "1.2", features = ["tokio-sleep"] } +backon = { version = "1.3", default-features = false } + dapi-grpc = { path = "../dapi-grpc", features = [ "core", "platform", - "client", ], default-features = false } futures = "0.3.28" +http = { version = "1.1.0", default-features = false, optional = true } http-serde = { version = "2.1", optional = true } -rand = { version = "0.8.5", features = ["small_rng"] } +getrandom = { version = "0.2", optional = true } +tonic-web-wasm-client = { version = "0.6.0", optional = true } +rand = { version = "0.8.5", features = [ + "small_rng", + "getrandom", +], default-features = false } thiserror = "1.0.64" tracing = "0.1.40" tokio = { version = "1.40", default-features = false } @@ -37,6 +55,6 @@ lru = { version = "0.12.3" } serde = { version = "1.0.197", optional = true, features = ["derive"] } serde_json = { version = "1.0.120", optional = true } chrono = { version = "0.4.38", features = ["serde"] } - +async-std = { version = "1.13", optional = true } [dev-dependencies] tokio = { version = "1.40", features = ["macros"] } diff --git a/packages/rs-dapi-client/src/address_list.rs b/packages/rs-dapi-client/src/address_list.rs index 2f59b22c3bc..eeea7be8a22 100644 --- a/packages/rs-dapi-client/src/address_list.rs +++ b/packages/rs-dapi-client/src/address_list.rs @@ -1,7 +1,7 @@ //! Subsystem to manage DAPI nodes. +use crate::Uri; use chrono::Utc; -use dapi_grpc::tonic::transport::Uri; use rand::{rngs::SmallRng, seq::IteratorRandom, SeedableRng}; use std::collections::hash_map::Entry; use std::collections::HashMap; diff --git a/packages/rs-dapi-client/src/connection_pool.rs b/packages/rs-dapi-client/src/connection_pool.rs index 97dd991d509..99effb4ac76 100644 --- a/packages/rs-dapi-client/src/connection_pool.rs +++ b/packages/rs-dapi-client/src/connection_pool.rs @@ -3,12 +3,12 @@ use std::{ sync::{Arc, Mutex}, }; -use dapi_grpc::tonic::transport::Uri; use lru::LruCache; use crate::{ request_settings::AppliedRequestSettings, transport::{CoreGrpcClient, PlatformGrpcClient}, + Uri, }; /// ConnectionPool represents pool of connections to DAPI nodes. diff --git a/packages/rs-dapi-client/src/dapi_client.rs b/packages/rs-dapi-client/src/dapi_client.rs index 126d820e1ca..1ff986b3896 100644 --- a/packages/rs-dapi-client/src/dapi_client.rs +++ b/packages/rs-dapi-client/src/dapi_client.rs @@ -3,6 +3,7 @@ use backon::{ConstantBuilder, Retryable}; use dapi_grpc::mock::Mockable; use dapi_grpc::tonic::async_trait; +#[cfg(not(feature = "wasm"))] use dapi_grpc::tonic::transport::Certificate; use std::fmt::{Debug, Display}; use std::sync::atomic::AtomicUsize; @@ -13,7 +14,7 @@ use tracing::Instrument; use crate::address_list::AddressListError; use crate::connection_pool::ConnectionPool; use crate::request_settings::AppliedRequestSettings; -use crate::transport::TransportError; +use crate::transport::{self, TransportError}; use crate::{ transport::{TransportClient, TransportRequest}, AddressList, CanRetry, DapiRequestExecutor, ExecutionError, ExecutionResponse, ExecutionResult, @@ -77,6 +78,7 @@ pub struct DapiClient { address_list: AddressList, settings: RequestSettings, pool: ConnectionPool, + #[cfg(not(feature = "wasm"))] /// Certificate Authority certificate to use for verifying the server's certificate. pub ca_certificate: Option, #[cfg(feature = "dump")] @@ -95,6 +97,7 @@ impl DapiClient { pool: ConnectionPool::new(address_count), #[cfg(feature = "dump")] dump_dir: None, + #[cfg(not(feature = "wasm"))] ca_certificate: None, } } @@ -107,6 +110,7 @@ impl DapiClient { /// /// # Returns /// [DapiClient] with CA certificate set. + #[cfg(not(feature = "wasm"))] pub fn with_ca_certificate(mut self, ca_cert: Certificate) -> Self { self.ca_certificate = Some(ca_cert); @@ -200,8 +204,9 @@ impl DapiRequestExecutor for DapiClient { .settings .override_by(R::SETTINGS_OVERRIDES) .override_by(settings) - .finalize() - .with_ca_certificate(self.ca_certificate.clone()); + .finalize(); + #[cfg(not(feature = "wasm"))] + let applied_settings = applied_settings.with_ca_certificate(self.ca_certificate.clone()); // Setup retry policy: let retry_settings = ConstantBuilder::default() @@ -310,10 +315,13 @@ impl DapiRequestExecutor for DapiClient { } }; + let sleeper = transport::channel_impl::BackonSleeper::default(); + // Start the routine with retry policy applied: // We allow let_and_return because `result` is used later if dump feature is enabled let result = routine .retry(retry_settings) + .sleep(sleeper) .notify(|error, duration| { let retries_counter = Arc::clone(&retries_counter_arc); retries_counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed); diff --git a/packages/rs-dapi-client/src/executor.rs b/packages/rs-dapi-client/src/executor.rs index 0afb8f57054..c87b2f9336b 100644 --- a/packages/rs-dapi-client/src/executor.rs +++ b/packages/rs-dapi-client/src/executor.rs @@ -34,7 +34,7 @@ pub trait InnerInto { } /// Error happened during request execution. -#[derive(Debug, Clone, thiserror::Error, Eq, PartialEq)] +#[derive(Debug, Clone, thiserror::Error, Eq)] #[error("{inner}")] pub struct ExecutionError { /// The cause of error @@ -45,6 +45,12 @@ pub struct ExecutionError { pub address: Option
, } +impl PartialEq for ExecutionError { + fn eq(&self, other: &Self) -> bool { + self.inner == other.inner && self.retries == other.retries && self.address == other.address + } +} + impl InnerInto> for ExecutionError where F: Into, diff --git a/packages/rs-dapi-client/src/lib.rs b/packages/rs-dapi-client/src/lib.rs index e820a714a0e..9603bb8e492 100644 --- a/packages/rs-dapi-client/src/lib.rs +++ b/packages/rs-dapi-client/src/lib.rs @@ -19,6 +19,8 @@ pub use address_list::AddressListError; pub use address_list::AddressStatus; pub use connection_pool::ConnectionPool; pub use dapi_client::{update_address_ban_status, DapiClient, DapiClientError}; +#[cfg(not(feature = "wasm"))] +pub use dapi_grpc::tonic::transport::http; #[cfg(feature = "dump")] pub use dump::DumpData; pub use executor::{ @@ -26,6 +28,11 @@ pub use executor::{ WrapToExecutionResult, }; use futures::{future::BoxFuture, FutureExt}; +#[cfg(feature = "wasm")] +pub use http::Uri; +#[cfg(not(feature = "wasm"))] +pub use http_serde::http::Uri; + pub use request_settings::RequestSettings; /// A DAPI request could be executed with an initialized [DapiClient]. diff --git a/packages/rs-dapi-client/src/request_settings.rs b/packages/rs-dapi-client/src/request_settings.rs index df89112322b..0767e15337a 100644 --- a/packages/rs-dapi-client/src/request_settings.rs +++ b/packages/rs-dapi-client/src/request_settings.rs @@ -1,5 +1,6 @@ //! DAPI client request settings processing. +#[cfg(not(feature = "wasm"))] use dapi_grpc::tonic::transport::Certificate; use std::time::Duration; @@ -65,6 +66,7 @@ impl RequestSettings { ban_failed_address: self .ban_failed_address .unwrap_or(DEFAULT_BAN_FAILED_ADDRESS), + #[cfg(not(feature = "wasm"))] ca_certificate: None, } } @@ -82,12 +84,14 @@ pub struct AppliedRequestSettings { /// Ban DAPI address if node not responded or responded with error. pub ban_failed_address: bool, /// Certificate Authority certificate to use for verifying the server's certificate. + #[cfg(not(feature = "wasm"))] pub ca_certificate: Option, } impl AppliedRequestSettings { /// Use provided CA certificate for verifying the server's certificate. /// /// If set to None, the system's default CA certificates will be used. + #[cfg(not(feature = "wasm"))] pub fn with_ca_certificate(mut self, ca_cert: Option) -> Self { self.ca_certificate = ca_cert; self diff --git a/packages/rs-dapi-client/src/transport.rs b/packages/rs-dapi-client/src/transport.rs index 26c394ff034..9a06459e4c6 100644 --- a/packages/rs-dapi-client/src/transport.rs +++ b/packages/rs-dapi-client/src/transport.rs @@ -1,16 +1,23 @@ //! Transport options that DAPI requests use under the hood. pub(crate) mod grpc; +#[cfg(not(feature = "wasm"))] +pub(crate) mod tonic_channel; +#[cfg(feature = "wasm")] +pub(crate) mod wasm_channel; use crate::connection_pool::ConnectionPool; pub use crate::request_settings::AppliedRequestSettings; -use crate::{CanRetry, RequestSettings}; +use crate::{CanRetry, RequestSettings, Uri}; +pub use channel_impl::{BackonSleeper, CoreGrpcClient, PlatformGrpcClient}; use dapi_grpc::mock::Mockable; -use dapi_grpc::tonic::transport::Uri; pub use futures::future::BoxFuture; -pub use grpc::{CoreGrpcClient, PlatformGrpcClient}; use std::any; use std::fmt::Debug; +#[cfg(not(feature = "wasm"))] +pub(crate) use tonic_channel as channel_impl; +#[cfg(feature = "wasm")] +pub(crate) use wasm_channel as channel_impl; /// Generic transport layer request. /// Requires [Clone] as could be retried and a client in general consumes a request. diff --git a/packages/rs-dapi-client/src/transport/grpc.rs b/packages/rs-dapi-client/src/transport/grpc.rs index 77b98acf812..c4ffc4f7cbe 100644 --- a/packages/rs-dapi-client/src/transport/grpc.rs +++ b/packages/rs-dapi-client/src/transport/grpc.rs @@ -2,52 +2,19 @@ use std::time::Duration; +#[cfg(not(feature = "wasm"))] +use super::tonic_channel::create_channel; +#[cfg(feature = "wasm")] +use super::wasm_channel::create_channel; use super::{CanRetry, TransportClient, TransportError, TransportRequest}; +use super::{CoreGrpcClient, PlatformGrpcClient}; use crate::connection_pool::{ConnectionPool, PoolPrefix}; -use crate::{request_settings::AppliedRequestSettings, RequestSettings}; -use dapi_grpc::core::v0::core_client::CoreClient; +use crate::{request_settings::AppliedRequestSettings, RequestSettings, Uri}; use dapi_grpc::core::v0::{self as core_proto}; -use dapi_grpc::platform::v0::{self as platform_proto, platform_client::PlatformClient}; -use dapi_grpc::tonic::transport::{Certificate, ClientTlsConfig, Uri}; -use dapi_grpc::tonic::Streaming; -use dapi_grpc::tonic::{transport::Channel, IntoRequest}; +use dapi_grpc::platform::v0::{self as platform_proto}; +use dapi_grpc::tonic::{IntoRequest, Streaming}; use futures::{future::BoxFuture, FutureExt, TryFutureExt}; -/// Platform Client using gRPC transport. -pub type PlatformGrpcClient = PlatformClient; -/// Core Client using gRPC transport. -pub type CoreGrpcClient = CoreClient; - -fn create_channel( - uri: Uri, - settings: Option<&AppliedRequestSettings>, -) -> Result { - let host = uri.host().expect("Failed to get host from URI").to_string(); - - let mut builder = Channel::builder(uri); - let mut tls_config = ClientTlsConfig::new() - .with_native_roots() - .with_webpki_roots() - .assume_http2(true); - - if let Some(settings) = settings { - if let Some(timeout) = settings.connect_timeout { - builder = builder.connect_timeout(timeout); - } - - if let Some(pem) = settings.ca_certificate.as_ref() { - let cert = Certificate::from_pem(pem); - tls_config = tls_config.ca_certificate(cert).domain_name(host); - }; - } - - builder = builder - .tls_config(tls_config) - .expect("Failed to set TLS config"); - - Ok(builder.connect_lazy()) -} - impl TransportClient for PlatformGrpcClient { fn with_uri(uri: Uri, pool: &ConnectionPool) -> Result { Ok(pool diff --git a/packages/rs-dapi-client/src/transport/tonic_channel.rs b/packages/rs-dapi-client/src/transport/tonic_channel.rs new file mode 100644 index 00000000000..f1e9de97038 --- /dev/null +++ b/packages/rs-dapi-client/src/transport/tonic_channel.rs @@ -0,0 +1,57 @@ +use std::time::Duration; + +use super::{CanRetry, TransportClient, TransportError, TransportRequest}; +use crate::connection_pool::{ConnectionPool, PoolPrefix}; +use crate::{request_settings::AppliedRequestSettings, RequestSettings, Uri}; +use dapi_grpc::core::v0::core_client::CoreClient; +use dapi_grpc::core::v0::{self as core_proto}; +use dapi_grpc::platform::v0::{self as platform_proto, platform_client::PlatformClient}; +use dapi_grpc::tonic::transport::{Certificate, Channel, ClientTlsConfig, Uri}; +use dapi_grpc::tonic::{IntoRequest, Streaming}; +use futures::{future::BoxFuture, FutureExt, TryFutureExt}; + +/// Platform Client using gRPC transport. +pub type PlatformGrpcClient = PlatformClient; +/// Core Client using gRPC transport. +pub type CoreGrpcClient = CoreClient; + +/// backon::Sleeper +#[derive(Default, Clone, Debug)] +pub(crate) struct Sleeper(backon::TokioSleeper); + +impl backon::Sleeper for Sleeper { + type Sleep = backon::TokioSleeper::Sleep; + fn sleep(&self, dur: Duration) -> Self::Sleep { + self.0.sleep(dur) + } +} + +fn create_channel( + uri: Uri, + settings: Option<&AppliedRequestSettings>, +) -> Result { + let host = uri.host().expect("Failed to get host from URI").to_string(); + + let mut builder = Channel::builder(uri); + let mut tls_config = ClientTlsConfig::new() + .with_native_roots() + .with_webpki_roots() + .assume_http2(true); + + if let Some(settings) = settings { + if let Some(timeout) = settings.connect_timeout { + builder = builder.connect_timeout(timeout); + } + + if let Some(pem) = settings.ca_certificate.as_ref() { + let cert = Certificate::from_pem(pem); + tls_config = tls_config.ca_certificate(cert).domain_name(host); + }; + } + + builder = builder + .tls_config(tls_config) + .expect("Failed to set TLS config"); + + Ok(builder.connect_lazy()) +} diff --git a/packages/rs-dapi-client/src/transport/wasm_channel.rs b/packages/rs-dapi-client/src/transport/wasm_channel.rs new file mode 100644 index 00000000000..9315558ff48 --- /dev/null +++ b/packages/rs-dapi-client/src/transport/wasm_channel.rs @@ -0,0 +1,67 @@ +//! Listing of gRPC requests used in DAPI. + +use std::thread::sleep; +use std::time::Duration; + +use super::TransportError; +use crate::{request_settings::AppliedRequestSettings, Uri}; +use dapi_grpc::core::v0::core_client::CoreClient; + +use dapi_grpc::platform::v0::platform_client::PlatformClient; +use dapi_grpc::tonic::{self as tonic}; +use futures::FutureExt; +// use tonic_web_wasm_client::Client as WasmClient; + +#[derive(Clone, Debug)] +// TODO impleent WasmClient using `tonic_web_wasm_client::Client` +pub struct WasmClient; + +impl tonic::client::GrpcService for WasmClient { + type ResponseBody = tonic::body::BoxBody; + fn call(&mut self, request: http::Request) -> Self::Future { + unimplemented!() + } + fn poll_ready( + &mut self, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + unimplemented!() + } + type Error = tonic::Status; + type Future = std::pin::Pin< + Box< + dyn std::future::Future< + Output = Result, Self::Error>, + > + Send, + >, + >; +} + +/// Platform Client using gRPC transport. +pub type PlatformGrpcClient = PlatformClient; +/// Core Client using gRPC transport. +pub type CoreGrpcClient = CoreClient; + +type S = futures::future::BoxFuture<'static, ()>; +/// backon::Sleeper +#[derive(Default, Clone, Debug)] +pub struct BackonSleeper {} +// TODO move somewhere else +impl backon::Sleeper for BackonSleeper { + type Sleep = S; + fn sleep(&self, dur: Duration) -> Self::Sleep { + // TODO: blocking sleep is not the best solution + sleep(dur); + async {}.boxed() + } +} + +pub(super) fn create_channel( + uri: Uri, + settings: Option<&AppliedRequestSettings>, +) -> Result { + // let host = uri.host().expect("Failed to get host from URI").to_string(); + // let client = tonic_web_wasm_client::Client::new(uri.to_string()); + + Ok(WasmClient {}) +} diff --git a/packages/rs-dpp/src/balances/credits.rs b/packages/rs-dpp/src/balances/credits.rs index d0f9e2805b9..8db94c32386 100644 --- a/packages/rs-dpp/src/balances/credits.rs +++ b/packages/rs-dpp/src/balances/credits.rs @@ -16,22 +16,18 @@ use std::convert::TryFrom; pub type Duffs = u64; /// Credits type - pub type Credits = u64; /// Signed Credits type is used for internal computations and total credits /// balance verification - pub type SignedCredits = i64; /// Maximum value of credits - pub const MAX_CREDITS: Credits = 9223372036854775807 as Credits; //i64 Max pub const CREDITS_PER_DUFF: Credits = 1000; /// Trait for signed and unsigned credits - pub trait Creditable { /// Convert unsigned credit to singed fn to_signed(&self) -> Result; diff --git a/packages/rs-drive-abci/Cargo.toml b/packages/rs-drive-abci/Cargo.toml index d637b3225d0..b722827034a 100644 --- a/packages/rs-drive-abci/Cargo.toml +++ b/packages/rs-drive-abci/Cargo.toml @@ -39,7 +39,10 @@ tracing = { version = "0.1.37", default-features = false, features = [] } clap = { version = "4.4.10", features = ["derive"] } envy = { version = "0.4.2" } dotenvy = { version = "0.15.7" } -dapi-grpc = { path = "../dapi-grpc", features = ["server"] } +dapi-grpc = { path = "../dapi-grpc", default-features = false, features = [ + "server", + "platform", +] } tracing-subscriber = { version = "0.3.16", default-features = false, features = [ "env-filter", "ansi", diff --git a/packages/rs-drive-proof-verifier/Cargo.toml b/packages/rs-drive-proof-verifier/Cargo.toml index e19a9ced1b5..632f87a8170 100644 --- a/packages/rs-drive-proof-verifier/Cargo.toml +++ b/packages/rs-drive-proof-verifier/Cargo.toml @@ -21,7 +21,10 @@ mocks = [ [dependencies] thiserror = { version = "1.0.63" } -dapi-grpc = { path = "../dapi-grpc" } +dapi-grpc = { path = "../dapi-grpc", default-features = false, features = [ + "platform", +] } + drive = { path = "../rs-drive", default-features = false, features = [ "verify", ] } diff --git a/packages/rs-sdk/Cargo.toml b/packages/rs-sdk/Cargo.toml index 1d781bfa9fa..a252e0d1ac2 100644 --- a/packages/rs-sdk/Cargo.toml +++ b/packages/rs-sdk/Cargo.toml @@ -11,17 +11,19 @@ chrono = { version = "0.4.38" } dpp = { path = "../rs-dpp", default-features = false, features = [ "dash-sdk-features", ] } -dapi-grpc = { path = "../dapi-grpc" } + +dapi-grpc = { path = "../dapi-grpc", default-features = false } rs-dapi-client = { path = "../rs-dapi-client", default-features = false } drive = { path = "../rs-drive", default-features = false, features = [ "verify", ] } + drive-proof-verifier = { path = "../rs-drive-proof-verifier" } dapi-grpc-macros = { path = "../rs-dapi-grpc-macros" } http = { version = "1.1" } rustls-pemfile = { version = "2.0.0" } thiserror = "1.0.64" -tokio = { version = "1.40", features = ["macros", "rt-multi-thread"] } +tokio = { version = "1.40", features = ["macros", "time"] } tokio-util = { version = "0.7.12" } async-trait = { version = "0.1.83" } ciborium = { git = "https://github.com/qrayven/ciborium", branch = "feat-ser-null-as-undefined" } @@ -42,8 +44,8 @@ bip37-bloom-filter = { git = "https://github.com/dashpay/rs-bip37-bloom-filter", zeroize = { version = "1.8", features = ["derive"] } [dev-dependencies] +rs-dapi-client = { path = "../rs-dapi-client" } tokio = { version = "1.40", features = ["macros", "rt-multi-thread"] } -rs-dapi-client = { path = "../rs-dapi-client", features = ["mocks"] } base64 = { version = "0.22.1" } tracing-subscriber = { version = "0.3.18", features = ["env-filter"] } dpp = { path = "../rs-dpp", features = [ @@ -54,11 +56,19 @@ dpp = { path = "../rs-dpp", features = [ data-contracts = { path = "../data-contracts" } tokio-test = { version = "0.4.4" } clap = { version = "4.5.4", features = ["derive"] } -sanitize-filename = { version = "0.5.0" } +sanitize-filename = { version = "0.6.0" } test-case = { version = "3.3.1" } [features] -default = ["mocks", "offline-testing"] +# TODO make a way to enable "tokio/rt-multi-thread" if someone uses --no-default-features +default = [ + "mocks", + "offline-testing", + "dapi-grpc/client", + "tokio/rt-multi-thread", +] + +wasm = ["dapi-grpc/wasm", "rs-dapi-client/wasm"] mocks = [ "dep:serde", @@ -106,3 +116,6 @@ system-data-contracts = ["dpp/data-contracts"] name = "read_contract" required-features = ["mocks"] + +[lib] +crate-type = ["cdylib", "rlib"] diff --git a/packages/rs-sdk/src/platform/transition/broadcast_identity.rs b/packages/rs-sdk/src/platform/transition/broadcast_identity.rs index 5bce4205cfe..f92bd77def4 100644 --- a/packages/rs-sdk/src/platform/transition/broadcast_identity.rs +++ b/packages/rs-sdk/src/platform/transition/broadcast_identity.rs @@ -10,6 +10,7 @@ use std::fmt::Debug; use dapi_grpc::platform::v0::{self as proto, BroadcastStateTransitionRequest}; use dpp::dashcore::PrivateKey; use dpp::identity::signer::Signer; +#[cfg(not(feature = "wasm"))] use dpp::native_bls::NativeBlsModule; use dpp::prelude::{AssetLockProof, Identity}; use dpp::state_transition::identity_create_transition::methods::IdentityCreateTransitionMethodsV0; @@ -104,16 +105,22 @@ impl BroadcastRequestForNewIdentity Result<(StateTransition, BroadcastStateTransitionRequest), Error> { - let identity_create_transition = IdentityCreateTransition::try_from_identity_with_signer( - self, - asset_lock_proof, - asset_lock_proof_private_key.inner.as_ref(), - signer, - &NativeBlsModule, - 0, - platform_version, - )?; - let request = identity_create_transition.broadcast_request_for_state_transition()?; - Ok((identity_create_transition, request)) + #[cfg(feature = "wasm")] + unimplemented!("NativeBlsModule not implemented for wasm32"); + #[cfg(not(feature = "wasm"))] + { + let identity_create_transition = + IdentityCreateTransition::try_from_identity_with_signer( + self, + asset_lock_proof, + asset_lock_proof_private_key.inner.as_ref(), + signer, + &NativeBlsModule, + 0, + platform_version, + )?; + let request = identity_create_transition.broadcast_request_for_state_transition()?; + Ok((identity_create_transition, request)) + } } } diff --git a/packages/rs-sdk/src/sdk.rs b/packages/rs-sdk/src/sdk.rs index 64a5db66457..6cc6d1deef5 100644 --- a/packages/rs-sdk/src/sdk.rs +++ b/packages/rs-sdk/src/sdk.rs @@ -10,6 +10,7 @@ use crate::platform::{Fetch, Identifier}; use arc_swap::{ArcSwapAny, ArcSwapOption}; use dapi_grpc::mock::Mockable; use dapi_grpc::platform::v0::{Proof, ResponseMetadata}; +#[cfg(not(feature = "wasm"))] use dapi_grpc::tonic::transport::Certificate; use dpp::bincode; use dpp::bincode::error::DecodeError; @@ -753,6 +754,7 @@ pub struct SdkBuilder { pub(crate) cancel_token: CancellationToken, /// CA certificate to use for TLS connections. + #[cfg(not(feature = "wasm"))] ca_certificate: Option, } @@ -784,7 +786,7 @@ impl Default for SdkBuilder { cancel_token: CancellationToken::new(), version: PlatformVersion::latest(), - + #[cfg(not(feature = "wasm"))] ca_certificate: None, #[cfg(feature = "mocks")] @@ -841,6 +843,7 @@ impl SdkBuilder { /// Used mainly for testing purposes and local networks. /// /// If not set, uses standard system CA certificates. + #[cfg(not(feature = "wasm"))] pub fn with_ca_certificate(mut self, pem_certificate: Certificate) -> Self { self.ca_certificate = Some(pem_certificate); self @@ -850,6 +853,7 @@ impl SdkBuilder { /// /// This is a convenience method that reads the certificate from a file and sets it using /// [SdkBuilder::with_ca_certificate()]. + #[cfg(not(feature = "wasm"))] pub fn with_ca_certificate_file( self, certificate_file_path: impl AsRef, @@ -1003,7 +1007,9 @@ impl SdkBuilder { let sdk= match self.addresses { // non-mock mode Some(addresses) => { + #[allow(unused_mut)] // needs to be mutable for features other than wasm let mut dapi = DapiClient::new(addresses, dapi_client_settings); + #[cfg(not(feature = "wasm"))] if let Some(pem) = self.ca_certificate { dapi = dapi.with_ca_certificate(pem); } diff --git a/packages/rs-sdk/src/sync.rs b/packages/rs-sdk/src/sync.rs index 5f5d2666699..d0bf327501e 100644 --- a/packages/rs-sdk/src/sync.rs +++ b/packages/rs-sdk/src/sync.rs @@ -15,13 +15,14 @@ use std::{ future::Future, sync::{mpsc::SendError, Arc}, }; -use tokio::{runtime::TryCurrentError, sync::Mutex}; +use tokio::sync::Mutex; #[derive(Debug, thiserror::Error)] pub enum AsyncError { /// Not running inside tokio runtime + #[cfg(not(feature = "wasm"))] #[error("not running inside tokio runtime: {0}")] - NotInTokioRuntime(#[from] TryCurrentError), + NotInTokioRuntime(#[from] tokio::runtime::TryCurrentError), /// Cannot receive response from async function #[error("cannot receive response from async function: {0}")] @@ -61,6 +62,7 @@ impl From for crate::Error { /// /// Due to limitations of tokio runtime, we cannot use `tokio::runtime::Runtime::block_on` if we are already inside a tokio runtime. /// This function is a workaround for that limitation. +#[cfg(not(feature = "wasm"))] pub fn block_on(fut: F) -> Result where F: Future + Send + 'static, @@ -83,6 +85,15 @@ where Ok(resp) } +#[cfg(feature = "wasm")] +pub fn block_on(_fut: F) -> Result +where + F: Future + Send + 'static, + F::Output: Send, +{ + unimplemented!("block_on is not supported in wasm"); +} + /// Worker function that runs the provided future and sends the result back to the caller using oneshot channel. async fn worker( fut: F, @@ -229,6 +240,7 @@ where false } }) + .sleep(rs_dapi_client::transport::BackonSleeper::default()) .notify(|error, duration| { tracing::warn!(?duration, ?error, "request failed, retrying"); }) @@ -244,7 +256,6 @@ where mod test { use super::*; use derive_more::Display; - use http::Uri; use rs_dapi_client::ExecutionError; use std::{ future::Future, diff --git a/packages/wasm-sdk/Cargo.toml b/packages/wasm-sdk/Cargo.toml new file mode 100644 index 00000000000..f93a19c161a --- /dev/null +++ b/packages/wasm-sdk/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "wasm-sdk" +version = "0.1.0" +edition = "2021" +rust-version.workspace = true +publish = false +[lib] +crate-type = ["cdylib"] + +[dependencies] +web-sys = { version = "0.3.4", features = [ + 'Document', + 'Element', + 'HtmlElement', + 'Node', + 'Window', +] } +wasm-bindgen = { version = "=0.2.99" } +# tenderdash-proto = { path = "../../../rs-tenderdash-abci/proto", default-features = false, features = [ +# "client", +# ] } +dash-sdk = { path = "../rs-sdk", default-features = false, features = ["wasm"] } +# tonic = { version = "*", features = ["transport"], default-features = false } +# client = [ +# "tonic/channel", FAIL +# "tonic/transport", FAIL +# "tonic/tls", +# "tonic/tls-roots", +# "tonic/tls-webpki-roots", +# "platform", +# ] diff --git a/packages/wasm-sdk/index.html b/packages/wasm-sdk/index.html new file mode 100644 index 00000000000..f8f2197595d --- /dev/null +++ b/packages/wasm-sdk/index.html @@ -0,0 +1,59 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/packages/wasm-sdk/src/lib.rs b/packages/wasm-sdk/src/lib.rs new file mode 100644 index 00000000000..f2e774f8ddc --- /dev/null +++ b/packages/wasm-sdk/src/lib.rs @@ -0,0 +1,11 @@ +use wasm_bindgen::prelude::*; + +#[wasm_bindgen] +extern "C" { + fn alert(s: &str); +} + +#[wasm_bindgen] +pub fn greet(name: &str) { + alert(&format!("Hello, {}!", name)); +} From cc1b0691e1f51c4f3f054df1f2685be0f7d01322 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 20 Dec 2024 13:33:54 +0100 Subject: [PATCH 06/26] chore: some tests --- Cargo.lock | 1 + packages/wasm-sdk/Cargo.toml | 2 + packages/wasm-sdk/src/lib.rs | 150 ++++++++++++++++++++++++++++++++++- 3 files changed, 151 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d518d867684..d172b0aa8f0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5990,6 +5990,7 @@ version = "0.1.0" dependencies = [ "dash-sdk", "wasm-bindgen", + "wasm-bindgen-futures", "web-sys", ] diff --git a/packages/wasm-sdk/Cargo.toml b/packages/wasm-sdk/Cargo.toml index f93a19c161a..846027d5a71 100644 --- a/packages/wasm-sdk/Cargo.toml +++ b/packages/wasm-sdk/Cargo.toml @@ -14,8 +14,10 @@ web-sys = { version = "0.3.4", features = [ 'HtmlElement', 'Node', 'Window', + 'console', ] } wasm-bindgen = { version = "=0.2.99" } +wasm-bindgen-futures = { version = "0.4.49" } # tenderdash-proto = { path = "../../../rs-tenderdash-abci/proto", default-features = false, features = [ # "client", # ] } diff --git a/packages/wasm-sdk/src/lib.rs b/packages/wasm-sdk/src/lib.rs index f2e774f8ddc..c0532259693 100644 --- a/packages/wasm-sdk/src/lib.rs +++ b/packages/wasm-sdk/src/lib.rs @@ -1,4 +1,55 @@ +use std::{ + ops::{Deref, DerefMut}, + str::FromStr, +}; + +use dash_sdk::{ + dpp::{ + block::extended_epoch_info::ExtendedEpochInfo, + dashcore::{ + key::Secp256k1, + secp256k1::{self, SecretKey}, + Network, PrivateKey, + }, + data_contract::accessors::v0::DataContractV0Getters, + document::serialization_traits::DocumentPlatformConversionMethodsV0, + identity::signer::Signer, + prelude::AssetLockProof, + serialization::{PlatformSerializable, PlatformSerializableWithPlatformVersion}, + }, + platform::{ + transition::{broadcast::BroadcastStateTransition, put_identity::PutIdentity}, + DataContract, Document, DocumentQuery, Fetch, Identifier, Identity, + }, + sdk::AddressList, + Sdk, SdkBuilder, +}; use wasm_bindgen::prelude::*; +use web_sys::{console, js_sys}; + +#[wasm_bindgen] +pub struct WasmSdk(Sdk); +// Dereference JsSdk to Sdk so that we can use &JsSdk everywhere where &sdk is needed +impl std::ops::Deref for WasmSdk { + type Target = Sdk; + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[wasm_bindgen] +pub struct WasmSdkBuilder(SdkBuilder); +impl Deref for WasmSdkBuilder { + type Target = SdkBuilder; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for WasmSdkBuilder { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} #[wasm_bindgen] extern "C" { @@ -6,6 +57,101 @@ extern "C" { } #[wasm_bindgen] -pub fn greet(name: &str) { - alert(&format!("Hello, {}!", name)); +pub async fn identity_testing() { + let sdk = SdkBuilder::new(AddressList::new()) + .build() + .expect("build sdk"); + + let id = Identifier::random(); + let identity = Identity::fetch_by_identifier(&sdk, id.clone()) + .await + .expect("fetch identity") + .expect("identity not found"); + + let identity_serialized = + PlatformSerializable::serialize_to_bytes(&identity).expect("serialize"); + + let asset_lock_proof = AssetLockProof::default(); + let asset_lock_proof_private_key = + PrivateKey::from_slice(&[0; 32], Network::Testnet).expect("create private key"); + + let signer = MockSigner; + let pushed: Identity = identity + .put_to_platform( + &sdk, + asset_lock_proof, + &asset_lock_proof_private_key, + &signer, + None, + ) + .await + .expect("put identity") + .broadcast_and_wait(&sdk, None) + .await + .unwrap(); +} + +#[wasm_bindgen] +pub async fn epoch_testing() { + let sdk = SdkBuilder::new(AddressList::new()) + .build() + .expect("build sdk"); + + let ei = ExtendedEpochInfo::fetch(&sdk, 0) + .await + .expect("fetch extended epoch info") + .expect("extended epoch info not found"); +} + +#[wasm_bindgen] +pub async fn setup_sdk() -> WasmSdk { + let sdk = SdkBuilder::new(AddressList::new()) + .build() + .expect("build sdk"); + WasmSdk(sdk) +} + +#[wasm_bindgen] +pub async fn docs_testing(sdk: &WasmSdk) { + let id = Identifier::random(); + + let dc = DataContract::fetch(&sdk, id) + .await + .expect("fetch data contract") + .expect("data contract not found"); + + let dcs = dc + .serialize_to_bytes_with_platform_version(sdk.version()) + .expect("serialize data contract"); + + let query = DocumentQuery::new(dc.clone(), "asd").expect("create query"); + let doc = Document::fetch(sdk, query) + .await + .expect("fetch document") + .expect("document not found"); + + let document_type = dc + .document_type_for_name("aaa") + .expect("document type for name"); + let doc_serialized = doc + .serialize(document_type, sdk.version()) + .expect("serialize document"); + + let msg = js_sys::JsString::from_str(&format!("{:?} {:?} ", dcs, doc_serialized)) + .expect("create js string"); + console::log_1(&msg); +} +#[derive(Clone, Debug)] +struct MockSigner; +impl Signer for MockSigner { + fn can_sign_with(&self, identity_public_key: &dash_sdk::platform::IdentityPublicKey) -> bool { + true + } + fn sign( + &self, + identity_public_key: &dash_sdk::platform::IdentityPublicKey, + data: &[u8], + ) -> Result { + todo!() + } } From 7243de546f501b09aae438ded0e57cde85617efd Mon Sep 17 00:00:00 2001 From: Ivan Shumkov Date: Thu, 2 Jan 2025 16:31:53 +0700 Subject: [PATCH 07/26] chore: experiments --- Cargo.lock | 87 ++++--- packages/rs-dpp/Cargo.toml | 54 ++-- packages/rs-dpp/src/bls/mod.rs | 2 +- .../class_methods/try_from_schema/v0/mod.rs | 2 + .../data_contract/document_type/index/mod.rs | 58 ++++- packages/rs-dpp/src/data_contract/mod.rs | 5 + packages/rs-dpp/src/lib.rs | 1 - .../stateTransition/dataContractCreate.json | 42 ---- .../stateTransition/dataContractUpdate.json | 35 --- .../src/schema/document/v0/documentBase.json | 83 ------ .../documentTransition/base.json | 34 --- .../documentTransition/create.json | 24 -- .../documentTransition/replace.json | 18 -- .../v0/stateTransition/documentsBatch.json | 48 ---- packages/rs-dpp/src/schema/identity/mod.rs | 1 - .../src/schema/identity/v0/identity.json | 40 --- .../rs-dpp/src/schema/identity/v0/identity.rs | 46 ---- packages/rs-dpp/src/schema/identity/v0/mod.rs | 3 - .../src/schema/identity/v0/publicKey.json | 150 ----------- .../assetLockProof/chainAssetLockProof.json | 27 -- .../assetLockProof/instantAssetLockProof.json | 33 --- .../v0/stateTransition/identityCreate.json | 38 --- .../identityCreditTransfer.json | 53 ---- .../identityCreditWithdrawal.json | 75 ------ .../v0/stateTransition/identityTopUp.json | 39 --- .../v0/stateTransition/identityUpdate.json | 81 ------ .../v0/stateTransition/publicKey.json | 146 ----------- packages/rs-dpp/src/schema/mod.rs | 23 -- .../v0/from_document.rs | 10 +- packages/rs-dpp/src/util/deserializer.rs | 14 -- packages/rs-dpp/src/util/json_schema.rs | 1 + packages/rs-drive-proof-verifier/Cargo.toml | 14 +- packages/rs-drive-proof-verifier/src/types.rs | 4 +- packages/rs-drive/Cargo.toml | 2 +- packages/rs-platform-value/Cargo.toml | 2 - .../src/inner_value_at_path.rs | 125 ++++++++-- packages/rs-sdk/Cargo.toml | 3 +- packages/rs-sdk/src/sdk.rs | 4 + packages/wasm-sdk/Cargo.toml | 17 +- packages/wasm-sdk/src/lib.rs | 164 +----------- packages/wasm-sdk/src/sdk.rs | 145 +++++++++++ .../src/state_transitions/documents.rs | 76 ++++++ .../wasm-sdk/src/state_transitions/mod.rs | 1 + packages/wasm-sdk/src/verify.rs | 236 ++++++++++++++++++ 44 files changed, 743 insertions(+), 1323 deletions(-) delete mode 100644 packages/rs-dpp/src/schema/data_contract/v0/stateTransition/dataContractCreate.json delete mode 100644 packages/rs-dpp/src/schema/data_contract/v0/stateTransition/dataContractUpdate.json delete mode 100644 packages/rs-dpp/src/schema/document/v0/documentBase.json delete mode 100644 packages/rs-dpp/src/schema/document/v0/stateTransition/documentTransition/base.json delete mode 100644 packages/rs-dpp/src/schema/document/v0/stateTransition/documentTransition/create.json delete mode 100644 packages/rs-dpp/src/schema/document/v0/stateTransition/documentTransition/replace.json delete mode 100644 packages/rs-dpp/src/schema/document/v0/stateTransition/documentsBatch.json delete mode 100644 packages/rs-dpp/src/schema/identity/mod.rs delete mode 100644 packages/rs-dpp/src/schema/identity/v0/identity.json delete mode 100644 packages/rs-dpp/src/schema/identity/v0/identity.rs delete mode 100644 packages/rs-dpp/src/schema/identity/v0/mod.rs delete mode 100644 packages/rs-dpp/src/schema/identity/v0/publicKey.json delete mode 100644 packages/rs-dpp/src/schema/identity/v0/stateTransition/assetLockProof/chainAssetLockProof.json delete mode 100644 packages/rs-dpp/src/schema/identity/v0/stateTransition/assetLockProof/instantAssetLockProof.json delete mode 100644 packages/rs-dpp/src/schema/identity/v0/stateTransition/identityCreate.json delete mode 100644 packages/rs-dpp/src/schema/identity/v0/stateTransition/identityCreditTransfer.json delete mode 100644 packages/rs-dpp/src/schema/identity/v0/stateTransition/identityCreditWithdrawal.json delete mode 100644 packages/rs-dpp/src/schema/identity/v0/stateTransition/identityTopUp.json delete mode 100644 packages/rs-dpp/src/schema/identity/v0/stateTransition/identityUpdate.json delete mode 100644 packages/rs-dpp/src/schema/identity/v0/stateTransition/publicKey.json delete mode 100644 packages/rs-dpp/src/schema/mod.rs create mode 100644 packages/wasm-sdk/src/sdk.rs create mode 100644 packages/wasm-sdk/src/state_transitions/documents.rs create mode 100644 packages/wasm-sdk/src/state_transitions/mod.rs create mode 100644 packages/wasm-sdk/src/verify.rs diff --git a/Cargo.lock b/Cargo.lock index d172b0aa8f0..56174e5ad90 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -29,7 +29,7 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "cipher", "cpufeatures", ] @@ -51,7 +51,7 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "getrandom", "once_cell", "serde", @@ -241,7 +241,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43a2b323ccce0a1d90b449fd71f2a06ca7faa7c54c2751f06c9bd851fc061059" dependencies = [ "async-lock", - "cfg-if", + "cfg-if 1.0.0", "concurrent-queue", "futures-io", "futures-lite", @@ -428,7 +428,7 @@ checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a" dependencies = [ "addr2line", "cc", - "cfg-if", + "cfg-if 1.0.0", "libc", "miniz_oxide 0.7.4", "object", @@ -607,7 +607,7 @@ dependencies = [ "arrayref", "arrayvec", "cc", - "cfg-if", + "cfg-if 1.0.0", "constant_time_eq 0.3.1", ] @@ -840,6 +840,12 @@ dependencies = [ "nom", ] +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" + [[package]] name = "cfg-if" version = "1.0.0" @@ -1114,7 +1120,7 @@ version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", ] [[package]] @@ -1222,7 +1228,7 @@ version = "4.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "cpufeatures", "curve25519-dalek-derive", "digest", @@ -1580,7 +1586,7 @@ dependencies = [ "data-contracts", "derive_more 1.0.0", "dpp", - "env_logger 0.11.5", + "env_logger 0.11.6", "getrandom", "hex", "indexmap 2.7.0", @@ -1589,7 +1595,6 @@ dependencies = [ "json-schema-compatibility-validator", "jsonschema", "lazy_static", - "log", "nohash-hasher", "num_enum 0.7.3", "once_cell", @@ -1822,7 +1827,7 @@ version = "0.8.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b45de904aa0b010bce2ab45264d0631681847fa7b6f2eaa7dab7619943bc4f59" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", ] [[package]] @@ -1847,9 +1852,9 @@ dependencies = [ [[package]] name = "env_filter" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f2c92ceda6ceec50f43169f9ee8424fe2db276791afde7b2cd8bc084cb376ab" +checksum = "186e05a59d4c50738528153b83b0b0194d3a29507dfec16eccd4b342903397d0" dependencies = [ "log", "regex", @@ -1870,9 +1875,9 @@ dependencies = [ [[package]] name = "env_logger" -version = "0.11.5" +version = "0.11.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13fa619b91fb2381732789fc5de83b45675e882f66623b7d8cb4f643017018d" +checksum = "dcaee3d8e3cfc3fd92428d477bc97fc29ec8716d180c0d74c643bb26166660e0" dependencies = [ "anstream", "anstyle", @@ -2227,7 +2232,7 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "js-sys", "libc", "wasi", @@ -2443,7 +2448,7 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dd08c532ae367adf81c312a4580bc67f1d0fe8bc9c460520283f4c0ff277888" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "crunchy", ] @@ -3023,7 +3028,7 @@ version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "windows-targets 0.52.6", ] @@ -3141,6 +3146,12 @@ version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" +[[package]] +name = "memory_units" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8452105ba047068f40ff7093dd1d9da90898e63dd61736462e9cdda6a90ad3c3" + [[package]] name = "merlin" version = "3.0.0" @@ -3255,7 +3266,7 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4c28b3fb6d753d28c20e826cd46ee611fda1cf3cde03a443a974043247c065a" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "downcast", "fragile", "mockall_derive", @@ -3269,7 +3280,7 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "341014e7f530314e9a1fdbc7400b244efea7122662c96bfa248c31da5bfb2020" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "proc-macro2", "quote", "syn 2.0.75", @@ -3548,7 +3559,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9529f4786b70a3e8c61e11179af17ab6188ad8d0ded78c5529441ed39d4bd9c1" dependencies = [ "bitflags 2.6.0", - "cfg-if", + "cfg-if 1.0.0", "foreign-types", "libc", "once_cell", @@ -3622,7 +3633,7 @@ version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "libc", "redox_syscall", "smallvec", @@ -3767,11 +3778,9 @@ dependencies = [ "ciborium 0.2.0", "hex", "indexmap 2.7.0", - "lazy_static", "platform-serialization", "platform-version", "rand", - "regex", "serde", "serde_json", "thiserror", @@ -3840,7 +3849,7 @@ version = "3.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a604568c3202727d1507653cb121dbd627a58684eb09a820fd746bee38b4442f" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "concurrent-queue", "hermit-abi 0.4.0", "pin-project-lite", @@ -4260,7 +4269,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" dependencies = [ "cc", - "cfg-if", + "cfg-if 1.0.0", "getrandom", "libc", "spin", @@ -4738,7 +4747,7 @@ version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "cpufeatures", "digest", ] @@ -4749,7 +4758,7 @@ version = "0.10.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "cpufeatures", "digest", ] @@ -5056,7 +5065,7 @@ version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04cbcdd0c794ebb0d4cf35e88edd2f7d2c4c3e9a5a6dab322839b321c6a87a64" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "fastrand", "once_cell", "rustix", @@ -5180,7 +5189,7 @@ version = "3.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adcb7fd841cd518e279be3d5a3eb0636409487998a4aff22f3de87b81e88384f" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "proc-macro2", "quote", "syn 2.0.75", @@ -5244,7 +5253,7 @@ version = "1.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "once_cell", ] @@ -5888,7 +5897,7 @@ version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a474f6281d1d70c17ae7aa6a613c87fce69a127e2624002df63dcb39d6cf6396" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "once_cell", "wasm-bindgen-macro", ] @@ -5913,7 +5922,7 @@ version = "0.4.49" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38176d9b44ea84e9184eff0bc34cc167ed044f816accfe5922e54d84cf48eca2" dependencies = [ - "cfg-if", + "cfg-if 1.0.0", "js-sys", "once_cell", "wasm-bindgen", @@ -5989,9 +5998,11 @@ name = "wasm-sdk" version = "0.1.0" dependencies = [ "dash-sdk", + "drive-proof-verifier", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "wee_alloc", ] [[package]] @@ -6026,6 +6037,18 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "wee_alloc" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbb3b5a6b2bb17cb6ad44a2e68a43e8d2722c997da10e928665c72ec6c0a0b8e" +dependencies = [ + "cfg-if 0.1.10", + "libc", + "memory_units", + "winapi", +] + [[package]] name = "which" version = "4.4.2" diff --git a/packages/rs-dpp/Cargo.toml b/packages/rs-dpp/Cargo.toml index f526a76c8a1..edd5f398aac 100644 --- a/packages/rs-dpp/Cargo.toml +++ b/packages/rs-dpp/Cargo.toml @@ -20,7 +20,7 @@ byteorder = { version = "1.4" } chrono = { version = "0.4.35", default-features = false, features = [ "wasmbind", "clock", -] } +]} ciborium = { git = "https://github.com/qrayven/ciborium", branch = "feat-ser-null-as-undefined", optional = true } dashcore = { git = "https://github.com/dashpay/rust-dashcore", features = [ "std", @@ -28,8 +28,7 @@ dashcore = { git = "https://github.com/dashpay/rust-dashcore", features = [ "rand", "signer", "serde", -], default-features = false, tag = "0.34.0" } -env_logger = { version = "0.11" } +], default-features = false, tag = "0.34.0", optional = true } getrandom = { version = "0.2", features = ["js"] } hex = { version = "0.4" } integer-encoding = { version = "4.0.0" } @@ -38,7 +37,6 @@ jsonschema = { git = "https://github.com/dashpay/jsonschema-rs", branch = "confi "draft202012", ], optional = true } lazy_static = { version = "1.4" } -log = { version = "0.4.6" } num_enum = "0.7" bincode = { version = "2.0.0-rc.3", features = ["serde"] } rand = { version = "0.8.5", features = ["small_rng"] } @@ -49,18 +47,18 @@ serde_repr = { version = "0.1.7" } sha2 = { version = "0.10" } thiserror = { version = "1.0" } data-contracts = { path = "../data-contracts", optional = true } -platform-value = { path = "../rs-platform-value" } +platform-value = { path = "../rs-platform-value", optional = true } platform-version = { path = "../rs-platform-version" } platform-versioning = { path = "../rs-platform-versioning" } platform-serialization = { path = "../rs-platform-serialization" } platform-serialization-derive = { path = "../rs-platform-serialization-derive" } derive_more = { version = "1.0", features = ["from", "display", "try_into"] } nohash-hasher = "0.2.0" -rust_decimal = "1.29.1" -rust_decimal_macros = "1.29.1" +rust_decimal = { version = "1.29.1", optional = true } +rust_decimal_macros = { version = "1.29.1", optional = true } indexmap = { version = "2.7.0", features = ["serde"] } strum = { version = "0.26", features = ["derive"] } -json-schema-compatibility-validator = { path = '../rs-json-schema-compatibility-validator' } +json-schema-compatibility-validator = { path = '../rs-json-schema-compatibility-validator', optional = true } once_cell = "1.19.0" [dev-dependencies] @@ -70,6 +68,7 @@ pretty_assertions = { version = "1.4.1" } dpp = { path = ".", features = ["all_features_without_client"] } assert_matches = "1.5.0" once_cell = "1.7" +env_logger = { version = "0.11" } [features] default = ["platform-value", "state-transitions"] @@ -121,27 +120,26 @@ all_features = [ ] dash-sdk-features = [ - "json-object", - "platform-value", - "system_contracts", - "state-transitions", - "validation", - "identity-hashing", - "identity-serialization", - "vote-serialization", - "document-value-conversion", - "data-contract-value-conversion", - "identity-value-conversion", - "core-types", - "core-types-serialization", - "core-types-serde-conversion", - "state-transition-serde-conversion", +# "json-object", +# "platform-value", +# "system_contracts", +# "validation", # TODO: This one is big +# "identity-hashing", +# "identity-serialization", +# "vote-serialization", +# "document-value-conversion", +# "data-contract-value-conversion", +# "identity-value-conversion", +# "core-types", +# "core-types-serialization", +# "core-types-serde-conversion", +# "state-transition-serde-conversion", "state-transition-value-conversion", - "state-transition-json-conversion", - "state-transition-validation", +# "state-transition-json-conversion", +# "state-transition-validation", "state-transition-signing", - "state-transitions", - "fee-distribution", +# "state-transitions", +# "fee-distribution", "client", "platform-value-cbor", ] @@ -208,6 +206,8 @@ validation = [ "state-transition-serde-conversion", "ed25519-dalek", ] +# TODO: Tring to remove regexp +create-contested-document = [] platform-value-json = ["platform-value/json"] platform-value-cbor = ["platform-value/cbor"] json-schema-validation = ["jsonschema", "platform-value-json"] diff --git a/packages/rs-dpp/src/bls/mod.rs b/packages/rs-dpp/src/bls/mod.rs index 8b825531c02..a5501f4634d 100644 --- a/packages/rs-dpp/src/bls/mod.rs +++ b/packages/rs-dpp/src/bls/mod.rs @@ -1,4 +1,4 @@ -#[cfg(all(not(target_arch = "wasm32"), feature = "bls-signatures"))] +#[cfg(feature = "bls-signatures")] pub mod native_bls; use crate::{ProtocolError, PublicKeyValidationError}; diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v0/mod.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v0/mod.rs index 57b3bffb37f..a55ce4a6d0e 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v0/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v0/mod.rs @@ -721,6 +721,8 @@ fn insert_values( Ok(()) } + +// TODO: This is quite big fn insert_values_nested( document_properties: &mut IndexMap, known_required: &BTreeSet, diff --git a/packages/rs-dpp/src/data_contract/document_type/index/mod.rs b/packages/rs-dpp/src/data_contract/document_type/index/mod.rs index a8768ed8f5d..70bb184aa2f 100644 --- a/packages/rs-dpp/src/data_contract/document_type/index/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/index/mod.rs @@ -25,6 +25,7 @@ use serde::de::{VariantAccess, Visitor}; use std::cmp::Ordering; #[cfg(feature = "index-serde-conversion")] use std::fmt; +use std::sync::OnceLock; use std::{collections::BTreeMap, convert::TryFrom}; pub mod random_index; @@ -53,10 +54,37 @@ impl TryFrom for ContestedIndexResolution { #[repr(u8)] #[derive(Debug)] pub enum ContestedIndexFieldMatch { - Regex(regex::Regex), + Regex(LazyRegex), PositiveIntegerMatch(u128), } +#[derive(Debug, Clone)] +pub struct LazyRegex { + regex: OnceLock, + regex_str: String, +} + +impl LazyRegex { + pub fn new(regex_str: String) -> Self { + LazyRegex { + regex: OnceLock::new(), + regex_str, + } + } + + pub fn is_match(&self, string: &str) -> bool { + let regexp = self + .regex + .get_or_init(|| Regex::new(&self.regex_str).expect("valid regexp")); + + regexp.is_match(string) + } + + pub fn as_str(&self) -> &str { + self.regex_str.as_str() + } +} + #[cfg(feature = "index-serde-conversion")] impl Serialize for ContestedIndexFieldMatch { fn serialize(&self, serializer: S) -> Result @@ -133,10 +161,9 @@ impl<'de> Deserialize<'de> for ContestedIndexFieldMatch { { match visitor.variant()? { (Field::Regex, v) => { - let regex_str: &str = v.newtype_variant()?; - Regex::new(regex_str) - .map(ContestedIndexFieldMatch::Regex) - .map_err(de::Error::custom) + let regex_str: String = v.newtype_variant()?; + + Ok(ContestedIndexFieldMatch::Regex(LazyRegex::new(regex_str))) } (Field::PositiveIntegerMatch, v) => { let num: u128 = v.newtype_variant()?; @@ -192,7 +219,7 @@ impl Clone for ContestedIndexFieldMatch { fn clone(&self) -> Self { match self { ContestedIndexFieldMatch::Regex(regex) => { - ContestedIndexFieldMatch::Regex(regex::Regex::new(regex.as_str()).unwrap()) + ContestedIndexFieldMatch::Regex(regex.clone()) } ContestedIndexFieldMatch::PositiveIntegerMatch(int) => { ContestedIndexFieldMatch::PositiveIntegerMatch(*int) @@ -494,15 +521,20 @@ impl TryFrom<&[(Value, Value)]> for Index { name = Some(field); } "regexPattern" => { - let regex = field_match_value.to_str()?.to_owned(); + let regex_str = + field_match_value.to_str()?.to_owned(); + + #[cfg(feature = "validation")] + Regex::new(®ex_str).map_err(|e| { + RegexError(format!( + "invalid field match regex: {}", + e.to_string() + )) + })?; + field_matches = Some(ContestedIndexFieldMatch::Regex( - Regex::new(®ex).map_err(|e| { - RegexError(format!( - "invalid field match regex: {}", - e.to_string() - )) - })?, + LazyRegex::new(regex_str), )); } key => { diff --git a/packages/rs-dpp/src/data_contract/mod.rs b/packages/rs-dpp/src/data_contract/mod.rs index 5fd8f7b56f5..2c1fa42fa75 100644 --- a/packages/rs-dpp/src/data_contract/mod.rs +++ b/packages/rs-dpp/src/data_contract/mod.rs @@ -23,6 +23,11 @@ mod v0; pub mod factory; #[cfg(feature = "factories")] pub use factory::*; +#[cfg(any( + feature = "data-contract-value-conversion", + feature = "data-contract-cbor-conversion", + feature = "data-contract-json-conversion" +))] pub mod conversion; #[cfg(feature = "client")] mod data_contract_facade; diff --git a/packages/rs-dpp/src/lib.rs b/packages/rs-dpp/src/lib.rs index 27932329aa9..0b6075e5d9c 100644 --- a/packages/rs-dpp/src/lib.rs +++ b/packages/rs-dpp/src/lib.rs @@ -24,7 +24,6 @@ pub mod version; pub mod errors; -pub mod schema; pub mod validation; #[cfg(feature = "client")] diff --git a/packages/rs-dpp/src/schema/data_contract/v0/stateTransition/dataContractCreate.json b/packages/rs-dpp/src/schema/data_contract/v0/stateTransition/dataContractCreate.json deleted file mode 100644 index c093f71afb9..00000000000 --- a/packages/rs-dpp/src/schema/data_contract/v0/stateTransition/dataContractCreate.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "version": { - "type": "integer", - "$comment": "Maximum is the latest protocol version" - }, - "type": { - "type": "integer", - "const": 0 - }, - "dataContract": { - "type": "object" - }, - "entropy": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32 - }, - "signaturePublicKeyId": { - "type": "integer", - "minimum": 0 - }, - "signature": { - "type": "array", - "byteArray": true, - "minItems": 65, - "maxItems": 96 - } - }, - "additionalProperties": false, - "required": [ - "version", - "type", - "dataContract", - "entropy", - "signaturePublicKeyId", - "signature" - ] -} diff --git a/packages/rs-dpp/src/schema/data_contract/v0/stateTransition/dataContractUpdate.json b/packages/rs-dpp/src/schema/data_contract/v0/stateTransition/dataContractUpdate.json deleted file mode 100644 index 4ce9c5dd353..00000000000 --- a/packages/rs-dpp/src/schema/data_contract/v0/stateTransition/dataContractUpdate.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "version": { - "type": "integer", - "$comment": "Maximum is the latest protocol version" - }, - "type": { - "type": "integer", - "const": 4 - }, - "dataContract": { - "type": "object" - }, - "signaturePublicKeyId": { - "type": "integer", - "minimum": 0 - }, - "signature": { - "type": "array", - "byteArray": true, - "minItems": 65, - "maxItems": 96 - } - }, - "additionalProperties": false, - "required": [ - "version", - "type", - "dataContract", - "signaturePublicKeyId", - "signature" - ] -} diff --git a/packages/rs-dpp/src/schema/document/v0/documentBase.json b/packages/rs-dpp/src/schema/document/v0/documentBase.json deleted file mode 100644 index a8ee99ae9cb..00000000000 --- a/packages/rs-dpp/src/schema/document/v0/documentBase.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "$protocolVersion": { - "type": "integer", - "$comment": "Maximum is the latest protocol version" - }, - "$id": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier" - }, - "$type": { - "type": "string" - }, - "$revision": { - "type": "integer", - "minimum": 1 - }, - "$dataContractId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier" - }, - "$ownerId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier" - }, - "$createdAt": { - "type": "integer", - "minimum": 0 - }, - "$updatedAt": { - "type": "integer", - "minimum": 0 - }, - "$transferredAt": { - "type": "integer", - "minimum": 0 - }, - "$createdAtBlockHeight": { - "type": "integer", - "minimum": 0 - }, - "$updatedAtBlockHeight": { - "type": "integer", - "minimum": 0 - }, - "$transferredAtBlockHeight": { - "type": "integer", - "minimum": 0 - }, - "$createdAtCoreBlockHeight": { - "type": "integer", - "minimum": 0 - }, - "$updatedAtCoreBlockHeight": { - "type": "integer", - "minimum": 0 - }, - "$transferredAtCoreBlockHeight": { - "type": "integer", - "minimum": 0 - } - }, - "required": [ - "$protocolVersion", - "$id", - "$type", - "$revision", - "$dataContractId", - "$ownerId" - ], - "additionalProperties": false -} diff --git a/packages/rs-dpp/src/schema/document/v0/stateTransition/documentTransition/base.json b/packages/rs-dpp/src/schema/document/v0/stateTransition/documentTransition/base.json deleted file mode 100644 index 7b74ddb4b87..00000000000 --- a/packages/rs-dpp/src/schema/document/v0/stateTransition/documentTransition/base.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "$id": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier" - }, - "$type": { - "type": "string" - }, - "$action": { - "type": "integer", - "enum": [0, 1, 3] - }, - "$dataContractId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier" - } - }, - "required": [ - "$id", - "$type", - "$action", - "$dataContractId" - ], - "additionalProperties": false -} diff --git a/packages/rs-dpp/src/schema/document/v0/stateTransition/documentTransition/create.json b/packages/rs-dpp/src/schema/document/v0/stateTransition/documentTransition/create.json deleted file mode 100644 index 399cb5c4f7d..00000000000 --- a/packages/rs-dpp/src/schema/document/v0/stateTransition/documentTransition/create.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "$entropy": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32 - }, - "$createdAt": { - "type": "integer", - "minimum": 0 - }, - "$updatedAt": { - "type": "integer", - "minimum": 0 - } - }, - "required": [ - "$entropy" - ], - "additionalProperties": false -} diff --git a/packages/rs-dpp/src/schema/document/v0/stateTransition/documentTransition/replace.json b/packages/rs-dpp/src/schema/document/v0/stateTransition/documentTransition/replace.json deleted file mode 100644 index 1fde6adba6f..00000000000 --- a/packages/rs-dpp/src/schema/document/v0/stateTransition/documentTransition/replace.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "$revision": { - "type": "integer", - "minimum": 1 - }, - "$updatedAt": { - "type": "integer", - "minimum": 0 - } - }, - "required": [ - "$revision" - ], - "additionalProperties": false -} diff --git a/packages/rs-dpp/src/schema/document/v0/stateTransition/documentsBatch.json b/packages/rs-dpp/src/schema/document/v0/stateTransition/documentsBatch.json deleted file mode 100644 index 01e4d2bad61..00000000000 --- a/packages/rs-dpp/src/schema/document/v0/stateTransition/documentsBatch.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "protocolVersion": { - "type": "integer", - "$comment": "Maximum is the latest protocol version" - }, - "type": { - "type": "integer", - "const": 1 - }, - "ownerId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier" - }, - "transitions": { - "type": "array", - "items": { - "type": "object" - }, - "minItems": 1, - "maxItems": 10 - }, - "signaturePublicKeyId": { - "type": "integer", - "minimum": 0 - }, - "signature": { - "type": "array", - "byteArray": true, - "minItems": 65, - "maxItems": 96 - } - }, - "additionalProperties": false, - "required": [ - "protocolVersion", - "type", - "ownerId", - "transitions", - "signaturePublicKeyId", - "signature" - ] -} diff --git a/packages/rs-dpp/src/schema/identity/mod.rs b/packages/rs-dpp/src/schema/identity/mod.rs deleted file mode 100644 index 2d24cd45f58..00000000000 --- a/packages/rs-dpp/src/schema/identity/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod v0; diff --git a/packages/rs-dpp/src/schema/identity/v0/identity.json b/packages/rs-dpp/src/schema/identity/v0/identity.json deleted file mode 100644 index d29b01e8c1c..00000000000 --- a/packages/rs-dpp/src/schema/identity/v0/identity.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "protocolVersion": { - "type": "integer", - "minimum": 0, - "$comment": "Maximum is the latest protocol version" - }, - "id": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier" - }, - "publicKeys": { - "type": "array", - "minItems": 1, - "maxItems": 32, - "uniqueItems": true - }, - "balance": { - "type": "integer", - "minimum": 0 - }, - "revision": { - "type": "integer", - "minimum": 0, - "description": "Identity update revision" - } - }, - "required": [ - "protocolVersion", - "id", - "publicKeys", - "balance", - "revision" - ] -} diff --git a/packages/rs-dpp/src/schema/identity/v0/identity.rs b/packages/rs-dpp/src/schema/identity/v0/identity.rs deleted file mode 100644 index 4a75f03993a..00000000000 --- a/packages/rs-dpp/src/schema/identity/v0/identity.rs +++ /dev/null @@ -1,46 +0,0 @@ -use serde_json::Value; - -pub const IDENTITY_JSON_STRING: &str = r#"{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "protocolVersion": { - "type": "integer", - "minimum": 0, - "$comment": "Maximum is the latest protocol version" - }, - "id": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier" - }, - "publicKeys": { - "type": "array", - "minItems": 1, - "maxItems": 32, - "uniqueItems": true - }, - "balance": { - "type": "integer", - "minimum": 0 - }, - "revision": { - "type": "integer", - "minimum": 0, - "description": "Identity update revision" - } - }, - "required": [ - "protocolVersion", - "id", - "publicKeys", - "balance", - "revision" - ] -}"#; - -pub fn identity_json() -> Result { - serde_json::from_str(IDENTITY_JSON_STRING) -} diff --git a/packages/rs-dpp/src/schema/identity/v0/mod.rs b/packages/rs-dpp/src/schema/identity/v0/mod.rs deleted file mode 100644 index 9210acfe1f9..00000000000 --- a/packages/rs-dpp/src/schema/identity/v0/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub use identity::identity_json; - -mod identity; diff --git a/packages/rs-dpp/src/schema/identity/v0/publicKey.json b/packages/rs-dpp/src/schema/identity/v0/publicKey.json deleted file mode 100644 index af3ae1f077c..00000000000 --- a/packages/rs-dpp/src/schema/identity/v0/publicKey.json +++ /dev/null @@ -1,150 +0,0 @@ - { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "id": { - "type": "integer", - "minimum": 0, - "description": "Public key ID", - "$comment": "Must be unique for the identity. It can’t be changed after adding a key. Included when signing state transitions to indicate which identity key was used to sign." - }, - "type": { - "type": "integer", - "enum": [ - 0, - 1, - 2, - 3 - ], - "description": "Public key type. 0 - ECDSA Secp256k1, 1 - BLS 12-381, 2 - ECDSA Secp256k1 Hash160, 3 - BIP 13 Hash160", - "$comment": "It can't be changed after adding a key" - }, - "purpose": { - "type": "integer", - "enum": [ - 0, - 1, - 2, - 3 - ], - "description": "Public key purpose. 0 - Authentication, 1 - Encryption, 2 - Decryption, 3 - Withdraw", - "$comment": "It can't be changed after adding a key" - }, - "securityLevel": { - "type": "integer", - "enum": [ - 0, - 1, - 2, - 3 - ], - "description": "Public key security level. 0 - Master, 1 - Critical, 2 - High, 3 - Medium", - "$comment": "It can't be changed after adding a key" - }, - "data": true, - "readOnly": { - "type": "boolean", - "description": "Read only", - "$comment": "Identity public key can't be modified with readOnly set to true. It can’t be changed after adding a key" - }, - "disabledAt": { - "type": "integer", - "description": "Timestamp indicating that the key was disabled at a specified time", - "minimum": 0 - } - }, - "allOf": [ - { - "if": { - "properties": { - "type": { - "const": 0 - } - } - }, - "then": { - "properties": { - "data": { - "type": "array", - "byteArray": true, - "minItems": 33, - "maxItems": 33, - "description": "Raw ECDSA public key", - "$comment": "It must be a valid key of the specified type and unique for the identity. It can’t be changed after adding a key" - } - } - } - }, - { - "if": { - "properties": { - "type": { - "const": 1 - } - } - }, - "then": { - "properties": { - "data": { - "type": "array", - "byteArray": true, - "minItems": 48, - "maxItems": 48, - "description": "Raw BLS public key", - "$comment": "It must be a valid key of the specified type and unique for the identity. It can’t be changed after adding a key" - } - } - } - }, - { - "if": { - "properties": { - "type": { - "const": 2 - } - } - }, - "then": { - "properties": { - "data": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 20, - "description": "ECDSA Secp256k1 public key Hash160", - "$comment": "It must be a valid key hash of the specified type and unique for the identity. It can’t be changed after adding a key" - } - } - } - }, - { - "if": { - "properties": { - "type": { - "const": 3 - } - } - }, - "then": { - "properties": { - "data": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 20, - "description": "BIP13 script public key", - "$comment": "It must be a valid script hash of the specified type and unique for the identity" - } - } - } - } - ], - "required": [ - "id", - "type", - "data", - "purpose", - "securityLevel" - ], - "additionalProperties": false - } diff --git a/packages/rs-dpp/src/schema/identity/v0/stateTransition/assetLockProof/chainAssetLockProof.json b/packages/rs-dpp/src/schema/identity/v0/stateTransition/assetLockProof/chainAssetLockProof.json deleted file mode 100644 index e5da91cbc26..00000000000 --- a/packages/rs-dpp/src/schema/identity/v0/stateTransition/assetLockProof/chainAssetLockProof.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "type": { - "type": "integer", - "const": 1 - }, - "coreChainLockedHeight": { - "type": "integer", - "minimum": 1, - "maximum": 4294967295 - }, - "outPoint": { - "type": "array", - "byteArray": true, - "minItems": 36, - "maxItems": 36 - } - }, - "additionalProperties": false, - "required": [ - "type", - "coreChainLockedHeight", - "outPoint" - ] -} diff --git a/packages/rs-dpp/src/schema/identity/v0/stateTransition/assetLockProof/instantAssetLockProof.json b/packages/rs-dpp/src/schema/identity/v0/stateTransition/assetLockProof/instantAssetLockProof.json deleted file mode 100644 index 5a5441b432f..00000000000 --- a/packages/rs-dpp/src/schema/identity/v0/stateTransition/assetLockProof/instantAssetLockProof.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "type": { - "type": "integer", - "const": 0 - }, - "instantLock": { - "type": "array", - "byteArray": true, - "minItems": 165, - "maxItems": 100000 - }, - "transaction": { - "type": "array", - "byteArray": true, - "minItems": 1, - "maxItems": 100000 - }, - "outputIndex": { - "type": "integer", - "minimum": 0 - } - }, - "additionalProperties": false, - "required": [ - "type", - "instantLock", - "transaction", - "outputIndex" - ] -} diff --git a/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityCreate.json b/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityCreate.json deleted file mode 100644 index 3eb2227a2f7..00000000000 --- a/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityCreate.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "protocolVersion": { - "type": "integer", - "$comment": "Maximum is the latest protocol version" - }, - "type": { - "type": "integer", - "const": 2 - }, - "assetLockProof": { - "type": "object" - }, - "publicKeys": { - "type": "array", - "minItems": 1, - "maxItems": 10, - "uniqueItems": true - }, - "signature": { - "type": "array", - "byteArray": true, - "minItems": 65, - "maxItems": 65, - "description": "Signature made by AssetLock one time ECDSA key" - } - }, - "additionalProperties": false, - "required": [ - "protocolVersion", - "type", - "assetLockProof", - "publicKeys", - "signature" - ] -} diff --git a/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityCreditTransfer.json b/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityCreditTransfer.json deleted file mode 100644 index da1047bbb2c..00000000000 --- a/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityCreditTransfer.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "protocolVersion": { - "type": "integer", - "$comment": "Maximum is the latest protocol version" - }, - "type": { - "type": "integer", - "const": 7 - }, - "identityId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier" - }, - "recipientId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier" - }, - "amount": { - "type": "integer", - "description": "The amount to be transferred", - "minimum": 1000 - }, - "signature": { - "type": "array", - "byteArray": true, - "minItems": 65, - "maxItems": 65 - }, - "signaturePublicKeyId": { - "type": "integer", - "minimum": 0 - } - }, - "additionalProperties": false, - "required": [ - "protocolVersion", - "type", - "identityId", - "recipientId", - "amount", - "signature", - "signaturePublicKeyId" - ] -} diff --git a/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityCreditWithdrawal.json b/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityCreditWithdrawal.json deleted file mode 100644 index c689d54afd9..00000000000 --- a/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityCreditWithdrawal.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "protocolVersion": { - "type": "integer", - "$comment": "Maximum is the latest protocol version" - }, - "type": { - "type": "integer", - "const": 6 - }, - "identityId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier" - }, - "amount": { - "type": "integer", - "description": "The amount to be withdrawn", - "minimum": 1000 - }, - "coreFeePerByte": { - "type": "integer", - "description": "This is the fee that you are willing to spend for this transaction in Duffs/Byte", - "minimum": 1, - "maximum": 4294967295 - }, - "pooling": { - "type": "integer", - "description": "This indicated the level at which Platform should try to pool this transaction", - "enum": [ - 0, - 1, - 2 - ] - }, - "outputScript": { - "type": "array", - "byteArray": true, - "minItems": 23, - "maxItems": 25 - }, - "signature": { - "type": "array", - "byteArray": true, - "minItems": 65, - "maxItems": 65 - }, - "signaturePublicKeyId": { - "type": "integer", - "minimum": 0 - }, - "revision": { - "type": "integer", - "minimum": 0, - "description": "Target identity revision" - } - }, - "additionalProperties": false, - "required": [ - "protocolVersion", - "type", - "identityId", - "amount", - "coreFeePerByte", - "pooling", - "outputScript", - "signature", - "signaturePublicKeyId", - "revision" - ] -} \ No newline at end of file diff --git a/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityTopUp.json b/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityTopUp.json deleted file mode 100644 index 73be31c5200..00000000000 --- a/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityTopUp.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "protocolVersion": { - "type": "integer", - "$comment": "Maximum is the latest protocol version" - }, - "type": { - "type": "integer", - "const": 3 - }, - "assetLockProof": { - "type": "object" - }, - "identityId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier" - }, - "signature": { - "type": "array", - "byteArray": true, - "minItems": 65, - "maxItems": 65, - "description": "Signature made by AssetLock one time ECDSA key" - } - }, - "additionalProperties": false, - "required": [ - "protocolVersion", - "type", - "assetLockProof", - "identityId", - "signature" - ] -} diff --git a/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityUpdate.json b/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityUpdate.json deleted file mode 100644 index b31632dd9ec..00000000000 --- a/packages/rs-dpp/src/schema/identity/v0/stateTransition/identityUpdate.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "protocolVersion": { - "type": "integer", - "$comment": "Maximum is the latest protocol version" - }, - "type": { - "type": "integer", - "const": 5 - }, - "identityId": { - "type": "array", - "byteArray": true, - "minItems": 32, - "maxItems": 32, - "contentMediaType": "application/x.dash.dpp.identifier" - }, - "signature": { - "type": "array", - "byteArray": true, - "minItems": 65, - "maxItems": 96 - }, - "revision": { - "type": "integer", - "minimum": 0, - "description": "Identity update revision" - }, - "addPublicKeys": { - "type": "array", - "minItems": 1, - "maxItems": 10, - "uniqueItems": true - }, - "disablePublicKeys": { - "type": "array", - "minItems": 1, - "maxItems": 10, - "uniqueItems": true, - "items": { - "type": "integer", - "minimum": 0 - } - }, - "signaturePublicKeyId": { - "type": "integer", - "minimum": 0 - } - }, - "anyOf": [ - { - "type": "object", - "required": [ - "addPublicKeys" - ], - "properties": { - "addPublicKeys": true - } - }, - { - "type": "object", - "required": [ - "disablePublicKeys" - ], - "properties": { - "disablePublicKeys": true - } - } - ], - "additionalProperties": false, - "required": [ - "protocolVersion", - "type", - "identityId", - "signature", - "revision", - "signaturePublicKeyId" - ] -} diff --git a/packages/rs-dpp/src/schema/identity/v0/stateTransition/publicKey.json b/packages/rs-dpp/src/schema/identity/v0/stateTransition/publicKey.json deleted file mode 100644 index ef4b454a9a4..00000000000 --- a/packages/rs-dpp/src/schema/identity/v0/stateTransition/publicKey.json +++ /dev/null @@ -1,146 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "id": { - "type": "integer", - "minimum": 0, - "description": "Public key ID", - "$comment": "Must be unique for the identity. It can’t be changed after adding a key. Included when signing state transitions to indicate which identity key was used to sign." - }, - "type": { - "type": "integer", - "enum": [ - 0, - 1, - 2 - ], - "description": "Public key type. 0 - ECDSA Secp256k1, 1 - BLS 12-381, 2 - ECDSA Secp256k1 Hash160", - "$comment": "It can't be changed after adding a key" - }, - "purpose": { - "type": "integer", - "enum": [ - 0, - 1, - 2, - 3 - ], - "description": "Public key purpose. 0 - Authentication, 1 - Encryption, 2 - Decryption, 3 - Withdraw", - "$comment": "It can't be changed after adding a key" - }, - "securityLevel": { - "type": "integer", - "enum": [ - 0, - 1, - 2, - 3 - ], - "description": "Public key security level. 0 - Master, 1 - Critical, 2 - High, 3 - Medium", - "$comment": "It can't be changed after adding a key" - }, - "data": true, - "readOnly": { - "type": "boolean", - "description": "Read only", - "$comment": "Identity public key can't be modified with readOnly set to true. It can’t be changed after adding a key" - }, - "signature": true - }, - "allOf": [ - { - "if": { - "properties": { - "type": { - "const": 0 - } - } - }, - "then": { - "properties": { - "data": { - "type": "array", - "byteArray": true, - "minItems": 33, - "maxItems": 33, - "description": "Raw ECDSA Secp256k1 public key", - "$comment": "It must be a valid key of the specified type and unique for the identity. It can’t be changed after adding a key" - }, - "signature": { - "type": "array", - "byteArray": true, - "description": "ECDSA Secp256k1 signature to prove ownership of public key", - "minItems": 65, - "maxItems": 65 - } - } - } - }, - { - "if": { - "properties": { - "type": { - "const": 1 - } - } - }, - "then": { - "properties": { - "data": { - "type": "array", - "byteArray": true, - "minItems": 48, - "maxItems": 48, - "description": "Raw BLS public key", - "$comment": "It must be a valid key of the specified type and unique for the identity. It can’t be changed after adding a key" - }, - "signature": { - "type": "array", - "byteArray": true, - "description": "BLS signature to prove ownership of public key", - "minItems": 96, - "maxItems": 96 - } - } - } - }, - { - "if": { - "properties": { - "type": { - "const": 2 - } - } - }, - "then": { - "properties": { - "data": { - "type": "array", - "byteArray": true, - "minItems": 20, - "maxItems": 20, - "description": "ECDSA Secp256k1 public key Hash160", - "$comment": "It must be a valid key hash of the specified type and unique for the identity. It can’t be changed after adding a key" - }, - "signature": { - "type": "array", - "byteArray": true, - "description": "ECDSA signature to prove ownership of public key", - "minItems": 65, - "maxItems": 65 - } - } - } - } - ], - "required": [ - "id", - "type", - "data", - "purpose", - "securityLevel", - "signature" - ], - "additionalProperties": false -} diff --git a/packages/rs-dpp/src/schema/mod.rs b/packages/rs-dpp/src/schema/mod.rs deleted file mode 100644 index 92bc6186b45..00000000000 --- a/packages/rs-dpp/src/schema/mod.rs +++ /dev/null @@ -1,23 +0,0 @@ -use lazy_static::lazy_static; -use serde_json::Value as JsonValue; - -pub mod identity; - -lazy_static! { - pub static ref BASE_TRANSITION_SCHEMA: JsonValue = serde_json::from_str(include_str!( - "./document/v0/stateTransition/documentTransition/base.json" - )) - .unwrap(); - pub static ref CREATE_TRANSITION_SCHEMA: JsonValue = serde_json::from_str(include_str!( - "./document/v0/stateTransition/documentTransition/create.json" - )) - .unwrap(); - pub static ref REPLACE_TRANSITION_SCHEMA: JsonValue = serde_json::from_str(include_str!( - "./document/v0/stateTransition/documentTransition/replace.json" - )) - .unwrap(); - pub static ref DOCUMENTS_BATCH_TRANSITIONS_SCHEMA: JsonValue = serde_json::from_str( - include_str!("./document/v0/stateTransition/documentsBatch.json") - ) - .unwrap(); -} diff --git a/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/document_create_transition/v0/from_document.rs b/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/document_create_transition/v0/from_document.rs index 3132a4ba07f..740d7a4b0ef 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/document_create_transition/v0/from_document.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/document_create_transition/v0/from_document.rs @@ -16,8 +16,14 @@ impl DocumentCreateTransitionV0 { platform_version: &PlatformVersion, base_feature_version: Option, ) -> Result { - let prefunded_voting_balance = - document_type.prefunded_voting_balance_for_document(&document, platform_version)?; + let prefunded_voting_balance = None; + + #[cfg(feature = "contested-documents")] + { + if let Some(vote_poll) = document_type.contested_vote_poll_for_document(&document) { + prefunded_voting_balance = Some(vote_poll); + } + } Ok(DocumentCreateTransitionV0 { base: DocumentBaseTransition::from_document( &document, diff --git a/packages/rs-dpp/src/util/deserializer.rs b/packages/rs-dpp/src/util/deserializer.rs index 301bdf24d27..9be4ff6bba3 100644 --- a/packages/rs-dpp/src/util/deserializer.rs +++ b/packages/rs-dpp/src/util/deserializer.rs @@ -6,23 +6,9 @@ use crate::consensus::basic::BasicError; use crate::consensus::ConsensusError; use integer_encoding::VarInt; use platform_version::version::FeatureVersion; -use serde_json::{Map, Number, Value as JsonValue}; use crate::errors::ProtocolError; -pub fn parse_protocol_version( - protocol_bytes: &[u8], - json_map: &mut Map, -) -> Result<(), ProtocolError> { - let protocol_version = get_protocol_version(protocol_bytes)?; - - json_map.insert( - String::from("$protocolVersion"), - JsonValue::Number(Number::from(protocol_version)), - ); - Ok(()) -} - /// A protocol version pub type ProtocolVersion = u32; diff --git a/packages/rs-dpp/src/util/json_schema.rs b/packages/rs-dpp/src/util/json_schema.rs index eaf8fb0d909..081460ea08a 100644 --- a/packages/rs-dpp/src/util/json_schema.rs +++ b/packages/rs-dpp/src/util/json_schema.rs @@ -26,6 +26,7 @@ pub trait JsonSchemaExt { fn is_type_of_identifier(&self) -> bool; } +// TODO: This is big (due to using regex inside?) pub fn resolve_uri<'a>(value: &'a Value, uri: &str) -> Result<&'a Value, DataContractError> { if !uri.starts_with("#/") { return Err(DataContractError::InvalidURI( diff --git a/packages/rs-drive-proof-verifier/Cargo.toml b/packages/rs-drive-proof-verifier/Cargo.toml index 632f87a8170..419c945c1e6 100644 --- a/packages/rs-drive-proof-verifier/Cargo.toml +++ b/packages/rs-drive-proof-verifier/Cargo.toml @@ -4,16 +4,12 @@ version = "1.7.0" edition = "2021" rust-version.workspace = true -crate-type = ["cdylib"] - [features] -default = ["mocks"] +default = [] mocks = [ "dep:serde", "dep:serde_json", - "dep:bincode", "dep:platform-serialization-derive", - "dep:platform-serialization", "dpp/document-serde-conversion", "indexmap/serde", ] @@ -30,13 +26,13 @@ drive = { path = "../rs-drive", default-features = false, features = [ ] } dpp = { path = "../rs-dpp", features = [ "bls-signatures", - "document-value-conversion", - "extended-document", +# "document-value-conversion", +# "extended-document", "core-types-serialization", ], default-features = false } -bincode = { version = "2.0.0-rc.3", features = ["serde"], optional = true } +bincode = { version = "2.0.0-rc.3", features = ["serde"] } platform-serialization-derive = { path = "../rs-platform-serialization-derive", optional = true } -platform-serialization = { path = "../rs-platform-serialization", optional = true } +platform-serialization = { path = "../rs-platform-serialization" } tenderdash-abci = { git = "https://github.com/dashpay/rs-tenderdash-abci", version = "1.2.1", tag = "v1.2.1+1.3.0", features = [ "crypto", ], default-features = false } diff --git a/packages/rs-drive-proof-verifier/src/types.rs b/packages/rs-drive-proof-verifier/src/types.rs index 40fa528a546..a482f6ddc12 100644 --- a/packages/rs-drive-proof-verifier/src/types.rs +++ b/packages/rs-drive-proof-verifier/src/types.rs @@ -35,10 +35,11 @@ use drive::grovedb::Element; pub use indexmap::IndexMap; use std::collections::{BTreeMap, BTreeSet}; +use dpp::dashcore::hashes::Hash; #[cfg(feature = "mocks")] use { bincode::{Decode, Encode}, - dpp::{dashcore::hashes::Hash, version as platform_version, ProtocolError}, + dpp::{version as platform_version, ProtocolError}, platform_serialization::{PlatformVersionEncode, PlatformVersionedDecode}, platform_serialization_derive::{PlatformDeserialize, PlatformSerialize}, }; @@ -239,6 +240,7 @@ pub type IdentityBalanceAndRevision = (u64, Revision); #[derive(Debug, Clone, PartialEq)] pub struct ContestedResource(pub Value); +#[cfg(feature = "mocks")] impl ContestedResource { /// Get the value. pub fn encode_to_vec( diff --git a/packages/rs-drive/Cargo.toml b/packages/rs-drive/Cargo.toml index 7af925f26c0..468c11324be 100644 --- a/packages/rs-drive/Cargo.toml +++ b/packages/rs-drive/Cargo.toml @@ -26,7 +26,7 @@ indexmap = { version = "2.0.2" } sqlparser = { version = "0.38.0" } # used for int maps and needed in the verifier nohash-hasher = { version = "0.2.0" } -dpp = { path = "../rs-dpp", features = [ +dpp = { package = "dpp", path = "../rs-dpp", features = [ "state-transitions", ], default-features = false, optional = true } thiserror = { version = "1.0.63" } diff --git a/packages/rs-platform-value/Cargo.toml b/packages/rs-platform-value/Cargo.toml index bbb11d7b775..499d572342d 100644 --- a/packages/rs-platform-value/Cargo.toml +++ b/packages/rs-platform-value/Cargo.toml @@ -18,8 +18,6 @@ serde = { version = "1.0.197", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"], optional = true } rand = { version = "0.8.4", features = ["small_rng"] } treediff = "5.0.0" -regex = "1.7.1" -lazy_static = "1.4.0" platform-serialization = { path = "../rs-platform-serialization" } platform-version = { path = "../rs-platform-version" } indexmap = "2.0.2" diff --git a/packages/rs-platform-value/src/inner_value_at_path.rs b/packages/rs-platform-value/src/inner_value_at_path.rs index d98dc7cc6b8..b117c20e715 100644 --- a/packages/rs-platform-value/src/inner_value_at_path.rs +++ b/packages/rs-platform-value/src/inner_value_at_path.rs @@ -1,28 +1,40 @@ use crate::value_map::ValueMapHelper; use crate::{error, Error, Value, ValueMap}; -use lazy_static::lazy_static; -use regex::Regex; use std::collections::BTreeMap; pub(crate) fn is_array_path(text: &str) -> Result)>, Error> { - lazy_static! { - static ref RE: Regex = Regex::new(r"(\w+)\[(\d+)?\]").unwrap(); + // 1. Find the last '[' character. + let Some(open_bracket_pos) = text.rfind('[') else { + return Ok(None); + }; + + // 2. Check if `text` ends with ']'. + if !text.ends_with(']') { + return Ok(None); } - RE.captures(text) - .map(|captures| { - Ok(( - captures.get(1).unwrap().as_str(), - captures - .get(2) - .map(|m| { - m.as_str() - .parse::() - .map_err(|_| Error::IntegerSizeError) - }) - .transpose()?, - )) - }) - .transpose() + + // 3. Extract the portion before the '[' as the field name. + let field_name = &text[..open_bracket_pos]; + + // 4. Ensure the field name consists only of word characters + if field_name.is_empty() || !field_name.chars().all(|c| c.is_alphanumeric() || c == '_') { + return Ok(None); + } + + // 5. Extract the portion inside the brackets. + let inside_brackets = &text[open_bracket_pos + 1..text.len() - 1]; + + // 6. If the inside is empty, there is no index number + if inside_brackets.is_empty() { + return Ok(Some((field_name, None))); + } + + // 7. Otherwise, parse the inside as a number (usize). + let index = inside_brackets + .parse::() + .map_err(|_| Error::IntegerSizeError)?; + + Ok(Some((field_name, Some(index)))) } impl Value { @@ -371,7 +383,8 @@ impl Value { } } #[cfg(test)] -mod test { +mod tests { + use super::*; use crate::platform_value; #[test] @@ -406,4 +419,76 @@ mod test { platform_value!("new_value") ); } + + mod is_array_path { + use super::*; + + #[test] + fn test_valid_no_index() { + let result = is_array_path("array[]"); + assert!(result.is_ok()); + let maybe_tuple = result.unwrap(); + assert!(maybe_tuple.is_some()); + let (field_name, index) = maybe_tuple.unwrap(); + assert_eq!(field_name, "array"); + assert_eq!(index, None); + } + + #[test] + fn test_valid_with_index() { + let result = is_array_path("arr[123]"); + assert!(result.is_ok()); + let maybe_tuple = result.unwrap(); + assert!(maybe_tuple.is_some()); + let (field_name, index) = maybe_tuple.unwrap(); + assert_eq!(field_name, "arr"); + assert_eq!(index, Some(123)); + } + + #[test] + fn test_no_brackets() { + let result = is_array_path("no_brackets"); + assert!(result.is_ok()); + assert!(result.unwrap().is_none()); + } + + #[test] + fn test_missing_closing_bracket() { + let result = is_array_path("array["); + assert!(result.is_ok()); + assert!(result.unwrap().is_none()); + } + + #[test] + fn test_non_alphanumeric_field() { + let result = is_array_path("arr-test[123]"); + assert!(result.is_ok()); + assert!(result.unwrap().is_none()); + } + + #[test] + fn test_empty_field_name() { + let result = is_array_path("[123]"); + assert!(result.is_ok()); + assert!(result.unwrap().is_none()); + } + + #[test] + fn test_non_numeric_index() { + let result = is_array_path("array[abc]"); + assert!(result.is_err()); + assert_eq!(result.unwrap_err(), Error::IntegerSizeError); + } + + #[test] + fn test_empty_index() { + let result = is_array_path("array[]"); + assert!(result.is_ok()); + let maybe_tuple = result.unwrap(); + assert!(maybe_tuple.is_some()); + let (field_name, index) = maybe_tuple.unwrap(); + assert_eq!(field_name, "array"); + assert_eq!(index, None); + } + } } diff --git a/packages/rs-sdk/Cargo.toml b/packages/rs-sdk/Cargo.toml index a252e0d1ac2..13b1bf01ae1 100644 --- a/packages/rs-sdk/Cargo.toml +++ b/packages/rs-sdk/Cargo.toml @@ -18,7 +18,7 @@ drive = { path = "../rs-drive", default-features = false, features = [ "verify", ] } -drive-proof-verifier = { path = "../rs-drive-proof-verifier" } +drive-proof-verifier = { path = "../rs-drive-proof-verifier", default-features = false } dapi-grpc-macros = { path = "../rs-dapi-grpc-macros" } http = { version = "1.1" } rustls-pemfile = { version = "2.0.0" } @@ -45,6 +45,7 @@ zeroize = { version = "1.8", features = ["derive"] } [dev-dependencies] rs-dapi-client = { path = "../rs-dapi-client" } +drive-proof-verifier = { path = "../rs-drive-proof-verifier" } tokio = { version = "1.40", features = ["macros", "rt-multi-thread"] } base64 = { version = "0.22.1" } tracing-subscriber = { version = "0.3.18", features = ["env-filter"] } diff --git a/packages/rs-sdk/src/sdk.rs b/packages/rs-sdk/src/sdk.rs index 6cc6d1deef5..7311095916f 100644 --- a/packages/rs-sdk/src/sdk.rs +++ b/packages/rs-sdk/src/sdk.rs @@ -275,6 +275,7 @@ impl Sdk { Ok(()) } + // TODO: Changed to public for tests /// Retrieve object `O` from proof contained in `request` (of type `R`) and `response`. /// /// This method is used to retrieve objects from proofs returned by Dash Platform. @@ -540,11 +541,14 @@ impl Sdk { } } + // TODO: Move to settings /// Indicate if the sdk should request and verify proofs. pub fn prove(&self) -> bool { self.proofs } + // TODO: If we remove this setter we don't need to use ArcSwap. + // It's good enough to set Context once when you initialize the SDK. /// Set the [ContextProvider] to use. /// /// [ContextProvider] is used to access state information, like data contracts and quorum public keys. diff --git a/packages/wasm-sdk/Cargo.toml b/packages/wasm-sdk/Cargo.toml index 846027d5a71..903df824c80 100644 --- a/packages/wasm-sdk/Cargo.toml +++ b/packages/wasm-sdk/Cargo.toml @@ -9,11 +9,6 @@ crate-type = ["cdylib"] [dependencies] web-sys = { version = "0.3.4", features = [ - 'Document', - 'Element', - 'HtmlElement', - 'Node', - 'Window', 'console', ] } wasm-bindgen = { version = "=0.2.99" } @@ -22,6 +17,7 @@ wasm-bindgen-futures = { version = "0.4.49" } # "client", # ] } dash-sdk = { path = "../rs-sdk", default-features = false, features = ["wasm"] } +drive-proof-verifier = { path = "../rs-drive-proof-verifier" } # tonic = { version = "*", features = ["transport"], default-features = false } # client = [ # "tonic/channel", FAIL @@ -31,3 +27,14 @@ dash-sdk = { path = "../rs-sdk", default-features = false, features = ["wasm"] } # "tonic/tls-webpki-roots", # "platform", # ] +wee_alloc = "0.4" + +[profile.release] +lto = "fat" +opt-level = "z" +panic = "abort" +debug = false + +#[package.metadata.wasm-pack.profile.release] +#wasm-opt = ['-g', '-O'] # -g for profiling +# -Oz -Oz -g diff --git a/packages/wasm-sdk/src/lib.rs b/packages/wasm-sdk/src/lib.rs index c0532259693..08f589e5310 100644 --- a/packages/wasm-sdk/src/lib.rs +++ b/packages/wasm-sdk/src/lib.rs @@ -1,157 +1,11 @@ -use std::{ - ops::{Deref, DerefMut}, - str::FromStr, -}; +pub mod sdk; +pub mod state_transitions; +pub mod verify; -use dash_sdk::{ - dpp::{ - block::extended_epoch_info::ExtendedEpochInfo, - dashcore::{ - key::Secp256k1, - secp256k1::{self, SecretKey}, - Network, PrivateKey, - }, - data_contract::accessors::v0::DataContractV0Getters, - document::serialization_traits::DocumentPlatformConversionMethodsV0, - identity::signer::Signer, - prelude::AssetLockProof, - serialization::{PlatformSerializable, PlatformSerializableWithPlatformVersion}, - }, - platform::{ - transition::{broadcast::BroadcastStateTransition, put_identity::PutIdentity}, - DataContract, Document, DocumentQuery, Fetch, Identifier, Identity, - }, - sdk::AddressList, - Sdk, SdkBuilder, -}; -use wasm_bindgen::prelude::*; -use web_sys::{console, js_sys}; +#[global_allocator] +static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; -#[wasm_bindgen] -pub struct WasmSdk(Sdk); -// Dereference JsSdk to Sdk so that we can use &JsSdk everywhere where &sdk is needed -impl std::ops::Deref for WasmSdk { - type Target = Sdk; - fn deref(&self) -> &Self::Target { - &self.0 - } -} -#[wasm_bindgen] -pub struct WasmSdkBuilder(SdkBuilder); -impl Deref for WasmSdkBuilder { - type Target = SdkBuilder; - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl DerefMut for WasmSdkBuilder { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} - -#[wasm_bindgen] -extern "C" { - fn alert(s: &str); -} - -#[wasm_bindgen] -pub async fn identity_testing() { - let sdk = SdkBuilder::new(AddressList::new()) - .build() - .expect("build sdk"); - - let id = Identifier::random(); - let identity = Identity::fetch_by_identifier(&sdk, id.clone()) - .await - .expect("fetch identity") - .expect("identity not found"); - - let identity_serialized = - PlatformSerializable::serialize_to_bytes(&identity).expect("serialize"); - - let asset_lock_proof = AssetLockProof::default(); - let asset_lock_proof_private_key = - PrivateKey::from_slice(&[0; 32], Network::Testnet).expect("create private key"); - - let signer = MockSigner; - let pushed: Identity = identity - .put_to_platform( - &sdk, - asset_lock_proof, - &asset_lock_proof_private_key, - &signer, - None, - ) - .await - .expect("put identity") - .broadcast_and_wait(&sdk, None) - .await - .unwrap(); -} - -#[wasm_bindgen] -pub async fn epoch_testing() { - let sdk = SdkBuilder::new(AddressList::new()) - .build() - .expect("build sdk"); - - let ei = ExtendedEpochInfo::fetch(&sdk, 0) - .await - .expect("fetch extended epoch info") - .expect("extended epoch info not found"); -} - -#[wasm_bindgen] -pub async fn setup_sdk() -> WasmSdk { - let sdk = SdkBuilder::new(AddressList::new()) - .build() - .expect("build sdk"); - WasmSdk(sdk) -} - -#[wasm_bindgen] -pub async fn docs_testing(sdk: &WasmSdk) { - let id = Identifier::random(); - - let dc = DataContract::fetch(&sdk, id) - .await - .expect("fetch data contract") - .expect("data contract not found"); - - let dcs = dc - .serialize_to_bytes_with_platform_version(sdk.version()) - .expect("serialize data contract"); - - let query = DocumentQuery::new(dc.clone(), "asd").expect("create query"); - let doc = Document::fetch(sdk, query) - .await - .expect("fetch document") - .expect("document not found"); - - let document_type = dc - .document_type_for_name("aaa") - .expect("document type for name"); - let doc_serialized = doc - .serialize(document_type, sdk.version()) - .expect("serialize document"); - - let msg = js_sys::JsString::from_str(&format!("{:?} {:?} ", dcs, doc_serialized)) - .expect("create js string"); - console::log_1(&msg); -} -#[derive(Clone, Debug)] -struct MockSigner; -impl Signer for MockSigner { - fn can_sign_with(&self, identity_public_key: &dash_sdk::platform::IdentityPublicKey) -> bool { - true - } - fn sign( - &self, - identity_public_key: &dash_sdk::platform::IdentityPublicKey, - data: &[u8], - ) -> Result { - todo!() - } -} +// TODO: Remove tracing or use +//https://github.com/old-storyai/tracing-wasm +//https://github.com/jquesada2016/tracing_subscriber_wasm +//https://crates.io/crates/tracing-web diff --git a/packages/wasm-sdk/src/sdk.rs b/packages/wasm-sdk/src/sdk.rs new file mode 100644 index 00000000000..a0539ed7a7b --- /dev/null +++ b/packages/wasm-sdk/src/sdk.rs @@ -0,0 +1,145 @@ +use dash_sdk::dpp::dashcore::{Network, PrivateKey}; +use dash_sdk::dpp::identity::signer::Signer; +use dash_sdk::dpp::identity::IdentityV0; +use dash_sdk::dpp::prelude::AssetLockProof; +use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; +use dash_sdk::platform::transition::put_identity::PutIdentity; +use dash_sdk::platform::{Fetch, Identifier, Identity}; +use dash_sdk::{Sdk, SdkBuilder}; +use std::collections::BTreeMap; +use std::ops::{Deref, DerefMut}; +use wasm_bindgen::prelude::wasm_bindgen; + +#[wasm_bindgen] +pub struct WasmSdk(Sdk); +// Dereference JsSdk to Sdk so that we can use &JsSdk everywhere where &sdk is needed +impl std::ops::Deref for WasmSdk { + type Target = Sdk; + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[wasm_bindgen] +pub struct WasmSdkBuilder(SdkBuilder); +impl Deref for WasmSdkBuilder { + type Target = SdkBuilder; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for WasmSdkBuilder { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +#[wasm_bindgen] +pub async fn identity_fetch(sdk: &WasmSdk) { + let id = Identifier::from_bytes(&[0; 32]).expect("create identifier"); + + let identity = Identity::fetch_by_identifier(sdk, id) + .await + .expect("fetch identity") + .expect("identity not found"); +} + +pub async fn identity_put(sdk: &WasmSdk) { + let id = Identifier::from_bytes(&[0; 32]).expect("create identifier"); + + let identity = Identity::V0(IdentityV0 { + id, + public_keys: BTreeMap::new(), + balance: 0, + revision: 0, + }); + + let asset_lock_proof = AssetLockProof::default(); + let asset_lock_proof_private_key = + PrivateKey::from_slice(&[0; 32], Network::Testnet).expect("create private key"); + + let signer = MockSigner; + let pushed: Identity = identity + .put_to_platform( + sdk, + asset_lock_proof, + &asset_lock_proof_private_key, + &signer, + None, + ) + .await + .expect("put identity") + .broadcast_and_wait(sdk, None) + .await + .unwrap(); +} + +// #[wasm_bindgen] +// pub async fn epoch_testing() { +// let sdk = SdkBuilder::new(AddressList::new()) +// .build() +// .expect("build sdk"); +// +// let ei = ExtendedEpochInfo::fetch(&sdk, 0) +// .await +// .expect("fetch extended epoch info") +// .expect("extended epoch info not found"); +// } + +// #[wasm_bindgen] +// pub fn setup_sdk() -> WasmSdk { +// let sdk = SdkBuilder::new(AddressList::new()) +// .build() +// .expect("build sdk"); +// WasmSdk(sdk) +// } + +// #[wasm_bindgen] +// pub async fn docs_testing(sdk: &WasmSdk) { +// let id = Identifier::random(); +// +// let factory = DataContractFactory::new(1).expect("create data contract factory"); +// factory +// .create(id, 1, platform_value!({}), None, None) +// .expect("create data contract"); +// +// let dc = DataContract::fetch(&sdk, id) +// .await +// .expect("fetch data contract") +// .expect("data contract not found"); +// +// let dcs = dc +// .serialize_to_bytes_with_platform_version(sdk.version()) +// .expect("serialize data contract"); +// +// let query = DocumentQuery::new(dc.clone(), "asd").expect("create query"); +// let doc = Document::fetch(sdk, query) +// .await +// .expect("fetch document") +// .expect("document not found"); +// +// let document_type = dc +// .document_type_for_name("aaa") +// .expect("document type for name"); +// let doc_serialized = doc +// .serialize(document_type, sdk.version()) +// .expect("serialize document"); +// +// let msg = js_sys::JsString::from_str(&format!("{:?} {:?} ", dcs, doc_serialized)) +// .expect("create js string"); +// console::log_1(&msg); +// } +#[derive(Clone, Debug)] +struct MockSigner; +impl Signer for MockSigner { + fn can_sign_with(&self, identity_public_key: &dash_sdk::platform::IdentityPublicKey) -> bool { + true + } + fn sign( + &self, + identity_public_key: &dash_sdk::platform::IdentityPublicKey, + data: &[u8], + ) -> Result { + todo!() + } +} diff --git a/packages/wasm-sdk/src/state_transitions/documents.rs b/packages/wasm-sdk/src/state_transitions/documents.rs new file mode 100644 index 00000000000..735f2fb6270 --- /dev/null +++ b/packages/wasm-sdk/src/state_transitions/documents.rs @@ -0,0 +1,76 @@ +use dash_sdk::dashcore_rpc::jsonrpc::serde_json::Value; +use dash_sdk::dpp::data_contract::document_type::DocumentTypeRef; +use dash_sdk::dpp::identity::KeyID; +use dash_sdk::dpp::platform_value::string_encoding::Encoding; +use dash_sdk::dpp::platform_value::Bytes32; +use dash_sdk::dpp::serialization::PlatformSerializable; +use dash_sdk::dpp::state_transition::documents_batch_transition::document_base_transition::v0::DocumentBaseTransitionV0; +use dash_sdk::dpp::state_transition::documents_batch_transition::document_base_transition::DocumentBaseTransition; +use dash_sdk::dpp::state_transition::documents_batch_transition::document_create_transition::DocumentCreateTransitionV0; +use dash_sdk::dpp::state_transition::documents_batch_transition::document_transition::action_type::DocumentTransitionActionType; +use dash_sdk::dpp::state_transition::documents_batch_transition::document_transition::DocumentTransition; +use dash_sdk::dpp::state_transition::documents_batch_transition::{ + DocumentCreateTransition, DocumentsBatchTransition, DocumentsBatchTransitionV0, +}; +use dash_sdk::platform::{Document, Identifier}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::fmt::Display; +use wasm_bindgen::prelude::*; +use web_sys::js_sys::{Number, Uint32Array, Uint8Array}; + +#[wasm_bindgen] +pub fn create_document( + document: JsValue, + identity_contract_nonce: Number, + signature_public_key_id: Number, +) -> Result { + // TODO: Extract document fields from JsValue + + let base = DocumentBaseTransition::V0(DocumentBaseTransitionV0 { + id: Default::default(), + identity_contract_nonce: 1, + document_type_name: "".to_string(), + data_contract_id: Default::default(), + }); + + let transition = DocumentCreateTransition::V0(DocumentCreateTransitionV0 { + base: Default::default(), + entropy: [0; 32], + data: Default::default(), + prefunded_voting_balance: None, + }); + + create_batch_transition( + vec![DocumentTransition::Create(transition)], + signature_public_key_id, + ) +} + +fn create_batch_transition( + transitions: Vec, + signature_public_key_id: Number, +) -> Result { + let signature_public_key_id = signature_public_key_id + .as_f64() + .ok_or_else(|| JsError::new("public_key_id must be a number"))?; + + // TODO: This is unsafe convertion + let signature_public_key_id = signature_public_key_id as KeyID; + + let document_batch_transition = DocumentsBatchTransition::V0(DocumentsBatchTransitionV0 { + owner_id: Default::default(), + transitions, + user_fee_increase: 0, + signature_public_key_id, + signature: Default::default(), + }); + + document_batch_transition + .serialize_to_bytes() + .map_err(to_js_error) + .map(|bytes| Uint8Array::from(bytes.as_slice())) +} + +fn to_js_error(e: impl Display) -> JsError { + JsError::new(&format!("{}", e)) +} diff --git a/packages/wasm-sdk/src/state_transitions/mod.rs b/packages/wasm-sdk/src/state_transitions/mod.rs new file mode 100644 index 00000000000..487a38d50d4 --- /dev/null +++ b/packages/wasm-sdk/src/state_transitions/mod.rs @@ -0,0 +1 @@ +pub mod documents; diff --git a/packages/wasm-sdk/src/verify.rs b/packages/wasm-sdk/src/verify.rs new file mode 100644 index 00000000000..61167168a10 --- /dev/null +++ b/packages/wasm-sdk/src/verify.rs @@ -0,0 +1,236 @@ +use dash_sdk::dpp::dashcore::Network; +use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; +use dash_sdk::dpp::data_contract::DataContract; +use dash_sdk::dpp::document::{Document, DocumentV0Getters}; +use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +use dash_sdk::dpp::identity::Identity; +use dash_sdk::dpp::platform_value::string_encoding::Encoding; +use dash_sdk::dpp::prelude::*; +use dash_sdk::dpp::serialization::PlatformDeserializableWithPotentialValidationFromVersionedStructure; +use dash_sdk::dpp::version::PlatformVersion; +use dash_sdk::platform::proto::get_identity_request::{ + GetIdentityRequestV0, Version as GetIdentityRequestVersion, +}; +use dash_sdk::platform::proto::get_identity_response::{ + get_identity_response_v0, GetIdentityResponseV0, Version, +}; +use dash_sdk::platform::proto::{ + GetDocumentsResponse, GetIdentityRequest, Proof, ResponseMetadata, +}; +use dash_sdk::platform::DocumentQuery; +use drive_proof_verifier::error::ContextProviderError; +use drive_proof_verifier::types::Documents; +use drive_proof_verifier::{ContextProvider, FromProof}; +use std::sync::Arc; +use wasm_bindgen::prelude::wasm_bindgen; + +#[wasm_bindgen] +pub async fn verify_identity_response() -> Option { + let id = Identifier::from_bytes(&[0; 32]).expect("create identifier"); + + let request = dash_sdk::dapi_grpc::platform::v0::GetIdentityRequest { + version: Some(GetIdentityRequestVersion::V0(GetIdentityRequestV0 { + id: vec![], + prove: true, + })), + }; + + let response = dash_sdk::dapi_grpc::platform::v0::GetIdentityResponse { + version: Some(Version::V0(GetIdentityResponseV0 { + result: Some(get_identity_response_v0::Result::Proof(Proof { + grovedb_proof: vec![], + quorum_hash: vec![], + signature: vec![], + round: 0, + block_id_hash: vec![], + quorum_type: 0, + })), + metadata: Some(ResponseMetadata { + height: 0, + core_chain_locked_height: 0, + epoch: 0, + time_ms: 0, + protocol_version: 0, + chain_id: "".to_string(), + }), + })), + }; + + let context = WasmContext {}; + + let (response, metadata, proof) = + >::maybe_from_proof_with_metadata( + request, + response, + Network::Dash, + PlatformVersion::latest(), + &context, + ) + .expect("parse proof"); + + response.map(IdentityWasm) +} + +#[wasm_bindgen] +pub async fn verify_data_contract() -> Option { + let request = dash_sdk::dapi_grpc::platform::v0::GetDataContractRequest { + version: Some( + dash_sdk::platform::proto::get_data_contract_request::Version::V0( + dash_sdk::platform::proto::get_data_contract_request::GetDataContractRequestV0 { + id: vec![], + prove: true, + }, + ), + ), + }; + + let response = dash_sdk::dapi_grpc::platform::v0::GetDataContractResponse { + version: Some( + dash_sdk::platform::proto::get_data_contract_response::Version::V0( + dash_sdk::platform::proto::get_data_contract_response::GetDataContractResponseV0 { + result: Some( + dash_sdk::platform::proto::get_data_contract_response::get_data_contract_response_v0::Result::Proof( + dash_sdk::platform::proto::Proof { + grovedb_proof: vec![], + quorum_hash: vec![], + signature: vec![], + round: 0, + block_id_hash: vec![], + quorum_type: 0, + }, + ), + ), + metadata: Some(dash_sdk::platform::proto::ResponseMetadata { + height: 0, + core_chain_locked_height: 0, + epoch: 0, + time_ms: 0, + protocol_version: 0, + chain_id: "".to_string(), + }), + }, + ), + ), + }; + + let context = WasmContext {}; + + let (response, _, _) = >::maybe_from_proof_with_metadata( + request, + response, + Network::Dash, + PlatformVersion::latest(), + &context, + ) + .expect("parse proof"); + + response.map(DataContractWasm) +} + +#[wasm_bindgen] +pub async fn verify_documents() -> Vec { + let data_contract = + DataContract::versioned_deserialize(&[13, 13, 13], false, PlatformVersion::latest()) + .expect("create data contract"); + + let query = DocumentQuery::new(data_contract, "asd").expect("create query"); + + let response = GetDocumentsResponse { + version: Some(dash_sdk::platform::proto::get_documents_response::Version::V0( + dash_sdk::platform::proto::get_documents_response::GetDocumentsResponseV0 { + result: Some( + dash_sdk::platform::proto::get_documents_response::get_documents_response_v0::Result::Proof( + Proof { + grovedb_proof: vec![], + quorum_hash: vec![], + signature: vec![], + round: 0, + block_id_hash: vec![], + quorum_type: 0, + }, + ), + ), + metadata: Some(ResponseMetadata { + height: 0, + core_chain_locked_height: 0, + epoch: 0, + time_ms: 0, + protocol_version: 0, + chain_id: "".to_string(), + }), + }, + )), + }; + + let (documents, _, _) = + >::maybe_from_proof_with_metadata( + query, + response, + Network::Dash, + PlatformVersion::latest(), + &WasmContext {}, + ) + .expect("parse proof"); + + documents + .unwrap() + .into_iter() + .filter(|(_, doc)| doc.is_some()) + .map(|(_, doc)| DocumentWasm(doc.unwrap())) + .collect() +} + +#[wasm_bindgen] +pub struct IdentityWasm(Identity); + +#[wasm_bindgen] +impl IdentityWasm { + pub fn id(&self) -> String { + self.0.id().to_string(Encoding::Base58) + } +} + +#[wasm_bindgen] +pub struct DataContractWasm(DataContract); + +#[wasm_bindgen] +impl DataContractWasm { + pub fn id(&self) -> String { + self.0.id().to_string(Encoding::Base58) + } +} + +#[wasm_bindgen] +pub struct DocumentWasm(Document); +#[wasm_bindgen] +impl DocumentWasm { + pub fn id(&self) -> String { + self.0.id().to_string(Encoding::Base58) + } +} + +struct WasmContext {} + +impl ContextProvider for WasmContext { + fn get_quorum_public_key( + &self, + quorum_type: u32, + quorum_hash: [u8; 32], + core_chain_locked_height: u32, + ) -> Result<[u8; 48], ContextProviderError> { + todo!() + } + + fn get_data_contract( + &self, + id: &Identifier, + ) -> Result>, ContextProviderError> { + todo!() + } + + fn get_platform_activation_height(&self) -> Result { + todo!() + } +} From c833fb08c927fc6ee77afb644512e16ee1c46fa1 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 2 Jan 2025 11:07:52 +0100 Subject: [PATCH 08/26] chore: fix build issues --- Cargo.lock | 1 + packages/rs-dpp/Cargo.toml | 49 +++++++++++++++++++++----------------- 2 files changed, 28 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 56174e5ad90..8f05ee52ccb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1595,6 +1595,7 @@ dependencies = [ "json-schema-compatibility-validator", "jsonschema", "lazy_static", + "log", "nohash-hasher", "num_enum 0.7.3", "once_cell", diff --git a/packages/rs-dpp/Cargo.toml b/packages/rs-dpp/Cargo.toml index edd5f398aac..7931f6aacf2 100644 --- a/packages/rs-dpp/Cargo.toml +++ b/packages/rs-dpp/Cargo.toml @@ -20,7 +20,7 @@ byteorder = { version = "1.4" } chrono = { version = "0.4.35", default-features = false, features = [ "wasmbind", "clock", -]} +] } ciborium = { git = "https://github.com/qrayven/ciborium", branch = "feat-ser-null-as-undefined", optional = true } dashcore = { git = "https://github.com/dashpay/rust-dashcore", features = [ "std", @@ -55,7 +55,7 @@ platform-serialization-derive = { path = "../rs-platform-serialization-derive" } derive_more = { version = "1.0", features = ["from", "display", "try_into"] } nohash-hasher = "0.2.0" rust_decimal = { version = "1.29.1", optional = true } -rust_decimal_macros = { version = "1.29.1", optional = true } +rust_decimal_macros = { version = "1.29.1", optional = true } indexmap = { version = "2.7.0", features = ["serde"] } strum = { version = "0.26", features = ["derive"] } json-schema-compatibility-validator = { path = '../rs-json-schema-compatibility-validator', optional = true } @@ -69,6 +69,7 @@ dpp = { path = ".", features = ["all_features_without_client"] } assert_matches = "1.5.0" once_cell = "1.7" env_logger = { version = "0.11" } +log = { version = "0.4.22" } [features] default = ["platform-value", "state-transitions"] @@ -120,26 +121,26 @@ all_features = [ ] dash-sdk-features = [ -# "json-object", -# "platform-value", -# "system_contracts", -# "validation", # TODO: This one is big -# "identity-hashing", -# "identity-serialization", -# "vote-serialization", -# "document-value-conversion", -# "data-contract-value-conversion", -# "identity-value-conversion", -# "core-types", -# "core-types-serialization", -# "core-types-serde-conversion", -# "state-transition-serde-conversion", + # "json-object", + # "platform-value", + # "system_contracts", + # "validation", # TODO: This one is big + # "identity-hashing", + # "identity-serialization", + # "vote-serialization", + # "document-value-conversion", + # "data-contract-value-conversion", + # "identity-value-conversion", + # "core-types", + # "core-types-serialization", + # "core-types-serde-conversion", + # "state-transition-serde-conversion", "state-transition-value-conversion", -# "state-transition-json-conversion", -# "state-transition-validation", + # "state-transition-json-conversion", + # "state-transition-validation", "state-transition-signing", -# "state-transitions", -# "fee-distribution", + # "state-transitions", + # "fee-distribution", "client", "platform-value-cbor", ] @@ -210,7 +211,11 @@ validation = [ create-contested-document = [] platform-value-json = ["platform-value/json"] platform-value-cbor = ["platform-value/cbor"] -json-schema-validation = ["jsonschema", "platform-value-json"] +json-schema-validation = [ + "jsonschema", + "platform-value-json", + "dep:json-schema-compatibility-validator", +] json-object = ["platform-value", "platform-value-json"] platform-value = [] identity-hashing = ["identity-serialization"] @@ -281,7 +286,7 @@ random-public-keys = ["bls-signatures", "ed25519-dalek"] random-identities = ["random-public-keys"] random-documents = [] random-document-types = ["platform-value-json"] -fee-distribution = [] +fee-distribution = ["dep:rust_decimal", "dep:rust_decimal_macros"] extended-document = [ "document-serde-conversion", "data-contract-serde-conversion", From 815a3646a224fe101a745f9a7940616e7e924139 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 2 Jan 2025 18:04:47 +0100 Subject: [PATCH 09/26] feat(wasm-sdk): wasm_channel working on browser --- Cargo.lock | 383 ++++++------------ packages/rs-dapi-client/Cargo.toml | 20 +- .../src/transport/wasm_channel.rs | 117 ++++-- packages/rs-sdk/src/sdk.rs | 16 +- packages/wasm-sdk/Cargo.toml | 7 + packages/wasm-sdk/index.html | 8 +- packages/wasm-sdk/src/error.rs | 7 + packages/wasm-sdk/src/lib.rs | 15 + packages/wasm-sdk/src/sdk.rs | 41 +- packages/wasm-sdk/src/verify.rs | 3 +- 10 files changed, 301 insertions(+), 316 deletions(-) create mode 100644 packages/wasm-sdk/src/error.rs diff --git a/Cargo.lock b/Cargo.lock index 8f05ee52ccb..1ce5925162a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -183,113 +183,17 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" -[[package]] -name = "async-channel" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35" -dependencies = [ - "concurrent-queue", - "event-listener 2.5.3", - "futures-core", -] - -[[package]] -name = "async-channel" -version = "2.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89b47800b0be77592da0afd425cc03468052844aff33b84e33cc696f64e77b6a" -dependencies = [ - "concurrent-queue", - "event-listener-strategy", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-executor" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30ca9a001c1e8ba5149f91a74362376cc6bc5b919d92d988668657bd570bdcec" -dependencies = [ - "async-task", - "concurrent-queue", - "fastrand", - "futures-lite", - "slab", -] - -[[package]] -name = "async-global-executor" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" -dependencies = [ - "async-channel 2.3.1", - "async-executor", - "async-io", - "async-lock", - "blocking", - "futures-lite", - "once_cell", -] - -[[package]] -name = "async-io" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a2b323ccce0a1d90b449fd71f2a06ca7faa7c54c2751f06c9bd851fc061059" -dependencies = [ - "async-lock", - "cfg-if 1.0.0", - "concurrent-queue", - "futures-io", - "futures-lite", - "parking", - "polling", - "rustix", - "slab", - "tracing", - "windows-sys 0.59.0", -] - [[package]] name = "async-lock" version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" dependencies = [ - "event-listener 5.3.1", + "event-listener", "event-listener-strategy", "pin-project-lite", ] -[[package]] -name = "async-std" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c634475f29802fde2b8f0b505b1bd00dfe4df7d4a000f0b36f7671197d5c3615" -dependencies = [ - "async-channel 1.9.0", - "async-global-executor", - "async-io", - "async-lock", - "crossbeam-utils", - "futures-channel", - "futures-core", - "futures-io", - "futures-lite", - "gloo-timers", - "kv-log-macro", - "log", - "memchr", - "once_cell", - "pin-project-lite", - "pin-utils", - "slab", - "wasm-bindgen-futures", -] - [[package]] name = "async-stream" version = "0.3.5" @@ -309,15 +213,9 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] -[[package]] -name = "async-task" -version = "4.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" - [[package]] name = "async-trait" version = "0.1.83" @@ -326,7 +224,7 @@ checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -406,7 +304,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -509,7 +407,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.75", + "syn 2.0.94", "which", ] @@ -530,7 +428,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -540,7 +438,7 @@ source = "git+https://github.com/dashpay/rs-bip37-bloom-filter?branch=develop#35 dependencies = [ "bitvec", "murmur3", - "thiserror", + "thiserror 1.0.64", ] [[package]] @@ -620,19 +518,6 @@ dependencies = [ "generic-array 0.14.7", ] -[[package]] -name = "blocking" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "703f41c54fc768e63e091340b424302bb1c29ef4aa0c7f10fe849dfb114d29ea" -dependencies = [ - "async-channel 2.3.1", - "async-task", - "futures-io", - "futures-lite", - "piper", -] - [[package]] name = "bls-dash-sys" version = "1.2.5" @@ -675,7 +560,7 @@ dependencies = [ "sha2", "sha3", "subtle", - "thiserror", + "thiserror 1.0.64", "uint-zigzag", "vsss-rs", "zeroize", @@ -731,7 +616,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", "syn_derive", ] @@ -983,7 +868,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -1056,6 +941,16 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if 1.0.0", + "wasm-bindgen", +] + [[package]] name = "const-oid" version = "0.9.6" @@ -1246,7 +1141,7 @@ checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -1272,7 +1167,7 @@ dependencies = [ "dapi-grpc", "heck 0.5.0", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -1296,7 +1191,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -1307,7 +1202,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -1342,7 +1237,7 @@ dependencies = [ "serde", "serde_json", "test-case", - "thiserror", + "thiserror 1.0.64", "tokio", "tokio-test", "tokio-util", @@ -1424,7 +1319,7 @@ dependencies = [ "platform-value", "platform-version", "serde_json", - "thiserror", + "thiserror 1.0.64", ] [[package]] @@ -1438,7 +1333,7 @@ dependencies = [ "platform-value", "platform-version", "serde_json", - "thiserror", + "thiserror 1.0.64", "wallet-utils-contract", "withdrawals-contract", ] @@ -1451,7 +1346,7 @@ checksum = "5060bb0febb73fa907273f8a7ed17ab4bf831d585eac835b28ec24a1e2460956" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -1482,7 +1377,7 @@ checksum = "67e77553c4162a157adbf834ebae5b415acbecbeafc7a74b0e886657506a7611" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -1495,7 +1390,7 @@ dependencies = [ "proc-macro2", "quote", "rustc_version", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -1515,7 +1410,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", "unicode-xid", ] @@ -1544,7 +1439,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -1566,7 +1461,7 @@ dependencies = [ "platform-value", "platform-version", "serde_json", - "thiserror", + "thiserror 1.0.64", ] [[package]] @@ -1615,7 +1510,7 @@ dependencies = [ "sha2", "strum", "test-case", - "thiserror", + "thiserror 1.0.64", "tokio", ] @@ -1656,7 +1551,7 @@ dependencies = [ "serde_json", "sqlparser", "tempfile", - "thiserror", + "thiserror 1.0.64", "tracing", ] @@ -1707,7 +1602,7 @@ dependencies = [ "strategy-tests", "tempfile", "tenderdash-abci", - "thiserror", + "thiserror 1.0.64", "tokio", "tokio-util", "tracing", @@ -1731,7 +1626,7 @@ dependencies = [ "serde", "serde_json", "tenderdash-abci", - "thiserror", + "thiserror 1.0.64", "tracing", ] @@ -1742,7 +1637,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9c8d6ea916fadcd87e3d1ff4802b696d717c83519b47e76f267ab77e536dd5a" dependencies = [ "ed-derive", - "thiserror", + "thiserror 1.0.64", ] [[package]] @@ -1848,7 +1743,7 @@ checksum = "f282cfdfe92516eb26c2af8589c274c7c17681f5ecc03c18255fe741c6aa64eb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -1912,12 +1807,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "event-listener" -version = "2.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" - [[package]] name = "event-listener" version = "5.3.1" @@ -1935,7 +1824,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f214dc438f977e6d4e3500aaa277f5ad94ca83fbbd9b1a15713ce2344ccc5a1" dependencies = [ - "event-listener 5.3.1", + "event-listener", "pin-project-lite", ] @@ -1985,7 +1874,7 @@ dependencies = [ "platform-value", "platform-version", "serde_json", - "thiserror", + "thiserror 1.0.64", ] [[package]] @@ -2152,19 +2041,6 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" -[[package]] -name = "futures-lite" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cef40d21ae2c515b51041df9ed313ed21e572df340ea58a922a0aefe7e8891a1" -dependencies = [ - "fastrand", - "futures-core", - "futures-io", - "parking", - "pin-project-lite", -] - [[package]] name = "futures-macro" version = "0.3.30" @@ -2173,7 +2049,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -2305,7 +2181,7 @@ dependencies = [ "reqwest", "sha2", "tempfile", - "thiserror", + "thiserror 1.0.64", "tokio", "tokio-util", "tower-http", @@ -2320,7 +2196,7 @@ checksum = "360f7c8d3b20beafcbf3cde8754bbcfd201ae2a30ec7594a4b9678fd2fa3c7a8" dependencies = [ "integer-encoding", "intmap", - "thiserror", + "thiserror 1.0.64", ] [[package]] @@ -2333,7 +2209,7 @@ dependencies = [ "hex", "integer-encoding", "intmap", - "thiserror", + "thiserror 1.0.64", ] [[package]] @@ -2358,7 +2234,7 @@ dependencies = [ "integer-encoding", "num_cpus", "rand", - "thiserror", + "thiserror 1.0.64", "time", ] @@ -2385,7 +2261,7 @@ dependencies = [ "rocksdb", "strum", "tempfile", - "thiserror", + "thiserror 1.0.64", ] [[package]] @@ -2394,7 +2270,7 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f4be0c1a1ef97068fe93212e7b6f349e0b44a9fc90063c8c28e110cfb8c2fcb2" dependencies = [ - "thiserror", + "thiserror 1.0.64", "versioned-feature-core 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -2928,7 +2804,7 @@ checksum = "ec9ad60d674508f3ca8f380a928cfe7b096bc729c4e2dbfe3852bc45da3ab30b" dependencies = [ "serde", "serde_json", - "thiserror", + "thiserror 1.0.64", ] [[package]] @@ -2940,7 +2816,7 @@ dependencies = [ "json-schema-compatibility-validator", "once_cell", "serde_json", - "thiserror", + "thiserror 1.0.64", ] [[package]] @@ -2990,15 +2866,6 @@ dependencies = [ "cpufeatures", ] -[[package]] -name = "kv-log-macro" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f" -dependencies = [ - "log", -] - [[package]] name = "lazy_static" version = "1.5.0" @@ -3093,9 +2960,6 @@ name = "log" version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" -dependencies = [ - "value-bag", -] [[package]] name = "lru" @@ -3123,7 +2987,7 @@ dependencies = [ "platform-value", "platform-version", "serde_json", - "thiserror", + "thiserror 1.0.64", ] [[package]] @@ -3190,7 +3054,7 @@ dependencies = [ "metrics", "metrics-util", "quanta", - "thiserror", + "thiserror 1.0.64", "tokio", "tracing", ] @@ -3284,7 +3148,7 @@ dependencies = [ "cfg-if 1.0.0", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -3298,7 +3162,7 @@ dependencies = [ "crossbeam-channel", "crossbeam-epoch", "crossbeam-utils", - "event-listener 5.3.1", + "event-listener", "futures-util", "once_cell", "parking_lot", @@ -3306,7 +3170,7 @@ dependencies = [ "rustc_version", "smallvec", "tagptr", - "thiserror", + "thiserror 1.0.64", "triomphe", "uuid", ] @@ -3436,7 +3300,7 @@ checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -3529,7 +3393,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -3576,7 +3440,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -3709,7 +3573,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -3724,17 +3588,6 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" -[[package]] -name = "piper" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96c8c490f422ef9a4efd2cb5b42b76c8613d7e7dfc1caf667b8a3350a5acc066" -dependencies = [ - "atomic-waker", - "fastrand", - "futures-io", -] - [[package]] name = "pkcs8" version = "0.10.2" @@ -3765,7 +3618,7 @@ version = "1.7.0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", "virtue 0.0.17", ] @@ -3784,7 +3637,7 @@ dependencies = [ "rand", "serde", "serde_json", - "thiserror", + "thiserror 1.0.64", "treediff", ] @@ -3793,7 +3646,7 @@ name = "platform-value-convertible" version = "1.7.0" dependencies = [ "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -3803,7 +3656,7 @@ dependencies = [ "bincode", "grovedb-version", "once_cell", - "thiserror", + "thiserror 1.0.64", "versioned-feature-core 1.0.0 (git+https://github.com/dashpay/versioned-feature-core)", ] @@ -3813,7 +3666,7 @@ version = "1.7.0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -3844,21 +3697,6 @@ dependencies = [ "plotters-backend", ] -[[package]] -name = "polling" -version = "3.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a604568c3202727d1507653cb121dbd627a58684eb09a820fd746bee38b4442f" -dependencies = [ - "cfg-if 1.0.0", - "concurrent-queue", - "hermit-abi 0.4.0", - "pin-project-lite", - "rustix", - "tracing", - "windows-sys 0.59.0", -] - [[package]] name = "portable-atomic" version = "1.7.0" @@ -3923,7 +3761,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e" dependencies = [ "proc-macro2", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -3970,9 +3808,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.86" +version = "1.0.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" +checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" dependencies = [ "unicode-ident", ] @@ -4004,7 +3842,7 @@ dependencies = [ "prost", "prost-types", "regex", - "syn 2.0.75", + "syn 2.0.94", "tempfile", ] @@ -4018,7 +3856,7 @@ dependencies = [ "itertools 0.13.0", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -4321,12 +4159,12 @@ dependencies = [ name = "rs-dapi-client" version = "1.7.0" dependencies = [ - "async-std", "backon", "chrono", "dapi-grpc", "futures", "getrandom", + "gloo-timers", "hex", "http", "http-serde", @@ -4335,10 +4173,11 @@ dependencies = [ "serde", "serde_json", "sha2", - "thiserror", + "thiserror 1.0.64", "tokio", "tonic-web-wasm-client", "tracing", + "wasm-bindgen-futures", ] [[package]] @@ -4616,7 +4455,7 @@ checksum = "24008e81ff7613ed8e5ba0cfaf24e2c2f1e5b8a0495711e44fcd4882fca62bcf" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -4650,7 +4489,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -4717,7 +4556,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -4729,7 +4568,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -4948,7 +4787,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -4979,9 +4818,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.75" +version = "2.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6af063034fc1935ede7be0122941bafa9bacb949334d090b77ca98b5817c7d9" +checksum = "987bc0be1cdea8b10216bd06e2ca407d40b9543468fafd3ddfb02f36e77f71f3" dependencies = [ "proc-macro2", "quote", @@ -4997,7 +4836,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -5085,7 +4924,7 @@ dependencies = [ "semver", "serde_json", "tenderdash-proto 1.2.1+1.3.0 (git+https://github.com/dashpay/rs-tenderdash-abci?tag=v1.2.1%2B1.3.0)", - "thiserror", + "thiserror 1.0.64", "tokio", "tokio-util", "tracing", @@ -5193,7 +5032,7 @@ dependencies = [ "cfg-if 1.0.0", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -5204,7 +5043,7 @@ checksum = "5c89e72a01ed4c579669add59014b9a524d609c0c88c6a585ce37485879f6ffb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", "test-case-core", ] @@ -5214,7 +5053,16 @@ version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d50af8abc119fb8bb6dbabcfa89656f46f84aa0ac7688088608076ad2b459a84" dependencies = [ - "thiserror-impl", + "thiserror-impl 1.0.64", +] + +[[package]] +name = "thiserror" +version = "2.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f072643fd0190df67a8bab670c20ef5d8737177d6ac6b2e9a236cb096206b2cc" +dependencies = [ + "thiserror-impl 2.0.9", ] [[package]] @@ -5225,7 +5073,18 @@ checksum = "08904e7672f5eb876eaaf87e0ce17857500934f4981c4a0ab2b4aa98baac7fc3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b50fa271071aae2e6ee85f842e2e28ba8cd2c5fb67f11fcb1fd70b276f9e7d4" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.94", ] [[package]] @@ -5350,7 +5209,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -5512,7 +5371,7 @@ dependencies = [ "prost-build", "prost-types", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -5531,7 +5390,7 @@ dependencies = [ "httparse", "js-sys", "pin-project", - "thiserror", + "thiserror 1.0.64", "tonic", "tower-service", "wasm-bindgen", @@ -5614,7 +5473,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -5796,12 +5655,6 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" -[[package]] -name = "value-bag" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ef4c4aa54d5d05a279399bfa921ec387b7aba77caf7a682ae8d86785b8fdad2" - [[package]] name = "vcpkg" version = "0.2.15" @@ -5874,7 +5727,7 @@ dependencies = [ "platform-value", "platform-version", "serde_json", - "thiserror", + "thiserror 1.0.64", ] [[package]] @@ -5913,7 +5766,7 @@ dependencies = [ "log", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", "wasm-bindgen-shared", ] @@ -5948,7 +5801,7 @@ checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -5976,7 +5829,7 @@ dependencies = [ "serde", "serde-wasm-bindgen", "serde_json", - "thiserror", + "thiserror 1.0.64", "wasm-bindgen", "wasm-bindgen-futures", "wasm-logger", @@ -5998,8 +5851,10 @@ dependencies = [ name = "wasm-sdk" version = "0.1.0" dependencies = [ + "console_error_panic_hook", "dash-sdk", "drive-proof-verifier", + "thiserror 2.0.9", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", @@ -6308,7 +6163,7 @@ dependencies = [ "serde", "serde_json", "serde_repr", - "thiserror", + "thiserror 1.0.64", ] [[package]] @@ -6355,7 +6210,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -6382,7 +6237,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.94", ] [[package]] @@ -6418,7 +6273,7 @@ dependencies = [ "flate2", "indexmap 2.7.0", "memchr", - "thiserror", + "thiserror 1.0.64", "zopfli", ] diff --git a/packages/rs-dapi-client/Cargo.toml b/packages/rs-dapi-client/Cargo.toml index f3ad5aaa288..ec57de5cef4 100644 --- a/packages/rs-dapi-client/Cargo.toml +++ b/packages/rs-dapi-client/Cargo.toml @@ -5,7 +5,13 @@ edition = "2021" [features] # TODO we should not enable deps features in default -default = ["mocks", "offline-testing", "dapi-grpc/client", "backon/tokio-sleep"] +default = [ + "mocks", + "offline-testing", + "dapi-grpc/client", + "backon/tokio-sleep", + "wasm", # TODO: remove +] mocks = [ "dep:sha2", "dep:hex", @@ -22,22 +28,21 @@ wasm = [ "dapi-grpc/wasm", "dapi-grpc/platform", "dapi-grpc/core", - # "backon/gloo-timers-sleep", - # "backon/std-blocking-sleep", - "dep:async-std", "dep:tonic-web-wasm-client", "dep:http", + "dep:wasm-bindgen-futures", + "dep:gloo-timers", "getrandom/js", ] [dependencies] backon = { version = "1.3", default-features = false } - +gloo-timers = { version = "0.3.0", features = ["futures"], optional = true } dapi-grpc = { path = "../dapi-grpc", features = [ "core", "platform", ], default-features = false } -futures = "0.3.28" +futures = { version = "0.3.28" } http = { version = "1.1.0", default-features = false, optional = true } http-serde = { version = "2.1", optional = true } getrandom = { version = "0.2", optional = true } @@ -55,6 +60,7 @@ lru = { version = "0.12.3" } serde = { version = "1.0.197", optional = true, features = ["derive"] } serde_json = { version = "1.0.120", optional = true } chrono = { version = "0.4.38", features = ["serde"] } -async-std = { version = "1.13", optional = true } +wasm-bindgen-futures = { version = "0.4.49", optional = true } + [dev-dependencies] tokio = { version = "1.40", features = ["macros"] } diff --git a/packages/rs-dapi-client/src/transport/wasm_channel.rs b/packages/rs-dapi-client/src/transport/wasm_channel.rs index 9315558ff48..a28e152f792 100644 --- a/packages/rs-dapi-client/src/transport/wasm_channel.rs +++ b/packages/rs-dapi-client/src/transport/wasm_channel.rs @@ -1,6 +1,6 @@ //! Listing of gRPC requests used in DAPI. -use std::thread::sleep; +use std::future::Future; use std::time::Duration; use super::TransportError; @@ -8,60 +8,107 @@ use crate::{request_settings::AppliedRequestSettings, Uri}; use dapi_grpc::core::v0::core_client::CoreClient; use dapi_grpc::platform::v0::platform_client::PlatformClient; -use dapi_grpc::tonic::{self as tonic}; -use futures::FutureExt; -// use tonic_web_wasm_client::Client as WasmClient; +use dapi_grpc::tonic::{self as tonic, Status}; +use futures::channel::oneshot; +use futures::future::BoxFuture; +use futures::{FutureExt, TryFutureExt}; +use http::Response; +use tonic_web_wasm_client::Client; +use wasm_bindgen_futures::spawn_local; +/// Platform Client using gRPC transport. +pub type PlatformGrpcClient = PlatformClient; +/// Core Client using gRPC transport. +pub type CoreGrpcClient = CoreClient; + +/// Create a channel that will be used to communicate with the DAPI. +pub(super) fn create_channel( + uri: Uri, + _settings: Option<&AppliedRequestSettings>, +) -> Result { + WasmClient::new(&uri.to_string()) +} + +/// Transport client used in wasm32 target (eg. Javascript family) #[derive(Clone, Debug)] -// TODO impleent WasmClient using `tonic_web_wasm_client::Client` -pub struct WasmClient; +pub struct WasmClient { + client: Client, +} + +impl WasmClient { + /// Create a new instance of the client, connecting to provided uri. + pub fn new(uri: &str) -> Result { + let client = tonic_web_wasm_client::Client::new(uri.to_string()); + Ok(Self { client }) + } +} impl tonic::client::GrpcService for WasmClient { + type Future = BoxFuture<'static, Result, Self::Error>>; type ResponseBody = tonic::body::BoxBody; + type Error = Status; + fn call(&mut self, request: http::Request) -> Self::Future { - unimplemented!() + let mut client = self.client.clone(); + let fut = client.call(request).map(|res| match res { + Ok(resp) => { + let body = tonic::body::boxed(resp.into_body()); + Ok(Response::new(body)) + } + Err(e) => Err(wasm_client_error_to_status(e)), + }); + + into_send(fut) } + fn poll_ready( &mut self, cx: &mut std::task::Context<'_>, ) -> std::task::Poll> { - unimplemented!() + self.client + .poll_ready(cx) + .map_err(wasm_client_error_to_status) } - type Error = tonic::Status; - type Future = std::pin::Pin< - Box< - dyn std::future::Future< - Output = Result, Self::Error>, - > + Send, - >, - >; } -/// Platform Client using gRPC transport. -pub type PlatformGrpcClient = PlatformClient; -/// Core Client using gRPC transport. -pub type CoreGrpcClient = CoreClient; +/// Map [`tonic_web_wasm_client::Error`] to [`tonic::Status`]. +/// +/// TODO: Add more error handling. +fn wasm_client_error_to_status(e: tonic_web_wasm_client::Error) -> Status { + match e { + tonic_web_wasm_client::Error::TonicStatusError(status) => status, + _ => Status::internal(format!("Failed to call gRPC service: {}", e)), + } +} -type S = futures::future::BoxFuture<'static, ()>; -/// backon::Sleeper +/// backon::Sleeper implementation for Wasm. +/// +/// ## Note +/// +/// It is already implemented in [::backon] crate, but it is not Send, so it cannot be used in our context. +/// We reimplement it here to make it Send. +// TODO: Consider moving it to different module. #[derive(Default, Clone, Debug)] pub struct BackonSleeper {} -// TODO move somewhere else impl backon::Sleeper for BackonSleeper { - type Sleep = S; + type Sleep = BoxFuture<'static, ()>; fn sleep(&self, dur: Duration) -> Self::Sleep { - // TODO: blocking sleep is not the best solution - sleep(dur); - async {}.boxed() + into_send(gloo_timers::future::sleep(dur)).boxed() } } -pub(super) fn create_channel( - uri: Uri, - settings: Option<&AppliedRequestSettings>, -) -> Result { - // let host = uri.host().expect("Failed to get host from URI").to_string(); - // let client = tonic_web_wasm_client::Client::new(uri.to_string()); - - Ok(WasmClient {}) +/// Convert a future into a boxed future that can be sent between threads. +/// +/// This is a workaround using oneshot channel to synchronize. +/// It spawns a local task that sends the result of the future to the channel. +fn into_send<'a, F: Future + 'static>(f: F) -> BoxFuture<'a, F::Output> +where + F::Output: Send, +{ + let (tx, rx) = oneshot::channel::(); + spawn_local(async move { + tx.send(f.await).ok(); + }); + rx.unwrap_or_else(|e| panic!("Failed to receive result: {:?}", e)) + .boxed() } diff --git a/packages/rs-sdk/src/sdk.rs b/packages/rs-sdk/src/sdk.rs index 7311095916f..5ac46f43153 100644 --- a/packages/rs-sdk/src/sdk.rs +++ b/packages/rs-sdk/src/sdk.rs @@ -37,6 +37,7 @@ use std::fmt::Debug; use std::num::NonZeroUsize; #[cfg(feature = "mocks")] use std::path::{Path, PathBuf}; +use std::str::FromStr; use std::sync::atomic::Ordering; use std::sync::{atomic, Arc}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -828,10 +829,19 @@ impl SdkBuilder { /// /// This is a helper method that preconfigures [SdkBuilder] for production use. /// Use this method if you want to connect to Dash Platform mainnet with production-ready product. + /// + /// ## Panics + /// + /// This method panics if the mainnet configuration cannot be loaded. + /// + /// ## Unstable + /// + /// This method is unstable and can be changed in the future. pub fn new_mainnet() -> Self { - unimplemented!( - "Mainnet address list not implemented yet. Use new() and provide address list." - ) + // TODO this is just some test mainnet node, we need to implement proper lookup of nodes + let addresses = AddressList::from_str("https://34.223.102.43:443") + .expect("hardcoded mainnet addresses must be valid"); + Self::new(addresses).with_network(Network::Dash) } /// Configure network type. diff --git a/packages/wasm-sdk/Cargo.toml b/packages/wasm-sdk/Cargo.toml index 903df824c80..fa9d2369cee 100644 --- a/packages/wasm-sdk/Cargo.toml +++ b/packages/wasm-sdk/Cargo.toml @@ -8,8 +8,15 @@ publish = false crate-type = ["cdylib"] [dependencies] +console_error_panic_hook = "0.1.6" +thiserror = { version = "2.0.9" } web-sys = { version = "0.3.4", features = [ 'console', + 'Document', + 'Element', + 'HtmlElement', + 'Node', + 'Window', ] } wasm-bindgen = { version = "=0.2.99" } wasm-bindgen-futures = { version = "0.4.49" } diff --git a/packages/wasm-sdk/index.html b/packages/wasm-sdk/index.html index f8f2197595d..e99c3f63f41 100644 --- a/packages/wasm-sdk/index.html +++ b/packages/wasm-sdk/index.html @@ -1,3 +1,4 @@ + @@ -14,7 +15,7 @@ // will "boot" the module and make it ready to use. Currently browsers // don't support natively imported WebAssembly as an ES module, but // eventually the manual initialization won't be required! - import init, { add } from './pkg/without_a_bundler.js'; + import init, { start } from './pkg/wasm_sdk.js'; async function run() { // First up we need to actually load the Wasm file, so we use the @@ -46,10 +47,7 @@ await init(); // And afterwards we can use all the functionality defined in wasm. - const result = add(1, 2); - console.log(`1 + 2 = ${result}`); - if (result !== 3) - throw new Error("wasm addition doesn't work!"); + // await start(); } run(); diff --git a/packages/wasm-sdk/src/error.rs b/packages/wasm-sdk/src/error.rs new file mode 100644 index 00000000000..5617208dea7 --- /dev/null +++ b/packages/wasm-sdk/src/error.rs @@ -0,0 +1,7 @@ +use dash_sdk::Error; +use wasm_bindgen::prelude::wasm_bindgen; + +#[wasm_bindgen] +#[derive(thiserror::Error, Debug)] +#[error("Dash SDK error: {0:?}")] +pub struct WasmError(#[from] Error); diff --git a/packages/wasm-sdk/src/lib.rs b/packages/wasm-sdk/src/lib.rs index 08f589e5310..c2fef6a4112 100644 --- a/packages/wasm-sdk/src/lib.rs +++ b/packages/wasm-sdk/src/lib.rs @@ -1,3 +1,6 @@ +use wasm_bindgen::{prelude::wasm_bindgen, JsValue}; + +pub mod error; pub mod sdk; pub mod state_transitions; pub mod verify; @@ -9,3 +12,15 @@ static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; //https://github.com/old-storyai/tracing-wasm //https://github.com/jquesada2016/tracing_subscriber_wasm //https://crates.io/crates/tracing-web + +#[wasm_bindgen(start)] +pub async fn start() -> Result<(), JsValue> { + let dash_sdk = sdk::WasmSdkBuilder::new_mainnet(); + let sdk = dash_sdk + .with_context_provider(verify::WasmContext {}) + .build() + .expect("build sdk"); + + sdk::identity_fetch(&sdk).await; + Ok(()) +} diff --git a/packages/wasm-sdk/src/sdk.rs b/packages/wasm-sdk/src/sdk.rs index a0539ed7a7b..5e4686af814 100644 --- a/packages/wasm-sdk/src/sdk.rs +++ b/packages/wasm-sdk/src/sdk.rs @@ -5,11 +5,14 @@ use dash_sdk::dpp::prelude::AssetLockProof; use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; use dash_sdk::platform::transition::put_identity::PutIdentity; use dash_sdk::platform::{Fetch, Identifier, Identity}; -use dash_sdk::{Sdk, SdkBuilder}; +use dash_sdk::{sdk, Sdk, SdkBuilder}; use std::collections::BTreeMap; use std::ops::{Deref, DerefMut}; use wasm_bindgen::prelude::wasm_bindgen; +use crate::error::WasmError; +use crate::verify::WasmContext; + #[wasm_bindgen] pub struct WasmSdk(Sdk); // Dereference JsSdk to Sdk so that we can use &JsSdk everywhere where &sdk is needed @@ -19,8 +22,22 @@ impl std::ops::Deref for WasmSdk { &self.0 } } + +impl AsRef for WasmSdk { + fn as_ref(&self) -> &Sdk { + &self.0 + } +} + +impl From for WasmSdk { + fn from(sdk: Sdk) -> Self { + WasmSdk(sdk) + } +} + #[wasm_bindgen] pub struct WasmSdkBuilder(SdkBuilder); + impl Deref for WasmSdkBuilder { type Target = SdkBuilder; fn deref(&self) -> &Self::Target { @@ -34,6 +51,28 @@ impl DerefMut for WasmSdkBuilder { } } +#[wasm_bindgen] +impl WasmSdkBuilder { + pub fn new_mainnet() -> Self { + std::panic::set_hook(Box::new(console_error_panic_hook::hook)); + WasmSdkBuilder(SdkBuilder::new_mainnet()) + } + + pub fn new_testnet() -> Self { + std::panic::set_hook(Box::new(console_error_panic_hook::hook)); + WasmSdkBuilder(SdkBuilder::new_testnet()) + } + + pub fn build(self) -> Result { + std::panic::set_hook(Box::new(console_error_panic_hook::hook)); + Ok(WasmSdk(self.0.build()?)) + } + + pub fn with_context_provider(self, context_provider: WasmContext) -> Self { + WasmSdkBuilder(self.0.with_context_provider(context_provider)) + } +} + #[wasm_bindgen] pub async fn identity_fetch(sdk: &WasmSdk) { let id = Identifier::from_bytes(&[0; 32]).expect("create identifier"); diff --git a/packages/wasm-sdk/src/verify.rs b/packages/wasm-sdk/src/verify.rs index 61167168a10..ef07010ce3b 100644 --- a/packages/wasm-sdk/src/verify.rs +++ b/packages/wasm-sdk/src/verify.rs @@ -211,7 +211,8 @@ impl DocumentWasm { } } -struct WasmContext {} +#[wasm_bindgen] +pub struct WasmContext {} impl ContextProvider for WasmContext { fn get_quorum_public_key( From aa9ecf88116609d0c74d7bec63e93ef18be5f002 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 3 Jan 2025 15:34:31 +0100 Subject: [PATCH 10/26] feat: fetch identity in browser --- Cargo.lock | 12 ++++ packages/wasm-dpp/Cargo.toml | 2 +- packages/wasm-sdk/Cargo.toml | 10 ++- packages/wasm-sdk/index.html | 9 ++- packages/wasm-sdk/src/context_provider.rs | 78 +++++++++++++++++++++++ packages/wasm-sdk/src/lib.rs | 9 +-- packages/wasm-sdk/src/sdk.rs | 51 ++++++++++----- packages/wasm-sdk/src/verify.rs | 36 ++--------- 8 files changed, 145 insertions(+), 62 deletions(-) create mode 100644 packages/wasm-sdk/src/context_provider.rs diff --git a/Cargo.lock b/Cargo.lock index 1ce5925162a..d6ef4c5f73d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5528,6 +5528,17 @@ dependencies = [ "tracing-serde", ] +[[package]] +name = "tracing-wasm" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4575c663a174420fa2d78f4108ff68f65bf2fbb7dd89f33749b6e826b3626e07" +dependencies = [ + "tracing", + "tracing-subscriber", + "wasm-bindgen", +] + [[package]] name = "treediff" version = "5.0.0" @@ -5855,6 +5866,7 @@ dependencies = [ "dash-sdk", "drive-proof-verifier", "thiserror 2.0.9", + "tracing-wasm", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", diff --git a/packages/wasm-dpp/Cargo.toml b/packages/wasm-dpp/Cargo.toml index ab0080a6924..95d04f9f23b 100644 --- a/packages/wasm-dpp/Cargo.toml +++ b/packages/wasm-dpp/Cargo.toml @@ -6,7 +6,7 @@ rust-version.workspace = true authors = ["Anton Suprunchuk "] [lib] -crate-type = ["cdylib"] +crate-type = ["cdylib", "rlib"] [dependencies] serde = { version = "1.0.197", features = ["derive"] } diff --git a/packages/wasm-sdk/Cargo.toml b/packages/wasm-sdk/Cargo.toml index fa9d2369cee..5890d790d83 100644 --- a/packages/wasm-sdk/Cargo.toml +++ b/packages/wasm-sdk/Cargo.toml @@ -8,7 +8,7 @@ publish = false crate-type = ["cdylib"] [dependencies] -console_error_panic_hook = "0.1.6" +console_error_panic_hook = { version = "0.1.6" } thiserror = { version = "2.0.9" } web-sys = { version = "0.3.4", features = [ 'console', @@ -20,11 +20,9 @@ web-sys = { version = "0.3.4", features = [ ] } wasm-bindgen = { version = "=0.2.99" } wasm-bindgen-futures = { version = "0.4.49" } -# tenderdash-proto = { path = "../../../rs-tenderdash-abci/proto", default-features = false, features = [ -# "client", -# ] } +# wasm-dpp = { path = "../wasm-dpp" } # TODO: breaks build with `invalid type: map, expected a string at line 2 column 18` dash-sdk = { path = "../rs-sdk", default-features = false, features = ["wasm"] } -drive-proof-verifier = { path = "../rs-drive-proof-verifier" } +drive-proof-verifier = { path = "../rs-drive-proof-verifier" } # TODO: I think it's not needed (LKl) # tonic = { version = "*", features = ["transport"], default-features = false } # client = [ # "tonic/channel", FAIL @@ -34,8 +32,8 @@ drive-proof-verifier = { path = "../rs-drive-proof-verifier" } # "tonic/tls-webpki-roots", # "platform", # ] +tracing-wasm = { version = "0.2.1" } wee_alloc = "0.4" - [profile.release] lto = "fat" opt-level = "z" diff --git a/packages/wasm-sdk/index.html b/packages/wasm-sdk/index.html index e99c3f63f41..b7427954308 100644 --- a/packages/wasm-sdk/index.html +++ b/packages/wasm-sdk/index.html @@ -15,7 +15,7 @@ // will "boot" the module and make it ready to use. Currently browsers // don't support natively imported WebAssembly as an ES module, but // eventually the manual initialization won't be required! - import init, { start } from './pkg/wasm_sdk.js'; + import init, { start, WasmSdkBuilder, identity_fetch } from './pkg/wasm_sdk.js'; async function run() { // First up we need to actually load the Wasm file, so we use the @@ -47,7 +47,12 @@ await init(); // And afterwards we can use all the functionality defined in wasm. - // await start(); + const sdk = await WasmSdkBuilder.new_mainnet().build(); + console.log(sdk); + + const identity = await identity_fetch(sdk, "T1jY1c6ojfhYe5w8TV7eNwWXvGRhkcqHJPHfdC54RVz"); + console.log("fetched identity"); + console.log(identity); } run(); diff --git a/packages/wasm-sdk/src/context_provider.rs b/packages/wasm-sdk/src/context_provider.rs new file mode 100644 index 00000000000..1d6989dfe52 --- /dev/null +++ b/packages/wasm-sdk/src/context_provider.rs @@ -0,0 +1,78 @@ +use std::sync::Arc; + +use dash_sdk::{ + dpp::{ + prelude::CoreBlockHeight, + util::vec::{decode_hex, encode_hex}, + }, + error::ContextProviderError, + platform::{DataContract, Identifier}, +}; +use drive_proof_verifier::ContextProvider; +use wasm_bindgen::prelude::wasm_bindgen; + +#[wasm_bindgen] +pub struct WasmContext {} +const QUORUM_KEYS: [&str; 24] = [ +"000000000000001c39ed197e4a7237dae2c3610de4ad6cbd2cf3a2fedd4b37d8:aac3de572143b96ea5de4a8bc77f17717d05553a305a6ae1e57ed0c59e0f387c5642d8cb85271c04640c8085c597f8ea", +"00000000000000120c0f7e2c576c08a15eaf1dd1159594cf50f9f9a632611309:86889be75ddc191996a061290da4971f7a22d585572b65ba32f8b16ea5187d2917890cb56c3bcf8ed1fd1c8f673bf767", +"00000000000000200c069dadfb37bb391407dab75912a0d17758a3e628c6d9d2:8a85e425a90f6e63f814837504a07d42d9911a03c03e98f8c0e0d4b97195e7fc734818f961f0551be659593753a11884", +"00000000000000213d0d942055b2f9b7b4af09ebd69f797862028a654f13f5b2:a5d49094a236732369e009251d9e8a3b39e6b26edd13895554118862ff5cafd78fb1b6d01437b5101a346494631a8c0f", +"00000000000000208e509567c6ddcac62e0a15cd07bf7b22aea6716576501ab2:ad701bf7c7027316cbfe54e9cf5a94852d48815adf2c795604b166299a5ae275a3f545347c7d7f614f05dcab5726b81b", +"0000000000000013720d5bfb69d50f7f364a2ea8b19caee40ace7d6aaf6e7a3e:96369462a670f0ce1297380e8a6bc1a710a25435c14807ecc78b3303dfb54db7218a11f0e9d3e4c560a740eaa999c576", +"000000000000001e25c58123f4d9219bdd6f91461041f6773bb605e0fff24842:b6a6fd74e744f680ba232c5a99fb76a84872c22cbcb60cf59894b8bb702e72d91e48a9c708fec208c3e04eeb97b048b3", +"000000000000001ffe6bce8e619487eca6044a1311155bd6d2d29358d4d387e3:a390dabce666a8128c55df2bb35057142788730abc43a0a6cf83c34a04180a0c9ecfc86888ad82fec104389ef35367e4", +"000000000000000d414a755d13e334e62aab935d218a9ebc83cec63ba0e4e53d:b87915ae41f3de8403266124f261db3a611ce03de7754c445e1ff0ae59173afb2fb633dd90a74696cb7c244d4dddb634", +"0000000000000012356e7671a39ae2034b355464e6125d90bb8e06d532c8bfc5:8530e55f3501b71d73a6954681867d53586f68d2e486860ecd47715344b5cfa30cc7907059a394cfac1193b4585473c2", +"00000000000000181ee33ebca476252349b4b72dca8264e58551d9da627a408e:a8c440998e5280791055f79cf37b9dcfe5aa9a250b64ebc8f3e48a1010aeb727845aa2540d0ee877212377dfd5b7494f", +"000000000000000bc70fac79f49e92742df030e830ee5b3b0a326a125d9bc46c:a5cc8af818ba0d9afe36cfec0b0c165a6b01b1d84d186e633ca41dda1f20b73fa72a2248ae2a8b50c203bba54af78f36", +"000000000000000ec3c9aebcfda407e2c76b8ebc53c6e49aaf77918a60ec37f9:b677a5128d96eb3ee91e26278c2a920dc70e68e43f4dfb6e57e7cbcc325c0e6de7c156fe10315cf0495588c2a80f507f", +"00000000000000224f402057a58bac46c704f3203e965eef1af244886e61cdfd:8ab4685a79a42ebdd181fdfdb08b267727a1a2c20f4d0ccd737f2fba2ae31f95eb4fe02807fce029899e4597c08d5c71", +"00000000000000096492426de8f080c23a4d72553be7118d3946de0fe8e42a5f:a487fc21b82f1959ad0c4ca5b66e3f15b15a748353d766e9d2f20fb1761be195bbf87754a825276102186e535f05db12", +"000000000000001fd4e2014cc8ca0a7b4aec1261494bbc0da8be1b5e7c44b9f5:ae26bb3e7af269d090bc4693021463e92f1be0de2ebca0694d137686a126f1f1d8416f26401cf74b99fb0c43d9e97ce9", +"000000000000000efdac1744c4ce8d0dbaabfd3a15f191e996beaf13b4839452:b81926d646be3755c650db5854a54a2dfee93f7c304caa212aa8f4ad5c7ad30d997717f60fe4dac583796dc70c86e8b9", +"000000000000000a750cf992ff18e9075a7368598231ae5e8d6cea2cc69d5cd8:ac8977096d7db7ac1e00dcc7fb86035217bd573709fb6236eb0654dfb4304ee62681ec63dbf9743d460c1e8434b12ed8", +"0000000000000002618a958dc306a644b736090f67b166d20d0af708368ea589:860df9186ad46b05ff3b55fbdcb21b17e9be416521b3df18ccaa0c06b7d5a7680de84e33bbe8481c57623db0a45f8dea", +"000000000000001431cf0358d7e9ff3bba83519fe4591a3798202046cb4b5e44:8766b15a9528d7f2d15c5aa92edf26d3ba41dd7e7fc79fe907a5da442025417d85bb2de9d4cbfb6b35d56495fa152e04", +"000000000000000f4acb9a7cd545317fb02d274202aeecdb34086a96c3151b74:b5e00dab44c054bd599c7c3e43ce3bca718bfc592b56f023cc848ddc217e6adee49aa06426f7c93454aa9759b06310d6", +"000000000000001058756a0050fed87fa811e6dbcc999759b14d121e2423ae7c:b3508952323926f552ec3829b6234e9480452afaf3fa10c2f423f0804fc7adffb4c8fd94c8507fc83e7cb56fd4678559", +"00000000000000166250396062788a2b678ef54118ab17447a4cf61f232f0df8:ac692ac97e00caddd4bb3abbeafb3e0824e5c1d91b670a18641fbc86193ccf812e816a838849dadfa72747cc48b9972b", +"000000000000001750f53fa70609db2a8d1dc53603168d3610acd7e9cde401e6:961f67dde80d7d9055138bbe778344d3afd6e5516b2375b73d55d34fbca0f43f92b5a60ad4021bb6823a8d548fc9886c", +]; + +impl ContextProvider for WasmContext { + fn get_quorum_public_key( + &self, + _quorum_type: u32, + quorum_hash: [u8; 32], + _core_chain_locked_height: u32, + ) -> Result<[u8; 48], ContextProviderError> { + let quorum_label = encode_hex(&quorum_hash) + ":"; + let key_hex = QUORUM_KEYS + .iter() + .find(|key| key.starts_with(&quorum_label)) + .ok_or(ContextProviderError::InvalidQuorum(format!( + "key for quorum {:?} not found in hardcoded dictionary", + &quorum_label[0..quorum_label.len() - 1] + )))?; + let key = decode_hex(&key_hex[quorum_label.len()..]) + .map_err(|e| ContextProviderError::InvalidQuorum(e.to_string()))? + .try_into() + .map_err(|_e| { + ContextProviderError::InvalidQuorum("invalid quorum key size".to_string()) + })?; + + Ok(key) + } + + fn get_data_contract( + &self, + _id: &Identifier, + ) -> Result>, ContextProviderError> { + todo!() + } + + fn get_platform_activation_height(&self) -> Result { + todo!() + } +} diff --git a/packages/wasm-sdk/src/lib.rs b/packages/wasm-sdk/src/lib.rs index c2fef6a4112..059d1fe55fb 100644 --- a/packages/wasm-sdk/src/lib.rs +++ b/packages/wasm-sdk/src/lib.rs @@ -1,5 +1,6 @@ use wasm_bindgen::{prelude::wasm_bindgen, JsValue}; +pub mod context_provider; pub mod error; pub mod sdk; pub mod state_transitions; @@ -15,12 +16,8 @@ static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen(start)] pub async fn start() -> Result<(), JsValue> { - let dash_sdk = sdk::WasmSdkBuilder::new_mainnet(); - let sdk = dash_sdk - .with_context_provider(verify::WasmContext {}) - .build() - .expect("build sdk"); + console_error_panic_hook::set_once(); + tracing_wasm::set_as_global_default(); - sdk::identity_fetch(&sdk).await; Ok(()) } diff --git a/packages/wasm-sdk/src/sdk.rs b/packages/wasm-sdk/src/sdk.rs index 5e4686af814..fadb1d520d6 100644 --- a/packages/wasm-sdk/src/sdk.rs +++ b/packages/wasm-sdk/src/sdk.rs @@ -1,3 +1,5 @@ +use crate::context_provider::WasmContext; +use crate::error::WasmError; use dash_sdk::dpp::dashcore::{Network, PrivateKey}; use dash_sdk::dpp::identity::signer::Signer; use dash_sdk::dpp::identity::IdentityV0; @@ -5,13 +7,12 @@ use dash_sdk::dpp::prelude::AssetLockProof; use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; use dash_sdk::platform::transition::put_identity::PutIdentity; use dash_sdk::platform::{Fetch, Identifier, Identity}; -use dash_sdk::{sdk, Sdk, SdkBuilder}; +use dash_sdk::{Sdk, SdkBuilder}; use std::collections::BTreeMap; +use std::fmt::{Debug, Display}; use std::ops::{Deref, DerefMut}; use wasm_bindgen::prelude::wasm_bindgen; - -use crate::error::WasmError; -use crate::verify::WasmContext; +use web_sys::window; #[wasm_bindgen] pub struct WasmSdk(Sdk); @@ -54,17 +55,16 @@ impl DerefMut for WasmSdkBuilder { #[wasm_bindgen] impl WasmSdkBuilder { pub fn new_mainnet() -> Self { - std::panic::set_hook(Box::new(console_error_panic_hook::hook)); - WasmSdkBuilder(SdkBuilder::new_mainnet()) + let sdk_builder = SdkBuilder::new_mainnet().with_context_provider(WasmContext {}); + + Self(sdk_builder) } pub fn new_testnet() -> Self { - std::panic::set_hook(Box::new(console_error_panic_hook::hook)); WasmSdkBuilder(SdkBuilder::new_testnet()) } pub fn build(self) -> Result { - std::panic::set_hook(Box::new(console_error_panic_hook::hook)); Ok(WasmSdk(self.0.build()?)) } @@ -74,13 +74,34 @@ impl WasmSdkBuilder { } #[wasm_bindgen] -pub async fn identity_fetch(sdk: &WasmSdk) { - let id = Identifier::from_bytes(&[0; 32]).expect("create identifier"); +// TODO: return -> wasm_dpp::IdentityWasm +pub async fn identity_fetch(sdk: &WasmSdk, base58_id: &str) { + let id = Identifier::from_string( + base58_id, + dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58, + ) + .expect("parse identity id"); let identity = Identity::fetch_by_identifier(sdk, id) .await .expect("fetch identity") - .expect("identity not found"); + .unwrap_or_else(|| panic!("identity {} not found", id)); + + display_in_browser(&format!("{:?}", identity)); + // >::from(identity) +} + +/// Helper to display results +fn display_in_browser(s: &D) { + // Get the document object + let document = window().unwrap().document().unwrap(); + + // Create a new div element with our message + let div = document.create_element("div").unwrap(); + div.set_text_content(Some(&s.to_string())); + + // Append the div to the body + document.body().unwrap().append_child(&div).unwrap(); } pub async fn identity_put(sdk: &WasmSdk) { @@ -98,7 +119,7 @@ pub async fn identity_put(sdk: &WasmSdk) { PrivateKey::from_slice(&[0; 32], Network::Testnet).expect("create private key"); let signer = MockSigner; - let pushed: Identity = identity + let _pushed: Identity = identity .put_to_platform( sdk, asset_lock_proof, @@ -171,13 +192,13 @@ pub async fn identity_put(sdk: &WasmSdk) { #[derive(Clone, Debug)] struct MockSigner; impl Signer for MockSigner { - fn can_sign_with(&self, identity_public_key: &dash_sdk::platform::IdentityPublicKey) -> bool { + fn can_sign_with(&self, _identity_public_key: &dash_sdk::platform::IdentityPublicKey) -> bool { true } fn sign( &self, - identity_public_key: &dash_sdk::platform::IdentityPublicKey, - data: &[u8], + _identity_public_key: &dash_sdk::platform::IdentityPublicKey, + _data: &[u8], ) -> Result { todo!() } diff --git a/packages/wasm-sdk/src/verify.rs b/packages/wasm-sdk/src/verify.rs index ef07010ce3b..88cf00000b3 100644 --- a/packages/wasm-sdk/src/verify.rs +++ b/packages/wasm-sdk/src/verify.rs @@ -5,7 +5,6 @@ use dash_sdk::dpp::document::{Document, DocumentV0Getters}; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::identity::Identity; use dash_sdk::dpp::platform_value::string_encoding::Encoding; -use dash_sdk::dpp::prelude::*; use dash_sdk::dpp::serialization::PlatformDeserializableWithPotentialValidationFromVersionedStructure; use dash_sdk::dpp::version::PlatformVersion; use dash_sdk::platform::proto::get_identity_request::{ @@ -18,16 +17,14 @@ use dash_sdk::platform::proto::{ GetDocumentsResponse, GetIdentityRequest, Proof, ResponseMetadata, }; use dash_sdk::platform::DocumentQuery; -use drive_proof_verifier::error::ContextProviderError; use drive_proof_verifier::types::Documents; -use drive_proof_verifier::{ContextProvider, FromProof}; -use std::sync::Arc; +use drive_proof_verifier::FromProof; use wasm_bindgen::prelude::wasm_bindgen; +use crate::context_provider::WasmContext; + #[wasm_bindgen] pub async fn verify_identity_response() -> Option { - let id = Identifier::from_bytes(&[0; 32]).expect("create identifier"); - let request = dash_sdk::dapi_grpc::platform::v0::GetIdentityRequest { version: Some(GetIdentityRequestVersion::V0(GetIdentityRequestV0 { id: vec![], @@ -58,7 +55,7 @@ pub async fn verify_identity_response() -> Option { let context = WasmContext {}; - let (response, metadata, proof) = + let (response, _metadata, _proof) = >::maybe_from_proof_with_metadata( request, response, @@ -210,28 +207,3 @@ impl DocumentWasm { self.0.id().to_string(Encoding::Base58) } } - -#[wasm_bindgen] -pub struct WasmContext {} - -impl ContextProvider for WasmContext { - fn get_quorum_public_key( - &self, - quorum_type: u32, - quorum_hash: [u8; 32], - core_chain_locked_height: u32, - ) -> Result<[u8; 48], ContextProviderError> { - todo!() - } - - fn get_data_contract( - &self, - id: &Identifier, - ) -> Result>, ContextProviderError> { - todo!() - } - - fn get_platform_activation_height(&self) -> Result { - todo!() - } -} From 1d3fe7508e8300d53c1fe333a1b858406b7b2eb0 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 6 Jan 2025 13:06:41 +0100 Subject: [PATCH 11/26] chore: update quorum keys --- packages/wasm-sdk/src/context_provider.rs | 73 +++++++++++++++-------- 1 file changed, 48 insertions(+), 25 deletions(-) diff --git a/packages/wasm-sdk/src/context_provider.rs b/packages/wasm-sdk/src/context_provider.rs index 1d6989dfe52..ed1d265d37b 100644 --- a/packages/wasm-sdk/src/context_provider.rs +++ b/packages/wasm-sdk/src/context_provider.rs @@ -13,32 +13,55 @@ use wasm_bindgen::prelude::wasm_bindgen; #[wasm_bindgen] pub struct WasmContext {} +/// Quorum keys for the testnet +/// This is a hardcoded list of quorum keys for the testnet. +/// This list was generated using the following script: +/// ```bash +// #!/bin/bash +/// function dash-cli() { +/// docker exec -ti dashmate_2d59c0c6_mainnet-core-1 dash-cli $@ +/// } +/// +/// +/// # Get the list of all quorum hashes +/// quorum_hashes=$(dash-cli quorum list | jq -r '.llmq_100_67[]') +/// +/// count=$(wc -w <<< $quorum_hashes) +/// +/// echo "const QUORUM_KEYS: [&str; $count] = [" +/// # Iterate over each quorum hash and get the respective public key +/// for quorum_hash in $quorum_hashes; do +/// quorum_public_key=$(dash-cli quorum info 4 $quorum_hash | jq -r '.quorumPublicKey') +/// echo "\"$quorum_hash:$quorum_public_key\"," +/// done +/// echo "]; +/// ``` const QUORUM_KEYS: [&str; 24] = [ -"000000000000001c39ed197e4a7237dae2c3610de4ad6cbd2cf3a2fedd4b37d8:aac3de572143b96ea5de4a8bc77f17717d05553a305a6ae1e57ed0c59e0f387c5642d8cb85271c04640c8085c597f8ea", -"00000000000000120c0f7e2c576c08a15eaf1dd1159594cf50f9f9a632611309:86889be75ddc191996a061290da4971f7a22d585572b65ba32f8b16ea5187d2917890cb56c3bcf8ed1fd1c8f673bf767", -"00000000000000200c069dadfb37bb391407dab75912a0d17758a3e628c6d9d2:8a85e425a90f6e63f814837504a07d42d9911a03c03e98f8c0e0d4b97195e7fc734818f961f0551be659593753a11884", -"00000000000000213d0d942055b2f9b7b4af09ebd69f797862028a654f13f5b2:a5d49094a236732369e009251d9e8a3b39e6b26edd13895554118862ff5cafd78fb1b6d01437b5101a346494631a8c0f", -"00000000000000208e509567c6ddcac62e0a15cd07bf7b22aea6716576501ab2:ad701bf7c7027316cbfe54e9cf5a94852d48815adf2c795604b166299a5ae275a3f545347c7d7f614f05dcab5726b81b", -"0000000000000013720d5bfb69d50f7f364a2ea8b19caee40ace7d6aaf6e7a3e:96369462a670f0ce1297380e8a6bc1a710a25435c14807ecc78b3303dfb54db7218a11f0e9d3e4c560a740eaa999c576", -"000000000000001e25c58123f4d9219bdd6f91461041f6773bb605e0fff24842:b6a6fd74e744f680ba232c5a99fb76a84872c22cbcb60cf59894b8bb702e72d91e48a9c708fec208c3e04eeb97b048b3", -"000000000000001ffe6bce8e619487eca6044a1311155bd6d2d29358d4d387e3:a390dabce666a8128c55df2bb35057142788730abc43a0a6cf83c34a04180a0c9ecfc86888ad82fec104389ef35367e4", -"000000000000000d414a755d13e334e62aab935d218a9ebc83cec63ba0e4e53d:b87915ae41f3de8403266124f261db3a611ce03de7754c445e1ff0ae59173afb2fb633dd90a74696cb7c244d4dddb634", -"0000000000000012356e7671a39ae2034b355464e6125d90bb8e06d532c8bfc5:8530e55f3501b71d73a6954681867d53586f68d2e486860ecd47715344b5cfa30cc7907059a394cfac1193b4585473c2", -"00000000000000181ee33ebca476252349b4b72dca8264e58551d9da627a408e:a8c440998e5280791055f79cf37b9dcfe5aa9a250b64ebc8f3e48a1010aeb727845aa2540d0ee877212377dfd5b7494f", -"000000000000000bc70fac79f49e92742df030e830ee5b3b0a326a125d9bc46c:a5cc8af818ba0d9afe36cfec0b0c165a6b01b1d84d186e633ca41dda1f20b73fa72a2248ae2a8b50c203bba54af78f36", -"000000000000000ec3c9aebcfda407e2c76b8ebc53c6e49aaf77918a60ec37f9:b677a5128d96eb3ee91e26278c2a920dc70e68e43f4dfb6e57e7cbcc325c0e6de7c156fe10315cf0495588c2a80f507f", -"00000000000000224f402057a58bac46c704f3203e965eef1af244886e61cdfd:8ab4685a79a42ebdd181fdfdb08b267727a1a2c20f4d0ccd737f2fba2ae31f95eb4fe02807fce029899e4597c08d5c71", -"00000000000000096492426de8f080c23a4d72553be7118d3946de0fe8e42a5f:a487fc21b82f1959ad0c4ca5b66e3f15b15a748353d766e9d2f20fb1761be195bbf87754a825276102186e535f05db12", -"000000000000001fd4e2014cc8ca0a7b4aec1261494bbc0da8be1b5e7c44b9f5:ae26bb3e7af269d090bc4693021463e92f1be0de2ebca0694d137686a126f1f1d8416f26401cf74b99fb0c43d9e97ce9", -"000000000000000efdac1744c4ce8d0dbaabfd3a15f191e996beaf13b4839452:b81926d646be3755c650db5854a54a2dfee93f7c304caa212aa8f4ad5c7ad30d997717f60fe4dac583796dc70c86e8b9", -"000000000000000a750cf992ff18e9075a7368598231ae5e8d6cea2cc69d5cd8:ac8977096d7db7ac1e00dcc7fb86035217bd573709fb6236eb0654dfb4304ee62681ec63dbf9743d460c1e8434b12ed8", -"0000000000000002618a958dc306a644b736090f67b166d20d0af708368ea589:860df9186ad46b05ff3b55fbdcb21b17e9be416521b3df18ccaa0c06b7d5a7680de84e33bbe8481c57623db0a45f8dea", -"000000000000001431cf0358d7e9ff3bba83519fe4591a3798202046cb4b5e44:8766b15a9528d7f2d15c5aa92edf26d3ba41dd7e7fc79fe907a5da442025417d85bb2de9d4cbfb6b35d56495fa152e04", -"000000000000000f4acb9a7cd545317fb02d274202aeecdb34086a96c3151b74:b5e00dab44c054bd599c7c3e43ce3bca718bfc592b56f023cc848ddc217e6adee49aa06426f7c93454aa9759b06310d6", -"000000000000001058756a0050fed87fa811e6dbcc999759b14d121e2423ae7c:b3508952323926f552ec3829b6234e9480452afaf3fa10c2f423f0804fc7adffb4c8fd94c8507fc83e7cb56fd4678559", -"00000000000000166250396062788a2b678ef54118ab17447a4cf61f232f0df8:ac692ac97e00caddd4bb3abbeafb3e0824e5c1d91b670a18641fbc86193ccf812e816a838849dadfa72747cc48b9972b", -"000000000000001750f53fa70609db2a8d1dc53603168d3610acd7e9cde401e6:961f67dde80d7d9055138bbe778344d3afd6e5516b2375b73d55d34fbca0f43f92b5a60ad4021bb6823a8d548fc9886c", -]; + "0000000000000028113a56cdec51df03d0a4786886455b56c405888820ef0941:a9cc0b5debb51078cc74666ce230512b5cc8a210e92e7a61143a94f2d39e0f2396fdb8a236f9e4f08bb9f9efade56aa0", + "000000000000001ca970d7cd594bba828499c114e7c414ffd76ca2472dbb628c:878251f1d4c7d126877159edf7393f1bc7f7fa8cd6a90b4b533bd464ba89c7439fd39e405a3ef9bb629c46a2150826f0", + "0000000000000008a01171418cdd051431ee153871a919a66c2c0ad0c879cf26:9919eaf780965b8ca0ec77b53c50b72cc382b3e8411c347f9f08c7285d77c44ba7fa07a023258b15f024fecf6332c5b7", + "0000000000000019d45a8e21c319cc0697798a5fb3beaf613d33bf960d6a6cbd:8132c57180bcfa1849837b28688c89e0e9547c637f8da62d7f5f48b6ad2f51ff3fc9466040b5a69e956a6814e09952ae", + "0000000000000005b46622b4f786df8170e3c72d56642d0959acc76f4798bfd6:8d75addd7d32795eaeeb63c65a15c4f61062e340cfcac56d915f387500714bb70db51791d2e9a6b3435e3dacb60ba98e", + "0000000000000001fce9c7c2a8b0f12827dad4b7e4748425ccb55ce21dd2bb1b:8c2d30a0becc4bc12b8cdcaea76c0b86b66cc1fce837acdc0f213af4c6ea2fb6606f65bd640316803b9c68e3c7228910", + "000000000000001abb166439088af6adefea719f6db41239bf336a00145fac4b:b4e1cb36f6d8fe47194aa6d266e1fcc31396b68a2cb48c55c9e6503933bfd699683e90f0a468df3ff037405038597a28", + "0000000000000014e8b2bfe48594251aab8f21db05d8ae8a87e071e8fc3e3cfb:ac0d4951a1405850593a90ac0f74049778b89a547b98aafbe1dd4685e3274d6700f2d886990bdf69de7fdcd6dd1e5ee8", + "000000000000000b11fd2c3cdb0a31bf6e8c6811f7f57ebc715dcc9fff4c619b:85bd11bb6eae1fdf8ba7373315ce4841354c295a052bad29c91f2c9b795e7ff14810651f474863b509e97a217e3cf3c5", + "000000000000000729844808a669505fd8281e7e965eb441a036fe6cbeb4693f:83757a46d09089db700dc49acf3ad009330bb349d6ec9235cd92c0a397474bb44f225b5d2dfca6388ce6bdc2b96a5926", + "0000000000000002440753acfe1a9a8632cd53324b21d7212362ba924a7b4cc8:ae108342f52fdf86ede01f6b815636337a05e824000071c60b26c98b9fc7d29fada982b4eaaedd61269372182b9cfc95", + "000000000000000afc58484fac033caa1aa088c96c01d450ae1de8cd8dd38a6e:8c6dba5bde17750d929bbabd2ab1dc15773166d5bba79dafceff8e9a799e7c7492c0c798133b6ea574f0bb09b7c07a77", + "000000000000001b84665ddc7527b20198e2462f103d397bdb02334c20a2be22:96d0333a2bf0db2e8a502104a1f0f8442648ff040c485f7da7d8a0703995f44e6759052b005ed64f49e97a5503ad88be", + "000000000000001b9fd42c73a767c026d44dbf269da97f3688b28beb06cc986d:952752cc09be8d537fc8c43266e91b44d875b84c15741b054889b26c65f6f251742424839ef42c6fe74479630d14b160", + "000000000000000a845c3966ddd0f2beb4742fe5879a4513b79dba8f19d12da0:937d433ed5df63877d59ec94fb096fa740cc517b9cec5253a6af911da394fcacf55bfeb9ac3930d0aa3fa5fe8248d9d0", + "000000000000000ae3bf646448897ea0a322518901faaee8f2f1e02027f251d8:a662eb0b193880570455c1e7a189b46348e49a50becf6f07b2a34d2c50923e4875888be19e0a315421ccc92e47c7c3f4", + "0000000000000003eb7db84bf0a0b8e526778844dcb5a10740dbe75f8fe72562:8d20289962877f6c8b4b1c2c0a9ca054ca1b41b4ae340544d74bac3223404fa7446a8aa116fa2befd37f1e50f3d28d53", + "000000000000000ca431a523ba79b0a040e14af944b50ac68cc3cc9192e6518c:a3c16e1c558a1a9828b2550028f605a3ed6a519022c7a2e7723531e3e622f03759994980fafa9a193a0e784e3b331370", + "00000000000000090aca1303c1455281cdf213107573b6887b28e7faf06b38a4:952520e764930f1c9c7a258a0689e67c9df9911e00777edf3d76b7914a0f0a0047cde86afc55888ead4b797fb8861dae", + "0000000000000021768892dc6eda195c176e3b7afd3537927268e8e5357c44bd:98eaafbc3fda5dd44d61361385f6a1f7ccb228294a7fb2a87072c27959d492eaabff98c60d05df21ab28f4e4147f7d85", + "0000000000000002aa4b5db3552bc3cd2fb52386ea84c713eca9cc11415e6a8e:8199ceaf1b719054432d52ae241819643f97af677b50f12a6c162f0124959597b0c68403421e971db14595a5dc3cf9be", + "00000000000000022c52da255c3d388035a9c4baa0e1b4a3376ca3363eaf96d9:ab40da63160f496fd64e81a58cc45e5b21246f8a5dcbe1f782ae5e8bd30237ed4df5d984c7927db043bc623db8079635", + "000000000000000c49614abc9f87d3122621e26933ebe82d17d94e6aa24f3797:87b5d5cd7a990a1cae0765af7447efeee90e7eb0b67736832c12442230004c5739d9ff8ae19bbac1658931b3136da816", + "000000000000001f1342af01769448b2b4c635a02c420f4844ba9058b52c489e:b826904db02b0edb1798d800d9658677bcdab856e380350b2637254d7a01f022ece44c33a51f4f9fc313071fc0f7e670", + ]; impl ContextProvider for WasmContext { fn get_quorum_public_key( From f6df953db08c1a19fc98337ef8f6bf8b3178f3c6 Mon Sep 17 00:00:00 2001 From: Ivan Shumkov Date: Tue, 7 Jan 2025 19:16:29 +0700 Subject: [PATCH 12/26] chore: demo fetching contract and identity --- Cargo.lock | 15 +- packages/js-dapi-client/package.json | 3 +- packages/rs-dapi-client/src/transport/grpc.rs | 11 + packages/rs-dpp/Cargo.toml | 5 +- .../src/data_contract/data_contract_facade.rs | 17 +- .../rs-dpp/src/identity/identity_facade.rs | 8 +- packages/wasm-sdk/Cargo.toml | 4 +- packages/wasm-sdk/index.html | 129 +++++--- packages/wasm-sdk/src/context_provider.rs | 48 +-- packages/wasm-sdk/src/dpp.rs | 313 ++++++++++++++++++ packages/wasm-sdk/src/error.rs | 6 + packages/wasm-sdk/src/lib.rs | 1 + packages/wasm-sdk/src/sdk.rs | 52 +-- .../src/state_transitions/documents.rs | 5 +- packages/wasm-sdk/src/verify.rs | 25 +- 15 files changed, 502 insertions(+), 140 deletions(-) create mode 100644 packages/wasm-sdk/src/dpp.rs diff --git a/Cargo.lock b/Cargo.lock index d6ef4c5f73d..ea9ac7d8bc0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4429,6 +4429,17 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "serde-wasm-bindgen" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b" +dependencies = [ + "js-sys", + "serde", + "wasm-bindgen", +] + [[package]] name = "serde_bare" version = "0.5.0" @@ -5838,7 +5849,7 @@ dependencies = [ "num_enum 0.7.3", "paste", "serde", - "serde-wasm-bindgen", + "serde-wasm-bindgen 0.5.0", "serde_json", "thiserror 1.0.64", "wasm-bindgen", @@ -5865,6 +5876,8 @@ dependencies = [ "console_error_panic_hook", "dash-sdk", "drive-proof-verifier", + "platform-value", + "serde-wasm-bindgen 0.6.5", "thiserror 2.0.9", "tracing-wasm", "wasm-bindgen", diff --git a/packages/js-dapi-client/package.json b/packages/js-dapi-client/package.json index a5a5ffd8cfe..01339bb5a31 100644 --- a/packages/js-dapi-client/package.json +++ b/packages/js-dapi-client/package.json @@ -82,7 +82,8 @@ "files": [ "docs", "lib", - "polyfills" + "polyfills", + "dist" ], "scripts": { "build:web": "webpack", diff --git a/packages/rs-dapi-client/src/transport/grpc.rs b/packages/rs-dapi-client/src/transport/grpc.rs index c4ffc4f7cbe..ff3887befbb 100644 --- a/packages/rs-dapi-client/src/transport/grpc.rs +++ b/packages/rs-dapi-client/src/transport/grpc.rs @@ -473,6 +473,17 @@ impl_transport_request_grpc!( subscribe_to_transactions_with_proofs ); +impl_transport_request_grpc!( + core_proto::MasternodeListRequest, + Streaming, + CoreGrpcClient, + RequestSettings { + timeout: Some(STREAMING_TIMEOUT), + ..RequestSettings::default() + }, + subscribe_to_masternode_list +); + // rpc getStatus(GetStatusRequest) returns (GetStatusResponse); impl_transport_request_grpc!( platform_proto::GetStatusRequest, diff --git a/packages/rs-dpp/Cargo.toml b/packages/rs-dpp/Cargo.toml index 7931f6aacf2..2575ed4393f 100644 --- a/packages/rs-dpp/Cargo.toml +++ b/packages/rs-dpp/Cargo.toml @@ -125,12 +125,13 @@ dash-sdk-features = [ # "platform-value", # "system_contracts", # "validation", # TODO: This one is big - # "identity-hashing", + "identity-hashing", + "data-contract-json-conversion", # "identity-serialization", # "vote-serialization", # "document-value-conversion", # "data-contract-value-conversion", - # "identity-value-conversion", + "identity-value-conversion", # "core-types", # "core-types-serialization", # "core-types-serde-conversion", diff --git a/packages/rs-dpp/src/data_contract/data_contract_facade.rs b/packages/rs-dpp/src/data_contract/data_contract_facade.rs index d1f606622e3..aa352c47699 100644 --- a/packages/rs-dpp/src/data_contract/data_contract_facade.rs +++ b/packages/rs-dpp/src/data_contract/data_contract_facade.rs @@ -57,10 +57,13 @@ impl DataContractFacade { pub fn create_from_object( &self, raw_data_contract: Value, - skip_validation: bool, + #[cfg(feature = "validation")] skip_validation: bool, ) -> Result { - self.factory - .create_from_object(raw_data_contract, skip_validation) + self.factory.create_from_object( + raw_data_contract, + #[cfg(feature = "validation")] + skip_validation, + ) } /// Create Data Contract from buffer @@ -68,9 +71,13 @@ impl DataContractFacade { pub fn create_from_buffer( &self, buffer: Vec, - skip_validation: bool, + #[cfg(feature = "validation")] skip_validation: bool, ) -> Result { - self.factory.create_from_buffer(buffer, skip_validation) + self.factory.create_from_buffer( + buffer, + #[cfg(feature = "validation")] + skip_validation, + ) } #[cfg(feature = "state-transitions")] diff --git a/packages/rs-dpp/src/identity/identity_facade.rs b/packages/rs-dpp/src/identity/identity_facade.rs index eecdf45e6e2..323fea838dd 100644 --- a/packages/rs-dpp/src/identity/identity_facade.rs +++ b/packages/rs-dpp/src/identity/identity_facade.rs @@ -56,9 +56,13 @@ impl IdentityFacade { pub fn create_from_buffer( &self, buffer: Vec, - skip_validation: bool, + #[cfg(feature = "validation")] skip_validation: bool, ) -> Result { - self.factory.create_from_buffer(buffer, skip_validation) + self.factory.create_from_buffer( + buffer, + #[cfg(feature = "validation")] + skip_validation, + ) } pub fn create_instant_lock_proof( diff --git a/packages/wasm-sdk/Cargo.toml b/packages/wasm-sdk/Cargo.toml index 5890d790d83..39829ebfd4a 100644 --- a/packages/wasm-sdk/Cargo.toml +++ b/packages/wasm-sdk/Cargo.toml @@ -20,7 +20,6 @@ web-sys = { version = "0.3.4", features = [ ] } wasm-bindgen = { version = "=0.2.99" } wasm-bindgen-futures = { version = "0.4.49" } -# wasm-dpp = { path = "../wasm-dpp" } # TODO: breaks build with `invalid type: map, expected a string at line 2 column 18` dash-sdk = { path = "../rs-sdk", default-features = false, features = ["wasm"] } drive-proof-verifier = { path = "../rs-drive-proof-verifier" } # TODO: I think it's not needed (LKl) # tonic = { version = "*", features = ["transport"], default-features = false } @@ -34,6 +33,9 @@ drive-proof-verifier = { path = "../rs-drive-proof-verifier" } # ] tracing-wasm = { version = "0.2.1" } wee_alloc = "0.4" +platform-value = { path = "../rs-platform-value", features = ["json"] } +serde-wasm-bindgen = { version = "0.6.5" } + [profile.release] lto = "fat" opt-level = "z" diff --git a/packages/wasm-sdk/index.html b/packages/wasm-sdk/index.html index b7427954308..f871a8566f5 100644 --- a/packages/wasm-sdk/index.html +++ b/packages/wasm-sdk/index.html @@ -2,61 +2,84 @@ - + + - - +
Loading...
+
+ + +
+ +
+ + +
+
+ + - \ No newline at end of file + diff --git a/packages/wasm-sdk/src/context_provider.rs b/packages/wasm-sdk/src/context_provider.rs index ed1d265d37b..173c8a4948b 100644 --- a/packages/wasm-sdk/src/context_provider.rs +++ b/packages/wasm-sdk/src/context_provider.rs @@ -37,31 +37,31 @@ pub struct WasmContext {} /// echo "]; /// ``` const QUORUM_KEYS: [&str; 24] = [ + "0000000000000010c832afa3f737b24aa0a19cb8c5fa8a7ebd51d195965c204e:a7123c10b0083c96665954dacbc92779b9bf5ee15b6e0b37de6c3ac6b5e611490611fbdf8128ea8012e1b8d79faf70e1", + "000000000000000b7ef1903452e3a0234b893567fe4f0f093b0de655756e413d:a75bca441f781fde0ae048181ab64e5bc85a2541b25267148bced1d1cbc1ff223e9b0d767f06b4a0773b65a7f374f72d", + "000000000000000aaf16a867b579ddbafc421ebf52b991c445aba9d42cc70f62:9665f284f989b998c053e4d34d022d7a9c1744214356150b6b815ba0c4b28dd6312ff3f6d86eb2ab49d84cb2a20518c5", + "00000000000000097177f56b1d83fcaa96101cb3c5e5cc1e624422552265aab0:ab96113d539e30e7f8f1ec605ab9228b6825bef1ea55cdf66826bb8308edf92fa782db1c3c6c348fb2daf5e13422fdff", + "00000000000000210518749e17c00b035a2a4982c906236c28c41ea2231bf7ef:803c3341a037217c6b8d6bf9a1f08b140749039fcbf2bd79d639ee6d70b16c9911f979e6f7014429d1a805876a9cb8dd", + "000000000000000d9085a108ae45615da3fc0b43313959a7fde892bb307d4f6a:ab880781c7ef1b5a38202065a90afc92ff25009f231a16daa766528bf36b78856d2a9a35c4d396326df434eb09fb3897", + "000000000000001871d3dab13ccefca7dd9735c27028e6612e8f1ac16114b080:ae5334bc41a2a2b1b52c8c454957f00a4554fb0ec82e7ca61b9391a4371346ab4679b55a15220af7ea657e153af867be", + "00000000000000223578d6be39205e0cddd36a0c73cde66aee0a7ad4bf451931:986eb45b5cd503f6ae09070b93fbf101ac69999147cce55a2f1f4b04b2aaf0ad7ea57ea96ee3f4335bcdd13dce6577f6", + "000000000000000208d59d5275610de33bca248e4055974573775affb2d99b0a:b4c419af96d4a053e90c6cc3be88c09f47543a8af9b5e94f0e345f91604843a60d8b19d045908b22ce52084f82f3a627", + "00000000000000065644145a3a5f94f9786245f4242a09fadfe277de7059b44a:95bebdad569bfe6c870f6f96c6a5d265f2d8561997b2a8be2d3192ad16ee872b833593a8096d8d7b142ba6ba2f662147", + "000000000000000ab82df09faf91a3e07b756dfc715c309a21feca21dd233559:91ebfc1415bf0e87e88024a1a794735130b8b438abdd29313f26bb3dece7577f77c80b0103a6c97c9a888f8e4334f44a", + "0000000000000023b4287203df6f4e1e67726b4f9bbeeec96a3b2e47227bcf7c:b1cc46b8d00f193238550b035860994e95c1515d95ef675c890bf38257dfc44631cc1da786550c1df7bda83dea17299c", + "000000000000000dd6431b32390b87c7c3c2377c46ecb8be2e36e0625400204b:a84f43efe056cd1221b9d4449dc3d0b3ce2e260f6378790f3e6123903d204ae83589e5a144533eb556acd05f920869a6", + "0000000000000005609c7e47752ff16847a49bd81f12885d3047c26c1d4de394:8f08f63fdd26e3e15f4c6daf45943c6ae097a40f46f4344cea63bcdfa9498525cfe0891c9d04057692738fa8f5e7b30d", + "000000000000001fb29b450739378551cd7539357e0ee49fd93c186eb8dd9db4:8cc74c3c7f10dd11845894dafafe47e60395d40bb151299638736dd078cc1052da13b3676e945d84cd4139a519a37975", + "0000000000000005f3b003f2b70096157046005944b316950c2d6f31a7fbdb6c:82780a7c99e2e09589a42a38e7be3d78d53072b09d964762cd9025b5b0b88bbed7e9e6c294a4fc8310d5025668240eaa", + "000000000000001f7bdf487d9ab675b9d4c53d8601b2b9dd619cf6f91271c1ef:ac79a22006a9c5d96250bd91784919a65259b5e1cf72af8294a998a420684ab3b9064094f247b0ebf1c5e39a545ac176", + "00000000000000127ae21d0e85ab8f511309b3492a689e680872d05d3d5e27b9:887332518d8a6d8806dfb1dd9588d2d4a2ec80193b5357ed87fc49567a72752ec8022dfaf4f5dec22c85aff4139daeb3", + "000000000000001c5d877e4b2b5964277c71377acd0e83d2b949426b54b761a2:a7149631eed0fdef466de0360ae09700b96fc29e76d46465efe60677596e7f93f8ff5e5e39917e04a3a26febe12b3b8a", + "000000000000000dab4691b25d967682b1902c05eefe691312cf520f6f2a3063:acc45cbf3ead9a04347438a68d72f86ffec76211562786f86125bbc2a444026343149cfb3d21fd27b386b50094250099", + "000000000000001aad53ced4755062f69421f7ca6c0bbe259e2626738c310759:8037c5282d443eb274a819a1d83758b29a97c12fdbbfa65a255e460045e71d9a5301f96ae76743787b12edf4f4e79e1c", + "0000000000000003e9cc2a59ebbede397e73e951f0968d4c94e04a92edb5586f:a62305e5154688adcc129da4a11bd0da388a731e52a361896f27473056d4dccb3642526086f83f36accbcaea43468121", + "000000000000001fd65c58acf87be67925c89348c5a76cc61cb467bbd9991a80:818283cbc34445f0c294d8ac071d4e43099fd318dad53337cd1daccc8a2aa760ee108c80f3f3c5bb01c41bba69ab2e8b", "0000000000000028113a56cdec51df03d0a4786886455b56c405888820ef0941:a9cc0b5debb51078cc74666ce230512b5cc8a210e92e7a61143a94f2d39e0f2396fdb8a236f9e4f08bb9f9efade56aa0", - "000000000000001ca970d7cd594bba828499c114e7c414ffd76ca2472dbb628c:878251f1d4c7d126877159edf7393f1bc7f7fa8cd6a90b4b533bd464ba89c7439fd39e405a3ef9bb629c46a2150826f0", - "0000000000000008a01171418cdd051431ee153871a919a66c2c0ad0c879cf26:9919eaf780965b8ca0ec77b53c50b72cc382b3e8411c347f9f08c7285d77c44ba7fa07a023258b15f024fecf6332c5b7", - "0000000000000019d45a8e21c319cc0697798a5fb3beaf613d33bf960d6a6cbd:8132c57180bcfa1849837b28688c89e0e9547c637f8da62d7f5f48b6ad2f51ff3fc9466040b5a69e956a6814e09952ae", - "0000000000000005b46622b4f786df8170e3c72d56642d0959acc76f4798bfd6:8d75addd7d32795eaeeb63c65a15c4f61062e340cfcac56d915f387500714bb70db51791d2e9a6b3435e3dacb60ba98e", - "0000000000000001fce9c7c2a8b0f12827dad4b7e4748425ccb55ce21dd2bb1b:8c2d30a0becc4bc12b8cdcaea76c0b86b66cc1fce837acdc0f213af4c6ea2fb6606f65bd640316803b9c68e3c7228910", - "000000000000001abb166439088af6adefea719f6db41239bf336a00145fac4b:b4e1cb36f6d8fe47194aa6d266e1fcc31396b68a2cb48c55c9e6503933bfd699683e90f0a468df3ff037405038597a28", - "0000000000000014e8b2bfe48594251aab8f21db05d8ae8a87e071e8fc3e3cfb:ac0d4951a1405850593a90ac0f74049778b89a547b98aafbe1dd4685e3274d6700f2d886990bdf69de7fdcd6dd1e5ee8", - "000000000000000b11fd2c3cdb0a31bf6e8c6811f7f57ebc715dcc9fff4c619b:85bd11bb6eae1fdf8ba7373315ce4841354c295a052bad29c91f2c9b795e7ff14810651f474863b509e97a217e3cf3c5", - "000000000000000729844808a669505fd8281e7e965eb441a036fe6cbeb4693f:83757a46d09089db700dc49acf3ad009330bb349d6ec9235cd92c0a397474bb44f225b5d2dfca6388ce6bdc2b96a5926", - "0000000000000002440753acfe1a9a8632cd53324b21d7212362ba924a7b4cc8:ae108342f52fdf86ede01f6b815636337a05e824000071c60b26c98b9fc7d29fada982b4eaaedd61269372182b9cfc95", - "000000000000000afc58484fac033caa1aa088c96c01d450ae1de8cd8dd38a6e:8c6dba5bde17750d929bbabd2ab1dc15773166d5bba79dafceff8e9a799e7c7492c0c798133b6ea574f0bb09b7c07a77", - "000000000000001b84665ddc7527b20198e2462f103d397bdb02334c20a2be22:96d0333a2bf0db2e8a502104a1f0f8442648ff040c485f7da7d8a0703995f44e6759052b005ed64f49e97a5503ad88be", - "000000000000001b9fd42c73a767c026d44dbf269da97f3688b28beb06cc986d:952752cc09be8d537fc8c43266e91b44d875b84c15741b054889b26c65f6f251742424839ef42c6fe74479630d14b160", - "000000000000000a845c3966ddd0f2beb4742fe5879a4513b79dba8f19d12da0:937d433ed5df63877d59ec94fb096fa740cc517b9cec5253a6af911da394fcacf55bfeb9ac3930d0aa3fa5fe8248d9d0", - "000000000000000ae3bf646448897ea0a322518901faaee8f2f1e02027f251d8:a662eb0b193880570455c1e7a189b46348e49a50becf6f07b2a34d2c50923e4875888be19e0a315421ccc92e47c7c3f4", - "0000000000000003eb7db84bf0a0b8e526778844dcb5a10740dbe75f8fe72562:8d20289962877f6c8b4b1c2c0a9ca054ca1b41b4ae340544d74bac3223404fa7446a8aa116fa2befd37f1e50f3d28d53", - "000000000000000ca431a523ba79b0a040e14af944b50ac68cc3cc9192e6518c:a3c16e1c558a1a9828b2550028f605a3ed6a519022c7a2e7723531e3e622f03759994980fafa9a193a0e784e3b331370", - "00000000000000090aca1303c1455281cdf213107573b6887b28e7faf06b38a4:952520e764930f1c9c7a258a0689e67c9df9911e00777edf3d76b7914a0f0a0047cde86afc55888ead4b797fb8861dae", - "0000000000000021768892dc6eda195c176e3b7afd3537927268e8e5357c44bd:98eaafbc3fda5dd44d61361385f6a1f7ccb228294a7fb2a87072c27959d492eaabff98c60d05df21ab28f4e4147f7d85", - "0000000000000002aa4b5db3552bc3cd2fb52386ea84c713eca9cc11415e6a8e:8199ceaf1b719054432d52ae241819643f97af677b50f12a6c162f0124959597b0c68403421e971db14595a5dc3cf9be", - "00000000000000022c52da255c3d388035a9c4baa0e1b4a3376ca3363eaf96d9:ab40da63160f496fd64e81a58cc45e5b21246f8a5dcbe1f782ae5e8bd30237ed4df5d984c7927db043bc623db8079635", - "000000000000000c49614abc9f87d3122621e26933ebe82d17d94e6aa24f3797:87b5d5cd7a990a1cae0765af7447efeee90e7eb0b67736832c12442230004c5739d9ff8ae19bbac1658931b3136da816", - "000000000000001f1342af01769448b2b4c635a02c420f4844ba9058b52c489e:b826904db02b0edb1798d800d9658677bcdab856e380350b2637254d7a01f022ece44c33a51f4f9fc313071fc0f7e670", - ]; +]; impl ContextProvider for WasmContext { fn get_quorum_public_key( diff --git a/packages/wasm-sdk/src/dpp.rs b/packages/wasm-sdk/src/dpp.rs new file mode 100644 index 00000000000..678f2c23b56 --- /dev/null +++ b/packages/wasm-sdk/src/dpp.rs @@ -0,0 +1,313 @@ +use dash_sdk::dpp::identity::accessors::{IdentityGettersV0, IdentitySettersV0}; +use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; +use dash_sdk::dpp::identity::{IdentityPublicKey, KeyID}; +use dash_sdk::dpp::metadata::Metadata; +use dash_sdk::dpp::platform_value::ReplacementType; +use dash_sdk::dpp::serialization::PlatformDeserializable; +use dash_sdk::dpp::serialization::PlatformSerializable; +use dash_sdk::dpp::serialization::ValueConvertible; + +use crate::error::{to_js_error, WasmError}; +use dash_sdk::dashcore_rpc::dashcore::hashes::serde::Serialize; +use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; +use dash_sdk::dpp::data_contract::conversion::json::DataContractJsonConversionMethodsV0; +use dash_sdk::dpp::version::PlatformVersion; +use dash_sdk::platform::{DataContract, Identity}; +use dash_sdk::Error; +use platform_value::string_encoding::Encoding; +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsValue; +use web_sys::js_sys; + +#[wasm_bindgen] +#[derive(Clone)] +pub struct IdentityWasm { + inner: Identity, + // metadata: Option, +} + +impl From for Identity { + fn from(identity: IdentityWasm) -> Self { + identity.inner + } +} + +impl From for IdentityWasm { + fn from(identity: Identity) -> Self { + Self { + inner: identity, + // metadata: None, + } + } +} +#[wasm_bindgen] +impl IdentityWasm { + #[wasm_bindgen(constructor)] + pub fn new(platform_version: u32) -> Result { + let platform_version = &PlatformVersion::get(platform_version).map_err(to_js_error)?; + + Identity::default_versioned(platform_version) + .map(Into::into) + .map_err(to_js_error) + } + // + // #[wasm_bindgen(js_name=getId)] + // pub fn get_id(&self) -> IdentifierWrapper { + // self.inner.id().into() + // } + // + // #[wasm_bindgen(js_name=setId)] + // pub fn set_id(&mut self, id: IdentifierWrapper) { + // self.inner.set_id(id.into()); + // } + + #[wasm_bindgen(js_name=setPublicKeys)] + pub fn set_public_keys(&mut self, public_keys: js_sys::Array) -> Result { + if public_keys.length() == 0 { + return Err(format!("Setting public keys failed. The input ('{}') is invalid. You must use array of PublicKeys", public_keys.to_string()).into()); + } + + // let public_keys = public_keys + // .iter() + // .map(|key| { + // key.to_wasm::("IdentityPublicKey") + // .map(|key| { + // let key = IdentityPublicKey::from(key.to_owned()); + // (key.id(), key) + // }) + // }) + // .collect::>()?; + // + // self.inner.set_public_keys(public_keys); + + Ok(self.inner.public_keys().len()) + } + // + // #[wasm_bindgen(js_name=getPublicKeys)] + // pub fn get_public_keys(&self) -> Vec { + // self.inner + // .public_keys() + // .iter() + // .map(|(_, k)| k.to_owned()) + // .map(IdentityPublicKeyWasm::from) + // .map(JsValue::from) + // .collect() + // } + // + // #[wasm_bindgen(js_name=getPublicKeyById)] + // pub fn get_public_key_by_id(&self, key_id: u32) -> Option { + // let key_id = key_id as KeyID; + // self.inner + // .get_public_key_by_id(key_id) + // .map(IdentityPublicKey::to_owned) + // .map(Into::into) + // } + + #[wasm_bindgen(getter)] + pub fn balance(&self) -> f64 { + self.inner.balance() as f64 + } + + #[wasm_bindgen(js_name=getBalance)] + pub fn get_balance(&self) -> f64 { + self.inner.balance() as f64 + } + + #[wasm_bindgen(js_name=setBalance)] + pub fn set_balance(&mut self, balance: f64) { + self.inner.set_balance(balance as u64); + } + + #[wasm_bindgen(js_name=increaseBalance)] + pub fn increase_balance(&mut self, amount: f64) -> f64 { + self.inner.increase_balance(amount as u64) as f64 + } + + #[wasm_bindgen(js_name=reduceBalance)] + pub fn reduce_balance(&mut self, amount: f64) -> f64 { + self.inner.reduce_balance(amount as u64) as f64 + } + + #[wasm_bindgen(js_name=setRevision)] + pub fn set_revision(&mut self, revision: f64) { + self.inner.set_revision(revision as u64); + } + + #[wasm_bindgen(js_name=getRevision)] + pub fn get_revision(&self) -> f64 { + self.inner.revision() as f64 + } + // + // #[wasm_bindgen(js_name=setMetadata)] + // pub fn set_metadata(&mut self, metadata: JsValue) -> Result<(), JsValue> { + // if !metadata.is_falsy() { + // let metadata = metadata.to_wasm::("Metadata")?.to_owned(); + // self.metadata = Some(metadata.into()); + // } + // + // Ok(()) + // } + // + // #[wasm_bindgen(js_name=getMetadata)] + // pub fn get_metadata(&self) -> Option { + // self.metadata.map(|metadata| metadata.to_owned().into()) + // } + + // #[wasm_bindgen(js_name=from)] + // pub fn from(object: JsValue) -> Self { + // let i: Identity = serde_json::from_str(&object.as_string().unwrap()).unwrap(); + // IdentityWasm { + // inner: i, + // metadata: None, + // } + // } + + #[wasm_bindgen(js_name=toJSON)] + pub fn to_json(&self) -> Result { + let mut value = self.inner.to_object().map_err(to_js_error)?; + + value + .replace_at_paths( + dash_sdk::dpp::identity::IDENTIFIER_FIELDS_RAW_OBJECT, + ReplacementType::TextBase58, + ) + .map_err(|e| e.to_string())?; + + // Monkey patch public keys data to be deserializable + let public_keys = value + .get_array_mut_ref(dash_sdk::dpp::identity::property_names::PUBLIC_KEYS) + .map_err(|e| e.to_string())?; + + for key in public_keys.iter_mut() { + key.replace_at_paths( + dash_sdk::dpp::identity::identity_public_key::BINARY_DATA_FIELDS, + ReplacementType::TextBase64, + ) + .map_err(|e| e.to_string())?; + } + + let json = value + .try_into_validating_json() + .map_err(|e| e.to_string())? + .to_string(); + + js_sys::JSON::parse(&json) + } + // + // #[wasm_bindgen(js_name=toObject)] + // pub fn to_object(&self) -> Result { + // let js_public_keys = js_sys::Array::new(); + // for pk in self.inner.public_keys().values() { + // let pk_wasm = IdentityPublicKeyWasm::from(pk.to_owned()); + // js_public_keys.push(&pk_wasm.to_object()?); + // } + // + // let value = self.inner.to_object().with_js_error()?; + // + // let serializer = serde_wasm_bindgen::Serializer::json_compatible(); + // let js_object = with_js_error!(value.serialize(&serializer))?; + // + // let id = Buffer::from_bytes(self.inner.id().as_slice()); + // + // js_sys::Reflect::set(&js_object, &"id".to_owned().into(), &id)?; + // + // js_sys::Reflect::set( + // &js_object, + // &"publicKeys".to_owned().into(), + // &JsValue::from(&js_public_keys), + // )?; + // + // Ok(js_object) + // } + // + // #[wasm_bindgen(js_name=toBuffer)] + // pub fn to_buffer(&self) -> Result { + // let bytes = + // PlatformSerializable::serialize_to_bytes(&self.inner.clone()).with_js_error()?; + // Ok(Buffer::from_bytes(&bytes)) + // } + + #[wasm_bindgen] + pub fn hash(&self) -> Result, JsError> { + self.inner.hash().map_err(to_js_error) + } + + // #[wasm_bindgen(js_name=addPublicKey)] + // pub fn add_public_key(&mut self, public_key: IdentityPublicKeyWasm) { + // self.inner + // .public_keys_mut() + // .insert(public_key.get_id(), public_key.into()); + // } + // + // #[wasm_bindgen(js_name=addPublicKeys)] + // pub fn add_public_keys(&mut self, public_keys: js_sys::Array) -> Result<(), JsValue> { + // if public_keys.length() == 0 { + // return Err(format!("Setting public keys failed. The input ('{}') is invalid. You must use array of PublicKeys", public_keys.to_string()).into()); + // } + // + // let public_keys: Vec = public_keys + // .iter() + // .map(|key| { + // key.to_wasm::("IdentityPublicKey") + // .map(|key| key.to_owned().into()) + // }) + // .collect::>()?; + // + // self.inner.add_public_keys(public_keys); + // + // Ok(()) + // } + + #[wasm_bindgen(js_name=getPublicKeyMaxId)] + pub fn get_public_key_max_id(&self) -> f64 { + self.inner.get_public_key_max_id() as f64 + } + + #[wasm_bindgen(js_name=fromBuffer)] + pub fn from_buffer(buffer: Vec) -> Result { + let identity: Identity = PlatformDeserializable::deserialize_from_bytes(buffer.as_slice()) + .map_err(to_js_error)?; + Ok(identity.into()) + } +} +// +// impl Inner for IdentityWasm { +// type InnerItem = Identity; +// +// fn into_inner(self) -> Self::InnerItem { +// self.inner +// } +// +// fn inner(&self) -> &Self::InnerItem { +// &self.inner +// } +// +// fn inner_mut(&mut self) -> &mut Self::InnerItem { +// &mut self.inner +// } +// } + +#[wasm_bindgen] +pub struct DataContractWasm(DataContract); + +impl From for DataContractWasm { + fn from(value: DataContract) -> Self { + Self(value) + } +} + +#[wasm_bindgen] +impl DataContractWasm { + pub fn id(&self) -> String { + self.0.id().to_string(Encoding::Base58) + } + + #[wasm_bindgen(js_name=toJSON)] + pub fn to_json(&self) -> Result { + let platform_version = PlatformVersion::first(); + + let json = self.0.to_json(platform_version)?; + let serializer = ::serde_wasm_bindgen::Serializer::json_compatible(); + json.serialize(&serializer).map_err(to_js_error) + } +} diff --git a/packages/wasm-sdk/src/error.rs b/packages/wasm-sdk/src/error.rs index 5617208dea7..0e3742b368f 100644 --- a/packages/wasm-sdk/src/error.rs +++ b/packages/wasm-sdk/src/error.rs @@ -1,7 +1,13 @@ use dash_sdk::Error; +use std::fmt::Display; use wasm_bindgen::prelude::wasm_bindgen; +use wasm_bindgen::JsError; #[wasm_bindgen] #[derive(thiserror::Error, Debug)] #[error("Dash SDK error: {0:?}")] pub struct WasmError(#[from] Error); + +pub(crate) fn to_js_error(e: impl Display) -> JsError { + JsError::new(&format!("{}", e)) +} diff --git a/packages/wasm-sdk/src/lib.rs b/packages/wasm-sdk/src/lib.rs index 059d1fe55fb..b56e5a4f009 100644 --- a/packages/wasm-sdk/src/lib.rs +++ b/packages/wasm-sdk/src/lib.rs @@ -1,6 +1,7 @@ use wasm_bindgen::{prelude::wasm_bindgen, JsValue}; pub mod context_provider; +pub mod dpp; pub mod error; pub mod sdk; pub mod state_transitions; diff --git a/packages/wasm-sdk/src/sdk.rs b/packages/wasm-sdk/src/sdk.rs index fadb1d520d6..b304b1c4e61 100644 --- a/packages/wasm-sdk/src/sdk.rs +++ b/packages/wasm-sdk/src/sdk.rs @@ -1,17 +1,21 @@ use crate::context_provider::WasmContext; -use crate::error::WasmError; +use crate::dpp::{DataContractWasm, IdentityWasm}; +use crate::error::{to_js_error, WasmError}; use dash_sdk::dpp::dashcore::{Network, PrivateKey}; use dash_sdk::dpp::identity::signer::Signer; use dash_sdk::dpp::identity::IdentityV0; use dash_sdk::dpp::prelude::AssetLockProof; +use dash_sdk::dpp::ProtocolError; +use dash_sdk::drive::verify::identity; use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; use dash_sdk::platform::transition::put_identity::PutIdentity; -use dash_sdk::platform::{Fetch, Identifier, Identity}; -use dash_sdk::{Sdk, SdkBuilder}; +use dash_sdk::platform::{DataContract, Fetch, Identifier, Identity}; +use dash_sdk::{Error, Sdk, SdkBuilder}; use std::collections::BTreeMap; use std::fmt::{Debug, Display}; use std::ops::{Deref, DerefMut}; use wasm_bindgen::prelude::wasm_bindgen; +use wasm_bindgen::JsError; use web_sys::window; #[wasm_bindgen] @@ -64,7 +68,7 @@ impl WasmSdkBuilder { WasmSdkBuilder(SdkBuilder::new_testnet()) } - pub fn build(self) -> Result { + pub fn build(self) -> Result { Ok(WasmSdk(self.0.build()?)) } @@ -74,34 +78,32 @@ impl WasmSdkBuilder { } #[wasm_bindgen] -// TODO: return -> wasm_dpp::IdentityWasm -pub async fn identity_fetch(sdk: &WasmSdk, base58_id: &str) { +pub async fn identity_fetch(sdk: &WasmSdk, base58_id: &str) -> Result { let id = Identifier::from_string( base58_id, dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58, - ) - .expect("parse identity id"); + )?; - let identity = Identity::fetch_by_identifier(sdk, id) - .await - .expect("fetch identity") - .unwrap_or_else(|| panic!("identity {} not found", id)); - - display_in_browser(&format!("{:?}", identity)); - // >::from(identity) + Identity::fetch_by_identifier(sdk, id) + .await? + .ok_or_else(|| JsError::new("Identity not found")) + .map(Into::into) } -/// Helper to display results -fn display_in_browser(s: &D) { - // Get the document object - let document = window().unwrap().document().unwrap(); - - // Create a new div element with our message - let div = document.create_element("div").unwrap(); - div.set_text_content(Some(&s.to_string())); +#[wasm_bindgen] +pub async fn data_contract_fetch( + sdk: &WasmSdk, + base58_id: &str, +) -> Result { + let id = Identifier::from_string( + base58_id, + dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58, + )?; - // Append the div to the body - document.body().unwrap().append_child(&div).unwrap(); + DataContract::fetch_by_identifier(sdk, id) + .await? + .ok_or_else(|| JsError::new("Data contract not found")) + .map(Into::into) } pub async fn identity_put(sdk: &WasmSdk) { diff --git a/packages/wasm-sdk/src/state_transitions/documents.rs b/packages/wasm-sdk/src/state_transitions/documents.rs index 735f2fb6270..9a7e0fb2090 100644 --- a/packages/wasm-sdk/src/state_transitions/documents.rs +++ b/packages/wasm-sdk/src/state_transitions/documents.rs @@ -1,3 +1,4 @@ +use crate::error::to_js_error; use dash_sdk::dashcore_rpc::jsonrpc::serde_json::Value; use dash_sdk::dpp::data_contract::document_type::DocumentTypeRef; use dash_sdk::dpp::identity::KeyID; @@ -70,7 +71,3 @@ fn create_batch_transition( .map_err(to_js_error) .map(|bytes| Uint8Array::from(bytes.as_slice())) } - -fn to_js_error(e: impl Display) -> JsError { - JsError::new(&format!("{}", e)) -} diff --git a/packages/wasm-sdk/src/verify.rs b/packages/wasm-sdk/src/verify.rs index 88cf00000b3..88bc35d0707 100644 --- a/packages/wasm-sdk/src/verify.rs +++ b/packages/wasm-sdk/src/verify.rs @@ -22,6 +22,7 @@ use drive_proof_verifier::FromProof; use wasm_bindgen::prelude::wasm_bindgen; use crate::context_provider::WasmContext; +use crate::dpp::{DataContractWasm, IdentityWasm}; #[wasm_bindgen] pub async fn verify_identity_response() -> Option { @@ -65,7 +66,7 @@ pub async fn verify_identity_response() -> Option { ) .expect("parse proof"); - response.map(IdentityWasm) + response.map(IdentityWasm::from) } #[wasm_bindgen] @@ -123,7 +124,7 @@ pub async fn verify_data_contract() -> Option { ) .expect("parse proof"); - response.map(DataContractWasm) + response.map(DataContractWasm::from) } #[wasm_bindgen] @@ -179,26 +180,6 @@ pub async fn verify_documents() -> Vec { .collect() } -#[wasm_bindgen] -pub struct IdentityWasm(Identity); - -#[wasm_bindgen] -impl IdentityWasm { - pub fn id(&self) -> String { - self.0.id().to_string(Encoding::Base58) - } -} - -#[wasm_bindgen] -pub struct DataContractWasm(DataContract); - -#[wasm_bindgen] -impl DataContractWasm { - pub fn id(&self) -> String { - self.0.id().to_string(Encoding::Base58) - } -} - #[wasm_bindgen] pub struct DocumentWasm(Document); #[wasm_bindgen] From 4567c60ea9909b6852d1672af443ce463ddc7de3 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 9 Jan 2025 00:54:28 +0100 Subject: [PATCH 13/26] chore(wasm): expose more code as bindings --- packages/wasm-sdk/src/sdk.rs | 106 +++++++++++++++++++---------------- 1 file changed, 58 insertions(+), 48 deletions(-) diff --git a/packages/wasm-sdk/src/sdk.rs b/packages/wasm-sdk/src/sdk.rs index b304b1c4e61..ae45876d17b 100644 --- a/packages/wasm-sdk/src/sdk.rs +++ b/packages/wasm-sdk/src/sdk.rs @@ -1,22 +1,30 @@ use crate::context_provider::WasmContext; use crate::dpp::{DataContractWasm, IdentityWasm}; use crate::error::{to_js_error, WasmError}; +use dash_sdk::dpp::block::extended_epoch_info::ExtendedEpochInfo; use dash_sdk::dpp::dashcore::{Network, PrivateKey}; +use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; +use dash_sdk::dpp::data_contract::DataContractFactory; +use dash_sdk::dpp::document::serialization_traits::DocumentPlatformConversionMethodsV0; use dash_sdk::dpp::identity::signer::Signer; use dash_sdk::dpp::identity::IdentityV0; use dash_sdk::dpp::prelude::AssetLockProof; +use dash_sdk::dpp::serialization::PlatformSerializableWithPlatformVersion; use dash_sdk::dpp::ProtocolError; use dash_sdk::drive::verify::identity; use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; use dash_sdk::platform::transition::put_identity::PutIdentity; -use dash_sdk::platform::{DataContract, Fetch, Identifier, Identity}; +use dash_sdk::platform::{DataContract, Document, DocumentQuery, Fetch, Identifier, Identity}; +use dash_sdk::sdk::AddressList; use dash_sdk::{Error, Sdk, SdkBuilder}; +use platform_value::platform_value; use std::collections::BTreeMap; use std::fmt::{Debug, Display}; use std::ops::{Deref, DerefMut}; +use std::str::FromStr; use wasm_bindgen::prelude::wasm_bindgen; use wasm_bindgen::JsError; -use web_sys::window; +use web_sys::{console, js_sys, window}; #[wasm_bindgen] pub struct WasmSdk(Sdk); @@ -106,6 +114,7 @@ pub async fn data_contract_fetch( .map(Into::into) } +#[wasm_bindgen] pub async fn identity_put(sdk: &WasmSdk) { let id = Identifier::from_bytes(&[0; 32]).expect("create identifier"); @@ -136,17 +145,17 @@ pub async fn identity_put(sdk: &WasmSdk) { .unwrap(); } -// #[wasm_bindgen] -// pub async fn epoch_testing() { -// let sdk = SdkBuilder::new(AddressList::new()) -// .build() -// .expect("build sdk"); -// -// let ei = ExtendedEpochInfo::fetch(&sdk, 0) -// .await -// .expect("fetch extended epoch info") -// .expect("extended epoch info not found"); -// } +#[wasm_bindgen] +pub async fn epoch_testing() { + let sdk = SdkBuilder::new(AddressList::new()) + .build() + .expect("build sdk"); + + let ei = ExtendedEpochInfo::fetch(&sdk, 0) + .await + .expect("fetch extended epoch info") + .expect("extended epoch info not found"); +} // #[wasm_bindgen] // pub fn setup_sdk() -> WasmSdk { @@ -156,41 +165,42 @@ pub async fn identity_put(sdk: &WasmSdk) { // WasmSdk(sdk) // } -// #[wasm_bindgen] -// pub async fn docs_testing(sdk: &WasmSdk) { -// let id = Identifier::random(); -// -// let factory = DataContractFactory::new(1).expect("create data contract factory"); -// factory -// .create(id, 1, platform_value!({}), None, None) -// .expect("create data contract"); -// -// let dc = DataContract::fetch(&sdk, id) -// .await -// .expect("fetch data contract") -// .expect("data contract not found"); -// -// let dcs = dc -// .serialize_to_bytes_with_platform_version(sdk.version()) -// .expect("serialize data contract"); -// -// let query = DocumentQuery::new(dc.clone(), "asd").expect("create query"); -// let doc = Document::fetch(sdk, query) -// .await -// .expect("fetch document") -// .expect("document not found"); -// -// let document_type = dc -// .document_type_for_name("aaa") -// .expect("document type for name"); -// let doc_serialized = doc -// .serialize(document_type, sdk.version()) -// .expect("serialize document"); -// -// let msg = js_sys::JsString::from_str(&format!("{:?} {:?} ", dcs, doc_serialized)) -// .expect("create js string"); -// console::log_1(&msg); -// } +#[wasm_bindgen] +pub async fn docs_testing(sdk: &WasmSdk) { + let id = Identifier::random(); + + let factory = DataContractFactory::new(1).expect("create data contract factory"); + factory + .create(id, 1, platform_value!({}), None, None) + .expect("create data contract"); + + let dc = DataContract::fetch(&sdk, id) + .await + .expect("fetch data contract") + .expect("data contract not found"); + + let dcs = dc + .serialize_to_bytes_with_platform_version(sdk.version()) + .expect("serialize data contract"); + + let query = DocumentQuery::new(dc.clone(), "asd").expect("create query"); + let doc = Document::fetch(sdk, query) + .await + .expect("fetch document") + .expect("document not found"); + + let document_type = dc + .document_type_for_name("aaa") + .expect("document type for name"); + let doc_serialized = doc + .serialize(document_type, sdk.version()) + .expect("serialize document"); + + let msg = js_sys::JsString::from_str(&format!("{:?} {:?} ", dcs, doc_serialized)) + .expect("create js string"); + console::log_1(&msg); +} + #[derive(Clone, Debug)] struct MockSigner; impl Signer for MockSigner { From 0a34d38106999a2a3da0b87f7b7403fb3e6d3f4d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 9 Jan 2025 00:55:40 +0100 Subject: [PATCH 14/26] deps: rs-tenderdash abci from revision --- Cargo.lock | 47 +++------------------ packages/dapi-grpc/Cargo.toml | 2 +- packages/rs-drive-abci/Cargo.toml | 2 +- packages/rs-drive-proof-verifier/Cargo.toml | 6 +-- 4 files changed, 12 insertions(+), 45 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ea9ac7d8bc0..18138284a3e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1155,7 +1155,7 @@ dependencies = [ "serde", "serde_bytes", "serde_json", - "tenderdash-proto 1.2.1+1.3.0", + "tenderdash-proto", "tonic", "tonic-build", ] @@ -4926,16 +4926,15 @@ dependencies = [ [[package]] name = "tenderdash-abci" version = "1.2.1+1.3.0" -source = "git+https://github.com/dashpay/rs-tenderdash-abci?tag=v1.2.1%2B1.3.0#aad72f4d25816bdf0f584ee4ba3cd383addf8a33" +source = "git+https://github.com/dashpay/rs-tenderdash-abci?rev=3106dcee743ebac2299ce32174a23b84445b20aa#3106dcee743ebac2299ce32174a23b84445b20aa" dependencies = [ "bytes", "futures", "hex", "lhash", "semver", - "serde_json", - "tenderdash-proto 1.2.1+1.3.0 (git+https://github.com/dashpay/rs-tenderdash-abci?tag=v1.2.1%2B1.3.0)", - "thiserror 1.0.64", + "tenderdash-proto", + "thiserror 2.0.9", "tokio", "tokio-util", "tracing", @@ -4947,6 +4946,7 @@ dependencies = [ [[package]] name = "tenderdash-proto" version = "1.2.1+1.3.0" +source = "git+https://github.com/dashpay/rs-tenderdash-abci?rev=3106dcee743ebac2299ce32174a23b84445b20aa#3106dcee743ebac2299ce32174a23b84445b20aa" dependencies = [ "bytes", "chrono", @@ -4957,26 +4957,7 @@ dependencies = [ "prost", "serde", "subtle-encoding", - "tenderdash-proto-compiler 1.2.1+1.3.0", - "time", - "tonic", -] - -[[package]] -name = "tenderdash-proto" -version = "1.2.1+1.3.0" -source = "git+https://github.com/dashpay/rs-tenderdash-abci?tag=v1.2.1%2B1.3.0#aad72f4d25816bdf0f584ee4ba3cd383addf8a33" -dependencies = [ - "bytes", - "chrono", - "derive_more 1.0.0", - "flex-error", - "num-derive", - "num-traits", - "prost", - "serde", - "subtle-encoding", - "tenderdash-proto-compiler 1.2.1+1.3.0 (git+https://github.com/dashpay/rs-tenderdash-abci?tag=v1.2.1%2B1.3.0)", + "tenderdash-proto-compiler", "time", "tonic", ] @@ -4984,21 +4965,7 @@ dependencies = [ [[package]] name = "tenderdash-proto-compiler" version = "1.2.1+1.3.0" -dependencies = [ - "fs_extra", - "prost-build", - "regex", - "tempfile", - "tonic-build", - "ureq", - "walkdir", - "zip 2.2.0", -] - -[[package]] -name = "tenderdash-proto-compiler" -version = "1.2.1+1.3.0" -source = "git+https://github.com/dashpay/rs-tenderdash-abci?tag=v1.2.1%2B1.3.0#aad72f4d25816bdf0f584ee4ba3cd383addf8a33" +source = "git+https://github.com/dashpay/rs-tenderdash-abci?rev=3106dcee743ebac2299ce32174a23b84445b20aa#3106dcee743ebac2299ce32174a23b84445b20aa" dependencies = [ "fs_extra", "prost-build", diff --git a/packages/dapi-grpc/Cargo.toml b/packages/dapi-grpc/Cargo.toml index 0e6a8794530..147e6d78eff 100644 --- a/packages/dapi-grpc/Cargo.toml +++ b/packages/dapi-grpc/Cargo.toml @@ -49,7 +49,7 @@ serde = ["dep:serde", "dep:serde_bytes", "tenderdash-proto/serde"] mocks = ["serde", "dep:serde_json"] [dependencies] -tenderdash-proto = { path = "../../../rs-tenderdash-abci/proto", default-features = false } +tenderdash-proto = { git = "https://github.com/dashpay/rs-tenderdash-abci", version = "1.2.1", rev = "3106dcee743ebac2299ce32174a23b84445b20aa", default-features = false } prost = { version = "0.13" } futures-core = "0.3.30" diff --git a/packages/rs-drive-abci/Cargo.toml b/packages/rs-drive-abci/Cargo.toml index b722827034a..78bc856f9cf 100644 --- a/packages/rs-drive-abci/Cargo.toml +++ b/packages/rs-drive-abci/Cargo.toml @@ -52,7 +52,7 @@ tracing-subscriber = { version = "0.3.16", default-features = false, features = "registry", "tracing-log", ], optional = false } -tenderdash-abci = { git = "https://github.com/dashpay/rs-tenderdash-abci", version = "1.2.1", tag = "v1.2.1+1.3.0", features = [ +tenderdash-abci = { git = "https://github.com/dashpay/rs-tenderdash-abci", version = "1.2.1", rev = "3106dcee743ebac2299ce32174a23b84445b20aa", features = [ "grpc", ] } lazy_static = "1.4.0" diff --git a/packages/rs-drive-proof-verifier/Cargo.toml b/packages/rs-drive-proof-verifier/Cargo.toml index 419c945c1e6..ad3eeda4567 100644 --- a/packages/rs-drive-proof-verifier/Cargo.toml +++ b/packages/rs-drive-proof-verifier/Cargo.toml @@ -26,14 +26,14 @@ drive = { path = "../rs-drive", default-features = false, features = [ ] } dpp = { path = "../rs-dpp", features = [ "bls-signatures", -# "document-value-conversion", -# "extended-document", + # "document-value-conversion", + # "extended-document", "core-types-serialization", ], default-features = false } bincode = { version = "2.0.0-rc.3", features = ["serde"] } platform-serialization-derive = { path = "../rs-platform-serialization-derive", optional = true } platform-serialization = { path = "../rs-platform-serialization" } -tenderdash-abci = { git = "https://github.com/dashpay/rs-tenderdash-abci", version = "1.2.1", tag = "v1.2.1+1.3.0", features = [ +tenderdash-abci = { git = "https://github.com/dashpay/rs-tenderdash-abci", version = "1.2.1", rev = "3106dcee743ebac2299ce32174a23b84445b20aa", features = [ "crypto", ], default-features = false } tracing = { version = "0.1.37" } From 0417b335429a0bb24645350e11f128ee3571e46b Mon Sep 17 00:00:00 2001 From: Ivan Shumkov Date: Mon, 13 Jan 2025 14:18:58 +0700 Subject: [PATCH 15/26] build(dpp): add optimization flags to dpp wasm build script --- packages/wasm-dpp/scripts/build-wasm.sh | 2 +- packages/wasm-sdk/src/sdk.rs | 11 ----------- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/packages/wasm-dpp/scripts/build-wasm.sh b/packages/wasm-dpp/scripts/build-wasm.sh index b7ada5425ef..4dd833c452f 100755 --- a/packages/wasm-dpp/scripts/build-wasm.sh +++ b/packages/wasm-dpp/scripts/build-wasm.sh @@ -49,7 +49,7 @@ fi if command -v wasm-opt &> /dev/null; then echo "Optimizing wasm using Binaryen" - wasm-opt -Oz "$OUTPUT_FILE" -o "$OUTPUT_FILE" + wasm-opt -tnh --flatten --rereloop -Oz --gufa -Oz --gufa -Oz "$OUTPUT_FILE" -o "$OUTPUT_FILE" else echo "wasm-opt command not found. Skipping wasm optimization." fi diff --git a/packages/wasm-sdk/src/sdk.rs b/packages/wasm-sdk/src/sdk.rs index ae45876d17b..12a3233d9f0 100644 --- a/packages/wasm-sdk/src/sdk.rs +++ b/packages/wasm-sdk/src/sdk.rs @@ -1,6 +1,5 @@ use crate::context_provider::WasmContext; use crate::dpp::{DataContractWasm, IdentityWasm}; -use crate::error::{to_js_error, WasmError}; use dash_sdk::dpp::block::extended_epoch_info::ExtendedEpochInfo; use dash_sdk::dpp::dashcore::{Network, PrivateKey}; use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; @@ -10,8 +9,6 @@ use dash_sdk::dpp::identity::signer::Signer; use dash_sdk::dpp::identity::IdentityV0; use dash_sdk::dpp::prelude::AssetLockProof; use dash_sdk::dpp::serialization::PlatformSerializableWithPlatformVersion; -use dash_sdk::dpp::ProtocolError; -use dash_sdk::drive::verify::identity; use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; use dash_sdk::platform::transition::put_identity::PutIdentity; use dash_sdk::platform::{DataContract, Document, DocumentQuery, Fetch, Identifier, Identity}; @@ -157,14 +154,6 @@ pub async fn epoch_testing() { .expect("extended epoch info not found"); } -// #[wasm_bindgen] -// pub fn setup_sdk() -> WasmSdk { -// let sdk = SdkBuilder::new(AddressList::new()) -// .build() -// .expect("build sdk"); -// WasmSdk(sdk) -// } - #[wasm_bindgen] pub async fn docs_testing(sdk: &WasmSdk) { let id = Identifier::random(); From d7c1ebfcf70eeea075035f5a3344faf1c0192759 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 13 Jan 2025 09:30:34 +0100 Subject: [PATCH 16/26] deps: change rs-tenderdash-abci version --- Cargo.lock | 6 +++--- packages/dapi-grpc/Cargo.toml | 5 ++--- packages/rs-drive-abci/Cargo.toml | 3 ++- packages/rs-drive-proof-verifier/Cargo.toml | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 18138284a3e..a8f2b05ca0a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4926,7 +4926,7 @@ dependencies = [ [[package]] name = "tenderdash-abci" version = "1.2.1+1.3.0" -source = "git+https://github.com/dashpay/rs-tenderdash-abci?rev=3106dcee743ebac2299ce32174a23b84445b20aa#3106dcee743ebac2299ce32174a23b84445b20aa" +source = "git+https://github.com/dashpay/rs-tenderdash-abci?rev=a558c0a2deab149183f125a012b14b709150401c#a558c0a2deab149183f125a012b14b709150401c" dependencies = [ "bytes", "futures", @@ -4946,7 +4946,7 @@ dependencies = [ [[package]] name = "tenderdash-proto" version = "1.2.1+1.3.0" -source = "git+https://github.com/dashpay/rs-tenderdash-abci?rev=3106dcee743ebac2299ce32174a23b84445b20aa#3106dcee743ebac2299ce32174a23b84445b20aa" +source = "git+https://github.com/dashpay/rs-tenderdash-abci?rev=a558c0a2deab149183f125a012b14b709150401c#a558c0a2deab149183f125a012b14b709150401c" dependencies = [ "bytes", "chrono", @@ -4965,7 +4965,7 @@ dependencies = [ [[package]] name = "tenderdash-proto-compiler" version = "1.2.1+1.3.0" -source = "git+https://github.com/dashpay/rs-tenderdash-abci?rev=3106dcee743ebac2299ce32174a23b84445b20aa#3106dcee743ebac2299ce32174a23b84445b20aa" +source = "git+https://github.com/dashpay/rs-tenderdash-abci?rev=a558c0a2deab149183f125a012b14b709150401c#a558c0a2deab149183f125a012b14b709150401c" dependencies = [ "fs_extra", "prost-build", diff --git a/packages/dapi-grpc/Cargo.toml b/packages/dapi-grpc/Cargo.toml index 147e6d78eff..b6bdc944d78 100644 --- a/packages/dapi-grpc/Cargo.toml +++ b/packages/dapi-grpc/Cargo.toml @@ -29,12 +29,11 @@ client = [ "tonic/tls-roots", "tonic/tls-webpki-roots", "platform", - "tenderdash-proto/client", ] # Specialized features for building the client in a wasm environment. # Conflicts with `client` and `server` feature. -wasm = ["tenderdash-proto/client"] +wasm = [] # Build tonic server code. Includes all client features and adds server-specific dependencies. server = [ @@ -49,7 +48,7 @@ serde = ["dep:serde", "dep:serde_bytes", "tenderdash-proto/serde"] mocks = ["serde", "dep:serde_json"] [dependencies] -tenderdash-proto = { git = "https://github.com/dashpay/rs-tenderdash-abci", version = "1.2.1", rev = "3106dcee743ebac2299ce32174a23b84445b20aa", default-features = false } +tenderdash-proto = { git = "https://github.com/dashpay/rs-tenderdash-abci", version = "1.2.1", rev = "a558c0a2deab149183f125a012b14b709150401c", default-features = false } prost = { version = "0.13" } futures-core = "0.3.30" diff --git a/packages/rs-drive-abci/Cargo.toml b/packages/rs-drive-abci/Cargo.toml index 78bc856f9cf..217e754bec6 100644 --- a/packages/rs-drive-abci/Cargo.toml +++ b/packages/rs-drive-abci/Cargo.toml @@ -52,9 +52,10 @@ tracing-subscriber = { version = "0.3.16", default-features = false, features = "registry", "tracing-log", ], optional = false } -tenderdash-abci = { git = "https://github.com/dashpay/rs-tenderdash-abci", version = "1.2.1", rev = "3106dcee743ebac2299ce32174a23b84445b20aa", features = [ +tenderdash-abci = { git = "https://github.com/dashpay/rs-tenderdash-abci", version = "1.2.1", rev = "a558c0a2deab149183f125a012b14b709150401c", features = [ "grpc", ] } + lazy_static = "1.4.0" itertools = { version = "0.13" } file-rotate = { version = "0.7.3" } diff --git a/packages/rs-drive-proof-verifier/Cargo.toml b/packages/rs-drive-proof-verifier/Cargo.toml index ad3eeda4567..4978b546331 100644 --- a/packages/rs-drive-proof-verifier/Cargo.toml +++ b/packages/rs-drive-proof-verifier/Cargo.toml @@ -33,7 +33,7 @@ dpp = { path = "../rs-dpp", features = [ bincode = { version = "2.0.0-rc.3", features = ["serde"] } platform-serialization-derive = { path = "../rs-platform-serialization-derive", optional = true } platform-serialization = { path = "../rs-platform-serialization" } -tenderdash-abci = { git = "https://github.com/dashpay/rs-tenderdash-abci", version = "1.2.1", rev = "3106dcee743ebac2299ce32174a23b84445b20aa", features = [ +tenderdash-abci = { git = "https://github.com/dashpay/rs-tenderdash-abci", version = "1.2.1", rev = "a558c0a2deab149183f125a012b14b709150401c", features = [ "crypto", ], default-features = false } tracing = { version = "0.1.37" } From e243d9e561b3c0247bff32282984ff71c118343f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 13 Jan 2025 09:30:50 +0100 Subject: [PATCH 17/26] chore: fix build --- packages/rs-dapi-client/src/transport/tonic_channel.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/rs-dapi-client/src/transport/tonic_channel.rs b/packages/rs-dapi-client/src/transport/tonic_channel.rs index f1e9de97038..34c52af2961 100644 --- a/packages/rs-dapi-client/src/transport/tonic_channel.rs +++ b/packages/rs-dapi-client/src/transport/tonic_channel.rs @@ -6,7 +6,7 @@ use crate::{request_settings::AppliedRequestSettings, RequestSettings, Uri}; use dapi_grpc::core::v0::core_client::CoreClient; use dapi_grpc::core::v0::{self as core_proto}; use dapi_grpc::platform::v0::{self as platform_proto, platform_client::PlatformClient}; -use dapi_grpc::tonic::transport::{Certificate, Channel, ClientTlsConfig, Uri}; +use dapi_grpc::tonic::transport::{Certificate, Channel, ClientTlsConfig}; use dapi_grpc::tonic::{IntoRequest, Streaming}; use futures::{future::BoxFuture, FutureExt, TryFutureExt}; @@ -17,16 +17,16 @@ pub type CoreGrpcClient = CoreClient; /// backon::Sleeper #[derive(Default, Clone, Debug)] -pub(crate) struct Sleeper(backon::TokioSleeper); +pub(crate) struct BackonSleeper(backon::TokioSleeper); impl backon::Sleeper for Sleeper { - type Sleep = backon::TokioSleeper::Sleep; + type Sleep = ::Sleep; fn sleep(&self, dur: Duration) -> Self::Sleep { self.0.sleep(dur) } } -fn create_channel( +pub(super) fn create_channel( uri: Uri, settings: Option<&AppliedRequestSettings>, ) -> Result { From 147106863872f41145d1309f74d381c9a97a2216 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 13 Jan 2025 10:22:51 +0100 Subject: [PATCH 18/26] refactor: replace wasm feature with target_arch --- packages/dapi-grpc/Cargo.toml | 4 -- packages/dapi-grpc/build.rs | 2 +- packages/dapi-grpc/src/lib.rs | 20 +++++++--- packages/rs-dapi-client/Cargo.toml | 40 +++++++++---------- packages/rs-dapi-client/src/dapi_client.rs | 17 ++++---- packages/rs-dapi-client/src/lib.rs | 6 +-- .../rs-dapi-client/src/request_settings.rs | 8 ++-- packages/rs-dapi-client/src/transport.rs | 18 +++++---- packages/rs-dapi-client/src/transport/grpc.rs | 5 +-- .../src/transport/tonic_channel.rs | 35 +++++++--------- packages/rs-sdk/Cargo.toml | 2 - packages/wasm-sdk/Cargo.toml | 4 +- 12 files changed, 79 insertions(+), 82 deletions(-) diff --git a/packages/dapi-grpc/Cargo.toml b/packages/dapi-grpc/Cargo.toml index 6a4899ae5f9..02a1ff3739c 100644 --- a/packages/dapi-grpc/Cargo.toml +++ b/packages/dapi-grpc/Cargo.toml @@ -31,10 +31,6 @@ client = [ "platform", ] -# Specialized features for building the client in a wasm environment. -# Conflicts with `client` and `server` feature. -wasm = [] - # Build tonic server code. Includes all client features and adds server-specific dependencies. server = [ "tonic/channel", diff --git a/packages/dapi-grpc/build.rs b/packages/dapi-grpc/build.rs index 29f93be032e..8e9f70cea6f 100644 --- a/packages/dapi-grpc/build.rs +++ b/packages/dapi-grpc/build.rs @@ -17,7 +17,7 @@ fn main() { generate_code(ImplType::Server); #[cfg(feature = "client")] generate_code(ImplType::Client); - #[cfg(feature = "wasm")] + #[cfg(target_arch = "wasm32")] generate_code(ImplType::Wasm); } diff --git a/packages/dapi-grpc/src/lib.rs b/packages/dapi-grpc/src/lib.rs index 4c33e157883..2988b4b5cc1 100644 --- a/packages/dapi-grpc/src/lib.rs +++ b/packages/dapi-grpc/src/lib.rs @@ -8,10 +8,17 @@ pub mod core { #[cfg(feature = "server")] include!("core/server/org.dash.platform.dapi.v0.rs"); - #[cfg(all(feature = "client", not(feature = "server")))] + #[cfg(all( + feature = "client", + not(feature = "server"), + not(target_arch = "wasm32") + ))] include!("core/client/org.dash.platform.dapi.v0.rs"); - #[cfg(all(feature = "wasm", not(any(feature = "server", feature = "client"))))] + #[cfg(all( + target_arch = "wasm32", + not(any(feature = "server", feature = "client")) + ))] include!("core/wasm/org.dash.platform.dapi.v0.rs"); } } @@ -25,16 +32,19 @@ pub mod platform { #[cfg(all(feature = "client", not(feature = "server")))] include!("platform/client/org.dash.platform.dapi.v0.rs"); - #[cfg(all(feature = "wasm", not(any(feature = "server", feature = "client"))))] + #[cfg(all( + target_arch = "wasm32", + not(any(feature = "server", feature = "client")) + ))] include!("platform/wasm/org.dash.platform.dapi.v0.rs"); } #[cfg(feature = "tenderdash-proto")] pub use tenderdash_proto as proto; - #[cfg(any(feature = "server", feature = "client", feature = "wasm"))] + #[cfg(any(feature = "server", feature = "client", target_arch = "wasm32"))] mod versioning; - #[cfg(any(feature = "server", feature = "client", feature = "wasm"))] + #[cfg(any(feature = "server", feature = "client", target_arch = "wasm32"))] pub use versioning::{VersionedGrpcMessage, VersionedGrpcResponse}; } diff --git a/packages/rs-dapi-client/Cargo.toml b/packages/rs-dapi-client/Cargo.toml index a5b29c33a2a..ece8c2cad17 100644 --- a/packages/rs-dapi-client/Cargo.toml +++ b/packages/rs-dapi-client/Cargo.toml @@ -5,13 +5,8 @@ edition = "2021" [features] # TODO we should not enable deps features in default -default = [ - "mocks", - "offline-testing", - "dapi-grpc/client", - "backon/tokio-sleep", - "wasm", # TODO: remove -] +default = ["mocks", "offline-testing"] + mocks = [ "dep:sha2", "dep:hex", @@ -24,29 +19,31 @@ mocks = [ dump = ["mocks"] # skip tests that require connection to the platform; enabled by default offline-testing = [] -wasm = [ - "dapi-grpc/wasm", - "dapi-grpc/platform", - "dapi-grpc/core", - "dep:tonic-web-wasm-client", - "dep:http", - "dep:wasm-bindgen-futures", - "dep:gloo-timers", - "getrandom/js", -] + +# non-wasm dependencies +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +backon = { version = "1.3", default-features = false, features = [ + "tokio-sleep", +] } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +gloo-timers = { version = "0.3.0", features = ["futures"] } +tonic-web-wasm-client = { version = "0.6.0" } +wasm-bindgen-futures = { version = "0.4.49" } +http = { version = "1.1.0", default-features = false } +getrandom = { version = "0.2", features = ["js"] } [dependencies] backon = { version = "1.3", default-features = false } -gloo-timers = { version = "0.3.0", features = ["futures"], optional = true } dapi-grpc = { path = "../dapi-grpc", features = [ "core", "platform", + "client", ], default-features = false } futures = { version = "0.3.28" } -http = { version = "1.1.0", default-features = false, optional = true } http-serde = { version = "2.1", optional = true } -getrandom = { version = "0.2", optional = true } -tonic-web-wasm-client = { version = "0.6.0", optional = true } + + rand = { version = "0.8.5", features = [ "small_rng", "getrandom", @@ -60,7 +57,6 @@ lru = { version = "0.12.3" } serde = { version = "1.0.197", optional = true, features = ["derive"] } serde_json = { version = "1.0.120", optional = true } chrono = { version = "0.4.38", features = ["serde"] } -wasm-bindgen-futures = { version = "0.4.49", optional = true } [dev-dependencies] tokio = { version = "1.40", features = ["macros"] } diff --git a/packages/rs-dapi-client/src/dapi_client.rs b/packages/rs-dapi-client/src/dapi_client.rs index 1ff986b3896..8986ac01d67 100644 --- a/packages/rs-dapi-client/src/dapi_client.rs +++ b/packages/rs-dapi-client/src/dapi_client.rs @@ -3,7 +3,7 @@ use backon::{ConstantBuilder, Retryable}; use dapi_grpc::mock::Mockable; use dapi_grpc::tonic::async_trait; -#[cfg(not(feature = "wasm"))] +#[cfg(not(target_arch = "wasm32"))] use dapi_grpc::tonic::transport::Certificate; use std::fmt::{Debug, Display}; use std::sync::atomic::AtomicUsize; @@ -78,7 +78,7 @@ pub struct DapiClient { address_list: AddressList, settings: RequestSettings, pool: ConnectionPool, - #[cfg(not(feature = "wasm"))] + #[cfg(not(target_arch = "wasm32"))] /// Certificate Authority certificate to use for verifying the server's certificate. pub ca_certificate: Option, #[cfg(feature = "dump")] @@ -97,7 +97,7 @@ impl DapiClient { pool: ConnectionPool::new(address_count), #[cfg(feature = "dump")] dump_dir: None, - #[cfg(not(feature = "wasm"))] + #[cfg(not(target_arch = "wasm32"))] ca_certificate: None, } } @@ -110,7 +110,7 @@ impl DapiClient { /// /// # Returns /// [DapiClient] with CA certificate set. - #[cfg(not(feature = "wasm"))] + #[cfg(not(target_arch = "wasm32"))] pub fn with_ca_certificate(mut self, ca_cert: Certificate) -> Self { self.ca_certificate = Some(ca_cert); @@ -205,7 +205,7 @@ impl DapiRequestExecutor for DapiClient { .override_by(R::SETTINGS_OVERRIDES) .override_by(settings) .finalize(); - #[cfg(not(feature = "wasm"))] + #[cfg(not(target_arch = "wasm32"))] let applied_settings = applied_settings.with_ca_certificate(self.ca_certificate.clone()); // Setup retry policy: @@ -315,11 +315,14 @@ impl DapiRequestExecutor for DapiClient { } }; - let sleeper = transport::channel_impl::BackonSleeper::default(); + let sleeper = transport::BackonSleeper::default(); // Start the routine with retry policy applied: // We allow let_and_return because `result` is used later if dump feature is enabled - let result = routine + let result: Result< + ExecutionResponse<::Response>, + ExecutionError, + > = routine .retry(retry_settings) .sleep(sleeper) .notify(|error, duration| { diff --git a/packages/rs-dapi-client/src/lib.rs b/packages/rs-dapi-client/src/lib.rs index 9603bb8e492..110fe8fd6bc 100644 --- a/packages/rs-dapi-client/src/lib.rs +++ b/packages/rs-dapi-client/src/lib.rs @@ -19,8 +19,6 @@ pub use address_list::AddressListError; pub use address_list::AddressStatus; pub use connection_pool::ConnectionPool; pub use dapi_client::{update_address_ban_status, DapiClient, DapiClientError}; -#[cfg(not(feature = "wasm"))] -pub use dapi_grpc::tonic::transport::http; #[cfg(feature = "dump")] pub use dump::DumpData; pub use executor::{ @@ -28,9 +26,9 @@ pub use executor::{ WrapToExecutionResult, }; use futures::{future::BoxFuture, FutureExt}; -#[cfg(feature = "wasm")] +#[cfg(target_arch = "wasm32")] pub use http::Uri; -#[cfg(not(feature = "wasm"))] +#[cfg(not(target_arch = "wasm32"))] pub use http_serde::http::Uri; pub use request_settings::RequestSettings; diff --git a/packages/rs-dapi-client/src/request_settings.rs b/packages/rs-dapi-client/src/request_settings.rs index 0767e15337a..39f2da42d00 100644 --- a/packages/rs-dapi-client/src/request_settings.rs +++ b/packages/rs-dapi-client/src/request_settings.rs @@ -1,6 +1,6 @@ //! DAPI client request settings processing. -#[cfg(not(feature = "wasm"))] +#[cfg(not(target_arch = "wasm32"))] use dapi_grpc::tonic::transport::Certificate; use std::time::Duration; @@ -66,7 +66,7 @@ impl RequestSettings { ban_failed_address: self .ban_failed_address .unwrap_or(DEFAULT_BAN_FAILED_ADDRESS), - #[cfg(not(feature = "wasm"))] + #[cfg(not(target_arch = "wasm32"))] ca_certificate: None, } } @@ -84,14 +84,14 @@ pub struct AppliedRequestSettings { /// Ban DAPI address if node not responded or responded with error. pub ban_failed_address: bool, /// Certificate Authority certificate to use for verifying the server's certificate. - #[cfg(not(feature = "wasm"))] + #[cfg(not(target_arch = "wasm32"))] pub ca_certificate: Option, } impl AppliedRequestSettings { /// Use provided CA certificate for verifying the server's certificate. /// /// If set to None, the system's default CA certificates will be used. - #[cfg(not(feature = "wasm"))] + #[cfg(not(target_arch = "wasm32"))] pub fn with_ca_certificate(mut self, ca_cert: Option) -> Self { self.ca_certificate = ca_cert; self diff --git a/packages/rs-dapi-client/src/transport.rs b/packages/rs-dapi-client/src/transport.rs index 9a06459e4c6..117dbbd59de 100644 --- a/packages/rs-dapi-client/src/transport.rs +++ b/packages/rs-dapi-client/src/transport.rs @@ -1,23 +1,27 @@ //! Transport options that DAPI requests use under the hood. pub(crate) mod grpc; -#[cfg(not(feature = "wasm"))] +#[cfg(not(target_arch = "wasm32"))] pub(crate) mod tonic_channel; -#[cfg(feature = "wasm")] +#[cfg(target_arch = "wasm32")] pub(crate) mod wasm_channel; use crate::connection_pool::ConnectionPool; pub use crate::request_settings::AppliedRequestSettings; use crate::{CanRetry, RequestSettings, Uri}; -pub use channel_impl::{BackonSleeper, CoreGrpcClient, PlatformGrpcClient}; use dapi_grpc::mock::Mockable; pub use futures::future::BoxFuture; use std::any; use std::fmt::Debug; -#[cfg(not(feature = "wasm"))] -pub(crate) use tonic_channel as channel_impl; -#[cfg(feature = "wasm")] -pub(crate) use wasm_channel as channel_impl; + +#[cfg(not(target_arch = "wasm32"))] +pub use tonic_channel::{ + create_channel, CoreGrpcClient, PlatformGrpcClient, TonicBackonSleeper as BackonSleeper, +}; +#[cfg(target_arch = "wasm32")] +pub use wasm_channel::{ + create_channel, CoreGrpcClient, PlatformGrpcClient, TonicBackonSleeper as BackonSleeper, +}; /// Generic transport layer request. /// Requires [Clone] as could be retried and a client in general consumes a request. diff --git a/packages/rs-dapi-client/src/transport/grpc.rs b/packages/rs-dapi-client/src/transport/grpc.rs index ff3887befbb..8c6195bd055 100644 --- a/packages/rs-dapi-client/src/transport/grpc.rs +++ b/packages/rs-dapi-client/src/transport/grpc.rs @@ -2,10 +2,7 @@ use std::time::Duration; -#[cfg(not(feature = "wasm"))] -use super::tonic_channel::create_channel; -#[cfg(feature = "wasm")] -use super::wasm_channel::create_channel; +use super::create_channel; use super::{CanRetry, TransportClient, TransportError, TransportRequest}; use super::{CoreGrpcClient, PlatformGrpcClient}; use crate::connection_pool::{ConnectionPool, PoolPrefix}; diff --git a/packages/rs-dapi-client/src/transport/tonic_channel.rs b/packages/rs-dapi-client/src/transport/tonic_channel.rs index 34c52af2961..927dcc91b39 100644 --- a/packages/rs-dapi-client/src/transport/tonic_channel.rs +++ b/packages/rs-dapi-client/src/transport/tonic_channel.rs @@ -1,14 +1,8 @@ -use std::time::Duration; - -use super::{CanRetry, TransportClient, TransportError, TransportRequest}; -use crate::connection_pool::{ConnectionPool, PoolPrefix}; -use crate::{request_settings::AppliedRequestSettings, RequestSettings, Uri}; +use super::TransportError; +use crate::{request_settings::AppliedRequestSettings, Uri}; use dapi_grpc::core::v0::core_client::CoreClient; -use dapi_grpc::core::v0::{self as core_proto}; -use dapi_grpc::platform::v0::{self as platform_proto, platform_client::PlatformClient}; +use dapi_grpc::platform::v0::platform_client::PlatformClient; use dapi_grpc::tonic::transport::{Certificate, Channel, ClientTlsConfig}; -use dapi_grpc::tonic::{IntoRequest, Streaming}; -use futures::{future::BoxFuture, FutureExt, TryFutureExt}; /// Platform Client using gRPC transport. pub type PlatformGrpcClient = PlatformClient; @@ -16,17 +10,18 @@ pub type PlatformGrpcClient = PlatformClient; pub type CoreGrpcClient = CoreClient; /// backon::Sleeper -#[derive(Default, Clone, Debug)] -pub(crate) struct BackonSleeper(backon::TokioSleeper); - -impl backon::Sleeper for Sleeper { - type Sleep = ::Sleep; - fn sleep(&self, dur: Duration) -> Self::Sleep { - self.0.sleep(dur) - } -} - -pub(super) fn create_channel( +// #[derive(Default, Clone, Debug)] +pub type TonicBackonSleeper = backon::TokioSleeper; + +// impl backon::Sleeper for TonicBackonSleeper { +// type Sleep = ::Sleep; +// fn sleep(&self, dur: Duration) -> Self::Sleep { +// self.0.sleep(dur) +// } +// } + +/// Create channel (connection) for gRPC transport. +pub fn create_channel( uri: Uri, settings: Option<&AppliedRequestSettings>, ) -> Result { diff --git a/packages/rs-sdk/Cargo.toml b/packages/rs-sdk/Cargo.toml index 12c6757bd52..3a969357aea 100644 --- a/packages/rs-sdk/Cargo.toml +++ b/packages/rs-sdk/Cargo.toml @@ -69,8 +69,6 @@ default = [ "tokio/rt-multi-thread", ] -wasm = ["dapi-grpc/wasm", "rs-dapi-client/wasm"] - mocks = [ "dep:serde", "dep:serde_json", diff --git a/packages/wasm-sdk/Cargo.toml b/packages/wasm-sdk/Cargo.toml index 39829ebfd4a..3b0d525fd80 100644 --- a/packages/wasm-sdk/Cargo.toml +++ b/packages/wasm-sdk/Cargo.toml @@ -8,6 +8,7 @@ publish = false crate-type = ["cdylib"] [dependencies] +dash-sdk = { path = "../rs-sdk", default-features = false } console_error_panic_hook = { version = "0.1.6" } thiserror = { version = "2.0.9" } web-sys = { version = "0.3.4", features = [ @@ -20,8 +21,7 @@ web-sys = { version = "0.3.4", features = [ ] } wasm-bindgen = { version = "=0.2.99" } wasm-bindgen-futures = { version = "0.4.49" } -dash-sdk = { path = "../rs-sdk", default-features = false, features = ["wasm"] } -drive-proof-verifier = { path = "../rs-drive-proof-verifier" } # TODO: I think it's not needed (LKl) +drive-proof-verifier = { path = "../rs-drive-proof-verifier" } # TODO: I think it's not needed (LKl) # tonic = { version = "*", features = ["transport"], default-features = false } # client = [ # "tonic/channel", FAIL From fbf630965bcdebae4c0da1054e2e0eef0d384cb4 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 13 Jan 2025 11:09:21 +0100 Subject: [PATCH 19/26] chore: remove wasm feature, continued --- Cargo.lock | 2 +- packages/dapi-grpc/Cargo.toml | 31 ++++++++++--------- packages/dapi-grpc/src/lib.rs | 20 ++++++------ packages/rs-dapi-client/src/transport.rs | 2 +- .../src/transport/wasm_channel.rs | 6 ++-- packages/rs-sdk/Cargo.toml | 12 +++---- .../platform/transition/broadcast_identity.rs | 6 ++-- packages/rs-sdk/src/sdk.rs | 12 +++---- packages/rs-sdk/src/sync.rs | 6 ++-- 9 files changed, 47 insertions(+), 50 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f4f30066a4c..a4950c89ec7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -314,7 +314,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba5289ec98f68f28dd809fd601059e6aa908bb8f6108620930828283d4ee23d7" dependencies = [ "fastrand", - "gloo-timers", "tokio", ] @@ -1150,6 +1149,7 @@ version = "1.8.0-dev.2" dependencies = [ "dapi-grpc-macros", "futures-core", + "getrandom", "platform-version", "prost", "serde", diff --git a/packages/dapi-grpc/Cargo.toml b/packages/dapi-grpc/Cargo.toml index 02a1ff3739c..97d7cbd2219 100644 --- a/packages/dapi-grpc/Cargo.toml +++ b/packages/dapi-grpc/Cargo.toml @@ -22,23 +22,10 @@ platform = [] tenderdash-proto = [] # Client support. -client = [ - "tonic/channel", - "tonic/transport", - "tonic/tls", - "tonic/tls-roots", - "tonic/tls-webpki-roots", - "platform", -] +client = ["platform"] # Build tonic server code. Includes all client features and adds server-specific dependencies. -server = [ - "tonic/channel", - "tonic/transport", - "platform", - "tenderdash-proto/server", - "client", -] +server = ["platform", "tenderdash-proto/server", "client"] serde = ["dep:serde", "dep:serde_bytes", "tenderdash-proto/serde"] mocks = ["serde", "dep:serde_json"] @@ -58,6 +45,20 @@ serde_json = { version = "1.0", optional = true } dapi-grpc-macros = { path = "../rs-dapi-grpc-macros" } platform-version = { path = "../rs-platform-version" } +[target.'cfg(target_arch = "wasm32")'.dependencies] +getrandom = { version = "0.2", features = ["js"] } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +tonic = { version = "0.12.3", features = [ + "codegen", + "prost", + "channel", + "transport", + "tls", + "tls-roots", + "tls-webpki-roots", +], default-features = false } + [build-dependencies] tonic-build = { version = "0.12.3" } diff --git a/packages/dapi-grpc/src/lib.rs b/packages/dapi-grpc/src/lib.rs index 2988b4b5cc1..c4258a8ff33 100644 --- a/packages/dapi-grpc/src/lib.rs +++ b/packages/dapi-grpc/src/lib.rs @@ -5,7 +5,7 @@ pub mod core { #![allow(non_camel_case_types)] pub mod v0 { // Note: only one of the features can be analyzed at a time - #[cfg(feature = "server")] + #[cfg(all(feature = "server", not(target_arch = "wasm32")))] include!("core/server/org.dash.platform.dapi.v0.rs"); #[cfg(all( @@ -15,10 +15,7 @@ pub mod core { ))] include!("core/client/org.dash.platform.dapi.v0.rs"); - #[cfg(all( - target_arch = "wasm32", - not(any(feature = "server", feature = "client")) - ))] + #[cfg(target_arch = "wasm32")] include!("core/wasm/org.dash.platform.dapi.v0.rs"); } } @@ -26,16 +23,17 @@ pub mod core { #[cfg(feature = "platform")] pub mod platform { pub mod v0 { - #[cfg(feature = "server")] + #[cfg(all(feature = "server", not(target_arch = "wasm32")))] include!("platform/server/org.dash.platform.dapi.v0.rs"); - #[cfg(all(feature = "client", not(feature = "server")))] - include!("platform/client/org.dash.platform.dapi.v0.rs"); - #[cfg(all( - target_arch = "wasm32", - not(any(feature = "server", feature = "client")) + feature = "client", + not(feature = "server"), + not(target_arch = "wasm32") ))] + include!("platform/client/org.dash.platform.dapi.v0.rs"); + + #[cfg(target_arch = "wasm32")] include!("platform/wasm/org.dash.platform.dapi.v0.rs"); } diff --git a/packages/rs-dapi-client/src/transport.rs b/packages/rs-dapi-client/src/transport.rs index 117dbbd59de..fc80cef58f0 100644 --- a/packages/rs-dapi-client/src/transport.rs +++ b/packages/rs-dapi-client/src/transport.rs @@ -20,7 +20,7 @@ pub use tonic_channel::{ }; #[cfg(target_arch = "wasm32")] pub use wasm_channel::{ - create_channel, CoreGrpcClient, PlatformGrpcClient, TonicBackonSleeper as BackonSleeper, + create_channel, CoreGrpcClient, PlatformGrpcClient, WasmBackonSleeper as BackonSleeper, }; /// Generic transport layer request. diff --git a/packages/rs-dapi-client/src/transport/wasm_channel.rs b/packages/rs-dapi-client/src/transport/wasm_channel.rs index a28e152f792..625e5b5791b 100644 --- a/packages/rs-dapi-client/src/transport/wasm_channel.rs +++ b/packages/rs-dapi-client/src/transport/wasm_channel.rs @@ -22,7 +22,7 @@ pub type PlatformGrpcClient = PlatformClient; pub type CoreGrpcClient = CoreClient; /// Create a channel that will be used to communicate with the DAPI. -pub(super) fn create_channel( +pub fn create_channel( uri: Uri, _settings: Option<&AppliedRequestSettings>, ) -> Result { @@ -89,8 +89,8 @@ fn wasm_client_error_to_status(e: tonic_web_wasm_client::Error) -> Status { /// We reimplement it here to make it Send. // TODO: Consider moving it to different module. #[derive(Default, Clone, Debug)] -pub struct BackonSleeper {} -impl backon::Sleeper for BackonSleeper { +pub struct WasmBackonSleeper {} +impl backon::Sleeper for WasmBackonSleeper { type Sleep = BoxFuture<'static, ()>; fn sleep(&self, dur: Duration) -> Self::Sleep { into_send(gloo_timers::future::sleep(dur)).boxed() diff --git a/packages/rs-sdk/Cargo.toml b/packages/rs-sdk/Cargo.toml index 3a969357aea..59add97bbdb 100644 --- a/packages/rs-sdk/Cargo.toml +++ b/packages/rs-sdk/Cargo.toml @@ -6,7 +6,7 @@ edition = "2021" [dependencies] arc-swap = { version = "1.7.1" } -backon = { version = "1.2", features = ["tokio-sleep"] } +backon = { version = "1.2", default-features = false } chrono = { version = "0.4.38" } dpp = { path = "../rs-dpp", default-features = false, features = [ "dash-sdk-features", @@ -43,6 +43,9 @@ lru = { version = "0.12.5", optional = true } bip37-bloom-filter = { git = "https://github.com/dashpay/rs-bip37-bloom-filter", branch = "develop" } zeroize = { version = "1.8", features = ["derive"] } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +tokio = { version = "1.40", features = ["macros", "time", "rt-multi-thread"] } + [dev-dependencies] rs-dapi-client = { path = "../rs-dapi-client" } drive-proof-verifier = { path = "../rs-drive-proof-verifier" } @@ -62,12 +65,7 @@ test-case = { version = "3.3.1" } [features] # TODO make a way to enable "tokio/rt-multi-thread" if someone uses --no-default-features -default = [ - "mocks", - "offline-testing", - "dapi-grpc/client", - "tokio/rt-multi-thread", -] +default = ["mocks", "offline-testing", "dapi-grpc/client"] mocks = [ "dep:serde", diff --git a/packages/rs-sdk/src/platform/transition/broadcast_identity.rs b/packages/rs-sdk/src/platform/transition/broadcast_identity.rs index f92bd77def4..dd38a1ce1a5 100644 --- a/packages/rs-sdk/src/platform/transition/broadcast_identity.rs +++ b/packages/rs-sdk/src/platform/transition/broadcast_identity.rs @@ -10,7 +10,7 @@ use std::fmt::Debug; use dapi_grpc::platform::v0::{self as proto, BroadcastStateTransitionRequest}; use dpp::dashcore::PrivateKey; use dpp::identity::signer::Signer; -#[cfg(not(feature = "wasm"))] +#[cfg(not(target_arch = "wasm32"))] use dpp::native_bls::NativeBlsModule; use dpp::prelude::{AssetLockProof, Identity}; use dpp::state_transition::identity_create_transition::methods::IdentityCreateTransitionMethodsV0; @@ -105,9 +105,9 @@ impl BroadcastRequestForNewIdentity Result<(StateTransition, BroadcastStateTransitionRequest), Error> { - #[cfg(feature = "wasm")] + #[cfg(target_arch = "wasm32")] unimplemented!("NativeBlsModule not implemented for wasm32"); - #[cfg(not(feature = "wasm"))] + #[cfg(not(target_arch = "wasm32"))] { let identity_create_transition = IdentityCreateTransition::try_from_identity_with_signer( diff --git a/packages/rs-sdk/src/sdk.rs b/packages/rs-sdk/src/sdk.rs index 5ac46f43153..74fbd6ff468 100644 --- a/packages/rs-sdk/src/sdk.rs +++ b/packages/rs-sdk/src/sdk.rs @@ -10,7 +10,7 @@ use crate::platform::{Fetch, Identifier}; use arc_swap::{ArcSwapAny, ArcSwapOption}; use dapi_grpc::mock::Mockable; use dapi_grpc::platform::v0::{Proof, ResponseMetadata}; -#[cfg(not(feature = "wasm"))] +#[cfg(not(target_arch = "wasm32"))] use dapi_grpc::tonic::transport::Certificate; use dpp::bincode; use dpp::bincode::error::DecodeError; @@ -759,7 +759,7 @@ pub struct SdkBuilder { pub(crate) cancel_token: CancellationToken, /// CA certificate to use for TLS connections. - #[cfg(not(feature = "wasm"))] + #[cfg(not(target_arch = "wasm32"))] ca_certificate: Option, } @@ -791,7 +791,7 @@ impl Default for SdkBuilder { cancel_token: CancellationToken::new(), version: PlatformVersion::latest(), - #[cfg(not(feature = "wasm"))] + #[cfg(not(target_arch = "wasm32"))] ca_certificate: None, #[cfg(feature = "mocks")] @@ -857,7 +857,7 @@ impl SdkBuilder { /// Used mainly for testing purposes and local networks. /// /// If not set, uses standard system CA certificates. - #[cfg(not(feature = "wasm"))] + #[cfg(not(target_arch = "wasm32"))] pub fn with_ca_certificate(mut self, pem_certificate: Certificate) -> Self { self.ca_certificate = Some(pem_certificate); self @@ -867,7 +867,7 @@ impl SdkBuilder { /// /// This is a convenience method that reads the certificate from a file and sets it using /// [SdkBuilder::with_ca_certificate()]. - #[cfg(not(feature = "wasm"))] + #[cfg(not(target_arch = "wasm32"))] pub fn with_ca_certificate_file( self, certificate_file_path: impl AsRef, @@ -1023,7 +1023,7 @@ impl SdkBuilder { Some(addresses) => { #[allow(unused_mut)] // needs to be mutable for features other than wasm let mut dapi = DapiClient::new(addresses, dapi_client_settings); - #[cfg(not(feature = "wasm"))] + #[cfg(not(target_arch = "wasm32"))] if let Some(pem) = self.ca_certificate { dapi = dapi.with_ca_certificate(pem); } diff --git a/packages/rs-sdk/src/sync.rs b/packages/rs-sdk/src/sync.rs index d0bf327501e..14a74acadd8 100644 --- a/packages/rs-sdk/src/sync.rs +++ b/packages/rs-sdk/src/sync.rs @@ -20,7 +20,7 @@ use tokio::sync::Mutex; #[derive(Debug, thiserror::Error)] pub enum AsyncError { /// Not running inside tokio runtime - #[cfg(not(feature = "wasm"))] + #[cfg(not(target_arch = "wasm32"))] #[error("not running inside tokio runtime: {0}")] NotInTokioRuntime(#[from] tokio::runtime::TryCurrentError), @@ -62,7 +62,7 @@ impl From for crate::Error { /// /// Due to limitations of tokio runtime, we cannot use `tokio::runtime::Runtime::block_on` if we are already inside a tokio runtime. /// This function is a workaround for that limitation. -#[cfg(not(feature = "wasm"))] +#[cfg(not(target_arch = "wasm32"))] pub fn block_on(fut: F) -> Result where F: Future + Send + 'static, @@ -85,7 +85,7 @@ where Ok(resp) } -#[cfg(feature = "wasm")] +#[cfg(target_arch = "wasm32")] pub fn block_on(_fut: F) -> Result where F: Future + Send + 'static, From 4d4c6a04f52c7dc4cb2f0cff0d776709fca63de5 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 13 Jan 2025 11:48:41 +0100 Subject: [PATCH 20/26] chore: replace deprecated FromMilis/ToMilis --- .../engine/finalize_block_proposal/v0/mod.rs | 2 +- .../initialization/init_chain/v0/mod.rs | 10 ++++- .../src/platform_types/block_proposal/v0.rs | 42 +++++++++---------- .../v0/mod.rs | 6 ++- 4 files changed, 34 insertions(+), 26 deletions(-) diff --git a/packages/rs-drive-abci/src/execution/engine/finalize_block_proposal/v0/mod.rs b/packages/rs-drive-abci/src/execution/engine/finalize_block_proposal/v0/mod.rs index ecfc3d6edf3..12ccb4f87b8 100644 --- a/packages/rs-drive-abci/src/execution/engine/finalize_block_proposal/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/engine/finalize_block_proposal/v0/mod.rs @@ -9,7 +9,7 @@ use dpp::block::extended_block_info::v0::ExtendedBlockInfoV0; use dpp::version::PlatformVersion; use tenderdash_abci::{ - proto::{serializers::timestamp::ToMilis, types::BlockId as ProtoBlockId}, + proto::{types::BlockId as ProtoBlockId, ToMillis}, signatures::Hashable, }; diff --git a/packages/rs-drive-abci/src/execution/engine/initialization/init_chain/v0/mod.rs b/packages/rs-drive-abci/src/execution/engine/initialization/init_chain/v0/mod.rs index b67cd012531..4e3bc0eb5bf 100644 --- a/packages/rs-drive-abci/src/execution/engine/initialization/init_chain/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/engine/initialization/init_chain/v0/mod.rs @@ -1,3 +1,4 @@ +use crate::abci::AbciError; use crate::error::execution::ExecutionError; use crate::error::Error; use crate::platform_types::platform::Platform; @@ -18,7 +19,7 @@ use dpp::version::PlatformVersion; use std::sync::Arc; use tenderdash_abci::proto::abci::{RequestInitChain, ResponseInitChain}; use tenderdash_abci::proto::google::protobuf::Timestamp; -use tenderdash_abci::proto::serializers::timestamp::FromMilis; +use tenderdash_abci::proto::FromMillis; impl Platform where @@ -154,7 +155,12 @@ where validator_set_update: Some(validator_set), next_core_chain_lock_update: None, initial_core_height: core_height, // we send back the core height when the fork happens - genesis_time: Some(Timestamp::from_milis(genesis_time)), + genesis_time: Some(Timestamp::from_millis(genesis_time).map_err(|e| { + AbciError::InvalidChainLock(format!( + "chainlock contains invalid genesis time: {}", + e + )) + })?), }) } } diff --git a/packages/rs-drive-abci/src/platform_types/block_proposal/v0.rs b/packages/rs-drive-abci/src/platform_types/block_proposal/v0.rs index 7ed2273d95d..783dd18ace0 100644 --- a/packages/rs-drive-abci/src/platform_types/block_proposal/v0.rs +++ b/packages/rs-drive-abci/src/platform_types/block_proposal/v0.rs @@ -5,10 +5,12 @@ use dpp::dashcore::hashes::Hash; use dpp::dashcore::{BlockHash, ChainLock}; use dpp::platform_value::Bytes32; use std::fmt; -use tenderdash_abci::proto::abci::{RequestPrepareProposal, RequestProcessProposal}; -use tenderdash_abci::proto::serializers::timestamp::ToMilis; -use tenderdash_abci::proto::types::CoreChainLock; -use tenderdash_abci::proto::version::Consensus; +use tenderdash_abci::proto::{ + abci::{RequestPrepareProposal, RequestProcessProposal}, + types::CoreChainLock, + version::Consensus, + ToMillis, +}; /// The block proposal is the combination of information that a proposer will propose, /// Or that a validator or full node will process @@ -37,7 +39,7 @@ pub struct BlockProposal<'a> { pub raw_state_transitions: &'a Vec>, } -impl<'a> fmt::Debug for BlockProposal<'a> { +impl fmt::Debug for BlockProposal<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!(f, "BlockProposal {{")?; writeln!(f, " consensus_versions: {:?},", self.consensus_versions)?; @@ -96,18 +98,16 @@ impl<'a> TryFrom<&'a RequestPrepareProposal> for BlockProposal<'a> { version, quorum_hash, } = value; - let consensus_versions = version - .as_ref() - .ok_or(AbciError::BadRequest( - "request is missing version".to_string(), - ))? - .clone(); + let consensus_versions = version.as_ref().ok_or(AbciError::BadRequest( + "request is missing version".to_string(), + ))?; let block_time_ms = time .as_ref() .ok_or(AbciError::BadRequest( "request is missing block time".to_string(), ))? - .to_milis(); + .to_millis() + .map_err(|e| AbciError::BadRequest(format!("invalid block time: {}", e)))?; let proposer_pro_tx_hash: [u8; 32] = proposer_pro_tx_hash.clone().try_into().map_err(|e| { AbciError::BadRequestDataSize(format!( @@ -135,7 +135,7 @@ impl<'a> TryFrom<&'a RequestPrepareProposal> for BlockProposal<'a> { .into()); } Ok(Self { - consensus_versions, + consensus_versions: *consensus_versions, block_hash: None, height: *height as u64, round: *round as u32, @@ -171,18 +171,18 @@ impl<'a> TryFrom<&'a RequestProcessProposal> for BlockProposal<'a> { version, quorum_hash, } = value; - let consensus_versions = version - .as_ref() - .ok_or(AbciError::BadRequest( - "process proposal request is missing version".to_string(), - ))? - .clone(); + let consensus_versions = version.as_ref().ok_or(AbciError::BadRequest( + "process proposal request is missing version".to_string(), + ))?; let block_time_ms = time .as_ref() .ok_or(Error::Abci(AbciError::BadRequest( "missing proposal time".to_string(), )))? - .to_milis(); + .to_millis() + .map_err(|e| { + Error::Abci(AbciError::BadRequest(format!("invalid block time: {}", e))) + })?; let proposer_pro_tx_hash: [u8; 32] = proposer_pro_tx_hash.clone().try_into().map_err(|e| { Error::Abci(AbciError::BadRequestDataSize(format!( @@ -239,7 +239,7 @@ impl<'a> TryFrom<&'a RequestProcessProposal> for BlockProposal<'a> { }) .transpose()?; Ok(Self { - consensus_versions, + consensus_versions: *consensus_versions, block_hash: Some(block_hash), height: *height as u64, round: *round as u32, diff --git a/packages/rs-drive-abci/src/platform_types/cleaned_abci_messages/request_init_chain_cleaned_params/v0/mod.rs b/packages/rs-drive-abci/src/platform_types/cleaned_abci_messages/request_init_chain_cleaned_params/v0/mod.rs index cccbfb02342..886aa1fd574 100644 --- a/packages/rs-drive-abci/src/platform_types/cleaned_abci_messages/request_init_chain_cleaned_params/v0/mod.rs +++ b/packages/rs-drive-abci/src/platform_types/cleaned_abci_messages/request_init_chain_cleaned_params/v0/mod.rs @@ -38,7 +38,7 @@ use dpp::util::deserializer::ProtocolVersion; use drive::dpp::identity::TimestampMillis; use serde::{Deserialize, Serialize}; use tenderdash_abci::proto::abci::RequestInitChain; -use tenderdash_abci::proto::serializers::timestamp::ToMilis; +use tenderdash_abci::proto::ToMillis; /// A struct for handling chain initialization requests #[derive(Serialize, Deserialize)] @@ -65,7 +65,9 @@ impl TryFrom for RequestInitChainCleanedParams { .ok_or(AbciError::BadRequest( "genesis time is required in init chain".to_string(), ))? - .to_milis() as TimestampMillis; + .to_millis() + .map_err(|e| AbciError::BadRequest(format!("genesis time is invalid: {}", e)))? + as TimestampMillis; let initial_core_height = match request.initial_core_height { 0 => None, h => Some(h), From 9df8371c2d4ad5e38bc35e81a7dc4ca21a2afc94 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 13 Jan 2025 12:02:47 +0100 Subject: [PATCH 21/26] chore(drive-abci): fix build --- .../src/execution/engine/finalize_block_proposal/v0/mod.rs | 5 ++++- packages/rs-drive-abci/src/mimic/mod.rs | 6 ++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/packages/rs-drive-abci/src/execution/engine/finalize_block_proposal/v0/mod.rs b/packages/rs-drive-abci/src/execution/engine/finalize_block_proposal/v0/mod.rs index 12ccb4f87b8..c8d71074316 100644 --- a/packages/rs-drive-abci/src/execution/engine/finalize_block_proposal/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/engine/finalize_block_proposal/v0/mod.rs @@ -195,7 +195,10 @@ where .expect("current epoch info should be in range"), ); - to_commit_block_info.time_ms = block_header.time.to_milis(); + to_commit_block_info.time_ms = block_header + .time + .to_millis() + .map_err(|e| AbciError::BadRequest(format!("invalid block time: {}", e)))?; to_commit_block_info.core_height = block_header.core_chain_locked_height; diff --git a/packages/rs-drive-abci/src/mimic/mod.rs b/packages/rs-drive-abci/src/mimic/mod.rs index f0c5f895bca..0cf59e80e0f 100644 --- a/packages/rs-drive-abci/src/mimic/mod.rs +++ b/packages/rs-drive-abci/src/mimic/mod.rs @@ -34,11 +34,11 @@ use tenderdash_abci::proto::abci::{ ValidatorSetUpdate, }; use tenderdash_abci::proto::google::protobuf::Timestamp; -use tenderdash_abci::proto::serializers::timestamp::ToMilis; use tenderdash_abci::proto::types::{ Block, BlockId, CanonicalVote, Data, EvidenceList, Header, PartSetHeader, SignedMsgType, StateId, VoteExtension, VoteExtensionType, }; +use tenderdash_abci::proto::ToMillis; use tenderdash_abci::signatures::Hashable; use tenderdash_abci::{proto::version::Consensus, signatures::Signable, Application}; @@ -239,7 +239,9 @@ impl<'a, C: CoreRPCLike> FullAbciApplication<'a, C> { app_version, core_chain_locked_height: core_height, height, - time: time.to_milis(), + time: time + .to_millis() + .expect("expected to convert time to millis"), }; let state_id_hash = state_id .calculate_msg_hash(CHAIN_ID, height as i64, round as i32) From 6cb9d1902ccc788b80cb6f82eadba78202994289 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 13 Jan 2025 12:11:14 +0100 Subject: [PATCH 22/26] chore: fix rs-dapi-client build --- packages/rs-dapi-client/Cargo.toml | 2 +- packages/rs-dapi-client/src/lib.rs | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/rs-dapi-client/Cargo.toml b/packages/rs-dapi-client/Cargo.toml index ece8c2cad17..7996dd12b92 100644 --- a/packages/rs-dapi-client/Cargo.toml +++ b/packages/rs-dapi-client/Cargo.toml @@ -30,7 +30,6 @@ backon = { version = "1.3", default-features = false, features = [ gloo-timers = { version = "0.3.0", features = ["futures"] } tonic-web-wasm-client = { version = "0.6.0" } wasm-bindgen-futures = { version = "0.4.49" } -http = { version = "1.1.0", default-features = false } getrandom = { version = "0.2", features = ["js"] } [dependencies] @@ -41,6 +40,7 @@ dapi-grpc = { path = "../dapi-grpc", features = [ "client", ], default-features = false } futures = { version = "0.3.28" } +http = { version = "1.1.0", default-features = false } http-serde = { version = "2.1", optional = true } diff --git a/packages/rs-dapi-client/src/lib.rs b/packages/rs-dapi-client/src/lib.rs index 110fe8fd6bc..c54e4d3f65b 100644 --- a/packages/rs-dapi-client/src/lib.rs +++ b/packages/rs-dapi-client/src/lib.rs @@ -26,11 +26,10 @@ pub use executor::{ WrapToExecutionResult, }; use futures::{future::BoxFuture, FutureExt}; -#[cfg(target_arch = "wasm32")] +#[cfg(any(target_arch = "wasm32", not(feature = "mocks")))] pub use http::Uri; -#[cfg(not(target_arch = "wasm32"))] +#[cfg(all(feature = "mocks", not(target_arch = "wasm32")))] pub use http_serde::http::Uri; - pub use request_settings::RequestSettings; /// A DAPI request could be executed with an initialized [DapiClient]. From f594438090cffbd1d0b6b8de8f51584889a7fedf Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 13 Jan 2025 12:17:04 +0100 Subject: [PATCH 23/26] chore: exclude wasm-sdk from cargo.toml --- Cargo.lock | 119 +++++++++++------------------------------------------ Cargo.toml | 3 +- 2 files changed, 25 insertions(+), 97 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cc63a448f43..73de44ee340 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -29,7 +29,7 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "cipher", "cpufeatures", ] @@ -51,7 +51,7 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "getrandom", "once_cell", "serde", @@ -325,7 +325,7 @@ checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a" dependencies = [ "addr2line", "cc", - "cfg-if 1.0.0", + "cfg-if", "libc", "miniz_oxide 0.7.4", "object", @@ -504,7 +504,7 @@ dependencies = [ "arrayref", "arrayvec", "cc", - "cfg-if 1.0.0", + "cfg-if", "constant_time_eq 0.3.1", ] @@ -724,12 +724,6 @@ dependencies = [ "nom", ] -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - [[package]] name = "cfg-if" version = "1.0.0" @@ -940,16 +934,6 @@ dependencies = [ "tracing-subscriber", ] -[[package]] -name = "console_error_panic_hook" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" -dependencies = [ - "cfg-if 1.0.0", - "wasm-bindgen", -] - [[package]] name = "const-oid" version = "0.9.6" @@ -1014,7 +998,7 @@ version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", ] [[package]] @@ -1122,7 +1106,7 @@ version = "4.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "cpufeatures", "curve25519-dalek-derive", "digest", @@ -1724,7 +1708,7 @@ version = "0.8.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b45de904aa0b010bce2ab45264d0631681847fa7b6f2eaa7dab7619943bc4f59" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", ] [[package]] @@ -2110,7 +2094,7 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "js-sys", "libc", "wasi", @@ -2326,7 +2310,7 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dd08c532ae367adf81c312a4580bc67f1d0fe8bc9c460520283f4c0ff277888" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "crunchy", ] @@ -2897,7 +2881,7 @@ version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "windows-targets 0.52.6", ] @@ -3012,12 +2996,6 @@ version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" -[[package]] -name = "memory_units" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8452105ba047068f40ff7093dd1d9da90898e63dd61736462e9cdda6a90ad3c3" - [[package]] name = "merlin" version = "3.0.0" @@ -3132,7 +3110,7 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4c28b3fb6d753d28c20e826cd46ee611fda1cf3cde03a443a974043247c065a" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "downcast", "fragile", "mockall_derive", @@ -3146,7 +3124,7 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "341014e7f530314e9a1fdbc7400b244efea7122662c96bfa248c31da5bfb2020" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "proc-macro2", "quote", "syn 2.0.94", @@ -3425,7 +3403,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9529f4786b70a3e8c61e11179af17ab6188ad8d0ded78c5529441ed39d4bd9c1" dependencies = [ "bitflags 2.6.0", - "cfg-if 1.0.0", + "cfg-if", "foreign-types", "libc", "once_cell", @@ -3499,7 +3477,7 @@ version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "libc", "redox_syscall", "smallvec", @@ -4109,7 +4087,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" dependencies = [ "cc", - "cfg-if 1.0.0", + "cfg-if", "getrandom", "libc", "spin", @@ -4430,17 +4408,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "serde-wasm-bindgen" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b" -dependencies = [ - "js-sys", - "serde", - "wasm-bindgen", -] - [[package]] name = "serde_bare" version = "0.5.0" @@ -4599,7 +4566,7 @@ version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "cpufeatures", "digest", ] @@ -4610,7 +4577,7 @@ version = "0.10.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "cpufeatures", "digest", ] @@ -4917,7 +4884,7 @@ version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04cbcdd0c794ebb0d4cf35e88edd2f7d2c4c3e9a5a6dab322839b321c6a87a64" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "fastrand", "once_cell", "rustix", @@ -5008,7 +4975,7 @@ version = "3.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adcb7fd841cd518e279be3d5a3eb0636409487998a4aff22f3de87b81e88384f" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "proc-macro2", "quote", "syn 2.0.94", @@ -5092,7 +5059,7 @@ version = "1.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "once_cell", ] @@ -5507,17 +5474,6 @@ dependencies = [ "tracing-serde", ] -[[package]] -name = "tracing-wasm" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4575c663a174420fa2d78f4108ff68f65bf2fbb7dd89f33749b6e826b3626e07" -dependencies = [ - "tracing", - "tracing-subscriber", - "wasm-bindgen", -] - [[package]] name = "treediff" version = "5.0.0" @@ -5741,7 +5697,7 @@ version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a474f6281d1d70c17ae7aa6a613c87fce69a127e2624002df63dcb39d6cf6396" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "once_cell", "wasm-bindgen-macro", ] @@ -5766,7 +5722,7 @@ version = "0.4.49" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38176d9b44ea84e9184eff0bc34cc167ed044f816accfe5922e54d84cf48eca2" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "js-sys", "once_cell", "wasm-bindgen", @@ -5817,7 +5773,7 @@ dependencies = [ "num_enum 0.7.3", "paste", "serde", - "serde-wasm-bindgen 0.5.0", + "serde-wasm-bindgen", "serde_json", "thiserror 1.0.64", "wasm-bindgen", @@ -5837,23 +5793,6 @@ dependencies = [ "web-sys", ] -[[package]] -name = "wasm-sdk" -version = "0.1.0" -dependencies = [ - "console_error_panic_hook", - "dash-sdk", - "drive-proof-verifier", - "platform-value", - "serde-wasm-bindgen 0.6.5", - "thiserror 2.0.9", - "tracing-wasm", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "wee_alloc", -] - [[package]] name = "wasm-streams" version = "0.4.1" @@ -5886,18 +5825,6 @@ dependencies = [ "rustls-pki-types", ] -[[package]] -name = "wee_alloc" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbb3b5a6b2bb17cb6ad44a2e68a43e8d2722c997da10e928665c72ec6c0a0b8e" -dependencies = [ - "cfg-if 0.1.10", - "libc", - "memory_units", - "winapi", -] - [[package]] name = "which" version = "4.4.2" diff --git a/Cargo.toml b/Cargo.toml index 88767db3719..d005160f041 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,8 @@ members = [ "packages/simple-signer", "packages/rs-json-schema-compatibility-validator", "packages/check-features", - "packages/wallet-utils-contract", "packages/wasm-sdk", + "packages/wallet-utils-contract", + # "packages/wasm-sdk", # This one is experimental and not ready for use ] [workspace.package] From cdccee522f400ecb7b0e7f904b01f42fed86efbf Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 13 Jan 2025 12:41:42 +0100 Subject: [PATCH 24/26] chore(drive-abci): fix build and tests --- .../rs-drive-abci/tests/strategy_tests/execution.rs | 4 ++-- packages/rs-drive-abci/tests/strategy_tests/query.rs | 10 +++++----- packages/rs-platform-value/src/inner_value.rs | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/rs-drive-abci/tests/strategy_tests/execution.rs b/packages/rs-drive-abci/tests/strategy_tests/execution.rs index d02a11e9500..64948002729 100644 --- a/packages/rs-drive-abci/tests/strategy_tests/execution.rs +++ b/packages/rs-drive-abci/tests/strategy_tests/execution.rs @@ -43,7 +43,7 @@ use std::collections::{BTreeMap, HashMap}; use tenderdash_abci::proto::abci::{ResponseInitChain, ValidatorSetUpdate}; use tenderdash_abci::proto::crypto::public_key::Sum::Bls12381; use tenderdash_abci::proto::google::protobuf::Timestamp; -use tenderdash_abci::proto::serializers::timestamp::FromMilis; +use tenderdash_abci::proto::FromMillis; use tenderdash_abci::Application; pub const GENESIS_TIME_MS: u64 = 1681094380000; @@ -1156,7 +1156,7 @@ pub(crate) fn continue_chain_for_strategy( height: state_id.height as i64, block_hash: &block_hash, app_hash: &root_app_hash, - time: Timestamp::from_milis(state_id.time), + time: Timestamp::from_millis(state_id.time).expect("must convert to millis"), signature: &signature, public_key: ¤t_quorum_with_test_info.public_key, }, diff --git a/packages/rs-drive-abci/tests/strategy_tests/query.rs b/packages/rs-drive-abci/tests/strategy_tests/query.rs index 56f166ab749..4a4103c4dbc 100644 --- a/packages/rs-drive-abci/tests/strategy_tests/query.rs +++ b/packages/rs-drive-abci/tests/strategy_tests/query.rs @@ -24,8 +24,8 @@ use rand::{Rng, SeedableRng}; use std::collections::HashMap; use strategy_tests::frequency::Frequency; use tenderdash_abci::proto::google::protobuf::Timestamp; -use tenderdash_abci::proto::serializers::timestamp::ToMilis; use tenderdash_abci::proto::types::{CanonicalVote, SignedMsgType, StateId}; +use tenderdash_abci::proto::ToMillis; use tenderdash_abci::signatures::{Hashable, Signable}; #[derive(Clone, Debug, Default)] @@ -72,7 +72,7 @@ pub struct ProofVerification<'a> { pub public_key: &'a dpp::bls_signatures::PublicKey, } -impl<'a> ProofVerification<'a> { +impl ProofVerification<'_> { /// Verify proof signature /// /// Constructs new signature for provided state ID and checks if signature is still valid. @@ -157,7 +157,7 @@ impl<'a> ProofVerification<'a> { app_version: self.app_version, core_chain_locked_height: self.core_chain_locked_height, height: self.height as u64, - time: self.time.to_milis(), + time: self.time.to_millis().expect("time as milliseconds"), }; self.verify_signature(state_id, proof.round) @@ -168,7 +168,7 @@ impl QueryStrategy { pub(crate) fn query_chain_for_strategy( &self, proof_verification: &ProofVerification, - current_identities: &Vec, + current_identities: &[Identity], abci_app: &FullAbciApplication, seed: StrategyRandomness, platform_version: &PlatformVersion, @@ -194,7 +194,7 @@ impl QueryStrategy { pub(crate) fn query_identities_by_public_key_hashes( proof_verification: &ProofVerification, - current_identities: &Vec, + current_identities: &[Identity], frequency: &Frequency, abci_app: &FullAbciApplication, rng: &mut StdRng, diff --git a/packages/rs-platform-value/src/inner_value.rs b/packages/rs-platform-value/src/inner_value.rs index c92828e91c0..d8606bd478b 100644 --- a/packages/rs-platform-value/src/inner_value.rs +++ b/packages/rs-platform-value/src/inner_value.rs @@ -361,7 +361,7 @@ impl Value { Self::inner_array_mut_ref(map, key) } - pub fn get_array_slice<'a>(&'a self, key: &'a str) -> Result<&[Value], Error> { + pub fn get_array_slice<'a>(&'a self, key: &'a str) -> Result<&'a [Value], Error> { let map = self.to_map()?; Self::inner_array_slice(map, key) } From 96899b580d3565f3cc9ab994a2a34d0a452dcb1d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 13 Jan 2025 12:54:08 +0100 Subject: [PATCH 25/26] chore(dpp): fix dpp build with no features --- packages/rs-dpp/Cargo.toml | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/packages/rs-dpp/Cargo.toml b/packages/rs-dpp/Cargo.toml index b8c993e3421..de5897134c3 100644 --- a/packages/rs-dpp/Cargo.toml +++ b/packages/rs-dpp/Cargo.toml @@ -28,7 +28,7 @@ dashcore = { git = "https://github.com/dashpay/rust-dashcore", features = [ "rand", "signer", "serde", -], default-features = false, tag = "0.34.0", optional = true } +], default-features = false, tag = "0.34.0" } getrandom = { version = "0.2", features = ["js"] } hex = { version = "0.4" } integer-encoding = { version = "4.0.0" } @@ -47,7 +47,7 @@ serde_repr = { version = "0.1.7" } sha2 = { version = "0.10" } thiserror = { version = "1.0" } data-contracts = { path = "../data-contracts", optional = true } -platform-value = { path = "../rs-platform-value", optional = true } +platform-value = { path = "../rs-platform-value" } platform-version = { path = "../rs-platform-version" } platform-versioning = { path = "../rs-platform-versioning" } platform-serialization = { path = "../rs-platform-serialization" } @@ -72,12 +72,11 @@ env_logger = { version = "0.11" } log = { version = "0.4.22" } [features] -default = ["platform-value", "state-transitions"] +default = ["state-transitions"] bls-signatures = ["dashcore/bls"] ed25519-dalek = ["dashcore/eddsa"] all_features = [ "json-object", - "platform-value", "system_contracts", "state-transitions", "extended-document", @@ -125,13 +124,13 @@ dash-sdk-features = [ # "platform-value", # "system_contracts", # "validation", # TODO: This one is big - "identity-hashing", + "identity-hashing", "data-contract-json-conversion", # "identity-serialization", # "vote-serialization", # "document-value-conversion", # "data-contract-value-conversion", - "identity-value-conversion", + "identity-value-conversion", # "core-types", # "core-types-serialization", # "core-types-serde-conversion", From 5147a411ce477ca3f3eacb2a670c286fb813eac4 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 13 Jan 2025 13:55:33 +0100 Subject: [PATCH 26/26] chore: minor refactor --- packages/rs-dapi-client/src/transport.rs | 2 +- packages/rs-dapi-client/src/transport/tonic_channel.rs | 2 +- packages/rs-sdk/Cargo.toml | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/rs-dapi-client/src/transport.rs b/packages/rs-dapi-client/src/transport.rs index fc80cef58f0..3e342dbd708 100644 --- a/packages/rs-dapi-client/src/transport.rs +++ b/packages/rs-dapi-client/src/transport.rs @@ -16,7 +16,7 @@ use std::fmt::Debug; #[cfg(not(target_arch = "wasm32"))] pub use tonic_channel::{ - create_channel, CoreGrpcClient, PlatformGrpcClient, TonicBackonSleeper as BackonSleeper, + create_channel, CoreGrpcClient, PlatformGrpcClient, TokioBackonSleeper as BackonSleeper, }; #[cfg(target_arch = "wasm32")] pub use wasm_channel::{ diff --git a/packages/rs-dapi-client/src/transport/tonic_channel.rs b/packages/rs-dapi-client/src/transport/tonic_channel.rs index 927dcc91b39..0df0f55bf2a 100644 --- a/packages/rs-dapi-client/src/transport/tonic_channel.rs +++ b/packages/rs-dapi-client/src/transport/tonic_channel.rs @@ -11,7 +11,7 @@ pub type CoreGrpcClient = CoreClient; /// backon::Sleeper // #[derive(Default, Clone, Debug)] -pub type TonicBackonSleeper = backon::TokioSleeper; +pub type TokioBackonSleeper = backon::TokioSleeper; // impl backon::Sleeper for TonicBackonSleeper { // type Sleep = ::Sleep; diff --git a/packages/rs-sdk/Cargo.toml b/packages/rs-sdk/Cargo.toml index ffe852f195f..1be9978ede2 100644 --- a/packages/rs-sdk/Cargo.toml +++ b/packages/rs-sdk/Cargo.toml @@ -65,7 +65,6 @@ test-case = { version = "3.3.1" } assert_matches = "1.5.0" [features] -# TODO make a way to enable "tokio/rt-multi-thread" if someone uses --no-default-features default = ["mocks", "offline-testing", "dapi-grpc/client"] mocks = [