diff --git a/.github/workflows/validate_pr.yml b/.github/workflows/validate_pr.yml index 7013aedf..9b7a17c4 100644 --- a/.github/workflows/validate_pr.yml +++ b/.github/workflows/validate_pr.yml @@ -2,40 +2,80 @@ name: Test and Check on: push: - branches: - - main + branches: [main] pull_request: + branches: [main] + paths-ignore: + - "README.md" + + workflow_dispatch: jobs: test: + concurrency: + group: test-${{ github.ref }} + cancel-in-progress: true runs-on: ubuntu-latest steps: - - name: Checkout code - uses: actions/checkout@v2 + - name: Checkout code + uses: actions/checkout@v2 + + - name: Install toolchain + id: toolchain + uses: actions-rs/toolchain@master + with: + profile: minimal + toolchain: stable + target: wasm32-unknown-unknown + + - name: Install protobuf-compiler + run: sudo apt-get install protobuf-compiler + + - name: Rust Cache + uses: Swatinem/rust-cache@v1.3.0 - - uses: actions-rs/toolchain@v1 - with: - toolchain: nightly-2023-07-16 - components: clippy + - name: Test workspace + run: cargo test --package pallet-eth2-light-client + + rustfmt: + concurrency: + group: rustfmt-${{ github.ref }} + cancel-in-progress: true + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Install latest stable + uses: actions-rs/toolchain@v1 + with: + toolchain: stable override: true - - - name: Install toolchain - id: toolchain - uses: actions-rs/toolchain@master - with: - profile: minimal - toolchain: nightly-2023-07-16 - target: wasm32-unknown-unknown - - - name: Install protobuf-compiler - run: sudo apt-get install protobuf-compiler - - - name: Rust Cache - uses: Swatinem/rust-cache@v1.3.0 - - - name: Test workspace - run: cargo test --package pallet-eth2-light-client - - - name: Clippy - run: cargo clippy --package pallet-eth2-light-client -- -D warnings \ No newline at end of file + components: rustfmt + + - name: Rustfmt check + run: cargo fmt --all -- --check + + clippy: + concurrency: + group: clippy-${{ github.ref }} + cancel-in-progress: true + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Install toolchain + id: toolchain + uses: actions-rs/toolchain@master + with: + profile: minimal + toolchain: stable + target: wasm32-unknown-unknown + + - name: Rust Cache + uses: Swatinem/rust-cache@v1.3.0 + + - name: Install Protobuf + run: sudo apt-get install protobuf-compiler + + - name: Run clippy + run: cargo clippy --package pallet-eth2-light-client -- -D warnings diff --git a/Cargo.toml b/Cargo.toml index f1420feb..b2b36837 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ members = [ "runtime", "primitives", ] +resolver = "2" [patch] [patch.crates-io] @@ -29,9 +30,9 @@ funty = "2.0.0" anyhow = "1.0" typed-builder = "0.16.0" log = { version = "0.4", default-features = false } -serde_json = { version = "1.0.74", default-features = false } -serde = { version = "1.0", features = ["derive"], default-features = false } -reqwest = { version = "0.11", features = ["blocking", "json"] } +serde_json = { version = "1.0.85", default-features = false, features = ["alloc"] } +serde = { version = "1.0.197", features = ["derive"], default-features = false } +reqwest = { version = "0.11.22", features = ["blocking", "json"] } clap = { version = "4.0.9", features = ["derive"] } tokio = { version = "1.1", features = ["macros", "rt", "time", "signal"] } env_logger = "0.9.0" @@ -76,91 +77,86 @@ zeroize = { version = "1.4.2", features = [ "zeroize_derive", ], default-features = false } -subxt = "0.29.0" -webb-relayer-utils = { git = "https://github.com/webb-tools/relayer.git" } -webb-relayer-types = { git = "https://github.com/webb-tools/relayer.git" } -webb = { version = "0.7.3", default-features = false, features = [ - "evm-runtime", - "substrate-runtime", -]} -webb-proposals = { git = "https://github.com/webb-tools/webb-rs", default-features = false, features = ["scale", "evm"] } - +subxt = "0.31.0" +subxt-signer = "0.31.0" +tangle-subxt = { git = "https://github.com/webb-tools/tangle" , rev = "8be20aa02a764422e1fd0ba30bc70b99d5f66887"} +webb-proposals = { git = "https://github.com/webb-tools/webb-rs", branch = "salman/polkadot-v1.7.0", default-features = false, features = ["scale", "evm"] } milagro_bls = { git = "https://github.com/Snowfork/milagro_bls", default-features = false, rev="a6d66e4eb89015e352fb1c9f7b661ecdbb5b2176" } -types = { git = "https://github.com/webb-tools/lighthouse.git", rev="ef72e752eaf45f4b7eb64dd8dbb0fe088f955df8" } -merkle_proof = { git = "https://github.com/webb-tools/lighthouse.git", rev="ef72e752eaf45f4b7eb64dd8dbb0fe088f955df8" } +types = { git = "https://github.com/webb-tools/lighthouse.git" } +merkle_proof = { git = "https://github.com/webb-tools/lighthouse.git" } tree_hash = { version = "0.5.0", features = ["arbitrary"], default-features = false } ethereum_hashing = { version = "1.0.0-beta.2", default-features = false } ethereum_ssz = { version = "0.5.0", features = ["arbitrary"], default-features = false } -sc-cli = { version = "0.10.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-offchain = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-core = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-executor = { version = "0.10.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-network = { version = "0.10.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-service = { version = "0.10.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-telemetry = { version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-keystore = { version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-transaction-pool = { version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-transaction-pool-api = { version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-consensus-aura = { version = "0.10.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-consensus-aura = { default-features = false, version = "0.10.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-consensus = { version = "0.10.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-consensus = { version = "0.10.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-consensus-grandpa = { version = "0.10.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-consensus-grandpa = { default-features = false, version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-client-api = { version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-io = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-timestamp = { version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-inherents = { default-features = false, version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-keyring = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-std = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -frame-system = { default-features = false, version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -frame-support = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -pallet-staking = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -pallet-transaction-payment = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -pallet-balances = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -pallet-grandpa = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -pallet-indices = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -pallet-session = { version = "4.0.0-dev", features = ["historical"], default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -pallet-staking-reward-curve = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -pallet-sudo = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -pallet-timestamp = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -pallet-utility = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-block-builder = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-offchain = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-session = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-staking = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-transaction-pool = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-version = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -frame-executive = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -frame-try-runtime = { version = "0.10.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } +sc-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sc-offchain = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-core = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sc-executor = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sc-network = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sc-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sc-telemetry = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sc-keystore = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sc-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sc-transaction-pool-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sc-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-consensus-aura = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-consensus = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sc-consensus = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sc-consensus-grandpa = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-consensus-grandpa = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sc-client-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0", features = ["serde"] } +sp-io = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-inherents = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-keyring = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-std = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +frame-system = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +frame-support = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +pallet-staking = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +pallet-transaction-payment = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +pallet-balances = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +pallet-grandpa = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +pallet-indices = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +pallet-session = { features = ["historical"], default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +pallet-staking-reward-curve = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +pallet-sudo = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +pallet-timestamp = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +pallet-utility = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-block-builder = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-offchain = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-session = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-staking = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-transaction-pool = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-version = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +frame-executive = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +frame-try-runtime = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } -pallet-aura = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -pallet-bags-list = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -frame-election-provider-support = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -pallet-election-provider-multi-phase = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } +pallet-aura = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +pallet-bags-list = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +frame-election-provider-support = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +pallet-election-provider-multi-phase = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } # These dependencies are used for the node template's RPCs -jsonrpsee = { version = "0.16.2", default-features = false } -sc-rpc = { version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-api = { version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0", default-features = false } -sc-rpc-api = { version = "0.10.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sp-blockchain = { version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -sc-basic-authorship = { version = "0.10.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -substrate-frame-rpc-system = { version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -pallet-transaction-payment-rpc = { version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } +jsonrpsee = { version = "0.20.3", features = ["server"] } +sc-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0", default-features = false } +sc-rpc-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +sp-blockchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0", default-features = false } +sc-basic-authorship = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +substrate-frame-rpc-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } # Used for the node template's RPCs -frame-system-rpc-runtime-api = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -pallet-transaction-payment-rpc-runtime-api = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } +frame-system-rpc-runtime-api = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +pallet-transaction-payment-rpc-runtime-api = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } # These dependencies are used for runtime benchmarking -frame-benchmarking = { version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -frame-benchmarking-cli = { version = "4.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -frame-system-benchmarking = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } -try-runtime-cli = { version = "0.10.0-dev", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } +frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +frame-system-benchmarking = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } +try-runtime-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.7.0" } # local deps pallet-eth2-light-client = { path = "./pallets/eth2-light-client", default-features = false } diff --git a/crates/bls/src/generic_aggregate_signature.rs b/crates/bls/src/generic_aggregate_signature.rs index 5d7f9f04..ce281341 100644 --- a/crates/bls/src/generic_aggregate_signature.rs +++ b/crates/bls/src/generic_aggregate_signature.rs @@ -196,7 +196,7 @@ where /// Verify that `self` represents an aggregate signature where all `pubkeys` have signed `msg`. pub fn fast_aggregate_verify(&self, msg: Hash256, pubkeys: &[&GenericPublicKey]) -> bool { if pubkeys.is_empty() { - return false + return false; } match self.point.as_ref() { @@ -227,7 +227,7 @@ where /// This function only exists for EF tests, it's presently not used in production. pub fn aggregate_verify(&self, msgs: &[Hash256], pubkeys: &[&GenericPublicKey]) -> bool { if msgs.is_empty() || msgs.len() != pubkeys.len() { - return false + return false; } match self.point.as_ref() { diff --git a/crates/bls/src/impls/milagro.rs b/crates/bls/src/impls/milagro.rs index 0e94d716..ad2bb108 100644 --- a/crates/bls/src/impls/milagro.rs +++ b/crates/bls/src/impls/milagro.rs @@ -32,7 +32,7 @@ pub fn verify_signature_sets<'a>( seed: [u8; 32], ) -> bool { if signature_sets.len() == 0 { - return false + return false; } signature_sets @@ -46,7 +46,7 @@ pub fn verify_signature_sets<'a>( } if signature_set.signature.point().is_none() { - return Err(()) + return Err(()); } Ok((signature_set.signature.as_ref(), aggregate, signature_set.message)) diff --git a/crates/bls/src/lib.rs b/crates/bls/src/lib.rs index 2e7a18a6..594be1e3 100644 --- a/crates/bls/src/lib.rs +++ b/crates/bls/src/lib.rs @@ -66,10 +66,12 @@ impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::MilagroError(_) => write!(f, "MilagroError"), - Error::InvalidByteLength { got, expected } => - write!(f, "InvalidByteLength {{ got: {got}, expected: {expected} }}"), - Error::InvalidSecretKeyLength { got, expected } => - write!(f, "InvalidSecretKeyLength {{ got: {got}, expected: {expected} }}"), + Error::InvalidByteLength { got, expected } => { + write!(f, "InvalidByteLength {{ got: {got}, expected: {expected} }}") + }, + Error::InvalidSecretKeyLength { got, expected } => { + write!(f, "InvalidSecretKeyLength {{ got: {got}, expected: {expected} }}") + }, Error::InvalidInfinityPublicKey => write!(f, "InvalidInfinityPublicKey"), Error::InvalidZeroSecretKey => write!(f, "InvalidZeroSecretKey"), } diff --git a/crates/bls/src/macros.rs b/crates/bls/src/macros.rs index 601c0989..dc59f990 100644 --- a/crates/bls/src/macros.rs +++ b/crates/bls/src/macros.rs @@ -1,6 +1,3 @@ -#[cfg(feature = "std")] -pub use eth2_serde_utils::hex as hex_encode; - /// Contains the functions required for a `TreeHash` implementation. /// /// Does not include the `Impl` section since it gets very complicated when it comes to generics. diff --git a/crates/bls/tests/tests.rs b/crates/bls/tests/tests.rs index 052fd35d..848e31d0 100644 --- a/crates/bls/tests/tests.rs +++ b/crates/bls/tests/tests.rs @@ -96,8 +96,8 @@ macro_rules! test_suite { #[test] fn partial_eq_infinity_agg_sig_and_real_agg_sig() { assert!( - AggregateSignature::infinity() != - AggregateSignatureTester::new_with_single_msg(1).sig + AggregateSignature::infinity() + != AggregateSignatureTester::new_with_single_msg(1).sig ) } diff --git a/crates/consensus-types/Cargo.toml b/crates/consensus-types/Cargo.toml index 671ebe1d..ed5cbb98 100644 --- a/crates/consensus-types/Cargo.toml +++ b/crates/consensus-types/Cargo.toml @@ -16,7 +16,7 @@ eth2-serde-utils = { package = "webb-eth2-serde-utils", path = "../serde-utils", bitvec = { workspace = true, features = ["atomic", "alloc"] } hex = { workspace = true } -codec = { workspace = true } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } scale-info = { workspace = true } serde = { workspace = true } rlp = { workspace = true } diff --git a/crates/consensus-types/src/lib.rs b/crates/consensus-types/src/lib.rs index afff85a0..936b2056 100644 --- a/crates/consensus-types/src/lib.rs +++ b/crates/consensus-types/src/lib.rs @@ -49,7 +49,7 @@ pub fn compute_fork_version( fork_version: ForkVersion, ) -> Option { if epoch >= bellatrix_epoch { - return Some(fork_version) + return Some(fork_version); } None @@ -66,7 +66,7 @@ pub fn compute_fork_version_by_slot( // Compute floor of log2 of a u32. pub const fn floorlog2(x: u32) -> u32 { if x == 0 { - return 0 + return 0; } 31 - x.leading_zeros() } @@ -119,7 +119,7 @@ pub fn convert_branch(branch: &[H256]) -> Vec { pub fn validate_beacon_block_header_update(header_update: &HeaderUpdate) -> bool { let branch = convert_branch(&header_update.execution_hash_branch); if branch.len() != EXECUTION_PROOF_SIZE { - return false + return false; } let l2_proof = &branch[0..L2_EXECUTION_PAYLOAD_PROOF_SIZE]; diff --git a/crates/consensus-types/src/network_config.rs b/crates/consensus-types/src/network_config.rs index f12f71e0..3878347b 100644 --- a/crates/consensus-types/src/network_config.rs +++ b/crates/consensus-types/src/network_config.rs @@ -74,11 +74,11 @@ impl NetworkConfig { pub fn compute_fork_version(&self, epoch: Epoch) -> Option { if epoch >= self.capella_fork_epoch { - return Some(self.capella_fork_version) + return Some(self.capella_fork_version); } if epoch >= self.bellatrix_fork_epoch { - return Some(self.bellatrix_fork_version) + return Some(self.bellatrix_fork_version); } None diff --git a/crates/eth-rpc-client/src/beacon_rpc_client.rs b/crates/eth-rpc-client/src/beacon_rpc_client.rs index 71c3046e..ab6706a4 100644 --- a/crates/eth-rpc-client/src/beacon_rpc_client.rs +++ b/crates/eth-rpc-client/src/beacon_rpc_client.rs @@ -249,8 +249,9 @@ impl BeaconRPCClient { let light_client_snapshot_json_str = self.get_json_from_raw_request(&url).await?; let parsed_json: Value = serde_json::from_str(&light_client_snapshot_json_str)?; let beacon_header: BeaconBlockHeader = match self.routes.version { - BeaconRPCVersion::V1_5 => - serde_json::from_value(parsed_json["data"]["header"]["beacon"].clone())?, + BeaconRPCVersion::V1_5 => { + serde_json::from_value(parsed_json["data"]["header"]["beacon"].clone())? + }, _ => serde_json::from_value(parsed_json["data"]["header"].clone())?, }; @@ -358,7 +359,7 @@ impl BeaconRPCClient { trace!(target: "relay", "Beacon chain request: {}", url); let json_str = client.get(url).await?; if serde_json::from_str::(&json_str).is_err() { - return Err(FailOnGettingJson { response: json_str }.into()) + return Err(FailOnGettingJson { response: json_str }.into()); } Ok(json_str) @@ -453,13 +454,13 @@ impl BeaconRPCClient { .sync_committee_signature ) == serde_json::to_string(&sync_aggregate.sync_committee_signature)? { - break + break; } } signature_slot += 1; if signature_slot - attested_header.slot > CHECK_SLOTS_FORWARD_LIMIT { - return Err(SignatureSlotNotFoundError.into()) + return Err(SignatureSlotNotFoundError.into()); } } @@ -584,7 +585,7 @@ impl BeaconRPCClient { if parse_json.is_object() { if let Some(msg_str) = parse_json["message"].as_str() { if msg_str.contains("No block found for") { - return Err(NoBlockForSlotError.into()) + return Err(NoBlockForSlotError.into()); } } } @@ -606,7 +607,7 @@ mod tests { const TIMEOUT_STATE_SECONDS: u64 = 1000; fn get_test_config() -> ConfigForTests { - ConfigForTests::load_from_toml("config_for_tests.toml".try_into().unwrap()) + ConfigForTests::load_from_toml("config_for_tests.toml".into()) } #[test] diff --git a/crates/eth-rpc-client/src/eth1_rpc_client.rs b/crates/eth-rpc-client/src/eth1_rpc_client.rs index 7361a4ab..95a4c40b 100644 --- a/crates/eth-rpc-client/src/eth1_rpc_client.rs +++ b/crates/eth-rpc-client/src/eth1_rpc_client.rs @@ -64,7 +64,7 @@ impl Eth1RPCClient { let val: Value = serde_json::from_str(&res)?; let is_sync = val["result"].as_bool(); if let Some(is_sync_val) = is_sync { - return Ok(is_sync_val) + return Ok(is_sync_val); } Ok(true) @@ -76,7 +76,7 @@ mod tests { use crate::{config_for_tests::ConfigForTests, eth1_rpc_client::Eth1RPCClient}; fn get_test_config() -> ConfigForTests { - ConfigForTests::load_from_toml("config_for_tests.toml".try_into().unwrap()) + ConfigForTests::load_from_toml("config_for_tests.toml".into()) } #[tokio::test] diff --git a/crates/eth-rpc-client/src/execution_block_proof.rs b/crates/eth-rpc-client/src/execution_block_proof.rs index 21213873..35ef5763 100644 --- a/crates/eth-rpc-client/src/execution_block_proof.rs +++ b/crates/eth-rpc-client/src/execution_block_proof.rs @@ -107,7 +107,7 @@ impl ExecutionBlockProof { index: usize, ) -> Result { if branch.len() != depth { - return Err(IncorrectBranchLength) + return Err(IncorrectBranchLength); } let mut merkle_root = leaf.as_bytes().to_vec(); @@ -148,7 +148,7 @@ mod tests { const TIMEOUT_STATE_SECONDS: u64 = 1000; fn get_test_config() -> ConfigForTests { - ConfigForTests::load_from_toml("config_for_tests.toml".try_into().unwrap()) + ConfigForTests::load_from_toml("config_for_tests.toml".into()) } #[test] diff --git a/crates/eth-rpc-client/src/hand_made_finality_light_client_update.rs b/crates/eth-rpc-client/src/hand_made_finality_light_client_update.rs index 4f80cae6..5b6363dc 100644 --- a/crates/eth-rpc-client/src/hand_made_finality_light_client_update.rs +++ b/crates/eth-rpc-client/src/hand_made_finality_light_client_update.rs @@ -116,12 +116,12 @@ impl HandMadeFinalityLightClientUpdate { sync_committee_bits.into_iter().map(|x| x.count_ones()).sum(); if sync_committee_bits_sum * 3 < (64 * 8 * 2) { current_attested_slot = signature_slot; - continue + continue; } if signature_beacon_body.attestations().is_empty() { current_attested_slot = signature_slot; - continue + continue; } let mut attested_slots: Vec = signature_beacon_body @@ -132,8 +132,8 @@ impl HandMadeFinalityLightClientUpdate { attested_slots.sort(); for i in (0..attested_slots.len()).rev() { - if (i == attested_slots.len() - 1 || attested_slots[i + 1] != attested_slots[i]) && - attested_slots[i] >= attested_slot + if (i == attested_slots.len() - 1 || attested_slots[i + 1] != attested_slots[i]) + && attested_slots[i] >= attested_slot { current_attested_slot = attested_slots[i]; @@ -142,10 +142,10 @@ impl HandMadeFinalityLightClientUpdate { .await { if err.downcast_ref::().is_none() { - return Err(err) + return Err(err); } } else { - return Ok((current_attested_slot, signature_slot)) + return Ok((current_attested_slot, signature_slot)); } } } @@ -334,7 +334,7 @@ mod tests { const TIMEOUT_STATE_SECONDS: u64 = 1000000; fn get_test_config() -> ConfigForTests { - ConfigForTests::load_from_toml("config_for_tests.toml".try_into().unwrap()) + ConfigForTests::load_from_toml("config_for_tests.toml".into()) } fn cmp_light_client_updates( diff --git a/crates/eth-rpc-client/src/utils.rs b/crates/eth-rpc-client/src/utils.rs index c35eea07..aea4927f 100644 --- a/crates/eth-rpc-client/src/utils.rs +++ b/crates/eth-rpc-client/src/utils.rs @@ -1,7 +1,7 @@ pub fn trim_quotes(s: String) -> String { let mut res_str = s; - if (res_str.starts_with('"') && res_str.ends_with('"')) || - (res_str.starts_with('\'') && res_str.ends_with('\'')) + if (res_str.starts_with('"') && res_str.ends_with('"')) + || (res_str.starts_with('\'') && res_str.ends_with('\'')) { res_str.pop(); res_str.remove(0); diff --git a/crates/eth-types/Cargo.toml b/crates/eth-types/Cargo.toml index 2981ac99..f5baff2d 100644 --- a/crates/eth-types/Cargo.toml +++ b/crates/eth-types/Cargo.toml @@ -12,7 +12,7 @@ tree-hash = { package = "webb-tree-hash", path = "../tree-hash", default-featur tree-hash-derive = { package = "webb-tree-hash-derive", path = "../tree-hash-derive", default-features = false } eth2-serde-utils = { package = "webb-eth2-serde-utils", path = "../serde-utils", default-features = false, optional = true } hex = { workspace = true } -codec = { workspace = true } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } scale-info = { workspace = true } serde = { workspace = true } rlp = { workspace = true } diff --git a/crates/eth-types/src/lib.rs b/crates/eth-types/src/lib.rs index 99daf36d..874e6544 100644 --- a/crates/eth-types/src/lib.rs +++ b/crates/eth-types/src/lib.rs @@ -250,7 +250,7 @@ impl RlpDecodable for BlockHeader { ); if block_header.hash.unwrap() != keccak256(serialized.as_raw()).into() { - return Err(RlpDecoderError::RlpInconsistentLengthAndData) + return Err(RlpDecoderError::RlpInconsistentLengthAndData); } block_header.partial_hash = Some( diff --git a/crates/eth2-hashing/src/lib.rs b/crates/eth2-hashing/src/lib.rs index f31e94d4..015d0a38 100644 --- a/crates/eth2-hashing/src/lib.rs +++ b/crates/eth2-hashing/src/lib.rs @@ -9,6 +9,7 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] +#![allow(unused_imports)] extern crate alloc; use alloc::{vec, vec::Vec}; diff --git a/crates/eth2-pallet-init/Cargo.toml b/crates/eth2-pallet-init/Cargo.toml index a5eb6c88..2a46bda7 100644 --- a/crates/eth2-pallet-init/Cargo.toml +++ b/crates/eth2-pallet-init/Cargo.toml @@ -21,9 +21,12 @@ serde_json = { workspace = true } serde = { workspace = true } toml = { workspace = true } async-trait = { workspace = true } -sp-keyring = { version = "24.0.0", default-features = false } -subxt = { workspace = true } -webb = { workspace = true } +sp-keyring = { workspace = true } +sp-core = { workspace = true } +subxt = { workspace = true, features = ["substrate-compat"] } +codec = { workspace = true } +subxt-signer = { workspace = true } +tangle-subxt = { workspace = true } scale-info = { workspace = true } webb-proposals = { workspace = true, features = ["scale", "evm"] } tokio = { workspace = true, features = ["macros", "rt", "time"] } diff --git a/crates/eth2-pallet-init/metadata/tangle-runtime.scale b/crates/eth2-pallet-init/metadata/tangle-runtime.scale deleted file mode 100644 index af2ae0b3..00000000 Binary files a/crates/eth2-pallet-init/metadata/tangle-runtime.scale and /dev/null differ diff --git a/crates/eth2-pallet-init/src/eth_client_pallet_trait.rs b/crates/eth2-pallet-init/src/eth_client_pallet_trait.rs index 82d8dfb4..c9971939 100644 --- a/crates/eth2-pallet-init/src/eth_client_pallet_trait.rs +++ b/crates/eth2-pallet-init/src/eth_client_pallet_trait.rs @@ -6,7 +6,7 @@ use eth_types::{ BlockHeader, H256, }; -use webb::substrate::subxt::utils::AccountId32; +use tangle_subxt::subxt::utils::AccountId32; pub type Balance = u128; diff --git a/crates/eth2-pallet-init/src/init_pallet.rs b/crates/eth2-pallet-init/src/init_pallet.rs index 511f8cdf..51cb48c0 100644 --- a/crates/eth2-pallet-init/src/init_pallet.rs +++ b/crates/eth2-pallet-init/src/init_pallet.rs @@ -5,9 +5,9 @@ use eth_rpc_client::{ }; use eth_types::{eth2::ExtendedBeaconBlockHeader, BlockHeader}; use log::info; +use tangle_subxt::subxt::utils::AccountId32; use tree_hash::TreeHash; use types::{ExecutionPayload, MainnetEthSpec}; -use webb::substrate::subxt::utils::AccountId32; use webb_proposals::TypedChainId; const CURRENT_SYNC_COMMITTEE_INDEX: u32 = 54; const CURRENT_SYNC_COMMITTEE_TREE_DEPTH: u32 = @@ -23,7 +23,7 @@ pub fn verify_light_client_snapshot( format!("{:#x}", light_client_snapshot.beacon_header.tree_hash_root()); if block_root != expected_block_root { - return false + return false; } let branch = @@ -136,14 +136,14 @@ pub async fn init_pallet( info!(target: "relay", "init_block_root: {}", init_block_root); - if BeaconRPCClient::get_period_for_slot(light_client_snapshot.beacon_header.slot) != - BeaconRPCClient::get_period_for_slot(finality_slot) + if BeaconRPCClient::get_period_for_slot(light_client_snapshot.beacon_header.slot) + != BeaconRPCClient::get_period_for_slot(finality_slot) { panic!("Period for init_block_root different from current period. Please use snapshot for current period"); } if !verify_light_client_snapshot(init_block_root, &light_client_snapshot) { - return Err(InvalidLightClientSnapshot.into()) + return Err(InvalidLightClientSnapshot.into()); } let mut trusted_signature: Option = Option::None; @@ -245,9 +245,9 @@ mod tests { const MAX_GAP_IN_EPOCH_BETWEEN_FINALIZED_SLOTS: u64 = 3; assert!( - last_finalized_slot_eth_client + - ONE_EPOCH_IN_SLOTS * MAX_GAP_IN_EPOCH_BETWEEN_FINALIZED_SLOTS >= - last_finalized_slot_eth_network.as_u64() + last_finalized_slot_eth_client + + ONE_EPOCH_IN_SLOTS * MAX_GAP_IN_EPOCH_BETWEEN_FINALIZED_SLOTS + >= last_finalized_slot_eth_network.as_u64() ); } } diff --git a/crates/eth2-pallet-init/src/lib.rs b/crates/eth2-pallet-init/src/lib.rs index 56df2ea8..cdb5d86a 100644 --- a/crates/eth2-pallet-init/src/lib.rs +++ b/crates/eth2-pallet-init/src/lib.rs @@ -8,4 +8,4 @@ pub mod init_pallet; pub mod misc; pub mod substrate_network; pub mod substrate_pallet_client; -pub use webb::substrate::tangle_runtime::api as tangle; +pub use tangle_subxt::tangle_runtime::api as tangle; diff --git a/crates/eth2-pallet-init/src/misc.rs b/crates/eth2-pallet-init/src/misc.rs index e0bac91a..f68ad071 100644 --- a/crates/eth2-pallet-init/src/misc.rs +++ b/crates/eth2-pallet-init/src/misc.rs @@ -1,4 +1,4 @@ -use webb::substrate::{scale::Encode, subxt::dynamic::Value}; +use tangle_subxt::{parity_scale_codec::Encode, subxt::dynamic::Value}; pub trait AsValue: Encode { fn as_value(&self) -> Value; diff --git a/crates/eth2-pallet-init/src/substrate_pallet_client.rs b/crates/eth2-pallet-init/src/substrate_pallet_client.rs index 062545c4..649087ba 100644 --- a/crates/eth2-pallet-init/src/substrate_pallet_client.rs +++ b/crates/eth2-pallet-init/src/substrate_pallet_client.rs @@ -8,53 +8,62 @@ use eth_types::{ BlockHeader, H256, }; +use codec::{Decode, Encode}; use std::sync::Arc; -use subxt::{error::DispatchError, utils::AccountId32}; -use webb::substrate::{ - scale::{Decode, Encode}, - subxt::{ - self, - ext::sp_core::{sr25519::Pair, Pair as _}, - storage::{address::Yes, StorageAddress}, - tx::{PairSigner, TxPayload, TxStatus}, - OnlineClient, PolkadotConfig, - }, +use subxt::{ + self, + error::DispatchError, + ext::sp_core::{sr25519::Pair, Pair as _}, + storage::{address::Yes, StorageAddress}, + tx::{PairSigner, TxPayload, TxStatus}, + utils::AccountId32, + OnlineClient, PolkadotConfig, }; -use webb_proposals::TypedChainId; -use tangle::runtime_types::pallet_eth2_light_client; +use tangle_subxt::tangle_runtime::{api as tangle, api::runtime_types::pallet_eth2_light_client}; +use webb_proposals::TypedChainId; pub fn convert_typed_chain_ids( t: TypedChainId, ) -> tangle::runtime_types::webb_proposals::header::TypedChainId { match t { TypedChainId::None => tangle::runtime_types::webb_proposals::header::TypedChainId::None, - TypedChainId::Evm(id) => - tangle::runtime_types::webb_proposals::header::TypedChainId::Evm(id), - TypedChainId::Substrate(id) => - tangle::runtime_types::webb_proposals::header::TypedChainId::Substrate(id), - TypedChainId::PolkadotParachain(id) => - tangle::runtime_types::webb_proposals::header::TypedChainId::PolkadotParachain(id), - TypedChainId::KusamaParachain(id) => - tangle::runtime_types::webb_proposals::header::TypedChainId::KusamaParachain(id), - TypedChainId::RococoParachain(id) => - tangle::runtime_types::webb_proposals::header::TypedChainId::RococoParachain(id), - TypedChainId::Cosmos(id) => - tangle::runtime_types::webb_proposals::header::TypedChainId::Cosmos(id), - TypedChainId::Solana(id) => - tangle::runtime_types::webb_proposals::header::TypedChainId::Solana(id), - TypedChainId::Ink(id) => - tangle::runtime_types::webb_proposals::header::TypedChainId::Ink(id), + TypedChainId::Evm(id) => { + tangle::runtime_types::webb_proposals::header::TypedChainId::Evm(id) + }, + TypedChainId::Substrate(id) => { + tangle::runtime_types::webb_proposals::header::TypedChainId::Substrate(id) + }, + TypedChainId::PolkadotParachain(id) => { + tangle::runtime_types::webb_proposals::header::TypedChainId::PolkadotParachain(id) + }, + TypedChainId::KusamaParachain(id) => { + tangle::runtime_types::webb_proposals::header::TypedChainId::KusamaParachain(id) + }, + TypedChainId::RococoParachain(id) => { + tangle::runtime_types::webb_proposals::header::TypedChainId::RococoParachain(id) + }, + TypedChainId::Cosmos(id) => { + tangle::runtime_types::webb_proposals::header::TypedChainId::Cosmos(id) + }, + TypedChainId::Solana(id) => { + tangle::runtime_types::webb_proposals::header::TypedChainId::Solana(id) + }, + TypedChainId::Ink(id) => { + tangle::runtime_types::webb_proposals::header::TypedChainId::Ink(id) + }, _ => unimplemented!("Unsupported chain id"), } } pub fn convert_mode(t: tangle::runtime_types::eth_types::pallet::ClientMode) -> ClientMode { match t { - tangle::runtime_types::eth_types::pallet::ClientMode::SubmitLightClientUpdate => - ClientMode::SubmitLightClientUpdate, - tangle::runtime_types::eth_types::pallet::ClientMode::SubmitHeader => - ClientMode::SubmitHeader, + tangle::runtime_types::eth_types::pallet::ClientMode::SubmitLightClientUpdate => { + ClientMode::SubmitLightClientUpdate + }, + tangle::runtime_types::eth_types::pallet::ClientMode::SubmitHeader => { + ClientMode::SubmitHeader + }, } } @@ -72,7 +81,7 @@ pub struct EthClientPallet { impl EthClientPallet { pub fn new(api: Arc>, typed_chain_id: TypedChainId) -> Self { - Self::new_with_pair(api, sp_keyring::AccountKeyring::Alice.pair(), typed_chain_id) + Self::new_with_pair(api, Pair::from_string("//Alice", None).unwrap(), typed_chain_id) } pub fn new_with_pair( @@ -191,7 +200,7 @@ impl EthClientPallet { std::io::ErrorKind::Other, format!("Failed to get hash storage value: {err:?}"), ) - .into()) + .into()); }, }; @@ -216,7 +225,7 @@ impl EthClientPallet { Ok(events) => { log::debug!("tx finalized"); let hash = events.extrinsic_hash(); - return Ok(hash.0.into()) + return Ok(hash.0.into()); }, Err(err) => { let error_msg = match err { @@ -235,7 +244,7 @@ impl EthClientPallet { std::io::ErrorKind::Other, format!("Tx failed : {error_msg}"), ) - .into()) + .into()); }, } }, @@ -310,7 +319,7 @@ impl EthClientPalletTrait for EthClientPallet { std::io::ErrorKind::Other, "Tried to submit empty headers".to_string(), ) - .into()) + .into()); } let mut txes = vec![]; @@ -321,8 +330,7 @@ impl EthClientPalletTrait for EthClientPallet { typed_chain_id: decoded_tcid, block_header: decoded_header, }; - let tx = - tangle::runtime_types::tangle_standalone_runtime::RuntimeCall::Eth2Client(call); + let tx = tangle::runtime_types::tangle_testnet_runtime::RuntimeCall::Eth2Client(call); txes.push(tx); } @@ -441,6 +449,3 @@ fn get_sr25519_keys_from_suri>(suri: T) -> anyhow::Result { } } } - -#[subxt::subxt(runtime_metadata_path = "./metadata/tangle-runtime.scale")] -pub mod tangle {} diff --git a/crates/finality-update-verify/src/lib.rs b/crates/finality-update-verify/src/lib.rs index 408cda59..77246e27 100644 --- a/crates/finality-update-verify/src/lib.rs +++ b/crates/finality-update-verify/src/lib.rs @@ -45,10 +45,10 @@ pub fn is_correct_finality_update( let sync_committee_bits_sum: u64 = sync_committee_bits.count_ones().try_into()?; if sync_committee_bits_sum < MIN_SYNC_COMMITTEE_PARTICIPANTS { - return Ok(false) + return Ok(false); } if sync_committee_bits_sum * 3 < (sync_committee_bits.len() * 2).try_into()? { - return Ok(false) + return Ok(false); } let participant_pubkeys = @@ -88,7 +88,7 @@ mod tests { use eth_types::eth2::{LightClientUpdate, SyncCommittee}; fn get_config() -> ConfigForTests { - ConfigForTests::load_from_toml("config_for_tests.toml".try_into().unwrap()) + ConfigForTests::load_from_toml("config_for_tests.toml".into()) } #[test] diff --git a/crates/lc-relay-types/Cargo.toml b/crates/lc-relay-types/Cargo.toml index 4cf5429c..8bb1bfbe 100644 --- a/crates/lc-relay-types/Cargo.toml +++ b/crates/lc-relay-types/Cargo.toml @@ -10,7 +10,7 @@ serde = { workspace = true } serde_json = { workspace = true } reqwest = { workspace = true, features = ["blocking", "json"] } anyhow = { workspace = true } -webb = { workspace = true} +tangle-subxt = { workspace = true} tracing = { workspace = true } backoff = { workspace = true } tokio = { workspace = true } diff --git a/crates/lc-relay-types/src/lib.rs b/crates/lc-relay-types/src/lib.rs index 746ec6ac..54ddd921 100644 --- a/crates/lc-relay-types/src/lib.rs +++ b/crates/lc-relay-types/src/lib.rs @@ -22,7 +22,7 @@ impl WebbRetryClient { let err; { - let resp = self.inner.get(url.clone()).send().await; + let resp = self.inner.get(url).send().await; match resp { Ok(val) => return Ok(val.text().await?), Err(err_) => err = err_, @@ -34,9 +34,9 @@ impl WebbRetryClient { if timeout_retries < self.timeout_retries && err.is_timeout() { timeout_retries += 1; tracing::error!(err = ?err, "retrying due to spurious network"); - continue + continue; } else { - return Err(err.into()) + return Err(err.into()); } } } @@ -47,7 +47,7 @@ impl WebbRetryClient { let err; { - let resp = self.inner.post(url.clone()).json(&body).send().await; + let resp = self.inner.post(url).json(&body).send().await; match resp { Ok(val) => return Ok(val.text().await?), Err(err_) => err = err_, @@ -59,9 +59,9 @@ impl WebbRetryClient { if timeout_retries < self.timeout_retries && err.is_timeout() { timeout_retries += 1; tracing::error!(err = ?err, "retrying due to spurious network"); - continue + continue; } else { - return Err(err.into()) + return Err(err.into()); } } } diff --git a/crates/lc-relayer-context/src/lib.rs b/crates/lc-relayer-context/src/lib.rs index 7824c273..6585e473 100644 --- a/crates/lc-relayer-context/src/lib.rs +++ b/crates/lc-relayer-context/src/lib.rs @@ -74,7 +74,7 @@ impl Shutdown { // If the shutdown signal has already been received, then return // immediately. if self.shutdown { - return + return; } // Cannot receive a "lag error" as only one value is ever sent. diff --git a/crates/merkle-proof/src/lib.rs b/crates/merkle-proof/src/lib.rs index c8da02b3..109aceed 100644 --- a/crates/merkle-proof/src/lib.rs +++ b/crates/merkle-proof/src/lib.rs @@ -57,7 +57,7 @@ impl MerkleTree { use MerkleTree::*; if leaves.is_empty() { - return Zero(depth) + return Zero(depth); } match depth { @@ -92,7 +92,7 @@ impl MerkleTree { use MerkleTree::*; if depth == 0 { - return Err(MerkleTreeError::DepthTooSmall) + return Err(MerkleTreeError::DepthTooSmall); } match self { @@ -256,7 +256,7 @@ mod tests { #[quickcheck] fn quickcheck_create_and_verify(int_leaves: Vec, depth: usize) -> TestResult { if depth > MAX_TREE_DEPTH || int_leaves.len() > 2usize.pow(depth as u32) { - return TestResult::discard() + return TestResult::discard(); } let leaves: Vec<_> = int_leaves.into_iter().map(H256::from_low_u64_be).collect(); @@ -274,7 +274,7 @@ mod tests { #[quickcheck] fn quickcheck_push_leaf_and_verify(int_leaves: Vec, depth: usize) -> TestResult { if depth == 0 || depth > MAX_TREE_DEPTH || int_leaves.len() > 2usize.pow(depth as u32) { - return TestResult::discard() + return TestResult::discard(); } let leaves_iter = int_leaves.into_iter().map(H256::from_low_u64_be); diff --git a/crates/serde-utils/src/fixed_bytes_hex.rs b/crates/serde-utils/src/fixed_bytes_hex.rs index bc6fef76..d06594ab 100644 --- a/crates/serde-utils/src/fixed_bytes_hex.rs +++ b/crates/serde-utils/src/fixed_bytes_hex.rs @@ -36,7 +36,7 @@ macro_rules! bytes_hex { "expected {} bytes for array, got {}", BYTES_LEN, decoded.len() - ))) + ))); } let mut array = [0; BYTES_LEN]; diff --git a/crates/serde-utils/src/u256_hex_be.rs b/crates/serde-utils/src/u256_hex_be.rs index bd904e7f..807aeeb5 100644 --- a/crates/serde-utils/src/u256_hex_be.rs +++ b/crates/serde-utils/src/u256_hex_be.rs @@ -26,7 +26,7 @@ impl<'de> Visitor<'de> for U256Visitor { E: de::Error, { if !value.starts_with("0x") { - return Err(de::Error::custom("must start with 0x")) + return Err(de::Error::custom("must start with 0x")); } let stripped = &value[2..]; if stripped.is_empty() { diff --git a/crates/serde-utils/src/u64_hex_be.rs b/crates/serde-utils/src/u64_hex_be.rs index 84e37042..7e8223b5 100644 --- a/crates/serde-utils/src/u64_hex_be.rs +++ b/crates/serde-utils/src/u64_hex_be.rs @@ -24,7 +24,7 @@ impl<'de> Visitor<'de> for QuantityVisitor { E: de::Error, { if !value.starts_with("0x") { - return Err(de::Error::custom("must start with 0x")) + return Err(de::Error::custom("must start with 0x")); } let stripped = value.trim_start_matches("0x"); @@ -68,7 +68,7 @@ where "expected max {} bytes for array, got {}", BYTES_LEN, decoded.len() - ))) + ))); } let mut array = [0; BYTES_LEN]; diff --git a/crates/serde-utils/src/u8_hex.rs b/crates/serde-utils/src/u8_hex.rs index 22d3686c..6ec3c6c4 100644 --- a/crates/serde-utils/src/u8_hex.rs +++ b/crates/serde-utils/src/u8_hex.rs @@ -20,7 +20,7 @@ where { let bytes = deserializer.deserialize_str(PrefixedHexVisitor)?; if bytes.len() != 1 { - return Err(D::Error::custom(format!("expected 1 byte for u8, got {}", bytes.len()))) + return Err(D::Error::custom(format!("expected 1 byte for u8, got {}", bytes.len()))); } Ok(bytes[0]) } diff --git a/crates/ssz-derive/src/lib.rs b/crates/ssz-derive/src/lib.rs index d02102e8..b26dc1ad 100644 --- a/crates/ssz-derive/src/lib.rs +++ b/crates/ssz-derive/src/lib.rs @@ -53,8 +53,9 @@ impl EnumBehaviour { s.map(|s| match s.as_ref() { ENUM_TRANSPARENT => EnumBehaviour::Transparent, ENUM_UNION => EnumBehaviour::Union, - other => - panic!("{} is an invalid enum_behaviour, use either {:?}", other, ENUM_VARIANTS), + other => { + panic!("{} is an invalid enum_behaviour, use either {:?}", other, ENUM_VARIANTS) + }, }) } } @@ -133,7 +134,7 @@ fn ssz_encode_derive_struct(derive_input: &DeriveInput, struct_data: &DataStruct for (ty, ident, field_opts) in parse_ssz_fields(struct_data) { if field_opts.skip_serializing { - continue + continue; } if let Some(module) = field_opts.with { @@ -427,7 +428,7 @@ fn ssz_decode_derive_struct(item: &DeriveInput, struct_data: &DataStruct) -> Tok let #ident = <_>::default(); }); - continue + continue; } let is_ssz_fixed_len; diff --git a/crates/ssz/examples/struct_definition.rs b/crates/ssz/examples/struct_definition.rs index a80a3ecf..bc602c42 100644 --- a/crates/ssz/examples/struct_definition.rs +++ b/crates/ssz/examples/struct_definition.rs @@ -13,16 +13,16 @@ impl Encode for Foo { } fn ssz_bytes_len(&self) -> usize { - ::ssz_fixed_len() + - ssz::BYTES_PER_LENGTH_OFFSET + - ::ssz_fixed_len() + - self.b.ssz_bytes_len() + ::ssz_fixed_len() + + ssz::BYTES_PER_LENGTH_OFFSET + + ::ssz_fixed_len() + + self.b.ssz_bytes_len() } fn ssz_append(&self, buf: &mut Vec) { - let offset = ::ssz_fixed_len() + - as Encode>::ssz_fixed_len() + - ::ssz_fixed_len(); + let offset = ::ssz_fixed_len() + + as Encode>::ssz_fixed_len() + + ::ssz_fixed_len(); let mut encoder = SszEncoder::container(buf, offset); diff --git a/crates/ssz/src/decode.rs b/crates/ssz/src/decode.rs index 0212529e..9f3c4663 100644 --- a/crates/ssz/src/decode.rs +++ b/crates/ssz/src/decode.rs @@ -79,8 +79,8 @@ pub fn sanitize_offset( ) -> Result { if num_fixed_bytes.map_or(false, |fixed_bytes| offset < fixed_bytes) { Err(DecodeError::OffsetIntoFixedPortion(offset)) - } else if previous_offset.is_none() && - num_fixed_bytes.map_or(false, |fixed_bytes| offset != fixed_bytes) + } else if previous_offset.is_none() + && num_fixed_bytes.map_or(false, |fixed_bytes| offset != fixed_bytes) { Err(DecodeError::OffsetSkipsVariableBytes(offset)) } else if offset > num_bytes { @@ -217,8 +217,9 @@ impl<'a> SszDecoderBuilder<'a> { // fixed-length bytes. match first_offset.cmp(&self.items_index) { Ordering::Less => return Err(DecodeError::OffsetIntoFixedPortion(first_offset)), - Ordering::Greater => - return Err(DecodeError::OffsetSkipsVariableBytes(first_offset)), + Ordering::Greater => { + return Err(DecodeError::OffsetSkipsVariableBytes(first_offset)) + }, Ordering::Equal => (), } @@ -241,7 +242,7 @@ impl<'a> SszDecoderBuilder<'a> { return Err(DecodeError::InvalidByteLength { len: self.bytes.len(), expected: self.items_index, - }) + }); } } diff --git a/crates/ssz/src/decode/impls.rs b/crates/ssz/src/decode/impls.rs index 087ec674..59f1b3ae 100644 --- a/crates/ssz/src/decode/impls.rs +++ b/crates/ssz/src/decode/impls.rs @@ -475,14 +475,14 @@ pub fn decode_list_of_variable_length_items if bytes.is_empty() { return Container::try_from_iter(iter::empty()).map_err(|e| { DecodeError::BytesInvalid(format!("Error trying to collect empty list: {e:?}")) - }) + }); } let first_offset = read_offset(bytes)?; sanitize_offset(first_offset, None, bytes.len(), Some(first_offset))?; if first_offset % BYTES_PER_LENGTH_OFFSET != 0 || first_offset < BYTES_PER_LENGTH_OFFSET { - return Err(DecodeError::InvalidListFixedBytesLen(first_offset)) + return Err(DecodeError::InvalidListFixedBytesLen(first_offset)); } let num_items = first_offset / BYTES_PER_LENGTH_OFFSET; @@ -490,7 +490,7 @@ pub fn decode_list_of_variable_length_items if max_len.map_or(false, |max| num_items > max) { return Err(DecodeError::BytesInvalid(format!( "Variable length list of {num_items} items exceeds maximum of {max_len:?}" - ))) + ))); } let mut offset = first_offset; diff --git a/crates/ssz/src/legacy.rs b/crates/ssz/src/legacy.rs index 627d358e..3dff7888 100644 --- a/crates/ssz/src/legacy.rs +++ b/crates/ssz/src/legacy.rs @@ -93,7 +93,7 @@ macro_rules! four_byte_option_impl { return Err(DecodeError::InvalidByteLength { len: bytes.len(), expected: BYTES_PER_LENGTH_OFFSET, - }) + }); } let (index_bytes, value_bytes) = bytes.split_at(BYTES_PER_LENGTH_OFFSET); diff --git a/crates/ssz/tests/tests.rs b/crates/ssz/tests/tests.rs index e2249db2..37df1377 100644 --- a/crates/ssz/tests/tests.rs +++ b/crates/ssz/tests/tests.rs @@ -100,8 +100,7 @@ mod round_trip { FixedLen { a: 1, b: 0, c: 1 }, ]; - let expected_encodings = vec![ - // | u16--| u64----------------------------| u32----------| + let expected_encodings = [ vec![00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00], vec![01, 00, 01, 00, 00, 00, 00, 00, 00, 00, 01, 00, 00, 00], vec![01, 00, 00, 00, 00, 00, 00, 00, 00, 00, 01, 00, 00, 00], @@ -194,9 +193,7 @@ mod round_trip { VariableLen { a: 1, b: vec![0, 1, 2], c: 1 }, ]; - let expected_encodings = vec![ - // 00..................................09 - // | u16--| vec offset-----| u32------------| vec payload --------| + let expected_encodings = [ vec![00, 00, 10, 00, 00, 00, 00, 00, 00, 00], vec![01, 00, 10, 00, 00, 00, 01, 00, 00, 00, 00, 00], vec![01, 00, 10, 00, 00, 00, 01, 00, 00, 00, 00, 00, 01, 00, 02, 00], diff --git a/crates/tree-hash-derive/src/lib.rs b/crates/tree-hash-derive/src/lib.rs index 3ff718fc..56716381 100644 --- a/crates/tree-hash-derive/src/lib.rs +++ b/crates/tree-hash-derive/src/lib.rs @@ -42,8 +42,9 @@ impl EnumBehaviour { s.map(|s| match s.as_ref() { ENUM_TRANSPARENT => EnumBehaviour::Transparent, ENUM_UNION => EnumBehaviour::Union, - other => - panic!("{} is an invalid enum_behaviour, use either {:?}", other, ENUM_VARIANTS), + other => { + panic!("{} is an invalid enum_behaviour, use either {:?}", other, ENUM_VARIANTS) + }, }) } } @@ -114,8 +115,8 @@ fn cached_tree_hash_attr_metas(attrs: &[Attribute]) -> Vec { /// The field attribute is: `#[tree_hash(skip_hashing)]` fn should_skip_hashing(field: &syn::Field) -> bool { field.attrs.iter().any(|attr| { - attr.path.is_ident("tree_hash") && - attr.tokens.to_string().replace(' ', "") == "(skip_hashing)" + attr.path.is_ident("tree_hash") + && attr.tokens.to_string().replace(' ', "") == "(skip_hashing)" }) } diff --git a/crates/tree-hash/src/lib.rs b/crates/tree-hash/src/lib.rs index f2499f1f..ffe8857c 100644 --- a/crates/tree-hash/src/lib.rs +++ b/crates/tree-hash/src/lib.rs @@ -86,7 +86,7 @@ pub fn mix_in_length(root: &Hash256, length: usize) -> Hash256 { /// https://github.com/ethereum/consensus-specs/blob/v1.1.0-beta.3/ssz/simple-serialize.md#union pub fn mix_in_selector(root: &Hash256, selector: u8) -> Option { if selector > MAX_UNION_SELECTOR { - return None + return None; } let mut chunk = [0; BYTES_PER_CHUNK]; diff --git a/crates/tree-hash/src/merkle_hasher.rs b/crates/tree-hash/src/merkle_hasher.rs index 623a7f7f..ad92c9d4 100644 --- a/crates/tree-hash/src/merkle_hasher.rs +++ b/crates/tree-hash/src/merkle_hasher.rs @@ -238,7 +238,7 @@ impl MerkleHasher { let max_leaves = 1 << (self.depth + 1); if self.next_leaf > max_leaves { - return Err(Error::MaximumLeavesExceeded { max_leaves }) + return Err(Error::MaximumLeavesExceeded { max_leaves }); } else if self.next_leaf == 1 { // A tree of depth one has a root that is equal to the first given leaf. self.root = Some(Hash256::from_slice(leaf)) @@ -272,14 +272,14 @@ impl MerkleHasher { // If the tree is incomplete, we must complete it by providing zero-hashes. loop { if let Some(root) = self.root { - break Ok(root) + break Ok(root); } else if let Some(node) = self.half_nodes.last() { let right_child = node.id * 2 + 1; self.process_right_node(right_child, self.zero_hash(right_child)); } else if self.next_leaf == 1 { // The next_leaf can only be 1 if the tree has a depth of one. If have been no // leaves supplied, assume a root of zero. - break Ok(Hash256::zero()) + break Ok(Hash256::zero()); } else { // The only scenario where there are (a) no half nodes and (b) a tree of depth // two or more is where no leaves have been supplied at all. @@ -331,14 +331,14 @@ impl MerkleHasher { ); if parent == 1 { self.root = Some(Hash256::from_slice(preimage.as_bytes())); - break + break; } else { parent = get_parent(parent); } }, _ => { self.half_nodes.push(HalfNode::new(parent, preimage)); - break + break; }, } } diff --git a/crates/tree-hash/src/merkleize_padded.rs b/crates/tree-hash/src/merkleize_padded.rs index eb609444..8e29b1bc 100644 --- a/crates/tree-hash/src/merkleize_padded.rs +++ b/crates/tree-hash/src/merkleize_padded.rs @@ -38,7 +38,7 @@ pub fn merkleize_padded(bytes: &[u8], min_leaves: usize) -> Hash256 { if bytes.len() <= BYTES_PER_CHUNK && min_leaves <= 1 { let mut o = bytes.to_vec(); o.resize(BYTES_PER_CHUNK, 0); - return Hash256::from_slice(&o) + return Hash256::from_slice(&o); } assert!( diff --git a/crates/tree-hash/src/merkleize_standard.rs b/crates/tree-hash/src/merkleize_standard.rs index 7072daa1..79d2d1cd 100644 --- a/crates/tree-hash/src/merkleize_standard.rs +++ b/crates/tree-hash/src/merkleize_standard.rs @@ -24,7 +24,7 @@ pub fn merkleize_standard(bytes: &[u8]) -> Hash256 { if bytes.len() <= HASHSIZE { let mut o = bytes.to_vec(); o.resize(HASHSIZE, 0); - return Hash256::from_slice(&o[0..HASHSIZE]) + return Hash256::from_slice(&o[0..HASHSIZE]); } let leaves = num_sanitized_leaves(bytes.len()); diff --git a/eth2substrate-block-relay-rs/Cargo.toml b/eth2substrate-block-relay-rs/Cargo.toml index 72726dc7..1d4bcea8 100644 --- a/eth2substrate-block-relay-rs/Cargo.toml +++ b/eth2substrate-block-relay-rs/Cargo.toml @@ -19,12 +19,12 @@ lc-relayer-context = { package = "webb-lc-relayer-context", path = "../crates/lc types = { workspace = true } eth2_hashing = { package = "ethereum_hashing", version = "1.0.0-beta.2" } eth2_ssz = { package = "ethereum_ssz", version = "0.5.0", features = ["arbitrary"] } -webb = { workspace = true } +tangle-subxt = { workspace = true } webb-proposals ={ workspace = true } anyhow = { workspace = true } funty = { workspace = true } -sp-keyring = { version = "18.0.0", default-features = false } -sp-core = { version = "16.0.0" } +sp-keyring = { workspace = true } +sp-core = { workspace = true } log = { workspace = true, features = ["std", "serde"] } serde_json = { workspace = true } serde = { workspace = true } diff --git a/eth2substrate-block-relay-rs/src/eth2substrate_relay.rs b/eth2substrate-block-relay-rs/src/eth2substrate_relay.rs index ec1cbd40..933ff96a 100644 --- a/eth2substrate-block-relay-rs/src/eth2substrate_relay.rs +++ b/eth2substrate-block-relay-rs/src/eth2substrate_relay.rs @@ -164,8 +164,8 @@ impl Eth2SubstrateRelay { { CHAIN_FINALIZED_EXECUTION_BLOCK_HEIGHT_ON_SUBSTRATE.inc_by(cmp::max( 0, - last_block_number as i64 - - CHAIN_FINALIZED_EXECUTION_BLOCK_HEIGHT_ON_SUBSTRATE.get(), + last_block_number as i64 + - CHAIN_FINALIZED_EXECUTION_BLOCK_HEIGHT_ON_SUBSTRATE.get(), )); } @@ -268,11 +268,11 @@ impl Eth2SubstrateRelay { headers.reverse(); if !self.submit_execution_blocks(headers).await { - return false + return false; } if min_block_number_in_batch == min_block_number { - break + break; } } @@ -280,8 +280,8 @@ impl Eth2SubstrateRelay { } async fn wait_for_synchronization(&self) -> anyhow::Result<()> { - while self.beacon_rpc_client.is_syncing().await? || - self.eth1_rpc_client.is_syncing().await? + while self.beacon_rpc_client.is_syncing().await? + || self.eth1_rpc_client.is_syncing().await? { info!(target: "relay", "Waiting for sync..."); tokio::time::sleep(Duration::from_secs(self.sleep_time_on_sync_secs)).await; @@ -403,17 +403,17 @@ impl Eth2SubstrateRelay { last_finalized_slot_on_substrate: u64, last_finalized_slot_on_eth: u64, ) -> bool { - if (last_finalized_slot_on_eth as i64) - (last_finalized_slot_on_substrate as i64) < - (ONE_EPOCH_IN_SLOTS * self.interval_between_light_client_updates_submission_in_epochs) + if (last_finalized_slot_on_eth as i64) - (last_finalized_slot_on_substrate as i64) + < (ONE_EPOCH_IN_SLOTS * self.interval_between_light_client_updates_submission_in_epochs) as i64 { info!(target: "relay", "Light client update were send less then {} epochs ago. Skipping sending light client update", self.interval_between_light_client_updates_submission_in_epochs); - return false + return false; } if last_finalized_slot_on_eth <= last_finalized_slot_on_substrate { info!(target: "relay", "Last finalized slot on Eth equal to last finalized slot on Substrate. Skipping sending light client update."); - return false + return false; } true @@ -447,7 +447,7 @@ impl Eth2SubstrateRelay { last_finalized_slot_on_eth, ) .await; - return true + return true; } false @@ -463,21 +463,22 @@ impl Eth2SubstrateRelay { if self.is_shot_run_mode() { info!(target: "relay", "Try sending light client update from file"); self.send_light_client_update_from_file().await; - return + return; } - if self.get_light_client_update_by_epoch && - self.send_regular_light_client_update_by_epoch( - last_finalized_slot_on_eth, - last_finalized_slot_on_near, - ) - .await + if self.get_light_client_update_by_epoch + && self + .send_regular_light_client_update_by_epoch( + last_finalized_slot_on_eth, + last_finalized_slot_on_near, + ) + .await { - return + return; } - if last_finalized_slot_on_eth >= - last_finalized_slot_on_near + self.max_blocks_for_finalization + if last_finalized_slot_on_eth + >= last_finalized_slot_on_near + self.max_blocks_for_finalization { info!(target: "relay", "Too big gap between slot of finalized block on NEAR and ETH. Sending hand made light client update"); self.send_hand_made_light_client_update(last_finalized_slot_on_near).await; @@ -562,10 +563,10 @@ impl Eth2SubstrateRelay { "Error on getting light client update. Skipping sending light client update", false ); - break res + break res; } - break res + break res; } warn!(target: "relay", "Error: {}", res.unwrap_err()); @@ -582,10 +583,10 @@ impl Eth2SubstrateRelay { last_finalized_slot_on_substrate: u64, ) -> anyhow::Result { const EXPECTED_EPOCHS_BETWEEN_HEAD_AND_FINALIZED_BLOCKS: u64 = 2; - let next_finalized_slot = last_finalized_slot_on_substrate + - self.interval_between_light_client_updates_submission_in_epochs * ONE_EPOCH_IN_SLOTS; - let attested_slot = next_finalized_slot + - EXPECTED_EPOCHS_BETWEEN_HEAD_AND_FINALIZED_BLOCKS * ONE_EPOCH_IN_SLOTS; + let next_finalized_slot = last_finalized_slot_on_substrate + + self.interval_between_light_client_updates_submission_in_epochs * ONE_EPOCH_IN_SLOTS; + let attested_slot = next_finalized_slot + + EXPECTED_EPOCHS_BETWEEN_HEAD_AND_FINALIZED_BLOCKS * ONE_EPOCH_IN_SLOTS; let attested_slot: u64 = self .beacon_rpc_client @@ -605,8 +606,8 @@ impl Eth2SubstrateRelay { ); let include_next_sync_committee = - BeaconRPCClient::get_period_for_slot(last_finalized_slot_on_substrate) != - BeaconRPCClient::get_period_for_slot(attested_slot); + BeaconRPCClient::get_period_for_slot(last_finalized_slot_on_substrate) + != BeaconRPCClient::get_period_for_slot(attested_slot); loop { let light_client_update = return_on_fail!( @@ -631,12 +632,12 @@ impl Eth2SubstrateRelay { .await, "Error on getting attested slot" ); - continue + continue; } trace!(target: "relay", "Hand made light client update: {:?}", light_client_update); self.send_specific_light_client_update(light_client_update).await; - return + return; } } @@ -654,7 +655,7 @@ impl Eth2SubstrateRelay { info!(target: "relay", "PASS bls signature verification!"); } else { warn!(target: "relay", "NOT PASS bls signature verification. Skip sending this light client update"); - return false + return false; } let execution_outcome = return_val_on_fail_and_sleep!( diff --git a/eth2substrate-block-relay-rs/src/test_utils.rs b/eth2substrate-block-relay-rs/src/test_utils.rs index 03907733..30bb60b4 100644 --- a/eth2substrate-block-relay-rs/src/test_utils.rs +++ b/eth2substrate-block-relay-rs/src/test_utils.rs @@ -77,7 +77,7 @@ pub async fn init_pallet_from_files( for header in &execution_blocks { if header.hash.unwrap() == finalized_hash { finalized_execution_header = Some(header.clone()); - break + break; } } diff --git a/gadget/src/lib.rs b/gadget/src/lib.rs index 0ed0200a..cceba31f 100644 --- a/gadget/src/lib.rs +++ b/gadget/src/lib.rs @@ -30,7 +30,7 @@ pub async fn ignite_lc_relayer(ctx: LightClientRelayerContext) -> anyhow::Result Ok(client) => client, Err(err) => { tracing::error!("Failed to connect with substrate client, retrying...!"); - return Err(backoff::Error::transient(err)) + return Err(backoff::Error::transient(err)); }, }; let api_client = Arc::new(api_client); @@ -59,7 +59,7 @@ pub async fn ignite_lc_relayer(ctx: LightClientRelayerContext) -> anyhow::Result Ok(_) => tracing::info!(target: "relay", "=== Pallet initialized ==="), Err(e) => { tracing::error!(target: "relay", "=== Failed to initialize pallet: {:?} ===", e); - return Err(backoff::Error::permanent(e)) + return Err(backoff::Error::permanent(e)); }, }; } @@ -75,14 +75,15 @@ pub async fn ignite_lc_relayer(ctx: LightClientRelayerContext) -> anyhow::Result pub async fn start_gadget(relayer_params: Eth2LightClientParams) { // Light Client Relayer let lc_relay_config = match relayer_params.lc_relay_config_path.as_ref() { - Some(p) => - loads_light_client_relayer_config(p).expect("failed to load light client config"), + Some(p) => { + loads_light_client_relayer_config(p).expect("failed to load light client config") + }, None => { tracing::error!( target: "light-client-gadget", "Error: Not Starting ETH2 Light Client Relayer Gadget. No Config Directory Specified" ); - return + return; }, }; @@ -94,7 +95,7 @@ pub async fn start_gadget(relayer_params: Eth2LightClientParams) { target: "light-client-gadget", "Error: Not Starting ETH2 Light Client Relayer Gadget. No Config Directory Specified" ); - return + return; }, }; let ctx = LightClientRelayerContext::new(lc_relay_config, lc_init_config); diff --git a/node/Cargo.toml b/node/Cargo.toml index e59586a5..fe79c3b8 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -72,7 +72,7 @@ frame-benchmarking-cli = { workspace = true } try-runtime-cli = { workspace = true, optional = true } [build-dependencies] -substrate-build-script-utils = { version = "3.0.0", git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" } +substrate-build-script-utils = { version = "11.0.0", git = "https://github.com/paritytech/polkadot-sdk" } [features] default = [] diff --git a/node/src/chain_spec.rs b/node/src/chain_spec.rs index bc95ca80..73f72416 100644 --- a/node/src/chain_spec.rs +++ b/node/src/chain_spec.rs @@ -53,9 +53,7 @@ fn session_keys(grandpa: GrandpaId, aura: AuraId) -> SessionKeys { } fn development_config_genesis() -> RuntimeGenesisConfig { - let wasm_binary = WASM_BINARY.unwrap(); testnet_genesis( - wasm_binary, vec![authority_keys_from_seed("Alice"), authority_keys_from_seed("Bob")], vec![], get_account_id_from_seed::("Alice"), @@ -65,6 +63,7 @@ fn development_config_genesis() -> RuntimeGenesisConfig { /// Development config (single validator Alice) pub fn development_config() -> ChainSpec { + #[allow(deprecated)] ChainSpec::from_genesis( "Development", "dev", @@ -76,13 +75,12 @@ pub fn development_config() -> ChainSpec { None, None, Default::default(), + WASM_BINARY.unwrap(), ) } fn local_testnet_genesis() -> RuntimeGenesisConfig { - let wasm_binary = WASM_BINARY.unwrap(); testnet_genesis( - wasm_binary, vec![authority_keys_from_seed("Alice"), authority_keys_from_seed("Bob")], vec![], get_account_id_from_seed::("Alice"), @@ -92,6 +90,7 @@ fn local_testnet_genesis() -> RuntimeGenesisConfig { /// Local testnet config (multivalidator Alice + Bob) pub fn local_testnet_config() -> ChainSpec { + #[allow(deprecated)] ChainSpec::from_genesis( "Local Testnet", "local_testnet", @@ -103,12 +102,12 @@ pub fn local_testnet_config() -> ChainSpec { None, None, Default::default(), + WASM_BINARY.unwrap(), ) } /// Configure initial storage state for FRAME modules. fn testnet_genesis( - wasm_binary: &[u8], initial_authorities: Vec<(AccountId, AccountId, GrandpaId, AuraId)>, initial_nominators: Vec, root_key: AccountId, @@ -164,7 +163,6 @@ fn testnet_genesis( RuntimeGenesisConfig { system: SystemConfig { // Add Wasm runtime to storage. - code: wasm_binary.to_vec(), ..Default::default() }, balances: BalancesConfig { diff --git a/node/src/command.rs b/node/src/command.rs index d33f1f49..94e6028c 100644 --- a/node/src/command.rs +++ b/node/src/command.rs @@ -42,8 +42,9 @@ impl SubstrateCli for Cli { Ok(match id { "dev" => Box::new(chain_spec::development_config()), "" | "local" => Box::new(chain_spec::local_testnet_config()), - path => - Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?), + path => { + Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?) + }, }) } } @@ -117,7 +118,7 @@ pub fn run() -> sc_cli::Result<()> { "Runtime benchmarking wasn't enabled when building the node. \ You can enable it with `--features runtime-benchmarks`." .into(), - ) + ); } cmd.run::(config) @@ -166,8 +167,9 @@ pub fn run() -> sc_cli::Result<()> { cmd.run(client, inherent_benchmark_data()?, Vec::new(), &ext_factory) }, - BenchmarkCmd::Machine(cmd) => - cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()), + BenchmarkCmd::Machine(cmd) => { + cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()) + }, } }) }, diff --git a/node/src/rpc.rs b/node/src/rpc.rs index 53c59bc0..246391ad 100644 --- a/node/src/rpc.rs +++ b/node/src/rpc.rs @@ -45,7 +45,7 @@ where let mut module = RpcModule::new(()); let FullDeps { client, pool, deny_unsafe } = deps; - module.merge(System::new(client.clone(), pool.clone(), deny_unsafe).into_rpc())?; + module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?; module.merge(TransactionPayment::new(client).into_rpc())?; // Extend this RPC with a custom API by using the following syntax. @@ -53,5 +53,12 @@ where // to call into the runtime. // `module.merge(YourRpcTrait::into_rpc(YourRpcStruct::new(ReferenceToClient, ...)))?;` + // You probably want to enable the `rpc v2 chainSpec` API as well + // + // let chain_name = chain_spec.name().to_string(); + // let genesis_hash = client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"); + // let properties = chain_spec.properties(); + // module.merge(ChainSpec::new(chain_name, genesis_hash, properties).into_rpc())?; + Ok(module) } diff --git a/node/src/service.rs b/node/src/service.rs index b58c90ad..67f685ec 100644 --- a/node/src/service.rs +++ b/node/src/service.rs @@ -166,9 +166,9 @@ pub fn new_full( &client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"), &config.chain_spec, ); - net_config.add_notification_protocol(sc_consensus_grandpa::grandpa_peers_set_config( - grandpa_protocol_name.clone(), - )); + let (grandpa_protocol_config, grandpa_notification_service) = + sc_consensus_grandpa::grandpa_peers_set_config(grandpa_protocol_name.clone()); + net_config.add_notification_protocol(grandpa_protocol_config); let warp_sync = Arc::new(sc_consensus_grandpa::warp_proof::NetworkProvider::new( backend.clone(), @@ -186,6 +186,7 @@ pub fn new_full( import_queue, block_announce_validator_builder: None, warp_sync_params: Some(WarpSyncParams::WithProvider(warp_sync)), + block_relay: None, })?; let role = config.role.clone(); @@ -330,6 +331,7 @@ pub fn new_full( link: grandpa_link, network, sync: Arc::new(sync_service), + notification_service: grandpa_notification_service, voting_rule: sc_consensus_grandpa::VotingRulesBuilder::default().build(), prometheus_registry, shared_voter_state: SharedVoterState::empty(), diff --git a/pallets/eth2-light-client/Cargo.toml b/pallets/eth2-light-client/Cargo.toml index 3c5c685c..f0a45bc1 100644 --- a/pallets/eth2-light-client/Cargo.toml +++ b/pallets/eth2-light-client/Cargo.toml @@ -25,7 +25,7 @@ sp-core = { workspace = true } log = { workspace = true } serde = { workspace = true, optional = true } -codec = { workspace = true, features = ["derive", "max-encoded-len"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } scale-info = { workspace = true } webb-proposals = { workspace = true, features = ["evm", "substrate"] } ethereum-types = { workspace = true } diff --git a/pallets/eth2-light-client/runtime-api/Cargo.toml b/pallets/eth2-light-client/runtime-api/Cargo.toml index 89809a65..868ff1c5 100644 --- a/pallets/eth2-light-client/runtime-api/Cargo.toml +++ b/pallets/eth2-light-client/runtime-api/Cargo.toml @@ -13,7 +13,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { workspace = true } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } sp-api = { workspace = true } webb-proposals = { workspace = true } eth-types = { path = "../../../crates/eth-types", default-features = false } diff --git a/pallets/eth2-light-client/src/lib.rs b/pallets/eth2-light-client/src/lib.rs index b4ee965a..bd4d0fe5 100644 --- a/pallets/eth2-light-client/src/lib.rs +++ b/pallets/eth2-light-client/src/lib.rs @@ -76,8 +76,6 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] -#![feature(slice_pattern)] - use eth_types::{ eth2::{ExtendedBeaconBlockHeader, LightClientState, LightClientUpdate, SyncCommittee}, pallet::{ClientMode, ExecutionHeaderInfo, InitInput}, @@ -395,8 +393,8 @@ pub mod pallet { let finalized_execution_header_hash = args.finalized_execution_header.calculate_hash(); ensure!( - finalized_execution_header_hash == - args.finalized_beacon_header.execution_block_hash, + finalized_execution_header_hash + == args.finalized_beacon_header.execution_block_hash, // Invalid execution block Error::::InvalidExecutionBlock, ); @@ -501,8 +499,8 @@ pub mod pallet { if let Some(diff_between_unfinalized_head_and_tail) = Self::get_diff_between_unfinalized_head_and_tail(typed_chain_id) { - let header_number_to_remove = (finalized_execution_header.block_number + - diff_between_unfinalized_head_and_tail) + let header_number_to_remove = (finalized_execution_header.block_number + + diff_between_unfinalized_head_and_tail) .saturating_sub(HashesGcThreshold::::get(typed_chain_id)); ensure!( @@ -607,12 +605,13 @@ impl Pallet { /// Returns finalized execution block hash pub fn block_hash_safe(typed_chain_id: TypedChainId, block_number: u64) -> Option { match Self::finalized_execution_header(typed_chain_id) { - Some(header) => + Some(header) => { if header.block_number >= block_number { Self::finalized_execution_blocks(typed_chain_id, block_number) } else { None - }, + } + }, None => None, } } @@ -686,12 +685,12 @@ impl Pallet { if Self::finalized_execution_blocks(typed_chain_id, header_number).is_some() { FinalizedExecutionBlocks::::remove(typed_chain_id, header_number); if header_number == 0 { - break + break; } else { header_number -= 1; } } else { - break + break; } } } @@ -701,8 +700,8 @@ impl Pallet { typed_chain_id: TypedChainId, ) -> Result<(), DispatchError> { ensure!( - ClientModeForChain::::get(typed_chain_id) == - Some(ClientMode::SubmitLightClientUpdate), + ClientModeForChain::::get(typed_chain_id) + == Some(ClientMode::SubmitLightClientUpdate), Error::::InvalidClientMode ); ensure!(!Paused::::get(typed_chain_id), Error::::LightClientUpdateNotAllowed); @@ -780,8 +779,8 @@ impl Pallet { ); ensure!( - update.attested_beacon_header.slot >= - update.finality_update.header_update.beacon_header.slot, + update.attested_beacon_header.slot + >= update.finality_update.header_update.beacon_header.slot, Error::::UpdateHeaderSlotLessThanFinalizedHeaderSlot ); diff --git a/pallets/eth2-light-client/src/mock.rs b/pallets/eth2-light-client/src/mock.rs index 12f68606..b4c1ad09 100644 --- a/pallets/eth2-light-client/src/mock.rs +++ b/pallets/eth2-light-client/src/mock.rs @@ -52,6 +52,7 @@ impl system::Config for Test { type SS58Prefix = SS58Prefix; type SystemWeightInfo = (); type Version = (); + type RuntimeTask = (); } parameter_types! { @@ -68,10 +69,10 @@ impl pallet_balances::Config for Test { type MaxReserves = (); type ReserveIdentifier = [u8; 8]; type FreezeIdentifier = (); - type MaxHolds = (); type MaxFreezes = (); type WeightInfo = (); type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = (); } parameter_types! { diff --git a/pallets/eth2-light-client/src/test_utils.rs b/pallets/eth2-light-client/src/test_utils.rs index ea478071..b641a68a 100644 --- a/pallets/eth2-light-client/src/test_utils.rs +++ b/pallets/eth2-light-client/src/test_utils.rs @@ -1,5 +1,3 @@ -use eth_types::eth2::LightClientUpdate; - use eth_types::{eth2::*, pallet::InitInput, BlockHeader}; use lazy_static::lazy_static; diff --git a/pallets/eth2-light-client/src/tests.rs b/pallets/eth2-light-client/src/tests.rs index 2654ac50..4d69aafc 100644 --- a/pallets/eth2-light-client/src/tests.rs +++ b/pallets/eth2-light-client/src/tests.rs @@ -43,6 +43,7 @@ pub fn get_test_context( (headers, updates, init_input_0) } +#[cfg(test)] mod generic_tests { use super::*; use crate::{ @@ -97,8 +98,8 @@ mod generic_tests { for header in headers[0].iter().skip(1) { let header_hash = header.calculate_hash(); assert!( - Eth2Client::block_hash_safe(GOERLI_CHAIN, header.number).unwrap_or_default() == - header_hash, + Eth2Client::block_hash_safe(GOERLI_CHAIN, header.number).unwrap_or_default() + == header_hash, "Execution block hash is not finalized: {header_hash:?}" ); } @@ -160,8 +161,8 @@ mod generic_tests { for header in headers[0].iter().skip(1) { assert!( - Eth2Client::block_hash_safe(GOERLI_CHAIN, header.number).unwrap_or_default() == - header.calculate_hash(), + Eth2Client::block_hash_safe(GOERLI_CHAIN, header.number).unwrap_or_default() + == header.calculate_hash(), "Execution block hash is not finalized: {:?}", header.calculate_hash() ); @@ -186,8 +187,8 @@ mod generic_tests { for header in headers[1].iter() { assert!( - Eth2Client::block_hash_safe(GOERLI_CHAIN, header.number).unwrap_or_default() == - header.calculate_hash(), + Eth2Client::block_hash_safe(GOERLI_CHAIN, header.number).unwrap_or_default() + == header.calculate_hash(), "Execution block hash is not finalized: {:?}", header.calculate_hash() ); @@ -488,6 +489,7 @@ mod generic_tests { } } +#[cfg(test)] mod mainnet_tests { use super::*; use crate::{ diff --git a/pallets/light-proposals/Cargo.toml b/pallets/light-proposals/Cargo.toml deleted file mode 100644 index 68affbc0..00000000 --- a/pallets/light-proposals/Cargo.toml +++ /dev/null @@ -1,82 +0,0 @@ -[package] -name = "pallet-light-proposals" -version = "0.1.0" -edition = "2021" - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] - -eth-types = { path = "../../crates/eth-types", default-features = false, features = ["eth2"] } -eth2-ssz = { package = "webb-eth2-ssz", path = "../../crates/ssz", default-features = false } -merkle-proof = { package = "webb-merkle-proof", path = "../../crates/merkle-proof", default-features = false } -bls = { package = "webb-bls", path = "../../crates/bls", default-features = false } -tree-hash = { package = "webb-tree-hash", path = "../../crates/tree-hash", default-features = false } -tree-hash-derive = { package = "webb-tree-hash-derive", path = "../../crates/tree-hash-derive", default-features = false } -consensus = { package = "webb-consensus-types", path = "../../crates/consensus-types", default-features = false } - -frame-support = { workspace = true, default-features = false } -frame-system = { workspace = true, default-features = false } -pallet-balances = { workspace = true, default-features = false } -sp-runtime = { workspace = true, default-features = false } -sp-std = { workspace = true, default-features = false } -sp-core = { workspace = true, default-features = false } - -log = { workspace = true, default-features = false } -serde = { workspace = true, optional = true, default-features = false } -codec = { workspace = true, features = ["derive", "max-encoded-len"] } -scale-info = { workspace = true, default-features = false } -webb-proposals = { workspace = true, default-features = false, features = ["evm", "substrate"] } -ethereum-types = { workspace = true, default-features = false } -derive_more = { workspace = true } -rlp = { workspace = true, default-features = false } -rlp-derive = { workspace = true, default-features = false } -tiny-keccak = { workspace = true, default-features = false } -bitvec = { workspace = true, features = ["atomic", "alloc"] } -hex = { workspace = true } -webb-light-client-primitives = { workspace = true } -dkg-runtime-primitives = { git = "https://github.com/webb-tools/dkg-substrate.git", branch = "master", default-features = false } -pallet-bridge-registry = { git = "https://github.com/webb-tools/dkg-substrate.git", branch = "master", default-features = false } -webb = { workspace = true, default-features = false } - -[dev-dependencies] -anyhow = { workspace = true } -lazy_static = { workspace = true } -serde_json = { workspace = true } -eth2-pallet-init = { package = "webb-eth2-pallet-init", path = "../../crates/eth2-pallet-init" } -async-trait = { workspace = true } -pallet-eth2-light-client = { workspace = true, features = ["testing"] } - -[features] -default = ["std"] -std = [ - "serde/std", - "codec/std", - "scale-info/std", - "webb-proposals/std", - "ethereum-types/std", - "rlp/std", - "bitvec/std", - "frame-support/std", - "frame-system/std", - "pallet-balances/std", - "sp-runtime/std", - "sp-std/std", - "sp-core/std", - "hex/std", - "dkg-runtime-primitives/std", - "pallet-bridge-registry/std", - "pallet-eth2-light-client/std", - - # Local dependencies - "bls/std", - "consensus/std", - "eth-types/std", - "eth2-ssz/std", - "tree-hash/std", - "merkle-proof/std", - "webb-light-client-primitives/std" -] - -try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/light-proposals/src/lib.rs b/pallets/light-proposals/src/lib.rs deleted file mode 100644 index 23acf222..00000000 --- a/pallets/light-proposals/src/lib.rs +++ /dev/null @@ -1,256 +0,0 @@ -// This file is part of Webb. -// Implementations are Substrate adaptations of the Rainbow Bridge. -// https://github.com/aurora-is-near/rainbow-bridge - -// Copyright (C) 2022 Webb Technologies Inc. -// SPDX-License-Identifier: GPL-3.0-or-later - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -// Ensure we're `no_std` when compiling for Wasm. -#![cfg_attr(not(feature = "std"), no_std)] -#![feature(slice_pattern)] -#![allow(unused)] - -use dkg_runtime_primitives::{ - ProposalHandlerTrait, -}; -use frame_support::{pallet_prelude::DispatchError, traits::Get}; -pub use pallet::*; -use scale_info::TypeInfo; -use sp_std::{convert::TryInto, prelude::*}; - -use webb::evm::{ - contract::protocol_solidity::variable_anchor::v_anchor_contract, ethers::contract::EthCall, -}; -use webb_light_client_primitives::{types::LightProposalInput, LEAF_INDEX_KEY, MERKLE_ROOT_KEY}; -use webb_proposals::{evm::AnchorUpdateProposal, Nonce, TypedChainId, FunctionSignature, ResourceId, ProposalHeader, ProposalKind, Proposal}; - -#[cfg(test)] -mod mock; - -#[cfg(test)] -mod tests; - -#[frame_support::pallet] -pub mod pallet { - use core::fmt::Debug; - -use super::*; - - use dkg_runtime_primitives::ProposalHandlerTrait; - - use frame_support::{ - dispatch::DispatchResultWithPostInfo, - pallet_prelude::{ValueQuery, *}, - }; - use frame_system::pallet_prelude::*; - use webb_light_client_primitives::{ - traits::{LightClientHandler, ProofVerifier}, - types::LightProposalInput, - }; - - #[pallet::pallet] - #[pallet::without_storage_info] - pub struct Pallet(_); - - #[pallet::config] - /// The module configuration trait. - pub trait Config: frame_system::Config + pallet_bridge_registry::Config { - /// The overarching event type. - type RuntimeEvent: From> + IsType<::RuntimeEvent>; - - /// Light client interface for the pallet - type LightClient: LightClientHandler; - - /// Storage proof verifier for the pallt - type ProofVerifier: ProofVerifier; - - /// Proposer handler trait - type ProposalHandler: ProposalHandlerTrait< - MaxProposalLength = ::MaxProposalLength, - >; - - /// Max length of submitted proof - #[pallet::constant] - type MaxProofSize: Get + TypeInfo + Clone + Debug + PartialEq + Eq; - - /// Max length of a proposal - #[pallet::constant] - type MaxProposalLength: Get - + Debug - + Clone - + Eq - + PartialEq - + PartialOrd - + Ord - + TypeInfo; - } - - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { - ProposalSubmitted { proposal: LightProposalInput }, - } - - #[pallet::storage] - #[pallet::getter(fn resource_id_to_nonce)] - /// Mapping of resource to nonce - pub type ResourceIdToNonce = StorageMap<_, Blake2_256, ResourceId, u32, ValueQuery>; - - #[pallet::error] - pub enum Error { - /// Cannot fetch bridge details - CannotFetchBridgeDetails, - /// Cannot fetch bridge metadata - CannotFetchBridgeMetadata, - /// Proof verification failed - ProofVerificationFailed, - } - - #[pallet::hooks] - impl Hooks> for Pallet {} - - #[pallet::call] - impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().reads_writes(1,1))] - pub fn submit_proposal( - origin: OriginFor, - proposal: LightProposalInput, - ) -> DispatchResultWithPostInfo { - ensure_signed(origin)?; - - // validate the block header against light client storage - T::LightClient::verify_block_header_exists( - proposal.block_header.clone(), - proposal.resource_id.typed_chain_id(), - )?; - - // validate the merkle proofs - T::ProofVerifier::verify_storage_proof( - proposal.clone().block_header, - MERKLE_ROOT_KEY.to_vec(), - proposal.clone().merkle_root_proof.to_vec(), - ) - .map_err(|_| Error::::ProofVerificationFailed)?; - - T::ProofVerifier::verify_storage_proof( - proposal.clone().block_header, - LEAF_INDEX_KEY.to_vec(), - proposal.clone().leaf_index_proof.to_vec(), - ) - .map_err(|_| Error::::ProofVerificationFailed)?; - - // prepare the proposals to all linked bridges - Self::submit_anchor_update_proposals(proposal.clone())?; - - Ok(().into()) - } - } -} - -impl Pallet { - /// Submits anchor update proposals for all registered bridges from bridge registry - /// - /// This function takes a `TypedChainId` representing the chain ID and a `LightProposalInput` - /// type `proposal` containing the proposal details. - /// - /// The function iterates through all registered bridges on the chain and creates an anchor - /// update proposal for each one. - /// - /// # Arguments - /// - /// * `typed_chain_id` - The typed chain ID. - /// * `proposal` - A `LightProposalInput` containing the details of the proposal. - /// - /// # Errors - /// - /// Returns a `DispatchError` if there was an issue during proposal submission. - pub fn submit_anchor_update_proposals( - proposal: LightProposalInput, - ) -> Result<(), DispatchError> { - let src_resource_id = proposal.resource_id; - - // fetch bridge index for source_resource_id - let bridge_index = pallet_bridge_registry::ResourceToBridgeIndex::::get(src_resource_id) - .ok_or(Error::::CannotFetchBridgeDetails)?; - - // get all connected resource_ids - let bridge_metadata = pallet_bridge_registry::Bridges::::get(bridge_index) - .ok_or(Error::::CannotFetchBridgeMetadata)?; - - for resource_id in bridge_metadata.resource_ids.iter() { - // create AUP for resource_id - Self::create_and_submit_anchor_update_proposal( - proposal.clone(), - src_resource_id, - *resource_id, - )?; - } - - // emit event - Self::deposit_event(Event::ProposalSubmitted { proposal: proposal.clone() }); - - Ok(()) - } - - /// Creates and submits an anchor update proposal. - /// - /// This function takes a `LightProposalInput` type `proposal`, representing the proposal - /// details, `src_resource_id` representing the source resource ID, and `target_resource_id` - /// representing the target resource ID. - /// - /// # Arguments - /// - /// * `proposal` - A `LightProposalInput` containing the details of the proposal. - /// * `src_resource_id` - The resource ID of the source. - /// * `target_resource_id` - The resource ID of the target. - /// - /// # Errors - /// - /// Returns a `DispatchError` if there was an issue during proposal submission. - pub fn create_and_submit_anchor_update_proposal( - proposal: LightProposalInput, - src_resource_id: ResourceId, - target_resource_id: ResourceId, - ) -> Result<(), DispatchError> { - // get the nonce used for target resrouce id - let nonce = ResourceIdToNonce::::get(target_resource_id); - // update the nonce - ResourceIdToNonce::::insert(target_resource_id, nonce.saturating_add(1u32)); - let function_signature_bytes = v_anchor_contract::UpdateEdgeCall::selector(); - - // prep the proposal - let proposal = AnchorUpdateProposal::new( - ProposalHeader::new( - target_resource_id, - FunctionSignature::from(function_signature_bytes), - nonce.into(), - ), - proposal.merkle_root, - src_resource_id, - ); - - let unsigned_anchor_update_proposal: Proposal = Proposal::Unsigned { - kind: ProposalKind::AnchorUpdate, - data: proposal.encode(), - }; - - // submit the proposal - T::ProposalHandler::handle_unsigned_proposal(unsigned_anchor_update_proposal)?; - - Ok(()) - } -} diff --git a/pallets/light-proposals/src/mock.rs b/pallets/light-proposals/src/mock.rs deleted file mode 100644 index 146f1e8a..00000000 --- a/pallets/light-proposals/src/mock.rs +++ /dev/null @@ -1,203 +0,0 @@ -use super::*; -use crate as pallet_light_proposals; - -use codec::{Decode, Encode}; -use consensus::network_config::{Network, NetworkConfig}; - -use dkg_runtime_primitives::{SignedProposalBatch, TypedChainId}; -use eth_types::BlockHeader; -use frame_support::{ensure, pallet_prelude::DispatchResult, parameter_types, sp_io, PalletId}; -use frame_system as system; -use scale_info::TypeInfo; -use sp_core::H256; -use sp_runtime::{ - traits::{BlakeTwo256, ConstU32, IdentifyAccount, IdentityLookup, Verify}, - AccountId32, BuildStorage, MultiSignature, -}; -use sp_std::convert::{TryFrom, TryInto}; -use webb_light_client_primitives::traits::ProofVerifier; - -pub type Signature = MultiSignature; -pub type AccountId = <::Signer as IdentifyAccount>::AccountId; - -// Configure a mock runtime to test the pallet. -frame_support::construct_runtime!( - pub enum Test { - System: frame_system, - Balances: pallet_balances, - BridgeRegistry: pallet_bridge_registry, - Eth2Client: pallet_eth2_light_client, - LightProposals: pallet_light_proposals - } -); - -parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const SS58Prefix: u8 = 42; -} - -impl system::Config for Test { - type AccountData = pallet_balances::AccountData; - type AccountId = AccountId; - type BaseCallFilter = frame_support::traits::Everything; - type BlockHashCount = BlockHashCount; - type BlockLength = (); - type Nonce = u64; - type Block = frame_system::mocking::MockBlock; - type BlockWeights = (); - type RuntimeCall = RuntimeCall; - type DbWeight = (); - type RuntimeEvent = RuntimeEvent; - type Hash = H256; - type Hashing = BlakeTwo256; - type Lookup = IdentityLookup; - type MaxConsumers = frame_support::traits::ConstU32<16>; - type OnKilledAccount = (); - type OnNewAccount = (); - type OnSetCode = (); - type RuntimeOrigin = RuntimeOrigin; - type PalletInfo = PalletInfo; - type SS58Prefix = SS58Prefix; - type SystemWeightInfo = (); - type Version = (); -} - -parameter_types! { - pub const ExistentialDeposit: u64 = 1; -} - -impl pallet_balances::Config for Test { - type AccountStore = System; - type Balance = u128; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ExistentialDeposit; - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type FreezeIdentifier = (); - type MaxHolds = (); - type MaxFreezes = (); - type WeightInfo = (); - type RuntimeHoldReason = RuntimeHoldReason; -} - -parameter_types! { - #[derive(serde::Serialize, serde::Deserialize)] - pub const MaxAdditionalFields: u32 = 5; - #[derive(serde::Serialize, serde::Deserialize)] - pub const MaxResources: u32 = 32; - pub const StoragePricePerByte: u128 = 1; - pub const Eth2ClientPalletId: PalletId = PalletId(*b"py/eth2c"); -} - -impl pallet_eth2_light_client::Config for Test { - type RuntimeEvent = RuntimeEvent; - type StoragePricePerByte = StoragePricePerByte; - type PalletId = Eth2ClientPalletId; - type Currency = Balances; -} - -parameter_types! { - #[derive(Clone, Encode, Decode, Debug, Eq, PartialEq, scale_info::TypeInfo, Ord, PartialOrd)] - pub const MaxProposalLength : u32 = 10_000; -} - -impl pallet_bridge_registry::Config for Test { - type RuntimeEvent = RuntimeEvent; - type BridgeIndex = u32; - type MaxAdditionalFields = MaxAdditionalFields; - type MaxResources = MaxResources; - type ForceOrigin = frame_system::EnsureRoot; - type MaxProposalLength = MaxProposalLength; - type WeightInfo = (); -} - -pub struct MockStorageProofVerifier; - -impl ProofVerifier for MockStorageProofVerifier { - fn verify_storage_proof( - _header: BlockHeader, - _key: Vec, - proof: Vec>, - ) -> Result { - // test case - ensure!(proof != vec![vec![123]], Error::::ProofVerificationFailed); - Ok(true) - } -} - -pub struct MockProposalHandler; - -impl ProposalHandlerTrait for MockProposalHandler { - type BatchId = u32; - type MaxProposalLength = MaxProposalLength; - type MaxProposals = ConstU32<100>; - type MaxSignatureLen = ConstU32<100>; - - fn handle_unsigned_proposal(_proposal: Proposal) -> DispatchResult { - Ok(()) - } - - fn handle_signed_proposal_batch( - _prop: SignedProposalBatch< - Self::BatchId, - Self::MaxProposalLength, - Self::MaxProposals, - Self::MaxSignatureLen, - >, - ) -> DispatchResult { - Ok(()) - } -} - -parameter_types! { - #[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone, Encode, Decode, TypeInfo)] - pub const MaxProofSize: u32 = 50; -} - -impl pallet_light_proposals::Config for Test { - type RuntimeEvent = RuntimeEvent; - type LightClient = Eth2Client; - type ProofVerifier = MockStorageProofVerifier; - type ProposalHandler = MockProposalHandler; - type MaxProofSize = MaxProofSize; - type MaxProposalLength = MaxProposalLength; -} - -// Build genesis storage according to the mock runtime. -pub fn new_test_ext() -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); - let _ = pallet_balances::GenesisConfig:: { - balances: vec![ - (AccountId32::new([1u8; 32]), 10u128.pow(18)), - (AccountId32::new([2u8; 32]), 20u128.pow(18)), - (AccountId32::new([3u8; 32]), 30u128.pow(18)), - ], - } - .assimilate_storage(&mut storage); - let _ = pallet_eth2_light_client::GenesisConfig:: { - phantom: Default::default(), - networks: vec![ - ( - // Mainnet - TypedChainId::Evm(1), - NetworkConfig::new(&Network::Mainnet), - ), - ( - // Goerli - TypedChainId::Evm(5), - NetworkConfig::new(&Network::Goerli), - ), - ], - } - .assimilate_storage(&mut storage); - - let _ = pallet_bridge_registry::GenesisConfig:: { - phantom: Default::default(), - bridges: vec![], - } - .assimilate_storage(&mut storage); - - storage.into() -} diff --git a/pallets/light-proposals/src/tests.rs b/pallets/light-proposals/src/tests.rs deleted file mode 100644 index c9bad1d8..00000000 --- a/pallets/light-proposals/src/tests.rs +++ /dev/null @@ -1,162 +0,0 @@ -#![allow(clippy::unwrap_used)] -use crate::{mock::*, Error, LightProposalInput, Proposal, ProposalKind, ResourceId}; -use dkg_runtime_primitives::{traits::OnSignedProposal, TypedChainId}; -use ethereum_types::Address; -use frame_support::{assert_err, assert_ok, bounded_vec}; -use lazy_static::lazy_static; -use pallet_bridge_registry::{types::BridgeMetadata, Bridges, ResourceToBridgeIndex}; -use pallet_eth2_light_client::tests::{get_test_context, submit_and_check_execution_headers}; -use sp_runtime::AccountId32; -use webb_proposals::{self, evm, FunctionSignature, Nonce, ProposalHeader, TargetSystem}; - -pub const GOERLI_CHAIN: TypedChainId = TypedChainId::Evm(5); -pub const ALICE: AccountId32 = AccountId32::new([1u8; 32]); - -lazy_static! { - static ref GOERLI_RESOURCE_ID: ResourceId = - ResourceId::new(TargetSystem::new_contract_address(Address::from([0; 20])), GOERLI_CHAIN); -} - -// setup bridge registry pallets with defaults -fn setup_bridge_registry() { - let target_chain = webb_proposals::TypedChainId::Evm(1); - let target_system = webb_proposals::TargetSystem::new_contract_address([1u8; 20]); - let target_resource_id = webb_proposals::ResourceId::new(target_system, target_chain); - // Create src info - let src_chain = GOERLI_CHAIN; - let src_target_system = webb_proposals::TargetSystem::new_contract_address([0u8; 20]); - let src_resource_id = webb_proposals::ResourceId::new(src_target_system, src_chain); - // Create mocked signed EVM anchor update proposals - let proposal = evm::AnchorUpdateProposal::new( - ProposalHeader::new(target_resource_id, FunctionSignature([0u8; 4]), Nonce(1)), - [1u8; 32], - src_resource_id, - ); - let signed_proposal = Proposal::Signed { - kind: ProposalKind::AnchorUpdate, - data: proposal.into_bytes().to_vec().try_into().unwrap(), - signature: vec![].try_into().unwrap(), - }; - // Handle signed proposal - assert_ok!(BridgeRegistry::on_signed_proposal(signed_proposal)); - // Verify the storage system updates correctly - assert_eq!(ResourceToBridgeIndex::::get(target_resource_id), Some(1)); - assert_eq!(ResourceToBridgeIndex::::get(src_resource_id), Some(1)); - assert_eq!( - Bridges::::get(1).unwrap(), - BridgeMetadata { - resource_ids: bounded_vec![src_resource_id, target_resource_id], - info: Default::default() - } - ); -} - -#[test] -fn test_light_light_proposal_flow() { - new_test_ext().execute_with(|| { - // setup bridge registry with defaults - setup_bridge_registry(); - - // prep light client pallet - let (headers, updates, _init_input) = get_test_context(None); - assert_ok!(Eth2Client::submit_beacon_chain_light_client_update( - RuntimeOrigin::signed(ALICE), - GOERLI_CHAIN, - updates[1].clone() - )); - - submit_and_check_execution_headers( - pallet_eth2_light_client::mock::RuntimeOrigin::signed(ALICE), - GOERLI_CHAIN, - headers[0].iter().skip(1).rev().collect(), - ); - - let mut header = headers[0][1].clone(); - let block_hash = pallet_eth2_light_client::FinalizedExecutionBlocks::::get( - GOERLI_CHAIN, - header.number, - ); - header.hash = block_hash; - - // setup light client payload - let light_proposal = LightProposalInput { - block_header: header, - merkle_root: [0; 32], - merkle_root_proof: vec![vec![0; 32]], - leaf_index: 0, - leaf_index_proof: vec![vec![0; 32]], - resource_id: *GOERLI_RESOURCE_ID, - }; - - assert_ok!(LightProposals::submit_proposal(RuntimeOrigin::signed(ALICE), light_proposal)); - }); -} - -#[test] -fn test_light_light_should_reject_if_header_is_not_present() { - new_test_ext().execute_with(|| { - // setup bridge registry with defaults - setup_bridge_registry(); - - let (headers, _updates, _init_input) = get_test_context(None); - - // setup light client payload - let light_proposal = LightProposalInput { - block_header: headers[0][1].clone(), - merkle_root: [0; 32], - merkle_root_proof: vec![vec![0; 32]], - leaf_index: 0, - leaf_index_proof: vec![vec![0; 32]], - resource_id: *GOERLI_RESOURCE_ID, - }; - - assert_err!( - LightProposals::submit_proposal(RuntimeOrigin::signed(ALICE), light_proposal), - pallet_eth2_light_client::Error::::HeaderHashDoesNotExist - ); - }); -} - -#[test] -fn test_light_light_should_reject_if_proof_verification_fails() { - new_test_ext().execute_with(|| { - // setup bridge registry with defaults - setup_bridge_registry(); - - // prep light client pallet - let (headers, updates, _init_input) = get_test_context(None); - assert_ok!(Eth2Client::submit_beacon_chain_light_client_update( - RuntimeOrigin::signed(ALICE), - GOERLI_CHAIN, - updates[1].clone() - )); - - submit_and_check_execution_headers( - pallet_eth2_light_client::mock::RuntimeOrigin::signed(ALICE), - GOERLI_CHAIN, - headers[0].iter().skip(1).rev().collect(), - ); - - let mut header = headers[0][1].clone(); - let block_hash = pallet_eth2_light_client::FinalizedExecutionBlocks::::get( - GOERLI_CHAIN, - header.number, - ); - header.hash = block_hash; - - // setup light client payload - let light_proposal = LightProposalInput { - block_header: header, - merkle_root: [0; 32], - merkle_root_proof: vec![vec![123]], - leaf_index: 0, - leaf_index_proof: vec![vec![0; 32]], - resource_id: *GOERLI_RESOURCE_ID, - }; - - assert_err!( - LightProposals::submit_proposal(RuntimeOrigin::signed(ALICE), light_proposal), - Error::::ProofVerificationFailed - ); - }); -} diff --git a/pallets/light-verifier/Cargo.toml b/pallets/light-verifier/Cargo.toml index f90a811e..32e7b611 100644 --- a/pallets/light-verifier/Cargo.toml +++ b/pallets/light-verifier/Cargo.toml @@ -26,7 +26,8 @@ sp-core = { workspace = true } log = { workspace = true } serde = { workspace = true, optional = true } -codec = { workspace = true, features = ["derive", "max-encoded-len"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } + scale-info = { workspace = true } webb-proposals = { workspace = true, features = ["evm", "substrate"] } ethereum-types = { workspace = true } @@ -38,7 +39,6 @@ tiny-keccak = { workspace = true } bitvec = { workspace = true, features = ["atomic", "alloc"] } hex = { workspace = true } webb-light-client-primitives = { workspace = true } -dkg-runtime-primitives = { git = "https://github.com/webb-tools/dkg-substrate.git", branch = "master", default-features = false } [dev-dependencies] anyhow = { workspace = true } @@ -68,7 +68,6 @@ std = [ "sp-std/std", "sp-core/std", "hex/std", - "dkg-runtime-primitives/std", "pallet-eth2-light-client/std", # Local dependencies diff --git a/pallets/light-verifier/src/lib.rs b/pallets/light-verifier/src/lib.rs index 95c893af..9058b3cb 100644 --- a/pallets/light-verifier/src/lib.rs +++ b/pallets/light-verifier/src/lib.rs @@ -20,7 +20,6 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] -#![feature(slice_pattern)] #![allow(unused)] use eth_types::BlockHeader; diff --git a/pallets/light-verifier/src/mock.rs b/pallets/light-verifier/src/mock.rs index 56843bed..5f7391ec 100644 --- a/pallets/light-verifier/src/mock.rs +++ b/pallets/light-verifier/src/mock.rs @@ -46,6 +46,7 @@ impl system::Config for Test { type DbWeight = (); type RuntimeEvent = RuntimeEvent; type Hash = H256; + type RuntimeTask = (); type Hashing = BlakeTwo256; type Lookup = IdentityLookup; type MaxConsumers = frame_support::traits::ConstU32<16>; @@ -73,7 +74,7 @@ impl pallet_balances::Config for Test { type MaxReserves = (); type ReserveIdentifier = [u8; 8]; type FreezeIdentifier = (); - type MaxHolds = (); + type RuntimeFreezeReason = (); type MaxFreezes = (); type WeightInfo = (); type RuntimeHoldReason = RuntimeHoldReason; diff --git a/pallets/light-verifier/src/verify.rs b/pallets/light-verifier/src/verify.rs index fa665c6d..dfce4b35 100644 --- a/pallets/light-verifier/src/verify.rs +++ b/pallets/light-verifier/src/verify.rs @@ -1,7 +1,7 @@ use super::*; -use dkg_runtime_primitives::H256; use frame_support::ensure; use rlp::Rlp; +use sp_core::H256; /// A utility for working with trie proofs. pub struct TrieProver; diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index 9cae80c8..12890217 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -14,7 +14,8 @@ webb-proposals = { workspace = true } ethereum-types = { workspace = true } log = { workspace = true } serde = { workspace = true, optional = true } -codec = { workspace = true, features = ["derive", "max-encoded-len"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } + scale-info = { workspace = true } [features] diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index 787a632f..91c25f78 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -13,7 +13,8 @@ repository = "https://github.com/substrate-developer-hub/substrate-node-template targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { workspace = true, features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } + scale-info = { workspace = true } log = { workspace = true } @@ -63,7 +64,7 @@ pallet-eth2-light-client = { path = "../pallets/eth2-light-client", default-feat pallet-eth2-light-client-runtime-api = { path = "../pallets/eth2-light-client/runtime-api", default-features = false } [build-dependencies] -substrate-wasm-builder = { version = "5.0.0-dev", git = "https://github.com/paritytech/polkadot-sdk", optional = true , branch = "release-polkadot-v1.1.0" } +substrate-wasm-builder = { version = "17.0.0", git = "https://github.com/paritytech/polkadot-sdk", optional = true , branch = "release-polkadot-v1.7.0" } [features] default = ["std"] diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index de15a363..7c74a0d9 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -11,12 +11,12 @@ use frame_election_provider_support::{ bounds::{ElectionBounds, ElectionBoundsBuilder}, onchain, BalancingConfig, ElectionDataProvider, SequentialPhragmen, VoteWeight, }; -use frame_support::{dispatch::DispatchClass, PalletId}; +use frame_support::{derive_impl, dispatch::DispatchClass, PalletId}; use frame_system::{ limits::{BlockLength, BlockWeights}, EnsureRoot, }; -use pallet_election_provider_multi_phase::SolutionAccuracyOf; +use pallet_election_provider_multi_phase::{BalanceOf, GeometricDepositBase, SolutionAccuracyOf}; use pallet_eth2_light_client_runtime_api::runtime_decl_for_eth_2_light_client_api::{ ClientMode, LightClientState, TypedChainId, }; @@ -27,15 +27,14 @@ use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ create_runtime_str, curve::PiecewiseLinear, - generic, - generic::Era, + generic::{self, Era}, impl_opaque_keys, traits::{ - self, BlakeTwo256, Block as BlockT, Get, IdentifyAccount, NumberFor, One, OpaqueKeys, - SaturatedConversion, StaticLookup, Verify, + self, BlakeTwo256, Block as BlockT, Convert, Get, IdentifyAccount, NumberFor, One, + OpaqueKeys, SaturatedConversion, StaticLookup, Verify, }, transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, MultiSignature, + ApplyExtrinsicResult, MultiSignature, Percent, }; use sp_std::prelude::*; #[cfg(feature = "std")] @@ -184,7 +183,7 @@ parameter_types! { } // Configure FRAME pallets to include in runtime. - +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { /// The basic call filter to use in dispatchable. type BaseCallFilter = frame_support::traits::Everything; @@ -230,6 +229,7 @@ impl frame_system::Config for Runtime { type SS58Prefix = SS58Prefix; /// The set code logic, just the default since we're not a parachain. type OnSetCode = (); + type RuntimeTask = (); type MaxConsumers = frame_support::traits::ConstU32<16>; } @@ -273,6 +273,7 @@ parameter_types! { pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE; pub const MaxNominatorRewardedPerValidator: u32 = 256; pub const OffendingValidatorsThreshold: Perbill = Perbill::from_percent(17); + pub const MaxControllersInDeprecationBatch: u32 = 5900; pub OffchainRepeat: BlockNumber = 5; pub HistoryDepth: u32 = 84; } @@ -302,7 +303,6 @@ impl pallet_staking::Config for Runtime { type SessionInterface = Self; type EraPayout = pallet_staking::ConvertCurve; type NextNewSession = Session; - type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; type OffendingValidatorsThreshold = OffendingValidatorsThreshold; type ElectionProvider = ElectionProviderMultiPhase; type GenesisElectionProvider = onchain::OnChainExecution; @@ -310,6 +310,8 @@ impl pallet_staking::Config for Runtime { // This a placeholder, to be introduced in the next PR as an instance of bags-list type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; + type MaxControllersInDeprecationBatch = ConstU32<5900>; + type MaxExposurePageSize = ConstU32<32>; type HistoryDepth = HistoryDepth; type NominationsQuota = pallet_staking::FixedNominationsQuota; type EventListeners = (); @@ -326,11 +328,8 @@ parameter_types! { // signed config pub const SignedRewardBase: Balance = DOLLARS; - pub const SignedDepositBase: Balance = DOLLARS; pub const SignedDepositByte: Balance = CENTS; - pub BetterUnsignedThreshold: Perbill = Perbill::from_rational(1u32, 10_000); - // miner configs pub const MultiPhaseUnsignedPriority: TransactionPriority = StakingUnsignedPriority::get() - 1u64; pub MinerMaxWeight: Weight = RuntimeBlockWeights::get() @@ -370,6 +369,9 @@ parameter_types! { .voters_count(10_000.into()).targets_count(1_500.into()).build(); pub ElectionBoundsOnChain: ElectionBounds = ElectionBoundsBuilder::default() .voters_count(5_000.into()).targets_count(1_250.into()).build(); + pub EnableVariableDepositBase: bool = false; + pub SignedFixedDeposit: Balance = 5; + pub SignedDepositIncreaseFactor: Percent = Percent::from_percent(10); } /// The numbers configured here could always be more than the the maximum limits of staking pallet @@ -400,8 +402,8 @@ impl Get> for OffchainRandomBalancing { max => { let seed = sp_io::offchain::random_seed(); let random = ::decode(&mut TrailingZeroInput::new(&seed)) - .expect("input is padded with zeroes; qed") % - max.saturating_add(1); + .expect("input is padded with zeroes; qed") + % max.saturating_add(1); random as usize }, }; @@ -450,14 +452,13 @@ impl pallet_election_provider_multi_phase::Config for Runtime { type EstimateCallFee = TransactionPayment; type SignedPhase = SignedPhase; type UnsignedPhase = UnsignedPhase; - type BetterUnsignedThreshold = BetterUnsignedThreshold; type BetterSignedThreshold = (); type OffchainRepeat = OffchainRepeat; type MinerTxPriority = MultiPhaseUnsignedPriority; type MinerConfig = Self; type SignedMaxSubmissions = ConstU32<10>; type SignedRewardBase = SignedRewardBase; - type SignedDepositBase = SignedDepositBase; + type SignedDepositBase = Self; type SignedDepositByte = SignedDepositByte; type SignedMaxRefunds = ConstU32<3>; type SignedDepositWeight = (); @@ -475,6 +476,18 @@ impl pallet_election_provider_multi_phase::Config for Runtime { type WeightInfo = pallet_election_provider_multi_phase::weights::SubstrateWeight; } +impl Convert> for Runtime { + /// returns the geometric increase deposit fee if `EnableVariableDepositBase` is set, otherwise + /// the fee is `SignedFixedDeposit`. + fn convert(queue_len: usize) -> Balance { + if !EnableVariableDepositBase::get() { + SignedFixedDeposit::get() + } else { + GeometricDepositBase::::convert(queue_len) + } + } +} + parameter_types! { pub const BagThresholds: &'static [u64] = &voter_bags::THRESHOLDS; } @@ -546,7 +559,7 @@ impl pallet_balances::Config for Runtime { type FreezeIdentifier = (); type MaxFreezes = (); type RuntimeHoldReason = RuntimeHoldReason; - type MaxHolds = (); + type RuntimeFreezeReason = (); } parameter_types! { diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 699de8c6..c38c8a87 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "nightly-2023-07-16" +channel = "stable" components = ["rustfmt", "clippy"] -targets = ["wasm32-unknown-unknown"] \ No newline at end of file +targets = ["wasm32-unknown-unknown"]