From abc4c3989bc599004a34cd6b0b3a91fc93bc2f27 Mon Sep 17 00:00:00 2001 From: Kurdistan Tech Ministry Date: Mon, 22 Dec 2025 17:12:58 +0300 Subject: [PATCH] style: Migrate to stable-only rustfmt configuration - Remove nightly-only features from .rustfmt.toml and vendor/ss58-registry/rustfmt.toml - Removed features: imports_granularity, wrap_comments, comment_width, reorder_impl_items, spaces_around_ranges, binop_separator, match_arm_blocks, trailing_semicolon, trailing_comma - Format all 898 affected files with stable rustfmt - Ensures long-term reliability without nightly toolchain dependency --- .rustfmt.toml | 27 +- bizinikiwi/bin/node/bench/src/tempdb.rs | 5 +- bizinikiwi/bin/node/cli/src/command.rs | 10 +- .../node/cli/tests/benchmark_pallet_works.rs | 1 - .../cli/tests/benchmark_pezpallet_works.rs | 1 - .../node/cli/tests/benchmark_storage_works.rs | 1 - .../bin/node/cli/tests/check_block_works.rs | 1 - .../bin/node/cli/tests/export_import_flow.rs | 1 - .../bin/node/cli/tests/inspect_works.rs | 1 - .../tests/running_the_node_and_interrupt.rs | 1 - .../node/cli/tests/temp_base_path_works.rs | 1 - bizinikiwi/bin/node/runtime/src/impls.rs | 4 +- bizinikiwi/bin/node/runtime/src/lib.rs | 28 +- bizinikiwi/bin/node/testing/src/bench.rs | 19 +- .../bin/utils/chain-spec-builder/src/lib.rs | 5 +- .../client/allocator/src/freeing_bump.rs | 4 +- bizinikiwi/client/api/src/in_mem.rs | 8 +- .../client/api/src/notifications/registry.rs | 5 +- .../client/authority-discovery/src/worker.rs | 15 +- .../basic-authorship/src/basic_authorship.rs | 13 +- .../client/chain-spec/src/chain_spec.rs | 34 +- .../client/chain-spec/src/json_patch.rs | 5 +- bizinikiwi/client/cli/src/arg_enums.rs | 20 +- .../client/cli/src/params/import_params.rs | 10 +- .../client/cli/src/params/network_params.rs | 9 +- .../client/cli/src/params/node_key_params.rs | 18 +- .../client/cli/src/params/rpc_params.rs | 4 +- .../cli/src/params/transaction_pool_params.rs | 10 +- .../client/consensus/aura/src/import_queue.rs | 5 +- bizinikiwi/client/consensus/aura/src/lib.rs | 5 +- .../client/consensus/aura/src/standalone.rs | 5 +- .../client/consensus/babe/src/authorship.rs | 8 +- .../client/consensus/babe/src/aux_schema.rs | 24 +- bizinikiwi/client/consensus/babe/src/lib.rs | 67 ++- .../client/consensus/beefy/src/aux_schema.rs | 10 +- .../beefy/src/communication/gossip.rs | 5 +- .../consensus/beefy/src/justification.rs | 5 +- bizinikiwi/client/consensus/beefy/src/lib.rs | 5 +- .../client/consensus/beefy/src/round.rs | 4 +- .../client/consensus/beefy/src/tests.rs | 5 +- .../client/consensus/beefy/src/worker.rs | 5 +- .../consensus/common/src/block_import.rs | 6 +- .../consensus/common/src/import_queue.rs | 14 +- .../common/src/import_queue/basic_queue.rs | 10 +- .../common/src/import_queue/buffered_link.rs | 15 +- bizinikiwi/client/consensus/epochs/src/lib.rs | 92 ++-- .../consensus/grandpa/src/authorities.rs | 17 +- .../consensus/grandpa/src/aux_schema.rs | 8 +- .../grandpa/src/communication/gossip.rs | 90 +-- .../grandpa/src/communication/mod.rs | 25 +- .../grandpa/src/communication/tests.rs | 10 +- .../consensus/grandpa/src/environment.rs | 26 +- .../client/consensus/grandpa/src/import.rs | 21 +- .../consensus/grandpa/src/justification.rs | 15 +- .../client/consensus/grandpa/src/tests.rs | 8 +- .../consensus/grandpa/src/until_imported.rs | 4 +- .../consensus/grandpa/src/voting_rule.rs | 4 +- .../manual-seal/src/consensus/babe.rs | 5 +- .../consensus/manual-seal/src/seal_block.rs | 5 +- bizinikiwi/client/consensus/pow/src/lib.rs | 20 +- bizinikiwi/client/consensus/slots/src/lib.rs | 6 +- bizinikiwi/client/db/src/lib.rs | 90 +-- bizinikiwi/client/db/src/parity_db.rs | 10 +- bizinikiwi/client/db/src/upgrade.rs | 5 +- bizinikiwi/client/db/src/utils.rs | 29 +- .../common/src/runtime_blob/runtime_blob.rs | 5 +- bizinikiwi/client/executor/polkavm/src/lib.rs | 40 +- .../executor/src/integration_tests/mod.rs | 15 +- .../client/executor/src/wasm_runtime.rs | 5 +- .../client/executor/wasmtime/src/imports.rs | 5 +- .../client/executor/wasmtime/src/runtime.rs | 21 +- .../client/executor/wasmtime/src/util.rs | 5 +- bizinikiwi/client/informant/src/display.rs | 18 +- bizinikiwi/client/keystore/src/lib.rs | 5 +- .../merkle-mountain-range/rpc/src/lib.rs | 4 +- .../merkle-mountain-range/src/aux_schema.rs | 8 +- .../merkle-mountain-range/src/test_utils.rs | 5 +- .../client/mixnet/src/maybe_inf_delay.rs | 5 +- bizinikiwi/client/mixnet/src/request.rs | 5 +- .../client/network-gossip/src/bridge.rs | 15 +- .../network-gossip/src/state_machine.rs | 5 +- .../src/light_client_requests/handler.rs | 20 +- bizinikiwi/client/network/src/behaviour.rs | 75 ++- bizinikiwi/client/network/src/bitswap/mod.rs | 6 +- bizinikiwi/client/network/src/discovery.rs | 14 +- .../client/network/src/litep2p/discovery.rs | 24 +- bizinikiwi/client/network/src/litep2p/mod.rs | 25 +- .../network/src/litep2p/shim/bitswap.rs | 5 +- .../src/litep2p/shim/notification/peerset.rs | 29 +- .../litep2p/shim/notification/tests/fuzz.rs | 35 +- .../src/litep2p/shim/request_response/mod.rs | 50 +- .../client/network/src/network_state.rs | 10 +- bizinikiwi/client/network/src/peer_info.rs | 14 +- bizinikiwi/client/network/src/protocol.rs | 10 +- .../client/network/src/protocol/message.rs | 5 +- .../src/protocol/notifications/behaviour.rs | 89 +-- .../src/protocol/notifications/handler.rs | 77 +-- .../src/protocol/notifications/service/mod.rs | 15 +- .../notifications/tests/conformance.rs | 12 +- .../src/protocol/notifications/tests/mod.rs | 28 +- .../notifications/upgrade/notifications.rs | 28 +- .../client/network/src/protocol_controller.rs | 23 +- .../client/network/src/request_responses.rs | 23 +- bizinikiwi/client/network/src/service.rs | 100 ++-- .../client/network/src/service/out_events.rs | 14 +- .../client/network/statement/src/lib.rs | 10 +- .../sync/src/block_announce_validator.rs | 11 +- .../network/sync/src/block_request_handler.rs | 11 +- bizinikiwi/client/network/sync/src/blocks.rs | 22 +- bizinikiwi/client/network/sync/src/engine.rs | 55 +- .../network/sync/src/service/network.rs | 15 +- .../network/sync/src/strategy/chain_sync.rs | 101 ++-- .../sync/src/strategy/chain_sync/test.rs | 6 +- .../network/sync/src/strategy/pezkuwi.rs | 26 +- .../client/network/sync/src/strategy/state.rs | 6 +- .../client/network/sync/src/strategy/warp.rs | 17 +- bizinikiwi/client/network/test/src/fuzz.rs | 29 +- bizinikiwi/client/network/test/src/lib.rs | 8 +- bizinikiwi/client/network/test/src/service.rs | 10 +- bizinikiwi/client/network/test/src/sync.rs | 32 +- .../client/network/transactions/src/lib.rs | 5 +- .../network/types/src/multiaddr/protocol.rs | 5 +- .../client/network/types/src/peer_id.rs | 5 +- bizinikiwi/client/offchain/src/api/http.rs | 28 +- .../client/offchain/src/api/timestamp.rs | 5 +- bizinikiwi/client/rpc-api/src/policy.rs | 5 +- bizinikiwi/client/rpc-api/src/state/error.rs | 10 +- bizinikiwi/client/rpc-api/src/system/error.rs | 15 +- .../rpc-servers/src/middleware/node_health.rs | 23 +- .../client/rpc-spec-v2/src/archive/archive.rs | 4 +- .../src/archive/archive_storage.rs | 10 +- .../rpc-spec-v2/src/chain_head/chain_head.rs | 34 +- .../src/chain_head/chain_head_follow.rs | 18 +- .../rpc-spec-v2/src/chain_head/error.rs | 35 +- .../rpc-spec-v2/src/chain_head/tests.rs | 10 +- .../rpc-spec-v2/src/transaction/error.rs | 40 +- .../rpc-spec-v2/src/transaction/event.rs | 43 +- .../src/transaction/transaction.rs | 20 +- bizinikiwi/client/rpc/src/state/state_full.rs | 25 +- bizinikiwi/client/rpc/src/statement/mod.rs | 5 +- bizinikiwi/client/rpc/src/system/tests.rs | 10 +- bizinikiwi/client/service/src/builder.rs | 22 +- .../service/src/chain_ops/export_blocks.rs | 5 +- .../service/src/chain_ops/import_blocks.rs | 21 +- .../client/service/src/client/client.rs | 76 +-- .../src/client/notification_pinning.rs | 5 +- bizinikiwi/client/service/src/lib.rs | 5 +- bizinikiwi/client/state-db/src/lib.rs | 39 +- .../client/state-db/src/noncanonical.rs | 12 +- bizinikiwi/client/statement-store/src/lib.rs | 23 +- bizinikiwi/client/sysinfo/src/sysinfo.rs | 37 +- .../client/tracing/benches/common/mod.rs | 5 +- bizinikiwi/client/tracing/src/lib.rs | 16 +- .../tracing/src/logging/event_format.rs | 8 +- .../client/transaction-pool/api/src/lib.rs | 10 +- .../client/transaction-pool/benches/basics.rs | 5 +- .../src/common/enactment_state.rs | 5 +- .../transaction-pool/src/common/tests.rs | 5 +- .../src/fork_aware_txpool/dropped_watcher.rs | 5 +- .../fork_aware_txpool/fork_aware_txpool.rs | 28 +- .../fork_aware_txpool/multi_view_listener.rs | 50 +- .../fork_aware_txpool/revalidation_worker.rs | 5 +- .../src/fork_aware_txpool/tx_mem_pool.rs | 39 +- .../src/fork_aware_txpool/view_store.rs | 5 +- .../transaction-pool/src/graph/base_pool.rs | 5 +- .../transaction-pool/src/graph/future.rs | 4 +- .../client/transaction-pool/src/graph/pool.rs | 15 +- .../transaction-pool/src/graph/ready.rs | 12 +- .../src/graph/validated_pool.rs | 18 +- .../single_state_txpool.rs | 19 +- .../tests/zombienet/yap_test.rs | 2 +- bizinikiwi/client/utils/src/mpsc.rs | 5 +- bizinikiwi/pezframe/alliance/src/migration.rs | 4 +- .../asset-conversion/ops/src/benchmarking.rs | 8 +- .../pezframe/asset-conversion/ops/src/lib.rs | 12 +- .../asset-conversion/src/benchmarking.rs | 20 +- .../pezframe/asset-conversion/src/tests.rs | 24 +- .../asset-rewards/src/benchmarking.rs | 8 +- .../pezframe/assets/precompiles/src/lib.rs | 4 +- bizinikiwi/pezframe/assets/src/functions.rs | 9 +- bizinikiwi/pezframe/babe/src/tests.rs | 4 +- bizinikiwi/pezframe/bags-list/src/list/mod.rs | 40 +- .../pezframe/balances/src/impl_currency.rs | 5 +- bizinikiwi/pezframe/balances/src/lib.rs | 14 +- bizinikiwi/pezframe/beefy/src/equivocation.rs | 49 +- bizinikiwi/pezframe/beefy/src/lib.rs | 20 +- bizinikiwi/pezframe/benchmarking/src/v1.rs | 2 +- .../pezframe/bounties/src/benchmarking.rs | 4 +- .../pezframe/broker/src/benchmarking.rs | 4 +- .../pezframe/broker/src/dispatchable_impls.rs | 10 +- .../child-bounties/src/benchmarking.rs | 4 +- bizinikiwi/pezframe/child-bounties/src/lib.rs | 16 +- .../pezframe/contracts/fixtures/build.rs | 4 +- .../mock-network/src/mocks/msg_queue.rs | 5 +- .../contracts/mock-network/src/teyrchain.rs | 4 +- .../pezframe/contracts/proc-macro/src/lib.rs | 3 +- .../contracts/src/benchmarking/mod.rs | 8 +- bizinikiwi/pezframe/contracts/src/exec.rs | 11 +- bizinikiwi/pezframe/contracts/src/lib.rs | 18 +- .../pezframe/contracts/src/migration/v10.rs | 4 +- .../pezframe/contracts/src/migration/v14.rs | 4 +- .../pezframe/contracts/src/migration/v15.rs | 12 +- .../pezframe/contracts/src/primitives.rs | 20 +- bizinikiwi/pezframe/contracts/src/storage.rs | 9 +- .../pezframe/contracts/src/storage/meter.rs | 34 +- bizinikiwi/pezframe/contracts/src/tests.rs | 4 +- bizinikiwi/pezframe/contracts/src/wasm/mod.rs | 5 +- .../pezframe/contracts/src/wasm/prepare.rs | 15 +- .../pezframe/contracts/src/wasm/runtime.rs | 15 +- .../contracts/uapi/src/host/wasm32.rs | 2 +- .../pezframe/conviction-voting/src/lib.rs | 5 +- .../pezframe/conviction-voting/src/tests.rs | 10 +- .../pezframe/conviction-voting/src/vote.rs | 34 +- .../pezframe/delegated-staking/src/lib.rs | 14 +- .../pezframe/delegated-staking/src/mock.rs | 4 +- .../pezframe/democracy/src/benchmarking.rs | 10 +- bizinikiwi/pezframe/democracy/src/lib.rs | 4 +- .../unlock_and_unreserve_all_funds.rs | 4 +- .../pezframe/democracy/src/migrations/v1.rs | 10 +- bizinikiwi/pezframe/democracy/src/vote.rs | 10 +- .../pezframe/democracy/src/vote_threshold.rs | 10 +- bizinikiwi/pezframe/derivatives/src/misc.rs | 5 +- .../derivatives/src/mock/auto_id_nfts.rs | 10 +- .../pezframe/derivatives/src/mock/mod.rs | 9 +- .../election-provider-multi-block/src/lib.rs | 67 +-- .../src/mock/mod.rs | 5 +- .../src/types.rs | 30 +- .../src/unsigned/miner.rs | 10 +- .../src/unsigned/mod.rs | 4 +- .../src/verifier/impls.rs | 14 +- .../election-provider-multi-phase/src/lib.rs | 14 +- .../election-provider-multi-phase/src/mock.rs | 14 +- .../src/unsigned.rs | 27 +- .../election-provider-support/src/bounds.rs | 4 +- .../pezframe/elections-phragmen/src/lib.rs | 17 +- .../unlock_and_unreserve_all_funds.rs | 4 +- .../authorization-tx-extension/src/mock.rs | 5 +- .../src/migrations/v1/tests.rs | 6 +- .../examples/offchain-worker/src/lib.rs | 15 +- bizinikiwi/pezframe/executive/src/lib.rs | 4 +- bizinikiwi/pezframe/executive/src/tests.rs | 24 +- bizinikiwi/pezframe/fast-unstake/src/lib.rs | 9 +- bizinikiwi/pezframe/fast-unstake/src/mock.rs | 4 +- .../pezframe/grandpa/src/equivocation.rs | 4 +- bizinikiwi/pezframe/identity/src/lib.rs | 10 +- bizinikiwi/pezframe/identity/src/migration.rs | 63 ++- bizinikiwi/pezframe/identity/src/tests.rs | 14 +- bizinikiwi/pezframe/identity/src/types.rs | 5 +- bizinikiwi/pezframe/im-online/src/lib.rs | 13 +- bizinikiwi/pezframe/im-online/src/tests.rs | 15 +- .../pezframe/merkle-mountain-range/src/lib.rs | 6 +- bizinikiwi/pezframe/message-queue/src/lib.rs | 25 +- .../pezframe/message-queue/src/tests.rs | 12 +- .../multi-asset-bounties/src/benchmarking.rs | 15 +- .../pezframe/multi-asset-bounties/src/lib.rs | 54 +- .../pezframe/nfts/src/features/attributes.rs | 19 +- .../pezframe/nfts/src/features/metadata.rs | 4 +- .../pezframe/nfts/src/impl_nonfungibles.rs | 8 +- bizinikiwi/pezframe/nfts/src/lib.rs | 5 +- bizinikiwi/pezframe/nfts/src/tests.rs | 6 +- bizinikiwi/pezframe/nis/src/lib.rs | 8 +- bizinikiwi/pezframe/nis/src/tests.rs | 6 +- .../benchmarking/src/inner.rs | 20 +- .../nomination-pools/fuzzer/src/call.rs | 4 +- .../pezframe/nomination-pools/src/lib.rs | 53 +- .../nomination-pools/src/migration.rs | 24 +- .../pezframe/nomination-pools/src/mock.rs | 4 +- .../test-delegate-stake/src/mock.rs | 8 +- .../pezframe/origin-restriction/src/lib.rs | 9 +- .../pezframe/origin-restriction/src/mock.rs | 10 +- .../pezframe/parameters/src/tests/mock.rs | 6 +- bizinikiwi/pezframe/people/src/extension.rs | 25 +- bizinikiwi/pezframe/people/src/lib.rs | 41 +- bizinikiwi/pezframe/people/src/tests.rs | 14 +- bizinikiwi/pezframe/preimage/src/lib.rs | 20 +- bizinikiwi/pezframe/preimage/src/migration.rs | 10 +- bizinikiwi/pezframe/proxy/src/lib.rs | 22 +- .../pezframe/ranked-collective/src/lib.rs | 5 +- .../pezframe/ranked-collective/src/tests.rs | 10 +- bizinikiwi/pezframe/referenda/src/branch.rs | 22 +- bizinikiwi/pezframe/referenda/src/lib.rs | 16 +- .../pezframe/referenda/src/migration.rs | 20 +- bizinikiwi/pezframe/referenda/src/types.rs | 25 +- .../revive/dev-node/node/src/command.rs | 5 +- .../pezframe/revive/rpc/examples/extrinsic.rs | 4 +- .../revive/rpc/examples/remark-extrinsic.rs | 2 +- bizinikiwi/pezframe/revive/rpc/src/client.rs | 17 +- .../revive/rpc/src/client/runtime_api.rs | 5 +- .../revive/rpc/src/client/storage_api.rs | 5 +- .../revive/rpc/src/receipt_provider.rs | 15 +- bizinikiwi/pezframe/revive/rpc/src/tests.rs | 15 +- bizinikiwi/pezframe/revive/src/address.rs | 4 +- .../pezframe/revive/src/benchmarking.rs | 27 +- .../pezframe/revive/src/call_builder.rs | 5 +- .../pezframe/revive/src/evm/api/rlp_codec.rs | 5 +- .../revive/src/evm/api/rpc_types_gen.rs | 17 +- .../pezframe/revive/src/evm/api/signature.rs | 45 +- .../src/evm/block_hash/block_builder.rs | 8 +- .../revive/src/evm/block_hash/hash_builder.rs | 34 +- .../revive/src/evm/block_hash/receipt.rs | 14 +- .../pezframe/revive/src/evm/block_storage.rs | 5 +- bizinikiwi/pezframe/revive/src/evm/runtime.rs | 26 +- .../revive/src/evm/tracing/call_tracing.rs | 5 +- .../src/evm/tracing/prestate_tracing.rs | 8 +- bizinikiwi/pezframe/revive/src/exec.rs | 30 +- bizinikiwi/pezframe/revive/src/lib.rs | 14 +- bizinikiwi/pezframe/revive/src/precompiles.rs | 5 +- .../revive/src/precompiles/builtin/storage.rs | 4 +- .../revive/src/precompiles/builtin/system.rs | 5 +- bizinikiwi/pezframe/revive/src/primitives.rs | 20 +- bizinikiwi/pezframe/revive/src/storage.rs | 14 +- .../pezframe/revive/src/storage/meter.rs | 24 +- bizinikiwi/pezframe/revive/src/tests.rs | 8 +- .../pezframe/revive/src/tests/precompiles.rs | 25 +- bizinikiwi/pezframe/revive/src/tests/pvm.rs | 4 +- bizinikiwi/pezframe/revive/src/vm/evm.rs | 8 +- .../vm/evm/instructions/arithmetic/i256.rs | 4 +- .../src/vm/evm/instructions/contract.rs | 9 +- bizinikiwi/pezframe/revive/src/vm/pvm.rs | 5 +- bizinikiwi/pezframe/revive/src/vm/pvm/env.rs | 10 +- .../pezframe/revive/src/vm/runtime_costs.rs | 15 +- .../pezframe/safe-mode/src/benchmarking.rs | 5 +- bizinikiwi/pezframe/safe-mode/src/tests.rs | 16 +- bizinikiwi/pezframe/scheduler/src/lib.rs | 16 +- bizinikiwi/pezframe/scheduler/src/tests.rs | 40 +- bizinikiwi/pezframe/scored-pool/src/lib.rs | 10 +- bizinikiwi/pezframe/session/src/mock.rs | 4 +- bizinikiwi/pezframe/society/src/lib.rs | 22 +- bizinikiwi/pezframe/society/src/migrations.rs | 4 +- bizinikiwi/pezframe/society/src/mock.rs | 5 +- .../staking-async/ah-client/src/lib.rs | 10 +- .../staking-async/ahm-test/src/ah/mock.rs | 4 +- .../staking-async/ahm-test/src/lib.rs | 12 +- .../staking-async/rc-client/src/lib.rs | 13 +- .../runtimes/rc/src/genesis_config_presets.rs | 6 +- .../staking-async/runtimes/rc/src/lib.rs | 30 +- .../runtimes/rc/src/weights/xcm/mod.rs | 10 +- .../runtimes/teyrchain/src/lib.rs | 150 ++--- .../runtimes/teyrchain/src/weights/xcm/mod.rs | 5 +- .../runtimes/teyrchain/src/xcm_config.rs | 6 +- .../staking-async/src/benchmarking.rs | 4 +- .../pezframe/staking-async/src/ledger.rs | 23 +- .../staking-async/src/pezpallet/impls.rs | 75 +-- .../staking-async/src/pezpallet/mod.rs | 18 +- .../staking-async/src/session_rotation.rs | 12 +- .../src/tests/election_data_provider.rs | 32 +- .../staking-async/src/tests/payout_stakers.rs | 12 +- .../staking-async/src/tests/slashing.rs | 6 +- .../pezframe/staking/reward-curve/src/lib.rs | 16 +- bizinikiwi/pezframe/staking/src/inflation.rs | 4 +- bizinikiwi/pezframe/staking/src/ledger.rs | 25 +- bizinikiwi/pezframe/staking/src/lib.rs | 4 +- bizinikiwi/pezframe/staking/src/migrations.rs | 4 +- .../pezframe/staking/src/pezpallet/impls.rs | 49 +- .../pezframe/staking/src/pezpallet/mod.rs | 18 +- bizinikiwi/pezframe/staking/src/tests.rs | 28 +- .../support/procedural/src/benchmark.rs | 19 +- .../procedural/src/construct_runtime/parse.rs | 52 +- .../support/procedural/src/derive_impl.rs | 9 +- .../pezframe/support/procedural/src/lib.rs | 18 +- .../procedural/src/no_bound/default.rs | 5 +- .../procedural/src/no_bound/partial_ord.rs | 24 +- .../src/pezpallet/expand/documentation.rs | 10 +- .../src/pezpallet/expand/genesis_config.rs | 6 +- .../src/pezpallet/expand/storage.rs | 12 +- .../src/pezpallet/expand/view_functions.rs | 5 +- .../procedural/src/pezpallet/parse/call.rs | 10 +- .../src/pezpallet/parse/composite.rs | 5 +- .../procedural/src/pezpallet/parse/config.rs | 26 +- .../procedural/src/pezpallet/parse/error.rs | 4 +- .../procedural/src/pezpallet/parse/mod.rs | 10 +- .../procedural/src/pezpallet/parse/storage.rs | 66 ++- .../procedural/src/pezpallet/parse/tasks.rs | 32 +- .../support/procedural/src/pezpallet_error.rs | 8 +- .../procedural/src/runtime/expand/mod.rs | 5 +- .../support/procedural/src/storage_alias.rs | 24 +- bizinikiwi/pezframe/support/src/migrations.rs | 5 +- .../pezframe/support/src/storage/child.rs | 30 +- .../support/src/storage/generator/mod.rs | 10 +- .../support/src/storage/stream_iter.rs | 10 +- .../support/src/storage/types/counted_nmap.rs | 6 +- .../pezframe/support/src/traits/reality.rs | 4 +- .../src/traits/tokens/fungible/union_of.rs | 85 +-- .../src/traits/tokens/fungibles/union_of.rs | 80 +-- .../tokens/imbalance/signed_imbalance.rs | 10 +- .../support/src/traits/try_runtime/mod.rs | 5 +- .../pezframe/support/test/tests/authorize.rs | 4 +- .../pezframe/support/test/tests/pallet.rs | 34 +- .../pezframe/support/test/tests/tasks.rs | 3 +- .../system/benchmarking/src/extensions.rs | 12 +- .../system/src/extensions/check_weight.rs | 16 +- bizinikiwi/pezframe/system/src/lib.rs | 10 +- bizinikiwi/pezframe/tips/src/benchmarking.rs | 6 +- bizinikiwi/pezframe/tips/src/lib.rs | 4 +- .../tips/src/migrations/unreserve_deposits.rs | 20 +- .../asset-conversion-tx-payment/src/lib.rs | 5 +- .../src/payment.rs | 42 +- .../asset-tx-payment/src/lib.rs | 5 +- .../asset-tx-payment/src/tests.rs | 13 +- .../pezframe/transaction-payment/src/lib.rs | 12 +- bizinikiwi/pezframe/uniques/src/lib.rs | 10 +- bizinikiwi/pezframe/utility/src/lib.rs | 4 +- bizinikiwi/pezframe/vesting/src/lib.rs | 4 +- bizinikiwi/pezframe/vesting/src/tests.rs | 8 +- .../pezframe/vesting/src/vesting_info.rs | 4 +- .../api/proc-macro/src/decl_runtime_apis.rs | 10 +- .../proc-macro/src/mock_impl_runtime_apis.rs | 15 +- .../primitives/api/proc-macro/src/utils.rs | 15 +- .../arithmetic/fuzzer/src/fixed_point.rs | 4 +- .../src/multiply_by_rational_with_rounding.rs | 10 +- .../fuzzer/src/per_thing_from_rational.rs | 10 +- .../primitives/arithmetic/src/biguint.rs | 6 +- .../primitives/arithmetic/src/per_things.rs | 10 +- .../primitives/consensus/babe/src/lib.rs | 4 +- .../consensus/beefy/src/commitment.rs | 6 +- .../primitives/consensus/beefy/src/lib.rs | 8 +- .../primitives/consensus/grandpa/src/lib.rs | 4 +- .../primitives/core/src/bandersnatch.rs | 6 +- bizinikiwi/primitives/core/src/bls.rs | 4 +- bizinikiwi/primitives/core/src/crypto.rs | 10 +- .../primitives/core/src/offchain/storage.rs | 10 +- .../primitives/core/src/offchain/testing.rs | 15 +- bizinikiwi/primitives/core/src/sr25519.rs | 45 +- .../crypto/hashing/proc-macro/src/impls.rs | 10 +- .../primitives/debug-derive/src/impls.rs | 5 +- bizinikiwi/primitives/inherents/src/lib.rs | 6 +- bizinikiwi/primitives/metadata-ir/src/v16.rs | 20 +- .../npos-elections/fuzzer/src/common.rs | 10 +- .../fuzzer/src/phragmen_balancing.rs | 6 +- .../fuzzer/src/phragmms_balancing.rs | 6 +- .../primitives/npos-elections/src/pjr.rs | 4 +- .../host_function_interface.rs | 5 +- .../runtime-interface/proc-macro/src/utils.rs | 9 +- .../runtime/src/generic/checked_extrinsic.rs | 5 +- .../primitives/runtime/src/generic/digest.rs | 30 +- .../primitives/runtime/src/generic/era.rs | 4 +- .../src/generic/unchecked_extrinsic.rs | 10 +- bizinikiwi/primitives/runtime/src/lib.rs | 18 +- .../runtime/src/offchain/storage_lock.rs | 8 +- .../runtime/src/proving_trie/mod.rs | 5 +- .../dispatch_transaction.rs | 5 +- .../runtime/src/transaction_validity.rs | 35 +- .../primitives/state-machine/src/basic.rs | 13 +- .../primitives/state-machine/src/lib.rs | 18 +- .../src/overlayed_changes/changeset.rs | 8 +- .../state-machine/src/trie_backend.rs | 4 +- .../state-machine/src/trie_backend_essence.rs | 14 +- .../primitives/statement-store/src/lib.rs | 17 +- bizinikiwi/primitives/storage/src/lib.rs | 5 +- .../trie/src/accessed_nodes_tracker.rs | 6 +- bizinikiwi/primitives/trie/src/cache/mod.rs | 5 +- .../primitives/trie/src/cache/shared_cache.rs | 4 +- bizinikiwi/primitives/trie/src/node_codec.rs | 25 +- bizinikiwi/primitives/trie/src/node_header.rs | 20 +- bizinikiwi/primitives/trie/src/trie_stream.rs | 20 +- .../proc-macro/src/decl_runtime_version.rs | 23 +- bizinikiwi/primitives/version/src/lib.rs | 59 +- bizinikiwi/test-utils/cli/src/lib.rs | 8 +- .../runtime/src/bizinikiwi_test_pallet.rs | 18 +- bizinikiwi/test-utils/runtime/src/lib.rs | 5 +- .../runtime/transaction-pool/src/lib.rs | 15 +- bizinikiwi/utils/pez-fork-tree/src/lib.rs | 41 +- .../benchmarking-cli/src/extrinsic/cmd.rs | 5 +- .../benchmarking-cli/src/machine/mod.rs | 5 +- .../benchmarking-cli/src/overhead/command.rs | 23 +- .../src/overhead/remark_builder.rs | 10 +- .../benchmarking-cli/src/pezpallet/command.rs | 41 +- .../benchmarking-cli/src/pezpallet/writer.rs | 9 +- .../src/shared/genesis_state.rs | 5 +- .../benchmarking-cli/src/storage/read.rs | 8 +- .../benchmarking-cli/src/storage/write.rs | 4 +- .../pezframe/remote-externalities/src/lib.rs | 4 +- .../rpc/state-trie-migration-rpc/src/lib.rs | 4 +- .../storage-access-test-runtime/src/lib.rs | 5 +- bizinikiwi/utils/txtesttool/bin/main.rs | 15 +- .../utils/txtesttool/src/execution_log.rs | 47 +- .../utils/txtesttool/src/fake_transaction.rs | 25 +- bizinikiwi/utils/txtesttool/src/lib.rs | 4 +- bizinikiwi/utils/txtesttool/src/runner.rs | 2 +- bizinikiwi/utils/txtesttool/src/scenario.rs | 8 +- .../txtesttool/src/subxt_api_connector.rs | 2 +- .../utils/txtesttool/src/subxt_transaction.rs | 31 +- .../utils/txtesttool/src/transaction.rs | 8 +- bizinikiwi/utils/wasm-builder/src/lib.rs | 14 +- .../utils/wasm-builder/src/prerequisites.rs | 4 +- .../utils/wasm-builder/src/wasm_project.rs | 17 +- .../reference_docs/frame_storage_derives.rs | 18 +- .../bin/runtime-common/src/extensions.rs | 4 +- pezbridges/bin/runtime-common/src/mock.rs | 4 +- pezbridges/modules/beefy/src/utils.rs | 6 +- pezbridges/modules/grandpa/src/call_ext.rs | 5 +- .../modules/messages/src/benchmarking.rs | 4 +- pezbridges/modules/messages/src/call_ext.rs | 8 +- pezbridges/modules/messages/src/lib.rs | 14 +- .../messages/src/tests/messages_generation.rs | 5 +- .../modules/messages/src/weights_ext.rs | 4 +- .../relayers/src/extension/grandpa_adapter.rs | 9 +- .../modules/relayers/src/extension/mod.rs | 9 +- .../relayers/src/extension/priority.rs | 6 +- .../src/extension/teyrchain_adapter.rs | 14 +- pezbridges/modules/relayers/src/mock.rs | 4 +- pezbridges/modules/teyrchains/src/call_ext.rs | 9 +- pezbridges/modules/teyrchains/src/lib.rs | 14 +- .../modules/teyrchains/src/weights_ext.rs | 6 +- .../modules/xcm-bridge-hub-router/src/lib.rs | 16 +- pezbridges/modules/xcm-bridge-hub/src/lib.rs | 5 +- pezbridges/modules/xcm-bridge-hub/src/mock.rs | 4 +- .../src/justification/verification/mod.rs | 4 +- pezbridges/primitives/header-chain/src/lib.rs | 4 +- pezbridges/primitives/messages/src/lib.rs | 5 +- .../primitives/relayers/src/extension.rs | 4 +- .../primitives/relayers/src/registration.rs | 5 +- pezbridges/primitives/runtime/src/chain.rs | 10 +- pezbridges/primitives/runtime/src/lib.rs | 12 +- .../client-bizinikiwi/src/client/rpc.rs | 5 +- .../src/metrics/float_storage_value.rs | 4 +- .../src/transaction_tracker.rs | 16 +- .../relays/equivocation/src/block_checker.rs | 24 +- .../relays/finality/src/finality_loop.rs | 8 +- pezbridges/relays/finality/src/headers.rs | 18 +- .../lib-bizinikiwi-relay/src/messages/mod.rs | 10 +- .../src/teyrchains/target.rs | 5 +- .../relays/messages/src/message_lane_loop.rs | 24 +- .../messages/src/message_race_delivery.rs | 12 +- .../messages/src/message_race_limits.rs | 8 +- .../messages/src/message_race_strategy.rs | 5 +- .../relays/teyrchains/src/teyrchains_loop.rs | 13 +- .../pezpallets/ethereum-client/src/impls.rs | 6 +- .../pezpallets/ethereum-client/src/lib.rs | 22 +- .../pezpallets/inbound-queue/src/lib.rs | 10 +- .../pezpallets/inbound-queue/src/mock.rs | 4 +- .../pezpallets/outbound-queue/src/lib.rs | 4 +- .../pezpallets/system-frontend/src/mock.rs | 5 +- .../primitives/beacon/src/receipt.rs | 5 +- .../snowbridge/primitives/beacon/src/types.rs | 40 +- .../primitives/core/src/location.rs | 20 +- .../primitives/inbound-queue/src/lib.rs | 10 +- .../primitives/inbound-queue/src/v1.rs | 20 +- .../outbound-queue/src/v1/converter/mod.rs | 10 +- .../outbound-queue/src/v1/message.rs | 30 +- .../src/v2/converter/convert.rs | 5 +- .../outbound-queue/src/v2/message.rs | 15 +- .../client/bootnodes/src/advertisement.rs | 5 +- pezcumulus/client/bootnodes/src/discovery.rs | 10 +- .../client/consensus/aura/src/collator.rs | 5 +- .../consensus/aura/src/collators/basic.rs | 9 +- .../consensus/aura/src/collators/mod.rs | 9 +- .../slot_based/block_builder_task.rs | 5 +- .../src/collators/slot_based/slot_timer.rs | 14 +- .../aura/src/equivocation_import_queue.rs | 9 +- .../consensus/common/src/parent_search.rs | 6 +- pezcumulus/client/network/src/lib.rs | 9 +- pezcumulus/client/network/src/tests.rs | 13 +- pezcumulus/client/pov-recovery/src/lib.rs | 5 +- pezcumulus/client/pov-recovery/src/tests.rs | 8 +- .../src/lib.rs | 5 +- .../relay-chain-minimal-node/src/lib.rs | 10 +- .../relay-chain-minimal-node/src/network.rs | 4 +- .../src/reconnecting_ws_client.rs | 4 +- .../client/relay-chain-streams/src/lib.rs | 4 +- pezcumulus/client/service/src/lib.rs | 5 +- .../pezkuwi-omni-node/lib/src/command.rs | 15 +- .../lib/src/common/runtime.rs | 2 +- .../pezkuwi-omni-node/lib/src/common/spec.rs | 10 +- .../src/chain_spec/bridge_hubs.rs | 15 +- .../src/chain_spec/coretime.rs | 50 +- .../pezkuwi-teyrchain/src/chain_spec/mod.rs | 89 +-- .../src/chain_spec/people.rs | 5 +- .../collator-selection/src/benchmarking.rs | 8 +- .../pezpallets/collator-selection/src/lib.rs | 12 +- .../teyrchain-system/proc-macro/src/lib.rs | 5 +- .../pezpallets/teyrchain-system/src/lib.rs | 5 +- .../pezpallets/teyrchain-system/src/mock.rs | 8 +- .../src/validate_block/trie_recorder.rs | 10 +- .../pezpallets/weight-reclaim/src/tests.rs | 34 +- pezcumulus/pezpallets/xcmp-queue/src/lib.rs | 20 +- .../pezpallets/xcmp-queue/src/migration.rs | 6 +- pezcumulus/pezpallets/xcmp-queue/src/mock.rs | 4 +- pezcumulus/primitives/core/src/lib.rs | 5 +- pezcumulus/primitives/timestamp/src/lib.rs | 4 +- .../utility/src/tests/swap_first.rs | 10 +- .../runtime/src/genesis_config_presets.rs | 7 +- pezcumulus/test/service/src/cli.rs | 5 +- pezcumulus/test/service/src/lib.rs | 15 +- pezcumulus/test/service/src/main.rs | 10 +- pezcumulus/teyrchains/common/src/impls.rs | 4 +- pezcumulus/teyrchains/common/src/pay.rs | 20 +- .../assets/asset-hub-pezkuwichain/src/lib.rs | 11 +- .../src/tests/reserve_transfer.rs | 4 +- .../src/tests/treasury.rs | 173 +++--- .../src/tests/xcm_fee_estimation.rs | 8 +- .../tests/assets/asset-hub-zagros/src/lib.rs | 13 +- .../src/tests/reserve_transfer.rs | 4 +- .../src/tests/xcm_fee_estimation.rs | 8 +- .../collectives/collectives-zagros/src/lib.rs | 11 +- .../coretime/coretime-pezkuwichain/src/lib.rs | 8 +- .../tests/coretime/coretime-zagros/src/lib.rs | 16 +- .../people/people-pezkuwichain/src/lib.rs | 5 +- .../tests/people/people-zagros/src/lib.rs | 16 +- .../bridge-hub-pezkuwichain/src/lib.rs | 6 +- .../pezbridges/bridge-hub-zagros/src/lib.rs | 20 +- .../pezpallets/identity-kyc/src/mock.rs | 5 +- .../pezpallets/pez-rewards/src/tests.rs | 6 +- .../pezpallets/pez-treasury/src/migrations.rs | 8 +- .../teyrchains/pezpallets/ping/src/lib.rs | 5 +- .../pezpallets/presale/src/benchmarking.rs | 25 +- .../teyrchains/pezpallets/presale/src/lib.rs | 172 ++++-- .../pezpallets/presale/src/tests.rs | 517 ++++++++++++++++-- .../teyrchains/pezpallets/referral/src/lib.rs | 4 +- .../pezpallets/referral/src/mock.rs | 5 +- .../pezpallets/referral/src/tests.rs | 3 +- .../pezpallets/staking-score/src/mock.rs | 16 +- .../pezpallets/tiki/src/benchmarking.rs | 4 +- .../teyrchains/pezpallets/tiki/src/lib.rs | 15 +- .../pezpallets/tiki/src/migrations.rs | 4 +- .../teyrchains/pezpallets/tiki/src/mock.rs | 11 +- .../teyrchains/pezpallets/tiki/src/tests.rs | 36 +- .../teyrchains/pezpallets/trust/src/lib.rs | 4 +- .../teyrchains/pezpallets/trust/src/tests.rs | 7 +- .../teyrchains/pezpallets/welati/src/lib.rs | 73 +-- .../pezpallets/welati/src/migrations.rs | 36 +- .../teyrchains/pezpallets/welati/src/mock.rs | 11 +- .../teyrchains/pezpallets/welati/src/types.rs | 42 +- .../src/genesis_config_presets.rs | 5 +- .../assets/asset-hub-pezkuwichain/src/lib.rs | 150 ++--- .../src/weights/xcm/mod.rs | 10 +- .../assets/asset-hub-zagros/src/lib.rs | 176 +++--- .../asset-hub-zagros/src/weights/xcm/mod.rs | 10 +- .../assets/asset-hub-zagros/src/xcm_config.rs | 6 +- .../runtimes/assets/common/src/migrations.rs | 5 +- .../runtimes/assets/test-utils/src/lib.rs | 5 +- .../assets/test-utils/src/test_cases.rs | 45 +- .../test-utils/src/test_cases_over_bridge.rs | 19 +- .../src/weights/xcm/mod.rs | 5 +- .../src/bridge_to_ethereum_config.rs | 5 +- .../bridge-hub-zagros/src/weights/xcm/mod.rs | 5 +- .../bridge-hubs/common/src/barriers.rs | 5 +- .../bridge-hubs/common/src/message_queue.rs | 10 +- .../test-utils/src/test_cases/helpers.rs | 12 +- .../collectives/collectives-zagros/src/lib.rs | 56 +- .../collectives-zagros/src/weights/xcm/mod.rs | 5 +- .../coretime/coretime-pezkuwichain/src/lib.rs | 30 +- .../src/weights/xcm/mod.rs | 5 +- .../coretime/coretime-zagros/src/lib.rs | 30 +- .../coretime-zagros/src/weights/xcm/mod.rs | 5 +- .../people/people-pezkuwichain/src/lib.rs | 24 +- .../src/weights/xcm/mod.rs | 5 +- .../runtimes/people/people-zagros/src/lib.rs | 24 +- .../people-zagros/src/weights/xcm/mod.rs | 5 +- .../teyrchains/runtimes/test-utils/src/lib.rs | 20 +- .../runtimes/testing/penpal/src/xcm_config.rs | 8 +- .../src/genesis_config_presets.rs | 5 +- .../testing/yet-another-teyrchain/src/lib.rs | 4 +- .../zombienet-sdk-helpers/src/lib.rs | 16 +- .../tests/zombie_ci/bootnodes.rs | 6 +- .../multiple_blocks_per_slot.rs | 4 +- .../zombie_ci/elastic_scaling/pov_recovery.rs | 2 +- .../elastic_scaling/slot_based_authoring.rs | 2 +- .../elastic_scaling/slot_based_rp_offset.rs | 4 +- .../elastic_scaling/upgrade_to_3_cores.rs | 2 +- .../tests/zombie_ci/full_node_catching_up.rs | 2 +- .../tests/zombie_ci/full_node_warp_sync.rs | 10 +- .../tests/zombie_ci/migrate_solo.rs | 2 +- .../zombie_ci/rpc_collator_build_blocks.rs | 2 +- .../tests/zombie_ci/statement_store.rs | 4 +- .../tests/zombie_ci/statement_store_bench.rs | 4 +- .../tests/zombie_ci/sync_blocks.rs | 2 +- .../teyrchain_extrinsic_get_finalized.rs | 2 +- pezkuwi/node/collation-generation/src/lib.rs | 5 +- .../core/approval-voting-parallel/src/lib.rs | 35 +- .../approval-voting/src/approval_checking.rs | 9 +- .../src/approval_db/v2/tests.rs | 5 +- .../src/approval_db/v3/tests.rs | 5 +- .../node/core/approval-voting/src/backend.rs | 8 +- .../node/core/approval-voting/src/criteria.rs | 24 +- .../node/core/approval-voting/src/import.rs | 20 +- pezkuwi/node/core/approval-voting/src/lib.rs | 68 ++- .../approval-voting/src/persisted_entries.rs | 4 +- .../node/core/approval-voting/src/tests.rs | 4 +- pezkuwi/node/core/av-store/src/tests.rs | 4 +- pezkuwi/node/core/backing/src/lib.rs | 15 +- pezkuwi/node/core/backing/src/tests/mod.rs | 5 +- .../node/core/candidate-validation/src/lib.rs | 82 +-- .../core/chain-selection/src/db_backend/v1.rs | 5 +- pezkuwi/node/core/chain-selection/src/tree.rs | 5 +- .../core/dispute-coordinator/src/backend.rs | 6 +- .../core/dispute-coordinator/src/import.rs | 9 +- .../dispute-coordinator/src/initialized.rs | 33 +- .../src/participation/queues/mod.rs | 8 +- .../src/participation/tests.rs | 4 +- .../dispute-coordinator/src/scraping/mod.rs | 6 +- .../dispute-coordinator/src/scraping/tests.rs | 12 +- .../core/dispute-coordinator/src/tests.rs | 5 +- .../src/fragment_chain/mod.rs | 4 +- .../core/prospective-teyrchains/src/lib.rs | 25 +- .../core/prospective-teyrchains/src/tests.rs | 12 +- .../src/disputes/prioritized_selection/mod.rs | 33 +- .../disputes/prioritized_selection/tests.rs | 8 +- pezkuwi/node/core/provisioner/src/lib.rs | 5 +- pezkuwi/node/core/provisioner/src/tests.rs | 5 +- pezkuwi/node/core/pvf-checker/src/lib.rs | 5 +- pezkuwi/node/core/pvf/common/src/error.rs | 22 +- .../core/pvf/common/src/executor_interface.rs | 11 +- pezkuwi/node/core/pvf/common/src/pvf.rs | 4 +- .../node/core/pvf/common/src/worker/mod.rs | 4 +- .../common/src/worker/security/change_root.rs | 11 +- .../pvf/common/src/worker/security/clone.rs | 16 +- .../node/core/pvf/execute-worker/src/lib.rs | 15 +- pezkuwi/node/core/pvf/src/artifacts.rs | 4 +- pezkuwi/node/core/pvf/src/execute/queue.rs | 14 +- pezkuwi/node/core/pvf/src/host.rs | 24 +- pezkuwi/node/core/pvf/src/prepare/pool.rs | 5 +- pezkuwi/node/core/pvf/src/prepare/queue.rs | 5 +- .../core/pvf/src/prepare/worker_interface.rs | 5 +- pezkuwi/node/core/pvf/src/security.rs | 9 +- pezkuwi/node/core/runtime-api/src/lib.rs | 215 +++++--- pezkuwi/node/malus/src/variants/common.rs | 28 +- .../variants/dispute_finalized_candidates.rs | 5 +- pezkuwi/node/metrics/src/runtime/mod.rs | 15 +- .../network/approval-distribution/src/lib.rs | 38 +- .../availability-distribution/src/error.rs | 22 +- .../availability-distribution/src/lib.rs | 5 +- .../src/requester/fetch_task/mod.rs | 10 +- .../src/requester/fetch_task/tests.rs | 8 +- .../src/tests/mod.rs | 12 +- .../network/availability-recovery/src/lib.rs | 27 +- .../availability-recovery/src/task/mod.rs | 10 +- .../src/task/strategy/chunks.rs | 8 +- .../src/task/strategy/full.rs | 10 +- .../src/task/strategy/mod.rs | 25 +- .../src/task/strategy/systematic.rs | 12 +- .../availability-recovery/src/tests.rs | 4 +- .../network/bitfield-distribution/src/lib.rs | 24 +- pezkuwi/node/network/bridge/src/rx/mod.rs | 15 +- pezkuwi/node/network/bridge/src/rx/tests.rs | 19 +- pezkuwi/node/network/bridge/src/tx/mod.rs | 5 +- .../src/collator_side/mod.rs | 14 +- .../src/collator_side/tests/mod.rs | 5 +- .../node/network/collator-protocol/src/lib.rs | 10 +- .../src/validator_side/error.rs | 14 +- .../src/validator_side/mod.rs | 57 +- .../src/validator_side/tests/mod.rs | 15 +- .../peer_manager/connected.rs | 50 +- .../network/dispute-distribution/src/lib.rs | 10 +- .../src/receiver/batches/batch.rs | 4 +- .../src/sender/send_task.rs | 5 +- .../node/network/gossip-support/src/lib.rs | 9 +- .../network/protocol/src/grid_topology.rs | 8 +- pezkuwi/node/network/protocol/src/lib.rs | 5 +- pezkuwi/node/network/protocol/src/peer_set.rs | 35 +- .../node/network/protocol/src/reputation.rs | 8 +- .../protocol/src/request_response/mod.rs | 4 +- .../protocol/src/request_response/outgoing.rs | 6 +- .../src/v2/candidates.rs | 22 +- .../statement-distribution/src/v2/cluster.rs | 12 +- .../statement-distribution/src/v2/grid.rs | 18 +- .../statement-distribution/src/v2/mod.rs | 44 +- .../statement-distribution/src/v2/requests.rs | 17 +- .../src/v2/tests/mod.rs | 4 +- pezkuwi/node/overseer/src/lib.rs | 5 +- pezkuwi/node/overseer/src/tests.rs | 12 +- pezkuwi/node/primitives/src/approval/mod.rs | 20 +- pezkuwi/node/primitives/src/disputes/mod.rs | 10 +- .../node/primitives/src/disputes/status.rs | 27 +- pezkuwi/node/service/src/builder/mod.rs | 14 +- pezkuwi/node/service/src/lib.rs | 10 +- pezkuwi/node/service/src/overseer.rs | 10 +- .../node/service/src/relay_chain_selection.rs | 19 +- .../node/service/src/teyrchains_db/upgrade.rs | 5 +- .../src/lib/approval/helpers.rs | 4 +- .../src/lib/approval/message_generator.rs | 30 +- .../src/lib/approval/mock_chain_selection.rs | 9 +- .../subsystem-bench/src/lib/approval/mod.rs | 34 +- .../src/lib/approval/test_message.rs | 20 +- .../src/lib/availability/mod.rs | 9 +- .../subsystem-bench/src/lib/disputes/mod.rs | 4 +- .../src/lib/mock/approval_voting_parallel.rs | 5 +- .../subsystem-bench/src/lib/mock/av_store.rs | 5 +- .../src/lib/mock/availability_recovery.rs | 5 +- .../src/lib/mock/candidate_backing.rs | 9 +- .../src/lib/mock/candidate_validation.rs | 5 +- .../subsystem-bench/src/lib/mock/chain_api.rs | 5 +- .../src/lib/mock/network_bridge.rs | 5 +- .../src/lib/mock/prospective_teyrchains.rs | 5 +- .../src/lib/mock/runtime_api.rs | 10 +- .../node/subsystem-bench/src/lib/network.rs | 58 +- .../src/lib/statement/test_state.rs | 10 +- .../node/subsystem-test-helpers/src/lib.rs | 5 +- pezkuwi/node/subsystem-types/src/lib.rs | 6 +- pezkuwi/node/subsystem-types/src/messages.rs | 105 ++-- .../src/messages/network_bridge_event.rs | 30 +- .../src/backing_implicit_view.rs | 30 +- pezkuwi/node/subsystem-util/src/database.rs | 5 +- .../src/inclusion_emulator/mod.rs | 5 +- pezkuwi/node/test/service/src/lib.rs | 10 +- pezkuwi/node/zombienet-backchannel/src/lib.rs | 5 +- .../pezpallets/validator-pool/src/tests.rs | 4 +- .../pezpallets/validator-pool/src/types.rs | 6 +- pezkuwi/primitives/src/v9/executor_params.rs | 5 +- pezkuwi/primitives/src/v9/mod.rs | 63 ++- .../runtime/common/src/assigned_slots/mod.rs | 12 +- pezkuwi/runtime/common/src/auctions/mod.rs | 14 +- pezkuwi/runtime/common/src/claims/mod.rs | 10 +- pezkuwi/runtime/common/src/impls.rs | 10 +- .../runtime/common/src/integration_tests.rs | 4 +- pezkuwi/runtime/common/src/mock.rs | 5 +- .../runtime/common/src/paras_registrar/mod.rs | 12 +- .../runtime/common/src/paras_sudo_wrapper.rs | 5 +- pezkuwi/runtime/common/src/slots/mod.rs | 10 +- pezkuwi/runtime/common/src/try_runtime.rs | 5 +- .../src/genesis_config_presets.rs | 17 +- pezkuwi/runtime/pezkuwichain/src/lib.rs | 10 +- .../pezkuwichain/src/weights/xcm/mod.rs | 10 +- .../teyrchains/src/assigner_coretime/mod.rs | 20 +- pezkuwi/runtime/teyrchains/src/builder.rs | 12 +- pezkuwi/runtime/teyrchains/src/disputes.rs | 60 +- .../teyrchains/src/disputes/slashing.rs | 5 +- .../runtime/teyrchains/src/disputes/tests.rs | 12 +- pezkuwi/runtime/teyrchains/src/dmp/tests.rs | 4 +- pezkuwi/runtime/teyrchains/src/hrmp.rs | 33 +- pezkuwi/runtime/teyrchains/src/hrmp/tests.rs | 48 +- .../runtime/teyrchains/src/inclusion/mod.rs | 8 +- .../runtime/teyrchains/src/inclusion/tests.rs | 8 +- pezkuwi/runtime/teyrchains/src/initializer.rs | 20 +- .../runtime/teyrchains/src/on_demand/mod.rs | 14 +- pezkuwi/runtime/teyrchains/src/paras/mod.rs | 53 +- pezkuwi/runtime/teyrchains/src/paras/tests.rs | 4 +- .../teyrchains/src/paras_inherent/mod.rs | 8 +- .../teyrchains/src/paras_inherent/tests.rs | 6 +- .../teyrchains/src/runtime_api_impl/v13.rs | 28 +- .../teyrchains/src/scheduler/migration.rs | 13 +- pezkuwi/runtime/teyrchains/src/ump_tests.rs | 4 +- .../zagros/src/genesis_config_presets.rs | 6 +- pezkuwi/runtime/zagros/src/lib.rs | 42 +- pezkuwi/runtime/zagros/src/weights/xcm/mod.rs | 10 +- pezkuwi/statement-table/src/generic.rs | 37 +- pezkuwi/tests/benchmark_block.rs | 1 - .../test-teyrchains/adder/collator/src/cli.rs | 10 +- .../undying/collator/src/cli.rs | 10 +- .../xcm/pezpallet-xcm-benchmarks/src/mock.rs | 5 +- .../xcm/pezpallet-xcm/precompiles/src/lib.rs | 5 +- pezkuwi/xcm/pezpallet-xcm/src/benchmarking.rs | 5 +- pezkuwi/xcm/pezpallet-xcm/src/lib.rs | 65 ++- pezkuwi/xcm/pezpallet-xcm/src/migration.rs | 32 +- .../src/transfer_assets_validation.rs | 18 +- pezkuwi/xcm/procedural/src/builder_pattern.rs | 5 +- pezkuwi/xcm/src/v3/junction.rs | 26 +- pezkuwi/xcm/src/v3/mod.rs | 195 ++++--- pezkuwi/xcm/src/v3/multiasset.rs | 29 +- pezkuwi/xcm/src/v3/traits.rs | 5 +- pezkuwi/xcm/src/v4/asset.rs | 34 +- pezkuwi/xcm/src/v4/junction.rs | 41 +- pezkuwi/xcm/src/v4/mod.rs | 243 ++++---- pezkuwi/xcm/src/v5/asset.rs | 29 +- pezkuwi/xcm/src/v5/junction.rs | 26 +- pezkuwi/xcm/src/v5/mod.rs | 175 +++--- pezkuwi/xcm/src/v5/traits.rs | 5 +- .../xcm/xcm-builder/src/asset_conversion.rs | 9 +- .../single_asset_adapter/mock.rs | 14 +- pezkuwi/xcm/xcm-builder/src/barriers.rs | 54 +- .../xcm/xcm-builder/src/currency_adapter.rs | 40 +- .../xcm/xcm-builder/src/fungible_adapter.rs | 40 +- .../xcm-builder/src/location_conversion.rs | 55 +- .../xcm/xcm-builder/src/matches_location.rs | 3 +- .../xcm-builder/src/nonfungible_adapter.rs | 20 +- pezkuwi/xcm/xcm-builder/src/origin_aliases.rs | 10 +- .../xcm/xcm-builder/src/origin_conversion.rs | 36 +- pezkuwi/xcm/xcm-builder/src/tests/barriers.rs | 5 +- pezkuwi/xcm/xcm-builder/src/tests/mock.rs | 39 +- pezkuwi/xcm/xcm-builder/src/tests/pay/mock.rs | 15 +- .../xcm/xcm-builder/src/universal_exports.rs | 5 +- pezkuwi/xcm/xcm-builder/src/weight.rs | 32 +- pezkuwi/xcm/xcm-executor/src/assets.rs | 48 +- pezkuwi/xcm/xcm-executor/src/lib.rs | 9 +- .../xcm/xcm-executor/src/traits/asset_lock.rs | 5 +- .../xcm-executor/src/traits/asset_transfer.rs | 4 +- .../xcm-executor/src/traits/token_matching.rs | 5 +- .../xcm/xcm-pez-simulator/fuzzer/src/fuzz.rs | 14 +- .../xcm-pez-simulator/fuzzer/src/teyrchain.rs | 5 +- .../src/mock_message_queue.rs | 15 +- pezkuwi/xcm/xcm-runtime-pezapis/tests/mock.rs | 9 +- .../tests/elastic_scaling/basic_3cores.rs | 4 +- .../doesnt_break_teyrchains.rs | 4 +- .../elastic_scaling/slot_based_12cores.rs | 5 +- .../elastic_scaling/slot_based_3cores.rs | 5 +- .../functional/approval_voting_coalescing.rs | 3 +- .../approved_peer_mixed_validators.rs | 5 +- .../async_backing_6_seconds_rate.rs | 5 +- .../tests/functional/duplicate_collations.rs | 5 +- .../functional/shared_core_idle_teyrchain.rs | 4 +- .../tests/functional/sync_backing.rs | 4 +- .../tests/smoke/coretime_revenue.rs | 28 +- .../tests/teyrchains/weights.rs | 31 +- templates/minimal/node/src/command.rs | 5 +- templates/solochain/node/src/command.rs | 10 +- templates/teyrchain/node/src/command.rs | 5 +- vendor/ss58-registry/build.rs | 10 +- vendor/ss58-registry/rustfmt.toml | 16 +- 898 files changed, 8671 insertions(+), 6432 deletions(-) diff --git a/.rustfmt.toml b/.rustfmt.toml index c3421539..5f34cd81 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1,24 +1,31 @@ +# Pezkuwi SDK - Stable Rustfmt Configuration +# Only stable features are used for long-term reliability + # Basic edition = "2021" hard_tabs = true max_width = 100 use_small_heuristics = "Max" + # Imports -imports_granularity = "Crate" reorder_imports = true + # Consistency newline_style = "Unix" + # Misc chain_width = 80 -spaces_around_ranges = false -binop_separator = "Back" -reorder_impl_items = false match_arm_leading_pipes = "Preserve" -match_arm_blocks = false match_block_trailing_comma = true -trailing_comma = "Vertical" -trailing_semicolon = false use_field_init_shorthand = true -# Format comments -comment_width = 100 -wrap_comments = true + +# NOTE: The following nightly-only features were removed for stable compatibility: +# - imports_granularity = "Crate" +# - wrap_comments = true +# - comment_width = 100 +# - reorder_impl_items = false +# - spaces_around_ranges = false +# - binop_separator = "Back" +# - match_arm_blocks = false +# - trailing_semicolon = false +# - trailing_comma = "Vertical" diff --git a/bizinikiwi/bin/node/bench/src/tempdb.rs b/bizinikiwi/bin/node/bench/src/tempdb.rs index d8d92278..af164c16 100644 --- a/bizinikiwi/bin/node/bench/src/tempdb.rs +++ b/bizinikiwi/bin/node/bench/src/tempdb.rs @@ -45,8 +45,9 @@ impl KeyValueDB for ParityDbWrapper { fn write(&self, transaction: DBTransaction) -> io::Result<()> { self.0 .commit(transaction.ops.iter().map(|op| match op { - kvdb::DBOp::Insert { col, key, value } => - (*col as u8, &key[key.len() - 32..], Some(value.to_vec())), + kvdb::DBOp::Insert { col, key, value } => { + (*col as u8, &key[key.len() - 32..], Some(value.to_vec())) + }, kvdb::DBOp::Delete { col, key } => (*col as u8, &key[key.len() - 32..], None), kvdb::DBOp::DeletePrefix { col: _, prefix: _ } => unimplemented!(), })) diff --git a/bizinikiwi/bin/node/cli/src/command.rs b/bizinikiwi/bin/node/cli/src/command.rs index cfe796df..00fba0d1 100644 --- a/bizinikiwi/bin/node/cli/src/command.rs +++ b/bizinikiwi/bin/node/cli/src/command.rs @@ -64,17 +64,19 @@ impl BizinikiwiCli for Cli { id: &str, ) -> std::result::Result, String> { let spec = match id { - "" => + "" => { return Err( "Please specify which chain you want to run, e.g. --dev or --chain=local" .into(), - ), + ) + }, "dev" => Box::new(chain_spec::development_config()), "local" => Box::new(chain_spec::local_testnet_config()), "fir" | "flaming-fir" => Box::new(chain_spec::flaming_fir_config()?), "staging" => Box::new(chain_spec::pezstaging_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))?) + }, }; Ok(spec) } diff --git a/bizinikiwi/bin/node/cli/tests/benchmark_pallet_works.rs b/bizinikiwi/bin/node/cli/tests/benchmark_pallet_works.rs index 28ad72a8..37d42537 100644 --- a/bizinikiwi/bin/node/cli/tests/benchmark_pallet_works.rs +++ b/bizinikiwi/bin/node/cli/tests/benchmark_pallet_works.rs @@ -16,7 +16,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . - #![cfg(feature = "runtime-benchmarks")] use assert_cmd::cargo::cargo_bin; diff --git a/bizinikiwi/bin/node/cli/tests/benchmark_pezpallet_works.rs b/bizinikiwi/bin/node/cli/tests/benchmark_pezpallet_works.rs index 650d7f95..e2fdc177 100644 --- a/bizinikiwi/bin/node/cli/tests/benchmark_pezpallet_works.rs +++ b/bizinikiwi/bin/node/cli/tests/benchmark_pezpallet_works.rs @@ -16,7 +16,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . - #![cfg(feature = "runtime-benchmarks")] use assert_cmd::cargo::cargo_bin; diff --git a/bizinikiwi/bin/node/cli/tests/benchmark_storage_works.rs b/bizinikiwi/bin/node/cli/tests/benchmark_storage_works.rs index 553c042c..f404ac26 100644 --- a/bizinikiwi/bin/node/cli/tests/benchmark_storage_works.rs +++ b/bizinikiwi/bin/node/cli/tests/benchmark_storage_works.rs @@ -16,7 +16,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . - #![cfg(feature = "runtime-benchmarks")] use assert_cmd::cargo::cargo_bin; diff --git a/bizinikiwi/bin/node/cli/tests/check_block_works.rs b/bizinikiwi/bin/node/cli/tests/check_block_works.rs index 45c4b3ab..1297e9fd 100644 --- a/bizinikiwi/bin/node/cli/tests/check_block_works.rs +++ b/bizinikiwi/bin/node/cli/tests/check_block_works.rs @@ -16,7 +16,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . - #![cfg(unix)] use assert_cmd::cargo::cargo_bin; diff --git a/bizinikiwi/bin/node/cli/tests/export_import_flow.rs b/bizinikiwi/bin/node/cli/tests/export_import_flow.rs index 33deacea..e4da680c 100644 --- a/bizinikiwi/bin/node/cli/tests/export_import_flow.rs +++ b/bizinikiwi/bin/node/cli/tests/export_import_flow.rs @@ -16,7 +16,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . - #![cfg(unix)] use assert_cmd::cargo::cargo_bin; diff --git a/bizinikiwi/bin/node/cli/tests/inspect_works.rs b/bizinikiwi/bin/node/cli/tests/inspect_works.rs index 64b0e13c..3faa9acd 100644 --- a/bizinikiwi/bin/node/cli/tests/inspect_works.rs +++ b/bizinikiwi/bin/node/cli/tests/inspect_works.rs @@ -16,7 +16,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . - #![cfg(unix)] use assert_cmd::cargo::cargo_bin; diff --git a/bizinikiwi/bin/node/cli/tests/running_the_node_and_interrupt.rs b/bizinikiwi/bin/node/cli/tests/running_the_node_and_interrupt.rs index 9879ebf3..9db07792 100644 --- a/bizinikiwi/bin/node/cli/tests/running_the_node_and_interrupt.rs +++ b/bizinikiwi/bin/node/cli/tests/running_the_node_and_interrupt.rs @@ -16,7 +16,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . - #![cfg(unix)] use assert_cmd::cargo::cargo_bin; use nix::sys::signal::Signal::{self, SIGINT, SIGTERM}; diff --git a/bizinikiwi/bin/node/cli/tests/temp_base_path_works.rs b/bizinikiwi/bin/node/cli/tests/temp_base_path_works.rs index 24e574b4..985f16d9 100644 --- a/bizinikiwi/bin/node/cli/tests/temp_base_path_works.rs +++ b/bizinikiwi/bin/node/cli/tests/temp_base_path_works.rs @@ -16,7 +16,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . - #![cfg(unix)] use assert_cmd::cargo::cargo_bin; diff --git a/bizinikiwi/bin/node/runtime/src/impls.rs b/bizinikiwi/bin/node/runtime/src/impls.rs index 04bf7a64..70759b28 100644 --- a/bizinikiwi/bin/node/runtime/src/impls.rs +++ b/bizinikiwi/bin/node/runtime/src/impls.rs @@ -308,8 +308,8 @@ mod multiplier_tests { // `cargo test congested_chain_simulation -- --nocapture` to get some insight. // almost full. The entire quota of normal transactions is taken. - let block_weight = BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap() - - Weight::from_parts(100, 0); + let block_weight = BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap() + - Weight::from_parts(100, 0); // Default bizinikiwi weight. let tx_weight = pezframe_support::weights::constants::ExtrinsicBaseWeight::get(); diff --git a/bizinikiwi/bin/node/runtime/src/lib.rs b/bizinikiwi/bin/node/runtime/src/lib.rs index a804225c..5436973f 100644 --- a/bizinikiwi/bin/node/runtime/src/lib.rs +++ b/bizinikiwi/bin/node/runtime/src/lib.rs @@ -442,21 +442,21 @@ impl InstanceFilter for ProxyType { ProxyType::Any => true, ProxyType::NonTransfer => !matches!( c, - RuntimeCall::Balances(..) | - RuntimeCall::Assets(..) | - RuntimeCall::Uniques(..) | - RuntimeCall::Nfts(..) | - RuntimeCall::Vesting(pezpallet_vesting::Call::vested_transfer { .. }) | - RuntimeCall::Indices(pezpallet_indices::Call::transfer { .. }) + RuntimeCall::Balances(..) + | RuntimeCall::Assets(..) + | RuntimeCall::Uniques(..) + | RuntimeCall::Nfts(..) + | RuntimeCall::Vesting(pezpallet_vesting::Call::vested_transfer { .. }) + | RuntimeCall::Indices(pezpallet_indices::Call::transfer { .. }) ), ProxyType::Governance => matches!( c, - RuntimeCall::Democracy(..) | - RuntimeCall::Council(..) | - RuntimeCall::Society(..) | - RuntimeCall::TechnicalCommittee(..) | - RuntimeCall::Elections(..) | - RuntimeCall::Treasury(..) + RuntimeCall::Democracy(..) + | RuntimeCall::Council(..) + | RuntimeCall::Society(..) + | RuntimeCall::TechnicalCommittee(..) + | RuntimeCall::Elections(..) + | RuntimeCall::Treasury(..) ), ProxyType::Staking => { matches!(c, RuntimeCall::Staking(..) | RuntimeCall::FastUnstake(..)) @@ -856,8 +856,8 @@ impl Get> for OffchainRandomBalancing { max => { let seed = pezsp_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 }, }; diff --git a/bizinikiwi/bin/node/testing/src/bench.rs b/bizinikiwi/bin/node/testing/src/bench.rs index 5446bf9b..1c0176cf 100644 --- a/bizinikiwi/bin/node/testing/src/bench.rs +++ b/bizinikiwi/bin/node/testing/src/bench.rs @@ -306,22 +306,24 @@ impl<'a> Iterator for BlockContentIterator<'a> { tx_ext(0, pez_kitchensink_runtime::ExistentialDeposit::get() + 1), ), function: match self.content.block_type { - BlockType::RandomTransfersKeepAlive => + BlockType::RandomTransfersKeepAlive => { RuntimeCall::Balances(BalancesCall::transfer_keep_alive { dest: pezsp_runtime::MultiAddress::Id(receiver), value: pez_kitchensink_runtime::ExistentialDeposit::get() + 1, - }), + }) + }, BlockType::RandomTransfersReaping => { RuntimeCall::Balances(BalancesCall::transfer_allow_death { dest: pezsp_runtime::MultiAddress::Id(receiver), // Transfer so that ending balance would be 1 less than existential // deposit so that we kill the sender account. - value: 100 * DOLLARS - - (pez_kitchensink_runtime::ExistentialDeposit::get() - 1), + value: 100 * DOLLARS + - (pez_kitchensink_runtime::ExistentialDeposit::get() - 1), }) }, - BlockType::Noop => - RuntimeCall::System(SystemCall::remark { remark: Vec::new() }), + BlockType::Noop => { + RuntimeCall::System(SystemCall::remark { remark: Vec::new() }) + }, }, }, self.runtime_version.spec_version, @@ -602,12 +604,13 @@ impl BenchKeyring { .into() }, ExtrinsicFormat::Bare => generic::UncheckedExtrinsic::new_bare(xt.function).into(), - ExtrinsicFormat::General(ext_version, tx_ext) => + ExtrinsicFormat::General(ext_version, tx_ext) => { generic::UncheckedExtrinsic::from_parts( xt.function, Preamble::General(ext_version, tx_ext), ) - .into(), + .into() + }, } } diff --git a/bizinikiwi/bin/utils/chain-spec-builder/src/lib.rs b/bizinikiwi/bin/utils/chain-spec-builder/src/lib.rs index d5bba485..a4e2f6cd 100644 --- a/bizinikiwi/bin/utils/chain-spec-builder/src/lib.rs +++ b/bizinikiwi/bin/utils/chain-spec-builder/src/lib.rs @@ -343,8 +343,9 @@ fn process_action( builder: pezsc_chain_spec::ChainSpecBuilder, ) -> Result { let builder = match cmd.action { - GenesisBuildAction::NamedPreset(NamedPresetCmd { ref preset_name }) => - builder.with_genesis_config_preset_name(&preset_name), + GenesisBuildAction::NamedPreset(NamedPresetCmd { ref preset_name }) => { + builder.with_genesis_config_preset_name(&preset_name) + }, GenesisBuildAction::Patch(PatchCmd { ref patch_path }) => { let patch = fs::read(patch_path.as_path()) .map_err(|e| format!("patch file {patch_path:?} shall be readable: {e}"))?; diff --git a/bizinikiwi/client/allocator/src/freeing_bump.rs b/bizinikiwi/client/allocator/src/freeing_bump.rs index b4644e50..0cd87ad6 100644 --- a/bizinikiwi/client/allocator/src/freeing_bump.rs +++ b/bizinikiwi/client/allocator/src/freeing_bump.rs @@ -421,8 +421,8 @@ impl FreeingBumpHeapAllocator { let header_ptr: u32 = match self.free_lists[order] { Link::Ptr(header_ptr) => { - if (u64::from(header_ptr) + u64::from(order.size()) + u64::from(HEADER_SIZE)) > - mem.size() + if (u64::from(header_ptr) + u64::from(order.size()) + u64::from(HEADER_SIZE)) + > mem.size() { return Err(error("Invalid header pointer detected")); } diff --git a/bizinikiwi/client/api/src/in_mem.rs b/bizinikiwi/client/api/src/in_mem.rs index a3d29e0c..d4b3e84a 100644 --- a/bizinikiwi/client/api/src/in_mem.rs +++ b/bizinikiwi/client/api/src/in_mem.rs @@ -205,10 +205,10 @@ impl Blockchain { } let this = self.storage.read(); let other = other.storage.read(); - this.hashes == other.hashes && - this.best_hash == other.best_hash && - this.best_number == other.best_number && - this.genesis_hash == other.genesis_hash + this.hashes == other.hashes + && this.best_hash == other.best_hash + && this.best_number == other.best_number + && this.genesis_hash == other.genesis_hash } /// Insert header CHT root. diff --git a/bizinikiwi/client/api/src/notifications/registry.rs b/bizinikiwi/client/api/src/notifications/registry.rs index 863c8370..cc4726b7 100644 --- a/bizinikiwi/client/api/src/notifications/registry.rs +++ b/bizinikiwi/client/api/src/notifications/registry.rs @@ -299,7 +299,7 @@ impl Registry { None => { wildcards.remove(&subscriber); }, - Some(filters) => + Some(filters) => { for key in filters.iter() { let remove_key = match listeners.get_mut(key) { Some(ref mut set) => { @@ -312,7 +312,8 @@ impl Registry { if remove_key { listeners.remove(key); } - }, + } + }, } } diff --git a/bizinikiwi/client/authority-discovery/src/worker.rs b/bizinikiwi/client/authority-discovery/src/worker.rs index 5cda331d..3e41b6f5 100644 --- a/bizinikiwi/client/authority-discovery/src/worker.rs +++ b/bizinikiwi/client/authority-discovery/src/worker.rs @@ -503,9 +503,9 @@ where "Publishing authority DHT record peer_id='{local_peer_id}' with addresses='{addresses:?}'", ); - if !self.warn_public_addresses && - self.public_addresses.is_empty() && - !has_global_listen_addresses + if !self.warn_public_addresses + && self.public_addresses.is_empty() + && !has_global_listen_addresses { self.warn_public_addresses = true; @@ -754,8 +754,9 @@ where // Make sure we don't ever work with an outdated set of authorities // and that we do not update known_authorithies too often. let best_hash = self.client.best_hash().await?; - if !self.known_authorities.contains_key(&record_key) && - self.authorities_queried_at + if !self.known_authorities.contains_key(&record_key) + && self + .authorities_queried_at .map(|authorities_queried_at| authorities_queried_at != best_hash) .unwrap_or(true) { @@ -991,8 +992,8 @@ where "Found same record for {:?} record creation time {:?}", authority_id, new_record.creation_time ); - if current_record_info.peers_with_record.len() + new_record.peers_with_record.len() <= - DEFAULT_KADEMLIA_REPLICATION_FACTOR + if current_record_info.peers_with_record.len() + new_record.peers_with_record.len() + <= DEFAULT_KADEMLIA_REPLICATION_FACTOR { current_record_info.peers_with_record.extend(new_record.peers_with_record); } diff --git a/bizinikiwi/client/basic-authorship/src/basic_authorship.rs b/bizinikiwi/client/basic-authorship/src/basic_authorship.rs index ecad5b95..e0f53187 100644 --- a/bizinikiwi/client/basic-authorship/src/basic_authorship.rs +++ b/bizinikiwi/client/basic-authorship/src/basic_authorship.rs @@ -395,8 +395,9 @@ where let mode = block_builder.extrinsic_inclusion_mode(); let end_reason = match mode { - ExtrinsicInclusionMode::AllExtrinsics => - self.apply_extrinsics(&mut block_builder, deadline, block_size_limit).await?, + ExtrinsicInclusionMode::AllExtrinsics => { + self.apply_extrinsics(&mut block_builder, deadline, block_size_limit).await? + }, ExtrinsicInclusionMode::OnlyInherents => EndProposingReason::TransactionForbidden, }; let (block, storage_changes, proof) = block_builder.build()?.into_inner(); @@ -1002,13 +1003,13 @@ mod tests { .chain((1..extrinsics_num as u64).map(extrinsic)) .collect::>(); - let block_limit = genesis_header.encoded_size() + - extrinsics + let block_limit = genesis_header.encoded_size() + + extrinsics .iter() .take(extrinsics_num - 1) .map(Encode::encoded_size) - .sum::() + - Vec::::new().encoded_size(); + .sum::() + + Vec::::new().encoded_size(); block_on(txpool.submit_at(genesis_hash, SOURCE, extrinsics.clone())).unwrap(); diff --git a/bizinikiwi/client/chain-spec/src/chain_spec.rs b/bizinikiwi/client/chain-spec/src/chain_spec.rs index 926032e8..a6dd4e5a 100644 --- a/bizinikiwi/client/chain-spec/src/chain_spec.rs +++ b/bizinikiwi/client/chain-spec/src/chain_spec.rs @@ -53,9 +53,9 @@ enum GenesisBuildAction { impl GenesisBuildAction { pub fn merge_patch(&mut self, patch: json::Value) { match self { - GenesisBuildAction::Patch(value) | - GenesisBuildAction::Full(value) | - GenesisBuildAction::NamedPreset(_, value, _) => json_merge(value, patch), + GenesisBuildAction::Patch(value) + | GenesisBuildAction::Full(value) + | GenesisBuildAction::NamedPreset(_, value, _) => json_merge(value, patch), } } } @@ -65,8 +65,9 @@ impl Clone for GenesisBuildAction { match self { Self::Patch(ref p) => Self::Patch(p.clone()), Self::Full(ref f) => Self::Full(f.clone()), - Self::NamedPreset(ref p, patch, _) => - Self::NamedPreset(p.clone(), patch.clone(), Default::default()), + Self::NamedPreset(ref p, patch, _) => { + Self::NamedPreset(p.clone(), patch.clone(), Default::default()) + }, } } } @@ -124,16 +125,18 @@ impl GenesisSource { Ok(genesis.genesis) }, Self::Storage(storage) => Ok(Genesis::Raw(RawGenesis::from(storage.clone()))), - Self::GenesisBuilderApi(GenesisBuildAction::Full(config), code) => + Self::GenesisBuilderApi(GenesisBuildAction::Full(config), code) => { Ok(Genesis::RuntimeGenesis(RuntimeGenesisInner { json_blob: RuntimeGenesisConfigJson::Config(config.clone()), code: code.clone(), - })), - Self::GenesisBuilderApi(GenesisBuildAction::Patch(patch), code) => + })) + }, + Self::GenesisBuilderApi(GenesisBuildAction::Patch(patch), code) => { Ok(Genesis::RuntimeGenesis(RuntimeGenesisInner { json_blob: RuntimeGenesisConfigJson::Patch(patch.clone()), code: code.clone(), - })), + })) + }, Self::GenesisBuilderApi(GenesisBuildAction::NamedPreset(name, patch, _), code) => { let mut preset = RuntimeCaller::::new(&code[..]).get_named_preset(Some(name))?; @@ -168,8 +171,9 @@ where // The `StateRootHash` variant exists as a way to keep note that other clients support // it, but Bizinikiwi itself isn't capable of loading chain specs with just a hash at // the moment. - Genesis::StateRootHash(_) => - return Err("Genesis storage in hash format not supported".into()), + Genesis::StateRootHash(_) => { + return Err("Genesis storage in hash format not supported".into()) + }, Genesis::RuntimeGenesis(RuntimeGenesisInner { json_blob: RuntimeGenesisConfigJson::Config(config), code, @@ -619,8 +623,12 @@ where RawGenesis::from(storage) }, (true, Genesis::Raw(raw)) => raw, - (_, genesis) => - return Ok(ChainSpecJsonContainer { client_spec: self.client_spec.clone(), genesis }), + (_, genesis) => { + return Ok(ChainSpecJsonContainer { + client_spec: self.client_spec.clone(), + genesis, + }) + }, }; Ok(ChainSpecJsonContainer { diff --git a/bizinikiwi/client/chain-spec/src/json_patch.rs b/bizinikiwi/client/chain-spec/src/json_patch.rs index 806f8ee2..d0435762 100644 --- a/bizinikiwi/client/chain-spec/src/json_patch.rs +++ b/bizinikiwi/client/chain-spec/src/json_patch.rs @@ -33,10 +33,11 @@ use serde_json::Value; /// * `b` - The JSON object to merge with `a`. pub fn merge(a: &mut Value, b: Value) { match (a, b) { - (Value::Object(a), Value::Object(b)) => + (Value::Object(a), Value::Object(b)) => { for (k, v) in b { merge(a.entry(k).or_insert(Value::Null), v); - }, + } + }, (a, b) => *a = b, }; } diff --git a/bizinikiwi/client/cli/src/arg_enums.rs b/bizinikiwi/client/cli/src/arg_enums.rs index ba87c876..48cbff23 100644 --- a/bizinikiwi/client/cli/src/arg_enums.rs +++ b/bizinikiwi/client/cli/src/arg_enums.rs @@ -79,14 +79,18 @@ pub fn execution_method_from_cli( pezsc_service::config::WasmExecutionMethod::Compiled { instantiation_strategy: match instantiation_strategy { - WasmtimeInstantiationStrategy::PoolingCopyOnWrite => - pezsc_service::config::WasmtimeInstantiationStrategy::PoolingCopyOnWrite, - WasmtimeInstantiationStrategy::RecreateInstanceCopyOnWrite => - pezsc_service::config::WasmtimeInstantiationStrategy::RecreateInstanceCopyOnWrite, - WasmtimeInstantiationStrategy::Pooling => - pezsc_service::config::WasmtimeInstantiationStrategy::Pooling, - WasmtimeInstantiationStrategy::RecreateInstance => - pezsc_service::config::WasmtimeInstantiationStrategy::RecreateInstance, + WasmtimeInstantiationStrategy::PoolingCopyOnWrite => { + pezsc_service::config::WasmtimeInstantiationStrategy::PoolingCopyOnWrite + }, + WasmtimeInstantiationStrategy::RecreateInstanceCopyOnWrite => { + pezsc_service::config::WasmtimeInstantiationStrategy::RecreateInstanceCopyOnWrite + }, + WasmtimeInstantiationStrategy::Pooling => { + pezsc_service::config::WasmtimeInstantiationStrategy::Pooling + }, + WasmtimeInstantiationStrategy::RecreateInstance => { + pezsc_service::config::WasmtimeInstantiationStrategy::RecreateInstance + }, }, } } diff --git a/bizinikiwi/client/cli/src/params/import_params.rs b/bizinikiwi/client/cli/src/params/import_params.rs index 13daaaf9..35ddc3c8 100644 --- a/bizinikiwi/client/cli/src/params/import_params.rs +++ b/bizinikiwi/client/cli/src/params/import_params.rs @@ -106,10 +106,12 @@ pub enum TrieCacheWarmUpStrategy { impl From for pezsc_service::config::TrieCacheWarmUpStrategy { fn from(strategy: TrieCacheWarmUpStrategy) -> Self { match strategy { - TrieCacheWarmUpStrategy::NonBlocking => - pezsc_service::config::TrieCacheWarmUpStrategy::NonBlocking, - TrieCacheWarmUpStrategy::Blocking => - pezsc_service::config::TrieCacheWarmUpStrategy::Blocking, + TrieCacheWarmUpStrategy::NonBlocking => { + pezsc_service::config::TrieCacheWarmUpStrategy::NonBlocking + }, + TrieCacheWarmUpStrategy::Blocking => { + pezsc_service::config::TrieCacheWarmUpStrategy::Blocking + }, } } } diff --git a/bizinikiwi/client/cli/src/params/network_params.rs b/bizinikiwi/client/cli/src/params/network_params.rs index 3bd3dbd6..39b77054 100644 --- a/bizinikiwi/client/cli/src/params/network_params.rs +++ b/bizinikiwi/client/cli/src/params/network_params.rs @@ -240,15 +240,16 @@ impl NetworkParams { // Activate if the user explicitly requested local discovery, `--dev` is given or the // chain type is `Local`/`Development` let allow_non_globals_in_dht = - self.discover_local || - is_dev || matches!(chain_type, ChainType::Local | ChainType::Development); + self.discover_local + || is_dev || matches!(chain_type, ChainType::Local | ChainType::Development); let allow_private_ip = match (self.allow_private_ip, self.no_private_ip) { (true, true) => unreachable!("`*_private_ip` flags are mutually exclusive; qed"), (true, false) => true, (false, true) => false, - (false, false) => - is_dev || matches!(chain_type, ChainType::Local | ChainType::Development), + (false, false) => { + is_dev || matches!(chain_type, ChainType::Local | ChainType::Development) + }, }; NetworkConfiguration { diff --git a/bizinikiwi/client/cli/src/params/node_key_params.rs b/bizinikiwi/client/cli/src/params/node_key_params.rs index fb422f69..cf1b850f 100644 --- a/bizinikiwi/client/cli/src/params/node_key_params.rs +++ b/bizinikiwi/client/cli/src/params/node_key_params.rs @@ -115,9 +115,9 @@ impl NodeKeyParams { .node_key_file .clone() .unwrap_or_else(|| net_config_dir.join(NODE_KEY_ED25519_FILE)); - if !self.unsafe_force_node_key_generation && - role.is_authority() && - !is_dev && !key_path.exists() + if !self.unsafe_force_node_key_generation + && role.is_authority() + && !is_dev && !key_path.exists() { return Err(Error::NetworkKeyNotFound(key_path)); } @@ -169,7 +169,9 @@ mod tests { params.node_key(net_config_dir, Role::Authority, false).and_then(|c| match c { NodeKeyConfig::Ed25519(pezsc_network::config::Secret::Input(ref ski)) if node_key_type == NodeKeyType::Ed25519 && &sk[..] == ski.as_ref() => - Ok(()), + { + Ok(()) + }, _ => Err(error::Error::Input("Unexpected node key config".into())), }) }) @@ -239,9 +241,11 @@ mod tests { let typ = params.node_key_type; params.node_key(net_config_dir, role, is_dev).and_then(move |c| match c { NodeKeyConfig::Ed25519(pezsc_network::config::Secret::File(ref f)) - if typ == NodeKeyType::Ed25519 && - f == &dir.join(NODE_KEY_ED25519_FILE) => - Ok(()), + if typ == NodeKeyType::Ed25519 + && f == &dir.join(NODE_KEY_ED25519_FILE) => + { + Ok(()) + }, _ => Err(error::Error::Input("Unexpected node key config".into())), }) }, diff --git a/bizinikiwi/client/cli/src/params/rpc_params.rs b/bizinikiwi/client/cli/src/params/rpc_params.rs index 0f949968..d26ba07c 100644 --- a/bizinikiwi/client/cli/src/params/rpc_params.rs +++ b/bizinikiwi/client/cli/src/params/rpc_params.rs @@ -224,8 +224,8 @@ impl RpcParams { for endpoint in &self.experimental_rpc_endpoint { // Technically, `0.0.0.0` isn't a public IP address, but it's a way to listen on // all interfaces. Thus, we consider it as a public endpoint and warn about it. - if endpoint.rpc_methods == RpcMethods::Unsafe && endpoint.is_global() || - endpoint.listen_addr.ip().is_unspecified() + if endpoint.rpc_methods == RpcMethods::Unsafe && endpoint.is_global() + || endpoint.listen_addr.ip().is_unspecified() { eprintln!( "It isn't safe to expose RPC publicly without a proxy server that filters \ diff --git a/bizinikiwi/client/cli/src/params/transaction_pool_params.rs b/bizinikiwi/client/cli/src/params/transaction_pool_params.rs index ccd6b99e..28bde81e 100644 --- a/bizinikiwi/client/cli/src/params/transaction_pool_params.rs +++ b/bizinikiwi/client/cli/src/params/transaction_pool_params.rs @@ -32,10 +32,12 @@ pub enum TransactionPoolType { impl Into for TransactionPoolType { fn into(self) -> pezsc_transaction_pool::TransactionPoolType { match self { - TransactionPoolType::SingleState => - pezsc_transaction_pool::TransactionPoolType::SingleState, - TransactionPoolType::ForkAware => - pezsc_transaction_pool::TransactionPoolType::ForkAware, + TransactionPoolType::SingleState => { + pezsc_transaction_pool::TransactionPoolType::SingleState + }, + TransactionPoolType::ForkAware => { + pezsc_transaction_pool::TransactionPoolType::ForkAware + }, } } } diff --git a/bizinikiwi/client/consensus/aura/src/import_queue.rs b/bizinikiwi/client/consensus/aura/src/import_queue.rs index 7fbb0706..6e34b041 100644 --- a/bizinikiwi/client/consensus/aura/src/import_queue.rs +++ b/bizinikiwi/client/consensus/aura/src/import_queue.rs @@ -88,8 +88,9 @@ where Ok(CheckedHeader::Checked(header, (slot, seal))) }, - Err(SealVerificationError::Deferred(header, slot)) => - Ok(CheckedHeader::Deferred(header, slot)), + Err(SealVerificationError::Deferred(header, slot)) => { + Ok(CheckedHeader::Deferred(header, slot)) + }, Err(SealVerificationError::Unsealed) => Err(Error::HeaderUnsealed(hash)), Err(SealVerificationError::BadSeal) => Err(Error::HeaderBadSeal(hash)), Err(SealVerificationError::BadSignature) => Err(Error::BadSignature(hash)), diff --git a/bizinikiwi/client/consensus/aura/src/lib.rs b/bizinikiwi/client/consensus/aura/src/lib.rs index 310384a6..f251667f 100644 --- a/bizinikiwi/client/consensus/aura/src/lib.rs +++ b/bizinikiwi/client/consensus/aura/src/lib.rs @@ -520,7 +520,7 @@ where match compatibility_mode { CompatibilityMode::None => {}, // Use `initialize_block` until we hit the block that should disable the mode. - CompatibilityMode::UseInitializeBlock { until } => + CompatibilityMode::UseInitializeBlock { until } => { if *until > context_block_number { runtime_api .initialize_block( @@ -534,7 +534,8 @@ where ), ) .map_err(|_| ConsensusError::InvalidAuthoritiesSet)?; - }, + } + }, } runtime_api diff --git a/bizinikiwi/client/consensus/aura/src/standalone.rs b/bizinikiwi/client/consensus/aura/src/standalone.rs index 384a4f11..d6526a83 100644 --- a/bizinikiwi/client/consensus/aura/src/standalone.rs +++ b/bizinikiwi/client/consensus/aura/src/standalone.rs @@ -208,7 +208,7 @@ where match compatibility_mode { CompatibilityMode::None => {}, // Use `initialize_block` until we hit the block that should disable the mode. - CompatibilityMode::UseInitializeBlock { until } => + CompatibilityMode::UseInitializeBlock { until } => { if *until > context_block_number { runtime_api .initialize_block( @@ -222,7 +222,8 @@ where ), ) .map_err(|_| ConsensusError::InvalidAuthoritiesSet)?; - }, + } + }, } runtime_api diff --git a/bizinikiwi/client/consensus/babe/src/authorship.rs b/bizinikiwi/client/consensus/babe/src/authorship.rs index 5119279e..86e295bb 100644 --- a/bizinikiwi/client/consensus/babe/src/authorship.rs +++ b/bizinikiwi/client/consensus/babe/src/authorship.rs @@ -53,8 +53,8 @@ pub(super) fn calculate_primary_threshold( let c = c.0 as f64 / c.1 as f64; - let theta = authorities[authority_index].1 as f64 / - authorities.iter().map(|(_, weight)| weight).sum::() as f64; + let theta = authorities[authority_index].1 as f64 + / authorities.iter().map(|(_, weight)| weight).sum::() as f64; assert!(theta > 0.0, "authority with weight 0."); @@ -204,8 +204,8 @@ pub fn claim_slot_using_keys( keys: &[(AuthorityId, usize)], ) -> Option<(PreDigest, AuthorityId)> { claim_primary_slot(slot, epoch, epoch.config.c, keystore, keys).or_else(|| { - if epoch.config.allowed_slots.is_secondary_plain_slots_allowed() || - epoch.config.allowed_slots.is_secondary_vrf_slots_allowed() + if epoch.config.allowed_slots.is_secondary_plain_slots_allowed() + || epoch.config.allowed_slots.is_secondary_vrf_slots_allowed() { claim_secondary_slot( slot, diff --git a/bizinikiwi/client/consensus/babe/src/aux_schema.rs b/bizinikiwi/client/consensus/babe/src/aux_schema.rs index 8a4183d1..bd6fbcbb 100644 --- a/bizinikiwi/client/consensus/babe/src/aux_schema.rs +++ b/bizinikiwi/client/consensus/babe/src/aux_schema.rs @@ -62,21 +62,25 @@ pub fn load_epoch_changes( let version = load_decode::<_, u32>(backend, BABE_EPOCH_CHANGES_VERSION)?; let maybe_epoch_changes = match version { - None => + None => { load_decode::<_, EpochChangesV0For>(backend, BABE_EPOCH_CHANGES_KEY)? - .map(|v0| v0.migrate().map(|_, _, epoch| epoch.migrate(config))), - Some(1) => + .map(|v0| v0.migrate().map(|_, _, epoch| epoch.migrate(config))) + }, + Some(1) => { load_decode::<_, EpochChangesV1For>(backend, BABE_EPOCH_CHANGES_KEY)? - .map(|v1| v1.migrate().map(|_, _, epoch| epoch.migrate(config))), + .map(|v1| v1.migrate().map(|_, _, epoch| epoch.migrate(config))) + }, Some(2) => { // v2 still uses `EpochChanges` v1 format but with a different `Epoch` type. load_decode::<_, EpochChangesV1For>(backend, BABE_EPOCH_CHANGES_KEY)? .map(|v2| v2.migrate()) }, - Some(BABE_EPOCH_CHANGES_CURRENT_VERSION) => - load_decode::<_, EpochChangesFor>(backend, BABE_EPOCH_CHANGES_KEY)?, - Some(other) => - return Err(ClientError::Backend(format!("Unsupported BABE DB version: {:?}", other))), + Some(BABE_EPOCH_CHANGES_CURRENT_VERSION) => { + load_decode::<_, EpochChangesFor>(backend, BABE_EPOCH_CHANGES_KEY)? + }, + Some(other) => { + return Err(ClientError::Backend(format!("Unsupported BABE DB version: {:?}", other))) + }, }; let epoch_changes = @@ -199,8 +203,8 @@ mod test { .tree() .iter() .map(|(_, _, epoch)| epoch.clone()) - .collect::>() == - vec![PersistedEpochHeader::Regular(EpochHeader { + .collect::>() + == vec![PersistedEpochHeader::Regular(EpochHeader { start_slot: 0.into(), end_slot: 100.into(), })], diff --git a/bizinikiwi/client/consensus/babe/src/lib.rs b/bizinikiwi/client/consensus/babe/src/lib.rs index ff33360d..97215c92 100644 --- a/bizinikiwi/client/consensus/babe/src/lib.rs +++ b/bizinikiwi/client/consensus/babe/src/lib.rs @@ -401,10 +401,11 @@ where } }, Some(2) => runtime_api.configuration(at_hash)?, - _ => + _ => { return Err(pezsp_blockchain::Error::VersionInvalid( "Unsupported or invalid BabeApi version".to_string(), - )), + )) + }, }; Ok(config) } @@ -791,13 +792,14 @@ where let sinks = &mut self.slot_notification_sinks.lock(); sinks.retain_mut(|sink| match sink.try_send((slot, epoch_descriptor.clone())) { Ok(()) => true, - Err(e) => + Err(e) => { if e.is_full() { warn!(target: LOG_TARGET, "Trying to notify a slot but the channel is full"); true } else { false - }, + } + }, }); } @@ -927,8 +929,9 @@ pub fn find_next_epoch_digest( trace!(target: LOG_TARGET, "Checking log {:?}, looking for epoch change digest.", log); let log = log.try_to::(OpaqueDigestItemId::Consensus(&BABE_ENGINE_ID)); match (log, epoch_digest.is_some()) { - (Some(ConsensusLog::NextEpochData(_)), true) => - return Err(babe_err(Error::MultipleEpochChangeDigests)), + (Some(ConsensusLog::NextEpochData(_)), true) => { + return Err(babe_err(Error::MultipleEpochChangeDigests)) + }, (Some(ConsensusLog::NextEpochData(epoch)), false) => epoch_digest = Some(epoch), _ => trace!(target: LOG_TARGET, "Ignoring digest not meant for us"), } @@ -946,8 +949,9 @@ fn find_next_config_digest( trace!(target: LOG_TARGET, "Checking log {:?}, looking for epoch change digest.", log); let log = log.try_to::(OpaqueDigestItemId::Consensus(&BABE_ENGINE_ID)); match (log, config_digest.is_some()) { - (Some(ConsensusLog::NextConfigData(_)), true) => - return Err(babe_err(Error::MultipleConfigChangeDigests)), + (Some(ConsensusLog::NextConfigData(_)), true) => { + return Err(babe_err(Error::MultipleConfigChangeDigests)) + }, (Some(ConsensusLog::NextConfigData(config)), false) => config_digest = Some(config), _ => trace!(target: LOG_TARGET, "Ignoring digest not meant for us"), } @@ -1094,8 +1098,8 @@ fn is_state_sync_or_gap_sync_import( ) -> bool { let number = *block.header.number(); let info = client.info(); - info.block_gap.map_or(false, |gap| gap.start <= number && number <= gap.end) || - block.with_state() + info.block_gap.map_or(false, |gap| gap.start <= number && number <= gap.end) + || block.with_state() } /// A block-import handler for BABE. @@ -1200,11 +1204,12 @@ where let import_result = self.inner.import_block(block).await; let aux = match import_result { Ok(ImportResult::Imported(aux)) => aux, - Ok(r) => + Ok(r) => { return Err(ConsensusError::ClientImport(format!( "Unexpected import result: {:?}", r - ))), + ))) + }, Err(r) => return Err(r.into()), }; @@ -1271,8 +1276,9 @@ where .get(babe_pre_digest.authority_index() as usize) { Some(author) => author.0.clone(), - None => - return Err(ConsensusError::Other(Error::::SlotAuthorNotFound.into())), + None => { + return Err(ConsensusError::Other(Error::::SlotAuthorNotFound.into())) + }, } }; if let Err(err) = self @@ -1321,12 +1327,14 @@ where .await .map_err(|e| { ConsensusError::Other(Box::new(match e { - CheckInherentsError::CreateInherentData(e) => - Error::::CreateInherents(e), + CheckInherentsError::CreateInherentData(e) => { + Error::::CreateInherents(e) + }, CheckInherentsError::Client(e) => Error::RuntimeApi(e), CheckInherentsError::CheckInherents(e) => Error::CheckInherents(e), - CheckInherentsError::CheckInherentsUnknownError(id) => - Error::CheckInherentsUnhandled(id), + CheckInherentsError::CheckInherentsUnknownError(id) => { + Error::CheckInherentsUnhandled(id) + }, })) })?; let (_, inner_body) = new_block.deconstruct(); @@ -1463,8 +1471,8 @@ where // Skip babe logic if block already in chain or importing blocks during initial sync, // otherwise the check for epoch changes will error because trying to re-import an // epoch change or because of missing epoch data in the tree, respectively. - if info.block_gap.map_or(false, |gap| gap.start <= number && number <= gap.end) || - block_status == BlockStatus::InChain + if info.block_gap.map_or(false, |gap| gap.start <= number && number <= gap.end) + || block_status == BlockStatus::InChain { // When re-importing existing block strip away intermediates. // In case of initial sync intermediates should not be present... @@ -1552,18 +1560,21 @@ where match (first_in_epoch, next_epoch_digest.is_some(), next_config_digest.is_some()) { (true, true, _) => {}, (false, false, false) => {}, - (false, false, true) => + (false, false, true) => { return Err(ConsensusError::ClientImport( babe_err(Error::::UnexpectedConfigChange).into(), - )), - (true, false, _) => + )) + }, + (true, false, _) => { return Err(ConsensusError::ClientImport( babe_err(Error::::ExpectedEpochChange(hash, slot)).into(), - )), - (false, true, _) => + )) + }, + (false, true, _) => { return Err(ConsensusError::ClientImport( babe_err(Error::::UnexpectedEpochChange).into(), - )), + )) + }, } if let Some(next_epoch_descriptor) = next_epoch_digest { @@ -1953,8 +1964,8 @@ where let mut hash = leaf; loop { let meta = client.header_metadata(hash)?; - if meta.number <= revert_up_to_number || - !weight_keys.insert(aux_schema::block_weight_key(hash)) + if meta.number <= revert_up_to_number + || !weight_keys.insert(aux_schema::block_weight_key(hash)) { // We've reached the revert point or an already processed branch, stop here. break; diff --git a/bizinikiwi/client/consensus/beefy/src/aux_schema.rs b/bizinikiwi/client/consensus/beefy/src/aux_schema.rs index 3d7cb1c6..e5d9a3b4 100644 --- a/bizinikiwi/client/consensus/beefy/src/aux_schema.rs +++ b/bizinikiwi/client/consensus/beefy/src/aux_schema.rs @@ -73,10 +73,12 @@ where { warn!(target: LOG_TARGET, "🥩 backend contains a BEEFY state of an obsolete version {v}. ignoring...") }, - Some(4) => - return load_decode::<_, PersistedState>(backend, WORKER_STATE_KEY), - other => - return Err(ClientError::Backend(format!("Unsupported BEEFY DB version: {:?}", other))), + Some(4) => { + return load_decode::<_, PersistedState>(backend, WORKER_STATE_KEY) + }, + other => { + return Err(ClientError::Backend(format!("Unsupported BEEFY DB version: {:?}", other))) + }, } // No persistent state found in DB. diff --git a/bizinikiwi/client/consensus/beefy/src/communication/gossip.rs b/bizinikiwi/client/consensus/beefy/src/communication/gossip.rs index c36f07a5..320bcecf 100644 --- a/bizinikiwi/client/consensus/beefy/src/communication/gossip.rs +++ b/bizinikiwi/client/consensus/beefy/src/communication/gossip.rs @@ -150,12 +150,13 @@ impl Filter { f.start = cfg.start; f.end = cfg.end; }, - _ => + _ => { self.inner = Some(FilterInner { start: cfg.start, end: cfg.end, validator_set: cfg.validator_set.clone(), - }), + }) + }, } } diff --git a/bizinikiwi/client/consensus/beefy/src/justification.rs b/bizinikiwi/client/consensus/beefy/src/justification.rs index e5aa8937..4070c50f 100644 --- a/bizinikiwi/client/consensus/beefy/src/justification.rs +++ b/bizinikiwi/client/consensus/beefy/src/justification.rs @@ -33,8 +33,9 @@ pub(crate) fn proof_block_num_and_set_id, ) -> (NumberFor, ValidatorSetId) { match proof { - VersionedFinalityProof::V1(sc) => - (sc.commitment.block_number, sc.commitment.validator_set_id), + VersionedFinalityProof::V1(sc) => { + (sc.commitment.block_number, sc.commitment.validator_set_id) + }, } } diff --git a/bizinikiwi/client/consensus/beefy/src/lib.rs b/bizinikiwi/client/consensus/beefy/src/lib.rs index b178435b..d190bfd9 100644 --- a/bizinikiwi/client/consensus/beefy/src/lib.rs +++ b/bizinikiwi/client/consensus/beefy/src/lib.rs @@ -787,10 +787,11 @@ where Some(active) => return Ok(active), // Move up the chain. Ultimately we'll get it from chain genesis state, or error out // there. - None => + None => { header = wait_for_parent_header(blockchain, header, HEADER_SYNC_DELAY) .await - .map_err(|e| Error::Backend(e.to_string()))?, + .map_err(|e| Error::Backend(e.to_string()))? + }, } } } diff --git a/bizinikiwi/client/consensus/beefy/src/round.rs b/bizinikiwi/client/consensus/beefy/src/round.rs index fdf1f51d..617d41d6 100644 --- a/bizinikiwi/client/consensus/beefy/src/round.rs +++ b/bizinikiwi/client/consensus/beefy/src/round.rs @@ -180,8 +180,8 @@ where // add valid vote let round = self.rounds.entry(vote.commitment.clone()).or_default(); - if round.add_vote((vote.id, vote.signature)) && - round.is_done(threshold(self.validator_set.len())) + if round.add_vote((vote.id, vote.signature)) + && round.is_done(threshold(self.validator_set.len())) { if let Some(round) = self.rounds.remove_entry(&vote.commitment) { return VoteImportResult::RoundConcluded(self.signed_commitment(round)); diff --git a/bizinikiwi/client/consensus/beefy/src/tests.rs b/bizinikiwi/client/consensus/beefy/src/tests.rs index 47b9db35..8c310c2b 100644 --- a/bizinikiwi/client/consensus/beefy/src/tests.rs +++ b/bizinikiwi/client/consensus/beefy/src/tests.rs @@ -1576,8 +1576,9 @@ async fn gossipped_finality_proofs() { .ok() .and_then(|message| match message { GossipMessage::::Vote(_) => unreachable!(), - GossipMessage::::FinalityProof(proof) => - Some(proof), + GossipMessage::::FinalityProof(proof) => { + Some(proof) + }, }) }) .fuse(), diff --git a/bizinikiwi/client/consensus/beefy/src/worker.rs b/bizinikiwi/client/consensus/beefy/src/worker.rs index 05e27bf1..4ebea313 100644 --- a/bizinikiwi/client/consensus/beefy/src/worker.rs +++ b/bizinikiwi/client/consensus/beefy/src/worker.rs @@ -526,7 +526,7 @@ where { let block_num = vote.commitment.block_number; match self.voting_oracle().triage_round(block_num)? { - RoundAction::Process => + RoundAction::Process => { if let Some(finality_proof) = self.handle_vote(vote)? { let gossip_proof = GossipMessage::::FinalityProof(finality_proof); @@ -536,7 +536,8 @@ where encoded_proof, true, ); - }, + } + }, RoundAction::Drop => metric_inc!(self.metrics, beefy_stale_votes), RoundAction::Enqueue => error!(target: LOG_TARGET, "🥩 unexpected vote: {:?}.", vote), }; diff --git a/bizinikiwi/client/consensus/common/src/block_import.rs b/bizinikiwi/client/consensus/common/src/block_import.rs index 3db39984..c6ad36e6 100644 --- a/bizinikiwi/client/consensus/common/src/block_import.rs +++ b/bizinikiwi/client/consensus/common/src/block_import.rs @@ -157,9 +157,9 @@ impl StateAction { /// Check if execution checks that require runtime calls should be skipped. pub fn skip_execution_checks(&self) -> bool { match self { - StateAction::ApplyChanges(_) | - StateAction::Execute | - StateAction::ExecuteIfPossible => false, + StateAction::ApplyChanges(_) + | StateAction::Execute + | StateAction::ExecuteIfPossible => false, StateAction::Skip => true, } } diff --git a/bizinikiwi/client/consensus/common/src/import_queue.rs b/bizinikiwi/client/consensus/common/src/import_queue.rs index ded1f42a..7ddbb037 100644 --- a/bizinikiwi/client/consensus/common/src/import_queue.rs +++ b/bizinikiwi/client/consensus/common/src/import_queue.rs @@ -193,8 +193,8 @@ impl BlockImportStatus { /// Returns the imported block number. pub fn number(&self) -> &BlockNumber { match self { - BlockImportStatus::ImportedKnown(n, _) | - BlockImportStatus::ImportedUnknown(n, _, _) => n, + BlockImportStatus::ImportedKnown(n, _) + | BlockImportStatus::ImportedUnknown(n, _, _) => n, } } } @@ -242,8 +242,9 @@ pub async fn import_single_block>( ) -> BlockImportResult { match verify_single_block_metered(import_handle, block_origin, block, verifier, None).await? { SingleBlockVerificationOutcome::Imported(import_status) => Ok(import_status), - SingleBlockVerificationOutcome::Verified(import_parameters) => - import_single_block_metered(import_handle, import_parameters, None).await, + SingleBlockVerificationOutcome::Verified(import_parameters) => { + import_single_block_metered(import_handle, import_parameters, None).await + }, } } @@ -262,8 +263,9 @@ where trace!(target: LOG_TARGET, "Block already in chain {}: {:?}", number, hash); Ok(BlockImportStatus::ImportedKnown(number, block_origin)) }, - Ok(ImportResult::Imported(aux)) => - Ok(BlockImportStatus::ImportedUnknown(number, aux, block_origin)), + Ok(ImportResult::Imported(aux)) => { + Ok(BlockImportStatus::ImportedUnknown(number, aux, block_origin)) + }, Ok(ImportResult::MissingState) => { debug!( target: LOG_TARGET, diff --git a/bizinikiwi/client/consensus/common/src/import_queue/basic_queue.rs b/bizinikiwi/client/consensus/common/src/import_queue/basic_queue.rs index 78a4c435..06aea1aa 100644 --- a/bizinikiwi/client/consensus/common/src/import_queue/basic_queue.rs +++ b/bizinikiwi/client/consensus/common/src/import_queue/basic_queue.rs @@ -310,8 +310,9 @@ impl BlockImportWorker { // Make sure to first process all justifications while let Poll::Ready(justification) = futures::poll!(justification_port.next()) { match justification { - Some(ImportJustification(who, hash, number, justification)) => - worker.import_justification(who, hash, number, justification).await, + Some(ImportJustification(who, hash, number, justification)) => { + worker.import_justification(who, hash, number, justification).await + }, None => { log::debug!( target: LOG_TARGET, @@ -361,8 +362,9 @@ impl BlockImportWorker { }); match result { Ok(()) => JustificationImportResult::Success, - Err(pezsp_consensus::Error::OutdatedJustification) => - JustificationImportResult::OutdatedJustification, + Err(pezsp_consensus::Error::OutdatedJustification) => { + JustificationImportResult::OutdatedJustification + }, Err(_) => JustificationImportResult::Failure, } }, diff --git a/bizinikiwi/client/consensus/common/src/import_queue/buffered_link.rs b/bizinikiwi/client/consensus/common/src/import_queue/buffered_link.rs index 7ff05b93..60fba0be 100644 --- a/bizinikiwi/client/consensus/common/src/import_queue/buffered_link.rs +++ b/bizinikiwi/client/consensus/common/src/import_queue/buffered_link.rs @@ -127,12 +127,15 @@ impl BufferedLinkReceiver { /// Send action for the synchronization to perform. pub fn send_actions(&mut self, msg: BlockImportWorkerMsg, link: &dyn Link) { match msg { - BlockImportWorkerMsg::BlocksProcessed(imported, count, results) => - link.blocks_processed(imported, count, results), - BlockImportWorkerMsg::JustificationImported(who, hash, number, import_result) => - link.justification_imported(who, &hash, number, import_result), - BlockImportWorkerMsg::RequestJustification(hash, number) => - link.request_justification(&hash, number), + BlockImportWorkerMsg::BlocksProcessed(imported, count, results) => { + link.blocks_processed(imported, count, results) + }, + BlockImportWorkerMsg::JustificationImported(who, hash, number, import_result) => { + link.justification_imported(who, &hash, number, import_result) + }, + BlockImportWorkerMsg::RequestJustification(hash, number) => { + link.request_justification(&hash, number) + }, } } diff --git a/bizinikiwi/client/consensus/epochs/src/lib.rs b/bizinikiwi/client/consensus/epochs/src/lib.rs index 5552bcca..18922067 100644 --- a/bizinikiwi/client/consensus/epochs/src/lib.rs +++ b/bizinikiwi/client/consensus/epochs/src/lib.rs @@ -199,8 +199,9 @@ where pub fn increment(&self, next_descriptor: E::NextEpochDescriptor) -> IncrementedEpoch { let next = self.as_ref().increment(next_descriptor); let to_persist = match *self { - ViableEpoch::UnimportedGenesis(ref epoch_0) => - PersistedEpoch::Genesis(epoch_0.clone(), next), + ViableEpoch::UnimportedGenesis(ref epoch_0) => { + PersistedEpoch::Genesis(epoch_0.clone(), next) + }, ViableEpoch::Signaled(_) => PersistedEpoch::Regular(next), }; @@ -246,8 +247,9 @@ impl PersistedEpoch { impl<'a, E: Epoch> From<&'a PersistedEpoch> for PersistedEpochHeader { fn from(epoch: &'a PersistedEpoch) -> Self { match epoch { - PersistedEpoch::Genesis(ref epoch_0, ref epoch_1) => - PersistedEpochHeader::Genesis(epoch_0.into(), epoch_1.into()), + PersistedEpoch::Genesis(ref epoch_0, ref epoch_1) => { + PersistedEpochHeader::Genesis(epoch_0.into(), epoch_1.into()) + }, PersistedEpoch::Regular(ref epoch_n) => PersistedEpochHeader::Regular(epoch_n.into()), } } @@ -261,8 +263,9 @@ impl PersistedEpoch { F: FnMut(&Hash, &Number, E) -> B, { match self { - PersistedEpoch::Genesis(epoch_0, epoch_1) => - PersistedEpoch::Genesis(f(h, n, epoch_0), f(h, n, epoch_1)), + PersistedEpoch::Genesis(epoch_0, epoch_1) => { + PersistedEpoch::Genesis(f(h, n, epoch_0), f(h, n, epoch_1)) + }, PersistedEpoch::Regular(epoch_n) => PersistedEpoch::Regular(f(h, n, epoch_n)), } } @@ -426,13 +429,19 @@ where self.epochs.get(&(id.hash, id.number)).and_then(|v| match v { PersistedEpoch::Genesis(ref epoch_0, _) if id.position == EpochIdentifierPosition::Genesis0 => - Some(epoch_0), + { + Some(epoch_0) + }, PersistedEpoch::Genesis(_, ref epoch_1) if id.position == EpochIdentifierPosition::Genesis1 => - Some(epoch_1), + { + Some(epoch_1) + }, PersistedEpoch::Regular(ref epoch_n) if id.position == EpochIdentifierPosition::Regular => - Some(epoch_n), + { + Some(epoch_n) + }, _ => None, }) } @@ -447,10 +456,12 @@ where G: FnOnce(E::Slot) -> E, { match descriptor { - ViableEpochDescriptor::UnimportedGenesis(slot) => - Some(ViableEpoch::UnimportedGenesis(make_genesis(*slot))), - ViableEpochDescriptor::Signaled(identifier, _) => - self.epoch(identifier).map(ViableEpoch::Signaled), + ViableEpochDescriptor::UnimportedGenesis(slot) => { + Some(ViableEpoch::UnimportedGenesis(make_genesis(*slot))) + }, + ViableEpochDescriptor::Signaled(identifier, _) => { + self.epoch(identifier).map(ViableEpoch::Signaled) + }, } } @@ -459,13 +470,19 @@ where self.epochs.get_mut(&(id.hash, id.number)).and_then(|v| match v { PersistedEpoch::Genesis(ref mut epoch_0, _) if id.position == EpochIdentifierPosition::Genesis0 => - Some(epoch_0), + { + Some(epoch_0) + }, PersistedEpoch::Genesis(_, ref mut epoch_1) if id.position == EpochIdentifierPosition::Genesis1 => - Some(epoch_1), + { + Some(epoch_1) + }, PersistedEpoch::Regular(ref mut epoch_n) if id.position == EpochIdentifierPosition::Regular => - Some(epoch_n), + { + Some(epoch_n) + }, _ => None, }) } @@ -480,10 +497,12 @@ where G: FnOnce(E::Slot) -> E, { match descriptor { - ViableEpochDescriptor::UnimportedGenesis(slot) => - Some(ViableEpoch::UnimportedGenesis(make_genesis(*slot))), - ViableEpochDescriptor::Signaled(identifier, _) => - self.epoch_mut(identifier).map(ViableEpoch::Signaled), + ViableEpochDescriptor::UnimportedGenesis(slot) => { + Some(ViableEpoch::UnimportedGenesis(make_genesis(*slot))) + }, + ViableEpochDescriptor::Signaled(identifier, _) => { + self.epoch_mut(identifier).map(ViableEpoch::Signaled) + }, } } @@ -589,8 +608,9 @@ where (EpochIdentifierPosition::Genesis0, epoch_0.clone()) } }, - PersistedEpochHeader::Regular(ref epoch_n) => - (EpochIdentifierPosition::Regular, epoch_n.clone()), + PersistedEpochHeader::Regular(ref epoch_n) => { + (EpochIdentifierPosition::Regular, epoch_n.clone()) + }, }, node, ) @@ -665,8 +685,8 @@ where let is_descendent_of = descendent_of_builder.build_is_descendent_of(None); let filter = |node_hash: &Hash, node_num: &Number, _: &PersistedEpochHeader| { - if number >= *node_num && - (is_descendent_of(node_hash, &hash).unwrap_or_default() || *node_hash == hash) + if number >= *node_num + && (is_descendent_of(node_hash, &hash).unwrap_or_default() || *node_hash == hash) { // Continue the search in this subtree. FilterAction::KeepNode @@ -1063,18 +1083,18 @@ mod tests { let is_descendent_of = |base: &Hash, block: &Hash| -> Result { match (block, base) { - | (b"A", b"0") | - (b"B", b"0" | b"A") | - (b"C", b"0" | b"A" | b"B") | - (b"D", b"0" | b"A" | b"B" | b"C") | - (b"E", b"0" | b"A" | b"B" | b"C" | b"D") | - (b"F", b"0" | b"A" | b"B" | b"C" | b"D" | b"E") | - (b"G", b"0" | b"A" | b"B" | b"C" | b"D" | b"E") | - (b"H", b"0" | b"A" | b"B" | b"C" | b"D" | b"E" | b"G") | - (b"I", b"0" | b"A" | b"B" | b"C" | b"D" | b"E" | b"G" | b"H") | - (b"J", b"0" | b"A" | b"B" | b"C" | b"D" | b"E" | b"G" | b"H" | b"I") | - (b"K", b"0" | b"A" | b"B" | b"C" | b"D" | b"E" | b"G" | b"H" | b"I" | b"J") | - ( + | (b"A", b"0") + | (b"B", b"0" | b"A") + | (b"C", b"0" | b"A" | b"B") + | (b"D", b"0" | b"A" | b"B" | b"C") + | (b"E", b"0" | b"A" | b"B" | b"C" | b"D") + | (b"F", b"0" | b"A" | b"B" | b"C" | b"D" | b"E") + | (b"G", b"0" | b"A" | b"B" | b"C" | b"D" | b"E") + | (b"H", b"0" | b"A" | b"B" | b"C" | b"D" | b"E" | b"G") + | (b"I", b"0" | b"A" | b"B" | b"C" | b"D" | b"E" | b"G" | b"H") + | (b"J", b"0" | b"A" | b"B" | b"C" | b"D" | b"E" | b"G" | b"H" | b"I") + | (b"K", b"0" | b"A" | b"B" | b"C" | b"D" | b"E" | b"G" | b"H" | b"I" | b"J") + | ( b"L", b"0" | b"A" | b"B" | b"C" | b"D" | b"E" | b"G" | b"H" | b"I" | b"J" | b"K", ) => Ok(true), diff --git a/bizinikiwi/client/consensus/grandpa/src/authorities.rs b/bizinikiwi/client/consensus/grandpa/src/authorities.rs index f66864f9..c44c96bc 100644 --- a/bizinikiwi/client/consensus/grandpa/src/authorities.rs +++ b/bizinikiwi/client/consensus/grandpa/src/authorities.rs @@ -230,8 +230,8 @@ where F: Fn(&H, &H) -> Result, { let filter = |node_hash: &H, node_num: &N, _: &PendingChange| { - if number >= *node_num && - (is_descendent_of(node_hash, &hash).unwrap_or_default() || *node_hash == hash) + if number >= *node_num + && (is_descendent_of(node_hash, &hash).unwrap_or_default() || *node_hash == hash) { // Continue the search in this subtree. FilterAction::KeepNode @@ -291,8 +291,9 @@ where } let earliest = match (forced, standard) { - (Some(forced), Some(standard)) => - Some(if forced.1 < standard.1 { forced } else { standard }), + (Some(forced), Some(standard)) => { + Some(if forced.1 < standard.1 { forced } else { standard }) + }, (Some(forced), None) => Some(forced), (None, Some(standard)) => Some(standard), (None, None) => None, @@ -476,8 +477,8 @@ where // check if there's any pending standard change that we depend on for (_, _, standard_change) in self.pending_standard_changes.roots() { - if standard_change.effective_number() <= median_last_finalized && - is_descendent_of(&standard_change.canon_hash, &change.canon_hash)? + if standard_change.effective_number() <= median_last_finalized + && is_descendent_of(&standard_change.canon_hash, &change.canon_hash)? { log::info!(target: LOG_TARGET, "Not applying authority set change forced at block #{:?}, due to pending standard change at block #{:?}", @@ -566,8 +567,8 @@ where // we will keep all forced changes for any later blocks and that are a // descendent of the finalized block (i.e. they are part of this branch). for change in pending_forced_changes { - if change.effective_number() > finalized_number && - is_descendent_of(&finalized_hash, &change.canon_hash)? + if change.effective_number() > finalized_number + && is_descendent_of(&finalized_hash, &change.canon_hash)? { self.pending_forced_changes.push(change) } diff --git a/bizinikiwi/client/consensus/grandpa/src/aux_schema.rs b/bizinikiwi/client/consensus/grandpa/src/aux_schema.rs index 7af64f54..9d524420 100644 --- a/bizinikiwi/client/consensus/grandpa/src/aux_schema.rs +++ b/bizinikiwi/client/consensus/grandpa/src/aux_schema.rs @@ -382,8 +382,12 @@ where }); } }, - Some(other) => - return Err(ClientError::Backend(format!("Unsupported GRANDPA DB version: {:?}", other))), + Some(other) => { + return Err(ClientError::Backend(format!( + "Unsupported GRANDPA DB version: {:?}", + other + ))) + }, } // genesis. diff --git a/bizinikiwi/client/consensus/grandpa/src/communication/gossip.rs b/bizinikiwi/client/consensus/grandpa/src/communication/gossip.rs index 955e9d5d..6808b60b 100644 --- a/bizinikiwi/client/consensus/grandpa/src/communication/gossip.rs +++ b/bizinikiwi/client/consensus/grandpa/src/communication/gossip.rs @@ -199,12 +199,13 @@ impl View { // the one we're aware of. match self.last_commit { None => Consider::Accept, - Some(ref num) => + Some(ref num) => { if num < &number { Consider::Accept } else { Consider::RejectPast - }, + } + }, } } } @@ -549,17 +550,17 @@ impl Peers { ) -> Result>, Misbehavior> { let Some(peer) = self.inner.get_mut(who) else { return Ok(None) }; - let invalid_change = peer.view.set_id > update.set_id || - peer.view.round > update.round && peer.view.set_id == update.set_id || - peer.view.last_commit.as_ref() > Some(&update.commit_finalized_height); + let invalid_change = peer.view.set_id > update.set_id + || peer.view.round > update.round && peer.view.set_id == update.set_id + || peer.view.last_commit.as_ref() > Some(&update.commit_finalized_height); if invalid_change { return Err(Misbehavior::InvalidViewChange); } let now = Instant::now(); - let duplicate_packet = (update.set_id, update.round, Some(&update.commit_finalized_height)) == - (peer.view.set_id, peer.view.round, peer.view.last_commit.as_ref()); + let duplicate_packet = (update.set_id, update.round, Some(&update.commit_finalized_height)) + == (peer.view.set_id, peer.view.round, peer.view.last_commit.as_ref()); if duplicate_packet { if let Some(last_update) = peer.view.last_update { @@ -820,8 +821,8 @@ impl Inner { ref mut x @ None => x.get_or_insert(LocalView::new(set_id, Round(1))), Some(ref mut v) => { if v.set_id == set_id { - let diff_authorities = self.authorities.iter().collect::>() != - authorities.iter().collect::>(); + let diff_authorities = self.authorities.iter().collect::>() + != authorities.iter().collect::>(); if diff_authorities { debug!( @@ -902,10 +903,12 @@ impl Inner { ) -> Action { match self.consider_vote(full.round, full.set_id) { Consider::RejectFuture => return Action::Discard(Misbehavior::FutureMessage.cost()), - Consider::RejectOutOfScope => - return Action::Discard(Misbehavior::OutOfScopeMessage.cost()), - Consider::RejectPast => - return Action::Discard(self.cost_past_rejection(who, full.round, full.set_id)), + Consider::RejectOutOfScope => { + return Action::Discard(Misbehavior::OutOfScopeMessage.cost()) + }, + Consider::RejectPast => { + return Action::Discard(self.cost_past_rejection(who, full.round, full.set_id)) + }, Consider::Accept => {}, } @@ -955,15 +958,17 @@ impl Inner { match self.consider_global(full.set_id, full.message.target_number) { Consider::RejectFuture => return Action::Discard(Misbehavior::FutureMessage.cost()), - Consider::RejectPast => - return Action::Discard(self.cost_past_rejection(who, full.round, full.set_id)), - Consider::RejectOutOfScope => - return Action::Discard(Misbehavior::OutOfScopeMessage.cost()), + Consider::RejectPast => { + return Action::Discard(self.cost_past_rejection(who, full.round, full.set_id)) + }, + Consider::RejectOutOfScope => { + return Action::Discard(Misbehavior::OutOfScopeMessage.cost()) + }, Consider::Accept => {}, } - if full.message.precommits.len() != full.message.auth_data.len() || - full.message.precommits.is_empty() + if full.message.precommits.len() != full.message.auth_data.len() + || full.message.precommits.is_empty() { debug!(target: LOG_TARGET, "Malformed compact commit"); telemetry!( @@ -1046,8 +1051,8 @@ impl Inner { // race where the peer sent us the request before it observed that // we had transitioned to a new set. In this case we charge a lower // cost. - if request.set_id.0.saturating_add(1) == local_view.set_id.0 && - local_view.round.0.saturating_sub(CATCH_UP_THRESHOLD) == 0 + if request.set_id.0.saturating_add(1) == local_view.set_id.0 + && local_view.round.0.saturating_sub(CATCH_UP_THRESHOLD) == 0 { return (None, Action::Discard(cost::HONEST_OUT_OF_SCOPE_CATCH_UP)); } @@ -1057,8 +1062,9 @@ impl Inner { match self.peers.peer(who) { None => return (None, Action::Discard(Misbehavior::OutOfScopeMessage.cost())), - Some(peer) if peer.view.round >= request.round => - return (None, Action::Discard(Misbehavior::OutOfScopeMessage.cost())), + Some(peer) if peer.view.round >= request.round => { + return (None, Action::Discard(Misbehavior::OutOfScopeMessage.cost())) + }, _ => {}, } @@ -1131,9 +1137,9 @@ impl Inner { // won't be able to reply since they don't follow the full GRANDPA // protocol and therefore might not have the vote data available. if let (Some(peer), Some(local_view)) = (self.peers.peer(who), &self.local_view) { - if self.catch_up_config.request_allowed(peer) && - peer.view.set_id == local_view.set_id && - peer.view.round.0.saturating_sub(CATCH_UP_THRESHOLD) > local_view.round.0 + if self.catch_up_config.request_allowed(peer) + && peer.view.set_id == local_view.set_id + && peer.view.round.0.saturating_sub(CATCH_UP_THRESHOLD) > local_view.round.0 { // send catch up request if allowed let round = peer.view.round.0 - 1; // peer.view.round is > 0 @@ -1166,8 +1172,9 @@ impl Inner { let update_res = self.peers.update_peer_state(who, update); let (cost_benefit, topics) = match update_res { - Ok(view) => - (benefit::NEIGHBOR_MESSAGE, view.map(|view| neighbor_topics::(view))), + Ok(view) => { + (benefit::NEIGHBOR_MESSAGE, view.map(|view| neighbor_topics::(view))) + }, Err(misbehavior) => (misbehavior.cost(), None), }; @@ -1249,8 +1256,8 @@ impl Inner { if round_elapsed < round_duration.mul_f32(PROPAGATION_SOME) { self.peers.first_stage_peers.contains(who) } else if round_elapsed < round_duration.mul_f32(PROPAGATION_ALL) { - self.peers.first_stage_peers.contains(who) || - self.peers.second_stage_peers.contains(who) + self.peers.first_stage_peers.contains(who) + || self.peers.second_stage_peers.contains(who) } else { self.peers.peer(who).map(|info| !info.roles.is_light()).unwrap_or(false) } @@ -1278,9 +1285,9 @@ impl Inner { }; if round_elapsed < round_duration.mul_f32(PROPAGATION_ALL) { - self.peers.first_stage_peers.contains(who) || - self.peers.second_stage_peers.contains(who) || - self.peers.lucky_light_peers.contains(who) + self.peers.first_stage_peers.contains(who) + || self.peers.second_stage_peers.contains(who) + || self.peers.lucky_light_peers.contains(who) } else { true } @@ -1611,9 +1618,9 @@ impl pezsc_network_gossip::Validator for GossipValidator false, Ok(GossipMessage::CatchUpRequest(_)) => false, @@ -1646,8 +1653,11 @@ impl pezsc_network_gossip::Validator for GossipValidator // we expire any commit message that doesn't target the same block // as our best commit or isn't from the same round and set id - !(full.message.target_number == number && - full.round == round && full.set_id == set_id), + { + !(full.message.target_number == number + && full.round == round + && full.set_id == set_id) + }, None => true, }, Ok(_) => true, @@ -2323,8 +2333,8 @@ mod tests { let test = |rounds_elapsed, peers| { // rewind n round durations - val.inner.write().local_view.as_mut().unwrap().round_start = Instant::now() - - Duration::from_millis( + val.inner.write().local_view.as_mut().unwrap().round_start = Instant::now() + - Duration::from_millis( (round_duration.as_millis() as f32 * rounds_elapsed) as u64, ); diff --git a/bizinikiwi/client/consensus/grandpa/src/communication/mod.rs b/bizinikiwi/client/consensus/grandpa/src/communication/mod.rs index ecb91074..c7447bdc 100644 --- a/bizinikiwi/client/consensus/grandpa/src/communication/mod.rs +++ b/bizinikiwi/client/consensus/grandpa/src/communication/mod.rs @@ -505,10 +505,11 @@ impl, S: Syncing> Future for NetworkBridge Poll::Ready(Some((to, packet))) => { self.gossip_engine.lock().send_message(to, packet.encode()); }, - Poll::Ready(None) => + Poll::Ready(None) => { return Poll::Ready(Err(Error::Network( "Neighbor packet worker stream closed.".into(), - ))), + ))) + }, Poll::Pending => break, } } @@ -518,17 +519,19 @@ impl, S: Syncing> Future for NetworkBridge Poll::Ready(Some(PeerReport { who, cost_benefit })) => { self.gossip_engine.lock().report(who, cost_benefit); }, - Poll::Ready(None) => + Poll::Ready(None) => { return Poll::Ready(Err(Error::Network( "Gossip validator report stream closed.".into(), - ))), + ))) + }, Poll::Pending => break, } } match self.gossip_engine.lock().poll_unpin(cx) { - Poll::Ready(()) => - return Poll::Ready(Err(Error::Network("Gossip engine future finished.".into()))), + Poll::Ready(()) => { + return Poll::Ready(Err(Error::Network("Gossip engine future finished.".into()))) + }, Poll::Pending => {}, } @@ -666,10 +669,12 @@ fn incoming_global( }) .filter_map(move |(notification, msg)| { future::ready(match msg { - GossipMessage::Commit(msg) => - process_commit(msg, notification, &gossip_engine, &gossip_validator, &voters), - GossipMessage::CatchUp(msg) => - process_catch_up(msg, notification, &gossip_engine, &gossip_validator, &voters), + GossipMessage::Commit(msg) => { + process_commit(msg, notification, &gossip_engine, &gossip_validator, &voters) + }, + GossipMessage::CatchUp(msg) => { + process_catch_up(msg, notification, &gossip_engine, &gossip_validator, &voters) + }, _ => { debug!(target: LOG_TARGET, "Skipping unknown message type"); None diff --git a/bizinikiwi/client/consensus/grandpa/src/communication/tests.rs b/bizinikiwi/client/consensus/grandpa/src/communication/tests.rs index ccd6f80f..26965cce 100644 --- a/bizinikiwi/client/consensus/grandpa/src/communication/tests.rs +++ b/bizinikiwi/client/consensus/grandpa/src/communication/tests.rs @@ -270,10 +270,11 @@ impl Tester { futures::future::poll_fn(move |cx| loop { match Stream::poll_next(Pin::new(&mut s.as_mut().unwrap().events), cx) { Poll::Ready(None) => panic!("concluded early"), - Poll::Ready(Some(item)) => + Poll::Ready(Some(item)) => { if pred(item) { return Poll::Ready(s.take().unwrap()); - }, + } + }, Poll::Pending => return Poll::Pending, } }) @@ -622,8 +623,9 @@ fn bad_commit_leads_to_report() { let fut = future::join(send_message, handle_commit) .then(move |(tester, ())| { tester.filter_network_events(move |event| match event { - Event::Report(who, cost_benefit) => - who == id && cost_benefit == super::cost::INVALID_COMMIT, + Event::Report(who, cost_benefit) => { + who == id && cost_benefit == super::cost::INVALID_COMMIT + }, _ => false, }) }) diff --git a/bizinikiwi/client/consensus/grandpa/src/environment.rs b/bizinikiwi/client/consensus/grandpa/src/environment.rs index 27172a28..3e608595 100644 --- a/bizinikiwi/client/consensus/grandpa/src/environment.rs +++ b/bizinikiwi/client/consensus/grandpa/src/environment.rs @@ -277,8 +277,8 @@ impl HasVoted
{ pub fn propose(&self) -> Option<&PrimaryPropose
> { match self { HasVoted::Yes(_, Vote::Propose(propose)) => Some(propose), - HasVoted::Yes(_, Vote::Prevote(propose, _)) | - HasVoted::Yes(_, Vote::Precommit(propose, _, _)) => propose.as_ref(), + HasVoted::Yes(_, Vote::Prevote(propose, _)) + | HasVoted::Yes(_, Vote::Precommit(propose, _, _)) => propose.as_ref(), _ => None, } } @@ -286,8 +286,8 @@ impl HasVoted
{ /// Returns the prevote we should vote with (if any.) pub fn prevote(&self) -> Option<&Prevote
> { match self { - HasVoted::Yes(_, Vote::Prevote(_, prevote)) | - HasVoted::Yes(_, Vote::Precommit(_, prevote, _)) => Some(prevote), + HasVoted::Yes(_, Vote::Prevote(_, prevote)) + | HasVoted::Yes(_, Vote::Precommit(_, prevote, _)) => Some(prevote), _ => None, } } @@ -528,8 +528,9 @@ where // find the hash of the latest block in the current set let current_set_latest_hash = match next_change { - Some((_, n)) if n.is_zero() => - return Err(Error::Safety("Authority set change signalled at genesis.".to_string())), + Some((_, n)) if n.is_zero() => { + return Err(Error::Safety("Authority set change signalled at genesis.".to_string())) + }, // the next set starts at `n` so the current one lasts until `n - 1`. if // `n` is later than the best block, then the current set is still live // at best block. @@ -733,12 +734,13 @@ where let local_id = local_authority_id(&self.voters, self.config.keystore.as_ref()); let has_voted = match self.voter_set_state.has_voted(round) { - HasVoted::Yes(id, vote) => + HasVoted::Yes(id, vote) => { if local_id.as_ref().map(|k| k == &id).unwrap_or(false) { HasVoted::Yes(id, vote) } else { HasVoted::No - }, + } + }, HasVoted::No => HasVoted::No, }; @@ -1253,10 +1255,10 @@ where let is_descendent_of = is_descendent_of(&*client, None); - if target_header.number() > best_header.number() || - target_header.number() == best_header.number() && - target_header.hash() != best_header.hash() || - !is_descendent_of(&target_header.hash(), &best_header.hash())? + if target_header.number() > best_header.number() + || target_header.number() == best_header.number() + && target_header.hash() != best_header.hash() + || !is_descendent_of(&target_header.hash(), &best_header.hash())? { debug!( target: LOG_TARGET, diff --git a/bizinikiwi/client/consensus/grandpa/src/import.rs b/bizinikiwi/client/consensus/grandpa/src/import.rs index dcb5d07b..a5be8027 100644 --- a/bizinikiwi/client/consensus/grandpa/src/import.rs +++ b/bizinikiwi/client/consensus/grandpa/src/import.rs @@ -111,9 +111,9 @@ where self.authority_set.inner().pending_changes().cloned().collect(); for pending_change in pending_changes { - if pending_change.delay_kind == DelayKind::Finalized && - pending_change.effective_number() > chain_info.finalized_number && - pending_change.effective_number() <= chain_info.best_number + if pending_change.delay_kind == DelayKind::Finalized + && pending_change.effective_number() > chain_info.finalized_number + && pending_change.effective_number() <= chain_info.best_number { let effective_block_hash = if !pending_change.delay.is_zero() { self.select_chain @@ -685,7 +685,7 @@ where ); } }, - None => + None => { if needs_justification { debug!( target: LOG_TARGET, @@ -694,7 +694,8 @@ where ); imported_aux.needs_justification = true; - }, + } + }, } Ok(ImportResult::Imported(imported_aux)) @@ -799,8 +800,9 @@ where let justification = match justification { Err(e) => { return match e { - pezsp_blockchain::Error::OutdatedJustification => - Err(ConsensusError::OutdatedJustification), + pezsp_blockchain::Error::OutdatedJustification => { + Err(ConsensusError::OutdatedJustification) + }, _ => Err(ConsensusError::ClientImport(e.to_string())), }; }, @@ -832,7 +834,7 @@ where // send the command to the voter let _ = self.send_voter_commands.unbounded_send(command); }, - Err(CommandOrError::Error(e)) => + Err(CommandOrError::Error(e)) => { return Err(match e { Error::Grandpa(error) => ConsensusError::ClientImport(error.to_string()), Error::Network(error) => ConsensusError::ClientImport(error), @@ -842,7 +844,8 @@ where Error::Signing(error) => ConsensusError::ClientImport(error), Error::Timer(error) => ConsensusError::ClientImport(error.to_string()), Error::RuntimeApi(error) => ConsensusError::ClientImport(error.to_string()), - }), + }) + }, Ok(_) => { assert!( !enacts_change, diff --git a/bizinikiwi/client/consensus/grandpa/src/justification.rs b/bizinikiwi/client/consensus/grandpa/src/justification.rs index b7475fba..5b738fc8 100644 --- a/bizinikiwi/client/consensus/grandpa/src/justification.rs +++ b/bizinikiwi/client/consensus/grandpa/src/justification.rs @@ -214,12 +214,14 @@ impl GrandpaJustification { &mut buf, ); match signature_result { - pezsp_consensus_grandpa::SignatureResult::Invalid => + pezsp_consensus_grandpa::SignatureResult::Invalid => { return Err(ClientError::BadJustification( "invalid signature for precommit in grandpa justification".to_string(), - )), - pezsp_consensus_grandpa::SignatureResult::OutdatedSet => - return Err(ClientError::OutdatedJustification), + )) + }, + pezsp_consensus_grandpa::SignatureResult::OutdatedSet => { + return Err(ClientError::OutdatedJustification) + }, pezsp_consensus_grandpa::SignatureResult::Valid => {}, } @@ -236,10 +238,11 @@ impl GrandpaJustification { visited_hashes.insert(hash); } }, - _ => + _ => { return Err(ClientError::BadJustification( "invalid precommit ancestry proof in grandpa justification".to_string(), - )), + )) + }, } } diff --git a/bizinikiwi/client/consensus/grandpa/src/tests.rs b/bizinikiwi/client/consensus/grandpa/src/tests.rs index d401921a..4dd8291c 100644 --- a/bizinikiwi/client/consensus/grandpa/src/tests.rs +++ b/bizinikiwi/client/consensus/grandpa/src/tests.rs @@ -1231,8 +1231,8 @@ async fn voter_persists_its_votes() { Pin::new(&mut *round_tx.lock()) .start_send(finality_grandpa::Message::Prevote(prevote)) .unwrap(); - } else if state.compare_exchange(1, 2, Ordering::SeqCst, Ordering::SeqCst).unwrap() == - 1 + } else if state.compare_exchange(1, 2, Ordering::SeqCst, Ordering::SeqCst).unwrap() + == 1 { // the next message we receive should be our own prevote let prevote = match signed.message { @@ -1246,8 +1246,8 @@ async fn voter_persists_its_votes() { // after alice restarts it should send its previous prevote // therefore we won't ever receive it again since it will be a // known message on the gossip layer - } else if state.compare_exchange(2, 3, Ordering::SeqCst, Ordering::SeqCst).unwrap() == - 2 + } else if state.compare_exchange(2, 3, Ordering::SeqCst, Ordering::SeqCst).unwrap() + == 2 { // we then receive a precommit from alice for block 15 // even though we casted a prevote for block 30 diff --git a/bizinikiwi/client/consensus/grandpa/src/until_imported.rs b/bizinikiwi/client/consensus/grandpa/src/until_imported.rs index af9d33d8..81edc5fd 100644 --- a/bizinikiwi/client/consensus/grandpa/src/until_imported.rs +++ b/bizinikiwi/client/consensus/grandpa/src/until_imported.rs @@ -940,8 +940,8 @@ mod tests { let block_sync_requests = block_sync_requester.requests.lock(); // we request blocks targeted by the precommits that aren't imported - if block_sync_requests.contains(&(h2.hash(), *h2.number())) && - block_sync_requests.contains(&(h3.hash(), *h3.number())) + if block_sync_requests.contains(&(h2.hash(), *h2.number())) + && block_sync_requests.contains(&(h3.hash(), *h3.number())) { return Poll::Ready(()); } diff --git a/bizinikiwi/client/consensus/grandpa/src/voting_rule.rs b/bizinikiwi/client/consensus/grandpa/src/voting_rule.rs index 2d04eb70..0a082aa8 100644 --- a/bizinikiwi/client/consensus/grandpa/src/voting_rule.rs +++ b/bizinikiwi/client/consensus/grandpa/src/voting_rule.rs @@ -236,8 +236,8 @@ where .await .filter(|(_, restricted_number)| { // NOTE: we can only restrict votes within the interval [base, target) - restricted_number >= base.number() && - restricted_number < restricted_target.number() + restricted_number >= base.number() + && restricted_number < restricted_target.number() }) .and_then(|(hash, _)| backend.header(hash).ok()) .and_then(std::convert::identity) diff --git a/bizinikiwi/client/consensus/manual-seal/src/consensus/babe.rs b/bizinikiwi/client/consensus/manual-seal/src/consensus/babe.rs index 1c93ce01..291eb90c 100644 --- a/bizinikiwi/client/consensus/manual-seal/src/consensus/babe.rs +++ b/bizinikiwi/client/consensus/manual-seal/src/consensus/babe.rs @@ -297,14 +297,15 @@ where // manually hard code epoch descriptor epoch_descriptor = match epoch_descriptor { - ViableEpochDescriptor::Signaled(identifier, _header) => + ViableEpochDescriptor::Signaled(identifier, _header) => { ViableEpochDescriptor::Signaled( identifier, EpochHeader { start_slot: slot, end_slot: (*slot * self.config.epoch_length).into(), }, - ), + ) + }, _ => unreachable!( "we're not in the authorities, so this isn't the genesis epoch; qed" ), diff --git a/bizinikiwi/client/consensus/manual-seal/src/seal_block.rs b/bizinikiwi/client/consensus/manual-seal/src/seal_block.rs index bf0717fb..e488edeb 100644 --- a/bizinikiwi/client/consensus/manual-seal/src/seal_block.rs +++ b/bizinikiwi/client/consensus/manual-seal/src/seal_block.rs @@ -96,8 +96,9 @@ pub async fn seal_block( // use the parent_hash supplied via `EngineCommand` // or fetch the best_block. let parent = match parent_hash { - Some(hash) => - client.header(hash)?.ok_or_else(|| Error::BlockNotFound(format!("{}", hash)))?, + Some(hash) => { + client.header(hash)?.ok_or_else(|| Error::BlockNotFound(format!("{}", hash)))? + }, None => select_chain.best_chain().await?, }; diff --git a/bizinikiwi/client/consensus/pow/src/lib.rs b/bizinikiwi/client/consensus/pow/src/lib.rs index 30d81464..93605526 100644 --- a/bizinikiwi/client/consensus/pow/src/lib.rs +++ b/bizinikiwi/client/consensus/pow/src/lib.rs @@ -285,8 +285,9 @@ where CheckInherentsError::CreateInherentData(e) => Error::CreateInherents(e), CheckInherentsError::Client(e) => Error::Client(e.into()), CheckInherentsError::CheckInherents(e) => Error::CheckInherents(e), - CheckInherentsError::CheckInherentsUnknownError(id) => - Error::CheckInherentsUnknownError(id), + CheckInherentsError::CheckInherentsUnknownError(id) => { + Error::CheckInherentsUnknownError(id) + }, })?; Ok(()) @@ -409,12 +410,13 @@ impl PowVerifier { let hash = header.hash(); let (seal, inner_seal) = match header.digest_mut().pop() { - Some(DigestItem::Seal(id, seal)) => + Some(DigestItem::Seal(id, seal)) => { if id == POW_ENGINE_ID { (DigestItem::Seal(id, seal.clone()), seal) } else { return Err(Error::WrongEngine(id)); - }, + } + }, _ => return Err(Error::HeaderUnsealed(hash)), }; @@ -646,8 +648,9 @@ fn find_pre_digest(header: &B::Header) -> Result>, Err for log in header.digest().logs() { trace!(target: LOG_TARGET, "Checking log {:?}, looking for pre runtime digest", log); match (log, pre_digest.is_some()) { - (DigestItem::PreRuntime(POW_ENGINE_ID, _), true) => - return Err(Error::MultiplePreRuntimeDigests), + (DigestItem::PreRuntime(POW_ENGINE_ID, _), true) => { + return Err(Error::MultiplePreRuntimeDigests) + }, (DigestItem::PreRuntime(POW_ENGINE_ID, v), false) => { pre_digest = Some(v.clone()); }, @@ -661,12 +664,13 @@ fn find_pre_digest(header: &B::Header) -> Result>, Err /// Fetch PoW seal. fn fetch_seal(digest: Option<&DigestItem>, hash: B::Hash) -> Result, Error> { match digest { - Some(DigestItem::Seal(id, seal)) => + Some(DigestItem::Seal(id, seal)) => { if id == &POW_ENGINE_ID { Ok(seal.clone()) } else { Err(Error::::WrongEngine(*id)) - }, + } + }, _ => Err(Error::::HeaderUnsealed(hash)), } } diff --git a/bizinikiwi/client/consensus/slots/src/lib.rs b/bizinikiwi/client/consensus/slots/src/lib.rs index 9e5b2449..f0bf1f2f 100644 --- a/bizinikiwi/client/consensus/slots/src/lib.rs +++ b/bizinikiwi/client/consensus/slots/src/lib.rs @@ -335,9 +335,9 @@ pub trait SimpleSlotWorker { let authorities_len = self.authorities_len(&aux_data); - if !self.force_authoring() && - self.sync_oracle().is_offline() && - authorities_len.map(|a| a > 1).unwrap_or(false) + if !self.force_authoring() + && self.sync_oracle().is_offline() + && authorities_len.map(|a| a > 1).unwrap_or(false) { debug!(target: logging_target, "Skipping proposal slot. Waiting for the network."); telemetry!( diff --git a/bizinikiwi/client/db/src/lib.rs b/bizinikiwi/client/db/src/lib.rs index 5551ba04..e64a37e5 100644 --- a/bizinikiwi/client/db/src/lib.rs +++ b/bizinikiwi/client/db/src/lib.rs @@ -598,10 +598,11 @@ impl BlockchainDb { )? { Some(justifications) => match Decode::decode(&mut &justifications[..]) { Ok(justifications) => Ok(Some(justifications)), - Err(err) => + Err(err) => { return Err(pezsp_blockchain::Error::Backend(format!( "Error decoding justifications: {err}" - ))), + ))) + }, }, None => Ok(None), } @@ -614,10 +615,11 @@ impl BlockchainDb { // Plain body match Decode::decode(&mut &body[..]) { Ok(body) => return Ok(Some(body)), - Err(err) => + Err(err) => { return Err(pezsp_blockchain::Error::Backend(format!( "Error decoding body: {err}" - ))), + ))) + }, } } @@ -646,10 +648,11 @@ impl BlockchainDb { )?; body.push(ex); }, - None => + None => { return Err(pezsp_blockchain::Error::Backend(format!( "Missing indexed transaction {hash:?}" - ))), + ))) + }, }; }, DbExtrinsic::Full(ex) => { @@ -659,10 +662,11 @@ impl BlockchainDb { } return Ok(Some(body)); }, - Err(err) => + Err(err) => { return Err(pezsp_blockchain::Error::Backend(format!( "Error decoding body list: {err}", - ))), + ))) + }, } } Ok(None) @@ -777,17 +781,19 @@ impl pezsc_client_api::blockchain::Backend for BlockchainD if let DbExtrinsic::Indexed { hash, .. } = ex { match self.db.get(columns::TRANSACTION, hash.as_ref()) { Some(t) => transactions.push(t), - None => + None => { return Err(pezsp_blockchain::Error::Backend(format!( "Missing indexed transaction {hash:?}", - ))), + ))) + }, } } } Ok(Some(transactions)) }, - Err(err) => - Err(pezsp_blockchain::Error::Backend(format!("Error decoding body list: {err}"))), + Err(err) => { + Err(pezsp_blockchain::Error::Backend(format!("Error decoding body list: {err}"))) + }, } } } @@ -851,8 +857,9 @@ impl BlockImportOperation { count += 1; let key = crate::offchain::concatenate_prefix_and_key(&prefix, &key); match value_operation { - OffchainOverlayedChange::SetValue(val) => - transaction.set_from_vec(columns::OFFCHAIN, &key, val), + OffchainOverlayedChange::SetValue(val) => { + transaction.set_from_vec(columns::OFFCHAIN, &key, val) + }, OffchainOverlayedChange::Remove => transaction.remove(columns::OFFCHAIN, &key), } } @@ -1275,9 +1282,9 @@ impl Backend { // Older DB versions have no last state key. Check if the state is available and set it. let info = backend.blockchain.info(); - if info.finalized_state.is_none() && - info.finalized_hash != Default::default() && - pezsc_client_api::Backend::have_state_at( + if info.finalized_state.is_none() + && info.finalized_hash != Default::default() + && pezsc_client_api::Backend::have_state_at( &backend, info.finalized_hash, info.finalized_number, @@ -1316,8 +1323,8 @@ impl Backend { let meta = self.blockchain.meta.read(); - if meta.best_number.saturating_sub(best_number).saturated_into::() > - self.canonicalization_delay + if meta.best_number.saturating_sub(best_number).saturated_into::() + > self.canonicalization_delay { return Err(pezsp_blockchain::Error::SetHeadTooOld); } @@ -1377,8 +1384,8 @@ impl Backend { ) -> ClientResult<()> { let last_finalized = last_finalized.unwrap_or_else(|| self.blockchain.meta.read().finalized_hash); - if last_finalized != self.blockchain.meta.read().genesis_hash && - *header.parent_hash() != last_finalized + if last_finalized != self.blockchain.meta.read().genesis_hash + && *header.parent_hash() != last_finalized { return Err(pezsp_blockchain::Error::NonSequentialFinalization(format!( "Last finalized {last_finalized:?} not parent of {:?}", @@ -1649,8 +1656,8 @@ impl Backend { let finalized = number_u64 == 0 || pending_block.leaf_state.is_final(); finalized } else { - (number.is_zero() && last_finalized_num.is_zero()) || - pending_block.leaf_state.is_final() + (number.is_zero() && last_finalized_num.is_zero()) + || pending_block.leaf_state.is_final() }; let header = &pending_block.header; @@ -1732,7 +1739,7 @@ impl Backend { if let Some(mut gap) = block_gap { match gap.gap_type { - BlockGapType::MissingHeaderAndBody => + BlockGapType::MissingHeaderAndBody => { if number == gap.start { gap.start += One::one(); utils::insert_number_to_key_mapping( @@ -1751,7 +1758,8 @@ impl Backend { debug!(target: "db", "Update block gap. {block_gap:?}"); } block_gap_updated = true; - }, + } + }, BlockGapType::MissingBody => { // Gap increased when syncing the header chain during fast sync. if number == gap.end + One::one() && !existing_body { @@ -1782,8 +1790,8 @@ impl Backend { }, } } else if operation.create_gap { - if number > best_num + One::one() && - self.blockchain.header(parent_hash)?.is_none() + if number > best_num + One::one() + && self.blockchain.header(parent_hash)?.is_none() { let gap = BlockGap { start: best_num + One::one(), @@ -1793,9 +1801,9 @@ impl Backend { insert_new_gap(&mut transaction, gap, &mut block_gap); block_gap_updated = true; debug!(target: "db", "Detected block gap (warp sync) {block_gap:?}"); - } else if number == best_num + One::one() && - self.blockchain.header(parent_hash)?.is_some() && - !existing_body + } else if number == best_num + One::one() + && self.blockchain.header(parent_hash)?.is_some() + && !existing_body { let gap = BlockGap { start: number, @@ -1893,8 +1901,8 @@ impl Backend { LastCanonicalized::NotCanonicalizing => false, }; - if requires_canonicalization && - pezsc_client_api::Backend::have_state_at(self, f_hash, f_num) + if requires_canonicalization + && pezsc_client_api::Backend::have_state_at(self, f_hash, f_num) { let commit = self.storage.state_db.canonicalize_block(&f_hash).map_err( pezsp_blockchain::Error::from_state_db::< @@ -2000,16 +2008,18 @@ impl Backend { id, )?; match Vec::>::decode(&mut &index[..]) { - Ok(index) => + Ok(index) => { for ex in index { if let DbExtrinsic::Indexed { hash, .. } = ex { transaction.release(columns::TRANSACTION, hash); } - }, - Err(err) => + } + }, + Err(err) => { return Err(pezsp_blockchain::Error::Backend(format!( "Error decoding body list: {err}", - ))), + ))) + }, } } Ok(()) @@ -2234,8 +2244,8 @@ impl pezsc_client_api::backend::Backend for Backend let last_finalized = self.blockchain.last_finalized()?; // We can do a quick check first, before doing a proper but more expensive check - if number > self.blockchain.info().finalized_number || - (hash != last_finalized && !is_descendent_of(&hash, &last_finalized)?) + if number > self.blockchain.info().finalized_number + || (hash != last_finalized && !is_descendent_of(&hash, &last_finalized)?) { return Err(ClientError::NotInFinalizedChain); } @@ -2370,8 +2380,8 @@ impl pezsc_client_api::backend::Backend for Backend reverted_finalized.insert(removed_hash); if let Some((hash, _)) = self.blockchain.info().finalized_state { if hash == hash_to_revert { - if !number_to_revert.is_zero() && - self.have_state_at(prev_hash, prev_number) + if !number_to_revert.is_zero() + && self.have_state_at(prev_hash, prev_number) { let lookup_key = utils::number_and_hash_to_lookup_key( prev_number, diff --git a/bizinikiwi/client/db/src/parity_db.rs b/bizinikiwi/client/db/src/parity_db.rs index 2a757658..0bae8207 100644 --- a/bizinikiwi/client/db/src/parity_db.rs +++ b/bizinikiwi/client/db/src/parity_db.rs @@ -97,7 +97,7 @@ impl> Database for DbAdapter { Some(match change { Change::Set(col, key, value) => (col as u8, key, Some(value)), Change::Remove(col, key) => (col as u8, key, None), - Change::Store(col, key, value) => + Change::Store(col, key, value) => { if ref_counted_column(col) { (col as u8, key.as_ref().to_vec(), Some(value)) } else { @@ -105,7 +105,8 @@ impl> Database for DbAdapter { not_ref_counted_column.push(col); } return None; - }, + } + }, Change::Reference(col, key) => { if ref_counted_column(col) { // FIXME accessing value is not strictly needed, optimize this in parity-db. @@ -118,7 +119,7 @@ impl> Database for DbAdapter { return None; } }, - Change::Release(col, key) => + Change::Release(col, key) => { if ref_counted_column(col) { (col as u8, key.as_ref().to_vec(), None) } else { @@ -126,7 +127,8 @@ impl> Database for DbAdapter { not_ref_counted_column.push(col); } return None; - }, + } + }, }) })); diff --git a/bizinikiwi/client/db/src/upgrade.rs b/bizinikiwi/client/db/src/upgrade.rs index 2d29cc0a..5a105861 100644 --- a/bizinikiwi/client/db/src/upgrade.rs +++ b/bizinikiwi/client/db/src/upgrade.rs @@ -163,8 +163,9 @@ fn migrate_3_to_4(db_path: &Path, _db_type: DatabaseType) -> Upgr /// If the file does not exist returns 0. fn current_version(path: &Path) -> UpgradeResult { match fs::File::open(version_file_path(path)) { - Err(ref err) if err.kind() == ErrorKind::NotFound => - Err(UpgradeError::MissingDatabaseVersionFile), + Err(ref err) if err.kind() == ErrorKind::NotFound => { + Err(UpgradeError::MissingDatabaseVersionFile) + }, Err(_) => Err(UpgradeError::UnknownDatabaseVersion), Ok(mut file) => { let mut s = String::new(); diff --git a/bizinikiwi/client/db/src/utils.rs b/bizinikiwi/client/db/src/utils.rs index 35df49dd..ff6687e4 100644 --- a/bizinikiwi/client/db/src/utils.rs +++ b/bizinikiwi/client/db/src/utils.rs @@ -202,8 +202,9 @@ fn open_database_at( let db: Arc> = match &db_source { DatabaseSource::ParityDb { path } => open_parity_db::(path, db_type, create)?, #[cfg(feature = "rocksdb")] - DatabaseSource::RocksDb { path, cache_size } => - open_kvdb_rocksdb::(path, db_type, create, *cache_size)?, + DatabaseSource::RocksDb { path, cache_size } => { + open_kvdb_rocksdb::(path, db_type, create, *cache_size)? + }, DatabaseSource::Custom { db, require_create_flag } => { if *require_create_flag && !create { return Err(OpenDbError::DoesNotExist); @@ -214,8 +215,9 @@ fn open_database_at( // check if rocksdb exists first, if not, open paritydb match open_kvdb_rocksdb::(rocksdb_path, db_type, false, *cache_size) { Ok(db) => db, - Err(OpenDbError::NotEnabled(_)) | Err(OpenDbError::DoesNotExist) => - open_parity_db::(paritydb_path, db_type, create)?, + Err(OpenDbError::NotEnabled(_)) | Err(OpenDbError::DoesNotExist) => { + open_parity_db::(paritydb_path, db_type, create)? + }, Err(as_is) => return Err(as_is), } }, @@ -368,13 +370,14 @@ pub fn check_database_type( db_type: DatabaseType, ) -> Result<(), OpenDbError> { match db.get(COLUMN_META, meta_keys::TYPE) { - Some(stored_type) => + Some(stored_type) => { if db_type.as_str().as_bytes() != &*stored_type { return Err(OpenDbError::UnexpectedDbType { expected: db_type, found: stored_type.to_owned(), }); - }, + } + }, None => { let mut transaction = Transaction::new(); transaction.set(COLUMN_META, meta_keys::TYPE, db_type.as_str().as_bytes()); @@ -396,8 +399,8 @@ fn maybe_migrate_to_type_subdir( // Do we have to migrate to a database-type-based subdirectory layout: // See if there's a file identifying a rocksdb or paritydb folder in the parent dir and // the target path ends in a role specific directory - if (basedir.join("db_version").exists() || basedir.join("metadata").exists()) && - (p.ends_with(DatabaseType::Full.as_str())) + if (basedir.join("db_version").exists() || basedir.join("metadata").exists()) + && (p.ends_with(DatabaseType::Full.as_str())) { // Try to open the database to check if the current `DatabaseType` matches the type of // database stored in the target directory and close the database on success. @@ -487,7 +490,7 @@ where { let genesis_hash: Block::Hash = match read_genesis_hash(db)? { Some(genesis_hash) => genesis_hash, - None => + None => { return Ok(Meta { best_hash: Default::default(), best_number: Zero::zero(), @@ -496,7 +499,8 @@ where genesis_hash: Default::default(), finalized_state: None, block_gap: None, - }), + }) + }, }; let load_meta_block = |desc, key| -> Result<_, pezsp_blockchain::Error> { @@ -546,10 +550,11 @@ where BLOCK_GAP_CURRENT_VERSION => db .get(COLUMN_META, meta_keys::BLOCK_GAP) .and_then(|d| Decode::decode(&mut d.as_slice()).ok()), - v => + v => { return Err(pezsp_blockchain::Error::Backend(format!( "Unsupported block gap DB version: {v}" - ))), + ))) + }, }, }; debug!(target: "db", "block_gap={:?}", block_gap); diff --git a/bizinikiwi/client/executor/common/src/runtime_blob/runtime_blob.rs b/bizinikiwi/client/executor/common/src/runtime_blob/runtime_blob.rs index ca9db8f0..28c96c46 100644 --- a/bizinikiwi/client/executor/common/src/runtime_blob/runtime_blob.rs +++ b/bizinikiwi/client/executor/common/src/runtime_blob/runtime_blob.rs @@ -191,8 +191,9 @@ impl RuntimeBlob { /// Consumes this runtime blob and serializes it. pub fn serialize(self) -> Vec { match self.0 { - BlobKind::WebAssembly(raw_module) => - serialize(raw_module).expect("serializing into a vec should succeed; qed"), + BlobKind::WebAssembly(raw_module) => { + serialize(raw_module).expect("serializing into a vec should succeed; qed") + }, BlobKind::PolkaVM(ref blob) => blob.1.to_vec(), } } diff --git a/bizinikiwi/client/executor/polkavm/src/lib.rs b/bizinikiwi/client/executor/polkavm/src/lib.rs index 50a65f1d..6c0d2f64 100644 --- a/bizinikiwi/client/executor/polkavm/src/lib.rs +++ b/bizinikiwi/client/executor/polkavm/src/lib.rs @@ -45,11 +45,12 @@ impl WasmInstance for Instance { ) -> (Result, Error>, Option) { let pc = match self.0.module().exports().find(|e| e.symbol() == name) { Some(export) => export.program_counter(), - None => + None => { return ( Err(format!("cannot call into the runtime: export not found: '{name}'").into()), None, - ), + ) + }, }; let Ok(raw_data_length) = u32::try_from(raw_data.len()) else { @@ -93,21 +94,24 @@ impl WasmInstance for Instance { match self.0.call_typed(&mut (), pc, (data_pointer, raw_data_length)) { Ok(()) => {}, - Err(CallError::Trap) => + Err(CallError::Trap) => { return ( Err(format!("call into the runtime method '{name}' failed: trap").into()), None, - ), - Err(CallError::Error(err)) => + ) + }, + Err(CallError::Error(err)) => { return ( Err(format!("call into the runtime method '{name}' failed: {err}").into()), None, - ), - Err(CallError::User(err)) => + ) + }, + Err(CallError::User(err)) => { return ( Err(format!("call into the runtime method '{name}' failed: {err}").into()), None, - ), + ) + }, Err(CallError::NotEnoughGas) => unreachable!("gas metering is never enabled"), Err(CallError::Step) => unreachable!("stepping is never enabled"), }; @@ -190,7 +194,7 @@ fn call_host_function(caller: &mut Caller<()>, function: &dyn Function) -> Resul args[nth_arg] = Value::F32(caller.instance.reg(Reg::ARG_REGS[nth_reg]) as u32); nth_reg += 1; }, - ValueType::I64 => + ValueType::I64 => { if caller.instance.is_64_bit() { args[nth_arg] = Value::I64(caller.instance.reg(Reg::ARG_REGS[nth_reg]) as i64); nth_reg += 1; @@ -203,8 +207,9 @@ fn call_host_function(caller: &mut Caller<()>, function: &dyn Function) -> Resul args[nth_arg] = Value::I64((u64::from(value_lo) | (u64::from(value_hi) << 32)) as i64); - }, - ValueType::F64 => + } + }, + ValueType::F64 => { if caller.instance.is_64_bit() { args[nth_arg] = Value::F64(caller.instance.reg(Reg::ARG_REGS[nth_reg])); nth_reg += 1; @@ -216,7 +221,8 @@ fn call_host_function(caller: &mut Caller<()>, function: &dyn Function) -> Resul nth_reg += 1; args[nth_arg] = Value::F64(u64::from(value_lo) | (u64::from(value_hi) << 32)); - }, + } + }, } } @@ -244,20 +250,22 @@ fn call_host_function(caller: &mut Caller<()>, function: &dyn Function) -> Resul Value::F32(value) => { caller.instance.set_reg(Reg::A0, value as u64); }, - Value::I64(value) => + Value::I64(value) => { if caller.instance.is_64_bit() { caller.instance.set_reg(Reg::A0, value as u64); } else { caller.instance.set_reg(Reg::A0, value as u64); caller.instance.set_reg(Reg::A1, (value >> 32) as u64); - }, - Value::F64(value) => + } + }, + Value::F64(value) => { if caller.instance.is_64_bit() { caller.instance.set_reg(Reg::A0, value as u64); } else { caller.instance.set_reg(Reg::A0, value as u64); caller.instance.set_reg(Reg::A1, (value >> 32) as u64); - }, + } + }, } } diff --git a/bizinikiwi/client/executor/src/integration_tests/mod.rs b/bizinikiwi/client/executor/src/integration_tests/mod.rs index 556d6fd1..0684fdb9 100644 --- a/bizinikiwi/client/executor/src/integration_tests/mod.rs +++ b/bizinikiwi/client/executor/src/integration_tests/mod.rs @@ -119,8 +119,9 @@ fn call_not_existing_function(wasm_method: WasmExecutionMethod) { match call_in_wasm("test_calling_missing_external", &[], wasm_method, &mut ext).unwrap_err() { Error::AbortedDueToTrap(error) => { let expected = match wasm_method { - WasmExecutionMethod::Compiled { .. } => - "call to a missing function env:missing_external", + WasmExecutionMethod::Compiled { .. } => { + "call to a missing function env:missing_external" + }, }; assert_eq!(error.message, expected); }, @@ -138,8 +139,9 @@ fn call_yet_another_not_existing_function(wasm_method: WasmExecutionMethod) { { Error::AbortedDueToTrap(error) => { let expected = match wasm_method { - WasmExecutionMethod::Compiled { .. } => - "call to a missing function env:yet_another_missing_external", + WasmExecutionMethod::Compiled { .. } => { + "call to a missing function env:yet_another_missing_external" + }, }; assert_eq!(error.message, expected); }, @@ -728,8 +730,9 @@ fn unreachable_intrinsic(wasm_method: WasmExecutionMethod) { match call_in_wasm("test_unreachable_intrinsic", &[], wasm_method, &mut ext).unwrap_err() { Error::AbortedDueToTrap(error) => { let expected = match wasm_method { - WasmExecutionMethod::Compiled { .. } => - "wasm trap: wasm `unreachable` instruction executed", + WasmExecutionMethod::Compiled { .. } => { + "wasm trap: wasm `unreachable` instruction executed" + }, }; assert_eq!(error.message, expected); }, diff --git a/bizinikiwi/client/executor/src/wasm_runtime.rs b/bizinikiwi/client/executor/src/wasm_runtime.rs index de5df3d0..4167d32b 100644 --- a/bizinikiwi/client/executor/src/wasm_runtime.rs +++ b/bizinikiwi/client/executor/src/wasm_runtime.rs @@ -303,7 +303,7 @@ where } match wasm_method { - WasmExecutionMethod::Compiled { instantiation_strategy } => + WasmExecutionMethod::Compiled { instantiation_strategy } => { pezsc_executor_wasmtime::create_runtime::( blob, pezsc_executor_wasmtime::Config { @@ -322,7 +322,8 @@ where }, }, ) - .map(|runtime| -> Box { Box::new(runtime) }), + .map(|runtime| -> Box { Box::new(runtime) }) + }, } } diff --git a/bizinikiwi/client/executor/wasmtime/src/imports.rs b/bizinikiwi/client/executor/wasmtime/src/imports.rs index 8f806116..a9eb433d 100644 --- a/bizinikiwi/client/executor/wasmtime/src/imports.rs +++ b/bizinikiwi/client/executor/wasmtime/src/imports.rs @@ -48,12 +48,13 @@ where ExternType::Func(func_ty) => { pending_func_imports.insert(name.to_owned(), (import_ty, func_ty)); }, - _ => + _ => { return Err(WasmError::Other(format!( "host doesn't provide any non function imports: {}:{}", import_ty.module(), name, - ))), + ))) + }, }; } diff --git a/bizinikiwi/client/executor/wasmtime/src/runtime.rs b/bizinikiwi/client/executor/wasmtime/src/runtime.rs index 2f30fed5..c2c91454 100644 --- a/bizinikiwi/client/executor/wasmtime/src/runtime.rs +++ b/bizinikiwi/client/executor/wasmtime/src/runtime.rs @@ -274,8 +274,9 @@ fn common_config(semantics: &Semantics) -> std::result::Result - maximum_pages.map(|p| p as u64 * WASM_PAGE_SIZE).unwrap_or(u64::MAX), + HeapAllocStrategy::Dynamic { maximum_pages } => { + maximum_pages.map(|p| p as u64 * WASM_PAGE_SIZE).unwrap_or(u64::MAX) + }, HeapAllocStrategy::Static { .. } => u64::MAX, }); @@ -283,8 +284,9 @@ fn common_config(semantics: &Semantics) -> std::result::Result - maximum_pages.map(|p| p as u64).unwrap_or(MAX_WASM_PAGES), + HeapAllocStrategy::Dynamic { maximum_pages } => { + maximum_pages.map(|p| p as u64).unwrap_or(MAX_WASM_PAGES) + }, HeapAllocStrategy::Static { .. } => MAX_WASM_PAGES, }; @@ -579,11 +581,12 @@ where .map_err(|e| WasmError::Other(format!("cannot create module: {:#}", e)))?; match config.semantics.instantiation_strategy { - InstantiationStrategy::Pooling | - InstantiationStrategy::PoolingCopyOnWrite | - InstantiationStrategy::RecreateInstance | - InstantiationStrategy::RecreateInstanceCopyOnWrite => - (module, InternalInstantiationStrategy::Builtin), + InstantiationStrategy::Pooling + | InstantiationStrategy::PoolingCopyOnWrite + | InstantiationStrategy::RecreateInstance + | InstantiationStrategy::RecreateInstanceCopyOnWrite => { + (module, InternalInstantiationStrategy::Builtin) + }, } }, CodeSupplyMode::Precompiled(compiled_artifact_path) => { diff --git a/bizinikiwi/client/executor/wasmtime/src/util.rs b/bizinikiwi/client/executor/wasmtime/src/util.rs index 3dd52f03..4c033371 100644 --- a/bizinikiwi/client/executor/wasmtime/src/util.rs +++ b/bizinikiwi/client/executor/wasmtime/src/util.rs @@ -116,8 +116,9 @@ pub(crate) fn replace_strategy_if_broken(strategy: &mut InstantiationStrategy) { // These strategies require a working `madvise` to be sound. InstantiationStrategy::PoolingCopyOnWrite => InstantiationStrategy::Pooling, - InstantiationStrategy::RecreateInstanceCopyOnWrite => - InstantiationStrategy::RecreateInstance, + InstantiationStrategy::RecreateInstanceCopyOnWrite => { + InstantiationStrategy::RecreateInstance + }, }; use std::sync::OnceLock; diff --git a/bizinikiwi/client/informant/src/display.rs b/bizinikiwi/client/informant/src/display.rs index bfa0053b..11c6d74b 100644 --- a/bizinikiwi/client/informant/src/display.rs +++ b/bizinikiwi/client/informant/src/display.rs @@ -106,6 +106,7 @@ impl InformantDisplay { // Handle all phases besides the two phases we already handle above. (_, _, Some(warp)) if !matches!(warp.phase, WarpSyncPhase::DownloadingBlocks(_)) => + { ( "⏩", "Warping".into(), @@ -114,7 +115,8 @@ impl InformantDisplay { warp.phase, (warp.total_bytes as f32) / (1024f32 * 1024f32) ), - ), + ) + }, (_, Some(state), _) => ( "⚙️ ", "State sync".into(), @@ -126,10 +128,12 @@ impl InformantDisplay { ), ), (SyncState::Idle, _, _) => ("💤", "Idle".into(), "".into()), - (SyncState::Downloading { target }, _, _) => - ("⚙️ ", format!("Syncing{}", speed), format!(", target=#{target}")), - (SyncState::Importing { target }, _, _) => - ("⚙️ ", format!("Preparing{}", speed), format!(", target=#{target}")), + (SyncState::Downloading { target }, _, _) => { + ("⚙️ ", format!("Syncing{}", speed), format!(", target=#{target}")) + }, + (SyncState::Importing { target }, _, _) => { + ("⚙️ ", format!("Preparing{}", speed), format!(", target=#{target}")) + }, }; info!( @@ -176,8 +180,8 @@ fn speed( let speed = diff .saturating_mul(10_000) .checked_div(u128::from(elapsed_ms)) - .map_or(0.0, |s| s as f64) / - 10.0; + .map_or(0.0, |s| s as f64) + / 10.0; format!(" {:4.1} bps", speed) } else { // If the number of blocks can't be converted to a regular integer, then we need a more diff --git a/bizinikiwi/client/keystore/src/lib.rs b/bizinikiwi/client/keystore/src/lib.rs index 97720082..0586ca4d 100644 --- a/bizinikiwi/client/keystore/src/lib.rs +++ b/bizinikiwi/client/keystore/src/lib.rs @@ -64,8 +64,9 @@ impl From for TraitError { fn from(error: Error) -> Self { match error { Error::KeyNotSupported(id) => TraitError::KeyNotSupported(id), - Error::InvalidSeed | Error::InvalidPhrase | Error::PublicKeyMismatch => - TraitError::ValidationError(error.to_string()), + Error::InvalidSeed | Error::InvalidPhrase | Error::PublicKeyMismatch => { + TraitError::ValidationError(error.to_string()) + }, Error::Unavailable => TraitError::Unavailable, Error::Io(e) => TraitError::Other(e.to_string()), Error::Json(e) => TraitError::Other(e.to_string()), diff --git a/bizinikiwi/client/merkle-mountain-range/rpc/src/lib.rs b/bizinikiwi/client/merkle-mountain-range/rpc/src/lib.rs index 72181d5f..3d59e679 100644 --- a/bizinikiwi/client/merkle-mountain-range/rpc/src/lib.rs +++ b/bizinikiwi/client/merkle-mountain-range/rpc/src/lib.rs @@ -270,8 +270,8 @@ where /// Converts an mmr-specific error into a [`CallError`]. fn mmr_error_into_rpc_error(err: MmrError) -> ErrorObjectOwned { - let error_code = MMR_ERROR + - match err { + let error_code = MMR_ERROR + + match err { MmrError::LeafNotFound => 1, MmrError::GenerateProof => 2, MmrError::Verify => 3, diff --git a/bizinikiwi/client/merkle-mountain-range/src/aux_schema.rs b/bizinikiwi/client/merkle-mountain-range/src/aux_schema.rs index 6e7e60bb..1070261b 100644 --- a/bizinikiwi/client/merkle-mountain-range/src/aux_schema.rs +++ b/bizinikiwi/client/merkle-mountain-range/src/aux_schema.rs @@ -65,8 +65,12 @@ where match version { None => (), Some(1) => return load_decode::<_, PersistedState>(backend, GADGET_STATE), - other => - return Err(ClientError::Backend(format!("Unsupported MMR aux DB version: {:?}", other))), + other => { + return Err(ClientError::Backend(format!( + "Unsupported MMR aux DB version: {:?}", + other + ))) + }, } // No persistent state found in DB. diff --git a/bizinikiwi/client/merkle-mountain-range/src/test_utils.rs b/bizinikiwi/client/merkle-mountain-range/src/test_utils.rs index 5f792226..4c20bb60 100644 --- a/bizinikiwi/client/merkle-mountain-range/src/test_utils.rs +++ b/bizinikiwi/client/merkle-mountain-range/src/test_utils.rs @@ -94,8 +94,9 @@ impl MmrBlock { node, self.parent_hash(), ), - OffchainKeyType::Canon => - NodesUtils::node_canon_offchain_key(MockRuntimeApi::INDEXING_PREFIX, node), + OffchainKeyType::Canon => { + NodesUtils::node_canon_offchain_key(MockRuntimeApi::INDEXING_PREFIX, node) + }, } } } diff --git a/bizinikiwi/client/mixnet/src/maybe_inf_delay.rs b/bizinikiwi/client/mixnet/src/maybe_inf_delay.rs index 71e69ddb..95f3f813 100644 --- a/bizinikiwi/client/mixnet/src/maybe_inf_delay.rs +++ b/bizinikiwi/client/mixnet/src/maybe_inf_delay.rs @@ -78,14 +78,15 @@ impl MaybeInfDelay { }, Inner::Finite(delay) => delay.reset(duration), }, - None => + None => { self.0 = match std::mem::replace( &mut self.0, Inner::Infinite { waker: None, delay: None }, ) { Inner::Finite(delay) => Inner::Infinite { waker: None, delay: Some(delay) }, infinite => infinite, - }, + } + }, } } } diff --git a/bizinikiwi/client/mixnet/src/request.rs b/bizinikiwi/client/mixnet/src/request.rs index 56d9f4c3..f845ec66 100644 --- a/bizinikiwi/client/mixnet/src/request.rs +++ b/bizinikiwi/client/mixnet/src/request.rs @@ -92,8 +92,9 @@ impl mixnet::request_manager::Request for Request { fn with_data(&self, f: impl FnOnce(Scattered) -> T, _context: &Self::Context) -> T { match self { - Request::SubmitExtrinsic { extrinsic, .. } => - f([&[SUBMIT_EXTRINSIC][..], extrinsic.0.as_slice()].as_slice().into()), + Request::SubmitExtrinsic { extrinsic, .. } => { + f([&[SUBMIT_EXTRINSIC][..], extrinsic.0.as_slice()].as_slice().into()) + }, } } diff --git a/bizinikiwi/client/network-gossip/src/bridge.rs b/bizinikiwi/client/network-gossip/src/bridge.rs index 72bd4c8d..af89db10 100644 --- a/bizinikiwi/client/network-gossip/src/bridge.rs +++ b/bizinikiwi/client/network-gossip/src/bridge.rs @@ -220,7 +220,7 @@ impl Future for GossipEngine { }, NotificationEvent::NotificationStreamOpened { peer, handshake, .. - } => + } => { if let Some(role) = this.network.peer_role(peer, handshake) { this.state_machine.new_peer( &mut this.notification_service, @@ -229,7 +229,8 @@ impl Future for GossipEngine { ); } else { log::debug!(target: "gossip", "role for {peer} couldn't be determined"); - }, + } + }, NotificationEvent::NotificationStreamClosed { peer } => { this.state_machine .peer_disconnected(&mut this.notification_service, peer); @@ -254,10 +255,12 @@ impl Future for GossipEngine { match sync_event_stream { Poll::Ready(Some(event)) => match event { - SyncEvent::PeerConnected(remote) => - this.network.add_set_reserved(remote, this.protocol.clone()), - SyncEvent::PeerDisconnected(remote) => - this.network.remove_set_reserved(remote, this.protocol.clone()), + SyncEvent::PeerConnected(remote) => { + this.network.add_set_reserved(remote, this.protocol.clone()) + }, + SyncEvent::PeerDisconnected(remote) => { + this.network.remove_set_reserved(remote, this.protocol.clone()) + }, }, // The sync event stream closed. Do the same for [`GossipValidator`]. Poll::Ready(None) => { diff --git a/bizinikiwi/client/network-gossip/src/state_machine.rs b/bizinikiwi/client/network-gossip/src/state_machine.rs index f9a09acd..13172e12 100644 --- a/bizinikiwi/client/network-gossip/src/state_machine.rs +++ b/bizinikiwi/client/network-gossip/src/state_machine.rs @@ -116,12 +116,13 @@ where for (id, ref mut peer) in peers.iter_mut() { for (message_hash, topic, message) in messages.clone() { let intent = match intent { - MessageIntent::Broadcast { .. } => + MessageIntent::Broadcast { .. } => { if peer.known_messages.contains(message_hash) { continue; } else { MessageIntent::Broadcast - }, + } + }, MessageIntent::PeriodicRebroadcast => { if peer.known_messages.contains(message_hash) { MessageIntent::PeriodicRebroadcast diff --git a/bizinikiwi/client/network/light/src/light_client_requests/handler.rs b/bizinikiwi/client/network/light/src/light_client_requests/handler.rs index 83f29c31..ee3ab0be 100644 --- a/bizinikiwi/client/network/light/src/light_client_requests/handler.rs +++ b/bizinikiwi/client/network/light/src/light_client_requests/handler.rs @@ -149,14 +149,18 @@ where let request = schema::v1::light::Request::decode(&payload[..])?; let response = match &request.request { - Some(schema::v1::light::request::Request::RemoteCallRequest(r)) => - self.on_remote_call_request(&peer, r)?, - Some(schema::v1::light::request::Request::RemoteReadRequest(r)) => - self.on_remote_read_request(&peer, r)?, - Some(schema::v1::light::request::Request::RemoteReadChildRequest(r)) => - self.on_remote_read_child_request(&peer, r)?, - None => - return Err(HandleRequestError::BadRequest("Remote request without request data.")), + Some(schema::v1::light::request::Request::RemoteCallRequest(r)) => { + self.on_remote_call_request(&peer, r)? + }, + Some(schema::v1::light::request::Request::RemoteReadRequest(r)) => { + self.on_remote_read_request(&peer, r)? + }, + Some(schema::v1::light::request::Request::RemoteReadChildRequest(r)) => { + self.on_remote_read_child_request(&peer, r)? + }, + None => { + return Err(HandleRequestError::BadRequest("Remote request without request data.")) + }, }; let mut data = Vec::new(); diff --git a/bizinikiwi/client/network/src/behaviour.rs b/bizinikiwi/client/network/src/behaviour.rs index 03ed397f..485fe799 100644 --- a/bizinikiwi/client/network/src/behaviour.rs +++ b/bizinikiwi/client/network/src/behaviour.rs @@ -360,10 +360,12 @@ impl From for BehaviourOut { set_id, notifications_sink, } => BehaviourOut::NotificationStreamReplaced { remote, set_id, notifications_sink }, - CustomMessageOutcome::NotificationStreamClosed { remote, set_id } => - BehaviourOut::NotificationStreamClosed { remote, set_id }, - CustomMessageOutcome::NotificationsReceived { remote, set_id, notification } => - BehaviourOut::NotificationsReceived { remote, set_id, notification }, + CustomMessageOutcome::NotificationStreamClosed { remote, set_id } => { + BehaviourOut::NotificationStreamClosed { remote, set_id } + }, + CustomMessageOutcome::NotificationsReceived { remote, set_id, notification } => { + BehaviourOut::NotificationsReceived { remote, set_id, notification } + }, } } } @@ -371,12 +373,15 @@ impl From for BehaviourOut { impl From for BehaviourOut { fn from(event: request_responses::Event) -> Self { match event { - request_responses::Event::InboundRequest { protocol, result, .. } => - BehaviourOut::InboundRequest { protocol, result }, - request_responses::Event::RequestFinished { protocol, duration, result, .. } => - BehaviourOut::RequestFinished { protocol, duration, result }, - request_responses::Event::ReputationChanges { peer, changes } => - BehaviourOut::ReputationChanges { peer, changes }, + request_responses::Event::InboundRequest { protocol, result, .. } => { + BehaviourOut::InboundRequest { protocol, result } + }, + request_responses::Event::RequestFinished { protocol, duration, result, .. } => { + BehaviourOut::RequestFinished { protocol, duration, result } + }, + request_responses::Event::ReputationChanges { peer, changes } => { + BehaviourOut::ReputationChanges { peer, changes } + }, } } } @@ -409,25 +414,33 @@ impl From for BehaviourOut { ), Some(duration), ), - DiscoveryOut::ClosestPeersNotFound(target, duration) => - BehaviourOut::Dht(DhtEvent::ClosestPeersNotFound(target.into()), Some(duration)), - DiscoveryOut::ValueFound(results, duration) => - BehaviourOut::Dht(DhtEvent::ValueFound(results.into()), Some(duration)), - DiscoveryOut::ValueNotFound(key, duration) => - BehaviourOut::Dht(DhtEvent::ValueNotFound(key.into()), Some(duration)), - DiscoveryOut::ValuePut(key, duration) => - BehaviourOut::Dht(DhtEvent::ValuePut(key.into()), Some(duration)), - DiscoveryOut::PutRecordRequest(record_key, record_value, publisher, expires) => + DiscoveryOut::ClosestPeersNotFound(target, duration) => { + BehaviourOut::Dht(DhtEvent::ClosestPeersNotFound(target.into()), Some(duration)) + }, + DiscoveryOut::ValueFound(results, duration) => { + BehaviourOut::Dht(DhtEvent::ValueFound(results.into()), Some(duration)) + }, + DiscoveryOut::ValueNotFound(key, duration) => { + BehaviourOut::Dht(DhtEvent::ValueNotFound(key.into()), Some(duration)) + }, + DiscoveryOut::ValuePut(key, duration) => { + BehaviourOut::Dht(DhtEvent::ValuePut(key.into()), Some(duration)) + }, + DiscoveryOut::PutRecordRequest(record_key, record_value, publisher, expires) => { BehaviourOut::Dht( DhtEvent::PutRecordRequest(record_key.into(), record_value, publisher, expires), None, - ), - DiscoveryOut::ValuePutFailed(key, duration) => - BehaviourOut::Dht(DhtEvent::ValuePutFailed(key.into()), Some(duration)), - DiscoveryOut::StartedProviding(key, duration) => - BehaviourOut::Dht(DhtEvent::StartedProviding(key.into()), Some(duration)), - DiscoveryOut::StartProvidingFailed(key, duration) => - BehaviourOut::Dht(DhtEvent::StartProvidingFailed(key.into()), Some(duration)), + ) + }, + DiscoveryOut::ValuePutFailed(key, duration) => { + BehaviourOut::Dht(DhtEvent::ValuePutFailed(key.into()), Some(duration)) + }, + DiscoveryOut::StartedProviding(key, duration) => { + BehaviourOut::Dht(DhtEvent::StartedProviding(key.into()), Some(duration)) + }, + DiscoveryOut::StartProvidingFailed(key, duration) => { + BehaviourOut::Dht(DhtEvent::StartProvidingFailed(key.into()), Some(duration)) + }, DiscoveryOut::ProvidersFound(key, providers, duration) => BehaviourOut::Dht( DhtEvent::ProvidersFound( key.into(), @@ -435,10 +448,12 @@ impl From for BehaviourOut { ), Some(duration), ), - DiscoveryOut::NoMoreProviders(key, duration) => - BehaviourOut::Dht(DhtEvent::NoMoreProviders(key.into()), Some(duration)), - DiscoveryOut::ProvidersNotFound(key, duration) => - BehaviourOut::Dht(DhtEvent::ProvidersNotFound(key.into()), Some(duration)), + DiscoveryOut::NoMoreProviders(key, duration) => { + BehaviourOut::Dht(DhtEvent::NoMoreProviders(key.into()), Some(duration)) + }, + DiscoveryOut::ProvidersNotFound(key, duration) => { + BehaviourOut::Dht(DhtEvent::ProvidersNotFound(key.into()), Some(duration)) + }, DiscoveryOut::RandomKademliaStarted => BehaviourOut::RandomKademliaStarted, } } diff --git a/bizinikiwi/client/network/src/bitswap/mod.rs b/bizinikiwi/client/network/src/bitswap/mod.rs index 0b65811c..092bd4d7 100644 --- a/bizinikiwi/client/network/src/bitswap/mod.rs +++ b/bizinikiwi/client/network/src/bitswap/mod.rs @@ -197,9 +197,9 @@ impl BitswapRequestHandler { }, }; - if cid.version() != cid::Version::V1 || - cid.hash().code() != u64::from(cid::multihash::Code::Blake2b256) || - cid.hash().size() != 32 + if cid.version() != cid::Version::V1 + || cid.hash().code() != u64::from(cid::multihash::Code::Blake2b256) + || cid.hash().size() != 32 { debug!(target: LOG_TARGET, "Ignoring unsupported CID {}: {}", peer, cid); continue; diff --git a/bizinikiwi/client/network/src/discovery.rs b/bizinikiwi/client/network/src/discovery.rs index 6511dbec..6c3c6a75 100644 --- a/bizinikiwi/client/network/src/discovery.rs +++ b/bizinikiwi/client/network/src/discovery.rs @@ -584,8 +584,9 @@ impl DiscoveryBehaviour { let ip = match addr.iter().next() { Some(Protocol::Ip4(ip)) => IpNetwork::from(ip), Some(Protocol::Ip6(ip)) => IpNetwork::from(ip), - Some(Protocol::Dns(_)) | Some(Protocol::Dns4(_)) | Some(Protocol::Dns6(_)) => - return true, + Some(Protocol::Dns(_)) | Some(Protocol::Dns4(_)) | Some(Protocol::Dns6(_)) => { + return true + }, _ => return false, }; ip.is_global() @@ -939,7 +940,7 @@ impl NetworkBehaviour for DiscoveryBehaviour { // We are not interested in this event at the moment. }, KademliaEvent::InboundRequest { request } => match request { - libp2p::kad::InboundRequest::PutRecord { record: Some(record), .. } => + libp2p::kad::InboundRequest::PutRecord { record: Some(record), .. } => { return Poll::Ready(ToSwarm::GenerateEvent( DiscoveryOut::PutRecordRequest( record.key, @@ -947,7 +948,8 @@ impl NetworkBehaviour for DiscoveryBehaviour { record.publisher.map(Into::into), record.expires, ), - )), + )) + }, _ => {}, }, KademliaEvent::OutboundQueryProgressed { @@ -1417,8 +1419,8 @@ mod tests { match e { SwarmEvent::Behaviour(behavior) => { match behavior { - DiscoveryOut::UnroutablePeer(other) | - DiscoveryOut::Discovered(other) => { + DiscoveryOut::UnroutablePeer(other) + | DiscoveryOut::Discovered(other) => { // Call `add_self_reported_address` to simulate identify // happening. let addr = swarms diff --git a/bizinikiwi/client/network/src/litep2p/discovery.rs b/bizinikiwi/client/network/src/litep2p/discovery.rs index 6e2c7a79..27d7af3d 100644 --- a/bizinikiwi/client/network/src/litep2p/discovery.rs +++ b/bizinikiwi/client/network/src/litep2p/discovery.rs @@ -507,8 +507,9 @@ impl Discovery { let ip = match address.iter().next() { Some(Protocol::Ip4(ip)) => IpNetwork::from(ip), Some(Protocol::Ip6(ip)) => IpNetwork::from(ip), - Some(Protocol::Dns(_)) | Some(Protocol::Dns4(_)) | Some(Protocol::Dns6(_)) => - return true, + Some(Protocol::Dns(_)) | Some(Protocol::Dns4(_)) | Some(Protocol::Dns6(_)) => { + return true + }, _ => return false, }; @@ -554,8 +555,8 @@ impl Discovery { } }, None => { - let oldest = (self.address_confirmations.len() >= - self.address_confirmations.limiter().max_length() as usize) + let oldest = (self.address_confirmations.len() + >= self.address_confirmations.limiter().max_length() as usize) .then(|| { self.address_confirmations.pop_oldest().map(|(address, peers)| { if peers.len() >= MIN_ADDRESS_CONFIRMATIONS { @@ -668,8 +669,9 @@ impl Stream for Discovery { record, })); }, - Poll::Ready(Some(KademliaEvent::PutRecordSuccess { query_id, key: _ })) => - return Poll::Ready(Some(DiscoveryEvent::PutRecordSuccess { query_id })), + Poll::Ready(Some(KademliaEvent::PutRecordSuccess { query_id, key: _ })) => { + return Poll::Ready(Some(DiscoveryEvent::PutRecordSuccess { query_id })) + }, Poll::Ready(Some(KademliaEvent::QueryFailed { query_id })) => { match this.random_walk_query_id == Some(query_id) { true => { @@ -781,16 +783,18 @@ impl Stream for Discovery { match Pin::new(&mut this.ping_event_stream).poll_next(cx) { Poll::Pending => {}, Poll::Ready(None) => return Poll::Ready(None), - Poll::Ready(Some(PingEvent::Ping { peer, ping })) => - return Poll::Ready(Some(DiscoveryEvent::Ping { peer, rtt: ping })), + Poll::Ready(Some(PingEvent::Ping { peer, ping })) => { + return Poll::Ready(Some(DiscoveryEvent::Ping { peer, rtt: ping })) + }, } if let Some(ref mut mdns_event_stream) = &mut this.mdns_event_stream { match Pin::new(mdns_event_stream).poll_next(cx) { Poll::Pending => {}, Poll::Ready(None) => return Poll::Ready(None), - Poll::Ready(Some(MdnsEvent::Discovered(addresses))) => - return Poll::Ready(Some(DiscoveryEvent::Discovered { addresses })), + Poll::Ready(Some(MdnsEvent::Discovered(addresses))) => { + return Poll::Ready(Some(DiscoveryEvent::Discovered { addresses })) + }, } } diff --git a/bizinikiwi/client/network/src/litep2p/mod.rs b/bizinikiwi/client/network/src/litep2p/mod.rs index 529741a7..8fa345fd 100644 --- a/bizinikiwi/client/network/src/litep2p/mod.rs +++ b/bizinikiwi/client/network/src/litep2p/mod.rs @@ -206,19 +206,20 @@ impl Litep2pNetworkBackend { .into_iter() .filter_map(|address| match address.iter().next() { Some( - Protocol::Dns(_) | - Protocol::Dns4(_) | - Protocol::Dns6(_) | - Protocol::Ip6(_) | - Protocol::Ip4(_), + Protocol::Dns(_) + | Protocol::Dns4(_) + | Protocol::Dns6(_) + | Protocol::Ip6(_) + | Protocol::Ip4(_), ) => match address.iter().find(|protocol| std::matches!(protocol, Protocol::P2p(_))) { Some(Protocol::P2p(multihash)) => PeerId::from_multihash(multihash.into()) .map_or(None, |peer| Some((peer, Some(address)))), _ => None, }, - Some(Protocol::P2p(multihash)) => - PeerId::from_multihash(multihash.into()).map_or(None, |peer| Some((peer, None))), + Some(Protocol::P2p(multihash)) => { + PeerId::from_multihash(multihash.into()).map_or(None, |peer| Some((peer, None))) + }, _ => None, }) .fold(HashMap::new(), |mut acc, (peer, maybe_address)| { @@ -300,8 +301,9 @@ impl Litep2pNetworkBackend { match iter.next() { Some(Protocol::Tcp(_)) => match iter.next() { - Some(Protocol::Ws(_) | Protocol::Wss(_)) => - Some((None, Some(address.clone()))), + Some(Protocol::Ws(_) | Protocol::Wss(_)) => { + Some((None, Some(address.clone()))) + }, Some(Protocol::P2p(_)) | None => Some((Some(address.clone()), None)), protocol => { log::error!( @@ -484,8 +486,9 @@ impl NetworkBackend for Litep2pNetworkBac use pezsc_network_types::multiaddr::Protocol; let address = match address.iter().last() { - Some(Protocol::Ws(_) | Protocol::Wss(_) | Protocol::Tcp(_)) => - address.with(Protocol::P2p(peer.into())), + Some(Protocol::Ws(_) | Protocol::Wss(_) | Protocol::Tcp(_)) => { + address.with(Protocol::P2p(peer.into())) + }, Some(Protocol::P2p(_)) => address, _ => return acc, }; diff --git a/bizinikiwi/client/network/src/litep2p/shim/bitswap.rs b/bizinikiwi/client/network/src/litep2p/shim/bitswap.rs index 54d3763c..16bb7ec8 100644 --- a/bizinikiwi/client/network/src/litep2p/shim/bitswap.rs +++ b/bizinikiwi/client/network/src/litep2p/shim/bitswap.rs @@ -76,8 +76,9 @@ impl BitswapServer { log::trace!(target: LOG_TARGET, "found cid {cid:?}, hash {hash:?}"); match want_type { - WantType::Block => - ResponseType::Block { cid, block: transaction }, + WantType::Block => { + ResponseType::Block { cid, block: transaction } + }, _ => ResponseType::Presence { cid, presence: BlockPresenceType::Have, diff --git a/bizinikiwi/client/network/src/litep2p/shim/notification/peerset.rs b/bizinikiwi/client/network/src/litep2p/shim/notification/peerset.rs index 0a1ca2d4..2e6a0d06 100644 --- a/bizinikiwi/client/network/src/litep2p/shim/notification/peerset.rs +++ b/bizinikiwi/client/network/src/litep2p/shim/notification/peerset.rs @@ -123,8 +123,9 @@ pub enum Direction { impl Direction { fn set_reserved(&mut self, new_reserved: Reserved) { match self { - Direction::Inbound(ref mut reserved) | Direction::Outbound(ref mut reserved) => - *reserved = new_reserved, + Direction::Inbound(ref mut reserved) | Direction::Outbound(ref mut reserved) => { + *reserved = new_reserved + }, } } } @@ -541,8 +542,8 @@ impl Peerset { match &state { // close was initiated either by remote ([`PeerState::Connected`]) or local node // ([`PeerState::Closing`]) and it was a non-reserved peer - PeerState::Connected { direction: Direction::Inbound(Reserved::No) } | - PeerState::Closing { direction: Direction::Inbound(Reserved::No) } => { + PeerState::Connected { direction: Direction::Inbound(Reserved::No) } + | PeerState::Closing { direction: Direction::Inbound(Reserved::No) } => { log::trace!( target: LOG_TARGET, "{}: inbound substream closed to non-reserved peer {peer:?}: {state:?}", @@ -558,8 +559,8 @@ impl Peerset { }, // close was initiated either by remote ([`PeerState::Connected`]) or local node // ([`PeerState::Closing`]) and it was a non-reserved peer - PeerState::Connected { direction: Direction::Outbound(Reserved::No) } | - PeerState::Closing { direction: Direction::Outbound(Reserved::No) } => { + PeerState::Connected { direction: Direction::Outbound(Reserved::No) } + | PeerState::Closing { direction: Direction::Outbound(Reserved::No) } => { log::trace!( target: LOG_TARGET, "{}: outbound substream closed to non-reserved peer {peer:?} {state:?}", @@ -791,8 +792,8 @@ impl Peerset { _ => {}, }, // reserved peers do not require change in the slot counts - Some(PeerState::Opening { direction: Direction::Inbound(Reserved::Yes) }) | - Some(PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) }) => { + Some(PeerState::Opening { direction: Direction::Inbound(Reserved::Yes) }) + | Some(PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) }) => { log::debug!( target: LOG_TARGET, "{}: substream open failure for reserved peer {peer:?}", @@ -884,10 +885,10 @@ impl Peerset { match self.peers.get_mut(peer) { Some(PeerState::Disconnected | PeerState::Backoff) => {}, Some( - PeerState::Opening { ref mut direction } | - PeerState::Connected { ref mut direction } | - PeerState::Canceled { ref mut direction } | - PeerState::Closing { ref mut direction }, + PeerState::Opening { ref mut direction } + | PeerState::Connected { ref mut direction } + | PeerState::Canceled { ref mut direction } + | PeerState::Closing { ref mut direction }, ) => { *direction = match direction { Direction::Inbound(Reserved::No) => { @@ -1440,8 +1441,8 @@ impl Stream for Peerset { .peers .iter() .filter_map(|(peer, state)| { - (!self.reserved_peers.contains(peer) && - std::matches!(state, PeerState::Connected { .. })) + (!self.reserved_peers.contains(peer) + && std::matches!(state, PeerState::Connected { .. })) .then_some(*peer) }) .collect::>(); diff --git a/bizinikiwi/client/network/src/litep2p/shim/notification/tests/fuzz.rs b/bizinikiwi/client/network/src/litep2p/shim/notification/tests/fuzz.rs index bafc7f3d..21a2ead1 100644 --- a/bizinikiwi/client/network/src/litep2p/shim/notification/tests/fuzz.rs +++ b/bizinikiwi/client/network/src/litep2p/shim/notification/tests/fuzz.rs @@ -162,7 +162,7 @@ async fn test_once() { // substream to `Peerset` and move peer state to `open`. // // if the substream was canceled while it was opening, move peer to `closing` - 2 => + 2 => { if let Some(peer) = opening.keys().choose(&mut rng).copied() { let direction = opening.remove(&peer).unwrap(); match peerset.report_substream_opened(peer, direction) { @@ -173,37 +173,43 @@ async fn test_once() { assert!(closing.insert(peer)); }, } - }, + } + }, // substream failed to open - 3 => + 3 => { if let Some(peer) = opening.keys().choose(&mut rng).copied() { let _ = opening.remove(&peer).unwrap(); peerset.report_substream_open_failure(peer, NotificationError::Rejected); - }, + } + }, // substream was closed by remote peer - 4 => + 4 => { if let Some(peer) = open.keys().choose(&mut rng).copied() { let _ = open.remove(&peer).unwrap(); peerset.report_substream_closed(peer); assert!(closed.insert(peer)); - }, + } + }, // substream was closed by local node - 5 => + 5 => { if let Some(peer) = closing.iter().choose(&mut rng).copied() { assert!(closing.remove(&peer)); assert!(closed.insert(peer)); peerset.report_substream_closed(peer); - }, + } + }, // random connected peer was disconnected by the protocol - 6 => + 6 => { if let Some(peer) = open.keys().choose(&mut rng).copied() { to_peerset.unbounded_send(PeersetCommand::DisconnectPeer { peer }).unwrap(); - }, + } + }, // ban random peer - 7 => + 7 => { if let Some(peer) = known_peers.iter().choose(&mut rng).copied() { peer_store_handle.report_peer(peer, ReputationChange::new_fatal("")); - }, + } + }, // inbound substream is received for a peer that was considered // outbound 8 => { @@ -364,7 +370,7 @@ async fn test_once() { } }, // inbound substream received for a peer in `closed` - 15 => + 15 => { if let Some(peer) = closed.iter().choose(&mut rng).copied() { match peerset.report_inbound_substream(peer) { ValidationResult::Accept => { @@ -373,7 +379,8 @@ async fn test_once() { }, ValidationResult::Reject => {}, } - }, + } + }, _ => unreachable!(), } } diff --git a/bizinikiwi/client/network/src/litep2p/shim/request_response/mod.rs b/bizinikiwi/client/network/src/litep2p/shim/request_response/mod.rs index fb16bb5f..52d0d3c9 100644 --- a/bizinikiwi/client/network/src/litep2p/shim/request_response/mod.rs +++ b/bizinikiwi/client/network/src/litep2p/shim/request_response/mod.rs @@ -382,36 +382,45 @@ impl RequestResponseProtocol { }; let status = match error { - RequestResponseError::NotConnected => - Some((RequestFailure::NotConnected, "not-connected")), + RequestResponseError::NotConnected => { + Some((RequestFailure::NotConnected, "not-connected")) + }, RequestResponseError::Rejected(reason) => { let reason = match reason { RejectReason::ConnectionClosed => "connection-closed", RejectReason::SubstreamClosed => "substream-closed", RejectReason::SubstreamOpenError(substream_error) => match substream_error { - SubstreamError::NegotiationError(NegotiationError::Timeout) => - "substream-timeout", + SubstreamError::NegotiationError(NegotiationError::Timeout) => { + "substream-timeout" + }, _ => "substream-open-error", }, RejectReason::DialFailed(None) => "dial-failed", - RejectReason::DialFailed(Some(ImmediateDialError::AlreadyConnected)) => - "dial-already-connected", - RejectReason::DialFailed(Some(ImmediateDialError::PeerIdMissing)) => - "dial-peerid-missing", - RejectReason::DialFailed(Some(ImmediateDialError::TriedToDialSelf)) => - "dial-tried-to-dial-self", - RejectReason::DialFailed(Some(ImmediateDialError::NoAddressAvailable)) => - "dial-no-address-available", - RejectReason::DialFailed(Some(ImmediateDialError::TaskClosed)) => - "dial-task-closed", - RejectReason::DialFailed(Some(ImmediateDialError::ChannelClogged)) => - "dial-channel-clogged", + RejectReason::DialFailed(Some(ImmediateDialError::AlreadyConnected)) => { + "dial-already-connected" + }, + RejectReason::DialFailed(Some(ImmediateDialError::PeerIdMissing)) => { + "dial-peerid-missing" + }, + RejectReason::DialFailed(Some(ImmediateDialError::TriedToDialSelf)) => { + "dial-tried-to-dial-self" + }, + RejectReason::DialFailed(Some(ImmediateDialError::NoAddressAvailable)) => { + "dial-no-address-available" + }, + RejectReason::DialFailed(Some(ImmediateDialError::TaskClosed)) => { + "dial-task-closed" + }, + RejectReason::DialFailed(Some(ImmediateDialError::ChannelClogged)) => { + "dial-channel-clogged" + }, }; Some((RequestFailure::Refused, reason)) }, - RequestResponseError::Timeout => - Some((RequestFailure::Network(OutboundFailure::Timeout), "timeout")), + RequestResponseError::Timeout => { + Some((RequestFailure::Network(OutboundFailure::Timeout), "timeout")) + }, RequestResponseError::Canceled => { log::debug!( target: LOG_TARGET, @@ -514,8 +523,9 @@ impl RequestResponseProtocol { match sent_feedback { None => self.handle.send_response(request_id, response), - Some(feedback) => - self.handle.send_response_with_feedback(request_id, response, feedback), + Some(feedback) => { + self.handle.send_response_with_feedback(request_id, response, feedback) + }, } self.metrics.register_inbound_request_success(started.elapsed()); diff --git a/bizinikiwi/client/network/src/network_state.rs b/bizinikiwi/client/network/src/network_state.rs index b503ae71..4ba8f855 100644 --- a/bizinikiwi/client/network/src/network_state.rs +++ b/bizinikiwi/client/network/src/network_state.rs @@ -106,10 +106,12 @@ pub enum Endpoint { impl From for PeerEndpoint { fn from(endpoint: ConnectedPoint) -> Self { match endpoint { - ConnectedPoint::Dialer { address, role_override, port_use: _ } => - Self::Dialing(address, role_override.into()), - ConnectedPoint::Listener { local_addr, send_back_addr } => - Self::Listening { local_addr, send_back_addr }, + ConnectedPoint::Dialer { address, role_override, port_use: _ } => { + Self::Dialing(address, role_override.into()) + }, + ConnectedPoint::Listener { local_addr, send_back_addr } => { + Self::Listening { local_addr, send_back_addr } + }, } } } diff --git a/bizinikiwi/client/network/src/peer_info.rs b/bizinikiwi/client/network/src/peer_info.rs index d5e4a823..99dfc651 100644 --- a/bizinikiwi/client/network/src/peer_info.rs +++ b/bizinikiwi/client/network/src/peer_info.rs @@ -288,8 +288,8 @@ impl PeerInfoBehaviour { } }, None => { - let oldest = (self.address_confirmations.len() >= - self.address_confirmations.limiter().max_length() as usize) + let oldest = (self.address_confirmations.len() + >= self.address_confirmations.limiter().max_length() as usize) .then(|| { self.address_confirmations.pop_oldest().map(|(address, peers)| { if peers.len() >= MIN_ADDRESS_CONFIRMATIONS { @@ -599,10 +599,12 @@ impl NetworkBehaviour for PeerInfoBehaviour { event: THandlerOutEvent, ) { match event { - Either::Left(event) => - self.ping.on_connection_handler_event(peer_id, connection_id, event), - Either::Right(event) => - self.identify.on_connection_handler_event(peer_id, connection_id, event), + Either::Left(event) => { + self.ping.on_connection_handler_event(peer_id, connection_id, event) + }, + Either::Right(event) => { + self.identify.on_connection_handler_event(peer_id, connection_id, event) + }, } } diff --git a/bizinikiwi/client/network/src/protocol.rs b/bizinikiwi/client/network/src/protocol.rs index 451e58a9..a1ac6f76 100644 --- a/bizinikiwi/client/network/src/protocol.rs +++ b/bizinikiwi/client/network/src/protocol.rs @@ -309,7 +309,7 @@ impl NetworkBehaviour for Protocol { notifications_sink, negotiated_fallback, .. - } => + } => { if set_id == HARDCODED_PEERSETS_SYNC { let _ = self.sync_handle.report_substream_opened( peer_id, @@ -334,8 +334,9 @@ impl NetworkBehaviour for Protocol { None }, } - }, - NotificationsOut::CustomProtocolReplaced { peer_id, notifications_sink, set_id } => + } + }, + NotificationsOut::CustomProtocolReplaced { peer_id, notifications_sink, set_id } => { if set_id == HARDCODED_PEERSETS_SYNC { let _ = self .sync_handle @@ -349,7 +350,8 @@ impl NetworkBehaviour for Protocol { notifications_sink, }, ) - }, + } + }, NotificationsOut::CustomProtocolClosed { peer_id, set_id } => { if set_id == HARDCODED_PEERSETS_SYNC { let _ = self.sync_handle.report_substream_closed(peer_id); diff --git a/bizinikiwi/client/network/src/protocol/message.rs b/bizinikiwi/client/network/src/protocol/message.rs index 61af05e3..27c1c9a2 100644 --- a/bizinikiwi/client/network/src/protocol/message.rs +++ b/bizinikiwi/client/network/src/protocol/message.rs @@ -109,12 +109,13 @@ pub mod generic { let compact = CompactStatus::decode(value)?; let chain_status = match >::decode(value) { Ok(v) => v, - Err(e) => + Err(e) => { if compact.version <= LAST_CHAIN_STATUS_VERSION { return Err(e); } else { Vec::new() - }, + } + }, }; let CompactStatus { diff --git a/bizinikiwi/client/network/src/protocol/notifications/behaviour.rs b/bizinikiwi/client/network/src/protocol/notifications/behaviour.rs index 7057f8c7..71a90963 100644 --- a/bizinikiwi/client/network/src/protocol/notifications/behaviour.rs +++ b/bizinikiwi/client/network/src/protocol/notifications/behaviour.rs @@ -1263,8 +1263,8 @@ impl NetworkBehaviour for Notifications { for set_id in (0..self.notif_protocols.len()).map(SetId::from) { match self.peers.entry((peer_id, set_id)).or_insert(PeerState::Poisoned) { // Requested | PendingRequest => Enabled - st @ &mut PeerState::Requested | - st @ &mut PeerState::PendingRequest { .. } => { + st @ &mut PeerState::Requested + | st @ &mut PeerState::PendingRequest { .. } => { trace!(target: LOG_TARGET, "Libp2p => Connected({}, {:?}, {:?}): Connection was requested by PSM.", peer_id, set_id, endpoint @@ -1304,10 +1304,10 @@ impl NetworkBehaviour for Notifications { // In all other states, add this new connection to the list of closed // inactive connections. - PeerState::Incoming { connections, .. } | - PeerState::Disabled { connections, .. } | - PeerState::DisabledPendingEnable { connections, .. } | - PeerState::Enabled { connections, .. } => { + PeerState::Incoming { connections, .. } + | PeerState::Disabled { connections, .. } + | PeerState::DisabledPendingEnable { connections, .. } + | PeerState::Enabled { connections, .. } => { trace!(target: LOG_TARGET, "Libp2p => Connected({}, {:?}, {:?}, {:?}): Secondary connection. Leaving closed.", peer_id, set_id, endpoint, connection_id); @@ -1593,9 +1593,9 @@ impl NetworkBehaviour for Notifications { } }, - PeerState::Requested | - PeerState::PendingRequest { .. } | - PeerState::Backoff { .. } => { + PeerState::Requested + | PeerState::PendingRequest { .. } + | PeerState::Backoff { .. } => { // This is a serious bug either in this state machine or in libp2p. error!(target: LOG_TARGET, "`inject_connection_closed` called for unknown peer {}", @@ -1629,8 +1629,8 @@ impl NetworkBehaviour for Notifications { // "Basic" situation: we failed to reach a peer that the peerset // requested. - st @ PeerState::Requested | - st @ PeerState::PendingRequest { .. } => { + st @ PeerState::Requested + | st @ PeerState::PendingRequest { .. } => { trace!(target: LOG_TARGET, "PSM <= Dropped({}, {:?})", peer_id, set_id); self.protocol_controller_handles[usize::from(set_id)] .dropped(peer_id); @@ -1639,7 +1639,9 @@ impl NetworkBehaviour for Notifications { let ban_duration = match st { PeerState::PendingRequest { timer_deadline, .. } if timer_deadline > now => - cmp::max(timer_deadline - now, Duration::from_secs(5)), + { + cmp::max(timer_deadline - now, Duration::from_secs(5)) + }, _ => Duration::from_secs(5), }; @@ -1662,10 +1664,10 @@ impl NetworkBehaviour for Notifications { // We can still get dial failures even if we are already connected // to the peer, as an extra diagnostic for an earlier attempt. - st @ PeerState::Disabled { .. } | - st @ PeerState::Enabled { .. } | - st @ PeerState::DisabledPendingEnable { .. } | - st @ PeerState::Incoming { .. } => { + st @ PeerState::Disabled { .. } + | st @ PeerState::Enabled { .. } + | st @ PeerState::DisabledPendingEnable { .. } + | st @ PeerState::Incoming { .. } => { *entry.into_mut() = st; }, @@ -1793,8 +1795,8 @@ impl NetworkBehaviour for Notifications { // more to do. debug_assert!(matches!( connec_state, - ConnectionState::OpenDesiredByRemote | - ConnectionState::Closing | ConnectionState::Opening + ConnectionState::OpenDesiredByRemote + | ConnectionState::Closing | ConnectionState::Opening )); } } else { @@ -2005,8 +2007,8 @@ impl NetworkBehaviour for Notifications { // All connections in `Disabled` and `DisabledPendingEnable` have been sent a // `Close` message already, and as such ignore any `CloseDesired` message. - state @ PeerState::Disabled { .. } | - state @ PeerState::DisabledPendingEnable { .. } => { + state @ PeerState::Disabled { .. } + | state @ PeerState::DisabledPendingEnable { .. } => { *entry.into_mut() = state; }, state => { @@ -2026,10 +2028,10 @@ impl NetworkBehaviour for Notifications { match self.peers.get_mut(&(peer_id, set_id)) { // Move the connection from `Closing` to `Closed`. - Some(PeerState::Incoming { connections, .. }) | - Some(PeerState::DisabledPendingEnable { connections, .. }) | - Some(PeerState::Disabled { connections, .. }) | - Some(PeerState::Enabled { connections, .. }) => { + Some(PeerState::Incoming { connections, .. }) + | Some(PeerState::DisabledPendingEnable { connections, .. }) + | Some(PeerState::Disabled { connections, .. }) + | Some(PeerState::Enabled { connections, .. }) => { if let Some((_, connec_state)) = connections.iter_mut().find(|(c, s)| { *c == connection_id && matches!(s, ConnectionState::Closing) }) { @@ -2094,8 +2096,8 @@ impl NetworkBehaviour for Notifications { *connec_state = ConnectionState::Open(notifications_sink); } else if let Some((_, connec_state)) = connections.iter_mut().find(|(c, s)| { - *c == connection_id && - matches!(s, ConnectionState::OpeningThenClosing) + *c == connection_id + && matches!(s, ConnectionState::OpeningThenClosing) }) { *connec_state = ConnectionState::Closing; } else { @@ -2105,9 +2107,9 @@ impl NetworkBehaviour for Notifications { } }, - Some(PeerState::Incoming { connections, .. }) | - Some(PeerState::DisabledPendingEnable { connections, .. }) | - Some(PeerState::Disabled { connections, .. }) => { + Some(PeerState::Incoming { connections, .. }) + | Some(PeerState::DisabledPendingEnable { connections, .. }) + | Some(PeerState::Disabled { connections, .. }) => { if let Some((_, connec_state)) = connections.iter_mut().find(|(c, s)| { *c == connection_id && matches!(s, ConnectionState::OpeningThenClosing) }) { @@ -2156,8 +2158,8 @@ impl NetworkBehaviour for Notifications { *connec_state = ConnectionState::Closed; } else if let Some((_, connec_state)) = connections.iter_mut().find(|(c, s)| { - *c == connection_id && - matches!(s, ConnectionState::OpeningThenClosing) + *c == connection_id + && matches!(s, ConnectionState::OpeningThenClosing) }) { *connec_state = ConnectionState::Closing; } else { @@ -2181,17 +2183,17 @@ impl NetworkBehaviour for Notifications { *entry.into_mut() = PeerState::Enabled { connections }; } }, - mut state @ PeerState::Incoming { .. } | - mut state @ PeerState::DisabledPendingEnable { .. } | - mut state @ PeerState::Disabled { .. } => { + mut state @ PeerState::Incoming { .. } + | mut state @ PeerState::DisabledPendingEnable { .. } + | mut state @ PeerState::Disabled { .. } => { match &mut state { - PeerState::Incoming { connections, .. } | - PeerState::Disabled { connections, .. } | - PeerState::DisabledPendingEnable { connections, .. } => { + PeerState::Incoming { connections, .. } + | PeerState::Disabled { connections, .. } + | PeerState::DisabledPendingEnable { connections, .. } => { if let Some((_, connec_state)) = connections.iter_mut().find(|(c, s)| { - *c == connection_id && - matches!(s, ConnectionState::OpeningThenClosing) + *c == connection_id + && matches!(s, ConnectionState::OpeningThenClosing) }) { *connec_state = ConnectionState::Closing; } else { @@ -2301,8 +2303,8 @@ impl NetworkBehaviour for Notifications { NotificationCommand::SetHandshake(handshake) => { self.set_notif_protocol_handshake(set_id.into(), handshake); }, - NotificationCommand::OpenSubstream(_peer) | - NotificationCommand::CloseSubstream(_peer) => { + NotificationCommand::OpenSubstream(_peer) + | NotificationCommand::CloseSubstream(_peer) => { todo!("substream control not implemented"); }, }, @@ -2416,8 +2418,9 @@ mod tests { (ConnectionState::Closing, ConnectionState::Closing) => true, (ConnectionState::Opening, ConnectionState::Opening) => true, (ConnectionState::OpeningThenClosing, ConnectionState::OpeningThenClosing) => true, - (ConnectionState::OpenDesiredByRemote, ConnectionState::OpenDesiredByRemote) => - true, + (ConnectionState::OpenDesiredByRemote, ConnectionState::OpenDesiredByRemote) => { + true + }, (ConnectionState::Open(_), ConnectionState::Open(_)) => true, _ => false, } diff --git a/bizinikiwi/client/network/src/protocol/notifications/handler.rs b/bizinikiwi/client/network/src/protocol/notifications/handler.rs index 73d35b47..aedd98a5 100644 --- a/bizinikiwi/client/network/src/protocol/notifications/handler.rs +++ b/bizinikiwi/client/network/src/protocol/notifications/handler.rs @@ -560,8 +560,8 @@ impl ConnectionHandler for NotifsHandler { // to do. return; }, - State::Opening { ref mut in_substream, .. } | - State::Open { ref mut in_substream, .. } => { + State::Opening { ref mut in_substream, .. } + | State::Open { ref mut in_substream, .. } => { if in_substream.is_some() { // Same remark as above. return; @@ -579,8 +579,8 @@ impl ConnectionHandler for NotifsHandler { let (new_open, protocol_index) = (outbound.protocol, outbound.info); match self.protocols[protocol_index].state { - State::Closed { ref mut pending_opening } | - State::OpenDesiredByRemote { ref mut pending_opening, .. } => { + State::Closed { ref mut pending_opening } + | State::OpenDesiredByRemote { ref mut pending_opening, .. } => { debug_assert!(*pending_opening); *pending_opening = false; }, @@ -626,8 +626,8 @@ impl ConnectionHandler for NotifsHandler { [dial_upgrade_error.info] .state { - State::Closed { ref mut pending_opening } | - State::OpenDesiredByRemote { ref mut pending_opening, .. } => { + State::Closed { ref mut pending_opening } + | State::OpenDesiredByRemote { ref mut pending_opening, .. } => { debug_assert!(*pending_opening); *pending_opening = false; }, @@ -786,10 +786,11 @@ impl ConnectionHandler for NotifsHandler { // available in `notifications_sink_rx`. This avoids waking up the task when // a substream is ready to send if there isn't actually something to send. match Pin::new(&mut *notifications_sink_rx).as_mut().poll_peek(cx) { - Poll::Ready(Some(&NotificationsSinkMessage::ForceClose)) => + Poll::Ready(Some(&NotificationsSinkMessage::ForceClose)) => { return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( NotifsHandlerOut::Close { protocol_index }, - )), + )) + }, Poll::Ready(Some(&NotificationsSinkMessage::Notification { .. })) => {}, Poll::Ready(None) | Poll::Pending => break, } @@ -803,11 +804,12 @@ impl ConnectionHandler for NotifsHandler { // Now that the substream is ready for a message, grab what to send. let message = match notifications_sink_rx.poll_next_unpin(cx) { - Poll::Ready(Some(NotificationsSinkMessage::Notification { message })) => - message, - Poll::Ready(Some(NotificationsSinkMessage::ForceClose)) | - Poll::Ready(None) | - Poll::Pending => { + Poll::Ready(Some(NotificationsSinkMessage::Notification { message })) => { + message + }, + Poll::Ready(Some(NotificationsSinkMessage::ForceClose)) + | Poll::Ready(None) + | Poll::Pending => { // Should never be reached, as per `poll_peek` above. debug_assert!(false); break; @@ -839,10 +841,12 @@ impl ConnectionHandler for NotifsHandler { *out_substream = None; let reason = match error { - NotificationsOutError::Io(_) | NotificationsOutError::Closed => - CloseReason::RemoteRequest, - NotificationsOutError::UnexpectedData => - CloseReason::ProtocolMisbehavior, + NotificationsOutError::Io(_) | NotificationsOutError::Closed => { + CloseReason::RemoteRequest + }, + NotificationsOutError::UnexpectedData => { + CloseReason::ProtocolMisbehavior + }, }; let event = NotifsHandlerOut::CloseDesired { protocol_index, reason }; @@ -851,10 +855,10 @@ impl ConnectionHandler for NotifsHandler { }; }, - State::Closed { .. } | - State::Opening { .. } | - State::Open { out_substream: None, .. } | - State::OpenDesiredByRemote { .. } => {}, + State::Closed { .. } + | State::Opening { .. } + | State::Open { out_substream: None, .. } + | State::OpenDesiredByRemote { .. } => {}, } } @@ -863,11 +867,11 @@ impl ConnectionHandler for NotifsHandler { // Inbound substreams being closed is always tolerated, except for the // `OpenDesiredByRemote` state which might need to be switched back to `Closed`. match &mut self.protocols[protocol_index].state { - State::Closed { .. } | - State::Open { in_substream: None, .. } | - State::Opening { in_substream: None, .. } => {}, + State::Closed { .. } + | State::Open { in_substream: None, .. } + | State::Opening { in_substream: None, .. } => {}, - State::Open { in_substream: in_substream @ Some(_), .. } => + State::Open { in_substream: in_substream @ Some(_), .. } => { match futures::prelude::stream::Stream::poll_next( Pin::new(in_substream.as_mut().unwrap()), cx, @@ -878,9 +882,10 @@ impl ConnectionHandler for NotifsHandler { return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour(event)); }, Poll::Ready(None) | Poll::Ready(Some(Err(_))) => *in_substream = None, - }, + } + }, - State::OpenDesiredByRemote { in_substream, pending_opening } => + State::OpenDesiredByRemote { in_substream, pending_opening } => { match NotificationsInSubstream::poll_process(Pin::new(in_substream), cx) { Poll::Pending => {}, Poll::Ready(Ok(())) => {}, @@ -894,9 +899,10 @@ impl ConnectionHandler for NotifsHandler { }, )); }, - }, + } + }, - State::Opening { in_substream: in_substream @ Some(_), .. } => + State::Opening { in_substream: in_substream @ Some(_), .. } => { match NotificationsInSubstream::poll_process( Pin::new(in_substream.as_mut().unwrap()), cx, @@ -904,7 +910,8 @@ impl ConnectionHandler for NotifsHandler { Poll::Pending => {}, Poll::Ready(Ok(())) => {}, Poll::Ready(Err(_)) => *in_substream = None, - }, + } + }, } } @@ -1003,8 +1010,9 @@ pub mod tests { }; futures::future::poll_fn(|cx| match substream.notifications.poll_next_unpin(cx) { - Poll::Ready(Some(NotificationsSinkMessage::Notification { message })) => - Poll::Ready(Some(message)), + Poll::Ready(Some(NotificationsSinkMessage::Notification { message })) => { + Poll::Ready(Some(message)) + }, Poll::Pending => Poll::Ready(None), Poll::Ready(Some(NotificationsSinkMessage::ForceClose)) | Poll::Ready(None) => { panic!("sink closed") @@ -1108,8 +1116,9 @@ pub mod tests { ) -> Poll> { match self.rx.poll_recv(cx) { Poll::Ready(Some(data)) => self.rx_buffer.extend_from_slice(&data), - Poll::Ready(None) => - return Poll::Ready(Err(std::io::ErrorKind::UnexpectedEof.into())), + Poll::Ready(None) => { + return Poll::Ready(Err(std::io::ErrorKind::UnexpectedEof.into())) + }, _ => {}, } diff --git a/bizinikiwi/client/network/src/protocol/notifications/service/mod.rs b/bizinikiwi/client/network/src/protocol/notifications/service/mod.rs index e8a4748f..46d29c1a 100644 --- a/bizinikiwi/client/network/src/protocol/notifications/service/mod.rs +++ b/bizinikiwi/client/network/src/protocol/notifications/service/mod.rs @@ -295,12 +295,13 @@ impl NotificationService for NotificationHandle { async fn next_event(&mut self) -> Option { loop { match self.rx.next().await? { - InnerNotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx } => + InnerNotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx } => { return Some(NotificationEvent::ValidateInboundSubstream { peer: peer.into(), handshake, result_tx, - }), + }) + }, InnerNotificationEvent::NotificationStreamOpened { peer, handshake, @@ -326,11 +327,12 @@ impl NotificationService for NotificationHandle { self.peers.remove(&peer); return Some(NotificationEvent::NotificationStreamClosed { peer: peer.into() }); }, - InnerNotificationEvent::NotificationReceived { peer, notification } => + InnerNotificationEvent::NotificationReceived { peer, notification } => { return Some(NotificationEvent::NotificationReceived { peer: peer.into(), notification, - }), + }) + }, InnerNotificationEvent::NotificationSinkReplaced { peer, sink } => { match self.peers.get_mut(&peer) { None => log::error!( @@ -515,8 +517,9 @@ impl ProtocolHandle { tokio::spawn(async move { while let Some(event) = results.next().await { match event { - Err(_) | Ok(ValidationResult::Reject) => - return tx.send(ValidationResult::Reject), + Err(_) | Ok(ValidationResult::Reject) => { + return tx.send(ValidationResult::Reject) + }, Ok(ValidationResult::Accept) => {}, } } diff --git a/bizinikiwi/client/network/src/protocol/notifications/tests/conformance.rs b/bizinikiwi/client/network/src/protocol/notifications/tests/conformance.rs index 959f5ba2..5499e7c7 100644 --- a/bizinikiwi/client/network/src/protocol/notifications/tests/conformance.rs +++ b/bizinikiwi/client/network/src/protocol/notifications/tests/conformance.rs @@ -209,12 +209,12 @@ async fn libp2p_to_litep2p_substream() { let mut libp2p_1111_seen = false; let mut libp2p_2222_seen = false; - while !libp2p_ready || - !litep2p_ready || - !litep2p_3333_seen || - !litep2p_4444_seen || - !libp2p_1111_seen || - !libp2p_2222_seen + while !libp2p_ready + || !litep2p_ready + || !litep2p_3333_seen + || !litep2p_4444_seen + || !libp2p_1111_seen + || !libp2p_2222_seen { tokio::select! { event = libp2p.select_next_some() => match event { diff --git a/bizinikiwi/client/network/src/protocol/notifications/tests/mod.rs b/bizinikiwi/client/network/src/protocol/notifications/tests/mod.rs index 117031aa..00105ef2 100644 --- a/bizinikiwi/client/network/src/protocol/notifications/tests/mod.rs +++ b/bizinikiwi/client/network/src/protocol/notifications/tests/mod.rs @@ -318,9 +318,9 @@ async fn reconnect_after_disconnect() { NotificationsOut::CustomProtocolClosed { .. }, )) => match service1_state { ServiceState::FirstConnec => service1_state = ServiceState::Disconnected, - ServiceState::ConnectedAgain | - ServiceState::NotConnected | - ServiceState::Disconnected => panic!(), + ServiceState::ConnectedAgain + | ServiceState::NotConnected + | ServiceState::Disconnected => panic!(), }, future::Either::Right(SwarmEvent::Behaviour( NotificationsOut::CustomProtocolOpen { .. }, @@ -340,9 +340,9 @@ async fn reconnect_after_disconnect() { NotificationsOut::CustomProtocolClosed { .. }, )) => match service2_state { ServiceState::FirstConnec => service2_state = ServiceState::Disconnected, - ServiceState::ConnectedAgain | - ServiceState::NotConnected | - ServiceState::Disconnected => panic!(), + ServiceState::ConnectedAgain + | ServiceState::NotConnected + | ServiceState::Disconnected => panic!(), }, _ => {}, } @@ -355,12 +355,12 @@ async fn reconnect_after_disconnect() { // In this case the disconnected node does not transit via `ServiceState::NotConnected` // and stays in `ServiceState::FirstConnec`. // TODO: update this once the fix is finally merged. - if service1_state == ServiceState::ConnectedAgain && - service2_state == ServiceState::ConnectedAgain || - service1_state == ServiceState::ConnectedAgain && - service2_state == ServiceState::FirstConnec || - service1_state == ServiceState::FirstConnec && - service2_state == ServiceState::ConnectedAgain + if service1_state == ServiceState::ConnectedAgain + && service2_state == ServiceState::ConnectedAgain + || service1_state == ServiceState::ConnectedAgain + && service2_state == ServiceState::FirstConnec + || service1_state == ServiceState::FirstConnec + && service2_state == ServiceState::ConnectedAgain { break; } @@ -384,8 +384,8 @@ async fn reconnect_after_disconnect() { }; match event { - SwarmEvent::Behaviour(NotificationsOut::CustomProtocolOpen { .. }) | - SwarmEvent::Behaviour(NotificationsOut::CustomProtocolClosed { .. }) => panic!(), + SwarmEvent::Behaviour(NotificationsOut::CustomProtocolOpen { .. }) + | SwarmEvent::Behaviour(NotificationsOut::CustomProtocolClosed { .. }) => panic!(), _ => {}, } } diff --git a/bizinikiwi/client/network/src/protocol/notifications/upgrade/notifications.rs b/bizinikiwi/client/network/src/protocol/notifications/upgrade/notifications.rs index 0fa67251..fcfae8db 100644 --- a/bizinikiwi/client/network/src/protocol/notifications/upgrade/notifications.rs +++ b/bizinikiwi/client/network/src/protocol/notifications/upgrade/notifications.rs @@ -263,10 +263,10 @@ where } }, - st @ NotificationsInSubstreamHandshake::NotSent | - st @ NotificationsInSubstreamHandshake::Sent | - st @ NotificationsInSubstreamHandshake::ClosingInResponseToRemote | - st @ NotificationsInSubstreamHandshake::BothSidesClosed => { + st @ NotificationsInSubstreamHandshake::NotSent + | st @ NotificationsInSubstreamHandshake::Sent + | st @ NotificationsInSubstreamHandshake::ClosingInResponseToRemote + | st @ NotificationsInSubstreamHandshake::BothSidesClosed => { *this.handshake = st; return Poll::Ready(Ok(())); }, @@ -308,8 +308,9 @@ where }, NotificationsInSubstreamHandshake::Flush => { match Sink::poll_flush(this.socket.as_mut(), cx)? { - Poll::Ready(()) => - *this.handshake = NotificationsInSubstreamHandshake::Sent, + Poll::Ready(()) => { + *this.handshake = NotificationsInSubstreamHandshake::Sent + }, Poll::Pending => { *this.handshake = NotificationsInSubstreamHandshake::Flush; return Poll::Pending; @@ -319,9 +320,10 @@ where NotificationsInSubstreamHandshake::Sent => { match Stream::poll_next(this.socket.as_mut(), cx) { - Poll::Ready(None) => + Poll::Ready(None) => { *this.handshake = - NotificationsInSubstreamHandshake::ClosingInResponseToRemote, + NotificationsInSubstreamHandshake::ClosingInResponseToRemote + }, Poll::Ready(Some(msg)) => { *this.handshake = NotificationsInSubstreamHandshake::Sent; return Poll::Ready(Some(msg)); @@ -333,16 +335,18 @@ where } }, - NotificationsInSubstreamHandshake::ClosingInResponseToRemote => + NotificationsInSubstreamHandshake::ClosingInResponseToRemote => { match Sink::poll_close(this.socket.as_mut(), cx)? { - Poll::Ready(()) => - *this.handshake = NotificationsInSubstreamHandshake::BothSidesClosed, + Poll::Ready(()) => { + *this.handshake = NotificationsInSubstreamHandshake::BothSidesClosed + }, Poll::Pending => { *this.handshake = NotificationsInSubstreamHandshake::ClosingInResponseToRemote; return Poll::Pending; }, - }, + } + }, NotificationsInSubstreamHandshake::BothSidesClosed => return Poll::Ready(None), } diff --git a/bizinikiwi/client/network/src/protocol_controller.rs b/bizinikiwi/client/network/src/protocol_controller.rs index 1df7c34c..784035d4 100644 --- a/bizinikiwi/client/network/src/protocol_controller.rs +++ b/bizinikiwi/client/network/src/protocol_controller.rs @@ -372,8 +372,9 @@ impl ProtocolController { /// Process connection event. fn process_event(&mut self, event: Event) { match event { - Event::IncomingConnection(peer_id, index) => - self.on_incoming_connection(peer_id, index), + Event::IncomingConnection(peer_id, index) => { + self.on_incoming_connection(peer_id, index) + }, Event::Dropped(peer_id) => self.on_peer_dropped(peer_id), } } @@ -386,8 +387,9 @@ impl ProtocolController { Action::SetReservedPeers(peer_ids) => self.on_set_reserved_peers(peer_ids), Action::SetReservedOnly(reserved_only) => self.on_set_reserved_only(reserved_only), Action::DisconnectPeer(peer_id) => self.on_disconnect_peer(peer_id), - Action::GetReservedPeers(pending_response) => - self.on_get_reserved_peers(pending_response), + Action::GetReservedPeers(pending_response) => { + self.on_get_reserved_peers(pending_response) + }, } } @@ -516,8 +518,8 @@ impl ProtocolController { if let PeerState::Connected(direction) = state { // Disconnect if we're at (or over) the regular node limit - let disconnect = self.reserved_only || - match direction { + let disconnect = self.reserved_only + || match direction { Direction::Inbound => self.num_in >= self.max_in, Direction::Outbound => self.num_out >= self.max_out, }; @@ -671,13 +673,14 @@ impl ProtocolController { *direction = Direction::Inbound; self.accept_connection(peer_id, incoming_index); }, - PeerState::NotConnected => + PeerState::NotConnected => { if self.peer_store.is_banned(&peer_id.into()) { self.reject_connection(peer_id, incoming_index); } else { *state = PeerState::Connected(Direction::Inbound); self.accept_connection(peer_id, incoming_index); - }, + } + }, } return; } @@ -827,8 +830,8 @@ impl ProtocolController { .outgoing_candidates(available_slots, ignored) .into_iter() .filter_map(|peer_id| { - (!self.reserved_nodes.contains_key(&peer_id.into()) && - !self.nodes.contains_key(&peer_id.into())) + (!self.reserved_nodes.contains_key(&peer_id.into()) + && !self.nodes.contains_key(&peer_id.into())) .then_some(peer_id) .or_else(|| { error!( diff --git a/bizinikiwi/client/network/src/request_responses.rs b/bizinikiwi/client/network/src/request_responses.rs index 8de5ed4c..d4b9ab4c 100644 --- a/bizinikiwi/client/network/src/request_responses.rs +++ b/bizinikiwi/client/network/src/request_responses.rs @@ -96,10 +96,12 @@ impl From for OutboundFailure { match out { request_response::OutboundFailure::DialFailure => OutboundFailure::DialFailure, request_response::OutboundFailure::Timeout => OutboundFailure::Timeout, - request_response::OutboundFailure::ConnectionClosed => - OutboundFailure::ConnectionClosed, - request_response::OutboundFailure::UnsupportedProtocols => - OutboundFailure::UnsupportedProtocols, + request_response::OutboundFailure::ConnectionClosed => { + OutboundFailure::ConnectionClosed + }, + request_response::OutboundFailure::UnsupportedProtocols => { + OutboundFailure::UnsupportedProtocols + }, request_response::OutboundFailure::Io(error) => OutboundFailure::Io(Arc::new(error)), } } @@ -133,8 +135,9 @@ impl From for InboundFailure { request_response::InboundFailure::ResponseOmission => InboundFailure::ResponseOmission, request_response::InboundFailure::Timeout => InboundFailure::Timeout, request_response::InboundFailure::ConnectionClosed => InboundFailure::ConnectionClosed, - request_response::InboundFailure::UnsupportedProtocols => - InboundFailure::UnsupportedProtocols, + request_response::InboundFailure::UnsupportedProtocols => { + InboundFailure::UnsupportedProtocols + }, request_response::InboundFailure::Io(error) => InboundFailure::Io(Arc::new(error)), } } @@ -434,7 +437,9 @@ impl RequestResponsesBehaviour { inbound_queue: protocol.inbound_queue, request_timeout: protocol.request_timeout, }), - Entry::Occupied(e) => return Err(RegisterError::DuplicateProtocol(e.key().clone())), + Entry::Occupied(e) => { + return Err(RegisterError::DuplicateProtocol(e.key().clone())) + }, }; } @@ -1086,7 +1091,9 @@ impl Codec for GenericCodec { Ok(l) => l, Err(unsigned_varint::io::ReadError::Io(err)) if matches!(err.kind(), io::ErrorKind::UnexpectedEof) => - return Ok(Err(())), + { + return Ok(Err(())) + }, Err(err) => return Err(io::Error::new(io::ErrorKind::InvalidInput, err)), }; diff --git a/bizinikiwi/client/network/src/service.rs b/bizinikiwi/client/network/src/service.rs index 8eddad1c..26d22599 100644 --- a/bizinikiwi/client/network/src/service.rs +++ b/bizinikiwi/client/network/src/service.rs @@ -529,8 +529,9 @@ where match result { Ok(b) => b, - Err(crate::request_responses::RegisterError::DuplicateProtocol(proto)) => - return Err(Error::DuplicateRequestResponseProtocol { protocol: proto }), + Err(crate::request_responses::RegisterError::DuplicateProtocol(proto)) => { + return Err(Error::DuplicateRequestResponseProtocol { protocol: proto }) + }, } }; @@ -1442,12 +1443,15 @@ where /// Process the next message coming from the `NetworkService`. fn handle_worker_message(&mut self, msg: ServiceToWorkerMsg) { match msg { - ServiceToWorkerMsg::FindClosestPeers(target) => - self.network_service.behaviour_mut().find_closest_peers(target), - ServiceToWorkerMsg::GetValue(key) => - self.network_service.behaviour_mut().get_value(key.into()), - ServiceToWorkerMsg::PutValue(key, value) => - self.network_service.behaviour_mut().put_value(key.into(), value), + ServiceToWorkerMsg::FindClosestPeers(target) => { + self.network_service.behaviour_mut().find_closest_peers(target) + }, + ServiceToWorkerMsg::GetValue(key) => { + self.network_service.behaviour_mut().get_value(key.into()) + }, + ServiceToWorkerMsg::PutValue(key, value) => { + self.network_service.behaviour_mut().put_value(key.into(), value) + }, ServiceToWorkerMsg::PutRecordTo { record, peers, update_local_storage } => self .network_service .behaviour_mut() @@ -1456,14 +1460,18 @@ where .network_service .behaviour_mut() .store_record(key.into(), value, publisher, expires), - ServiceToWorkerMsg::StartProviding(key) => - self.network_service.behaviour_mut().start_providing(key.into()), - ServiceToWorkerMsg::StopProviding(key) => - self.network_service.behaviour_mut().stop_providing(&key.into()), - ServiceToWorkerMsg::GetProviders(key) => - self.network_service.behaviour_mut().get_providers(key.into()), - ServiceToWorkerMsg::AddKnownAddress(peer_id, addr) => - self.network_service.behaviour_mut().add_known_address(peer_id, addr), + ServiceToWorkerMsg::StartProviding(key) => { + self.network_service.behaviour_mut().start_providing(key.into()) + }, + ServiceToWorkerMsg::StopProviding(key) => { + self.network_service.behaviour_mut().stop_providing(&key.into()) + }, + ServiceToWorkerMsg::GetProviders(key) => { + self.network_service.behaviour_mut().get_providers(key.into()) + }, + ServiceToWorkerMsg::AddKnownAddress(peer_id, addr) => { + self.network_service.behaviour_mut().add_known_address(peer_id, addr) + }, ServiceToWorkerMsg::EventStream(sender) => self.event_streams.push(sender), ServiceToWorkerMsg::Request { target, @@ -1510,18 +1518,23 @@ where }, Err(err) => { let reason = match err { - ResponseFailure::Network(InboundFailure::Timeout) => - Some("timeout"), + ResponseFailure::Network(InboundFailure::Timeout) => { + Some("timeout") + }, ResponseFailure::Network(InboundFailure::UnsupportedProtocols) => // `UnsupportedProtocols` is reported for every single // inbound request whenever a request with an unsupported // protocol is received. This is not reported in order to // avoid confusions. - None, - ResponseFailure::Network(InboundFailure::ResponseOmission) => - Some("busy-omitted"), - ResponseFailure::Network(InboundFailure::ConnectionClosed) => - Some("connection-closed"), + { + None + }, + ResponseFailure::Network(InboundFailure::ResponseOmission) => { + Some("busy-omitted") + }, + ResponseFailure::Network(InboundFailure::ConnectionClosed) => { + Some("connection-closed") + }, ResponseFailure::Network(InboundFailure::Io(_)) => Some("io"), }; @@ -1540,7 +1553,7 @@ where duration, result, .. - }) => + }) => { if let Some(metrics) = self.metrics.as_ref() { match result { Ok(_) => { @@ -1555,13 +1568,16 @@ where RequestFailure::UnknownProtocol => "unknown-protocol", RequestFailure::Refused => "refused", RequestFailure::Obsolete => "obsolete", - RequestFailure::Network(OutboundFailure::DialFailure) => - "dial-failure", + RequestFailure::Network(OutboundFailure::DialFailure) => { + "dial-failure" + }, RequestFailure::Network(OutboundFailure::Timeout) => "timeout", - RequestFailure::Network(OutboundFailure::ConnectionClosed) => - "connection-closed", - RequestFailure::Network(OutboundFailure::UnsupportedProtocols) => - "unsupported", + RequestFailure::Network(OutboundFailure::ConnectionClosed) => { + "connection-closed" + }, + RequestFailure::Network(OutboundFailure::UnsupportedProtocols) => { + "unsupported" + }, RequestFailure::Network(OutboundFailure::Io(_)) => "io", }; @@ -1571,7 +1587,8 @@ where .inc(); }, } - }, + } + }, SwarmEvent::Behaviour(BehaviourOut::ReputationChanges { peer, changes }) => { for change in changes { self.peer_store_handle.report_peer(peer.into(), change); @@ -1801,18 +1818,19 @@ where if let Some(metrics) = self.metrics.as_ref() { let reason = match error { - DialError::Denied { cause } => + DialError::Denied { cause } => { if cause.downcast::().is_ok() { Some("limit-reached") } else { None - }, + } + }, DialError::LocalPeerId { .. } => Some("local-peer-id"), DialError::WrongPeerId { .. } => Some("invalid-peer-id"), DialError::Transport(_) => Some("transport-error"), - DialError::NoAddresses | - DialError::DialPeerConditionFalse(_) | - DialError::Aborted => None, // ignore them + DialError::NoAddresses + | DialError::DialPeerConditionFalse(_) + | DialError::Aborted => None, // ignore them }; if let Some(reason) = reason { metrics.pending_connections_errors_total.with_label_values(&[reason]).inc(); @@ -1840,14 +1858,16 @@ where ); if let Some(metrics) = self.metrics.as_ref() { let reason = match error { - ListenError::Denied { cause } => + ListenError::Denied { cause } => { if cause.downcast::().is_ok() { Some("limit-reached") } else { None - }, - ListenError::WrongPeerId { .. } | ListenError::LocalPeerId { .. } => - Some("invalid-peer-id"), + } + }, + ListenError::WrongPeerId { .. } | ListenError::LocalPeerId { .. } => { + Some("invalid-peer-id") + }, ListenError::Transport(_) => Some("transport-error"), ListenError::Aborted => None, // ignore it }; diff --git a/bizinikiwi/client/network/src/service/out_events.rs b/bizinikiwi/client/network/src/service/out_events.rs index b431d54e..10b2b957 100644 --- a/bizinikiwi/client/network/src/service/out_events.rs +++ b/bizinikiwi/client/network/src/service/out_events.rs @@ -205,8 +205,8 @@ impl OutChannels { ); } sender.warning_fired = SenderWarningState::FiredFull; - } else if sender.warning_fired == SenderWarningState::FiredFull && - current_pending < sender.queue_size_warning.wrapping_div(2) + } else if sender.warning_fired == SenderWarningState::FiredFull + && current_pending < sender.queue_size_warning.wrapping_div(2) { sender.warning_fired = SenderWarningState::FiredFree; debug!( @@ -304,7 +304,7 @@ impl Metrics { self.events_total.with_label_values(&[protocol_label, "sent", name]).inc(); }); }, - Event::NotificationsReceived { messages, .. } => + Event::NotificationsReceived { messages, .. } => { for (protocol, message) in messages { format_label("notif-", protocol, |protocol_label| { self.events_total.with_label_values(&[protocol_label, "sent", name]).inc(); @@ -312,7 +312,8 @@ impl Metrics { self.notifications_sizes .with_label_values(&[protocol, "sent", name]) .inc_by(u64::try_from(message.len()).unwrap_or(u64::MAX)); - }, + } + }, } } @@ -331,7 +332,7 @@ impl Metrics { self.events_total.with_label_values(&[protocol_label, "received", name]).inc(); }); }, - Event::NotificationsReceived { messages, .. } => + Event::NotificationsReceived { messages, .. } => { for (protocol, message) in messages { format_label("notif-", protocol, |protocol_label| { self.events_total @@ -341,7 +342,8 @@ impl Metrics { self.notifications_sizes .with_label_values(&[protocol, "received", name]) .inc_by(u64::try_from(message.len()).unwrap_or(u64::MAX)); - }, + } + }, } } } diff --git a/bizinikiwi/client/network/statement/src/lib.rs b/bizinikiwi/client/network/statement/src/lib.rs index 6dd41b05..94b2500f 100644 --- a/bizinikiwi/client/network/statement/src/lib.rs +++ b/bizinikiwi/client/network/statement/src/lib.rs @@ -503,10 +503,12 @@ where fn on_handle_statement_import(&mut self, who: PeerId, import: &SubmitResult) { match import { - SubmitResult::New(NetworkPriority::High) => - self.network.report_peer(who, rep::EXCELLENT_STATEMENT), - SubmitResult::New(NetworkPriority::Low) => - self.network.report_peer(who, rep::GOOD_STATEMENT), + SubmitResult::New(NetworkPriority::High) => { + self.network.report_peer(who, rep::EXCELLENT_STATEMENT) + }, + SubmitResult::New(NetworkPriority::Low) => { + self.network.report_peer(who, rep::GOOD_STATEMENT) + }, SubmitResult::Known => self.network.report_peer(who, rep::ANY_STATEMENT_REFUND), SubmitResult::KnownExpired => {}, SubmitResult::Ignored => {}, diff --git a/bizinikiwi/client/network/sync/src/block_announce_validator.rs b/bizinikiwi/client/network/sync/src/block_announce_validator.rs index f2f0da8e..a3497a36 100644 --- a/bizinikiwi/client/network/sync/src/block_announce_validator.rs +++ b/bizinikiwi/client/network/sync/src/block_announce_validator.rs @@ -75,9 +75,9 @@ pub(crate) enum BlockAnnounceValidationResult { impl BlockAnnounceValidationResult { fn peer_id(&self) -> &PeerId { match self { - BlockAnnounceValidationResult::Failure { peer_id, .. } | - BlockAnnounceValidationResult::Process { peer_id, .. } | - BlockAnnounceValidationResult::Skip { peer_id } => peer_id, + BlockAnnounceValidationResult::Failure { peer_id, .. } + | BlockAnnounceValidationResult::Process { peer_id, .. } + | BlockAnnounceValidationResult::Skip { peer_id } => peer_id, } } } @@ -262,12 +262,13 @@ impl BlockAnnounceValidator { ); }, Entry::Occupied(mut entry) => match entry.get().checked_sub(1) { - Some(value) => + Some(value) => { if value == 0 { entry.remove(); } else { *entry.get_mut() = value; - }, + } + }, None => { entry.remove(); diff --git a/bizinikiwi/client/network/sync/src/block_request_handler.rs b/bizinikiwi/client/network/sync/src/block_request_handler.rs index dc6b14e5..07fcb644 100644 --- a/bizinikiwi/client/network/sync/src/block_request_handler.rs +++ b/bizinikiwi/client/network/sync/src/block_request_handler.rs @@ -400,8 +400,9 @@ where let body = if get_body { match self.client.block_body(hash)? { - Some(mut extrinsics) => - extrinsics.iter_mut().map(|extrinsic| extrinsic.encode()).collect(), + Some(mut extrinsics) => { + extrinsics.iter_mut().map(|extrinsic| extrinsic.encode()).collect() + }, None => { log::trace!(target: LOG_TARGET, "Missing data for block request."); break; @@ -441,9 +442,9 @@ where indexed_body, }; - let new_total_size = total_size + - block_data.body.iter().map(|ex| ex.len()).sum::() + - block_data.indexed_body.iter().map(|ex| ex.len()).sum::(); + let new_total_size = total_size + + block_data.body.iter().map(|ex| ex.len()).sum::() + + block_data.indexed_body.iter().map(|ex| ex.len()).sum::(); // Send at least one block, but make sure to not exceed the limit. if !blocks.is_empty() && new_total_size > MAX_BODY_BYTES { diff --git a/bizinikiwi/client/network/sync/src/blocks.rs b/bizinikiwi/client/network/sync/src/blocks.rs index f682dfde..b8646a60 100644 --- a/bizinikiwi/client/network/sync/src/blocks.rs +++ b/bizinikiwi/client/network/sync/src/blocks.rs @@ -136,23 +136,29 @@ impl BlockCollection { // the range start. (Some((start, &BlockRangeState::Downloading { ref len, downloading })), _) if downloading < max_parallel && *start >= first_different => - (*start..*start + *len, downloading), + { + (*start..*start + *len, downloading) + }, // If there is a gap between ranges requested, download this gap unless the peer // has common number above the gap start (Some((start, r)), Some((next_start, _))) - if *start + r.len() < *next_start && - *start + r.len() >= first_different => - (*start + r.len()..cmp::min(*next_start, *start + r.len() + count), 0), + if *start + r.len() < *next_start + && *start + r.len() >= first_different => + { + (*start + r.len()..cmp::min(*next_start, *start + r.len() + count), 0) + }, // Download `count` blocks after the last range requested unless the peer // has common number above this new range - (Some((start, r)), None) if *start + r.len() >= first_different => - (*start + r.len()..*start + r.len() + count, 0), + (Some((start, r)), None) if *start + r.len() >= first_different => { + (*start + r.len()..*start + r.len() + count, 0) + }, // If there are no ranges currently requested, download `count` blocks after // `common` number (None, None) => (first_different..first_different + count, 0), // If the first range starts above `common + 1`, download the gap at the start - (None, Some((start, _))) if *start > first_different => - (first_different..cmp::min(first_different + count, *start), 0), + (None, Some((start, _))) if *start > first_different => { + (first_different..cmp::min(first_different + count, *start), 0) + }, // Move on to the next range pair _ => { prev = next; diff --git a/bizinikiwi/client/network/sync/src/engine.rs b/bizinikiwi/client/network/sync/src/engine.rs index 9a67bb19..361558d0 100644 --- a/bizinikiwi/client/network/sync/src/engine.rs +++ b/bizinikiwi/client/network/sync/src/engine.rs @@ -290,8 +290,8 @@ where where N: NetworkBackend::Hash>, { - let cache_capacity = (net_config.network_config.default_peers_set.in_peers + - net_config.network_config.default_peers_set.out_peers) + let cache_capacity = (net_config.network_config.default_peers_set.in_peers + + net_config.network_config.default_peers_set.out_peers) .max(1); let important_peers = { let mut imp_p = HashSet::new(); @@ -328,8 +328,8 @@ where let default_peers_set_num_full = net_config.network_config.default_peers_set_num_full as usize; let default_peers_set_num_light = { - let total = net_config.network_config.default_peers_set.out_peers + - net_config.network_config.default_peers_set.in_peers; + let total = net_config.network_config.default_peers_set.out_peers + + net_config.network_config.default_peers_set.in_peers; total.saturating_sub(net_config.network_config.default_peers_set_num_full) as usize }; @@ -663,10 +663,12 @@ where } self.event_streams.push(tx); }, - ToServiceCommand::RequestJustification(hash, number) => - self.strategy.request_justification(&hash, number), - ToServiceCommand::ClearJustificationRequests => - self.strategy.clear_justification_requests(), + ToServiceCommand::RequestJustification(hash, number) => { + self.strategy.request_justification(&hash, number) + }, + ToServiceCommand::ClearJustificationRequests => { + self.strategy.clear_justification_requests() + }, ToServiceCommand::BlocksProcessed(imported, count, results) => { self.strategy.on_blocks_processed(imported, count, results); }, @@ -734,8 +736,9 @@ where self.peers.iter().map(|(peer_id, peer)| (*peer_id, peer.info)).collect(); let _ = tx.send(peers_info); }, - ToServiceCommand::OnBlockFinalized(hash, header) => - self.strategy.on_block_finalized(&hash, *header.number()), + ToServiceCommand::OnBlockFinalized(hash, header) => { + self.strategy.on_block_finalized(&hash, *header.number()) + }, } } @@ -815,9 +818,9 @@ where log::debug!(target: LOG_TARGET, "{peer_id} disconnected"); } - if !self.default_peers_set_no_slot_connected_peers.remove(&peer_id) && - info.inbound && - info.info.roles.is_full() + if !self.default_peers_set_no_slot_connected_peers.remove(&peer_id) + && info.inbound + && info.info.roles.is_full() { match self.num_in_peers.checked_sub(1) { Some(value) => { @@ -918,21 +921,21 @@ where let no_slot_peer = self.default_peers_set_no_slot_peers.contains(&peer_id); let this_peer_reserved_slot: usize = if no_slot_peer { 1 } else { 0 }; - if handshake.roles.is_full() && - self.strategy.num_peers() >= - self.default_peers_set_num_full + - self.default_peers_set_no_slot_connected_peers.len() + - this_peer_reserved_slot + if handshake.roles.is_full() + && self.strategy.num_peers() + >= self.default_peers_set_num_full + + self.default_peers_set_no_slot_connected_peers.len() + + this_peer_reserved_slot { log::debug!(target: LOG_TARGET, "Too many full nodes, rejecting {peer_id}"); return Err(false); } // make sure to accept no more than `--in-peers` many full nodes - if !no_slot_peer && - handshake.roles.is_full() && - direction.is_inbound() && - self.num_in_peers == self.max_in_peers + if !no_slot_peer + && handshake.roles.is_full() + && direction.is_inbound() + && self.num_in_peers == self.max_in_peers { log::debug!(target: LOG_TARGET, "All inbound slots have been consumed, rejecting {peer_id}"); return Err(false); @@ -942,8 +945,8 @@ where // // `ChainSync` only accepts full peers whereas `SyncingEngine` accepts both full and light // peers. Verify that there is a slot in `SyncingEngine` for the inbound light peer - if handshake.roles.is_light() && - (self.peers.len() - self.strategy.num_peers()) >= self.default_peers_set_num_light + if handshake.roles.is_light() + && (self.peers.len() - self.strategy.num_peers()) >= self.default_peers_set_num_light { log::debug!(target: LOG_TARGET, "Too many light nodes, rejecting {peer_id}"); return Err(false); @@ -1034,8 +1037,8 @@ where self.network_service .disconnect_peer(peer_id, self.block_announce_protocol_name.clone()); }, - RequestFailure::Network(OutboundFailure::ConnectionClosed) | - RequestFailure::NotConnected => { + RequestFailure::Network(OutboundFailure::ConnectionClosed) + | RequestFailure::NotConnected => { self.network_service .disconnect_peer(peer_id, self.block_announce_protocol_name.clone()); }, diff --git a/bizinikiwi/client/network/sync/src/service/network.rs b/bizinikiwi/client/network/sync/src/service/network.rs index cf8186d6..bd2ff0ed 100644 --- a/bizinikiwi/client/network/sync/src/service/network.rs +++ b/bizinikiwi/client/network/sync/src/service/network.rs @@ -119,12 +119,15 @@ impl NetworkServiceProvider { while let Some(inner) = rx.next().await { match inner { - ToServiceCommand::DisconnectPeer(peer, protocol_name) => - service.disconnect_peer(peer, protocol_name), - ToServiceCommand::ReportPeer(peer, reputation_change) => - service.report_peer(peer, reputation_change), - ToServiceCommand::StartRequest(peer, protocol, request, tx, connect) => - service.start_request(peer, protocol, request, None, tx, connect), + ToServiceCommand::DisconnectPeer(peer, protocol_name) => { + service.disconnect_peer(peer, protocol_name) + }, + ToServiceCommand::ReportPeer(peer, reputation_change) => { + service.report_peer(peer, reputation_change) + }, + ToServiceCommand::StartRequest(peer, protocol, request, tx, connect) => { + service.start_request(peer, protocol, request, None, tx, connect) + }, } } } diff --git a/bizinikiwi/client/network/sync/src/strategy/chain_sync.rs b/bizinikiwi/client/network/sync/src/strategy/chain_sync.rs index 21f288d6..0802b8a4 100644 --- a/bizinikiwi/client/network/sync/src/strategy/chain_sync.rs +++ b/bizinikiwi/client/network/sync/src/strategy/chain_sync.rs @@ -441,8 +441,8 @@ where if is_best { if known && self.best_queued_number >= number { self.update_peer_common_number(&peer_id, number); - } else if announce.header.parent_hash() == &self.best_queued_hash || - known_parent && self.best_queued_number >= number + } else if announce.header.parent_hash() == &self.best_queued_hash + || known_parent && self.best_queued_number >= number { self.update_peer_common_number(&peer_id, number.saturating_sub(One::one())); } @@ -727,7 +727,7 @@ where self.complete_gap_if_target(number); }, - Err(BlockImportError::IncompleteHeader(peer_id)) => + Err(BlockImportError::IncompleteHeader(peer_id)) => { if let Some(peer) = peer_id { warn!( target: LOG_TARGET, @@ -736,7 +736,8 @@ where self.actions .push(SyncingAction::DropPeer(BadPeer(peer, rep::INCOMPLETE_HEADER))); self.restart(); - }, + } + }, Err(BlockImportError::VerificationFailed(peer_id, e)) => { let extra_message = peer_id .map_or_else(|| "".into(), |peer| format!(" received from ({peer})")); @@ -753,14 +754,15 @@ where self.restart(); }, - Err(BlockImportError::BadBlock(peer_id)) => + Err(BlockImportError::BadBlock(peer_id)) => { if let Some(peer) = peer_id { warn!( target: LOG_TARGET, "💔 Block {hash:?} received from peer {peer} has been blacklisted", ); self.actions.push(SyncingAction::DropPeer(BadPeer(peer, rep::BAD_BLOCK))); - }, + } + }, Err(BlockImportError::MissingState) => { // This may happen if the chain we were requesting upon has been discarded // in the meantime because other chain has been finalized. @@ -1096,9 +1098,9 @@ where Ok(req) }, - Ok(BlockStatus::Queued) | - Ok(BlockStatus::InChainWithState) | - Ok(BlockStatus::InChainPruned) => { + Ok(BlockStatus::Queued) + | Ok(BlockStatus::InChainWithState) + | Ok(BlockStatus::InChainPruned) => { debug!( target: LOG_TARGET, "New peer {peer_id} with known best hash {best_hash} ({best_number}).", @@ -1278,8 +1280,8 @@ where }, }; if matching_hash.is_some() { - if *start < self.best_queued_number && - self.best_queued_number <= peer.best_number + if *start < self.best_queued_number + && self.best_queued_number <= peer.best_number { // We've made progress on this chain since the search was started. // Opportunistically set common number to updated number @@ -1335,8 +1337,8 @@ where matching_hash, peer.common_number, ); - if peer.common_number < peer.best_number && - peer.best_number < self.best_queued_number + if peer.common_number < peer.best_number + && peer.best_number < self.best_queued_number { trace!( target: LOG_TARGET, @@ -1364,9 +1366,9 @@ where return Ok(()); } }, - PeerSyncState::Available | - PeerSyncState::DownloadingJustification(..) | - PeerSyncState::DownloadingState => Vec::new(), + PeerSyncState::Available + | PeerSyncState::DownloadingJustification(..) + | PeerSyncState::DownloadingState => Vec::new(), } } else { // When request.is_none() this is a block announcement. Just accept blocks. @@ -1525,14 +1527,17 @@ where fn required_block_attributes(&self) -> BlockAttributes { match self.mode { - ChainSyncMode::Full => - BlockAttributes::HEADER | BlockAttributes::JUSTIFICATION | BlockAttributes::BODY, - ChainSyncMode::LightState { storage_chain_mode: false, .. } => - BlockAttributes::HEADER | BlockAttributes::JUSTIFICATION | BlockAttributes::BODY, - ChainSyncMode::LightState { storage_chain_mode: true, .. } => - BlockAttributes::HEADER | - BlockAttributes::JUSTIFICATION | - BlockAttributes::INDEXED_BODY, + ChainSyncMode::Full => { + BlockAttributes::HEADER | BlockAttributes::JUSTIFICATION | BlockAttributes::BODY + }, + ChainSyncMode::LightState { storage_chain_mode: false, .. } => { + BlockAttributes::HEADER | BlockAttributes::JUSTIFICATION | BlockAttributes::BODY + }, + ChainSyncMode::LightState { storage_chain_mode: true, .. } => { + BlockAttributes::HEADER + | BlockAttributes::JUSTIFICATION + | BlockAttributes::INDEXED_BODY + }, } } @@ -1653,11 +1658,11 @@ where PeerSyncState::Available => { self.add_peer(peer_id, peer_sync.best_hash, peer_sync.best_number); }, - PeerSyncState::AncestorSearch { .. } | - PeerSyncState::DownloadingNew(_) | - PeerSyncState::DownloadingStale(_) | - PeerSyncState::DownloadingGap(_) | - PeerSyncState::DownloadingState => { + PeerSyncState::AncestorSearch { .. } + | PeerSyncState::DownloadingNew(_) + | PeerSyncState::DownloadingStale(_) + | PeerSyncState::DownloadingGap(_) + | PeerSyncState::DownloadingState => { // Cancel a request first, as `add_peer` may generate a new request. self.actions .push(SyncingAction::CancelRequest { peer_id, key: Self::STRATEGY_KEY }); @@ -1699,8 +1704,8 @@ where self.best_queued_hash = info.best_hash; self.best_queued_number = info.best_number; - if self.mode == ChainSyncMode::Full && - self.client.block_status(info.best_hash)? != BlockStatus::InChainWithState + if self.mode == ChainSyncMode::Full + && self.client.block_status(info.best_hash)? != BlockStatus::InChainWithState { self.import_existing = true; // Latest state is missing, start with the last finalized state or genesis instead. @@ -1835,9 +1840,9 @@ where .peers .iter_mut() .filter_map(move |(&id, peer)| { - if !peer.state.is_available() || - !allowed_requests.contains(&id) || - !disconnected_peers.is_peer_available(&id) + if !peer.state.is_available() + || !allowed_requests.contains(&id) + || !disconnected_peers.is_peer_available(&id) { return None; } @@ -1847,11 +1852,11 @@ where // common number is smaller than the last finalized block number, we should do an // ancestor search to find a better common block. If the queue is full we wait till // all blocks are imported though. - if best_queued.saturating_sub(peer.common_number) > - MAX_BLOCKS_TO_LOOK_BACKWARDS.into() && - best_queued < peer.best_number && - peer.common_number < last_finalized && - queue_blocks.len() <= MAJOR_SYNC_BLOCKS as usize + if best_queued.saturating_sub(peer.common_number) + > MAX_BLOCKS_TO_LOOK_BACKWARDS.into() + && best_queued < peer.best_number + && peer.common_number < last_finalized + && queue_blocks.len() <= MAJOR_SYNC_BLOCKS as usize { trace!( target: LOG_TARGET, @@ -1947,8 +1952,8 @@ where if self.allowed_requests.is_empty() { return None; } - if self.state_sync.is_some() && - self.peers.iter().any(|(_, peer)| peer.state == PeerSyncState::DownloadingState) + if self.state_sync.is_some() + && self.peers.iter().any(|(_, peer)| peer.state == PeerSyncState::DownloadingState) { // Only one pending state request is allowed. return None; @@ -1959,9 +1964,9 @@ where } for (id, peer) in self.peers.iter_mut() { - if peer.state.is_available() && - peer.common_number >= sync.target_number() && - self.disconnected_peers.is_peer_available(&id) + if peer.state.is_available() + && peer.common_number >= sync.target_number() + && self.disconnected_peers.is_peer_available(&id) { peer.state = PeerSyncState::DownloadingState; let request = sync.next_request(); @@ -2286,8 +2291,8 @@ fn fork_sync_request( } // Download the fork only if it is behind or not too far ahead our tip of the chain // Otherwise it should be downloaded in full sync mode. - if r.number <= best_num || - (r.number - best_num).saturated_into::() < max_blocks_per_request as u32 + if r.number <= best_num + || (r.number - best_num).saturated_into::() < max_blocks_per_request as u32 { let parent_status = r.parent_hash.as_ref().map_or(BlockStatus::Unknown, check_block); let count = if parent_status == BlockStatus::Unknown { @@ -2378,8 +2383,8 @@ pub fn validate_blocks( return Err(BadPeer(*peer_id, rep::NOT_REQUESTED)); } - if request.fields.contains(BlockAttributes::HEADER) && - blocks.iter().any(|b| b.header.is_none()) + if request.fields.contains(BlockAttributes::HEADER) + && blocks.iter().any(|b| b.header.is_none()) { trace!( target: LOG_TARGET, diff --git a/bizinikiwi/client/network/sync/src/strategy/chain_sync/test.rs b/bizinikiwi/client/network/sync/src/strategy/chain_sync/test.rs index 667beb8f..bda04947 100644 --- a/bizinikiwi/client/network/sync/src/strategy/chain_sync/test.rs +++ b/bizinikiwi/client/network/sync/src/strategy/chain_sync/test.rs @@ -211,9 +211,9 @@ fn restart_doesnt_affect_peers_downloading_finality_data() { // the justification request should be scheduled to the // new peer which is at the given block assert!(sync.justification_requests().iter().any(|(p, r)| { - *p == peer_id3 && - r.fields == BlockAttributes::JUSTIFICATION && - r.from == FromBlock::Hash(b1_hash) + *p == peer_id3 + && r.fields == BlockAttributes::JUSTIFICATION + && r.from == FromBlock::Hash(b1_hash) })); assert_eq!( diff --git a/bizinikiwi/client/network/sync/src/strategy/pezkuwi.rs b/bizinikiwi/client/network/sync/src/strategy/pezkuwi.rs index 0ea5bb2a..57ac33ab 100644 --- a/bizinikiwi/client/network/sync/src/strategy/pezkuwi.rs +++ b/bizinikiwi/client/network/sync/src/strategy/pezkuwi.rs @@ -47,8 +47,9 @@ use std::{any::Any, collections::HashMap, sync::Arc}; fn chain_sync_mode(sync_mode: SyncMode) -> ChainSyncMode { match sync_mode { SyncMode::Full => ChainSyncMode::Full, - SyncMode::LightState { skip_proofs, storage_chain_mode } => - ChainSyncMode::LightState { skip_proofs, storage_chain_mode }, + SyncMode::LightState { skip_proofs, storage_chain_mode } => { + ChainSyncMode::LightState { skip_proofs, storage_chain_mode } + }, SyncMode::Warp => ChainSyncMode::Full, } } @@ -188,7 +189,7 @@ where response: Box, ) { match key { - StateStrategy::::STRATEGY_KEY => + StateStrategy::::STRATEGY_KEY => { if let Some(state) = &mut self.state { let Ok(response) = response.downcast::>() else { warn!(target: LOG_TARGET, "Failed to downcast state response"); @@ -206,8 +207,9 @@ where or corresponding strategy is not active.", ); debug_assert!(false); - }, - WarpSync::::STRATEGY_KEY => + } + }, + WarpSync::::STRATEGY_KEY => { if let Some(warp) = &mut self.warp { warp.on_generic_response(peer_id, protocol_name, response); } else { @@ -217,8 +219,9 @@ where or warp strategy is not active", ); debug_assert!(false); - }, - ChainSync::::STRATEGY_KEY => + } + }, + ChainSync::::STRATEGY_KEY => { if let Some(chain_sync) = &mut self.chain_sync { chain_sync.on_generic_response(peer_id, key, protocol_name, response); } else { @@ -228,7 +231,8 @@ where or corresponding strategy is not active.", ); debug_assert!(false); - }, + } + }, key => { warn!( target: LOG_TARGET, @@ -268,9 +272,9 @@ where } fn is_major_syncing(&self) -> bool { - self.warp.is_some() || - self.state.is_some() || - match self.chain_sync { + self.warp.is_some() + || self.state.is_some() + || match self.chain_sync { Some(ref s) => s.status().state.is_major_syncing(), None => unreachable!("At least one syncing strategy is active; qed"), } diff --git a/bizinikiwi/client/network/sync/src/strategy/state.rs b/bizinikiwi/client/network/sync/src/strategy/state.rs index 398beb67..3db49a94 100644 --- a/bizinikiwi/client/network/sync/src/strategy/state.rs +++ b/bizinikiwi/client/network/sync/src/strategy/state.rs @@ -322,9 +322,9 @@ impl StateStrategy { // Find a random peer that is synced as much as peer majority and is above // `min_best_number`. for (peer_id, peer) in self.peers.iter_mut() { - if peer.state.is_available() && - peer.best_number >= threshold && - self.disconnected_peers.is_peer_available(peer_id) + if peer.state.is_available() + && peer.best_number >= threshold + && self.disconnected_peers.is_peer_available(peer_id) { peer.state = new_state; return Some(*peer_id); diff --git a/bizinikiwi/client/network/sync/src/strategy/warp.rs b/bizinikiwi/client/network/sync/src/strategy/warp.rs index 35449c2b..9fe4b90a 100644 --- a/bizinikiwi/client/network/sync/src/strategy/warp.rs +++ b/bizinikiwi/client/network/sync/src/strategy/warp.rs @@ -261,8 +261,9 @@ where } let phase = match warp_sync_config { - WarpSyncConfig::WithProvider(warp_sync_provider) => - Phase::WaitingForPeers { warp_sync_provider }, + WarpSyncConfig::WithProvider(warp_sync_provider) => { + Phase::WaitingForPeers { warp_sync_provider } + }, WarpSyncConfig::WithTarget(target_header) => Phase::TargetBlock(target_header), }; @@ -558,9 +559,9 @@ where // Find a random peer that is synced as much as peer majority and is above // `min_best_number`. for (peer_id, peer) in self.peers.iter_mut() { - if peer.state.is_available() && - peer.best_number >= threshold && - self.disconnected_peers.is_peer_available(peer_id) + if peer.state.is_available() + && peer.best_number >= threshold + && self.disconnected_peers.is_peer_available(peer_id) { peer.state = new_state; return Some(*peer_id); @@ -632,9 +633,9 @@ where peer_id, BlockRequest:: { id: 0, - fields: BlockAttributes::HEADER | - BlockAttributes::BODY | - BlockAttributes::JUSTIFICATION, + fields: BlockAttributes::HEADER + | BlockAttributes::BODY + | BlockAttributes::JUSTIFICATION, from: FromBlock::Hash(target_hash), direction: Direction::Ascending, max: Some(1), diff --git a/bizinikiwi/client/network/test/src/fuzz.rs b/bizinikiwi/client/network/test/src/fuzz.rs index 2530ea1f..a1eaaf43 100644 --- a/bizinikiwi/client/network/test/src/fuzz.rs +++ b/bizinikiwi/client/network/test/src/fuzz.rs @@ -259,7 +259,7 @@ async fn test_once() { let state = known_nodes.get_mut(&peer_id).unwrap(); match *state { - State::Incoming(incoming_index) => + State::Incoming(incoming_index) => { if n.0 < incoming_index.0 { log::info!( "Ignoring obsolete Accept for {:?} while awaiting {:?} for peer {}", @@ -271,7 +271,8 @@ async fn test_once() { "Received {:?} while awaiting {:?} for peer {}", n, incoming_index, peer_id, ); - }, + } + }, _ => {}, } @@ -290,7 +291,7 @@ async fn test_once() { let state = known_nodes.get_mut(&peer_id).unwrap(); match *state { - State::Incoming(incoming_index) => + State::Incoming(incoming_index) => { if n.0 < incoming_index.0 { log::info!( "Ignoring obsolete Reject for {:?} while awaiting {:?} for peer {}", @@ -302,7 +303,8 @@ async fn test_once() { "Received {:?} while awaiting {:?} for peer {}", n, incoming_index, peer_id, ); - }, + } + }, _ => {}, } @@ -326,15 +328,16 @@ async fn test_once() { }, // If we generate 2, adjust a random reputation. - 2 => + 2 => { if let Some(id) = known_nodes.keys().choose(&mut rng) { let val = Uniform::new_inclusive(i32::MIN, i32::MAX).sample(&mut rng); let peer: pezsc_network_types::PeerId = id.into(); peer_store_handle.report_peer(peer, ReputationChange::new(val, "")); - }, + } + }, // If we generate 3, disconnect from a random node. - 3 => + 3 => { if let Some(id) = connected_nodes.iter().choose(&mut rng).cloned() { log::info!("Disconnected from {}", id); connected_nodes.remove(&id); @@ -347,15 +350,16 @@ async fn test_once() { current_peer = Some(id); current_event = Some(Event::Disconnected); - }, + } + }, // If we generate 4, connect to a random node. 4 => { if let Some(id) = known_nodes .keys() .filter(|n| { - incoming_nodes.values().all(|m| m != *n) && - !connected_nodes.contains(*n) + incoming_nodes.values().all(|m| m != *n) + && !connected_nodes.contains(*n) }) .choose(&mut rng) .cloned() @@ -395,12 +399,13 @@ async fn test_once() { reserved_nodes.insert(*id); } }, - 8 => + 8 => { if let Some(id) = reserved_nodes.iter().choose(&mut rng).cloned() { log::info!("Remove reserved: {}", id); reserved_nodes.remove(&id); protocol_handle.remove_reserved_peer(id); - }, + } + }, _ => unreachable!(), } diff --git a/bizinikiwi/client/network/test/src/lib.rs b/bizinikiwi/client/network/test/src/lib.rs index 493c44df..7d4ee664 100644 --- a/bizinikiwi/client/network/test/src/lib.rs +++ b/bizinikiwi/client/network/test/src/lib.rs @@ -768,8 +768,8 @@ pub trait TestNetFactory: Default + Sized + Send { *genesis_extra_storage = storage; } - if !config.force_genesis && - matches!(config.sync_mode, SyncMode::LightState { .. } | SyncMode::Warp) + if !config.force_genesis + && matches!(config.sync_mode, SyncMode::LightState { .. } | SyncMode::Warp) { test_client_builder = test_client_builder.set_no_genesis(); } @@ -1040,8 +1040,8 @@ pub trait TestNetFactory: Default + Sized + Send { let peers = self.peers_mut(); for peer in peers { - if peer.sync_service.is_major_syncing() || - peer.sync_service.status().await.unwrap().queued_blocks != 0 + if peer.sync_service.is_major_syncing() + || peer.sync_service.status().await.unwrap().queued_blocks != 0 { return false; } diff --git a/bizinikiwi/client/network/test/src/service.rs b/bizinikiwi/client/network/test/src/service.rs index 0b2c5ee8..0c7a770f 100644 --- a/bizinikiwi/client/network/test/src/service.rs +++ b/bizinikiwi/client/network/test/src/service.rs @@ -392,10 +392,12 @@ async fn notifications_state_consistent() { // forever while nothing at all happens on the network. let continue_test = futures_timer::Delay::new(Duration::from_millis(20)); match future::select(future::select(next1, next2), continue_test).await { - future::Either::Left((future::Either::Left((Some(ev), _)), _)) => - future::Either::Left(ev), - future::Either::Left((future::Either::Right((Some(ev), _)), _)) => - future::Either::Right(ev), + future::Either::Left((future::Either::Left((Some(ev), _)), _)) => { + future::Either::Left(ev) + }, + future::Either::Left((future::Either::Right((Some(ev), _)), _)) => { + future::Either::Right(ev) + }, future::Either::Right(_) => continue, _ => break, } diff --git a/bizinikiwi/client/network/test/src/sync.rs b/bizinikiwi/client/network/test/src/sync.rs index dfeef79f..5bb37557 100644 --- a/bizinikiwi/client/network/test/src/sync.rs +++ b/bizinikiwi/client/network/test/src/sync.rs @@ -44,9 +44,9 @@ async fn sync_peers_works() { pezsp_tracing::try_init_simple(); let mut net = TestNet::new(3); - while net.peer(0).num_peers().await != 2 && - net.peer(1).num_peers().await != 2 && - net.peer(2).num_peers().await != 2 + while net.peer(0).num_peers().await != 2 + && net.peer(1).num_peers().await != 2 + && net.peer(2).num_peers().await != 2 { futures::future::poll_fn::<(), _>(|cx| { net.poll(cx); @@ -280,13 +280,13 @@ async fn sync_justifications() { net.poll(cx); for height in (10..21).step_by(5) { - if net.peer(0).client().justifications(hashes[height - 1]).unwrap() != - Some(Justifications::from((*b"FRNK", Vec::new()))) + if net.peer(0).client().justifications(hashes[height - 1]).unwrap() + != Some(Justifications::from((*b"FRNK", Vec::new()))) { return Poll::Pending; } - if net.peer(1).client().justifications(hashes[height - 1]).unwrap() != - Some(Justifications::from((*b"FRNK", Vec::new()))) + if net.peer(1).client().justifications(hashes[height - 1]).unwrap() + != Some(Justifications::from((*b"FRNK", Vec::new()))) { return Poll::Pending; } @@ -320,10 +320,10 @@ async fn sync_justifications_across_forks() { futures::future::poll_fn::<(), _>(|cx| { net.poll(cx); - if net.peer(0).client().justifications(f1_best).unwrap() == - Some(Justifications::from((*b"FRNK", Vec::new()))) && - net.peer(1).client().justifications(f1_best).unwrap() == - Some(Justifications::from((*b"FRNK", Vec::new()))) + if net.peer(0).client().justifications(f1_best).unwrap() + == Some(Justifications::from((*b"FRNK", Vec::new()))) + && net.peer(1).client().justifications(f1_best).unwrap() + == Some(Justifications::from((*b"FRNK", Vec::new()))) { Poll::Ready(()) } else { @@ -896,9 +896,9 @@ async fn block_announce_data_is_propagated() { }); // Wait until peer 1 is connected to both nodes. - while net.peer(1).num_peers().await != 2 || - net.peer(0).num_peers().await != 1 || - net.peer(2).num_peers().await != 1 + while net.peer(1).num_peers().await != 2 + || net.peer(0).num_peers().await != 1 + || net.peer(2).num_peers().await != 1 { futures::future::poll_fn::<(), _>(|cx| { net.poll(cx); @@ -1000,8 +1000,8 @@ async fn multiple_requests_are_accepted_as_long_as_they_are_not_fulfilled() { futures::future::poll_fn::<(), _>(|cx| { net.poll(cx); - if net.peer(1).client().justifications(hashof10).unwrap() != - Some(Justifications::from((*b"FRNK", Vec::new()))) + if net.peer(1).client().justifications(hashof10).unwrap() + != Some(Justifications::from((*b"FRNK", Vec::new()))) { return Poll::Pending; } diff --git a/bizinikiwi/client/network/transactions/src/lib.rs b/bizinikiwi/client/network/transactions/src/lib.rs index 678ecfaf..c90b8337 100644 --- a/bizinikiwi/client/network/transactions/src/lib.rs +++ b/bizinikiwi/client/network/transactions/src/lib.rs @@ -443,8 +443,9 @@ where fn on_handle_transaction_import(&mut self, who: PeerId, import: TransactionImport) { match import { - TransactionImport::KnownGood => - self.network.report_peer(who, rep::ANY_TRANSACTION_REFUND), + TransactionImport::KnownGood => { + self.network.report_peer(who, rep::ANY_TRANSACTION_REFUND) + }, TransactionImport::NewGood => self.network.report_peer(who, rep::GOOD_TRANSACTION), TransactionImport::Bad => self.network.report_peer(who, rep::BAD_TRANSACTION), TransactionImport::None => {}, diff --git a/bizinikiwi/client/network/types/src/multiaddr/protocol.rs b/bizinikiwi/client/network/types/src/multiaddr/protocol.rs index 417f6bdb..5d0c394d 100644 --- a/bizinikiwi/client/network/types/src/multiaddr/protocol.rs +++ b/bizinikiwi/client/network/types/src/multiaddr/protocol.rs @@ -116,8 +116,9 @@ impl<'a> From> for Protocol<'a> { LiteP2pProtocol::P2pWebSocketStar => Protocol::P2pWebSocketStar, LiteP2pProtocol::Memory(port) => Protocol::Memory(port), LiteP2pProtocol::Onion(str, port) => Protocol::Onion(str, port), - LiteP2pProtocol::Onion3(addr) => - Protocol::Onion3(Cow::Owned(*addr.hash()), addr.port()), + LiteP2pProtocol::Onion3(addr) => { + Protocol::Onion3(Cow::Owned(*addr.hash()), addr.port()) + }, LiteP2pProtocol::P2p(multihash) => Protocol::P2p(multihash.into()), LiteP2pProtocol::P2pCircuit => Protocol::P2pCircuit, LiteP2pProtocol::Quic => Protocol::Quic, diff --git a/bizinikiwi/client/network/types/src/peer_id.rs b/bizinikiwi/client/network/types/src/peer_id.rs index 44ec2d7f..cdae7419 100644 --- a/bizinikiwi/client/network/types/src/peer_id.rs +++ b/bizinikiwi/client/network/types/src/peer_id.rs @@ -77,8 +77,9 @@ impl PeerId { pub fn from_multihash(multihash: Multihash) -> Result { match Code::try_from(multihash.code()) { Ok(Code::Sha2_256) => Ok(PeerId { multihash }), - Ok(Code::Identity) if multihash.digest().len() <= MAX_INLINE_KEY_LENGTH => - Ok(PeerId { multihash }), + Ok(Code::Identity) if multihash.digest().len() <= MAX_INLINE_KEY_LENGTH => { + Ok(PeerId { multihash }) + }, _ => Err(multihash), } } diff --git a/bizinikiwi/client/offchain/src/api/http.rs b/bizinikiwi/client/offchain/src/api/http.rs index 166e8c77..76477c65 100644 --- a/bizinikiwi/client/offchain/src/api/http.rs +++ b/bizinikiwi/client/offchain/src/api/http.rs @@ -324,8 +324,8 @@ impl HttpApi { return Err(HttpError::IoError); }, - v @ HttpApiRequest::Dispatched(None) | - v @ HttpApiRequest::Response(HttpApiRequestRp { sending_body: None, .. }) => { + v @ HttpApiRequest::Dispatched(None) + | v @ HttpApiRequest::Response(HttpApiRequestRp { sending_body: None, .. }) => { tracing::debug!(target: LOG_TARGET, id = %request_id.0, "Body sending already finished"); // We have already finished sending this body. @@ -347,8 +347,8 @@ impl HttpApi { for id in ids { match self.requests.get_mut(id) { Some(HttpApiRequest::NotDispatched(_, _)) => {}, - Some(HttpApiRequest::Dispatched(sending_body)) | - Some(HttpApiRequest::Response(HttpApiRequestRp { sending_body, .. })) => { + Some(HttpApiRequest::Dispatched(sending_body)) + | Some(HttpApiRequest::Response(HttpApiRequestRp { sending_body, .. })) => { let _ = sending_body.take(); continue; }, @@ -554,10 +554,11 @@ impl HttpApi { if let future::MaybeDone::Done(next_body) = next_body { match next_body { - Some(Ok(chunk)) => + Some(Ok(chunk)) => { if let Ok(chunk) = chunk.into_data() { response.current_read_chunk = Some(chunk.reader()); - }, + } + }, Some(Err(_)) => return Err(HttpError::IoError), None => return Ok(0), // eof } @@ -580,8 +581,9 @@ impl fmt::Debug for HttpApi { impl fmt::Debug for HttpApiRequest { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - HttpApiRequest::NotDispatched(_, _) => - f.debug_tuple("HttpApiRequest::NotDispatched").finish(), + HttpApiRequest::NotDispatched(_, _) => { + f.debug_tuple("HttpApiRequest::NotDispatched").finish() + }, HttpApiRequest::Dispatched(_) => f.debug_tuple("HttpApiRequest::Dispatched").finish(), HttpApiRequest::Response(HttpApiRequestRp { status_code, headers, .. }) => f .debug_tuple("HttpApiRequest::Response") @@ -761,10 +763,12 @@ impl fmt::Debug for HttpWorker { impl fmt::Debug for HttpWorkerRequest { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - HttpWorkerRequest::Dispatched(_) => - f.debug_tuple("HttpWorkerRequest::Dispatched").finish(), - HttpWorkerRequest::ReadBody { .. } => - f.debug_tuple("HttpWorkerRequest::Response").finish(), + HttpWorkerRequest::Dispatched(_) => { + f.debug_tuple("HttpWorkerRequest::Dispatched").finish() + }, + HttpWorkerRequest::ReadBody { .. } => { + f.debug_tuple("HttpWorkerRequest::Response").finish() + }, } } } diff --git a/bizinikiwi/client/offchain/src/api/timestamp.rs b/bizinikiwi/client/offchain/src/api/timestamp.rs index 77553ed3..5322e87f 100644 --- a/bizinikiwi/client/offchain/src/api/timestamp.rs +++ b/bizinikiwi/client/offchain/src/api/timestamp.rs @@ -60,8 +60,9 @@ pub fn deadline_to_future( future::maybe_done(match deadline.map(timestamp_from_now) { None => Either::Left(future::pending()), // Only apply delay if we need to wait a non-zero duration - Some(duration) if duration <= Duration::from_secs(0) => - Either::Right(Either::Left(future::ready(()))), + Some(duration) if duration <= Duration::from_secs(0) => { + Either::Right(Either::Left(future::ready(()))) + }, Some(duration) => Either::Right(Either::Right(futures_timer::Delay::new(duration))), }) } diff --git a/bizinikiwi/client/rpc-api/src/policy.rs b/bizinikiwi/client/rpc-api/src/policy.rs index 89979330..1a5276d8 100644 --- a/bizinikiwi/client/rpc-api/src/policy.rs +++ b/bizinikiwi/client/rpc-api/src/policy.rs @@ -28,8 +28,9 @@ pub fn check_if_safe(ext: &jsonrpsee::Extensions) -> Result<(), UnsafeRpcError> match ext.get::().map(|deny_unsafe| deny_unsafe.check_if_safe()) { Some(Ok(())) => Ok(()), Some(Err(e)) => Err(e), - None => - unreachable!("DenyUnsafe extension is always set by the bizinikiwi rpc server; qed"), + None => { + unreachable!("DenyUnsafe extension is always set by the bizinikiwi rpc server; qed") + }, } } diff --git a/bizinikiwi/client/rpc-api/src/state/error.rs b/bizinikiwi/client/rpc-api/src/state/error.rs index 6c8f1eac..380c467d 100644 --- a/bizinikiwi/client/rpc-api/src/state/error.rs +++ b/bizinikiwi/client/rpc-api/src/state/error.rs @@ -58,10 +58,12 @@ const BASE_ERROR: i32 = crate::error::base::STATE; impl From for ErrorObjectOwned { fn from(e: Error) -> ErrorObjectOwned { match e { - Error::InvalidBlockRange { .. } => - ErrorObject::owned(BASE_ERROR + 1, e.to_string(), None::<()>), - Error::InvalidCount { .. } => - ErrorObject::owned(BASE_ERROR + 2, e.to_string(), None::<()>), + Error::InvalidBlockRange { .. } => { + ErrorObject::owned(BASE_ERROR + 1, e.to_string(), None::<()>) + }, + Error::InvalidCount { .. } => { + ErrorObject::owned(BASE_ERROR + 2, e.to_string(), None::<()>) + }, e => ErrorObject::owned(BASE_ERROR + 3, e.to_string(), None::<()>), } } diff --git a/bizinikiwi/client/rpc-api/src/system/error.rs b/bizinikiwi/client/rpc-api/src/system/error.rs index bb7e5a1d..c2197e24 100644 --- a/bizinikiwi/client/rpc-api/src/system/error.rs +++ b/bizinikiwi/client/rpc-api/src/system/error.rs @@ -54,13 +54,16 @@ const MALFORMATTED_PEER_ARG_ERROR: i32 = BASE_ERROR + 2; impl From for ErrorObjectOwned { fn from(e: Error) -> ErrorObjectOwned { match e { - Error::NotHealthy(ref h) => - ErrorObject::owned(NOT_HEALTHY_ERROR, e.to_string(), Some(h)), - Error::MalformattedPeerArg(e) => - ErrorObject::owned(MALFORMATTED_PEER_ARG_ERROR, e, None::<()>), + Error::NotHealthy(ref h) => { + ErrorObject::owned(NOT_HEALTHY_ERROR, e.to_string(), Some(h)) + }, + Error::MalformattedPeerArg(e) => { + ErrorObject::owned(MALFORMATTED_PEER_ARG_ERROR, e, None::<()>) + }, Error::UnsafeRpcCalled(e) => e.into(), - Error::Internal(e) => - ErrorObjectOwned::owned(ErrorCode::InternalError.code(), e, None::<()>), + Error::Internal(e) => { + ErrorObjectOwned::owned(ErrorCode::InternalError.code(), e, None::<()>) + }, } } } diff --git a/bizinikiwi/client/rpc-servers/src/middleware/node_health.rs b/bizinikiwi/client/rpc-servers/src/middleware/node_health.rs index 9c66c876..cdd79f0d 100644 --- a/bizinikiwi/client/rpc-servers/src/middleware/node_health.rs +++ b/bizinikiwi/client/rpc-servers/src/middleware/node_health.rs @@ -99,8 +99,9 @@ where async move { Ok(match maybe_intercept { - InterceptRequest::Deny => - http_response(StatusCode::METHOD_NOT_ALLOWED, HttpBody::empty()), + InterceptRequest::Deny => { + http_response(StatusCode::METHOD_NOT_ALLOWED, HttpBody::empty()) + }, InterceptRequest::No => fut.await.map_err(|err| err.into())?, InterceptRequest::Health => { let res = fut.await.map_err(|err| err.into())?; @@ -114,9 +115,11 @@ where let res = fut.await.map_err(|err| err.into())?; match parse_rpc_response(res.into_body()).await { Ok(health) - if (!health.is_syncing && health.peers > 0) || - !health.should_have_peers => - http_ok_response(HttpBody::empty()), + if (!health.is_syncing && health.peers > 0) + || !health.should_have_peers => + { + http_ok_response(HttpBody::empty()) + }, _ => http_internal_error(), } }, @@ -188,18 +191,20 @@ enum InterceptRequest { impl InterceptRequest { fn from_http(req: &HttpRequest) -> InterceptRequest { match req.uri().path() { - "/health" => + "/health" => { if req.method() == http::Method::GET { InterceptRequest::Health } else { InterceptRequest::Deny - }, - "/health/readiness" => + } + }, + "/health/readiness" => { if req.method() == http::Method::GET { InterceptRequest::Readiness } else { InterceptRequest::Deny - }, + } + }, // Forward all other requests to the RPC server. _ => InterceptRequest::No, } diff --git a/bizinikiwi/client/rpc-spec-v2/src/archive/archive.rs b/bizinikiwi/client/rpc-spec-v2/src/archive/archive.rs index c5da5605..c42ac115 100644 --- a/bizinikiwi/client/rpc-spec-v2/src/archive/archive.rs +++ b/bizinikiwi/client/rpc-spec-v2/src/archive/archive.rs @@ -233,8 +233,8 @@ where let key = StorageKey(parse_hex_param(query.key)?); // Validate that paginationStartKey is only used with descendant queries - if query.pagination_start_key.is_some() && - !query.query_type.is_descendant_query() + if query.pagination_start_key.is_some() + && !query.query_type.is_descendant_query() { return Err(ArchiveError::InvalidParam( "paginationStartKey is only valid for descendantsValues and descendantsHashes query types" diff --git a/bizinikiwi/client/rpc-spec-v2/src/archive/archive_storage.rs b/bizinikiwi/client/rpc-spec-v2/src/archive/archive_storage.rs index ee3626ac..c0dea80e 100644 --- a/bizinikiwi/client/rpc-spec-v2/src/archive/archive_storage.rs +++ b/bizinikiwi/client/rpc-spec-v2/src/archive/archive_storage.rs @@ -234,8 +234,9 @@ where }; let maybe_result = match operation_type { - ArchiveStorageDiffOperationType::Added => - self.fetch_storage(hash, key.clone(), maybe_child_trie.clone(), fetch_type)?, + ArchiveStorageDiffOperationType::Added => { + self.fetch_storage(hash, key.clone(), maybe_child_trie.clone(), fetch_type)? + }, ArchiveStorageDiffOperationType::Deleted => self.fetch_storage( previous_hash, key.clone(), @@ -373,7 +374,7 @@ where let mut b = right.next(); core::iter::from_fn(move || match (a.take(), b.take()) { - (Some(a_value), Some(b_value)) => + (Some(a_value), Some(b_value)) => { if a_value < b_value { b = Some(b_value); a = left.next(); @@ -389,7 +390,8 @@ where b = right.next(); Some(Diff::Equal(a_value)) - }, + } + }, (Some(a_value), None) => { a = left.next(); Some(Diff::Added(a_value)) diff --git a/bizinikiwi/client/rpc-spec-v2/src/chain_head/chain_head.rs b/bizinikiwi/client/rpc-spec-v2/src/chain_head/chain_head.rs index a7dd78b9..80f1b457 100644 --- a/bizinikiwi/client/rpc-spec-v2/src/chain_head/chain_head.rs +++ b/bizinikiwi/client/rpc-spec-v2/src/chain_head/chain_head.rs @@ -276,9 +276,10 @@ where let result = spawn_blocking(&self.executor, async move { let mut block_guard = match subscriptions.lock_block(&follow_subscription, hash, 1) { Ok(block) => block, - Err(SubscriptionManagementError::SubscriptionAbsent) | - Err(SubscriptionManagementError::ExceededLimits) => - return ResponsePayload::success(MethodResponse::LimitReached), + Err(SubscriptionManagementError::SubscriptionAbsent) + | Err(SubscriptionManagementError::ExceededLimits) => { + return ResponsePayload::success(MethodResponse::LimitReached) + }, Err(SubscriptionManagementError::BlockHashAbsent) => { // Block is not part of the subscription. return ResponsePayload::error(ChainHeadRpcError::InvalidBlock); @@ -355,8 +356,8 @@ where let block_guard = match self.subscriptions.lock_block(&follow_subscription, hash, 1) { Ok(block) => block, - Err(SubscriptionManagementError::SubscriptionAbsent) | - Err(SubscriptionManagementError::ExceededLimits) => return Ok(None), + Err(SubscriptionManagementError::SubscriptionAbsent) + | Err(SubscriptionManagementError::ExceededLimits) => return Ok(None), Err(SubscriptionManagementError::BlockHashAbsent) => { // Block is not part of the subscription. return Err(ChainHeadRpcError::InvalidBlock.into()); @@ -419,8 +420,8 @@ where let mut block_guard = match self.subscriptions.lock_block(&follow_subscription, hash, items.len()) { Ok(block) => block, - Err(SubscriptionManagementError::SubscriptionAbsent) | - Err(SubscriptionManagementError::ExceededLimits) => { + Err(SubscriptionManagementError::SubscriptionAbsent) + | Err(SubscriptionManagementError::ExceededLimits) => { return ResponsePayload::success(MethodResponse::LimitReached); }, Err(SubscriptionManagementError::BlockHashAbsent) => { @@ -486,8 +487,8 @@ where let mut block_guard = match self.subscriptions.lock_block(&follow_subscription, hash, 1) { Ok(block) => block, - Err(SubscriptionManagementError::SubscriptionAbsent) | - Err(SubscriptionManagementError::ExceededLimits) => { + Err(SubscriptionManagementError::SubscriptionAbsent) + | Err(SubscriptionManagementError::ExceededLimits) => { // Invalid invalid subscription ID. return ResponsePayload::success(MethodResponse::LimitReached); }, @@ -556,10 +557,12 @@ where } let result = match hash_or_hashes { - ListOrValue::Value(hash) => - self.subscriptions.unpin_blocks(&follow_subscription, [hash]), - ListOrValue::List(hashes) => - self.subscriptions.unpin_blocks(&follow_subscription, hashes), + ListOrValue::Value(hash) => { + self.subscriptions.unpin_blocks(&follow_subscription, [hash]) + }, + ListOrValue::List(hashes) => { + self.subscriptions.unpin_blocks(&follow_subscription, hashes) + }, }; match result { @@ -572,8 +575,9 @@ where // Block is not part of the subscription. Err(ChainHeadRpcError::InvalidBlock) }, - Err(SubscriptionManagementError::DuplicateHashes) => - Err(ChainHeadRpcError::InvalidDuplicateHashes), + Err(SubscriptionManagementError::DuplicateHashes) => { + Err(ChainHeadRpcError::InvalidDuplicateHashes) + }, Err(_) => Err(ChainHeadRpcError::InvalidBlock), } } diff --git a/bizinikiwi/client/rpc-spec-v2/src/chain_head/chain_head_follow.rs b/bizinikiwi/client/rpc-spec-v2/src/chain_head/chain_head_follow.rs index 74dea3cf..e5a17881 100644 --- a/bizinikiwi/client/rpc-spec-v2/src/chain_head/chain_head_follow.rs +++ b/bizinikiwi/client/rpc-spec-v2/src/chain_head/chain_head_follow.rs @@ -257,7 +257,9 @@ where let parent = match parent { Some(parent) => parent, // Nothing to compare against, always report. - None => return Some(RuntimeEvent::Valid(RuntimeVersionEvent { spec: block_rt.into() })), + None => { + return Some(RuntimeEvent::Valid(RuntimeVersionEvent { spec: block_rt.into() })) + }, }; let parent_rt = match self.client.runtime_version_at(parent) { @@ -522,7 +524,9 @@ where let parent_block_hash = *notification.header.parent_hash(); if !self.announced_blocks.was_announced(&parent_block_hash) { // The parent block was not reported, we have a gap. - return Err(SubscriptionManagementError::Custom("Parent block was not reported".into())); + return Err(SubscriptionManagementError::Custom( + "Parent block was not reported".into(), + )); } self.announced_blocks.insert(block_hash, false); @@ -714,10 +718,12 @@ where // create a channel to propagate error messages let mut handle_events = |event| match event { NotificationType::InitialEvents(events) => Ok(events), - NotificationType::NewBlock(notification) => - self.handle_import_blocks(notification, &startup_point), - NotificationType::Finalized(notification) => - self.handle_finalized_blocks(notification, &startup_point), + NotificationType::NewBlock(notification) => { + self.handle_import_blocks(notification, &startup_point) + }, + NotificationType::Finalized(notification) => { + self.handle_finalized_blocks(notification, &startup_point) + }, NotificationType::MethodResponse(notification) => Ok(vec![notification]), }; diff --git a/bizinikiwi/client/rpc-spec-v2/src/chain_head/error.rs b/bizinikiwi/client/rpc-spec-v2/src/chain_head/error.rs index 6e02ff60..a88de023 100644 --- a/bizinikiwi/client/rpc-spec-v2/src/chain_head/error.rs +++ b/bizinikiwi/client/rpc-spec-v2/src/chain_head/error.rs @@ -75,20 +75,27 @@ impl From for ErrorObject<'static> { let msg = e.to_string(); match e { - Error::ReachedLimits => - ErrorObject::owned(rpc_spec_v2::REACHED_LIMITS, msg, None::<()>), - Error::InvalidBlock => - ErrorObject::owned(rpc_spec_v2::INVALID_BLOCK_ERROR, msg, None::<()>), - Error::InvalidRuntimeCall(_) => - ErrorObject::owned(rpc_spec_v2::INVALID_RUNTIME_CALL, msg, None::<()>), - Error::InvalidContinue => - ErrorObject::owned(rpc_spec_v2::INVALID_CONTINUE, msg, None::<()>), - Error::InvalidDuplicateHashes => - ErrorObject::owned(rpc_spec_v2::INVALID_DUPLICATE_HASHES, msg, None::<()>), - Error::InvalidParam(_) => - ErrorObject::owned(json_rpc_spec::INVALID_PARAM_ERROR, msg, None::<()>), - Error::InternalError(_) => - ErrorObject::owned(json_rpc_spec::INTERNAL_ERROR, msg, None::<()>), + Error::ReachedLimits => { + ErrorObject::owned(rpc_spec_v2::REACHED_LIMITS, msg, None::<()>) + }, + Error::InvalidBlock => { + ErrorObject::owned(rpc_spec_v2::INVALID_BLOCK_ERROR, msg, None::<()>) + }, + Error::InvalidRuntimeCall(_) => { + ErrorObject::owned(rpc_spec_v2::INVALID_RUNTIME_CALL, msg, None::<()>) + }, + Error::InvalidContinue => { + ErrorObject::owned(rpc_spec_v2::INVALID_CONTINUE, msg, None::<()>) + }, + Error::InvalidDuplicateHashes => { + ErrorObject::owned(rpc_spec_v2::INVALID_DUPLICATE_HASHES, msg, None::<()>) + }, + Error::InvalidParam(_) => { + ErrorObject::owned(json_rpc_spec::INVALID_PARAM_ERROR, msg, None::<()>) + }, + Error::InternalError(_) => { + ErrorObject::owned(json_rpc_spec::INTERNAL_ERROR, msg, None::<()>) + }, } } } diff --git a/bizinikiwi/client/rpc-spec-v2/src/chain_head/tests.rs b/bizinikiwi/client/rpc-spec-v2/src/chain_head/tests.rs index 536f3097..459e31ee 100644 --- a/bizinikiwi/client/rpc-spec-v2/src/chain_head/tests.rs +++ b/bizinikiwi/client/rpc-spec-v2/src/chain_head/tests.rs @@ -3335,16 +3335,18 @@ async fn storage_closest_merkle_value() { loop { match get_next_event::>(&mut sub).await { - FollowEvent::OperationStorageItems(res) if res.operation_id == operation_id => + FollowEvent::OperationStorageItems(res) if res.operation_id == operation_id => { for res in res.items { let value = match res.result { StorageResultType::ClosestDescendantMerkleValue(value) => value, _ => panic!("Unexpected StorageResultType"), }; merkle_values.insert(res.key, value); - }, - FollowEvent::OperationStorageDone(done) if done.operation_id == operation_id => - break, + } + }, + FollowEvent::OperationStorageDone(done) if done.operation_id == operation_id => { + break + }, _ => panic!("Unexpected event"), } } diff --git a/bizinikiwi/client/rpc-spec-v2/src/transaction/error.rs b/bizinikiwi/client/rpc-spec-v2/src/transaction/error.rs index 80505bd7..be368304 100644 --- a/bizinikiwi/client/rpc-spec-v2/src/transaction/error.rs +++ b/bizinikiwi/client/rpc-spec-v2/src/transaction/error.rs @@ -42,10 +42,11 @@ impl From for TransactionEvent { Error::Verification(e) => TransactionEvent::Invalid(TransactionError { error: format!("Verification error: {}", e), }), - Error::Pool(PoolError::InvalidTransaction(InvalidTransaction::Custom(e))) => + Error::Pool(PoolError::InvalidTransaction(InvalidTransaction::Custom(e))) => { TransactionEvent::Invalid(TransactionError { error: format!("Invalid transaction with custom error: {}", e), - }), + }) + }, Error::Pool(PoolError::InvalidTransaction(e)) => { let msg: &str = e.into(); TransactionEvent::Invalid(TransactionError { @@ -58,28 +59,32 @@ impl From for TransactionEvent { error: format!("Unknown transaction validity: {}", msg), }) }, - Error::Pool(PoolError::TemporarilyBanned) => + Error::Pool(PoolError::TemporarilyBanned) => { TransactionEvent::Invalid(TransactionError { error: "Transaction is temporarily banned".into(), - }), - Error::Pool(PoolError::AlreadyImported(_)) => + }) + }, + Error::Pool(PoolError::AlreadyImported(_)) => { TransactionEvent::Invalid(TransactionError { error: "Transaction is already imported".into(), - }), - Error::Pool(PoolError::TooLowPriority { old, new }) => + }) + }, + Error::Pool(PoolError::TooLowPriority { old, new }) => { TransactionEvent::Invalid(TransactionError { error: format!( "The priority of the transaction is too low (pool {} > current {})", old, new ), - }), + }) + }, Error::Pool(PoolError::CycleDetected) => TransactionEvent::Invalid(TransactionError { error: "The transaction contains a cyclic dependency".into(), }), - Error::Pool(PoolError::ImmediatelyDropped) => + Error::Pool(PoolError::ImmediatelyDropped) => { TransactionEvent::Invalid(TransactionError { error: "The transaction could not enter the pool because of the limit".into(), - }), + }) + }, Error::Pool(PoolError::Unactionable) => TransactionEvent::Invalid(TransactionError { error: "Transaction cannot be propagated and the local node does not author blocks" .into(), @@ -88,14 +93,16 @@ impl From for TransactionEvent { error: "Transaction does not provide any tags, so the pool cannot identify it" .into(), }), - Error::Pool(PoolError::InvalidBlockId(_)) => + Error::Pool(PoolError::InvalidBlockId(_)) => { TransactionEvent::Invalid(TransactionError { error: "The provided block ID is not valid".into(), - }), - Error::Pool(PoolError::RejectedFutureTransaction) => + }) + }, + Error::Pool(PoolError::RejectedFutureTransaction) => { TransactionEvent::Invalid(TransactionError { error: "The pool is not accepting future transactions".into(), - }), + }) + }, } } } @@ -120,8 +127,9 @@ impl From for ErrorObject<'static> { let msg = e.to_string(); match e { - ErrorBroadcast::InvalidOperationID => - ErrorObject::owned(json_rpc_spec::INVALID_PARAM_ERROR, msg, None::<()>), + ErrorBroadcast::InvalidOperationID => { + ErrorObject::owned(json_rpc_spec::INVALID_PARAM_ERROR, msg, None::<()>) + }, } } } diff --git a/bizinikiwi/client/rpc-spec-v2/src/transaction/event.rs b/bizinikiwi/client/rpc-spec-v2/src/transaction/event.rs index e6aa8be0..da223aad 100644 --- a/bizinikiwi/client/rpc-spec-v2/src/transaction/event.rs +++ b/bizinikiwi/client/rpc-spec-v2/src/transaction/event.rs @@ -100,10 +100,10 @@ impl TransactionEvent { pub fn is_final(&self) -> bool { matches!( &self, - TransactionEvent::Finalized(_) | - TransactionEvent::Error(_) | - TransactionEvent::Invalid(_) | - TransactionEvent::Dropped(_) + TransactionEvent::Finalized(_) + | TransactionEvent::Error(_) + | TransactionEvent::Invalid(_) + | TransactionEvent::Dropped(_) ) } } @@ -171,18 +171,24 @@ enum TransactionEventIR { impl From> for TransactionEventIR { fn from(value: TransactionEvent) -> Self { match value { - TransactionEvent::Validated => - TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Validated), - TransactionEvent::BestChainBlockIncluded(event) => - TransactionEventIR::Block(TransactionEventBlockIR::BestChainBlockIncluded(event)), - TransactionEvent::Finalized(event) => - TransactionEventIR::Block(TransactionEventBlockIR::Finalized(event)), - TransactionEvent::Error(event) => - TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Error(event)), - TransactionEvent::Invalid(event) => - TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Invalid(event)), - TransactionEvent::Dropped(event) => - TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Dropped(event)), + TransactionEvent::Validated => { + TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Validated) + }, + TransactionEvent::BestChainBlockIncluded(event) => { + TransactionEventIR::Block(TransactionEventBlockIR::BestChainBlockIncluded(event)) + }, + TransactionEvent::Finalized(event) => { + TransactionEventIR::Block(TransactionEventBlockIR::Finalized(event)) + }, + TransactionEvent::Error(event) => { + TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Error(event)) + }, + TransactionEvent::Invalid(event) => { + TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Invalid(event)) + }, + TransactionEvent::Dropped(event) => { + TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Dropped(event)) + }, } } } @@ -198,8 +204,9 @@ impl From> for TransactionEvent { }, TransactionEventIR::Block(block) => match block { TransactionEventBlockIR::Finalized(event) => TransactionEvent::Finalized(event), - TransactionEventBlockIR::BestChainBlockIncluded(event) => - TransactionEvent::BestChainBlockIncluded(event), + TransactionEventBlockIR::BestChainBlockIncluded(event) => { + TransactionEvent::BestChainBlockIncluded(event) + }, }, } } diff --git a/bizinikiwi/client/rpc-spec-v2/src/transaction/transaction.rs b/bizinikiwi/client/rpc-spec-v2/src/transaction/transaction.rs index 5a62b208..9942cb8a 100644 --- a/bizinikiwi/client/rpc-spec-v2/src/transaction/transaction.rs +++ b/bizinikiwi/client/rpc-spec-v2/src/transaction/transaction.rs @@ -165,17 +165,21 @@ fn handle_event( event: TransactionStatus, ) -> Option> { match event { - TransactionStatus::Ready | TransactionStatus::Future => - Some(TransactionEvent::::Validated), - TransactionStatus::InBlock((hash, index)) => - Some(TransactionEvent::BestChainBlockIncluded(Some(TransactionBlock { hash, index }))), + TransactionStatus::Ready | TransactionStatus::Future => { + Some(TransactionEvent::::Validated) + }, + TransactionStatus::InBlock((hash, index)) => { + Some(TransactionEvent::BestChainBlockIncluded(Some(TransactionBlock { hash, index }))) + }, TransactionStatus::Retracted(_) => Some(TransactionEvent::BestChainBlockIncluded(None)), - TransactionStatus::FinalityTimeout(_) => + TransactionStatus::FinalityTimeout(_) => { Some(TransactionEvent::Dropped(TransactionDropped { error: "Maximum number of finality watchers has been reached".into(), - })), - TransactionStatus::Finalized((hash, index)) => - Some(TransactionEvent::Finalized(TransactionBlock { hash, index })), + })) + }, + TransactionStatus::Finalized((hash, index)) => { + Some(TransactionEvent::Finalized(TransactionBlock { hash, index })) + }, TransactionStatus::Usurped(_) => Some(TransactionEvent::Invalid(TransactionError { error: "Extrinsic was rendered invalid by another extrinsic".into(), })), diff --git a/bizinikiwi/client/rpc/src/state/state_full.rs b/bizinikiwi/client/rpc/src/state/state_full.rs index dfa86516..a6645030 100644 --- a/bizinikiwi/client/rpc/src/state/state_full.rs +++ b/bizinikiwi/client/rpc/src/state/state_full.rs @@ -519,8 +519,9 @@ where self.block_or_best(block) .and_then(|block| { let child_info = match ChildType::from_prefixed_key(&storage_key) { - Some((ChildType::ParentKeyId, storage_key)) => - ChildInfo::new_default(storage_key), + Some((ChildType::ParentKeyId, storage_key)) => { + ChildInfo::new_default(storage_key) + }, None => return Err(pezsp_blockchain::Error::InvalidChildStorageKey), }; self.client @@ -545,8 +546,9 @@ where self.block_or_best(block) .and_then(|block| { let child_info = match ChildType::from_prefixed_key(&storage_key) { - Some((ChildType::ParentKeyId, storage_key)) => - ChildInfo::new_default(storage_key), + Some((ChildType::ParentKeyId, storage_key)) => { + ChildInfo::new_default(storage_key) + }, None => return Err(pezsp_blockchain::Error::InvalidChildStorageKey), }; self.client.child_storage_keys(block, child_info, Some(&prefix), None) @@ -566,8 +568,9 @@ where self.block_or_best(block) .and_then(|block| { let child_info = match ChildType::from_prefixed_key(&storage_key) { - Some((ChildType::ParentKeyId, storage_key)) => - ChildInfo::new_default(storage_key), + Some((ChildType::ParentKeyId, storage_key)) => { + ChildInfo::new_default(storage_key) + }, None => return Err(pezsp_blockchain::Error::InvalidChildStorageKey), }; self.client.child_storage_keys( @@ -590,8 +593,9 @@ where self.block_or_best(block) .and_then(|block| { let child_info = match ChildType::from_prefixed_key(&storage_key) { - Some((ChildType::ParentKeyId, storage_key)) => - ChildInfo::new_default(storage_key), + Some((ChildType::ParentKeyId, storage_key)) => { + ChildInfo::new_default(storage_key) + }, None => return Err(pezsp_blockchain::Error::InvalidChildStorageKey), }; self.client.child_storage(block, &child_info, &key) @@ -631,8 +635,9 @@ where self.block_or_best(block) .and_then(|block| { let child_info = match ChildType::from_prefixed_key(&storage_key) { - Some((ChildType::ParentKeyId, storage_key)) => - ChildInfo::new_default(storage_key), + Some((ChildType::ParentKeyId, storage_key)) => { + ChildInfo::new_default(storage_key) + }, None => return Err(pezsp_blockchain::Error::InvalidChildStorageKey), }; self.client.child_storage_hash(block, &child_info, &key) diff --git a/bizinikiwi/client/rpc/src/statement/mod.rs b/bizinikiwi/client/rpc/src/statement/mod.rs index 09972a19..98579ad5 100644 --- a/bizinikiwi/client/rpc/src/statement/mod.rs +++ b/bizinikiwi/client/rpc/src/statement/mod.rs @@ -130,8 +130,9 @@ impl StatementApiServer for StatementStore { SubmitResult::New(_) | SubmitResult::Known => Ok(()), // `KnownExpired` should not happen. Expired statements submitted with // `StatementSource::Rpc` should be renewed. - SubmitResult::KnownExpired => - Err(Error::StatementStore("Submitted an expired statement.".into()).into()), + SubmitResult::KnownExpired => { + Err(Error::StatementStore("Submitted an expired statement.".into()).into()) + }, SubmitResult::Bad(e) => Err(Error::StatementStore(e.into()).into()), SubmitResult::Ignored => Err(Error::StatementStore("Store is full.".into()).into()), SubmitResult::InternalError(e) => Err(Error::StatementStore(e.to_string()).into()), diff --git a/bizinikiwi/client/rpc/src/system/tests.rs b/bizinikiwi/client/rpc/src/system/tests.rs index 18b1b5f5..328534de 100644 --- a/bizinikiwi/client/rpc/src/system/tests.rs +++ b/bizinikiwi/client/rpc/src/system/tests.rs @@ -98,15 +98,17 @@ fn api>>(sync: T) -> RpcModule> { Request::NetworkAddReservedPeer(peer, sender) => { let _ = match pezsc_network::config::parse_str_addr(&peer) { Ok(_) => sender.send(Ok(())), - Err(s) => - sender.send(Err(error::Error::MalformattedPeerArg(s.to_string()))), + Err(s) => { + sender.send(Err(error::Error::MalformattedPeerArg(s.to_string()))) + }, }; }, Request::NetworkRemoveReservedPeer(peer, sender) => { let _ = match peer.parse::() { Ok(_) => sender.send(Ok(())), - Err(s) => - sender.send(Err(error::Error::MalformattedPeerArg(s.to_string()))), + Err(s) => { + sender.send(Err(error::Error::MalformattedPeerArg(s.to_string()))) + }, }; }, Request::NetworkReservedPeers(sender) => { diff --git a/bizinikiwi/client/service/src/builder.rs b/bizinikiwi/client/service/src/builder.rs index 1bb5a6a6..a4bae428 100644 --- a/bizinikiwi/client/service/src/builder.rs +++ b/bizinikiwi/client/service/src/builder.rs @@ -119,8 +119,9 @@ impl KeystoreContainer { /// Construct KeystoreContainer pub fn new(config: &KeystoreConfig) -> Result { let keystore = Arc::new(match config { - KeystoreConfig::Path { path, password } => - LocalKeystore::open(path.clone(), password.clone())?, + KeystoreConfig::Path { path, password } => { + LocalKeystore::open(path.clone(), password.clone())? + }, KeystoreConfig::InMemory => LocalKeystore::in_memory(), }); @@ -884,8 +885,8 @@ where // An archive node that can respond to the `archive` RPC-v2 queries is a node with: // - state pruning in archive mode: The storage of blocks is kept around // - block pruning in archive mode: The block's body is kept around - let is_archive_node = state_pruning.as_ref().map(|sp| sp.is_archive()).unwrap_or(false) && - blocks_pruning.is_archive(); + let is_archive_node = state_pruning.as_ref().map(|sp| sp.is_archive()).unwrap_or(false) + && blocks_pruning.is_archive(); let genesis_hash = client.hash(Zero::zero()).ok().flatten().expect("Genesis block exists; qed"); if is_archive_node { let archive_v2 = pezsc_rpc_spec_v2::archive::Archive::new( @@ -1043,8 +1044,8 @@ where &mut net_config, network_service_provider.handle(), Arc::clone(&client), - config.network.default_peers_set.in_peers as usize + - config.network.default_peers_set.out_peers as usize, + config.network.default_peers_set.in_peers as usize + + config.network.default_peers_set.out_peers as usize, &spawn_handle, ), }; @@ -1464,8 +1465,9 @@ where if client.requires_full_sync() { match net_config.network_config.sync_mode { - SyncMode::LightState { .. } => - return Err("Fast sync doesn't work for archive nodes".into()), + SyncMode::LightState { .. } => { + return Err("Fast sync doesn't work for archive nodes".into()) + }, SyncMode::Warp => return Err("Warp sync doesn't work for archive nodes".into()), SyncMode::Full => {}, } @@ -1474,8 +1476,8 @@ where let genesis_hash = client.info().genesis_hash; let (state_request_protocol_config, state_request_protocol_name) = { - let num_peer_hint = net_config.network_config.default_peers_set_num_full as usize + - net_config.network_config.default_peers_set.reserved_nodes.len(); + let num_peer_hint = net_config.network_config.default_peers_set_num_full as usize + + net_config.network_config.default_peers_set.reserved_nodes.len(); // Allow both outgoing and incoming requests. let (handler, protocol_config) = StateRequestHandler::new::(&protocol_id, fork_id, client.clone(), num_peer_hint); diff --git a/bizinikiwi/client/service/src/chain_ops/export_blocks.rs b/bizinikiwi/client/service/src/chain_ops/export_blocks.rs index 9e0cccef..df5e284f 100644 --- a/bizinikiwi/client/service/src/chain_ops/export_blocks.rs +++ b/bizinikiwi/client/service/src/chain_ops/export_blocks.rs @@ -81,13 +81,14 @@ where .transpose()? .flatten() { - Some(block) => + Some(block) => { if binary { output.write_all(&block.encode())?; } else { serde_json::to_writer(&mut output, &block) .map_err(|e| format!("Error writing JSON: {}", e))?; - }, + } + }, None => return Poll::Ready(Ok(())), } if (block % 10000u32.into()).is_zero() { diff --git a/bizinikiwi/client/service/src/chain_ops/import_blocks.rs b/bizinikiwi/client/service/src/chain_ops/import_blocks.rs index 7f1ff042..fe7aae12 100644 --- a/bizinikiwi/client/service/src/chain_ops/import_blocks.rs +++ b/bizinikiwi/client/service/src/chain_ops/import_blocks.rs @@ -104,8 +104,8 @@ where /// Returns the number of blocks read thus far. fn read_block_count(&self) -> u64 { match self { - BlockIter::Binary { read_block_count, .. } | - BlockIter::Json { read_block_count, .. } => *read_block_count, + BlockIter::Binary { read_block_count, .. } + | BlockIter::Json { read_block_count, .. } => *read_block_count, } } @@ -229,8 +229,8 @@ impl Speedometer { let speed = diff .saturating_mul(10_000) .checked_div(u128::from(elapsed_ms)) - .map_or(0.0, |s| s as f64) / - 10.0; + .map_or(0.0, |s| s as f64) + / 10.0; info!("📦 Current best block: {} ({:4.1} bps)", self.best_number, speed); } else { // If the number of blocks can't be converted to a regular integer, then we need a more @@ -375,8 +375,8 @@ where let read_block_count = block_iter.read_block_count(); match block_result { Ok(block) => { - if read_block_count - link.imported_blocks.load(Ordering::Acquire) >= - MAX_PENDING_BLOCKS + if read_block_count - link.imported_blocks.load(Ordering::Acquire) + >= MAX_PENDING_BLOCKS { // The queue is full, so do not add this block and simply wait // until the queue has made some progress. @@ -392,19 +392,20 @@ where state = Some(ImportState::Reading { block_iter }); } }, - Err(e) => + Err(e) => { return Poll::Ready(Err(Error::Other(format!( "Error reading block #{}: {}", read_block_count, e - )))), + )))) + }, } }, } }, ImportState::WaitingForImportQueueToCatchUp { block_iter, mut delay, block } => { let read_block_count = block_iter.read_block_count(); - if read_block_count - link.imported_blocks.load(Ordering::Acquire) >= - MAX_PENDING_BLOCKS + if read_block_count - link.imported_blocks.load(Ordering::Acquire) + >= MAX_PENDING_BLOCKS { // Queue is still full, so wait until there is room to insert our block. match Pin::new(&mut delay).poll(cx) { diff --git a/bizinikiwi/client/service/src/client/client.rs b/bizinikiwi/client/service/src/client/client.rs index 7d13b7c8..f22c71d0 100644 --- a/bizinikiwi/client/service/src/client/client.rs +++ b/bizinikiwi/client/service/src/client/client.rs @@ -579,9 +579,9 @@ where // the block is lower than our last finalized block so it must revert // finality, refusing import. - if status == blockchain::BlockStatus::Unknown && - *import_headers.post().number() <= info.finalized_number && - !gap_block + if status == blockchain::BlockStatus::Unknown + && *import_headers.post().number() <= info.finalized_number + && !gap_block { return Err(pezsp_blockchain::Error::NotInFinalizedChain); } @@ -590,8 +590,9 @@ where // but the general goal is to only make notifications when we are already fully synced // and get a new chain head. let make_notifications = match origin { - BlockOrigin::NetworkBroadcast | BlockOrigin::Own | BlockOrigin::ConsensusBroadcast => - true, + BlockOrigin::NetworkBroadcast | BlockOrigin::Own | BlockOrigin::ConsensusBroadcast => { + true + }, BlockOrigin::Genesis | BlockOrigin::NetworkInitialSync | BlockOrigin::File => false, }; @@ -625,12 +626,14 @@ where let storage_key = PrefixedStorageKey::new_ref(&parent_storage); let storage_key = match ChildType::from_prefixed_key(storage_key) { - Some((ChildType::ParentKeyId, storage_key)) => - storage_key, - None => + Some((ChildType::ParentKeyId, storage_key)) => { + storage_key + }, + None => { return Err(Error::Backend( "Invalid child storage key.".to_string(), - )), + )) + }, }; let entry = storage .children_default @@ -680,11 +683,12 @@ where )?; } - let is_new_best = !gap_block && - (finalized || - match fork_choice { - ForkChoiceStrategy::LongestChain => - import_headers.post().number() > &info.best_number, + let is_new_best = !gap_block + && (finalized + || match fork_choice { + ForkChoiceStrategy::LongestChain => { + import_headers.post().number() > &info.best_number + }, ForkChoiceStrategy::Custom(v) => v, }); @@ -806,18 +810,21 @@ where let state_action = std::mem::replace(&mut import_block.state_action, StateAction::Skip); let (enact_state, storage_changes) = match (self.block_status(*parent_hash)?, state_action) { - (BlockStatus::KnownBad, _) => - return Ok(PrepareStorageChangesResult::Discard(ImportResult::KnownBad)), + (BlockStatus::KnownBad, _) => { + return Ok(PrepareStorageChangesResult::Discard(ImportResult::KnownBad)) + }, ( BlockStatus::InChainPruned, StateAction::ApplyChanges(pezsc_consensus::StorageChanges::Changes(_)), ) => return Ok(PrepareStorageChangesResult::Discard(ImportResult::MissingState)), (_, StateAction::ApplyChanges(changes)) => (true, Some(changes)), - (BlockStatus::Unknown, _) => - return Ok(PrepareStorageChangesResult::Discard(ImportResult::UnknownParent)), + (BlockStatus::Unknown, _) => { + return Ok(PrepareStorageChangesResult::Discard(ImportResult::UnknownParent)) + }, (_, StateAction::Skip) => (false, None), - (BlockStatus::InChainPruned, StateAction::Execute) => - return Ok(PrepareStorageChangesResult::Discard(ImportResult::MissingState)), + (BlockStatus::InChainPruned, StateAction::Execute) => { + return Ok(PrepareStorageChangesResult::Discard(ImportResult::MissingState)) + }, (BlockStatus::InChainPruned, StateAction::ExecuteIfPossible) => (false, None), (_, StateAction::Execute) => (true, None), (_, StateAction::ExecuteIfPossible) => (true, None), @@ -1116,12 +1123,13 @@ where let hash_and_number = self.backend.blockchain().number(hash)?.map(|n| (hash, n)); match hash_and_number { - Some((hash, number)) => + Some((hash, number)) => { if self.backend.have_state_at(hash, number) { Ok(BlockStatus::InChainWithState) } else { Ok(BlockStatus::InChainPruned) - }, + } + }, None => Ok(BlockStatus::Unknown), } } @@ -1264,8 +1272,9 @@ where let child_info = |storage_key: &Vec| -> pezsp_blockchain::Result { let storage_key = PrefixedStorageKey::new_ref(storage_key); match ChildType::from_prefixed_key(storage_key) { - Some((ChildType::ParentKeyId, storage_key)) => - Ok(ChildInfo::new_default(storage_key)), + Some((ChildType::ParentKeyId, storage_key)) => { + Ok(ChildInfo::new_default(storage_key)) + }, None => Err(Error::Backend("Invalid child storage key.".to_string())), } }; @@ -1325,8 +1334,8 @@ where } total_size += size; - if current_child.is_none() && - pezsp_core::storage::well_known_keys::is_child_storage_key( + if current_child.is_none() + && pezsp_core::storage::well_known_keys::is_child_storage_key( next_key.as_slice(), ) && !child_roots.contains(value.as_slice()) { @@ -1783,10 +1792,12 @@ where .block_status(hash) .map_err(|e| ConsensusError::ClientImport(e.to_string()))? { - BlockStatus::InChainWithState | BlockStatus::Queued => - return Ok(ImportResult::AlreadyInChain), - BlockStatus::InChainPruned if !import_existing => - return Ok(ImportResult::AlreadyInChain), + BlockStatus::InChainWithState | BlockStatus::Queued => { + return Ok(ImportResult::AlreadyInChain) + }, + BlockStatus::InChainPruned if !import_existing => { + return Ok(ImportResult::AlreadyInChain) + }, BlockStatus::InChainPruned => {}, BlockStatus::Unknown => {}, BlockStatus::KnownBad => return Ok(ImportResult::KnownBad), @@ -1952,8 +1963,9 @@ where fn block(&self, hash: Block::Hash) -> pezsp_blockchain::Result>> { Ok(match (self.header(hash)?, self.body(hash)?, self.justifications(hash)?) { - (Some(header), Some(extrinsics), justifications) => - Some(SignedBlock { block: Block::new(header, extrinsics), justifications }), + (Some(header), Some(extrinsics), justifications) => { + Some(SignedBlock { block: Block::new(header, extrinsics), justifications }) + }, _ => None, }) } diff --git a/bizinikiwi/client/service/src/client/notification_pinning.rs b/bizinikiwi/client/service/src/client/notification_pinning.rs index e9da6357..19043044 100644 --- a/bizinikiwi/client/service/src/client/notification_pinning.rs +++ b/bizinikiwi/client/service/src/client/notification_pinning.rs @@ -176,10 +176,11 @@ impl> NotificationPinningWorker while let Some(message) = self.unpin_message_rx.next().await { match message { UnpinWorkerMessage::AnnouncePin(hash) => self.handle_announce_message(hash), - UnpinWorkerMessage::Unpin(hash) => + UnpinWorkerMessage::Unpin(hash) => { if self.handle_unpin_message(hash).is_err() { return; - }, + } + }, } } log::debug!(target: LOG_TARGET, "Terminating unpin-worker, stream terminated.") diff --git a/bizinikiwi/client/service/src/lib.rs b/bizinikiwi/client/service/src/lib.rs index 5c906feb..87f52687 100644 --- a/bizinikiwi/client/service/src/lib.rs +++ b/bizinikiwi/client/service/src/lib.rs @@ -543,8 +543,9 @@ where TransactionImport::NewGood }, Err(e) => match e.into_pool_error() { - Ok(pezsc_transaction_pool_api::error::Error::AlreadyImported(_)) => - TransactionImport::KnownGood, + Ok(pezsc_transaction_pool_api::error::Error::AlreadyImported(_)) => { + TransactionImport::KnownGood + }, Ok(_) => TransactionImport::Bad, Err(_) => { // it is not bad at least, just some internal node logic error, so peer is diff --git a/bizinikiwi/client/state-db/src/lib.rs b/bizinikiwi/client/state-db/src/lib.rs index 49da5f31..f9a60283 100644 --- a/bizinikiwi/client/state-db/src/lib.rs +++ b/bizinikiwi/client/state-db/src/lib.rs @@ -317,8 +317,9 @@ impl StateDbSync { let non_canonical: NonCanonicalOverlay = NonCanonicalOverlay::new(&db)?; let pruning: Option> = match mode { - PruningMode::Constrained(Constraints { max_blocks }) => - Some(RefWindow::new(db, max_blocks.unwrap_or(0), ref_counting)?), + PruningMode::Constrained(Constraints { max_blocks }) => { + Some(RefWindow::new(db, max_blocks.unwrap_or(0), ref_counting)?) + }, PruningMode::ArchiveAll | PruningMode::ArchiveCanonical => None, }; @@ -420,10 +421,11 @@ impl StateDbSync { match pruning.next_hash() { // the block record is temporary unavailable, break and try next time Err(Error::StateDb(StateDbError::BlockUnavailable)) => break, - res => + res => { if res?.map_or(false, |h| pinned.contains_key(&h)) { break; - }, + } + }, } match pruning.prune_one(commit) { // this branch should not reach as previous `next_hash` don't return error @@ -442,16 +444,18 @@ impl StateDbSync { fn revert_one(&mut self) -> Option> { match self.mode { PruningMode::ArchiveAll => Some(CommitSet::default()), - PruningMode::ArchiveCanonical | PruningMode::Constrained(_) => - self.non_canonical.revert_one(), + PruningMode::ArchiveCanonical | PruningMode::Constrained(_) => { + self.non_canonical.revert_one() + }, } } fn remove(&mut self, hash: &BlockHash) -> Option> { match self.mode { PruningMode::ArchiveAll => Some(CommitSet::default()), - PruningMode::ArchiveCanonical | PruningMode::Constrained(_) => - self.non_canonical.remove(hash), + PruningMode::ArchiveCanonical | PruningMode::Constrained(_) => { + self.non_canonical.remove(hash) + }, } } @@ -462,8 +466,8 @@ impl StateDbSync { match self.mode { PruningMode::ArchiveAll => Ok(()), PruningMode::ArchiveCanonical | PruningMode::Constrained(_) => { - let have_block = self.non_canonical.have_block(hash) || - self.pruning.as_ref().map_or_else( + let have_block = self.non_canonical.have_block(hash) + || self.pruning.as_ref().map_or_else( || hint(), |pruning| match pruning.have_block(hash, number) { HaveBlock::No => false, @@ -545,11 +549,12 @@ impl StateDb { requested_mode.unwrap_or_default() }, - (false, None, _) => + (false, None, _) => { return Err(StateDbError::Metadata( "An existing StateDb does not have PRUNING_MODE stored in its meta-data".into(), ) - .into()), + .into()) + }, (false, Some(stored), None) => stored, @@ -694,10 +699,12 @@ fn choose_pruning_mode( ) -> Result { match (stored, requested) { (PruningMode::ArchiveAll, PruningMode::ArchiveAll) => Ok(PruningMode::ArchiveAll), - (PruningMode::ArchiveCanonical, PruningMode::ArchiveCanonical) => - Ok(PruningMode::ArchiveCanonical), - (PruningMode::Constrained(_), PruningMode::Constrained(requested)) => - Ok(PruningMode::Constrained(requested)), + (PruningMode::ArchiveCanonical, PruningMode::ArchiveCanonical) => { + Ok(PruningMode::ArchiveCanonical) + }, + (PruningMode::Constrained(_), PruningMode::Constrained(requested)) => { + Ok(PruningMode::Constrained(requested)) + }, (stored, requested) => Err(StateDbError::IncompatiblePruningModes { requested, stored }), } } diff --git a/bizinikiwi/client/state-db/src/noncanonical.rs b/bizinikiwi/client/state-db/src/noncanonical.rs index d783edbc..d9c2e822 100644 --- a/bizinikiwi/client/state-db/src/noncanonical.rs +++ b/bizinikiwi/client/state-db/src/noncanonical.rs @@ -138,8 +138,8 @@ fn discard_descendants( while let Some(i) = level.blocks.iter().position(|overlay| { parents .get(&overlay.hash) - .expect("there is a parent entry for each entry in levels; qed") == - hash + .expect("there is a parent entry for each entry in levels; qed") + == hash }) { let overlay = level.remove(i); let mut num_pinned = discard_descendants( @@ -285,8 +285,8 @@ impl NonCanonicalOverlay { return Err(StateDbError::InvalidParent); } } - let level = if self.levels.is_empty() || - number == front_block_number + self.levels.len() as u64 + let level = if self.levels.is_empty() + || number == front_block_number + self.levels.len() as u64 { self.levels.push_back(OverlayLevel::new()); self.levels.back_mut().expect("can't be empty after insertion; qed") @@ -578,8 +578,8 @@ mod tests { use pezsp_core::H256; fn contains(overlay: &NonCanonicalOverlay, key: u64) -> bool { - overlay.get(&H256::from_low_u64_be(key)) == - Some(H256::from_low_u64_be(key).as_bytes().to_vec()) + overlay.get(&H256::from_low_u64_be(key)) + == Some(H256::from_low_u64_be(key).as_bytes().to_vec()) } #[test] diff --git a/bizinikiwi/client/statement-store/src/lib.rs b/bizinikiwi/client/statement-store/src/lib.rs index f6a717f6..22798e78 100644 --- a/bizinikiwi/client/statement-store/src/lib.rs +++ b/bizinikiwi/client/statement-store/src/lib.rs @@ -445,8 +445,8 @@ impl Index { } // Check if we can evict enough lower priority statements to satisfy constraints for (entry, (_, len)) in account_rec.by_priority.iter() { - if (account_rec.data_size - would_free_size + statement_len <= max_size) && - account_rec.by_priority.len() + 1 - evicted.len() <= max_count + if (account_rec.data_size - would_free_size + statement_len <= max_size) + && account_rec.by_priority.len() + 1 - evicted.len() <= max_count { // Satisfied break; @@ -470,8 +470,8 @@ impl Index { } } // Now check global constraints as well. - if !((self.total_size - would_free_size + statement_len <= self.options.max_total_size) && - self.entries.len() + 1 - evicted.len() <= self.options.max_total_statements) + if !((self.total_size - would_free_size + statement_len <= self.options.max_total_size) + && self.entries.len() + 1 - evicted.len() <= self.options.max_total_statements) { log::debug!( target: LOG_TARGET, @@ -909,14 +909,16 @@ impl StatementStore for Store { } match self.index.read().query(&hash) { - IndexQuery::Expired => + IndexQuery::Expired => { if !source.can_be_resubmitted() { return SubmitResult::KnownExpired; - }, - IndexQuery::Exists => + } + }, + IndexQuery::Exists => { if !source.can_be_resubmitted() { return SubmitResult::Known; - }, + } + }, IndexQuery::Unknown => {}, } @@ -957,8 +959,9 @@ impl StatementStore for Store { self.metrics.report(|metrics| metrics.validations_invalid.inc()); return SubmitResult::Bad("Missing statement proof"); }, - Err(InvalidStatement::InternalError) => - return SubmitResult::InternalError(Error::Runtime), + Err(InvalidStatement::InternalError) => { + return SubmitResult::InternalError(Error::Runtime) + }, }; let current_time = self.timestamp(); diff --git a/bizinikiwi/client/sysinfo/src/sysinfo.rs b/bizinikiwi/client/sysinfo/src/sysinfo.rs index cdd5080b..3ad91dff 100644 --- a/bizinikiwi/client/sysinfo/src/sysinfo.rs +++ b/bizinikiwi/client/sysinfo/src/sysinfo.rs @@ -100,8 +100,9 @@ impl Metric { match self { Self::Sr25519Verify => Cow::Borrowed("SR25519-Verify"), Self::Blake2256 => Cow::Borrowed("BLAKE2-256"), - Self::Blake2256Parallel { num_cores } => - Cow::Owned(format!("BLAKE2-256-Parallel-{}", num_cores)), + Self::Blake2256Parallel { num_cores } => { + Cow::Owned(format!("BLAKE2-256-Parallel-{}", num_cores)) + }, Self::MemCopy => Cow::Borrowed("Copy"), Self::DiskSeqWrite => Cow::Borrowed("Seq Write"), Self::DiskRndWrite => Cow::Borrowed("Rnd Write"), @@ -411,8 +412,8 @@ pub fn benchmark_cpu_parallelism(limit: ExecutionLimit, refhw_num_cores: usize) let average_score = benchmark_threads .into_iter() .map(|thread| thread.join().map(|throughput| throughput.as_kibs()).unwrap_or(0.0)) - .sum::() / - refhw_num_cores as f64; + .sum::() + / refhw_num_cores as f64; Throughput::from_kibs(average_score) } @@ -727,14 +728,15 @@ impl Requirements { } match requirement.metric { - Metric::Blake2256 => + Metric::Blake2256 => { if requirement.minimum > hwbench.cpu_hashrate_score { failures.push(CheckFailure { metric: requirement.metric, expected: requirement.minimum, found: hwbench.cpu_hashrate_score, }); - }, + } + }, Metric::Blake2256Parallel { .. } => { if requirement.minimum > hwbench.parallel_cpu_hashrate_score { failures.push(CheckFailure { @@ -744,15 +746,16 @@ impl Requirements { }); } }, - Metric::MemCopy => + Metric::MemCopy => { if requirement.minimum > hwbench.memory_memcpy_score { failures.push(CheckFailure { metric: requirement.metric, expected: requirement.minimum, found: hwbench.memory_memcpy_score, }); - }, - Metric::DiskSeqWrite => + } + }, + Metric::DiskSeqWrite => { if let Some(score) = hwbench.disk_sequential_write_score { if requirement.minimum > score { failures.push(CheckFailure { @@ -761,8 +764,9 @@ impl Requirements { found: score, }); } - }, - Metric::DiskRndWrite => + } + }, + Metric::DiskRndWrite => { if let Some(score) = hwbench.disk_random_write_score { if requirement.minimum > score { failures.push(CheckFailure { @@ -771,7 +775,8 @@ impl Requirements { found: score, }); } - }, + } + }, Metric::Sr25519Verify => {}, } } @@ -820,16 +825,16 @@ mod tests { #[test] fn test_benchmark_disk_sequential_writes() { assert!( - benchmark_disk_sequential_writes(DEFAULT_DISK_EXECUTION_LIMIT, "./".as_ref()).unwrap() > - Throughput::from_mibs(0.0) + benchmark_disk_sequential_writes(DEFAULT_DISK_EXECUTION_LIMIT, "./".as_ref()).unwrap() + > Throughput::from_mibs(0.0) ); } #[test] fn test_benchmark_disk_random_writes() { assert!( - benchmark_disk_random_writes(DEFAULT_DISK_EXECUTION_LIMIT, "./".as_ref()).unwrap() > - Throughput::from_mibs(0.0) + benchmark_disk_random_writes(DEFAULT_DISK_EXECUTION_LIMIT, "./".as_ref()).unwrap() + > Throughput::from_mibs(0.0) ); } diff --git a/bizinikiwi/client/tracing/benches/common/mod.rs b/bizinikiwi/client/tracing/benches/common/mod.rs index 304bcb23..ddbb870d 100644 --- a/bizinikiwi/client/tracing/benches/common/mod.rs +++ b/bizinikiwi/client/tracing/benches/common/mod.rs @@ -71,13 +71,14 @@ fn parse_interest_cache_config() -> Option { let value = parts[1].trim(); match key { - "lru_cache_size" => + "lru_cache_size" => { if let Ok(size) = value.parse::() { config = config.with_lru_cache_size(size); eprintln!("Interest cache: lru_cache_size = {}", size); } else { eprintln!("Invalid lru_cache_size value '{}'", value); - }, + } + }, "min_verbosity" => { let level = match value.to_lowercase().as_str() { "error" => Some(Level::Error), diff --git a/bizinikiwi/client/tracing/src/lib.rs b/bizinikiwi/client/tracing/src/lib.rs index 8b116a0e..13279692 100644 --- a/bizinikiwi/client/tracing/src/lib.rs +++ b/bizinikiwi/client/tracing/src/lib.rs @@ -141,10 +141,10 @@ impl Values { /// Checks if all individual collections are empty pub fn is_empty(&self) -> bool { - self.bool_values.is_empty() && - self.i64_values.is_empty() && - self.u64_values.is_empty() && - self.string_values.is_empty() + self.bool_values.is_empty() + && self.i64_values.is_empty() + && self.u64_values.is_empty() + && self.string_values.is_empty() } } @@ -175,10 +175,10 @@ impl Serialize for Values { where S: Serializer, { - let len = self.bool_values.len() + - self.i64_values.len() + - self.u64_values.len() + - self.string_values.len(); + let len = self.bool_values.len() + + self.i64_values.len() + + self.u64_values.len() + + self.string_values.len(); let mut map = serializer.serialize_map(Some(len))?; for (k, v) in &self.bool_values { map.serialize_entry(k, v)?; diff --git a/bizinikiwi/client/tracing/src/logging/event_format.rs b/bizinikiwi/client/tracing/src/logging/event_format.rs index a781d428..6562a3f8 100644 --- a/bizinikiwi/client/tracing/src/logging/event_format.rs +++ b/bizinikiwi/client/tracing/src/logging/event_format.rs @@ -116,10 +116,10 @@ where mut writer: format::Writer<'_>, event: &Event, ) -> fmt::Result { - if self.dup_to_stdout && - (event.metadata().level() == &Level::INFO || - event.metadata().level() == &Level::WARN || - event.metadata().level() == &Level::ERROR) + if self.dup_to_stdout + && (event.metadata().level() == &Level::INFO + || event.metadata().level() == &Level::WARN + || event.metadata().level() == &Level::ERROR) { let mut out = String::new(); let buf_writer = format::Writer::new(&mut out); diff --git a/bizinikiwi/client/transaction-pool/api/src/lib.rs b/bizinikiwi/client/transaction-pool/api/src/lib.rs index 43dee0cd..179a9420 100644 --- a/bizinikiwi/client/transaction-pool/api/src/lib.rs +++ b/bizinikiwi/client/transaction-pool/api/src/lib.rs @@ -162,11 +162,11 @@ impl TransactionStatus { pub fn is_final(&self) -> bool { // The state must be kept in sync with `crate::graph::Sender`. match self { - Self::Usurped(_) | - Self::Finalized(_) | - Self::FinalityTimeout(_) | - Self::Invalid | - Self::Dropped => true, + Self::Usurped(_) + | Self::Finalized(_) + | Self::FinalityTimeout(_) + | Self::Invalid + | Self::Dropped => true, _ => false, } } diff --git a/bizinikiwi/client/transaction-pool/benches/basics.rs b/bizinikiwi/client/transaction-pool/benches/basics.rs index d0ff5051..953366f1 100644 --- a/bizinikiwi/client/transaction-pool/benches/basics.rs +++ b/bizinikiwi/client/transaction-pool/benches/basics.rs @@ -103,8 +103,9 @@ impl ChainApi for TestApi { ) -> Result>, Self::Error> { Ok(match at { BlockId::Number(num) => Some(*num), - BlockId::Hash(hash) if *hash == H256::from_low_u64_be(hash.to_low_u64_be()) => - Some(hash.to_low_u64_be()), + BlockId::Hash(hash) if *hash == H256::from_low_u64_be(hash.to_low_u64_be()) => { + Some(hash.to_low_u64_be()) + }, BlockId::Hash(_) => None, }) } diff --git a/bizinikiwi/client/transaction-pool/src/common/enactment_state.rs b/bizinikiwi/client/transaction-pool/src/common/enactment_state.rs index 18a472be..b7ab27ac 100644 --- a/bizinikiwi/client/transaction-pool/src/common/enactment_state.rs +++ b/bizinikiwi/client/transaction-pool/src/common/enactment_state.rs @@ -107,8 +107,9 @@ where // do not proceed with txpool maintain if block distance is too high let skip_maintenance = match (hash_to_number(new_hash), hash_to_number(self.recent_best_block)) { - (Ok(Some(new)), Ok(Some(current))) => - new.saturating_sub(current) > SKIP_MAINTENANCE_THRESHOLD.into(), + (Ok(Some(new)), Ok(Some(current))) => { + new.saturating_sub(current) > SKIP_MAINTENANCE_THRESHOLD.into() + }, _ => true, }; diff --git a/bizinikiwi/client/transaction-pool/src/common/tests.rs b/bizinikiwi/client/transaction-pool/src/common/tests.rs index aeecfe36..f3bac0ae 100644 --- a/bizinikiwi/client/transaction-pool/src/common/tests.rs +++ b/bizinikiwi/client/transaction-pool/src/common/tests.rs @@ -178,8 +178,9 @@ impl ChainApi for TestApi { ) -> Result>, Self::Error> { Ok(match at { BlockId::Number(num) => Some(*num), - BlockId::Hash(hash) if *hash == H256::from_low_u64_be(hash.to_low_u64_be()) => - Some(hash.to_low_u64_be()), + BlockId::Hash(hash) if *hash == H256::from_low_u64_be(hash.to_low_u64_be()) => { + Some(hash.to_low_u64_be()) + }, BlockId::Hash(_) => None, }) } diff --git a/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/dropped_watcher.rs b/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/dropped_watcher.rs index 1479bdc2..b5469e14 100644 --- a/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/dropped_watcher.rs +++ b/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/dropped_watcher.rs @@ -296,8 +296,9 @@ where return Some(DroppedTransaction::new_enforced_by_limts(tx_hash)); } }, - TransactionStatus::Usurped(by) => - return Some(DroppedTransaction::new_usurped(tx_hash, by)), + TransactionStatus::Usurped(by) => { + return Some(DroppedTransaction::new_usurped(tx_hash, by)) + }, TransactionStatus::Invalid => { if let Some(mut views_keeping_tx_valid) = self.transaction_views(tx_hash) { views_keeping_tx_valid.get_mut().remove(&block_hash); diff --git a/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/fork_aware_txpool.rs b/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/fork_aware_txpool.rs index c1d55068..48b8cf14 100644 --- a/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/fork_aware_txpool.rs +++ b/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/fork_aware_txpool.rs @@ -748,9 +748,10 @@ where let insertion = match self.mempool.push_watched(source, at_number, xt.clone()).await { Ok(result) => result, - Err(TxPoolApiError::ImmediatelyDropped) => + Err(TxPoolApiError::ImmediatelyDropped) => { self.attempt_transaction_replacement(source, at_number, true, xt.clone()) - .await?, + .await? + }, Err(e) => return Err(e.into()), }; @@ -803,8 +804,9 @@ where .zip(xts.clone()) .map(|(result, xt)| async move { match result { - Err(TxPoolApiError::ImmediatelyDropped) => - self.attempt_transaction_replacement(source, at_number, false, xt).await, + Err(TxPoolApiError::ImmediatelyDropped) => { + self.attempt_transaction_replacement(source, at_number, false, xt).await + }, _ => result, } }) @@ -991,8 +993,9 @@ where "fatp::submit_one" ); match self.submit_at(_at, source, vec![xt]).await { - Ok(mut v) => - v.pop().expect("There is exactly one element in result of submit_at. qed."), + Ok(mut v) => { + v.pop().expect("There is exactly one element in result of submit_at. qed.") + }, Err(e) => Err(e), } } @@ -1279,8 +1282,8 @@ where return; }; - if at.number.saturating_sub(oldest_block_number).into() <= - self.finality_timeout_threshold.into() + if at.number.saturating_sub(oldest_block_number).into() + <= self.finality_timeout_threshold.into() { return; } @@ -1511,8 +1514,8 @@ where // note: There is no point to fetch the transactions from blocks older than threshold. // All transactions included in these blocks, were already removed from pool // with FinalityTimeout event. - if at.number.saturating_sub(block.number).into() <= - self.finality_timeout_threshold.into() + if at.number.saturating_sub(block.number).into() + <= self.finality_timeout_threshold.into() { all_txs.extend(self.fetch_block_transactions(block).await); } @@ -1984,10 +1987,11 @@ where let compute_tree_route = |from, to| -> Result, String> { match self.api.tree_route(from, to) { Ok(tree_route) => Ok(tree_route), - Err(e) => + Err(e) => { return Err(format!( "Error occurred while computing tree_route from {from:?} to {to:?}: {e}" - )), + )) + }, } }; let block_id_to_number = diff --git a/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/multi_view_listener.rs b/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/multi_view_listener.rs index cf75c847..e86c9ec6 100644 --- a/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/multi_view_listener.rs +++ b/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/multi_view_listener.rs @@ -113,10 +113,10 @@ where { fn hash(&self) -> ExtrinsicHash { match self { - Self::Invalidated(hash) | - Self::Finalized(hash, _, _) | - Self::Broadcasted(hash, _) | - Self::Dropped(hash, _) => *hash, + Self::Invalidated(hash) + | Self::Finalized(hash, _, _) + | Self::Broadcasted(hash, _) + | Self::Dropped(hash, _) => *hash, Self::FinalityTimeout(hash, _) => *hash, } } @@ -130,18 +130,24 @@ where fn into(self) -> TransactionStatus, BlockHash> { match self { TransactionStatusUpdate::Invalidated(_) => TransactionStatus::Invalid, - TransactionStatusUpdate::Finalized(_, hash, index) => - TransactionStatus::Finalized((*hash, *index)), - TransactionStatusUpdate::Broadcasted(_, peers) => - TransactionStatus::Broadcast(peers.clone()), - TransactionStatusUpdate::Dropped(_, DroppedReason::Usurped(by)) => - TransactionStatus::Usurped(*by), - TransactionStatusUpdate::Dropped(_, DroppedReason::LimitsEnforced) => - TransactionStatus::Dropped, - TransactionStatusUpdate::Dropped(_, DroppedReason::Invalid) => - TransactionStatus::Invalid, - TransactionStatusUpdate::FinalityTimeout(_, block_hash) => - TransactionStatus::FinalityTimeout(*block_hash), + TransactionStatusUpdate::Finalized(_, hash, index) => { + TransactionStatus::Finalized((*hash, *index)) + }, + TransactionStatusUpdate::Broadcasted(_, peers) => { + TransactionStatus::Broadcast(peers.clone()) + }, + TransactionStatusUpdate::Dropped(_, DroppedReason::Usurped(by)) => { + TransactionStatus::Usurped(*by) + }, + TransactionStatusUpdate::Dropped(_, DroppedReason::LimitsEnforced) => { + TransactionStatus::Dropped + }, + TransactionStatusUpdate::Dropped(_, DroppedReason::Invalid) => { + TransactionStatus::Invalid + }, + TransactionStatusUpdate::FinalityTimeout(_, block_hash) => { + TransactionStatus::FinalityTimeout(*block_hash) + }, } } } @@ -390,12 +396,12 @@ where self.terminate = true; Some(status) }, - TransactionStatus::FinalityTimeout(_) | - TransactionStatus::Retracted(_) | - TransactionStatus::Broadcast(_) | - TransactionStatus::Usurped(_) | - TransactionStatus::Dropped | - TransactionStatus::Invalid => None, + TransactionStatus::FinalityTimeout(_) + | TransactionStatus::Retracted(_) + | TransactionStatus::Broadcast(_) + | TransactionStatus::Usurped(_) + | TransactionStatus::Dropped + | TransactionStatus::Invalid => None, } } diff --git a/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/revalidation_worker.rs b/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/revalidation_worker.rs index 78bf443a..31c8570f 100644 --- a/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/revalidation_worker.rs +++ b/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/revalidation_worker.rs @@ -79,8 +79,9 @@ where break; }; match payload { - WorkerPayload::RevalidateView(view, worker_channels) => - view.revalidate(worker_channels).await, + WorkerPayload::RevalidateView(view, worker_channels) => { + view.revalidate(worker_channels).await + }, WorkerPayload::RevalidateMempool( mempool, view_store, diff --git a/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/tx_mem_pool.rs b/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/tx_mem_pool.rs index 78bcad2b..64d3c163 100644 --- a/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/tx_mem_pool.rs +++ b/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/tx_mem_pool.rs @@ -217,13 +217,13 @@ where ChainApi: graph::ChainApi + 'static, { fn eq(&self, other: &Self) -> bool { - self.watched == other.watched && - self.tx == other.tx && - self.bytes == other.bytes && - self.source == other.source && - *self.priority.read() == *other.priority.read() && - self.validated_at.load(atomic::Ordering::Relaxed) == - other.validated_at.load(atomic::Ordering::Relaxed) + self.watched == other.watched + && self.tx == other.tx + && self.bytes == other.bytes + && self.source == other.source + && *self.priority.read() == *other.priority.read() + && self.validated_at.load(atomic::Ordering::Relaxed) + == other.validated_at.load(atomic::Ordering::Relaxed) } } @@ -427,8 +427,8 @@ where /// Returns true if provided values would exceed defined limits. fn is_limit_exceeded(&self, length: usize, current_total_bytes: usize) -> bool { - length > self.max_transactions_count || - current_total_bytes > self.max_transactions_total_bytes + length > self.max_transactions_count + || current_total_bytes > self.max_transactions_total_bytes } /// Attempts to insert a transaction into the memory pool, ensuring it does not @@ -451,8 +451,9 @@ where transactions.insert(tx_hash, Arc::from(tx)); Ok(InsertionInfo::new(tx_hash, source)) }, - (_, true) => - Err(pezsc_transaction_pool_api::error::Error::AlreadyImported(Box::new(tx_hash))), + (_, true) => { + Err(pezsc_transaction_pool_api::error::Error::AlreadyImported(Box::new(tx_hash))) + }, (true, _) => Err(pezsc_transaction_pool_api::error::Error::ImmediatelyDropped), }; trace!( @@ -598,9 +599,9 @@ where self.with_transactions(|iter| { iter.filter(|(_, xt)| { let finalized_block_number = finalized_block.number.into().as_u64(); - xt.validated_at.load(atomic::Ordering::Relaxed) + - TXMEMPOOL_REVALIDATION_PERIOD < - finalized_block_number + xt.validated_at.load(atomic::Ordering::Relaxed) + + TXMEMPOOL_REVALIDATION_PERIOD + < finalized_block_number }) .sorted_by_key(|(_, tx)| tx.validated_at.load(atomic::Ordering::Relaxed)) .take(TXMEMPOOL_MAX_REVALIDATION_BATCH_SIZE) @@ -633,11 +634,11 @@ where let invalid_hashes = validation_results .into_iter() .filter_map(|(tx_hash, validation_result)| match validation_result { - Ok(Ok(_)) | - Ok(Err(TransactionValidityError::Invalid(InvalidTransaction::Future))) => None, - Err(_) | - Ok(Err(TransactionValidityError::Unknown(_))) | - Ok(Err(TransactionValidityError::Invalid(_))) => { + Ok(Ok(_)) + | Ok(Err(TransactionValidityError::Invalid(InvalidTransaction::Future))) => None, + Err(_) + | Ok(Err(TransactionValidityError::Unknown(_))) + | Ok(Err(TransactionValidityError::Invalid(_))) => { trace!( target: LOG_TARGET, ?tx_hash, diff --git a/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/view_store.rs b/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/view_store.rs index 9827dcc3..49b1abce 100644 --- a/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/view_store.rs +++ b/bizinikiwi/client/transaction-pool/src/fork_aware_txpool/view_store.rs @@ -330,8 +330,9 @@ where ); return Err(error); }, - Some(Ok(result)) => - Ok(ViewStoreSubmitOutcome::from(result).with_watcher(external_watcher)), + Some(Ok(result)) => { + Ok(ViewStoreSubmitOutcome::from(result).with_watcher(external_watcher)) + }, None => Ok(ViewStoreSubmitOutcome::new(tx_hash, None).with_watcher(external_watcher)), } } diff --git a/bizinikiwi/client/transaction-pool/src/graph/base_pool.rs b/bizinikiwi/client/transaction-pool/src/graph/base_pool.rs index 080ef252..acf75286 100644 --- a/bizinikiwi/client/transaction-pool/src/graph/base_pool.rs +++ b/bizinikiwi/client/transaction-pool/src/graph/base_pool.rs @@ -515,12 +515,13 @@ impl BasePool + _ => { if worst.imported_at > current.imported_at { current.clone() } else { worst - }, + } + }, }, ), }); diff --git a/bizinikiwi/client/transaction-pool/src/graph/future.rs b/bizinikiwi/client/transaction-pool/src/graph/future.rs index ef03ad0f..3c5099f6 100644 --- a/bizinikiwi/client/transaction-pool/src/graph/future.rs +++ b/bizinikiwi/client/transaction-pool/src/graph/future.rs @@ -83,8 +83,8 @@ impl WaitingTransaction { .filter(|tag| { // is true if the tag is already satisfied either via transaction in the pool // or one that was recently included. - let is_provided = provided.contains_key(&**tag) || - recently_pruned.iter().any(|x| x.contains(&**tag)); + let is_provided = provided.contains_key(&**tag) + || recently_pruned.iter().any(|x| x.contains(&**tag)); !is_provided }) .cloned() diff --git a/bizinikiwi/client/transaction-pool/src/graph/pool.rs b/bizinikiwi/client/transaction-pool/src/graph/pool.rs index 31c87a7b..964b29fa 100644 --- a/bizinikiwi/client/transaction-pool/src/graph/pool.rs +++ b/bizinikiwi/client/transaction-pool/src/graph/pool.rs @@ -553,7 +553,7 @@ impl> Pool { }; let validity = match status { - Ok(validity) => + Ok(validity) => { if validity.provides.is_empty() { ValidatedTransaction::Invalid(hash, error::Error::NoTagsProvided.into()) } else { @@ -565,11 +565,14 @@ impl> Pool { bytes, validity, ) - }, - Err(TransactionValidityError::Invalid(e)) => - ValidatedTransaction::Invalid(hash, error::Error::InvalidTransaction(e).into()), - Err(TransactionValidityError::Unknown(e)) => - ValidatedTransaction::Unknown(hash, error::Error::UnknownTransaction(e).into()), + } + }, + Err(TransactionValidityError::Invalid(e)) => { + ValidatedTransaction::Invalid(hash, error::Error::InvalidTransaction(e).into()) + }, + Err(TransactionValidityError::Unknown(e)) => { + ValidatedTransaction::Unknown(hash, error::Error::UnknownTransaction(e).into()) + }, }; (hash, validity) diff --git a/bizinikiwi/client/transaction-pool/src/graph/ready.rs b/bizinikiwi/client/transaction-pool/src/graph/ready.rs index 47cb2e20..5c9c63d1 100644 --- a/bizinikiwi/client/transaction-pool/src/graph/ready.rs +++ b/bizinikiwi/client/transaction-pool/src/graph/ready.rs @@ -752,18 +752,18 @@ mod tests { }; // higher priority = better assert!( - TransactionRef { transaction: Arc::new(with_priority(3, 3)), insertion_id: 1 } > - TransactionRef { transaction: Arc::new(with_priority(2, 3)), insertion_id: 2 } + TransactionRef { transaction: Arc::new(with_priority(3, 3)), insertion_id: 1 } + > TransactionRef { transaction: Arc::new(with_priority(2, 3)), insertion_id: 2 } ); // lower validity = better assert!( - TransactionRef { transaction: Arc::new(with_priority(3, 2)), insertion_id: 1 } > - TransactionRef { transaction: Arc::new(with_priority(3, 3)), insertion_id: 2 } + TransactionRef { transaction: Arc::new(with_priority(3, 2)), insertion_id: 1 } + > TransactionRef { transaction: Arc::new(with_priority(3, 3)), insertion_id: 2 } ); // lower insertion_id = better assert!( - TransactionRef { transaction: Arc::new(with_priority(3, 3)), insertion_id: 1 } > - TransactionRef { transaction: Arc::new(with_priority(3, 3)), insertion_id: 2 } + TransactionRef { transaction: Arc::new(with_priority(3, 3)), insertion_id: 1 } + > TransactionRef { transaction: Arc::new(with_priority(3, 3)), insertion_id: 2 } ); } diff --git a/bizinikiwi/client/transaction-pool/src/graph/validated_pool.rs b/bizinikiwi/client/transaction-pool/src/graph/validated_pool.rs index 5b379f91..3858a926 100644 --- a/bizinikiwi/client/transaction-pool/src/graph/validated_pool.rs +++ b/bizinikiwi/client/transaction-pool/src/graph/validated_pool.rs @@ -318,8 +318,9 @@ impl> ValidatedPool { results .into_iter() .map(|res| match res { - Ok(outcome) if removed.contains(&outcome.hash) => - Err(error::Error::ImmediatelyDropped.into()), + Ok(outcome) if removed.contains(&outcome.hash) => { + Err(error::Error::ImmediatelyDropped.into()) + }, other => other, }) .collect() @@ -348,7 +349,7 @@ impl> ValidatedPool { let sinks = &mut self.import_notification_sinks.lock(); sinks.retain_mut(|sink| match sink.try_send(*hash) { Ok(()) => true, - Err(e) => + Err(e) => { if e.is_full() { warn!( target: LOG_TARGET, @@ -358,7 +359,8 @@ impl> ValidatedPool { true } else { false - }, + } + }, }); } @@ -394,8 +396,8 @@ impl> ValidatedPool { let ready_limit = &self.options.ready; let future_limit = &self.options.future; - if ready_limit.is_exceeded(status.ready, status.ready_bytes) || - future_limit.is_exceeded(status.future, status.future_bytes) + if ready_limit.is_exceeded(status.ready, status.ready_bytes) + || future_limit.is_exceeded(status.future, status.future_bytes) { trace!( target: LOG_TARGET, @@ -575,8 +577,8 @@ impl> ValidatedPool { final_statuses.insert(tx_hash, Status::Failed); }, }, - ValidatedTransaction::Invalid(_, _) | - ValidatedTransaction::Unknown(_, _) => { + ValidatedTransaction::Invalid(_, _) + | ValidatedTransaction::Unknown(_, _) => { final_statuses.insert(tx_hash, Status::Failed); }, } diff --git a/bizinikiwi/client/transaction-pool/src/single_state_txpool/single_state_txpool.rs b/bizinikiwi/client/transaction-pool/src/single_state_txpool/single_state_txpool.rs index 327b6eca..ef5bae90 100644 --- a/bizinikiwi/client/transaction-pool/src/single_state_txpool/single_state_txpool.rs +++ b/bizinikiwi/client/transaction-pool/src/single_state_txpool/single_state_txpool.rs @@ -198,8 +198,9 @@ where pool_api.clone(), )); let (revalidation_queue, background_task) = match revalidation_type { - RevalidationType::Light => - (revalidation::RevalidationQueue::new(pool_api.clone(), pool.clone()), None), + RevalidationType::Light => { + (revalidation::RevalidationQueue::new(pool_api.clone(), pool.clone()), None) + }, RevalidationType::Full => { let (queue, background) = revalidation::RevalidationQueue::new_background( pool_api.clone(), @@ -219,8 +220,9 @@ where pool, revalidation_queue: Arc::new(revalidation_queue), revalidation_strategy: Arc::new(Mutex::new(match revalidation_type { - RevalidationType::Light => - RevalidationStrategy::Light(RevalidationStatus::NotScheduled), + RevalidationType::Light => { + RevalidationStrategy::Light(RevalidationStatus::NotScheduled) + }, RevalidationType::Full => RevalidationStrategy::Always, })), ready_poll: Arc::new(Mutex::new(ReadyPoll::new(best_block_number))), @@ -582,8 +584,8 @@ impl RevalidationStatus { }, Self::Scheduled(revalidate_at_time, revalidate_at_block) => { let is_required = - revalidate_at_time.map(|at| Instant::now() >= at).unwrap_or(false) || - revalidate_at_block.map(|at| block >= at).unwrap_or(false); + revalidate_at_time.map(|at| Instant::now() >= at).unwrap_or(false) + || revalidate_at_block.map(|at| block >= at).unwrap_or(false); if is_required { *self = Self::InProgress; } @@ -777,10 +779,11 @@ where let compute_tree_route = |from, to| -> Result, String> { match self.api.tree_route(from, to) { Ok(tree_route) => Ok(tree_route), - Err(e) => + Err(e) => { return Err(format!( "Error occurred while computing tree_route from {from:?} to {to:?}: {e}" - )), + )) + }, } }; let block_id_to_number = diff --git a/bizinikiwi/client/transaction-pool/tests/zombienet/yap_test.rs b/bizinikiwi/client/transaction-pool/tests/zombienet/yap_test.rs index b682fb1d..fc54118f 100644 --- a/bizinikiwi/client/transaction-pool/tests/zombienet/yap_test.rs +++ b/bizinikiwi/client/transaction-pool/tests/zombienet/yap_test.rs @@ -22,7 +22,7 @@ // https://github.com/pezkuwichain/pezkuwi-sdk/issues/124#issuecomment-2808830472 use crate::zombienet::{BlockSubscriptionType, NetworkSpawner, ScenarioBuilderSharedParams}; -use pezcumulus_zombienet_sdk_helpers::{create_assign_core_call}; +use pezcumulus_zombienet_sdk_helpers::create_assign_core_call; use serde_json::json; use txtesttool::{execution_log::ExecutionLog, scenario::ScenarioBuilder}; use zombienet_sdk::{ diff --git a/bizinikiwi/client/utils/src/mpsc.rs b/bizinikiwi/client/utils/src/mpsc.rs index c834bdbb..eea79070 100644 --- a/bizinikiwi/client/utils/src/mpsc.rs +++ b/bizinikiwi/client/utils/src/mpsc.rs @@ -108,8 +108,9 @@ impl TracingUnboundedSender { .with_label_values(&[self.name]) .set(self.inner.len().saturated_into()); - if self.inner.len() >= self.queue_size_warning && - self.warning_fired + if self.inner.len() >= self.queue_size_warning + && self + .warning_fired .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed) .is_ok() { diff --git a/bizinikiwi/pezframe/alliance/src/migration.rs b/bizinikiwi/pezframe/alliance/src/migration.rs index d3278a91..190b9039 100644 --- a/bizinikiwi/pezframe/alliance/src/migration.rs +++ b/bizinikiwi/pezframe/alliance/src/migration.rs @@ -108,8 +108,8 @@ pub(crate) mod v1_to_v2 { .len() .saturating_add(fellows_vec.len()) .saturating_add(allies.len()) - .saturating_add(retiring.len()) == - 0 + .saturating_add(retiring.len()) + == 0 { return T::DbWeight::get().reads(4); } diff --git a/bizinikiwi/pezframe/asset-conversion/ops/src/benchmarking.rs b/bizinikiwi/pezframe/asset-conversion/ops/src/benchmarking.rs index ae65dc15..a062fdf7 100644 --- a/bizinikiwi/pezframe/asset-conversion/ops/src/benchmarking.rs +++ b/bizinikiwi/pezframe/asset-conversion/ops/src/benchmarking.rs @@ -82,10 +82,10 @@ fn mint_setup_fee_asset( assert_ok!(T::Assets::mint_into( T::PoolSetupFeeAsset::get(), &caller, - T::PoolSetupFee::get() + - T::Assets::deposit_required(asset1.clone()) + - T::Assets::deposit_required(asset2.clone()) + - T::PoolAssets::deposit_required(lp_token.clone()) + T::PoolSetupFee::get() + + T::Assets::deposit_required(asset1.clone()) + + T::Assets::deposit_required(asset2.clone()) + + T::PoolAssets::deposit_required(lp_token.clone()) )); } diff --git a/bizinikiwi/pezframe/asset-conversion/ops/src/lib.rs b/bizinikiwi/pezframe/asset-conversion/ops/src/lib.rs index 1c86fa5a..1c3893d7 100644 --- a/bizinikiwi/pezframe/asset-conversion/ops/src/lib.rs +++ b/bizinikiwi/pezframe/asset-conversion/ops/src/lib.rs @@ -208,8 +208,8 @@ pub mod pezpallet { // Transfer all pool related assets to the new account. ensure!( - balance1 == - T::Assets::transfer( + balance1 + == T::Assets::transfer( asset1.clone(), &prior_account, &new_account, @@ -220,8 +220,8 @@ pub mod pezpallet { ); ensure!( - balance2 == - T::Assets::transfer( + balance2 + == T::Assets::transfer( asset2.clone(), &prior_account, &new_account, @@ -232,8 +232,8 @@ pub mod pezpallet { ); ensure!( - lp_balance == - T::PoolAssets::transfer( + lp_balance + == T::PoolAssets::transfer( info.lp_token.clone(), &prior_account, &new_account, diff --git a/bizinikiwi/pezframe/asset-conversion/src/benchmarking.rs b/bizinikiwi/pezframe/asset-conversion/src/benchmarking.rs index bdd6d760..ae3c13e3 100644 --- a/bizinikiwi/pezframe/asset-conversion/src/benchmarking.rs +++ b/bizinikiwi/pezframe/asset-conversion/src/benchmarking.rs @@ -127,10 +127,10 @@ fn mint_setup_fee_asset( assert_ok!(T::Assets::mint_into( T::PoolSetupFeeAsset::get(), &caller, - T::PoolSetupFee::get() + - T::Assets::deposit_required(asset1.clone()) + - T::Assets::deposit_required(asset2.clone()) + - T::PoolAssets::deposit_required(lp_token.clone()) + T::PoolSetupFee::get() + + T::Assets::deposit_required(asset1.clone()) + + T::Assets::deposit_required(asset2.clone()) + + T::PoolAssets::deposit_required(lp_token.clone()) )); } @@ -387,18 +387,18 @@ mod benchmarks { Box::new(asset2.clone()) )); - if n > 0 && - ::Assets::deposit_held(asset1.clone(), pool_account.clone()).is_some() + if n > 0 + && ::Assets::deposit_held(asset1.clone(), pool_account.clone()).is_some() { let _ = ::Assets::refund(asset1.clone(), pool_account.clone()); } - if n > 1 && - ::Assets::deposit_held(asset2.clone(), pool_account.clone()).is_some() + if n > 1 + && ::Assets::deposit_held(asset2.clone(), pool_account.clone()).is_some() { let _ = ::Assets::refund(asset2.clone(), pool_account.clone()); } - if n > 2 && - ::PoolAssets::deposit_held(lp_token.clone(), pool_account.clone()) + if n > 2 + && ::PoolAssets::deposit_held(lp_token.clone(), pool_account.clone()) .is_some() { let _ = ::PoolAssets::refund(lp_token, pool_account); diff --git a/bizinikiwi/pezframe/asset-conversion/src/tests.rs b/bizinikiwi/pezframe/asset-conversion/src/tests.rs index be1ab2a2..fb2513cf 100644 --- a/bizinikiwi/pezframe/asset-conversion/src/tests.rs +++ b/bizinikiwi/pezframe/asset-conversion/src/tests.rs @@ -1392,12 +1392,12 @@ fn can_swap_tokens_for_exact_tokens_when_not_liquidity_provider() { assert_ok!(Assets::mint(RuntimeOrigin::signed(user2), 2, user2, base2)); let pezpallet_account = ::PoolLocator::address(&pool_id).unwrap(); - let before1 = balance(pezpallet_account, token_1.clone()) + - balance(user, token_1.clone()) + - balance(user2, token_1.clone()); - let before2 = balance(pezpallet_account, token_2.clone()) + - balance(user, token_2.clone()) + - balance(user2, token_2.clone()); + let before1 = balance(pezpallet_account, token_1.clone()) + + balance(user, token_1.clone()) + + balance(user2, token_1.clone()); + let before2 = balance(pezpallet_account, token_2.clone()) + + balance(user, token_2.clone()) + + balance(user2, token_2.clone()); let liquidity1 = 10000; let liquidity2 = 200; @@ -1440,15 +1440,15 @@ fn can_swap_tokens_for_exact_tokens_when_not_liquidity_provider() { // native and asset totals should be preserved. assert_eq!( before1, - balance(pezpallet_account, token_1.clone()) + - balance(user, token_1.clone()) + - balance(user2, token_1.clone()) + balance(pezpallet_account, token_1.clone()) + + balance(user, token_1.clone()) + + balance(user2, token_1.clone()) ); assert_eq!( before2, - balance(pezpallet_account, token_2.clone()) + - balance(user, token_2.clone()) + - balance(user2, token_2.clone()) + balance(pezpallet_account, token_2.clone()) + + balance(user, token_2.clone()) + + balance(user2, token_2.clone()) ); let lp_token_minted = pool_balance(user2, lp_token); diff --git a/bizinikiwi/pezframe/asset-rewards/src/benchmarking.rs b/bizinikiwi/pezframe/asset-rewards/src/benchmarking.rs index 36f235b4..69f8274c 100644 --- a/bizinikiwi/pezframe/asset-rewards/src/benchmarking.rs +++ b/bizinikiwi/pezframe/asset-rewards/src/benchmarking.rs @@ -258,8 +258,8 @@ mod benchmarks { } let new_reward_rate_per_block = - T::Assets::minimum_balance(T::BenchmarkHelper::reward_asset()).max(T::Balance::one()) + - T::Balance::one(); + T::Assets::minimum_balance(T::BenchmarkHelper::reward_asset()).max(T::Balance::one()) + + T::Balance::one(); #[extrinsic_call] _(caller_origin as T::RuntimeOrigin, 0, new_reward_rate_per_block); @@ -296,8 +296,8 @@ mod benchmarks { } let new_expiry_block = pool_expire::() - .evaluate(T::BlockNumberProvider::current_block_number()) + - BlockNumberFor::::one(); + .evaluate(T::BlockNumberProvider::current_block_number()) + + BlockNumberFor::::one(); #[extrinsic_call] _(create_origin as T::RuntimeOrigin, 0, DispatchTime::At(new_expiry_block)); diff --git a/bizinikiwi/pezframe/assets/precompiles/src/lib.rs b/bizinikiwi/pezframe/assets/precompiles/src/lib.rs index ba221bf6..0a5fa364 100644 --- a/bizinikiwi/pezframe/assets/precompiles/src/lib.rs +++ b/bizinikiwi/pezframe/assets/precompiles/src/lib.rs @@ -110,7 +110,9 @@ where match input { IERC20Calls::transfer(_) | IERC20Calls::approve(_) | IERC20Calls::transferFrom(_) if env.is_read_only() => - Err(Error::Error(pezpallet_revive::Error::::StateChangeDenied.into())), + { + Err(Error::Error(pezpallet_revive::Error::::StateChangeDenied.into())) + }, IERC20Calls::transfer(call) => Self::transfer(asset_id, call, env), IERC20Calls::totalSupply(_) => Self::total_supply(asset_id, env), diff --git a/bizinikiwi/pezframe/assets/src/functions.rs b/bizinikiwi/pezframe/assets/src/functions.rs index 2d379036..9f8d2b00 100644 --- a/bizinikiwi/pezframe/assets/src/functions.rs +++ b/bizinikiwi/pezframe/assets/src/functions.rs @@ -160,8 +160,8 @@ impl, I: 'static> Pezpallet { if amount < details.min_balance { return DepositConsequence::BelowMinimum; } - if !details.is_sufficient && - !pezframe_system::Pezpallet::::can_accrue_consumers(who, 2) + if !details.is_sufficient + && !pezframe_system::Pezpallet::::can_accrue_consumers(who, 2) { return DepositConsequence::CannotCreate; } @@ -209,7 +209,7 @@ impl, I: 'static> Pezpallet { T::Holder::balance_on_hold(id.clone(), who), T::Freezer::frozen_balance(id.clone(), who), ) { - (None, None) => + (None, None) => { if rest < details.min_balance { if keep_alive { WouldDie @@ -218,7 +218,8 @@ impl, I: 'static> Pezpallet { } } else { Success - }, + } + }, (maybe_held, maybe_frozen) => { let frozen = maybe_frozen.unwrap_or_default(); let held = maybe_held.unwrap_or_default(); diff --git a/bizinikiwi/pezframe/babe/src/tests.rs b/bizinikiwi/pezframe/babe/src/tests.rs index 6d1d8cc5..1bf9b74f 100644 --- a/bizinikiwi/pezframe/babe/src/tests.rs +++ b/bizinikiwi/pezframe/babe/src/tests.rs @@ -251,8 +251,8 @@ fn can_estimate_current_epoch_progress() { ); } else { assert!( - Babe::estimate_current_session_progress(i).0.unwrap() < - Permill::from_percent(100) + Babe::estimate_current_session_progress(i).0.unwrap() + < Permill::from_percent(100) ); } } diff --git a/bizinikiwi/pezframe/bags-list/src/list/mod.rs b/bizinikiwi/pezframe/bags-list/src/list/mod.rs index a81b341f..2e1e00e1 100644 --- a/bizinikiwi/pezframe/bags-list/src/list/mod.rs +++ b/bizinikiwi/pezframe/bags-list/src/list/mod.rs @@ -267,15 +267,14 @@ impl, I: 'static> List { // easier; they can just configure `type BagThresholds = ()`. let thresholds = T::BagThresholds::get(); let iter = thresholds.iter().copied(); - let iter: Box> = if thresholds.last() == - Some(&T::Score::max_value()) - { - // in the event that they included it, we can just pass the iterator through unchanged. - Box::new(iter.rev()) - } else { - // otherwise, insert it here. - Box::new(iter.chain(iter::once(T::Score::max_value())).rev()) - }; + let iter: Box> = + if thresholds.last() == Some(&T::Score::max_value()) { + // in the event that they included it, we can just pass the iterator through unchanged. + Box::new(iter.rev()) + } else { + // otherwise, insert it here. + Box::new(iter.chain(iter::once(T::Score::max_value())).rev()) + }; iter.filter_map(Bag::get).flat_map(|bag| bag.iter()) } @@ -615,15 +614,14 @@ impl, I: 'static> List { let thresholds = T::BagThresholds::get(); let iter = thresholds.iter().copied(); - let iter: Box> = if thresholds.last() == - Some(&T::Score::max_value()) - { - // in the event that they included it, we can just pass the iterator through unchanged. - Box::new(iter) - } else { - // otherwise, insert it here. - Box::new(iter.chain(core::iter::once(T::Score::max_value()))) - }; + let iter: Box> = + if thresholds.last() == Some(&T::Score::max_value()) { + // in the event that they included it, we can just pass the iterator through unchanged. + Box::new(iter) + } else { + // otherwise, insert it here. + Box::new(iter.chain(core::iter::once(T::Score::max_value()))) + }; iter.filter_map(|t| { Bag::::get(t) @@ -960,9 +958,9 @@ impl, I: 'static> Node { let expected_bag = Bag::::get(self.bag_upper).ok_or("bag not found for node")?; let id = self.id(); - let non_terminal_check = !self.is_terminal() && - expected_bag.head.as_ref() != Some(id) && - expected_bag.tail.as_ref() != Some(id); + let non_terminal_check = !self.is_terminal() + && expected_bag.head.as_ref() != Some(id) + && expected_bag.tail.as_ref() != Some(id); let terminal_check = expected_bag.head.as_ref() == Some(id) || expected_bag.tail.as_ref() == Some(id); pezframe_support::ensure!( diff --git a/bizinikiwi/pezframe/balances/src/impl_currency.rs b/bizinikiwi/pezframe/balances/src/impl_currency.rs index b644a177..6d70973f 100644 --- a/bizinikiwi/pezframe/balances/src/impl_currency.rs +++ b/bizinikiwi/pezframe/balances/src/impl_currency.rs @@ -835,8 +835,9 @@ where if slashed == beneficiary { return match status { Status::Free => Ok(Self::unreserve_named(id, slashed, value)), - Status::Reserved => - Ok(value.saturating_sub(Self::reserved_balance_named(id, slashed))), + Status::Reserved => { + Ok(value.saturating_sub(Self::reserved_balance_named(id, slashed))) + }, }; } diff --git a/bizinikiwi/pezframe/balances/src/lib.rs b/bizinikiwi/pezframe/balances/src/lib.rs index 8d97f1bf..998ce184 100644 --- a/bizinikiwi/pezframe/balances/src/lib.rs +++ b/bizinikiwi/pezframe/balances/src/lib.rs @@ -1295,16 +1295,18 @@ pub mod pezpallet { ensure!(!is_new, Error::::DeadAccount); Self::try_mutate_account(slashed, false, |from_account, _| -> DispatchResult { match status { - Status::Free => + Status::Free => { to_account.free = to_account .free .checked_add(&actual) - .ok_or(ArithmeticError::Overflow)?, - Status::Reserved => + .ok_or(ArithmeticError::Overflow)? + }, + Status::Reserved => { to_account.reserved = to_account .reserved .checked_add(&actual) - .ok_or(ArithmeticError::Overflow)?, + .ok_or(ArithmeticError::Overflow)? + }, } from_account.reserved.saturating_reduce(actual); Ok(()) @@ -1377,8 +1379,8 @@ pub mod pezpallet { fn hold_and_freeze_count() -> Result<(), pezsp_runtime::TryRuntimeError> { Holds::::iter_keys().try_for_each(|k| { - if Holds::::decode_len(k).unwrap_or(0) > - T::RuntimeHoldReason::VARIANT_COUNT as usize + if Holds::::decode_len(k).unwrap_or(0) + > T::RuntimeHoldReason::VARIANT_COUNT as usize { Err("Found `Hold` with too many elements") } else { diff --git a/bizinikiwi/pezframe/beefy/src/equivocation.rs b/bizinikiwi/pezframe/beefy/src/equivocation.rs index 084fe05c..6046002c 100644 --- a/bizinikiwi/pezframe/beefy/src/equivocation.rs +++ b/bizinikiwi/pezframe/beefy/src/equivocation.rs @@ -155,36 +155,45 @@ impl EquivocationEvidenceFor { /// Returns the authority id of the equivocator. fn offender_id(&self) -> &T::BeefyId { match self { - EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, _) => - equivocation_proof.offender_id(), - EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, _) => - &equivocation_proof.vote.id, - EquivocationEvidenceFor::FutureBlockVotingProof(equivocation_proof, _) => - &equivocation_proof.vote.id, + EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, _) => { + equivocation_proof.offender_id() + }, + EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, _) => { + &equivocation_proof.vote.id + }, + EquivocationEvidenceFor::FutureBlockVotingProof(equivocation_proof, _) => { + &equivocation_proof.vote.id + }, } } /// Returns the round number at which the equivocation occurred. fn round_number(&self) -> &BlockNumberFor { match self { - EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, _) => - equivocation_proof.round_number(), - EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, _) => - &equivocation_proof.vote.commitment.block_number, - EquivocationEvidenceFor::FutureBlockVotingProof(equivocation_proof, _) => - &equivocation_proof.vote.commitment.block_number, + EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, _) => { + equivocation_proof.round_number() + }, + EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, _) => { + &equivocation_proof.vote.commitment.block_number + }, + EquivocationEvidenceFor::FutureBlockVotingProof(equivocation_proof, _) => { + &equivocation_proof.vote.commitment.block_number + }, } } /// Returns the set id at which the equivocation occurred. fn set_id(&self) -> ValidatorSetId { match self { - EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, _) => - equivocation_proof.set_id(), - EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, _) => - equivocation_proof.vote.commitment.validator_set_id, - EquivocationEvidenceFor::FutureBlockVotingProof(equivocation_proof, _) => - equivocation_proof.vote.commitment.validator_set_id, + EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, _) => { + equivocation_proof.set_id() + }, + EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, _) => { + equivocation_proof.vote.commitment.validator_set_id + }, + EquivocationEvidenceFor::FutureBlockVotingProof(equivocation_proof, _) => { + equivocation_proof.vote.commitment.validator_set_id + }, } } @@ -273,8 +282,8 @@ impl EquivocationEvidenceFor { fn slash_fraction(&self) -> Option { match self { EquivocationEvidenceFor::DoubleVotingProof(_, _) => None, - EquivocationEvidenceFor::ForkVotingProof(_, _) | - EquivocationEvidenceFor::FutureBlockVotingProof(_, _) => Some(Perbill::from_percent(50)), + EquivocationEvidenceFor::ForkVotingProof(_, _) + | EquivocationEvidenceFor::FutureBlockVotingProof(_, _) => Some(Perbill::from_percent(50)), } } } diff --git a/bizinikiwi/pezframe/beefy/src/lib.rs b/bizinikiwi/pezframe/beefy/src/lib.rs index 958d9f56..1f631b3b 100644 --- a/bizinikiwi/pezframe/beefy/src/lib.rs +++ b/bizinikiwi/pezframe/beefy/src/lib.rs @@ -439,16 +439,18 @@ pub mod pezpallet { impl Call { pub fn to_equivocation_evidence_for(&self) -> Option> { match self { - Call::report_double_voting_unsigned { equivocation_proof, key_owner_proof } => + Call::report_double_voting_unsigned { equivocation_proof, key_owner_proof } => { Some(EquivocationEvidenceFor::::DoubleVotingProof( *equivocation_proof.clone(), key_owner_proof.clone(), - )), - Call::report_fork_voting_unsigned { equivocation_proof, key_owner_proof } => + )) + }, + Call::report_fork_voting_unsigned { equivocation_proof, key_owner_proof } => { Some(EquivocationEvidenceFor::::ForkVotingProof( *equivocation_proof.clone(), key_owner_proof.clone(), - )), + )) + }, _ => None, } } @@ -457,16 +459,18 @@ pub mod pezpallet { impl From> for Call { fn from(evidence: EquivocationEvidenceFor) -> Self { match evidence { - EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, key_owner_proof) => + EquivocationEvidenceFor::DoubleVotingProof(equivocation_proof, key_owner_proof) => { Call::report_double_voting_unsigned { equivocation_proof: Box::new(equivocation_proof), key_owner_proof, - }, - EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, key_owner_proof) => + } + }, + EquivocationEvidenceFor::ForkVotingProof(equivocation_proof, key_owner_proof) => { Call::report_fork_voting_unsigned { equivocation_proof: Box::new(equivocation_proof), key_owner_proof, - }, + } + }, EquivocationEvidenceFor::FutureBlockVotingProof( equivocation_proof, key_owner_proof, diff --git a/bizinikiwi/pezframe/benchmarking/src/v1.rs b/bizinikiwi/pezframe/benchmarking/src/v1.rs index a0c61e84..63c0a176 100644 --- a/bizinikiwi/pezframe/benchmarking/src/v1.rs +++ b/bizinikiwi/pezframe/benchmarking/src/v1.rs @@ -923,7 +923,7 @@ macro_rules! impl_bench_name_tests { // Every variant must implement [`BenchmarkingSetup`]. // // ```nocompile -// +// // struct Transfer; // impl BenchmarkingSetup for Transfer { ... } // diff --git a/bizinikiwi/pezframe/bounties/src/benchmarking.rs b/bizinikiwi/pezframe/bounties/src/benchmarking.rs index 193c6e21..08ce4817 100644 --- a/bizinikiwi/pezframe/bounties/src/benchmarking.rs +++ b/bizinikiwi/pezframe/bounties/src/benchmarking.rs @@ -66,8 +66,8 @@ fn setup_bounty, I: 'static>( let caller = account("caller", u, SEED); let value: BalanceOf = T::BountyValueMinimum::get().saturating_mul(100u32.into()); let fee = value / 2u32.into(); - let deposit = T::BountyDepositBase::get() + - T::DataDepositPerByte::get() * T::MaximumReasonLength::get().into(); + let deposit = T::BountyDepositBase::get() + + T::DataDepositPerByte::get() * T::MaximumReasonLength::get().into(); let _ = T::Currency::make_free_balance_be(&caller, deposit + minimum_balance::()); let curator = account("curator", u, SEED); let _ = diff --git a/bizinikiwi/pezframe/broker/src/benchmarking.rs b/bizinikiwi/pezframe/broker/src/benchmarking.rs index 6ab6722c..292b49a1 100644 --- a/bizinikiwi/pezframe/broker/src/benchmarking.rs +++ b/bizinikiwi/pezframe/broker/src/benchmarking.rs @@ -270,8 +270,8 @@ mod benches { _(origin as T::RuntimeOrigin, initial_price, extra_cores.try_into().unwrap()); assert!(SaleInfo::::get().is_some()); - let sale_start = RCBlockNumberProviderOf::::current_block_number() + - config.interlude_length; + let sale_start = RCBlockNumberProviderOf::::current_block_number() + + config.interlude_length; assert_last_event::( Event::SaleInitialized { sale_start, diff --git a/bizinikiwi/pezframe/broker/src/dispatchable_impls.rs b/bizinikiwi/pezframe/broker/src/dispatchable_impls.rs index ef833c1d..8f49f600 100644 --- a/bizinikiwi/pezframe/broker/src/dispatchable_impls.rs +++ b/bizinikiwi/pezframe/broker/src/dispatchable_impls.rs @@ -109,9 +109,9 @@ impl Pezpallet { let config = Configuration::::get().ok_or(Error::::Uninitialized)?; // Determine the core count - let core_count = Leases::::decode_len().unwrap_or(0) as CoreIndex + - Reservations::::decode_len().unwrap_or(0) as CoreIndex + - extra_cores; + let core_count = Leases::::decode_len().unwrap_or(0) as CoreIndex + + Reservations::::decode_len().unwrap_or(0) as CoreIndex + + extra_cores; Self::do_request_core_count(core_count)?; @@ -352,7 +352,9 @@ impl Pezpallet { let assigned = match PotentialRenewals::::get(renewal_id) { Some(PotentialRenewalRecord { completion: Partial(w), price: p }) if price == p => - w, + { + w + }, _ => CoreMask::void(), } | region_id.mask; let workload = diff --git a/bizinikiwi/pezframe/child-bounties/src/benchmarking.rs b/bizinikiwi/pezframe/child-bounties/src/benchmarking.rs index 8ed3ec31..f896b54d 100644 --- a/bizinikiwi/pezframe/child-bounties/src/benchmarking.rs +++ b/bizinikiwi/pezframe/child-bounties/src/benchmarking.rs @@ -66,8 +66,8 @@ fn setup_bounty( let caller = account("caller", user, SEED); let value: BalanceOf = T::BountyValueMinimum::get().saturating_mul(100u32.into()); let fee = value / 2u32.into(); - let deposit = T::BountyDepositBase::get() + - T::DataDepositPerByte::get() * T::MaximumReasonLength::get().into(); + let deposit = T::BountyDepositBase::get() + + T::DataDepositPerByte::get() * T::MaximumReasonLength::get().into(); let _ = T::Currency::make_free_balance_be(&caller, deposit + T::Currency::minimum_balance()); let curator = account("curator", user, SEED); let _ = T::Currency::make_free_balance_be( diff --git a/bizinikiwi/pezframe/child-bounties/src/lib.rs b/bizinikiwi/pezframe/child-bounties/src/lib.rs index 46ff3ba3..15a6f888 100644 --- a/bizinikiwi/pezframe/child-bounties/src/lib.rs +++ b/bizinikiwi/pezframe/child-bounties/src/lib.rs @@ -288,8 +288,8 @@ pub mod pezpallet { description.try_into().map_err(|_| BountiesError::::ReasonTooBig)?; ensure!(value >= T::ChildBountyValueMinimum::get(), BountiesError::::InvalidValue); ensure!( - ParentChildBounties::::get(parent_bounty_id) <= - T::MaxActiveChildBountyCount::get() as u32, + ParentChildBounties::::get(parent_bounty_id) + <= T::MaxActiveChildBountyCount::get() as u32, Error::::TooManyChildBounties, ); @@ -536,8 +536,8 @@ pub mod pezpallet { // child-bounty curator can unassign the child-bounty curator. ensure!( maybe_sender.map_or(true, |sender| { - sender == *curator || - Self::ensure_bounty_active(parent_bounty_id) + sender == *curator + || Self::ensure_bounty_active(parent_bounty_id) .map_or(false, |(parent_curator, _)| { sender == parent_curator }) @@ -566,8 +566,8 @@ pub mod pezpallet { Some(sender) => { let (parent_curator, update_due) = Self::ensure_bounty_active(parent_bounty_id)?; - if sender == parent_curator || - update_due < Self::treasury_block_number() + if sender == parent_curator + || update_due < Self::treasury_block_number() { // Slash the child-bounty curator if // + the call is made by the parent bounty curator. @@ -646,8 +646,8 @@ pub mod pezpallet { child_bounty.status = ChildBountyStatus::PendingPayout { curator: signer, beneficiary: beneficiary.clone(), - unlock_at: Self::treasury_block_number() + - T::BountyDepositPayoutDelay::get(), + unlock_at: Self::treasury_block_number() + + T::BountyDepositPayoutDelay::get(), }; Ok(()) } else { diff --git a/bizinikiwi/pezframe/contracts/fixtures/build.rs b/bizinikiwi/pezframe/contracts/fixtures/build.rs index 46a8b087..bfaa9b12 100644 --- a/bizinikiwi/pezframe/contracts/fixtures/build.rs +++ b/bizinikiwi/pezframe/contracts/fixtures/build.rs @@ -224,8 +224,8 @@ fn post_process_wasm(input_path: &Path, output_path: &Path) -> Result<()> { deserialize_file(input_path).with_context(|| format!("Failed to read {:?}", input_path))?; if let Some(section) = module.export_section_mut() { section.entries_mut().retain(|entry| { - matches!(entry.internal(), Internal::Function(_)) && - (entry.field() == "call" || entry.field() == "deploy") + matches!(entry.internal(), Internal::Function(_)) + && (entry.field() == "call" || entry.field() == "deploy") }); } diff --git a/bizinikiwi/pezframe/contracts/mock-network/src/mocks/msg_queue.rs b/bizinikiwi/pezframe/contracts/mock-network/src/mocks/msg_queue.rs index 05fb02d7..dd1c10d4 100644 --- a/bizinikiwi/pezframe/contracts/mock-network/src/mocks/msg_queue.rs +++ b/bizinikiwi/pezframe/contracts/mock-network/src/mocks/msg_queue.rs @@ -114,8 +114,9 @@ pub mod pezpallet { max_weight, Weight::zero(), ) { - Outcome::Error(InstructionError { error, .. }) => - (Err(error), Event::Fail(Some(hash), error)), + Outcome::Error(InstructionError { error, .. }) => { + (Err(error), Event::Fail(Some(hash), error)) + }, Outcome::Complete { used } => (Ok(used), Event::Success(Some(hash))), // As far as the caller is concerned, this was dispatched without error, so // we just report the weight used. diff --git a/bizinikiwi/pezframe/contracts/mock-network/src/teyrchain.rs b/bizinikiwi/pezframe/contracts/mock-network/src/teyrchain.rs index 255d1ca6..53873909 100644 --- a/bizinikiwi/pezframe/contracts/mock-network/src/teyrchain.rs +++ b/bizinikiwi/pezframe/contracts/mock-network/src/teyrchain.rs @@ -177,8 +177,8 @@ pub fn estimate_weight(number_of_instructions: u64) -> Weight { pub fn estimate_fee_for_weight(weight: Weight) -> u128 { let (_, units_per_second, units_per_mb) = TokensPerSecondPerMegabyte::get(); - units_per_second * (weight.ref_time() as u128) / (WEIGHT_REF_TIME_PER_SECOND as u128) + - units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128) + units_per_second * (weight.ref_time() as u128) / (WEIGHT_REF_TIME_PER_SECOND as u128) + + units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128) } pub type LocalBalancesTransactor = diff --git a/bizinikiwi/pezframe/contracts/proc-macro/src/lib.rs b/bizinikiwi/pezframe/contracts/proc-macro/src/lib.rs index 859b59d8..b610154d 100644 --- a/bizinikiwi/pezframe/contracts/proc-macro/src/lib.rs +++ b/bizinikiwi/pezframe/contracts/proc-macro/src/lib.rs @@ -391,7 +391,8 @@ impl EnvDef { fn is_valid_special_arg(idx: usize, arg: &FnArg) -> bool { let FnArg::Typed(pat) = arg else { return false }; - let ident = if let syn::Pat::Ident(ref ident) = *pat.pat { &ident.ident } else { return false }; + let ident = + if let syn::Pat::Ident(ref ident) = *pat.pat { &ident.ident } else { return false }; let name_ok = match idx { 0 => ident == "ctx" || ident == "_ctx", 1 => ident == "memory" || ident == "_memory", diff --git a/bizinikiwi/pezframe/contracts/src/benchmarking/mod.rs b/bizinikiwi/pezframe/contracts/src/benchmarking/mod.rs index c608e80c..ef2769f5 100644 --- a/bizinikiwi/pezframe/contracts/src/benchmarking/mod.rs +++ b/bizinikiwi/pezframe/contracts/src/benchmarking/mod.rs @@ -568,10 +568,10 @@ mod benchmarks { // value and value transferred via call should be removed from the caller assert_eq!( T::Currency::balance(&instance.caller), - caller_funding::() - - instance.value - - value - deposit - - Pezpallet::::min_balance(), + caller_funding::() + - instance.value + - value - deposit + - Pezpallet::::min_balance(), ); // contract should have received the value assert_eq!(T::Currency::balance(&instance.account_id), before + value); diff --git a/bizinikiwi/pezframe/contracts/src/exec.rs b/bizinikiwi/pezframe/contracts/src/exec.rs index fbeacb28..c5e92998 100644 --- a/bizinikiwi/pezframe/contracts/src/exec.rs +++ b/bizinikiwi/pezframe/contracts/src/exec.rs @@ -884,9 +884,9 @@ where // `Relaxed` will only be ever set in case of off-chain execution. // Instantiations are never allowed even when executing off-chain. - if !(executable.is_deterministic() || - (matches!(determinism, Determinism::Relaxed) && - matches!(entry_point, ExportedFunction::Call))) + if !(executable.is_deterministic() + || (matches!(determinism, Determinism::Relaxed) + && matches!(entry_point, ExportedFunction::Call))) { return Err(Error::::Indeterministic.into()); } @@ -1064,8 +1064,9 @@ where with_transaction(|| -> TransactionOutcome> { let output = do_transaction(); match &output { - Ok(result) if !result.did_revert() => - TransactionOutcome::Commit(Ok((true, output))), + Ok(result) if !result.did_revert() => { + TransactionOutcome::Commit(Ok((true, output))) + }, _ => TransactionOutcome::Rollback(Ok((false, output))), } }); diff --git a/bizinikiwi/pezframe/contracts/src/lib.rs b/bizinikiwi/pezframe/contracts/src/lib.rs index 41fd1891..ba2bc0f0 100644 --- a/bizinikiwi/pezframe/contracts/src/lib.rs +++ b/bizinikiwi/pezframe/contracts/src/lib.rs @@ -694,8 +694,8 @@ pub mod pezpallet { // We can use storage to store items using the available block ref_time with the // `set_storage` host function. - let max_storage_size: u32 = ((max_block_ref_time / - (>::weight(&RuntimeCosts::SetStorage { + let max_storage_size: u32 = ((max_block_ref_time + / (>::weight(&RuntimeCosts::SetStorage { new_bytes: max_payload_size, old_bytes: 0, }) @@ -717,8 +717,8 @@ pub mod pezpallet { // We can use storage to store events using the available block ref_time with the // `deposit_event` host function. The overhead of stored events, which is around 100B, // is not taken into account to simplify calculations, as it does not change much. - let max_events_size: u32 = ((max_block_ref_time / - (>::weight(&RuntimeCosts::DepositEvent { + let max_events_size: u32 = ((max_block_ref_time + / (>::weight(&RuntimeCosts::DepositEvent { num_topic: 0, len: max_payload_size, }) @@ -1570,12 +1570,13 @@ impl Invokable for CallInput { let mut storage_meter = match StorageMeter::new(&origin, common.storage_deposit_limit, common.value) { Ok(meter) => meter, - Err(err) => + Err(err) => { return InternalOutput { result: Err(err.into()), gas_meter, storage_deposit: Default::default(), - }, + } + }, }; let schedule = T::Schedule::get(); let result = ExecStack::>::run_call( @@ -1780,7 +1781,7 @@ impl Pezpallet { let (module, deposit) = match result { Ok(result) => result, - Err(error) => + Err(error) => { return ContractResult { gas_consumed: Zero::zero(), gas_required: Zero::zero(), @@ -1788,7 +1789,8 @@ impl Pezpallet { debug_message: debug_message.unwrap_or(Default::default()).into(), result: Err(error), events: events(), - }, + } + }, }; storage_deposit_limit = diff --git a/bizinikiwi/pezframe/contracts/src/migration/v10.rs b/bizinikiwi/pezframe/contracts/src/migration/v10.rs index b0e743c2..0dcc329a 100644 --- a/bizinikiwi/pezframe/contracts/src/migration/v10.rs +++ b/bizinikiwi/pezframe/contracts/src/migration/v10.rs @@ -308,8 +308,8 @@ where &contract.deposit_account, ); ensure!( - deposit == - contract + deposit + == contract .storage_base_deposit .saturating_add(contract.storage_item_deposit) .saturating_add(contract.storage_byte_deposit), diff --git a/bizinikiwi/pezframe/contracts/src/migration/v14.rs b/bizinikiwi/pezframe/contracts/src/migration/v14.rs index a7809d9b..869c80f0 100644 --- a/bizinikiwi/pezframe/contracts/src/migration/v14.rs +++ b/bizinikiwi/pezframe/contracts/src/migration/v14.rs @@ -249,8 +249,8 @@ where old_balance_allocation.total ); ensure!( - T::Currency::total_balance(&owner) == - BalanceOf::::decode(&mut &old_balance_allocation.total.encode()[..]) + T::Currency::total_balance(&owner) + == BalanceOf::::decode(&mut &old_balance_allocation.total.encode()[..]) .unwrap(), "Balance mismatch " ); diff --git a/bizinikiwi/pezframe/contracts/src/migration/v15.rs b/bizinikiwi/pezframe/contracts/src/migration/v15.rs index ea265da5..cda7bf4f 100644 --- a/bizinikiwi/pezframe/contracts/src/migration/v15.rs +++ b/bizinikiwi/pezframe/contracts/src/migration/v15.rs @@ -315,18 +315,18 @@ impl MigrationStep for Migration { "code_hash mismatch" ); ensure!( - migration_contract_info.storage_byte_deposit == - crate_contract_info.storage_byte_deposit, + migration_contract_info.storage_byte_deposit + == crate_contract_info.storage_byte_deposit, "storage_byte_deposit mismatch" ); ensure!( - migration_contract_info.storage_base_deposit == - crate_contract_info.storage_base_deposit(), + migration_contract_info.storage_base_deposit + == crate_contract_info.storage_base_deposit(), "storage_base_deposit mismatch" ); ensure!( - &migration_contract_info.delegate_dependencies == - crate_contract_info.delegate_dependencies(), + &migration_contract_info.delegate_dependencies + == crate_contract_info.delegate_dependencies(), "delegate_dependencies mismatch" ); } diff --git a/bizinikiwi/pezframe/contracts/src/primitives.rs b/bizinikiwi/pezframe/contracts/src/primitives.rs index 127660c2..24a40f59 100644 --- a/bizinikiwi/pezframe/contracts/src/primitives.rs +++ b/bizinikiwi/pezframe/contracts/src/primitives.rs @@ -200,18 +200,20 @@ where match (self, rhs) { (Charge(lhs), Charge(rhs)) => Charge(lhs.saturating_add(*rhs)), (Refund(lhs), Refund(rhs)) => Refund(lhs.saturating_add(*rhs)), - (Charge(lhs), Refund(rhs)) => + (Charge(lhs), Refund(rhs)) => { if lhs >= rhs { Charge(lhs.saturating_sub(*rhs)) } else { Refund(rhs.saturating_sub(*lhs)) - }, - (Refund(lhs), Charge(rhs)) => + } + }, + (Refund(lhs), Charge(rhs)) => { if lhs > rhs { Refund(lhs.saturating_sub(*rhs)) } else { Charge(rhs.saturating_sub(*lhs)) - }, + } + }, } } @@ -221,18 +223,20 @@ where match (self, rhs) { (Charge(lhs), Refund(rhs)) => Charge(lhs.saturating_add(*rhs)), (Refund(lhs), Charge(rhs)) => Refund(lhs.saturating_add(*rhs)), - (Charge(lhs), Charge(rhs)) => + (Charge(lhs), Charge(rhs)) => { if lhs >= rhs { Charge(lhs.saturating_sub(*rhs)) } else { Refund(rhs.saturating_sub(*lhs)) - }, - (Refund(lhs), Refund(rhs)) => + } + }, + (Refund(lhs), Refund(rhs)) => { if lhs > rhs { Refund(lhs.saturating_sub(*rhs)) } else { Charge(rhs.saturating_sub(*lhs)) - }, + } + }, } } diff --git a/bizinikiwi/pezframe/contracts/src/storage.rs b/bizinikiwi/pezframe/contracts/src/storage.rs index 10a2ba8e..d8526731 100644 --- a/bizinikiwi/pezframe/contracts/src/storage.rs +++ b/bizinikiwi/pezframe/contracts/src/storage.rs @@ -198,12 +198,13 @@ impl ContractInfo { if let Some(storage_meter) = storage_meter { let mut diff = meter::Diff::default(); match (old_len, new_value.as_ref().map(|v| v.len() as u32)) { - (Some(old_len), Some(new_len)) => + (Some(old_len), Some(new_len)) => { if new_len > old_len { diff.bytes_added = new_len - old_len; } else { diff.bytes_removed = old_len - new_len; - }, + } + }, (None, Some(new_len)) => { diff.bytes_added = new_len; diff.items_added = 1; @@ -297,8 +298,8 @@ impl ContractInfo { /// of those keys can be deleted from the deletion queue given the supplied weight limit. pub fn deletion_budget(meter: &WeightMeter) -> (Weight, u32) { let base_weight = T::WeightInfo::on_process_deletion_queue_batch(); - let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1) - - T::WeightInfo::on_initialize_per_trie_key(0); + let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1) + - T::WeightInfo::on_initialize_per_trie_key(0); // `weight_per_key` being zero makes no sense and would constitute a failure to // benchmark properly. We opt for not removing any keys at all in this case. diff --git a/bizinikiwi/pezframe/contracts/src/storage/meter.rs b/bizinikiwi/pezframe/contracts/src/storage/meter.rs index dfb9c066..2b9afd37 100644 --- a/bizinikiwi/pezframe/contracts/src/storage/meter.rs +++ b/bizinikiwi/pezframe/contracts/src/storage/meter.rs @@ -194,16 +194,20 @@ impl Diff { info.storage_items = info.storage_items.saturating_add(items_added).saturating_sub(items_removed); match &bytes_deposit { - Deposit::Charge(amount) => - info.storage_byte_deposit = info.storage_byte_deposit.saturating_add(*amount), - Deposit::Refund(amount) => - info.storage_byte_deposit = info.storage_byte_deposit.saturating_sub(*amount), + Deposit::Charge(amount) => { + info.storage_byte_deposit = info.storage_byte_deposit.saturating_add(*amount) + }, + Deposit::Refund(amount) => { + info.storage_byte_deposit = info.storage_byte_deposit.saturating_sub(*amount) + }, } match &items_deposit { - Deposit::Charge(amount) => - info.storage_item_deposit = info.storage_item_deposit.saturating_add(*amount), - Deposit::Refund(amount) => - info.storage_item_deposit = info.storage_item_deposit.saturating_sub(*amount), + Deposit::Charge(amount) => { + info.storage_item_deposit = info.storage_item_deposit.saturating_add(*amount) + }, + Deposit::Refund(amount) => { + info.storage_item_deposit = info.storage_item_deposit.saturating_sub(*amount) + }, } bytes_deposit.saturating_add(&items_deposit) @@ -265,8 +269,9 @@ impl Contribution { fn update_contract(&self, info: Option<&mut ContractInfo>) -> DepositOf { match self { Self::Alive(diff) => diff.update_contract::(info), - Self::Terminated { deposit, beneficiary: _ } | Self::Checked(deposit) => - deposit.clone(), + Self::Terminated { deposit, beneficiary: _ } | Self::Checked(deposit) => { + deposit.clone() + }, } } } @@ -346,8 +351,9 @@ where /// Returns the state of the currently executed contract. fn contract_state(&self) -> ContractState { match &self.own_contribution { - Contribution::Terminated { deposit: _, beneficiary } => - ContractState::Terminated { beneficiary: beneficiary.clone() }, + Contribution::Terminated { deposit: _, beneficiary } => { + ContractState::Terminated { beneficiary: beneficiary.clone() } + }, _ => ContractState::Alive, } } @@ -524,8 +530,8 @@ impl Ext for ReservingExt { let default = max.min(T::DefaultDepositLimit::get()); let limit = limit.unwrap_or(default); ensure!( - limit <= max && - matches!(T::Currency::can_withdraw(origin, limit), WithdrawConsequence::Success), + limit <= max + && matches!(T::Currency::can_withdraw(origin, limit), WithdrawConsequence::Success), >::StorageDepositNotEnoughFunds, ); Ok(limit) diff --git a/bizinikiwi/pezframe/contracts/src/tests.rs b/bizinikiwi/pezframe/contracts/src/tests.rs index 2fba0d93..bfebb5f5 100644 --- a/bizinikiwi/pezframe/contracts/src/tests.rs +++ b/bizinikiwi/pezframe/contracts/src/tests.rs @@ -150,8 +150,8 @@ pub mod test_utils { let code_info_len = CodeInfo::::max_encoded_len() as u64; // Calculate deposit to be reserved. // We add 2 storage items: one for code, other for code_info - DepositPerByte::get().saturating_mul(code_len as u64 + code_info_len) + - DepositPerItem::get().saturating_mul(2) + DepositPerByte::get().saturating_mul(code_len as u64 + code_info_len) + + DepositPerItem::get().saturating_mul(2) } pub fn ensure_stored(code_hash: CodeHash) -> usize { // Assert that code_info is stored diff --git a/bizinikiwi/pezframe/contracts/src/wasm/mod.rs b/bizinikiwi/pezframe/contracts/src/wasm/mod.rs index f0874f64..77785e26 100644 --- a/bizinikiwi/pezframe/contracts/src/wasm/mod.rs +++ b/bizinikiwi/pezframe/contracts/src/wasm/mod.rs @@ -690,8 +690,9 @@ mod tests { let entry = self.storage.entry(key.clone()); let result = match (entry, take_old) { (Entry::Vacant(_), _) => WriteOutcome::New, - (Entry::Occupied(entry), false) => - WriteOutcome::Overwritten(entry.remove().len() as u32), + (Entry::Occupied(entry), false) => { + WriteOutcome::Overwritten(entry.remove().len() as u32) + }, (Entry::Occupied(entry), true) => WriteOutcome::Taken(entry.remove()), }; if let Some(value) = value { diff --git a/bizinikiwi/pezframe/contracts/src/wasm/prepare.rs b/bizinikiwi/pezframe/contracts/src/wasm/prepare.rs index 082713e8..26efd82e 100644 --- a/bizinikiwi/pezframe/contracts/src/wasm/prepare.rs +++ b/bizinikiwi/pezframe/contracts/src/wasm/prepare.rs @@ -133,16 +133,17 @@ impl LoadedModule { match export.name() { "call" => call_found = true, "deploy" => deploy_found = true, - _ => + _ => { return Err( "unknown function export: expecting only deploy and call functions", - ), + ) + }, } // Check the signature. // Both "call" and "deploy" have the () -> () function type. // We still support () -> (i32) for backwards compatibility. - if !(ft.params().is_empty() && - (ft.results().is_empty() || ft.results() == [WasmiValueType::I32])) + if !(ft.params().is_empty() + && (ft.results().is_empty() || ft.results() == [WasmiValueType::I32])) { return Err("entry point has wrong signature"); } @@ -194,9 +195,9 @@ impl LoadedModule { ExternType::Func(_) => { import.ty().func().ok_or("expected a function")?; - if !::ChainExtension::enabled() && - (import.name().as_bytes() == b"seal_call_chain_extension" || - import.name().as_bytes() == b"call_chain_extension") + if !::ChainExtension::enabled() + && (import.name().as_bytes() == b"seal_call_chain_extension" + || import.name().as_bytes() == b"call_chain_extension") { return Err( "Module uses chain extensions but chain extensions are disabled", diff --git a/bizinikiwi/pezframe/contracts/src/wasm/runtime.rs b/bizinikiwi/pezframe/contracts/src/wasm/runtime.rs index 2e9b867b..1f7cbc8b 100644 --- a/bizinikiwi/pezframe/contracts/src/wasm/runtime.rs +++ b/bizinikiwi/pezframe/contracts/src/wasm/runtime.rs @@ -364,8 +364,9 @@ impl Token for RuntimeCosts { DelegateCallBase => T::WeightInfo::seal_delegate_call(), CallTransferSurcharge => cost_args!(seal_call, 1, 0), CallInputCloned(len) => cost_args!(seal_call, 0, len), - Instantiate { input_data_len, salt_len } => - T::WeightInfo::seal_instantiate(input_data_len, salt_len), + Instantiate { input_data_len, salt_len } => { + T::WeightInfo::seal_instantiate(input_data_len, salt_len) + }, HashSha256(len) => T::WeightInfo::seal_hash_sha2_256(len), HashKeccak256(len) => T::WeightInfo::seal_hash_keccak_256(len), HashBlake256(len) => T::WeightInfo::seal_hash_blake2_256(len), @@ -481,8 +482,9 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { ReturnFlags::from_bits(*flags).ok_or(Error::::InvalidCallFlags)?; return Ok(ExecReturnValue { flags, data: data.to_vec() }); }, - Termination => - return Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() }), + Termination => { + return Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() }) + }, SupervisorError(error) => return Err((*error).into()), } } @@ -2271,8 +2273,9 @@ pub mod env { Environment::new(ctx, memory, id, input_ptr, input_len, output_ptr, output_len_ptr); let ret = match chain_extension.call(env)? { RetVal::Converging(val) => Ok(val), - RetVal::Diverging { flags, data } => - Err(TrapReason::Return(ReturnData { flags: flags.bits(), data })), + RetVal::Diverging { flags, data } => { + Err(TrapReason::Return(ReturnData { flags: flags.bits(), data })) + }, }; ctx.chain_extension = Some(chain_extension); ret diff --git a/bizinikiwi/pezframe/contracts/uapi/src/host/wasm32.rs b/bizinikiwi/pezframe/contracts/uapi/src/host/wasm32.rs index 55600bc3..d0bb91ca 100644 --- a/bizinikiwi/pezframe/contracts/uapi/src/host/wasm32.rs +++ b/bizinikiwi/pezframe/contracts/uapi/src/host/wasm32.rs @@ -308,7 +308,7 @@ mod sys { // (v1) => [gas_left], // } // ``` -// +// // Expands to: // ```nocompile // fn gas_left(output: &mut &mut [u8]) { diff --git a/bizinikiwi/pezframe/conviction-voting/src/lib.rs b/bizinikiwi/pezframe/conviction-voting/src/lib.rs index 130560b8..7950a8c2 100644 --- a/bizinikiwi/pezframe/conviction-voting/src/lib.rs +++ b/bizinikiwi/pezframe/conviction-voting/src/lib.rs @@ -645,8 +645,9 @@ impl, I: 'static> Pezpallet { }), ); match old { - Voting::Delegating(Delegating { .. }) => - return Err(Error::::AlreadyDelegating.into()), + Voting::Delegating(Delegating { .. }) => { + return Err(Error::::AlreadyDelegating.into()) + }, Voting::Casting(Casting { votes, delegations, prior }) => { // here we just ensure that we're currently idling with no votes recorded. ensure!(votes.is_empty(), Error::::AlreadyVoting); diff --git a/bizinikiwi/pezframe/conviction-voting/src/tests.rs b/bizinikiwi/pezframe/conviction-voting/src/tests.rs index 7b231d25..becbf167 100644 --- a/bizinikiwi/pezframe/conviction-voting/src/tests.rs +++ b/bizinikiwi/pezframe/conviction-voting/src/tests.rs @@ -99,8 +99,9 @@ impl Polling> for TestPolls { let mut polls = Polls::get(); let entry = polls.get_mut(&index); let r = match entry { - Some(Ongoing(ref mut tally_mut_ref, class)) => - f(PollStatus::Ongoing(tally_mut_ref, *class)), + Some(Ongoing(ref mut tally_mut_ref, class)) => { + f(PollStatus::Ongoing(tally_mut_ref, *class)) + }, Some(Completed(when, succeeded)) => f(PollStatus::Completed(*when, *succeeded)), None => f(PollStatus::None), }; @@ -114,8 +115,9 @@ impl Polling> for TestPolls { let mut polls = Polls::get(); let entry = polls.get_mut(&index); let r = match entry { - Some(Ongoing(ref mut tally_mut_ref, class)) => - f(PollStatus::Ongoing(tally_mut_ref, *class)), + Some(Ongoing(ref mut tally_mut_ref, class)) => { + f(PollStatus::Ongoing(tally_mut_ref, *class)) + }, Some(Completed(when, succeeded)) => f(PollStatus::Completed(*when, *succeeded)), None => f(PollStatus::None), }?; diff --git a/bizinikiwi/pezframe/conviction-voting/src/vote.rs b/bizinikiwi/pezframe/conviction-voting/src/vote.rs index 3c332220..632a9b6e 100644 --- a/bizinikiwi/pezframe/conviction-voting/src/vote.rs +++ b/bizinikiwi/pezframe/conviction-voting/src/vote.rs @@ -110,17 +110,21 @@ impl AccountVote { // winning side: can only be removed after the lock period ends. match (self, approved) { // If the vote has no conviction, always return None - (AccountVote::Standard { vote: Vote { conviction: Conviction::None, .. }, .. }, _) => - None, + (AccountVote::Standard { vote: Vote { conviction: Conviction::None, .. }, .. }, _) => { + None + }, // For Standard votes, check the approval condition (AccountVote::Standard { vote, balance }, LockedIf::Status(is_approved)) if vote.aye == is_approved => - Some((vote.conviction.lock_periods(), balance)), + { + Some((vote.conviction.lock_periods(), balance)) + }, // If LockedIf::Always, return the lock period regardless of the vote - (AccountVote::Standard { vote, balance }, LockedIf::Always) => - Some((vote.conviction.lock_periods(), balance)), + (AccountVote::Standard { vote, balance }, LockedIf::Always) => { + Some((vote.conviction.lock_periods(), balance)) + }, // All other cases return None _ => None, @@ -132,8 +136,9 @@ impl AccountVote { match self { AccountVote::Standard { balance, .. } => balance, AccountVote::Split { aye, nay } => aye.saturating_add(nay), - AccountVote::SplitAbstain { aye, nay, abstain } => - aye.saturating_add(nay).saturating_add(abstain), + AccountVote::SplitAbstain { aye, nay, abstain } => { + aye.saturating_add(nay).saturating_add(abstain) + }, } } @@ -307,8 +312,9 @@ where /// The amount of this account's balance that must currently be locked due to voting. pub fn locked_balance(&self) -> Balance { match self { - Voting::Casting(Casting { votes, prior, .. }) => - votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i)), + Voting::Casting(Casting { votes, prior, .. }) => { + votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i)) + }, Voting::Delegating(Delegating { balance, prior, .. }) => *balance.max(&prior.locked()), } } @@ -319,10 +325,12 @@ where prior: PriorLock, ) { let (d, p) = match self { - Voting::Casting(Casting { ref mut delegations, ref mut prior, .. }) => - (delegations, prior), - Voting::Delegating(Delegating { ref mut delegations, ref mut prior, .. }) => - (delegations, prior), + Voting::Casting(Casting { ref mut delegations, ref mut prior, .. }) => { + (delegations, prior) + }, + Voting::Delegating(Delegating { ref mut delegations, ref mut prior, .. }) => { + (delegations, prior) + }, }; *d = delegations; *p = prior; diff --git a/bizinikiwi/pezframe/delegated-staking/src/lib.rs b/bizinikiwi/pezframe/delegated-staking/src/lib.rs index f8a3b02b..82138b8a 100644 --- a/bizinikiwi/pezframe/delegated-staking/src/lib.rs +++ b/bizinikiwi/pezframe/delegated-staking/src/lib.rs @@ -326,9 +326,9 @@ pub mod pezpallet { let ledger = AgentLedger::::get(&who).ok_or(Error::::NotAgent)?; ensure!( - ledger.total_delegated == Zero::zero() && - ledger.pending_slash == Zero::zero() && - ledger.unclaimed_withdrawals == Zero::zero(), + ledger.total_delegated == Zero::zero() + && ledger.pending_slash == Zero::zero() + && ledger.unclaimed_withdrawals == Zero::zero(), Error::::NotAllowed ); @@ -788,16 +788,16 @@ impl Pezpallet { ensure!( matches!( T::CoreStaking::status(&agent).expect("agent should be bonded"), - pezsp_staking::StakerStatus::Nominator(_) | - pezsp_staking::StakerStatus::Idle + pezsp_staking::StakerStatus::Nominator(_) + | pezsp_staking::StakerStatus::Idle ), "agent should be bonded and not validator" ); } ensure!( - ledger.stakeable_balance() >= - T::CoreStaking::total_stake(&agent).unwrap_or_default(), + ledger.stakeable_balance() + >= T::CoreStaking::total_stake(&agent).unwrap_or_default(), "Cannot stake more than balance" ); } diff --git a/bizinikiwi/pezframe/delegated-staking/src/mock.rs b/bizinikiwi/pezframe/delegated-staking/src/mock.rs index 2f0f1e8f..1da65e4f 100644 --- a/bizinikiwi/pezframe/delegated-staking/src/mock.rs +++ b/bizinikiwi/pezframe/delegated-staking/src/mock.rs @@ -303,8 +303,8 @@ pub(crate) fn start_era(era: pezsp_staking::EraIndex) { } pub(crate) fn eq_stake(who: AccountId, total: Balance, active: Balance) -> bool { - Staking::stake(&who).unwrap() == Stake { total, active } && - get_agent_ledger(&who).ledger.stakeable_balance() == total + Staking::stake(&who).unwrap() == Stake { total, active } + && get_agent_ledger(&who).ledger.stakeable_balance() == total } pub(crate) fn get_agent_ledger(agent: &AccountId) -> AgentLedgerOuter { diff --git a/bizinikiwi/pezframe/democracy/src/benchmarking.rs b/bizinikiwi/pezframe/democracy/src/benchmarking.rs index e030cedf..445a24b9 100644 --- a/bizinikiwi/pezframe/democracy/src/benchmarking.rs +++ b/bizinikiwi/pezframe/democracy/src/benchmarking.rs @@ -551,8 +551,9 @@ mod benchmarks { for i in 0..r { if let Some(value) = ReferendumInfoOf::::get(i) { match value { - ReferendumInfo::Finished { .. } => - return Err("Referendum has been finished".into()), + ReferendumInfo::Finished { .. } => { + return Err("Referendum has been finished".into()) + }, ReferendumInfo::Ongoing(_) => (), } } @@ -589,8 +590,9 @@ mod benchmarks { for i in 0..r { if let Some(value) = ReferendumInfoOf::::get(i) { match value { - ReferendumInfo::Finished { .. } => - return Err("Referendum has been finished".into()), + ReferendumInfo::Finished { .. } => { + return Err("Referendum has been finished".into()) + }, ReferendumInfo::Ongoing(_) => (), } } diff --git a/bizinikiwi/pezframe/democracy/src/lib.rs b/bizinikiwi/pezframe/democracy/src/lib.rs index a814af4e..edab0e41 100644 --- a/bizinikiwi/pezframe/democracy/src/lib.rs +++ b/bizinikiwi/pezframe/democracy/src/lib.rs @@ -1670,8 +1670,8 @@ impl Pezpallet { // of unbaked referendum is bounded by this number. In case those number have changed in a // runtime upgrade the formula should be adjusted but the bound should still be sensible. LowestUnbaked::::mutate(|ref_index| { - while *ref_index < last && - ReferendumInfoOf::::get(*ref_index) + while *ref_index < last + && ReferendumInfoOf::::get(*ref_index) .map_or(true, |info| matches!(info, ReferendumInfo::Finished { .. })) { *ref_index += 1 diff --git a/bizinikiwi/pezframe/democracy/src/migrations/unlock_and_unreserve_all_funds.rs b/bizinikiwi/pezframe/democracy/src/migrations/unlock_and_unreserve_all_funds.rs index 059810d0..8072bbac 100644 --- a/bizinikiwi/pezframe/democracy/src/migrations/unlock_and_unreserve_all_funds.rs +++ b/bizinikiwi/pezframe/democracy/src/migrations/unlock_and_unreserve_all_funds.rs @@ -192,8 +192,8 @@ where let bugged_deposits = all_accounts .iter() .filter(|account| { - account_deposits.get(&account).unwrap_or(&Zero::zero()) > - account_reserved_before.get(&account).unwrap_or(&Zero::zero()) + account_deposits.get(&account).unwrap_or(&Zero::zero()) + > account_reserved_before.get(&account).unwrap_or(&Zero::zero()) }) .count(); diff --git a/bizinikiwi/pezframe/democracy/src/migrations/v1.rs b/bizinikiwi/pezframe/democracy/src/migrations/v1.rs index 1d19454e..12f642a8 100644 --- a/bizinikiwi/pezframe/democracy/src/migrations/v1.rs +++ b/bizinikiwi/pezframe/democracy/src/migrations/v1.rs @@ -92,16 +92,18 @@ pub mod v1 { weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); log::info!(target: TARGET, "migrating referendum #{:?}", &index); Some(match old { - ReferendumInfo::Ongoing(status) => + ReferendumInfo::Ongoing(status) => { ReferendumInfo::Ongoing(ReferendumStatus { end: status.end, proposal: Bounded::from_legacy_hash(status.proposal), threshold: status.threshold, delay: status.delay, tally: status.tally, - }), - ReferendumInfo::Finished { approved, end } => - ReferendumInfo::Finished { approved, end }, + }) + }, + ReferendumInfo::Finished { approved, end } => { + ReferendumInfo::Finished { approved, end } + }, }) }, ); diff --git a/bizinikiwi/pezframe/democracy/src/vote.rs b/bizinikiwi/pezframe/democracy/src/vote.rs index 4ca2e18d..154ea2fa 100644 --- a/bizinikiwi/pezframe/democracy/src/vote.rs +++ b/bizinikiwi/pezframe/democracy/src/vote.rs @@ -98,8 +98,9 @@ impl AccountVote { pub fn locked_if(self, approved: bool) -> Option<(u32, Balance)> { // winning side: can only be removed after the lock period ends. match self { - AccountVote::Standard { vote, balance } if vote.aye == approved => - Some((vote.conviction.lock_periods(), balance)), + AccountVote::Standard { vote, balance } if vote.aye == approved => { + Some((vote.conviction.lock_periods(), balance)) + }, _ => None, } } @@ -215,8 +216,9 @@ impl< /// The amount of this account's balance that must currently be locked due to voting. pub fn locked_balance(&self) -> Balance { match self { - Voting::Direct { votes, prior, .. } => - votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i)), + Voting::Direct { votes, prior, .. } => { + votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i)) + }, Voting::Delegating { balance, prior, .. } => *balance.max(&prior.locked()), } } diff --git a/bizinikiwi/pezframe/democracy/src/vote_threshold.rs b/bizinikiwi/pezframe/democracy/src/vote_threshold.rs index 1438bcc6..f8baa844 100644 --- a/bizinikiwi/pezframe/democracy/src/vote_threshold.rs +++ b/bizinikiwi/pezframe/democracy/src/vote_threshold.rs @@ -107,10 +107,12 @@ impl< return false; } match *self { - VoteThreshold::SuperMajorityApprove => - compare_rationals(tally.nays, sqrt_voters, tally.ayes, sqrt_electorate), - VoteThreshold::SuperMajorityAgainst => - compare_rationals(tally.nays, sqrt_electorate, tally.ayes, sqrt_voters), + VoteThreshold::SuperMajorityApprove => { + compare_rationals(tally.nays, sqrt_voters, tally.ayes, sqrt_electorate) + }, + VoteThreshold::SuperMajorityAgainst => { + compare_rationals(tally.nays, sqrt_electorate, tally.ayes, sqrt_voters) + }, VoteThreshold::SimpleMajority => tally.ayes > tally.nays, } } diff --git a/bizinikiwi/pezframe/derivatives/src/misc.rs b/bizinikiwi/pezframe/derivatives/src/misc.rs index cd2d37f5..95a50c83 100644 --- a/bizinikiwi/pezframe/derivatives/src/misc.rs +++ b/bizinikiwi/pezframe/derivatives/src/misc.rs @@ -211,9 +211,10 @@ impl, DerivativeId { fn matches_instance(asset: &Asset) -> Result { match asset.fun { - Fungibility::NonFungible(asset_instance) => + Fungibility::NonFungible(asset_instance) => { Registry::get_derivative(&(asset.id.clone(), asset_instance)) - .map_err(|_| Error::AssetNotHandled), + .map_err(|_| Error::AssetNotHandled) + }, Fungibility::Fungible(_) => Err(Error::AssetNotHandled), } } diff --git a/bizinikiwi/pezframe/derivatives/src/mock/auto_id_nfts.rs b/bizinikiwi/pezframe/derivatives/src/mock/auto_id_nfts.rs index a189320a..c6949622 100644 --- a/bizinikiwi/pezframe/derivatives/src/mock/auto_id_nfts.rs +++ b/bizinikiwi/pezframe/derivatives/src/mock/auto_id_nfts.rs @@ -66,16 +66,18 @@ impl Update> for PredefinedIdNfts { unique_items::ItemOwner::::try_mutate(id, |owner| { match owner { - Some(current_owner) => + Some(current_owner) => { if *current_owner == check_owner { *owner = Some(*new_owner); Ok(()) } else { Err(unique_items::Error::::NoPermission .into()) - }, - None => - Err(unique_items::Error::::UnknownItem.into()), + } + }, + None => { + Err(unique_items::Error::::UnknownItem.into()) + }, } }) } diff --git a/bizinikiwi/pezframe/derivatives/src/mock/mod.rs b/bizinikiwi/pezframe/derivatives/src/mock/mod.rs index 2169d7e2..dcbc4e51 100644 --- a/bizinikiwi/pezframe/derivatives/src/mock/mod.rs +++ b/bizinikiwi/pezframe/derivatives/src/mock/mod.rs @@ -169,7 +169,9 @@ impl ContainsPair for TrustAssetsFromSiblings { match (asset_location.unpack(), origin.unpack()) { ((1, [Teyrchain(asset_para_id), ..]), (1, [Teyrchain(origin_para_id)])) if asset_para_id == origin_para_id => - true, + { + true + }, _ => false, } } @@ -210,8 +212,9 @@ pub struct SiblingAssetToReserveLocationConvert; impl ConvertLocation for SiblingAssetToReserveLocationConvert { fn convert_location(location: &Location) -> Option { match location.unpack() { - (1, [Teyrchain(para_id), ..]) => - LocationToAccountId::convert_location(&Location::new(1, Teyrchain(*para_id))), + (1, [Teyrchain(para_id), ..]) => { + LocationToAccountId::convert_location(&Location::new(1, Teyrchain(*para_id))) + }, _ => None, } } diff --git a/bizinikiwi/pezframe/election-provider-multi-block/src/lib.rs b/bizinikiwi/pezframe/election-provider-multi-block/src/lib.rs index ebd4c0c1..5dcc04f7 100644 --- a/bizinikiwi/pezframe/election-provider-multi-block/src/lib.rs +++ b/bizinikiwi/pezframe/election-provider-multi-block/src/lib.rs @@ -732,8 +732,9 @@ pub mod pezpallet { let weight2 = match next_phase { Phase::Signed(_) => T::WeightInfo::on_initialize_into_signed(), - Phase::SignedValidation(_) => - T::WeightInfo::on_initialize_into_signed_validation(), + Phase::SignedValidation(_) => { + T::WeightInfo::on_initialize_into_signed_validation() + }, Phase::Unsigned(_) => T::WeightInfo::on_initialize_into_unsigned(), _ => T::WeightInfo::on_initialize_nothing(), }; @@ -777,8 +778,8 @@ pub mod pezpallet { let max_vote: usize = as NposSolution>::LIMIT; // 2. Maximum sum of [SolutionAccuracy; 16] must fit into `UpperOf`. - let maximum_chain_accuracy: Vec>> = (0.. - max_vote) + let maximum_chain_accuracy: Vec>> = (0 + ..max_vote) .map(|_| { >>::from( >::one().deconstruct(), @@ -809,8 +810,8 @@ pub mod pezpallet { "Signed phase not set correct -- both should be set or unset" ); assert!( - signed_validation.is_zero() || - signed_validation % T::Pages::get().into() == Zero::zero(), + signed_validation.is_zero() + || signed_validation % T::Pages::get().into() == Zero::zero(), "signed validation phase should be a multiple of the number of pages." ); @@ -1041,8 +1042,8 @@ pub mod pezpallet { .take(up_to_page as usize) { ensure!( - (exists ^ Self::voters(p).is_none()) && - (exists ^ Self::voters_hash(p).is_none()), + (exists ^ Self::voters(p).is_none()) + && (exists ^ Self::voters_hash(p).is_none()), "voter page existence mismatch" ); @@ -1058,8 +1059,8 @@ pub mod pezpallet { .take((T::Pages::get() - up_to_page) as usize) { ensure!( - (exists ^ Self::voters(p).is_some()) && - (exists ^ Self::voters_hash(p).is_some()), + (exists ^ Self::voters(p).is_some()) + && (exists ^ Self::voters_hash(p).is_some()), "voter page non-existence mismatch" ); } @@ -1079,17 +1080,17 @@ pub mod pezpallet { ensure!(Self::desired_targets().is_some(), "desired target mismatch"); ensure!(Self::targets_hash().is_some(), "targets hash mismatch"); ensure!( - Self::targets_decode_len().unwrap_or_default() as u32 == - T::TargetSnapshotPerBlock::get(), + Self::targets_decode_len().unwrap_or_default() as u32 + == T::TargetSnapshotPerBlock::get(), "targets decode length mismatch" ); // ensure that voter pages that should exist, indeed to exist.. for p in crate::Pezpallet::::lsp()..=crate::Pezpallet::::msp() { ensure!( - Self::voters_hash(p).is_some() && - Self::voters_decode_len(p).unwrap_or_default() as u32 == - T::VoterSnapshotPerBlock::get(), + Self::voters_hash(p).is_some() + && Self::voters_decode_len(p).unwrap_or_default() as u32 + == T::VoterSnapshotPerBlock::get(), "voter page existence mismatch" ); } @@ -1118,21 +1119,23 @@ pub mod pezpallet { Phase::Off => Self::ensure_snapshot(false, T::Pages::get()), // we will star the snapshot in the next phase. - Phase::Snapshot(p) if p == T::Pages::get() => - Self::ensure_snapshot(false, T::Pages::get()), + Phase::Snapshot(p) if p == T::Pages::get() => { + Self::ensure_snapshot(false, T::Pages::get()) + }, // we are mid voter snapshot. - Phase::Snapshot(p) if p < T::Pages::get() && p > 0 => - Self::ensure_snapshot(true, T::Pages::get() - p - 1), + Phase::Snapshot(p) if p < T::Pages::get() && p > 0 => { + Self::ensure_snapshot(true, T::Pages::get() - p - 1) + }, // we cannot check anything in this block -- we take the last page of the snapshot. Phase::Snapshot(_) => Ok(()), // full snapshot must exist in these phases. - Phase::Emergency | - Phase::Signed(_) | - Phase::SignedValidation(_) | - Phase::Export(_) | - Phase::Done | - Phase::Unsigned(_) => Self::ensure_snapshot(true, T::Pages::get()), + Phase::Emergency + | Phase::Signed(_) + | Phase::SignedValidation(_) + | Phase::Export(_) + | Phase::Done + | Phase::Unsigned(_) => Self::ensure_snapshot(true, T::Pages::get()), }?; Ok(()) @@ -1316,8 +1319,8 @@ impl Pezpallet { // check the snapshot fingerprint, if asked for. ensure!( maybe_snapshot_fingerprint - .map_or(true, |snapshot_fingerprint| Snapshot::::fingerprint() == - snapshot_fingerprint), + .map_or(true, |snapshot_fingerprint| Snapshot::::fingerprint() + == snapshot_fingerprint), CommonError::WrongFingerprint ); @@ -1676,11 +1679,11 @@ impl ElectionProvider for Pezpallet { Phase::Off => Err(()), // we're doing sth but not read. - Phase::Signed(_) | - Phase::SignedValidation(_) | - Phase::Unsigned(_) | - Phase::Snapshot(_) | - Phase::Emergency => Ok(false), + Phase::Signed(_) + | Phase::SignedValidation(_) + | Phase::Unsigned(_) + | Phase::Snapshot(_) + | Phase::Emergency => Ok(false), // we're ready Phase::Done | Phase::Export(_) => Ok(true), diff --git a/bizinikiwi/pezframe/election-provider-multi-block/src/mock/mod.rs b/bizinikiwi/pezframe/election-provider-multi-block/src/mock/mod.rs index 6f65fd6d..32877aa2 100644 --- a/bizinikiwi/pezframe/election-provider-multi-block/src/mock/mod.rs +++ b/bizinikiwi/pezframe/election-provider-multi-block/src/mock/mod.rs @@ -285,9 +285,10 @@ impl InstantElectionProvider for MockFallback { desired_targets: u32, ) -> Result, Self::Error> { match FallbackMode::get() { - FallbackModes::Continue => + FallbackModes::Continue => { crate::Continue::::instant_elect(voters, targets, desired_targets) - .map_err(|x| x.to_string()), + .map_err(|x| x.to_string()) + }, FallbackModes::Emergency => crate::InitiateEmergencyPhase::::instant_elect( voters, targets, diff --git a/bizinikiwi/pezframe/election-provider-multi-block/src/types.rs b/bizinikiwi/pezframe/election-provider-multi-block/src/types.rs index 6f042f48..022e2e8a 100644 --- a/bizinikiwi/pezframe/election-provider-multi-block/src/types.rs +++ b/bizinikiwi/pezframe/election-provider-multi-block/src/types.rs @@ -334,14 +334,17 @@ impl Phase { Self::are_we_done() } }, - Self::Snapshot(non_zero_remaining) => - Self::Snapshot(non_zero_remaining.defensive_saturating_sub(One::one())), + Self::Snapshot(non_zero_remaining) => { + Self::Snapshot(non_zero_remaining.defensive_saturating_sub(One::one())) + }, // signed phase - Self::Signed(zero) if zero == BlockNumberFor::::zero() => - Self::SignedValidation(T::SignedValidationPhase::get()), - Self::Signed(non_zero_left) => - Self::Signed(non_zero_left.defensive_saturating_sub(One::one())), + Self::Signed(zero) if zero == BlockNumberFor::::zero() => { + Self::SignedValidation(T::SignedValidationPhase::get()) + }, + Self::Signed(non_zero_left) => { + Self::Signed(non_zero_left.defensive_saturating_sub(One::one())) + }, // signed validation Self::SignedValidation(zero) @@ -353,21 +356,24 @@ impl Phase { Self::are_we_done() } }, - Self::SignedValidation(non_zero_left) => - Self::SignedValidation(non_zero_left.saturating_sub(One::one())), + Self::SignedValidation(non_zero_left) => { + Self::SignedValidation(non_zero_left.saturating_sub(One::one())) + }, // unsigned phase -- at this phase we will Self::Unsigned(zero) if zero == BlockNumberFor::::zero() => Self::are_we_done(), - Self::Unsigned(non_zero_left) => - Self::Unsigned(non_zero_left.defensive_saturating_sub(One::one())), + Self::Unsigned(non_zero_left) => { + Self::Unsigned(non_zero_left.defensive_saturating_sub(One::one())) + }, // Done. Wait for export to start. Self::Done => Self::Done, // Export Self::Export(0) => Self::Off, - Self::Export(non_zero_left) => - Self::Export(non_zero_left.defensive_saturating_sub(One::one())), + Self::Export(non_zero_left) => { + Self::Export(non_zero_left.defensive_saturating_sub(One::one())) + }, } } diff --git a/bizinikiwi/pezframe/election-provider-multi-block/src/unsigned/miner.rs b/bizinikiwi/pezframe/election-provider-multi-block/src/unsigned/miner.rs index d5f12682..29326c9a 100644 --- a/bizinikiwi/pezframe/election-provider-multi-block/src/unsigned/miner.rs +++ b/bizinikiwi/pezframe/election-provider-multi-block/src/unsigned/miner.rs @@ -925,8 +925,9 @@ impl OffchainWorkerMiner { |maybe_head: Result>, _>| { match maybe_head { Ok(Some(head)) if now < head => Err("fork."), - Ok(Some(head)) if now >= head && now <= head + threshold => - Err("recently executed."), + Ok(Some(head)) if now >= head && now <= head + threshold => { + Err("recently executed.") + }, Ok(Some(head)) if now > head + threshold => { // we can run again now. Write the new head. Ok(now) @@ -961,8 +962,9 @@ impl OffchainWorkerMiner { let storage = StorageValueRef::persistent(&Self::OFFCHAIN_CACHED_CALL); match storage.mutate::<_, (), _>(|_| Ok((call.clone(), snapshot_fingerprint))) { Ok(_) => Ok(()), - Err(MutateStorageError::ConcurrentModification(_)) => - Err(OffchainMinerError::FailedToStoreSolution), + Err(MutateStorageError::ConcurrentModification(_)) => { + Err(OffchainMinerError::FailedToStoreSolution) + }, Err(MutateStorageError::ValueFunctionFailed(_)) => { // this branch should be unreachable according to the definition of // `StorageValueRef::mutate`: that function should only ever `Err` if the closure we diff --git a/bizinikiwi/pezframe/election-provider-multi-block/src/unsigned/mod.rs b/bizinikiwi/pezframe/election-provider-multi-block/src/unsigned/mod.rs index b573467b..69d2723e 100644 --- a/bizinikiwi/pezframe/election-provider-multi-block/src/unsigned/mod.rs +++ b/bizinikiwi/pezframe/election-provider-multi-block/src/unsigned/mod.rs @@ -240,8 +240,8 @@ mod pezpallet { "weight of `submit_unsigned` is too high" ); assert!( - ::MinerPages::get() as usize <= - ::Pages::get() as usize, + ::MinerPages::get() as usize + <= ::Pages::get() as usize, "number of pages in the unsigned phase is too high" ); } diff --git a/bizinikiwi/pezframe/election-provider-multi-block/src/verifier/impls.rs b/bizinikiwi/pezframe/election-provider-multi-block/src/verifier/impls.rs index 3e435575..243938ce 100644 --- a/bizinikiwi/pezframe/election-provider-multi-block/src/verifier/impls.rs +++ b/bizinikiwi/pezframe/election-provider-multi-block/src/verifier/impls.rs @@ -341,10 +341,12 @@ pub(crate) mod pezpallet { // store the valid pages for (support, page) in supports.into_iter().zip(pages.iter()) { match Self::valid() { - ValidSolution::X => - QueuedSolutionX::::insert(Self::round(), page, support), - ValidSolution::Y => - QueuedSolutionY::::insert(Self::round(), page, support), + ValidSolution::X => { + QueuedSolutionX::::insert(Self::round(), page, support) + }, + ValidSolution::Y => { + QueuedSolutionY::::insert(Self::round(), page, support) + }, } } QueuedSolutionScore::::insert(Self::round(), score); @@ -490,8 +492,8 @@ pub(crate) mod pezpallet { // The number of existing keys in `QueuedSolutionBackings` must always match that of // the INVALID variant. ensure!( - QueuedSolutionBackings::::iter_prefix(Self::round()).count() == - Self::invalid_iter().count(), + QueuedSolutionBackings::::iter_prefix(Self::round()).count() + == Self::invalid_iter().count(), "incorrect number of backings pages", ); diff --git a/bizinikiwi/pezframe/election-provider-multi-phase/src/lib.rs b/bizinikiwi/pezframe/election-provider-multi-phase/src/lib.rs index 3ac1c19b..7ae52815 100644 --- a/bizinikiwi/pezframe/election-provider-multi-phase/src/lib.rs +++ b/bizinikiwi/pezframe/election-provider-multi-phase/src/lib.rs @@ -1769,7 +1769,7 @@ impl Pezpallet { match SignedSubmissionNextIndex::::get() { 0 => Ok(()), - next => + next => { if SignedSubmissionsMap::::get(next).is_some() { return Err( "The next submissions index should not be in the submissions maps already" @@ -1777,7 +1777,8 @@ impl Pezpallet { ); } else { Ok(()) - }, + } + }, } } @@ -1786,12 +1787,13 @@ impl Pezpallet { fn try_state_phase_off() -> Result<(), TryRuntimeError> { match CurrentPhase::::get().is_off() { false => Ok(()), - true => + true => { if Snapshot::::get().is_some() { Err("Snapshot must be none when in Phase::Off".into()) } else { Ok(()) - }, + } + }, } } } @@ -2749,8 +2751,8 @@ mod tests { let mut active = 1; while weight_with(active) - .all_lte(::BlockWeights::get().max_block) || - active == all_voters + .all_lte(::BlockWeights::get().max_block) + || active == all_voters { active += 1; } diff --git a/bizinikiwi/pezframe/election-provider-multi-phase/src/mock.rs b/bizinikiwi/pezframe/election-provider-multi-phase/src/mock.rs index 9b8c8607..0581db33 100644 --- a/bizinikiwi/pezframe/election-provider-multi-phase/src/mock.rs +++ b/bizinikiwi/pezframe/election-provider-multi-phase/src/mock.rs @@ -400,10 +400,12 @@ impl MinerConfig for Runtime { (10 as u64).saturating_add((5 as u64).saturating_mul(a as u64)), 0, ), - MockedWeightInfo::Complex => - Weight::from_parts((0 * v + 0 * t + 1000 * a + 0 * d) as u64, 0), - MockedWeightInfo::Real => - <() as multi_phase::weights::WeightInfo>::feasibility_check(v, t, a, d), + MockedWeightInfo::Complex => { + Weight::from_parts((0 * v + 0 * t + 1000 * a + 0 * d) as u64, 0) + }, + MockedWeightInfo::Real => { + <() as multi_phase::weights::WeightInfo>::feasibility_check(v, t, a, d) + }, } } } @@ -494,8 +496,8 @@ impl ElectionDataProvider for StakingMock { let targets = Targets::get(); - if !DataProviderAllowBadData::get() && - bounds.count.map_or(false, |max_len| targets.len() > max_len.0 as usize) + if !DataProviderAllowBadData::get() + && bounds.count.map_or(false, |max_len| targets.len() > max_len.0 as usize) { return Err("Targets too big"); } diff --git a/bizinikiwi/pezframe/election-provider-multi-phase/src/unsigned.rs b/bizinikiwi/pezframe/election-provider-multi-phase/src/unsigned.rs index 65530b57..cd0e46b5 100644 --- a/bizinikiwi/pezframe/election-provider-multi-phase/src/unsigned.rs +++ b/bizinikiwi/pezframe/election-provider-multi-phase/src/unsigned.rs @@ -152,8 +152,9 @@ fn save_solution(call: &Call) -> Result<(), MinerError> { let storage = StorageValueRef::persistent(OFFCHAIN_CACHED_CALL); match storage.mutate::<_, (), _>(|_| Ok(call.clone())) { Ok(_) => Ok(()), - Err(MutateStorageError::ConcurrentModification(_)) => - Err(MinerError::FailedToStoreSolution), + Err(MutateStorageError::ConcurrentModification(_)) => { + Err(MinerError::FailedToStoreSolution) + }, Err(MutateStorageError::ValueFunctionFailed(_)) => { // this branch should be unreachable according to the definition of // `StorageValueRef::mutate`: that function should only ever `Err` if the closure we @@ -354,8 +355,9 @@ impl>> Pezpallet { |maybe_head: Result>, _>| { match maybe_head { Ok(Some(head)) if now < head => Err("fork."), - Ok(Some(head)) if now >= head && now <= head + threshold => - Err("recently executed."), + Ok(Some(head)) if now >= head && now <= head + threshold => { + Err("recently executed.") + }, Ok(Some(head)) if now > head + threshold => { // we can run again now. Write the new head. Ok(now) @@ -372,8 +374,9 @@ impl>> Pezpallet { // all good Ok(_) => Ok(()), // failed to write. - Err(MutateStorageError::ConcurrentModification(_)) => - Err(MinerError::Lock("failed to write to offchain db (concurrent modification).")), + Err(MutateStorageError::ConcurrentModification(_)) => { + Err(MinerError::Lock("failed to write to offchain db (concurrent modification).")) + }, // fork etc. Err(MutateStorageError::ValueFunctionFailed(why)) => Err(MinerError::Lock(why)), } @@ -400,8 +403,8 @@ impl>> Pezpallet { // ensure correct number of winners. ensure!( - DesiredTargets::::get().unwrap_or_default() == - raw_solution.solution.unique_targets().len() as u32, + DesiredTargets::::get().unwrap_or_default() + == raw_solution.solution.unique_targets().len() as u32, Error::::PreDispatchWrongWinnerCount, ); @@ -669,8 +672,8 @@ impl Miner { high = test; } } - let maximum_allowed_voters = if low < assignments.len() && - encoded_size_of(&assignments[..low + 1])? <= max_allowed_length + let maximum_allowed_voters = if low < assignments.len() + && encoded_size_of(&assignments[..low + 1])? <= max_allowed_length { low + 1 } else { @@ -682,8 +685,8 @@ impl Miner { encoded_size_of(&assignments[..maximum_allowed_voters]).unwrap() <= max_allowed_length ); debug_assert!(if maximum_allowed_voters < assignments.len() { - encoded_size_of(&assignments[..maximum_allowed_voters + 1]).unwrap() > - max_allowed_length + encoded_size_of(&assignments[..maximum_allowed_voters + 1]).unwrap() + > max_allowed_length } else { true }); diff --git a/bizinikiwi/pezframe/election-provider-support/src/bounds.rs b/bizinikiwi/pezframe/election-provider-support/src/bounds.rs index 14c8aea7..4a6a4f0b 100644 --- a/bizinikiwi/pezframe/election-provider-support/src/bounds.rs +++ b/bizinikiwi/pezframe/election-provider-support/src/bounds.rs @@ -151,8 +151,8 @@ impl DataProviderBounds { /// Returns true if `given_size` or `given_count` exhausts `self.size` or `self_count`, /// respectively. pub fn exhausted(self, given_size: Option, given_count: Option) -> bool { - self.count_exhausted(given_count.unwrap_or(CountBound::zero())) || - self.size_exhausted(given_size.unwrap_or(SizeBound::zero())) + self.count_exhausted(given_count.unwrap_or(CountBound::zero())) + || self.size_exhausted(given_size.unwrap_or(SizeBound::zero())) } /// Ensures the given encode-able slice meets both the length and count bounds. diff --git a/bizinikiwi/pezframe/elections-phragmen/src/lib.rs b/bizinikiwi/pezframe/elections-phragmen/src/lib.rs index 78f568ec..8ce30254 100644 --- a/bizinikiwi/pezframe/elections-phragmen/src/lib.rs +++ b/bizinikiwi/pezframe/elections-phragmen/src/lib.rs @@ -311,8 +311,8 @@ pub mod pezpallet { ); let to_seconds = |w: &Weight| { - w.ref_time() as f32 / - pezframe_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND as f32 + w.ref_time() as f32 + / pezframe_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND as f32 }; log::debug!( @@ -1099,8 +1099,8 @@ impl Pezpallet { // All candidates/members/runners-up who are no longer retaining a position as a // seat holder will lose their bond. candidates_and_deposit.iter().for_each(|(c, d)| { - if new_members_ids_sorted.binary_search(c).is_err() && - new_runners_up_ids_sorted.binary_search(c).is_err() + if new_members_ids_sorted.binary_search(c).is_err() + && new_runners_up_ids_sorted.binary_search(c).is_err() { let (imbalance, _) = T::Currency::slash_reserved(c, *d); T::LoserCandidate::on_unbalanced(imbalance); @@ -1268,11 +1268,12 @@ impl Pezpallet { // - Members and candidates sets are disjoint; // - Members and runners-ups sets are disjoint. fn try_state_members_disjoint() -> Result<(), TryRuntimeError> { - match Self::intersects(&Pezpallet::::members_ids(), &Self::candidates_ids()) && - Self::intersects(&Pezpallet::::members_ids(), &Self::runners_up_ids()) + match Self::intersects(&Pezpallet::::members_ids(), &Self::candidates_ids()) + && Self::intersects(&Pezpallet::::members_ids(), &Self::runners_up_ids()) { - true => - Err("Members set should be disjoint from candidates and runners-up sets".into()), + true => { + Err("Members set should be disjoint from candidates and runners-up sets".into()) + }, false => Ok(()), } } diff --git a/bizinikiwi/pezframe/elections-phragmen/src/migrations/unlock_and_unreserve_all_funds.rs b/bizinikiwi/pezframe/elections-phragmen/src/migrations/unlock_and_unreserve_all_funds.rs index 844824ce..0190ea3a 100644 --- a/bizinikiwi/pezframe/elections-phragmen/src/migrations/unlock_and_unreserve_all_funds.rs +++ b/bizinikiwi/pezframe/elections-phragmen/src/migrations/unlock_and_unreserve_all_funds.rs @@ -211,8 +211,8 @@ where let bugged_deposits = all_accounts .iter() .filter(|account| { - account_deposited_sums.get(&account).unwrap_or(&Zero::zero()) > - account_reserved_before.get(&account).unwrap_or(&Zero::zero()) + account_deposited_sums.get(&account).unwrap_or(&Zero::zero()) + > account_reserved_before.get(&account).unwrap_or(&Zero::zero()) }) .count(); diff --git a/bizinikiwi/pezframe/examples/authorization-tx-extension/src/mock.rs b/bizinikiwi/pezframe/examples/authorization-tx-extension/src/mock.rs index 6be6d0f7..0e8dab16 100644 --- a/bizinikiwi/pezframe/examples/authorization-tx-extension/src/mock.rs +++ b/bizinikiwi/pezframe/examples/authorization-tx-extension/src/mock.rs @@ -99,8 +99,9 @@ mod example_runtime { fn try_origin(o: RuntimeOrigin) -> Result { match o.clone().into() { - Ok(pezpallet_coownership::Origin::::Coowners(first, second)) => - Ok((first, second)), + Ok(pezpallet_coownership::Origin::::Coowners(first, second)) => { + Ok((first, second)) + }, _ => Err(o), } } diff --git a/bizinikiwi/pezframe/examples/multi-block-migrations/src/migrations/v1/tests.rs b/bizinikiwi/pezframe/examples/multi-block-migrations/src/migrations/v1/tests.rs index 089f8583..c8104161 100644 --- a/bizinikiwi/pezframe/examples/multi-block-migrations/src/migrations/v1/tests.rs +++ b/bizinikiwi/pezframe/examples/multi-block-migrations/src/migrations/v1/tests.rs @@ -41,9 +41,9 @@ fn lazy_migration_works() { } // Give it enough weight do do exactly 16 iterations: - let limit = ::WeightInfo::progress_mbms_none() + - pezpallet_migrations::Pezpallet::::exec_migration_max_weight() + - weights::BizinikiwiWeight::::step() * 16; + let limit = ::WeightInfo::progress_mbms_none() + + pezpallet_migrations::Pezpallet::::exec_migration_max_weight() + + weights::BizinikiwiWeight::::step() * 16; MigratorServiceWeight::set(&limit); System::set_block_number(1); diff --git a/bizinikiwi/pezframe/examples/offchain-worker/src/lib.rs b/bizinikiwi/pezframe/examples/offchain-worker/src/lib.rs index 960aa678..65533dda 100644 --- a/bizinikiwi/pezframe/examples/offchain-worker/src/lib.rs +++ b/bizinikiwi/pezframe/examples/offchain-worker/src/lib.rs @@ -207,10 +207,12 @@ pub mod pezpallet { let should_send = Self::choose_transaction_type(block_number); let res = match should_send { TransactionType::Signed => Self::fetch_price_and_send_signed(), - TransactionType::UnsignedForAny => - Self::fetch_price_and_send_unsigned_for_any_account(block_number), - TransactionType::UnsignedForAll => - Self::fetch_price_and_send_unsigned_for_all_accounts(block_number), + TransactionType::UnsignedForAny => { + Self::fetch_price_and_send_unsigned_for_any_account(block_number) + }, + TransactionType::UnsignedForAll => { + Self::fetch_price_and_send_unsigned_for_all_accounts(block_number) + }, TransactionType::Raw => Self::fetch_price_and_send_raw_unsigned(block_number), TransactionType::None => Ok(()), }; @@ -403,8 +405,9 @@ impl Pezpallet { match last_send { // If we already have a value in storage and the block number is recent enough // we avoid sending another transaction at this time. - Ok(Some(block)) if block_number < block + T::GracePeriod::get() => - Err(RECENTLY_SENT), + Ok(Some(block)) if block_number < block + T::GracePeriod::get() => { + Err(RECENTLY_SENT) + }, // In every other case we attempt to acquire the lock and send a transaction. _ => Ok(block_number), } diff --git a/bizinikiwi/pezframe/executive/src/lib.rs b/bizinikiwi/pezframe/executive/src/lib.rs index 4ece6101..4c582588 100644 --- a/bizinikiwi/pezframe/executive/src/lib.rs +++ b/bizinikiwi/pezframe/executive/src/lib.rs @@ -687,8 +687,8 @@ where // Check that `parent_hash` is correct. let n = *header.number(); assert!( - n > BlockNumberFor::::zero() && - >::block_hash( + n > BlockNumberFor::::zero() + && >::block_hash( n - BlockNumberFor::::one() ) == *header.parent_hash(), "Parent hash should be valid.", diff --git a/bizinikiwi/pezframe/executive/src/tests.rs b/bizinikiwi/pezframe/executive/src/tests.rs index 13fd97e6..857c9051 100644 --- a/bizinikiwi/pezframe/executive/src/tests.rs +++ b/bizinikiwi/pezframe/executive/src/tests.rs @@ -270,9 +270,9 @@ mod custom2 { // Inherent call is accepted for being dispatched fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> { match call { - Call::allowed_unsigned { .. } | - Call::optional_inherent { .. } | - Call::inherent { .. } => Ok(()), + Call::allowed_unsigned { .. } + | Call::optional_inherent { .. } + | Call::inherent { .. } => Ok(()), _ => Err(UnknownTransaction::NoUnsignedValidator.into()), } } @@ -607,8 +607,8 @@ fn balance_transfer_dispatch_works() { .assimilate_storage(&mut t) .unwrap(); let xt = UncheckedXt::new_signed(call_transfer(2, 69), 1, 1.into(), tx_ext(0, 0)); - let weight = xt.get_dispatch_info().total_weight() + - ::BlockWeights::get() + let weight = xt.get_dispatch_info().total_weight() + + ::BlockWeights::get() .get(DispatchClass::Normal) .base_extrinsic; let fee: Balance = @@ -786,8 +786,8 @@ fn block_weight_limit_enforced() { // + extension weight // + extrinsic len Weight::from_parts( - (transfer_weight.ref_time() + extension_weight.ref_time() + 5) * - (nonce + 1), + (transfer_weight.ref_time() + extension_weight.ref_time() + 5) + * (nonce + 1), (nonce + 1) * encoded_len ) + base_block_weight, ); @@ -828,8 +828,8 @@ fn block_weight_and_size_is_stored_per_tx() { let mut t = new_test_ext(2); t.execute_with(|| { // Block execution weight + on_initialize weight from custom module - let base_block_weight = Weight::from_parts(175, 0) + - ::BlockWeights::get().base_block; + let base_block_weight = Weight::from_parts(175, 0) + + ::BlockWeights::get().base_block; Executive::initialize_block(&Header::new_from_number(1)); @@ -843,9 +843,9 @@ fn block_weight_and_size_is_stored_per_tx() { assert!(Executive::apply_extrinsic(x1.clone()).unwrap().is_ok()); assert!(Executive::apply_extrinsic(x2.clone()).unwrap().is_ok()); - let extrinsic_weight = transfer_weight + - extension_weight + - ::BlockWeights::get() + let extrinsic_weight = transfer_weight + + extension_weight + + ::BlockWeights::get() .get(DispatchClass::Normal) .base_extrinsic; // Check we account for all extrinsic weight and their len. diff --git a/bizinikiwi/pezframe/fast-unstake/src/lib.rs b/bizinikiwi/pezframe/fast-unstake/src/lib.rs index a7eb3916..5c56f51c 100644 --- a/bizinikiwi/pezframe/fast-unstake/src/lib.rs +++ b/bizinikiwi/pezframe/fast-unstake/src/lib.rs @@ -531,8 +531,8 @@ pub mod pezpallet { let unchecked_eras_to_check = { // get the last available `bonding_duration` eras up to current era in reverse // order. - let total_check_range = (current_era.saturating_sub(bonding_duration)..= - current_era) + let total_check_range = (current_era.saturating_sub(bonding_duration) + ..=current_era) .rev() .collect::>(); debug_assert!( @@ -608,7 +608,7 @@ pub mod pezpallet { ); match checked.try_extend(unchecked_eras_to_check.clone().into_iter()) { - Ok(_) => + Ok(_) => { if stashes.is_empty() { Self::deposit_event(Event::::BatchFinished { size: 0 }); } else { @@ -616,7 +616,8 @@ pub mod pezpallet { Self::deposit_event(Event::::BatchChecked { eras: unchecked_eras_to_check, }); - }, + } + }, Err(_) => { // don't put the head back in -- there is an internal error in the // pezpallet. diff --git a/bizinikiwi/pezframe/fast-unstake/src/mock.rs b/bizinikiwi/pezframe/fast-unstake/src/mock.rs index fabb33e8..ece5b2a1 100644 --- a/bizinikiwi/pezframe/fast-unstake/src/mock.rs +++ b/bizinikiwi/pezframe/fast-unstake/src/mock.rs @@ -209,8 +209,8 @@ impl ExtBuilder { (VALIDATOR_PREFIX..VALIDATOR_PREFIX + VALIDATORS_PER_ERA) .map(|v| { // for the sake of sanity, let's register this taker as an actual validator. - let others = (NOMINATOR_PREFIX.. - (NOMINATOR_PREFIX + NOMINATORS_PER_VALIDATOR_PER_ERA)) + let others = (NOMINATOR_PREFIX + ..(NOMINATOR_PREFIX + NOMINATORS_PER_VALIDATOR_PER_ERA)) .map(|n| IndividualExposure { who: n, value: 0 as Balance }) .collect::>(); (v, Exposure { total: 0, own: 0, others }) diff --git a/bizinikiwi/pezframe/grandpa/src/equivocation.rs b/bizinikiwi/pezframe/grandpa/src/equivocation.rs index 37011399..a21d1c84 100644 --- a/bizinikiwi/pezframe/grandpa/src/equivocation.rs +++ b/bizinikiwi/pezframe/grandpa/src/equivocation.rs @@ -213,8 +213,8 @@ where // Check that the session id for the membership proof is within the // bounds of the set id reported in the equivocation. - if session_index > set_id_session_index || - previous_set_id_session_index + if session_index > set_id_session_index + || previous_set_id_session_index .map(|previous_index| session_index <= previous_index) .unwrap_or(false) { diff --git a/bizinikiwi/pezframe/identity/src/lib.rs b/bizinikiwi/pezframe/identity/src/lib.rs index 41ac866c..3cbd52a9 100644 --- a/bizinikiwi/pezframe/identity/src/lib.rs +++ b/bizinikiwi/pezframe/identity/src/lib.rs @@ -708,14 +708,16 @@ pub mod pezpallet { let item = (reg_index, Judgement::FeePaid(registrar.fee)); match id.judgements.binary_search_by_key(®_index, |x| x.0) { - Ok(i) => + Ok(i) => { if id.judgements[i].1.is_sticky() { return Err(Error::::StickyJudgement.into()); } else { id.judgements[i] = item - }, - Err(i) => - id.judgements.try_insert(i, item).map_err(|_| Error::::TooManyRegistrars)?, + } + }, + Err(i) => { + id.judgements.try_insert(i, item).map_err(|_| Error::::TooManyRegistrars)? + }, } T::Currency::reserve(&sender, registrar.fee)?; diff --git a/bizinikiwi/pezframe/identity/src/migration.rs b/bizinikiwi/pezframe/identity/src/migration.rs index f8081d18..eab00f61 100644 --- a/bizinikiwi/pezframe/identity/src/migration.rs +++ b/bizinikiwi/pezframe/identity/src/migration.rs @@ -274,42 +274,50 @@ pub mod v2 { // At first, migrate any authorities. None => Self::authority_step(None), // Migrate any remaining authorities. - Some(MigrationState::Authority(maybe_last_authority)) => - Self::authority_step(Some(maybe_last_authority)), + Some(MigrationState::Authority(maybe_last_authority)) => { + Self::authority_step(Some(maybe_last_authority)) + }, // After the last authority was migrated, start migrating usernames from // the former `AccountOfUsername` into `UsernameInfoOf`. Some(MigrationState::FinishedAuthorities) => Self::username_step(None), // Keep migrating usernames. - Some(MigrationState::Username(maybe_last_username)) => - Self::username_step(Some(maybe_last_username)), + Some(MigrationState::Username(maybe_last_username)) => { + Self::username_step(Some(maybe_last_username)) + }, // After the last username was migrated, start migrating all identities in // `IdentityOf`, which currently hold the primary username of the owner account // as well as any associated identity. Accounts which set a username but not an // identity also have a zero deposit identity stored, which will be removed. Some(MigrationState::FinishedUsernames) => Self::identity_step(None), // Keep migrating identities. - Some(MigrationState::Identity(last_key)) => - Self::identity_step(Some(last_key.clone())), + Some(MigrationState::Identity(last_key)) => { + Self::identity_step(Some(last_key.clone())) + }, // After the last identity was migrated, start migrating usernames pending // approval from `PendingUsernames`. Some(MigrationState::FinishedIdentities) => Self::pending_username_step(None), // Keep migrating pending usernames. - Some(MigrationState::PendingUsername(last_key)) => - Self::pending_username_step(Some(last_key.clone())), + Some(MigrationState::PendingUsername(last_key)) => { + Self::pending_username_step(Some(last_key.clone())) + }, // After the last pending username was migrated, start clearing the storage // previously associated with authorities in `UsernameAuthority`. - Some(MigrationState::FinishedPendingUsernames) => - Self::cleanup_authority_step(None), + Some(MigrationState::FinishedPendingUsernames) => { + Self::cleanup_authority_step(None) + }, // Keep clearing the obsolete authority storage. - Some(MigrationState::CleanupAuthorities(maybe_last_username)) => - Self::cleanup_authority_step(Some(maybe_last_username)), + Some(MigrationState::CleanupAuthorities(maybe_last_username)) => { + Self::cleanup_authority_step(Some(maybe_last_username)) + }, // After the last obsolete authority was cleared from storage, start clearing // the storage previously associated with usernames in `AccountOfUsername`. - Some(MigrationState::FinishedCleanupAuthorities) => - Self::cleanup_username_step(None), + Some(MigrationState::FinishedCleanupAuthorities) => { + Self::cleanup_username_step(None) + }, // Keep clearing the obsolete username storage. - Some(MigrationState::CleanupUsernames(maybe_last_username)) => - Self::cleanup_username_step(Some(maybe_last_username)), + Some(MigrationState::CleanupUsernames(maybe_last_username)) => { + Self::cleanup_username_step(Some(maybe_last_username)) + }, // After the last obsolete username was cleared from storage, the migration is // done. Some(MigrationState::Finished) => { @@ -428,16 +436,19 @@ pub mod v2 { ) -> Weight { match step { MigrationState::Authority(_) => T::WeightInfo::migration_v2_authority_step(), - MigrationState::FinishedAuthorities | MigrationState::Username(_) => - T::WeightInfo::migration_v2_username_step(), - MigrationState::FinishedUsernames | MigrationState::Identity(_) => - T::WeightInfo::migration_v2_identity_step(), - MigrationState::FinishedIdentities | MigrationState::PendingUsername(_) => - T::WeightInfo::migration_v2_pending_username_step(), - MigrationState::FinishedPendingUsernames | - MigrationState::CleanupAuthorities(_) => T::WeightInfo::migration_v2_cleanup_authority_step(), - MigrationState::FinishedCleanupAuthorities | - MigrationState::CleanupUsernames(_) => T::WeightInfo::migration_v2_cleanup_username_step(), + MigrationState::FinishedAuthorities | MigrationState::Username(_) => { + T::WeightInfo::migration_v2_username_step() + }, + MigrationState::FinishedUsernames | MigrationState::Identity(_) => { + T::WeightInfo::migration_v2_identity_step() + }, + MigrationState::FinishedIdentities | MigrationState::PendingUsername(_) => { + T::WeightInfo::migration_v2_pending_username_step() + }, + MigrationState::FinishedPendingUsernames + | MigrationState::CleanupAuthorities(_) => T::WeightInfo::migration_v2_cleanup_authority_step(), + MigrationState::FinishedCleanupAuthorities + | MigrationState::CleanupUsernames(_) => T::WeightInfo::migration_v2_cleanup_username_step(), MigrationState::Finished => Weight::zero(), } } diff --git a/bizinikiwi/pezframe/identity/src/tests.rs b/bizinikiwi/pezframe/identity/src/tests.rs index 61108c1e..473dbd72 100644 --- a/bizinikiwi/pezframe/identity/src/tests.rs +++ b/bizinikiwi/pezframe/identity/src/tests.rs @@ -185,8 +185,8 @@ fn infoof_twenty() -> IdentityInfo { fn id_deposit(id: &IdentityInfo) -> u64 { let base_deposit: u64 = <::BasicDeposit as Get>::get(); - let byte_deposit: u64 = <::ByteDeposit as Get>::get() * - TryInto::::try_into(id.encoded_size()).unwrap(); + let byte_deposit: u64 = <::ByteDeposit as Get>::get() + * TryInto::::try_into(id.encoded_size()).unwrap(); base_deposit + byte_deposit } @@ -202,11 +202,11 @@ fn identity_fields_repr_works() { assert_eq!(IdentityField::Image as u64, 1 << 6); assert_eq!(IdentityField::Twitter as u64, 1 << 7); - let fields = IdentityField::Legal | - IdentityField::Web | - IdentityField::Riot | - IdentityField::PgpFingerprint | - IdentityField::Twitter; + let fields = IdentityField::Legal + | IdentityField::Web + | IdentityField::Riot + | IdentityField::PgpFingerprint + | IdentityField::Twitter; assert!(!fields.contains(IdentityField::Display)); assert!(fields.contains(IdentityField::Legal)); diff --git a/bizinikiwi/pezframe/identity/src/types.rs b/bizinikiwi/pezframe/identity/src/types.rs index 01586c09..8f4c5fd8 100644 --- a/bizinikiwi/pezframe/identity/src/types.rs +++ b/bizinikiwi/pezframe/identity/src/types.rs @@ -293,8 +293,9 @@ impl< > Registration { pub(crate) fn total_deposit(&self) -> Balance { - self.deposit + - self.judgements + self.deposit + + self + .judgements .iter() .map(|(_, ref j)| if let Judgement::FeePaid(fee) = j { *fee } else { Zero::zero() }) .fold(Zero::zero(), |a, i| a + i) diff --git a/bizinikiwi/pezframe/im-online/src/lib.rs b/bizinikiwi/pezframe/im-online/src/lib.rs index 6aa8168e..ba47098c 100644 --- a/bizinikiwi/pezframe/im-online/src/lib.rs +++ b/bizinikiwi/pezframe/im-online/src/lib.rs @@ -532,8 +532,8 @@ impl Pezpallet { fn is_online_aux(authority_index: AuthIndex, authority: &ValidatorId) -> bool { let current_session = T::ValidatorSet::session_index(); - ReceivedHeartbeats::::contains_key(current_session, authority_index) || - AuthoredBlocks::::get(current_session, authority) != 0 + ReceivedHeartbeats::::contains_key(current_session, authority_index) + || AuthoredBlocks::::get(current_session, authority) != 0 } /// Returns `true` if a heartbeat has been received for the authority at `authority_index` in @@ -583,8 +583,8 @@ impl Pezpallet { // haven't sent an heartbeat yet we'll send one unconditionally. the idea is to prevent // all nodes from sending the heartbeats at the same block and causing a temporary (but // deterministic) spike in transactions. - progress >= START_HEARTBEAT_FINAL_PERIOD || - progress >= START_HEARTBEAT_RANDOM_PERIOD && random_choice(progress) + progress >= START_HEARTBEAT_FINAL_PERIOD + || progress >= START_HEARTBEAT_RANDOM_PERIOD && random_choice(progress) } else { // otherwise we fallback to using the block number calculated at the beginning // of the session that should roughly correspond to the middle of the session @@ -695,8 +695,9 @@ impl Pezpallet { // we will re-send it. match status { // we are still waiting for inclusion. - Ok(Some(status)) if status.is_recent(session_index, now) => - Err(OffchainErr::WaitingForInclusion(status.sent_at)), + Ok(Some(status)) if status.is_recent(session_index, now) => { + Err(OffchainErr::WaitingForInclusion(status.sent_at)) + }, // attempt to set new status _ => Ok(HeartbeatStatus { session_index, sent_at: now }), } diff --git a/bizinikiwi/pezframe/im-online/src/tests.rs b/bizinikiwi/pezframe/im-online/src/tests.rs index 3d17add3..3e0aadee 100644 --- a/bizinikiwi/pezframe/im-online/src/tests.rs +++ b/bizinikiwi/pezframe/im-online/src/tests.rs @@ -125,8 +125,9 @@ fn heartbeat( signature: signature.clone(), }) .map_err(|e| match e { - TransactionValidityError::Invalid(InvalidTransaction::Custom(INVALID_VALIDATORS_LEN)) => - "invalid validators len", + TransactionValidityError::Invalid(InvalidTransaction::Custom(INVALID_VALIDATORS_LEN)) => { + "invalid validators len" + }, e @ _ => <&'static str>::from(e), })?; ImOnline::heartbeat(RuntimeOrigin::none(), heartbeat, signature) @@ -226,8 +227,9 @@ fn should_generate_heartbeats() { // check stuff about the transaction. let ex: Extrinsic = Decode::decode(&mut &*transaction).unwrap(); let heartbeat = match ex.function { - crate::mock::RuntimeCall::ImOnline(crate::Call::heartbeat { heartbeat, .. }) => - heartbeat, + crate::mock::RuntimeCall::ImOnline(crate::Call::heartbeat { heartbeat, .. }) => { + heartbeat + }, e => panic!("Unexpected call: {:?}", e), }; @@ -340,8 +342,9 @@ fn should_not_send_a_report_if_already_online() { // check stuff about the transaction. let ex: Extrinsic = Decode::decode(&mut &*transaction).unwrap(); let heartbeat = match ex.function { - crate::mock::RuntimeCall::ImOnline(crate::Call::heartbeat { heartbeat, .. }) => - heartbeat, + crate::mock::RuntimeCall::ImOnline(crate::Call::heartbeat { heartbeat, .. }) => { + heartbeat + }, e => panic!("Unexpected call: {:?}", e), }; diff --git a/bizinikiwi/pezframe/merkle-mountain-range/src/lib.rs b/bizinikiwi/pezframe/merkle-mountain-range/src/lib.rs index da873d00..e205e665 100644 --- a/bizinikiwi/pezframe/merkle-mountain-range/src/lib.rs +++ b/bizinikiwi/pezframe/merkle-mountain-range/src/lib.rs @@ -405,9 +405,9 @@ impl, I: 'static> Pezpallet { leaves: Vec>, proof: LeafProof>, ) -> Result<(), Error> { - if proof.leaf_count > NumberOfLeaves::::get() || - proof.leaf_count == 0 || - proof.items.len().saturating_add(leaves.len()) as u64 > proof.leaf_count + if proof.leaf_count > NumberOfLeaves::::get() + || proof.leaf_count == 0 + || proof.items.len().saturating_add(leaves.len()) as u64 > proof.leaf_count { return Err( Error::Verify.log_debug("The proof has incorrect number of leaves or proof items.") diff --git a/bizinikiwi/pezframe/message-queue/src/lib.rs b/bizinikiwi/pezframe/message-queue/src/lib.rs index bba0b706..25241304 100644 --- a/bizinikiwi/pezframe/message-queue/src/lib.rs +++ b/bizinikiwi/pezframe/message-queue/src/lib.rs @@ -989,9 +989,9 @@ impl Pezpallet { if let (Some(service_weight), Some(on_idle)) = (T::ServiceWeight::get(), T::IdleMaxServiceWeight::get()) { - if !(service_weight.all_gt(on_idle) || - on_idle.all_gt(service_weight) || - service_weight == on_idle) + if !(service_weight.all_gt(on_idle) + || on_idle.all_gt(service_weight) + || service_weight == on_idle) { return Err("One of `ServiceWeight` or `IdleMaxServiceWeight` needs to be `all_gt` or both need to be equal.".into()); } @@ -1096,8 +1096,8 @@ impl Pezpallet { page.peek_index(index.into() as usize).ok_or(Error::::NoMessage)?; let payload_len = payload.len() as u64; ensure!( - page_index < book_state.begin || - (page_index == book_state.begin && pos < page.first.into() as usize), + page_index < book_state.begin + || (page_index == book_state.begin && pos < page.first.into() as usize), Error::::Queued ); ensure!(!is_processed, Error::::AlreadyProcessed); @@ -1114,8 +1114,9 @@ impl Pezpallet { // additional overweight event being deposited. ) { Overweight | InsufficientWeight => Err(Error::::InsufficientWeight), - StackLimitReached | Unprocessable { permanent: false } => - Err(Error::::TemporarilyUnprocessable), + StackLimitReached | Unprocessable { permanent: false } => { + Err(Error::::TemporarilyUnprocessable) + }, Unprocessable { permanent: true } | Processed => { page.note_processed_at_pos(pos); book_state.message_count.saturating_dec(); @@ -1657,7 +1658,7 @@ impl Pezpallet { let (progressed, n) = Self::service_queue(next.clone(), &mut weight, overweight_limit); next = match n { - Some(n) => + Some(n) => { if !progressed { if last_no_progress == Some(n.clone()) { break; @@ -1669,7 +1670,8 @@ impl Pezpallet { } else { last_no_progress = None; n - }, + } + }, None => break, } } @@ -1780,8 +1782,9 @@ impl ServiceQueues for Pezpallet { Error::::InsufficientWeight => ExecuteOverweightError::InsufficientWeight, Error::::AlreadyProcessed => ExecuteOverweightError::AlreadyProcessed, Error::::QueuePaused => ExecuteOverweightError::QueuePaused, - Error::::NoPage | Error::::NoMessage | Error::::Queued => - ExecuteOverweightError::NotFound, + Error::::NoPage | Error::::NoMessage | Error::::Queued => { + ExecuteOverweightError::NotFound + }, Error::::RecursiveDisallowed => ExecuteOverweightError::RecursiveDisallowed, _ => ExecuteOverweightError::Other, }) diff --git a/bizinikiwi/pezframe/message-queue/src/tests.rs b/bizinikiwi/pezframe/message-queue/src/tests.rs index e6416851..6f1e6846 100644 --- a/bizinikiwi/pezframe/message-queue/src/tests.rs +++ b/bizinikiwi/pezframe/message-queue/src/tests.rs @@ -876,8 +876,8 @@ fn page_try_append_message_basic_works() { msgs += 1; } } - let expected_msgs = (::HeapSize::get()) / - (ItemHeader::<::Size>::max_encoded_len() as u32 + 4); + let expected_msgs = (::HeapSize::get()) + / (ItemHeader::<::Size>::max_encoded_len() as u32 + 4); assert_eq!(expected_msgs, msgs, "Wrong number of messages"); assert_eq!(page.remaining, msgs); assert_eq!(page.remaining_size, msgs * 4); @@ -1441,8 +1441,8 @@ fn ready_ring_knit_and_unknit_works() { #[test] fn enqueue_message_works() { use MessageOrigin::*; - let max_msg_per_page = ::HeapSize::get() as u64 / - (ItemHeader::<::Size>::max_encoded_len() as u64 + 1); + let max_msg_per_page = ::HeapSize::get() as u64 + / (ItemHeader::<::Size>::max_encoded_len() as u64 + 1); build_and_execute::(|| { // Enqueue messages which should fill three pages. @@ -1471,8 +1471,8 @@ fn enqueue_message_works() { #[test] fn enqueue_messages_works() { use MessageOrigin::*; - let max_msg_per_page = ::HeapSize::get() as u64 / - (ItemHeader::<::Size>::max_encoded_len() as u64 + 1); + let max_msg_per_page = ::HeapSize::get() as u64 + / (ItemHeader::<::Size>::max_encoded_len() as u64 + 1); build_and_execute::(|| { // Enqueue messages which should fill three pages. diff --git a/bizinikiwi/pezframe/multi-asset-bounties/src/benchmarking.rs b/bizinikiwi/pezframe/multi-asset-bounties/src/benchmarking.rs index 07fd423f..b3de0a2b 100644 --- a/bizinikiwi/pezframe/multi-asset-bounties/src/benchmarking.rs +++ b/bizinikiwi/pezframe/multi-asset-bounties/src/benchmarking.rs @@ -272,16 +272,19 @@ pub fn set_status, I: 'static>( .expect("no bounty"); let new_status = match bounty.3 { - BountyStatus::FundingAttempted { curator, .. } => - BountyStatus::FundingAttempted { payment_status: new_payment_status, curator }, - BountyStatus::RefundAttempted { curator, .. } => - BountyStatus::RefundAttempted { payment_status: new_payment_status, curator }, - BountyStatus::PayoutAttempted { curator, beneficiary, .. } => + BountyStatus::FundingAttempted { curator, .. } => { + BountyStatus::FundingAttempted { payment_status: new_payment_status, curator } + }, + BountyStatus::RefundAttempted { curator, .. } => { + BountyStatus::RefundAttempted { payment_status: new_payment_status, curator } + }, + BountyStatus::PayoutAttempted { curator, beneficiary, .. } => { BountyStatus::PayoutAttempted { payment_status: new_payment_status, curator, beneficiary, - }, + } + }, _ => return Err(BenchmarkError::Stop("unexpected bounty status")), }; diff --git a/bizinikiwi/pezframe/multi-asset-bounties/src/lib.rs b/bizinikiwi/pezframe/multi-asset-bounties/src/lib.rs index e11cbc58..bf651da3 100644 --- a/bizinikiwi/pezframe/multi-asset-bounties/src/lib.rs +++ b/bizinikiwi/pezframe/multi-asset-bounties/src/lib.rs @@ -663,8 +663,8 @@ pub mod pezpallet { Error::::InvalidValue ); ensure!( - ChildBountiesPerParent::::get(parent_bounty_id) < - T::MaxActiveChildBountyCount::get() as u32, + ChildBountiesPerParent::::get(parent_bounty_id) + < T::MaxActiveChildBountyCount::get() as u32, Error::::TooManyChildBounties, ); @@ -898,8 +898,8 @@ pub mod pezpallet { // curator can unassign the child-/bounty curator. ensure!( maybe_sender.map_or(true, |sender| { - sender == *curator || - parent_curator + sender == *curator + || parent_curator .map_or(false, |parent_curator| sender == parent_curator) }), BadOrigin @@ -1070,8 +1070,9 @@ pub mod pezpallet { Self::get_bounty_details(parent_bounty_id, child_bounty_id)?; let maybe_curator = match status { - BountyStatus::Funded { curator } | BountyStatus::Active { curator, .. } => - Some(curator), + BountyStatus::Funded { curator } | BountyStatus::Active { curator, .. } => { + Some(curator) + }, BountyStatus::CuratorUnassigned => None, _ => return Err(Error::::UnexpectedStatus.into()), }; @@ -1174,13 +1175,14 @@ pub mod pezpallet { let new_status = match new_payment_status { PaymentState::Succeeded => match (child_bounty_id, parent_curator) { - (Some(_), Some(parent_curator)) if curator == parent_curator => - BountyStatus::Active { curator }, + (Some(_), Some(parent_curator)) if curator == parent_curator => { + BountyStatus::Active { curator } + }, _ => BountyStatus::Funded { curator }, }, - PaymentState::Pending | - PaymentState::Failed | - PaymentState::Attempted { .. } => BountyStatus::FundingAttempted { + PaymentState::Pending + | PaymentState::Failed + | PaymentState::Attempted { .. } => BountyStatus::FundingAttempted { payment_status: new_payment_status, curator, }, @@ -1220,9 +1222,9 @@ pub mod pezpallet { Self::remove_bounty(parent_bounty_id, child_bounty_id, metadata); return Ok(Pays::No.into()); }, - PaymentState::Pending | - PaymentState::Failed | - PaymentState::Attempted { .. } => BountyStatus::RefundAttempted { + PaymentState::Pending + | PaymentState::Failed + | PaymentState::Attempted { .. } => BountyStatus::RefundAttempted { payment_status: new_payment_status, curator: curator.clone(), }, @@ -1256,9 +1258,9 @@ pub mod pezpallet { Self::remove_bounty(parent_bounty_id, child_bounty_id, metadata); return Ok(Pays::No.into()); }, - PaymentState::Pending | - PaymentState::Failed | - PaymentState::Attempted { .. } => BountyStatus::PayoutAttempted { + PaymentState::Pending + | PaymentState::Failed + | PaymentState::Attempted { .. } => BountyStatus::PayoutAttempted { curator: curator.clone(), beneficiary: beneficiary.clone(), payment_status: new_payment_status.clone(), @@ -1629,8 +1631,9 @@ impl, I: 'static> Pezpallet { }); Ok(PaymentState::Succeeded) }, - PaymentStatus::InProgress | PaymentStatus::Unknown => - return Err(Error::::FundingInconclusive.into()), + PaymentStatus::InProgress | PaymentStatus::Unknown => { + return Err(Error::::FundingInconclusive.into()) + }, PaymentStatus::Failure => { Self::deposit_event(Event::::PaymentFailed { index: parent_bounty_id, @@ -1697,7 +1700,9 @@ impl, I: 'static> Pezpallet { }, PaymentStatus::InProgress | PaymentStatus::Unknown => // nothing new to report - Err(Error::::RefundInconclusive.into()), + { + Err(Error::::RefundInconclusive.into()) + }, PaymentStatus::Failure => { // assume payment has failed, allow user to retry Self::deposit_event(Event::::PaymentFailed { @@ -1727,8 +1732,9 @@ impl, I: 'static> Pezpallet { let source = match child_bounty_id { None => Self::bounty_account(parent_bounty_id, asset_kind.clone())?, - Some(child_bounty_id) => - Self::child_bounty_account(parent_bounty_id, child_bounty_id, asset_kind.clone())?, + Some(child_bounty_id) => { + Self::child_bounty_account(parent_bounty_id, child_bounty_id, asset_kind.clone())? + }, }; let id = >::Paymaster::pay(&source, &beneficiary, asset_kind, payout) @@ -1771,7 +1777,9 @@ impl, I: 'static> Pezpallet { }, PaymentStatus::InProgress | PaymentStatus::Unknown => // nothing new to report - Err(Error::::PayoutInconclusive.into()), + { + Err(Error::::PayoutInconclusive.into()) + }, PaymentStatus::Failure => { // assume payment has failed, allow user to retry Self::deposit_event(Event::::PaymentFailed { diff --git a/bizinikiwi/pezframe/nfts/src/features/attributes.rs b/bizinikiwi/pezframe/nfts/src/features/attributes.rs index 7b601be1..9e3974bf 100644 --- a/bizinikiwi/pezframe/nfts/src/features/attributes.rs +++ b/bizinikiwi/pezframe/nfts/src/features/attributes.rs @@ -99,8 +99,8 @@ impl, I: 'static> Pezpallet { let mut deposit = Zero::zero(); // disabled DepositRequired setting only affects the CollectionOwner namespace - if collection_config.is_setting_enabled(CollectionSetting::DepositRequired) || - namespace != AttributeNamespace::CollectionOwner + if collection_config.is_setting_enabled(CollectionSetting::DepositRequired) + || namespace != AttributeNamespace::CollectionOwner { deposit = T::DepositPerByte::get() .saturating_mul(((key.len() + value.len()) as u32).into()) @@ -461,19 +461,22 @@ impl, I: 'static> Pezpallet { ) -> Result { let mut result = false; match namespace { - AttributeNamespace::CollectionOwner => - result = Self::has_role(&collection, &origin, CollectionRole::Admin), - AttributeNamespace::ItemOwner => + AttributeNamespace::CollectionOwner => { + result = Self::has_role(&collection, &origin, CollectionRole::Admin) + }, + AttributeNamespace::ItemOwner => { if let Some(item) = maybe_item { let item_details = Item::::get(&collection, &item).ok_or(Error::::UnknownItem)?; result = origin == &item_details.owner - }, - AttributeNamespace::Account(account_id) => + } + }, + AttributeNamespace::Account(account_id) => { if let Some(item) = maybe_item { let approvals = ItemAttributesApprovalsOf::::get(&collection, &item); result = account_id == origin && approvals.contains(&origin) - }, + } + }, _ => (), }; Ok(result) diff --git a/bizinikiwi/pezframe/nfts/src/features/metadata.rs b/bizinikiwi/pezframe/nfts/src/features/metadata.rs index 32346558..993b60f2 100644 --- a/bizinikiwi/pezframe/nfts/src/features/metadata.rs +++ b/bizinikiwi/pezframe/nfts/src/features/metadata.rs @@ -253,8 +253,8 @@ impl, I: 'static> Pezpallet { let collection_config = Self::get_collection_config(&collection)?; ensure!( - maybe_check_origin.is_none() || - collection_config.is_setting_enabled(CollectionSetting::UnlockedMetadata), + maybe_check_origin.is_none() + || collection_config.is_setting_enabled(CollectionSetting::UnlockedMetadata), Error::::LockedCollectionMetadata ); diff --git a/bizinikiwi/pezframe/nfts/src/impl_nonfungibles.rs b/bizinikiwi/pezframe/nfts/src/impl_nonfungibles.rs index 229a65a5..44c91fab 100644 --- a/bizinikiwi/pezframe/nfts/src/impl_nonfungibles.rs +++ b/bizinikiwi/pezframe/nfts/src/impl_nonfungibles.rs @@ -128,9 +128,11 @@ impl, I: 'static> Inspect<::AccountId> for Pezpa ItemConfigOf::::get(collection, item), ) { (Some(cc), Some(ic)) - if cc.is_setting_enabled(CollectionSetting::TransferableItems) && - ic.is_setting_enabled(ItemSetting::Transferable) => - true, + if cc.is_setting_enabled(CollectionSetting::TransferableItems) + && ic.is_setting_enabled(ItemSetting::Transferable) => + { + true + }, _ => false, } } diff --git a/bizinikiwi/pezframe/nfts/src/lib.rs b/bizinikiwi/pezframe/nfts/src/lib.rs index 1bc3eda6..82953320 100644 --- a/bizinikiwi/pezframe/nfts/src/lib.rs +++ b/bizinikiwi/pezframe/nfts/src/lib.rs @@ -1443,8 +1443,9 @@ pub mod pezpallet { ) -> DispatchResult { let origin = ensure_signed(origin)?; let depositor = match namespace { - AttributeNamespace::CollectionOwner => - Self::collection_owner(collection).ok_or(Error::::UnknownCollection)?, + AttributeNamespace::CollectionOwner => { + Self::collection_owner(collection).ok_or(Error::::UnknownCollection)? + }, _ => origin.clone(), }; Self::do_set_attribute(origin, collection, maybe_item, namespace, key, value, depositor) diff --git a/bizinikiwi/pezframe/nfts/src/tests.rs b/bizinikiwi/pezframe/nfts/src/tests.rs index 1c8eb39a..7143fa01 100644 --- a/bizinikiwi/pezframe/nfts/src/tests.rs +++ b/bizinikiwi/pezframe/nfts/src/tests.rs @@ -3114,9 +3114,9 @@ fn collection_locking_should_work() { let stored_config = CollectionConfigOf::::get(collection_id).unwrap(); let full_lock_config = collection_config_from_disabled_settings( - CollectionSetting::TransferableItems | - CollectionSetting::UnlockedMetadata | - CollectionSetting::UnlockedAttributes, + CollectionSetting::TransferableItems + | CollectionSetting::UnlockedMetadata + | CollectionSetting::UnlockedAttributes, ); assert_eq!(stored_config, full_lock_config); }); diff --git a/bizinikiwi/pezframe/nis/src/lib.rs b/bizinikiwi/pezframe/nis/src/lib.rs index dec3bb2e..b9a26abe 100644 --- a/bizinikiwi/pezframe/nis/src/lib.rs +++ b/bizinikiwi/pezframe/nis/src/lib.rs @@ -1071,10 +1071,10 @@ pub mod pezpallet { let expiry = now.saturating_add(T::BasePeriod::get().saturating_mul(duration.into())); let mut count = 0; - while count < max_bids && - !queue.is_empty() && - !remaining.is_zero() && - weight.check_accrue(T::WeightInfo::process_bid()) + while count < max_bids + && !queue.is_empty() + && !remaining.is_zero() + && weight.check_accrue(T::WeightInfo::process_bid()) { let bid = match queue.pop() { Some(b) => b, diff --git a/bizinikiwi/pezframe/nis/src/tests.rs b/bizinikiwi/pezframe/nis/src/tests.rs index 2edf2892..64bd413f 100644 --- a/bizinikiwi/pezframe/nis/src/tests.rs +++ b/bizinikiwi/pezframe/nis/src/tests.rs @@ -718,9 +718,9 @@ fn multiple_thaws_works_in_alternative_thaw_order() { fn enlargement_to_target_works() { new_test_ext().execute_with(|| { System::run_to_block::(2); - let w = <() as WeightInfo>::process_queues() + - <() as WeightInfo>::process_queue() + - (<() as WeightInfo>::process_bid() * 2); + let w = <() as WeightInfo>::process_queues() + + <() as WeightInfo>::process_queue() + + (<() as WeightInfo>::process_bid() * 2); super::mock::MaxIntakeWeight::set(w); assert_ok!(Nis::place_bid(signed(1), 40, 1)); assert_ok!(Nis::place_bid(signed(1), 40, 2)); diff --git a/bizinikiwi/pezframe/nomination-pools/benchmarking/src/inner.rs b/bizinikiwi/pezframe/nomination-pools/benchmarking/src/inner.rs index 702dd099..2fb6fedf 100644 --- a/bizinikiwi/pezframe/nomination-pools/benchmarking/src/inner.rs +++ b/bizinikiwi/pezframe/nomination-pools/benchmarking/src/inner.rs @@ -349,8 +349,8 @@ mod benchmarks { // commission of 50% deducted here. assert!( - T::StakeAdapter::active_stake(Pool::from(scenario.origin1)) >= - scenario.dest_weight / 2u32.into() + T::StakeAdapter::active_stake(Pool::from(scenario.origin1)) + >= scenario.dest_weight / 2u32.into() ); } @@ -989,8 +989,8 @@ mod benchmarks { assert_eq!(PoolMembers::::get(&depositor).unwrap().total_balance(), deposit_amount); // verify delegated balance. assert!( - T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) == - Some(deposit_amount), + T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) + == Some(deposit_amount), ); // ugly type conversion between balances of pezpallet staking and pools (which really are @@ -1013,8 +1013,8 @@ mod benchmarks { ); // verify delegated balance are not yet slashed. assert!( - T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) == - Some(deposit_amount), + T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) + == Some(deposit_amount), ); // Fill member's sub pools for the worst case. @@ -1049,8 +1049,8 @@ mod benchmarks { deposit_amount / 2u32.into() ); assert!( - T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) == - Some(deposit_amount / 2u32.into()), + T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) + == Some(deposit_amount / 2u32.into()), ); } @@ -1168,8 +1168,8 @@ mod benchmarks { } // verify balances once more. assert!( - T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) == - Some(deposit_amount), + T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) + == Some(deposit_amount), ); assert_eq!(PoolMembers::::get(&depositor).unwrap().total_balance(), deposit_amount); } diff --git a/bizinikiwi/pezframe/nomination-pools/fuzzer/src/call.rs b/bizinikiwi/pezframe/nomination-pools/fuzzer/src/call.rs index 5de55bcf..69114705 100644 --- a/bizinikiwi/pezframe/nomination-pools/fuzzer/src/call.rs +++ b/bizinikiwi/pezframe/nomination-pools/fuzzer/src/call.rs @@ -267,8 +267,8 @@ fn main() { } // execute sanity checks at a fixed interval, possibly on every block. - if iteration % - (std::env::var("SANITY_CHECK_INTERVAL") + if iteration + % (std::env::var("SANITY_CHECK_INTERVAL") .ok() .and_then(|x| x.parse::().ok())) .unwrap_or(1) == 0 diff --git a/bizinikiwi/pezframe/nomination-pools/src/lib.rs b/bizinikiwi/pezframe/nomination-pools/src/lib.rs index 2caa347a..2516ebb5 100644 --- a/bizinikiwi/pezframe/nomination-pools/src/lib.rs +++ b/bizinikiwi/pezframe/nomination-pools/src/lib.rs @@ -644,9 +644,10 @@ impl PoolMember { ) -> Result<(), Error> { if let Some(new_points) = self.points.checked_sub(&points_dissolved) { match self.unbonding_eras.get_mut(&unbonding_era) { - Some(already_unbonding_points) => + Some(already_unbonding_points) => { *already_unbonding_points = - already_unbonding_points.saturating_add(points_issued), + already_unbonding_points.saturating_add(points_issued) + }, None => self .unbonding_eras .try_insert(unbonding_era, points_issued) @@ -1138,8 +1139,8 @@ impl BondedPool { } fn can_nominate(&self, who: &T::AccountId) -> bool { - self.is_root(who) || - self.roles.nominator.as_ref().map_or(false, |nominator| nominator == who) + self.is_root(who) + || self.roles.nominator.as_ref().map_or(false, |nominator| nominator == who) } fn can_kick(&self, who: &T::AccountId) -> bool { @@ -1246,9 +1247,9 @@ impl BondedPool { // any unbond must comply with the balance condition: ensure!( - is_full_unbond || - balance_after_unbond >= - if is_depositor { + is_full_unbond + || balance_after_unbond + >= if is_depositor { Pezpallet::::depositor_min_bond() } else { MinJoinBond::::get() @@ -2876,8 +2877,8 @@ pub mod pezpallet { .ok_or(Error::::PoolMemberNotFound)? .active_points(); - if bonded_pool.points_to_balance(depositor_points) >= - T::StakeAdapter::minimum_nominator_bond() + if bonded_pool.points_to_balance(depositor_points) + >= T::StakeAdapter::minimum_nominator_bond() { ensure!(bonded_pool.can_nominate(&who), Error::::NotNominator); } @@ -3246,8 +3247,8 @@ pub mod pezpallet { // ensure pool exists. let bonded_pool = BondedPool::::get(pool_id).ok_or(Error::::PoolNotFound)?; ensure!( - T::StakeAdapter::pool_strategy(Pool::from(bonded_pool.bonded_account())) == - adapter::StakeStrategyType::Transfer, + T::StakeAdapter::pool_strategy(Pool::from(bonded_pool.bonded_account())) + == adapter::StakeStrategyType::Transfer, Error::::AlreadyMigrated ); @@ -3620,10 +3621,12 @@ impl Pezpallet { )?; let (points_issued, bonded) = match extra { - BondExtra::FreeBalance(amount) => - (bonded_pool.try_bond_funds(&member_account, amount, BondType::Extra)?, amount), - BondExtra::Rewards => - (bonded_pool.try_bond_funds(&member_account, claimed, BondType::Extra)?, claimed), + BondExtra::FreeBalance(amount) => { + (bonded_pool.try_bond_funds(&member_account, amount, BondType::Extra)?, amount) + }, + BondExtra::Rewards => { + (bonded_pool.try_bond_funds(&member_account, claimed, BondType::Extra)?, claimed) + }, }; bonded_pool.ok_to_be_open()?; @@ -3776,8 +3779,8 @@ impl Pezpallet { ) -> Result, DispatchError> { // only executed in tests: ensure the member account is correct. debug_assert!( - PoolMembers::::get(member_account.clone().get()).expect("member must exist") == - pool_member + PoolMembers::::get(member_account.clone().get()).expect("member must exist") + == pool_member ); let pool_account = Pezpallet::::generate_bonded_account(pool_member.pool_id); @@ -3879,8 +3882,8 @@ impl Pezpallet { for id in reward_pools { let account = Self::generate_reward_account(id); - if T::Currency::reducible_balance(&account, Preservation::Expendable, Fortitude::Polite) < - T::Currency::minimum_balance() + if T::Currency::reducible_balance(&account, Preservation::Expendable, Fortitude::Polite) + < T::Currency::minimum_balance() { log!( warn, @@ -3925,8 +3928,8 @@ impl Pezpallet { RewardPools::::iter_keys().try_for_each(|id| -> Result<(), TryRuntimeError> { // the sum of the pending rewards must be less than the leftover balance. Since the // reward math rounds down, we might accumulate some dust here. - let pending_rewards_lt_leftover_bal = RewardPool::::current_balance(id) >= - pools_members_pending_rewards.get(&id).copied().unwrap_or_default(); + let pending_rewards_lt_leftover_bal = RewardPool::::current_balance(id) + >= pools_members_pending_rewards.get(&id).copied().unwrap_or_default(); // If this happens, this is most likely due to an old bug and not a recent code change. // We warn about this in try-runtime checks but do not panic. @@ -3958,8 +3961,8 @@ impl Pezpallet { let depositor = PoolMembers::::get(&bonded_pool.roles.depositor).unwrap(); let depositor_has_enough_stake = bonded_pool - .is_destroying_and_only_depositor(depositor.active_points()) || - depositor.active_points() >= MinCreateBond::::get(); + .is_destroying_and_only_depositor(depositor.active_points()) + || depositor.active_points() >= MinCreateBond::::get(); if !depositor_has_enough_stake { log!( warn, @@ -4162,8 +4165,8 @@ impl Pezpallet { let pool_account = Self::generate_bonded_account(pool_id); // true if pool is still not migrated to `DelegateStake`. - T::StakeAdapter::pool_strategy(Pool::from(pool_account)) != - adapter::StakeStrategyType::Delegate + T::StakeAdapter::pool_strategy(Pool::from(pool_account)) + != adapter::StakeStrategyType::Delegate } /// Checks whether member delegation needs to be migrated to diff --git a/bizinikiwi/pezframe/nomination-pools/src/migration.rs b/bizinikiwi/pezframe/nomination-pools/src/migration.rs index b54a84ff..7224626b 100644 --- a/bizinikiwi/pezframe/nomination-pools/src/migration.rs +++ b/bizinikiwi/pezframe/nomination-pools/src/migration.rs @@ -134,8 +134,8 @@ pub mod unversioned { let pool_acc = Pezpallet::::generate_bonded_account(id); // only migrate if the pool is in Transfer Strategy. - if T::StakeAdapter::pool_strategy(Pool::from(pool_acc)) == - adapter::StakeStrategyType::Transfer + if T::StakeAdapter::pool_strategy(Pool::from(pool_acc)) + == adapter::StakeStrategyType::Transfer { let _ = Pezpallet::::migrate_to_delegate_stake(id).map_err(|err| { log!( @@ -198,8 +198,8 @@ pub mod unversioned { BondedPools::::iter_keys().take(MaxPools::get() as usize).enumerate() { let pool_account = Pezpallet::::generate_bonded_account(id); - if T::StakeAdapter::pool_strategy(Pool::from(pool_account.clone())) == - adapter::StakeStrategyType::Transfer + if T::StakeAdapter::pool_strategy(Pool::from(pool_account.clone())) + == adapter::StakeStrategyType::Transfer { log!(error, "Pool {} failed to migrate", id,); return Err(TryRuntimeError::Other("Pool failed to migrate")); @@ -518,8 +518,8 @@ pub mod v5 { "There are undecodable BondedPools in storage. This migration will not fix that." ); ensure!( - SubPoolsStorage::::iter_keys().count() == - SubPoolsStorage::::iter_values().count(), + SubPoolsStorage::::iter_keys().count() + == SubPoolsStorage::::iter_values().count(), "There are undecodable SubPools in storage. This migration will not fix that." ); ensure!( @@ -552,10 +552,10 @@ pub mod v5 { // `total_commission_claimed` field. ensure!( RewardPools::::iter().all(|(_, reward_pool)| reward_pool - .total_commission_pending >= - Zero::zero() && reward_pool - .total_commission_claimed >= - Zero::zero()), + .total_commission_pending + >= Zero::zero() && reward_pool + .total_commission_claimed + >= Zero::zero()), "a commission value has been incorrectly set" ); ensure!( @@ -573,8 +573,8 @@ pub mod v5 { "There are undecodable BondedPools in storage." ); ensure!( - SubPoolsStorage::::iter_keys().count() == - SubPoolsStorage::::iter_values().count(), + SubPoolsStorage::::iter_keys().count() + == SubPoolsStorage::::iter_values().count(), "There are undecodable SubPools in storage." ); ensure!( diff --git a/bizinikiwi/pezframe/nomination-pools/src/mock.rs b/bizinikiwi/pezframe/nomination-pools/src/mock.rs index 70b41924..2eead440 100644 --- a/bizinikiwi/pezframe/nomination-pools/src/mock.rs +++ b/bizinikiwi/pezframe/nomination-pools/src/mock.rs @@ -171,8 +171,8 @@ impl pezsp_staking::StakingInterface for StakingMock { DelegateMock::on_withdraw(who, withdraw_amount); UnbondingBalanceMap::set(&unbonding_map); - Ok(UnbondingBalanceMap::get().get(&who).unwrap().is_empty() && - BondedBalanceMap::get().get(&who).unwrap().is_zero()) + Ok(UnbondingBalanceMap::get().get(&who).unwrap().is_empty() + && BondedBalanceMap::get().get(&who).unwrap().is_zero()) } fn bond(stash: &Self::AccountId, value: Self::Balance, _: &Self::AccountId) -> DispatchResult { diff --git a/bizinikiwi/pezframe/nomination-pools/test-delegate-stake/src/mock.rs b/bizinikiwi/pezframe/nomination-pools/test-delegate-stake/src/mock.rs index 73f6e2c7..0f146a80 100644 --- a/bizinikiwi/pezframe/nomination-pools/test-delegate-stake/src/mock.rs +++ b/bizinikiwi/pezframe/nomination-pools/test-delegate-stake/src/mock.rs @@ -190,7 +190,13 @@ impl pezpallet_nomination_pools::adapter::StakeStrategy for MockAdapter { bond_type: BondType, ) -> DispatchResult { if LegacyAdapter::get() { - return TransferStake::pledge_bond(who, pool_account, reward_account, amount, bond_type); + return TransferStake::pledge_bond( + who, + pool_account, + reward_account, + amount, + bond_type, + ); } DelegateStake::pledge_bond(who, pool_account, reward_account, amount, bond_type) } diff --git a/bizinikiwi/pezframe/origin-restriction/src/lib.rs b/bizinikiwi/pezframe/origin-restriction/src/lib.rs index 1886e1da..ceb77f6d 100644 --- a/bizinikiwi/pezframe/origin-restriction/src/lib.rs +++ b/bizinikiwi/pezframe/origin-restriction/src/lib.rs @@ -318,8 +318,8 @@ impl TransactionExtension for RestrictOrigin { Usages::::insert(&entity, &usage); let allowed_one_time_excess = || { - usage_without_new_xt == 0u32.into() && - T::OperationAllowedOneTimeExcess::contains(&entity, call) + usage_without_new_xt == 0u32.into() + && T::OperationAllowedOneTimeExcess::contains(&entity, call) }; if usage.used <= allowance.max || allowed_one_time_excess() { Ok((ValidTransaction::default(), Val::Charge { fee, entity }, origin)) @@ -350,7 +350,7 @@ impl TransactionExtension for RestrictOrigin { _result: &DispatchResult, ) -> Result { match pre { - Pre::Charge { fee, entity } => + Pre::Charge { fee, entity } => { if post_info.pays_fee == Pays::No { Usages::::mutate_exists(entity, |maybe_usage| { if let Some(usage) = maybe_usage { @@ -364,7 +364,8 @@ impl TransactionExtension for RestrictOrigin { Ok(Weight::zero()) } else { Ok(Weight::zero()) - }, + } + }, Pre::NoCharge { refund } => Ok(refund), } } diff --git a/bizinikiwi/pezframe/origin-restriction/src/mock.rs b/bizinikiwi/pezframe/origin-restriction/src/mock.rs index cf6636f2..2d391997 100644 --- a/bizinikiwi/pezframe/origin-restriction/src/mock.rs +++ b/bizinikiwi/pezframe/origin-restriction/src/mock.rs @@ -141,10 +141,12 @@ impl RestrictedEntity for RuntimeRestrictedEntity { fn restricted_entity(caller: &OriginCaller) -> Option { match caller { - OriginCaller::system(pezframe_system::Origin::::Signed(RESTRICTED_ORIGIN_1)) => - Some(RuntimeRestrictedEntity::A), - OriginCaller::system(pezframe_system::Origin::::Signed(RESTRICTED_ORIGIN_2)) => - Some(RuntimeRestrictedEntity::B), + OriginCaller::system(pezframe_system::Origin::::Signed(RESTRICTED_ORIGIN_1)) => { + Some(RuntimeRestrictedEntity::A) + }, + OriginCaller::system(pezframe_system::Origin::::Signed(RESTRICTED_ORIGIN_2)) => { + Some(RuntimeRestrictedEntity::B) + }, _ => None, } } diff --git a/bizinikiwi/pezframe/parameters/src/tests/mock.rs b/bizinikiwi/pezframe/parameters/src/tests/mock.rs index 1a412a96..1107b5ae 100644 --- a/bizinikiwi/pezframe/parameters/src/tests/mock.rs +++ b/bizinikiwi/pezframe/parameters/src/tests/mock.rs @@ -113,9 +113,9 @@ mod custom_origin { } match key { - RuntimeParametersKey::SomEWeirdSPElLInGS(_) | - RuntimeParametersKey::Nis(_) | - RuntimeParametersKey::Pallet1(_) => ensure_root(origin.clone()), + RuntimeParametersKey::SomEWeirdSPElLInGS(_) + | RuntimeParametersKey::Nis(_) + | RuntimeParametersKey::Pallet1(_) => ensure_root(origin.clone()), RuntimeParametersKey::Pallet2(_) => ensure_signed(origin.clone()).map(|_| ()), } .map_err(|_| origin) diff --git a/bizinikiwi/pezframe/people/src/extension.rs b/bizinikiwi/pezframe/people/src/extension.rs index 9f266843..163e0af5 100644 --- a/bizinikiwi/pezframe/people/src/extension.rs +++ b/bizinikiwi/pezframe/people/src/extension.rs @@ -118,17 +118,21 @@ impl TransactionExtension< Weight::zero(), // Alias with existing account - Some(AsPersonInfo::AsPersonalAliasWithAccount(_)) => - T::WeightInfo::as_person_alias_with_account(), + Some(AsPersonInfo::AsPersonalAliasWithAccount(_)) => { + T::WeightInfo::as_person_alias_with_account() + }, // Alias with proof - Some(AsPersonInfo::AsPersonalAliasWithProof(_, _, _)) => - T::WeightInfo::as_person_alias_with_proof(), + Some(AsPersonInfo::AsPersonalAliasWithProof(_, _, _)) => { + T::WeightInfo::as_person_alias_with_proof() + }, // Personal Identity with proof - Some(AsPersonInfo::AsPersonalIdentityWithProof(_, _)) => - T::WeightInfo::as_person_identity_with_proof(), + Some(AsPersonInfo::AsPersonalIdentityWithProof(_, _)) => { + T::WeightInfo::as_person_identity_with_proof() + }, // Personal Identity with existing account - Some(AsPersonInfo::AsPersonalIdentityWithAccount(_)) => - T::WeightInfo::as_person_identity_with_account(), + Some(AsPersonInfo::AsPersonalIdentityWithAccount(_)) => { + T::WeightInfo::as_person_identity_with_account() + }, } } @@ -299,8 +303,9 @@ impl TransactionExtension< Result { match val { - Val::UsingAccount(who, nonce) => - CheckNonce::::prepare_nonce_for_account(&who, nonce)?, + Val::UsingAccount(who, nonce) => { + CheckNonce::::prepare_nonce_for_account(&who, nonce)? + }, Val::NotUsing | Val::UsingProof => (), } diff --git a/bizinikiwi/pezframe/people/src/lib.rs b/bizinikiwi/pezframe/people/src/lib.rs index 3794cc60..8ce0bd2f 100644 --- a/bizinikiwi/pezframe/people/src/lib.rs +++ b/bizinikiwi/pezframe/people/src/lib.rs @@ -494,10 +494,10 @@ pub mod pezpallet { // Check if there are any rings with suspensions and try to clean the first one. if let Some(ring_index) = PendingSuspensions::::iter_keys().next() { - if Self::should_remove_suspended_keys(ring_index, true) && - weight_meter.can_consume(T::WeightInfo::remove_suspended_people( - T::MaxRingSize::get(), - )) { + if Self::should_remove_suspended_keys(ring_index, true) + && weight_meter + .can_consume(T::WeightInfo::remove_suspended_people(T::MaxRingSize::get())) + { let actual = Self::remove_suspended_keys(ring_index); weight_meter.consume(actual) } @@ -829,9 +829,9 @@ pub mod pezpallet { // merged. let current_ring_index = CurrentRingIndex::::get(); ensure!( - base_ring_index != target_ring_index && - base_ring_index != current_ring_index && - target_ring_index != current_ring_index, + base_ring_index != target_ring_index + && base_ring_index != current_ring_index + && target_ring_index != current_ring_index, Error::::InvalidRing ); @@ -1091,8 +1091,9 @@ pub mod pezpallet { People::::insert(id, record); }, // This call accepts migrations only for included keys. - RingPosition::Onboarding { .. } => - return Err(Error::::InvalidKeyMigration.into()), + RingPosition::Onboarding { .. } => { + return Err(Error::::InvalidKeyMigration.into()) + }, // Suspended people shouldn't be able to call this, but protect against this case // anyway. RingPosition::Suspended => return Err(Error::::Suspended.into()), @@ -1212,9 +1213,9 @@ pub mod pezpallet { // Here we check we have enough items in the queue so that the onboarding group size is // respected, but also that we can support another queue of at least onboarding size // in a future call. - let can_onboard_with_cohort = to_include >= onboarding_size && - ring_status.total.saturating_add(to_include.saturated_into()) <= - T::MaxRingSize::get().saturating_sub(onboarding_size); + let can_onboard_with_cohort = to_include >= onboarding_size + && ring_status.total.saturating_add(to_include.saturated_into()) + <= T::MaxRingSize::get().saturating_sub(onboarding_size); // If this call completely fills the ring, no onboarding rule enforcement will be // necessary. let ring_filled = open_slots == to_include; @@ -1645,8 +1646,9 @@ pub mod pezpallet { } let op_res = with_storage_layer::(|| match drain.next() { - Some((id, new_key)) => - Self::migrate_keys_single_included_key(id, new_key).map(|_| false), + Some((id, new_key)) => { + Self::migrate_keys_single_included_key(id, new_key).map(|_| false) + }, None => { let rings_state = RingsState::::get() .end_key_migration() @@ -1809,9 +1811,9 @@ pub mod pezpallet { } fn renew_id_reservation(personal_id: PersonalId) -> Result<(), DispatchError> { - if NextPersonalId::::get() <= personal_id || - People::::contains_key(personal_id) || - ReservedPersonalId::::contains_key(personal_id) + if NextPersonalId::::get() <= personal_id + || People::::contains_key(personal_id) + || ReservedPersonalId::::contains_key(personal_id) { return Err(Error::::PersonalIdReservationCannotRenew.into()); } @@ -2046,8 +2048,9 @@ pub mod pezpallet { fn try_origin(o: OriginFor, arg: &Context) -> Result> { match ensure_revised_personal_alias(o.clone().into_caller()) { - Ok(ca) if &ca.ca.context == arg => - Ok(RevisedAlias { revision: ca.revision, ring: ca.ring, alias: ca.ca.alias }), + Ok(ca) if &ca.ca.context == arg => { + Ok(RevisedAlias { revision: ca.revision, ring: ca.ring, alias: ca.ca.alias }) + }, _ => Err(o), } } diff --git a/bizinikiwi/pezframe/people/src/tests.rs b/bizinikiwi/pezframe/people/src/tests.rs index f7891818..6e9f8f21 100644 --- a/bizinikiwi/pezframe/people/src/tests.rs +++ b/bizinikiwi/pezframe/people/src/tests.rs @@ -2056,8 +2056,8 @@ mod onboard_people { assert_eq!(tail, 2); assert!( - !OnboardingQueue::::get(head).is_empty() && - !OnboardingQueue::::get(tail).is_empty() + !OnboardingQueue::::get(head).is_empty() + && !OnboardingQueue::::get(tail).is_empty() ); for _ in 0..=expected_rings_to_build - 1 { @@ -2662,11 +2662,11 @@ fn on_poll_works() { let merge_pages_weight = <::WeightInfo as crate::WeightInfo>::merge_queue_pages(); - let expected_consumed = base_weight + - step_migration_weight.saturating_mul(5) + - end_migrate_db_weight + - step_remove_keys_weight + - merge_pages_weight; + let expected_consumed = base_weight + + step_migration_weight.saturating_mul(5) + + end_migrate_db_weight + + step_remove_keys_weight + + merge_pages_weight; assert_eq!(meter.consumed(), expected_consumed); }); } diff --git a/bizinikiwi/pezframe/preimage/src/lib.rs b/bizinikiwi/pezframe/preimage/src/lib.rs index 27b9ab8a..6b0f6aa5 100644 --- a/bizinikiwi/pezframe/preimage/src/lib.rs +++ b/bizinikiwi/pezframe/preimage/src/lib.rs @@ -358,17 +358,20 @@ impl Pezpallet { // We take a deposit only if there is a provided depositor and the preimage was not // previously requested. This also allows the tx to pay no fee. let status = match (RequestStatusFor::::get(hash), maybe_depositor) { - (Some(RequestStatus::Requested { maybe_ticket, count, .. }), _) => - RequestStatus::Requested { maybe_ticket, count, maybe_len: Some(len) }, - (Some(RequestStatus::Unrequested { .. }), Some(_)) => - return Err(Error::::AlreadyNoted.into()), + (Some(RequestStatus::Requested { maybe_ticket, count, .. }), _) => { + RequestStatus::Requested { maybe_ticket, count, maybe_len: Some(len) } + }, + (Some(RequestStatus::Unrequested { .. }), Some(_)) => { + return Err(Error::::AlreadyNoted.into()) + }, (Some(RequestStatus::Unrequested { ticket, len }), None) => RequestStatus::Requested { maybe_ticket: Some(ticket), count: 1, maybe_len: Some(len), }, - (None, None) => - RequestStatus::Requested { maybe_ticket: None, count: 1, maybe_len: Some(len) }, + (None, None) => { + RequestStatus::Requested { maybe_ticket: None, count: 1, maybe_len: Some(len) } + }, (None, Some(depositor)) => { let ticket = T::Consideration::new(depositor, Footprint::from_parts(1, len as usize))?; @@ -500,8 +503,9 @@ impl Pezpallet { use RequestStatus::*; Self::do_ensure_updated(&hash); match RequestStatusFor::::get(hash) { - Some(Requested { maybe_len: Some(len), .. }) | Some(Unrequested { len, .. }) => - Some(len), + Some(Requested { maybe_len: Some(len), .. }) | Some(Unrequested { len, .. }) => { + Some(len) + }, _ => None, } } diff --git a/bizinikiwi/pezframe/preimage/src/migration.rs b/bizinikiwi/pezframe/preimage/src/migration.rs index 6b4ce418..34725c13 100644 --- a/bizinikiwi/pezframe/preimage/src/migration.rs +++ b/bizinikiwi/pezframe/preimage/src/migration.rs @@ -130,15 +130,17 @@ pub mod v1 { v0::OldRequestStatus::Unrequested(deposit) => match deposit { Some(deposit) => OldRequestStatus::Unrequested { deposit, len }, // `None` depositor becomes system-requested. - None => - OldRequestStatus::Requested { deposit: None, count: 1, len: Some(len) }, + None => { + OldRequestStatus::Requested { deposit: None, count: 1, len: Some(len) } + }, }, v0::OldRequestStatus::Requested(0) => { log::error!(target: TARGET, "preimage has counter of zero: {:?}", hash); continue; }, - v0::OldRequestStatus::Requested(count) => - OldRequestStatus::Requested { deposit: None, count, len: Some(len) }, + v0::OldRequestStatus::Requested(count) => { + OldRequestStatus::Requested { deposit: None, count, len: Some(len) } + }, }; log::trace!(target: TARGET, "Moving preimage {:?} with len {}", hash, len); diff --git a/bizinikiwi/pezframe/proxy/src/lib.rs b/bizinikiwi/pezframe/proxy/src/lib.rs index 3be8292c..db5fdb8b 100644 --- a/bizinikiwi/pezframe/proxy/src/lib.rs +++ b/bizinikiwi/pezframe/proxy/src/lib.rs @@ -564,9 +564,9 @@ pub mod pezpallet { let call_hash = T::CallHasher::hash_of(&call); let now = T::BlockNumberProvider::current_block_number(); Self::edit_announcements(&delegate, |ann| { - ann.real != real || - ann.call_hash != call_hash || - now.saturating_sub(ann.height) < def.delay + ann.real != real + || ann.call_hash != call_hash + || now.saturating_sub(ann.height) < def.delay }) .map_err(|_| Error::::Unannounced)?; @@ -987,8 +987,8 @@ impl Pezpallet { force_proxy_type: Option, ) -> Result>, DispatchError> { let f = |x: &ProxyDefinition>| -> bool { - &x.delegate == delegate && - force_proxy_type.as_ref().map_or(true, |y| &x.proxy_type == y) + &x.delegate == delegate + && force_proxy_type.as_ref().map_or(true, |y| &x.proxy_type == y) }; Ok(Proxies::::get(real).0.into_iter().find(f).ok_or(Error::::NotProxy)?) } @@ -1007,15 +1007,19 @@ impl Pezpallet { match c.is_sub_type() { // Proxy call cannot add or remove a proxy with more permissions than it already // has. - Some(Call::add_proxy { ref proxy_type, .. }) | - Some(Call::remove_proxy { ref proxy_type, .. }) + Some(Call::add_proxy { ref proxy_type, .. }) + | Some(Call::remove_proxy { ref proxy_type, .. }) if !def.proxy_type.is_superset(proxy_type) => - false, + { + false + }, // Proxy call cannot remove all proxies or kill pure proxies unless it has full // permissions. Some(Call::remove_proxies { .. }) | Some(Call::kill_pure { .. }) if def.proxy_type != T::ProxyType::default() => - false, + { + false + }, _ => def.proxy_type.filter(c), } }); diff --git a/bizinikiwi/pezframe/ranked-collective/src/lib.rs b/bizinikiwi/pezframe/ranked-collective/src/lib.rs index ec60e030..d80f8ecc 100644 --- a/bizinikiwi/pezframe/ranked-collective/src/lib.rs +++ b/bizinikiwi/pezframe/ranked-collective/src/lib.rs @@ -643,8 +643,9 @@ pub mod pezpallet { poll, |mut status| -> Result<(TallyOf, VoteRecord), DispatchError> { match status { - PollStatus::None | PollStatus::Completed(..) => - Err(Error::::NotPolling)?, + PollStatus::None | PollStatus::Completed(..) => { + Err(Error::::NotPolling)? + }, PollStatus::Ongoing(ref mut tally, class) => { match Voting::::get(&poll, &who) { Some(Aye(votes)) => { diff --git a/bizinikiwi/pezframe/ranked-collective/src/tests.rs b/bizinikiwi/pezframe/ranked-collective/src/tests.rs index 8d5c9c72..4e0b1ae0 100644 --- a/bizinikiwi/pezframe/ranked-collective/src/tests.rs +++ b/bizinikiwi/pezframe/ranked-collective/src/tests.rs @@ -88,8 +88,9 @@ impl Polling> for TestPolls { let mut polls = Polls::get(); let entry = polls.get_mut(&index); let r = match entry { - Some(Ongoing(ref mut tally_mut_ref, class)) => - f(PollStatus::Ongoing(tally_mut_ref, *class)), + Some(Ongoing(ref mut tally_mut_ref, class)) => { + f(PollStatus::Ongoing(tally_mut_ref, *class)) + }, Some(Completed(when, succeeded)) => f(PollStatus::Completed(*when, *succeeded)), None => f(PollStatus::None), }; @@ -105,8 +106,9 @@ impl Polling> for TestPolls { let mut polls = Polls::get(); let entry = polls.get_mut(&index); let r = match entry { - Some(Ongoing(ref mut tally_mut_ref, class)) => - f(PollStatus::Ongoing(tally_mut_ref, *class)), + Some(Ongoing(ref mut tally_mut_ref, class)) => { + f(PollStatus::Ongoing(tally_mut_ref, *class)) + }, Some(Completed(when, succeeded)) => f(PollStatus::Completed(*when, *succeeded)), None => f(PollStatus::None), }?; diff --git a/bizinikiwi/pezframe/referenda/src/branch.rs b/bizinikiwi/pezframe/referenda/src/branch.rs index 2d1b03f9..ff7414d8 100644 --- a/bizinikiwi/pezframe/referenda/src/branch.rs +++ b/bizinikiwi/pezframe/referenda/src/branch.rs @@ -113,17 +113,17 @@ impl ServiceBranch { NotQueued => T::WeightInfo::place_decision_deposit_not_queued(), BeginDecidingPassing => T::WeightInfo::place_decision_deposit_passing(), BeginDecidingFailing => T::WeightInfo::place_decision_deposit_failing(), - BeginConfirming | - ContinueConfirming | - EndConfirming | - ContinueNotConfirming | - Approved | - Rejected | - RequeuedInsertion | - RequeuedSlide | - TimedOut | - Fail | - NoDeposit => return None, + BeginConfirming + | ContinueConfirming + | EndConfirming + | ContinueNotConfirming + | Approved + | Rejected + | RequeuedInsertion + | RequeuedSlide + | TimedOut + | Fail + | NoDeposit => return None, }; Some(ref_time_weight) diff --git a/bizinikiwi/pezframe/referenda/src/lib.rs b/bizinikiwi/pezframe/referenda/src/lib.rs index a9fa69ae..d4ce36af 100644 --- a/bizinikiwi/pezframe/referenda/src/lib.rs +++ b/bizinikiwi/pezframe/referenda/src/lib.rs @@ -931,8 +931,8 @@ impl, I: 'static> Pezpallet { let alarm_interval = T::AlarmInterval::get().max(One::one()); // Alarm must go off no earlier than `when`. // This rounds `when` upwards to the next multiple of `alarm_interval`. - let when = (when.saturating_add(alarm_interval.saturating_sub(One::one())) / - alarm_interval) + let when = (when.saturating_add(alarm_interval.saturating_sub(One::one())) + / alarm_interval) .saturating_mul(alarm_interval); let result = T::Scheduler::schedule( DispatchTime::At(when), @@ -1321,8 +1321,8 @@ impl, I: 'static> Pezpallet { id: TrackIdOf, ) -> bool { let x = Perbill::from_rational(elapsed.min(period), period); - support_needed.passing(x, tally.support(id)) && - approval_needed.passing(x, tally.approval(id)) + support_needed.passing(x, tally.support(id)) + && approval_needed.passing(x, tally.approval(id)) } /// Clear metadata if exist for a given referendum index. @@ -1344,8 +1344,8 @@ impl, I: 'static> Pezpallet { #[cfg(any(feature = "try-runtime", test))] fn do_try_state() -> Result<(), pezsp_runtime::TryRuntimeError> { ensure!( - ReferendumCount::::get() as usize == - ReferendumInfoFor::::iter_keys().count(), + ReferendumCount::::get() as usize + == ReferendumInfoFor::::iter_keys().count(), "Number of referenda in `ReferendumInfoFor` is different than `ReferendumCount`" ); @@ -1383,8 +1383,8 @@ impl, I: 'static> Pezpallet { if let Some(deciding) = status.deciding { ensure!( - deciding.since < - deciding + deciding.since + < deciding .confirming .unwrap_or(BlockNumberFor::::max_value()), "Deciding status cannot begin before confirming stage." diff --git a/bizinikiwi/pezframe/referenda/src/migration.rs b/bizinikiwi/pezframe/referenda/src/migration.rs index d9f43d9a..e27ed0a4 100644 --- a/bizinikiwi/pezframe/referenda/src/migration.rs +++ b/bizinikiwi/pezframe/referenda/src/migration.rs @@ -152,14 +152,18 @@ pub mod v1 { v0::ReferendumInfoFor::::iter().for_each(|(key, value)| { let maybe_new_value = match value { v0::ReferendumInfo::Ongoing(_) | v0::ReferendumInfo::Killed(_) => None, - v0::ReferendumInfo::Approved(e, s, d) => - Some(ReferendumInfo::Approved(e, Some(s), d)), - v0::ReferendumInfo::Rejected(e, s, d) => - Some(ReferendumInfo::Rejected(e, Some(s), d)), - v0::ReferendumInfo::Cancelled(e, s, d) => - Some(ReferendumInfo::Cancelled(e, Some(s), d)), - v0::ReferendumInfo::TimedOut(e, s, d) => - Some(ReferendumInfo::TimedOut(e, Some(s), d)), + v0::ReferendumInfo::Approved(e, s, d) => { + Some(ReferendumInfo::Approved(e, Some(s), d)) + }, + v0::ReferendumInfo::Rejected(e, s, d) => { + Some(ReferendumInfo::Rejected(e, Some(s), d)) + }, + v0::ReferendumInfo::Cancelled(e, s, d) => { + Some(ReferendumInfo::Cancelled(e, Some(s), d)) + }, + v0::ReferendumInfo::TimedOut(e, s, d) => { + Some(ReferendumInfo::TimedOut(e, Some(s), d)) + }, }; if let Some(new_value) = maybe_new_value { weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); diff --git a/bizinikiwi/pezframe/referenda/src/types.rs b/bizinikiwi/pezframe/referenda/src/types.rs index 891ac047..f88c4da7 100644 --- a/bizinikiwi/pezframe/referenda/src/types.rs +++ b/bizinikiwi/pezframe/referenda/src/types.rs @@ -394,8 +394,9 @@ impl< Ongoing(x) if x.decision_deposit.is_none() => Ok(None), // Cannot refund deposit if Ongoing as this breaks assumptions. Ongoing(_) => Err(()), - Approved(_, _, d) | Rejected(_, _, d) | TimedOut(_, _, d) | Cancelled(_, _, d) => - Ok(d.take()), + Approved(_, _, d) | Rejected(_, _, d) | TimedOut(_, _, d) | Cancelled(_, _, d) => { + Ok(d.take()) + }, Killed(_) => Ok(None), } } @@ -567,10 +568,12 @@ impl Curve { /// Determine the `y` value for the given `x` value. pub fn threshold(&self, x: Perbill) -> Perbill { match self { - Self::LinearDecreasing { length, floor, ceil } => - *ceil - (x.min(*length).saturating_div(*length, Down) * (*ceil - *floor)), - Self::SteppedDecreasing { begin, end, step, period } => - (*begin - (step.int_mul(x.int_div(*period))).min(*begin)).max(*end), + Self::LinearDecreasing { length, floor, ceil } => { + *ceil - (x.min(*length).saturating_div(*length, Down) * (*ceil - *floor)) + }, + Self::SteppedDecreasing { begin, end, step, period } => { + (*begin - (step.int_mul(x.int_div(*period))).min(*begin)).max(*end) + }, Self::Reciprocal { factor, x_offset, y_offset } => factor .checked_rounding_div(FixedI64::from(x) + *x_offset, Low) .map(|yp| (yp + *y_offset).into_clamped_perthing()) @@ -609,20 +612,22 @@ impl Curve { /// ``` pub fn delay(&self, y: Perbill) -> Perbill { match self { - Self::LinearDecreasing { length, floor, ceil } => + Self::LinearDecreasing { length, floor, ceil } => { if y < *floor { Perbill::one() } else if y > *ceil { Perbill::zero() } else { (*ceil - y).saturating_div(*ceil - *floor, Up).saturating_mul(*length) - }, - Self::SteppedDecreasing { begin, end, step, period } => + } + }, + Self::SteppedDecreasing { begin, end, step, period } => { if y < *end { Perbill::one() } else { period.int_mul((*begin - y.min(*begin) + step.less_epsilon()).int_div(*step)) - }, + } + }, Self::Reciprocal { factor, x_offset, y_offset } => { let y = FixedI64::from(y); let maybe_term = factor.checked_rounding_div(y - *y_offset, High); diff --git a/bizinikiwi/pezframe/revive/dev-node/node/src/command.rs b/bizinikiwi/pezframe/revive/dev-node/node/src/command.rs index c9b2d244..b7d4fe7f 100644 --- a/bizinikiwi/pezframe/revive/dev-node/node/src/command.rs +++ b/bizinikiwi/pezframe/revive/dev-node/node/src/command.rs @@ -50,8 +50,9 @@ impl BizinikiwiCli for Cli { fn load_spec(&self, id: &str) -> Result, String> { Ok(match id { "dev" | "" => Box::new(chain_spec::development_chain_spec()?), - 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))?) + }, }) } } diff --git a/bizinikiwi/pezframe/revive/rpc/examples/extrinsic.rs b/bizinikiwi/pezframe/revive/rpc/examples/extrinsic.rs index 776caede..cd5d9e3c 100644 --- a/bizinikiwi/pezframe/revive/rpc/examples/extrinsic.rs +++ b/bizinikiwi/pezframe/revive/rpc/examples/extrinsic.rs @@ -14,12 +14,12 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. +use pezkuwi_subxt::OnlineClient; +use pezkuwi_subxt_signer::sr25519::dev; use pezpallet_revive_eth_rpc::subxt_client::{ self, revive::calls::types::InstantiateWithCode, SrcChainConfig, }; use pezsp_weights::Weight; -use pezkuwi_subxt::OnlineClient; -use pezkuwi_subxt_signer::sr25519::dev; #[tokio::main] async fn main() -> Result<(), Box> { diff --git a/bizinikiwi/pezframe/revive/rpc/examples/remark-extrinsic.rs b/bizinikiwi/pezframe/revive/rpc/examples/remark-extrinsic.rs index a0a9453d..2883307e 100644 --- a/bizinikiwi/pezframe/revive/rpc/examples/remark-extrinsic.rs +++ b/bizinikiwi/pezframe/revive/rpc/examples/remark-extrinsic.rs @@ -14,9 +14,9 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -use pezpallet_revive_eth_rpc::subxt_client::{self, system::calls::types::Remark, SrcChainConfig}; use pezkuwi_subxt::OnlineClient; use pezkuwi_subxt_signer::sr25519::dev; +use pezpallet_revive_eth_rpc::subxt_client::{self, system::calls::types::Remark, SrcChainConfig}; #[tokio::main] async fn main() -> Result<(), Box> { diff --git a/bizinikiwi/pezframe/revive/rpc/src/client.rs b/bizinikiwi/pezframe/revive/rpc/src/client.rs index c081638c..14e5d87e 100644 --- a/bizinikiwi/pezframe/revive/rpc/src/client.rs +++ b/bizinikiwi/pezframe/revive/rpc/src/client.rs @@ -185,9 +185,10 @@ impl From for ErrorObjectOwned { match err { ClientError::SubxtError(pezkuwi_subxt::Error::OtherRpcClientError( pezkuwi_subxt::ext::pezkuwi_subxt_rpcs::Error::User(err), - )) | - ClientError::RpcError(pezkuwi_subxt::ext::pezkuwi_subxt_rpcs::Error::User(err)) => - ErrorObjectOwned::owned::>(err.code, err.message, None), + )) + | ClientError::RpcError(pezkuwi_subxt::ext::pezkuwi_subxt_rpcs::Error::User(err)) => { + ErrorObjectOwned::owned::>(err.code, err.message, None) + }, ClientError::TransactError(EthTransactError::Data(data)) => { let msg = match decode_revert_reason(&data) { Some(reason) => format!("execution reverted: {reason}"), @@ -197,10 +198,12 @@ impl From for ErrorObjectOwned { let data = format!("0x{}", hex::encode(data)); ErrorObjectOwned::owned::(REVERT_CODE, msg, Some(data)) }, - ClientError::TransactError(EthTransactError::Message(msg)) => - ErrorObjectOwned::owned::(CALL_EXECUTION_FAILED_CODE, msg, None), - _ => - ErrorObjectOwned::owned::(CALL_EXECUTION_FAILED_CODE, err.to_string(), None), + ClientError::TransactError(EthTransactError::Message(msg)) => { + ErrorObjectOwned::owned::(CALL_EXECUTION_FAILED_CODE, msg, None) + }, + _ => { + ErrorObjectOwned::owned::(CALL_EXECUTION_FAILED_CODE, err.to_string(), None) + }, } } } diff --git a/bizinikiwi/pezframe/revive/rpc/src/client/runtime_api.rs b/bizinikiwi/pezframe/revive/rpc/src/client/runtime_api.rs index 1aa4ade8..cd51d556 100644 --- a/bizinikiwi/pezframe/revive/rpc/src/client/runtime_api.rs +++ b/bizinikiwi/pezframe/revive/rpc/src/client/runtime_api.rs @@ -75,8 +75,9 @@ impl RuntimeApi { block: BlockNumberOrTagOrHash, ) -> Result, ClientError> { let timestamp_override = match block { - BlockNumberOrTagOrHash::BlockTag(BlockTag::Pending) => - Some(Timestamp::current().as_millis()), + BlockNumberOrTagOrHash::BlockTag(BlockTag::Pending) => { + Some(Timestamp::current().as_millis()) + }, _ => None, }; diff --git a/bizinikiwi/pezframe/revive/rpc/src/client/storage_api.rs b/bizinikiwi/pezframe/revive/rpc/src/client/storage_api.rs index c5b54b89..a6cf95ab 100644 --- a/bizinikiwi/pezframe/revive/rpc/src/client/storage_api.rs +++ b/bizinikiwi/pezframe/revive/rpc/src/client/storage_api.rs @@ -28,7 +28,10 @@ use pezsp_core::H256; /// A wrapper around the Bizinikiwi Storage API. #[derive(Clone)] -pub struct StorageApi(StorageClientAt>, #[expect(dead_code)] H256); +pub struct StorageApi( + StorageClientAt>, + #[expect(dead_code)] H256, +); impl StorageApi { /// Create a new instance of the StorageApi. diff --git a/bizinikiwi/pezframe/revive/rpc/src/receipt_provider.rs b/bizinikiwi/pezframe/revive/rpc/src/receipt_provider.rs index eef4de10..dfcd1896 100644 --- a/bizinikiwi/pezframe/revive/rpc/src/receipt_provider.rs +++ b/bizinikiwi/pezframe/revive/rpc/src/receipt_provider.rs @@ -225,8 +225,9 @@ impl ReceiptProvider { /// Check if the block is before the earliest block. pub fn is_before_earliest_block(&self, at: &BlockNumberOrTag) -> bool { match at { - BlockNumberOrTag::U256(block_number) => - self.receipt_extractor.is_before_earliest_block(block_number.as_u32()), + BlockNumberOrTag::U256(block_number) => { + self.receipt_extractor.is_before_earliest_block(block_number.as_u32()) + }, BlockNumberOrTag::BlockTag(_) => false, } } @@ -617,15 +618,17 @@ mod tests { async fn count(pool: &SqlitePool, table: &str, block_hash: Option) -> usize { let count: i64 = match block_hash { - None => + None => { sqlx::query_scalar(&format!("SELECT COUNT(*) FROM {table}")) .fetch_one(pool) - .await, - Some(hash) => + .await + }, + Some(hash) => { sqlx::query_scalar(&format!("SELECT COUNT(*) FROM {table} WHERE block_hash = ?")) .bind(hash.as_ref()) .fetch_one(pool) - .await, + .await + }, } .unwrap(); diff --git a/bizinikiwi/pezframe/revive/rpc/src/tests.rs b/bizinikiwi/pezframe/revive/rpc/src/tests.rs index 7155ed60..3e65d9f7 100644 --- a/bizinikiwi/pezframe/revive/rpc/src/tests.rs +++ b/bizinikiwi/pezframe/revive/rpc/src/tests.rs @@ -209,8 +209,8 @@ async fn submit_bizinikiwi_transactions( log::trace!(target: LOG_TARGET, "Bizinikiwi tx {i} submitted"); while let Some(status) = progress.next().await { match status { - Ok(TxStatus::InFinalizedBlock(block)) | - Ok(TxStatus::InBestBlock(block)) => { + Ok(TxStatus::InFinalizedBlock(block)) + | Ok(TxStatus::InBestBlock(block)) => { log::trace!(target: LOG_TARGET, "Bizinikiwi tx {i} included in block {:?}", block.block_hash() @@ -250,8 +250,9 @@ async fn verify_transactions_in_single_block( let block_tx_hashes = match &block.transactions { HashesOrTransactionInfos::Hashes(hashes) => hashes.clone(), - HashesOrTransactionInfos::TransactionInfos(infos) => - infos.iter().map(|info| info.hash).collect(), + HashesOrTransactionInfos::TransactionInfos(infos) => { + infos.iter().map(|info| info.hash).collect() + }, }; if let Some(missing_hash) = @@ -780,7 +781,11 @@ async fn test_runtime_pallets_address_upload_code(client: Arc) -> anyh let code_hash = H256(pezsp_io::hashing::keccak_256(&bytecode)); let query = subxt_client::storage().revive().pristine_code(); let block_hash: pezsp_core::H256 = get_bizinikiwi_block_hash(receipt.block_number).await?; - let stored_code: Vec = node_client.storage().at(block_hash).fetch(&query, (code_hash,)).await + let stored_code: Vec = node_client + .storage() + .at(block_hash) + .fetch(&query, (code_hash,)) + .await .expect("Code with hash should exist in storage") .decode()?; assert_eq!(stored_code, bytecode, "Stored code should match the uploaded bytecode"); diff --git a/bizinikiwi/pezframe/revive/src/address.rs b/bizinikiwi/pezframe/revive/src/address.rs index 8315421d..74b561d2 100644 --- a/bizinikiwi/pezframe/revive/src/address.rs +++ b/bizinikiwi/pezframe/revive/src/address.rs @@ -165,8 +165,8 @@ where } fn is_mapped(account_id: &T::AccountId) -> bool { - is_eth_derived(account_id) || - >::contains_key(Self::to_address(account_id)) + is_eth_derived(account_id) + || >::contains_key(Self::to_address(account_id)) } } diff --git a/bizinikiwi/pezframe/revive/src/benchmarking.rs b/bizinikiwi/pezframe/revive/src/benchmarking.rs index 9c617a18..2d4690bd 100644 --- a/bizinikiwi/pezframe/revive/src/benchmarking.rs +++ b/bizinikiwi/pezframe/revive/src/benchmarking.rs @@ -264,10 +264,11 @@ mod benchmarks { T::Currency::balance_on_hold(&HoldReason::AddressMapping.into(), &caller); assert_eq!( T::Currency::balance(&caller), - caller_funding::() - - value - deposit - - code_deposit - mapping_deposit - - Pezpallet::::min_balance(), + caller_funding::() + - value - deposit + - code_deposit + - mapping_deposit + - Pezpallet::::min_balance(), ); // contract has the full value assert_eq!(T::Currency::balance(&account_id), value + Pezpallet::::min_balance()); @@ -368,10 +369,11 @@ mod benchmarks { // value was removed from the caller assert_eq!( T::Currency::total_balance(&caller), - caller_funding::() - - value - deposit - - code_deposit - mapping_deposit - - Pezpallet::::min_balance(), + caller_funding::() + - value - deposit + - code_deposit + - mapping_deposit + - Pezpallet::::min_balance(), ); // contract has the full value assert_eq!(T::Currency::balance(&account_id), value + Pezpallet::::min_balance()); @@ -411,10 +413,11 @@ mod benchmarks { // value and value transferred via call should be removed from the caller assert_eq!( T::Currency::balance(&instance.caller), - caller_funding::() - - value - deposit - - code_deposit - mapping_deposit - - Pezpallet::::min_balance() + caller_funding::() + - value - deposit + - code_deposit + - mapping_deposit + - Pezpallet::::min_balance() ); // contract should have received the value assert_eq!(T::Currency::balance(&instance.account_id), before + value); diff --git a/bizinikiwi/pezframe/revive/src/call_builder.rs b/bizinikiwi/pezframe/revive/src/call_builder.rs index 17926369..dcaaa883 100644 --- a/bizinikiwi/pezframe/revive/src/call_builder.rs +++ b/bizinikiwi/pezframe/revive/src/call_builder.rs @@ -443,8 +443,9 @@ impl VmBinaryModule { // return execution right away without breaking up basic block // SENTINEL is a hard coded syscall that terminates execution 0 => writeln!(text, "ecalli {}", crate::SENTINEL).unwrap(), - i if i % (limits::code::BASIC_BLOCK_SIZE - 1) == 0 => - text.push_str("fallthrough\n"), + i if i % (limits::code::BASIC_BLOCK_SIZE - 1) == 0 => { + text.push_str("fallthrough\n") + }, _ => text.push_str("a0 = a1 + a2\n"), } } diff --git a/bizinikiwi/pezframe/revive/src/evm/api/rlp_codec.rs b/bizinikiwi/pezframe/revive/src/evm/api/rlp_codec.rs index b18b48ee..89cb6523 100644 --- a/bizinikiwi/pezframe/revive/src/evm/api/rlp_codec.rs +++ b/bizinikiwi/pezframe/revive/src/evm/api/rlp_codec.rs @@ -62,8 +62,9 @@ impl TransactionSigned { Transaction2930Signed(tx) => Transaction2930Unsigned(tx.transaction_2930_unsigned), Transaction1559Signed(tx) => Transaction1559Unsigned(tx.transaction_1559_unsigned), Transaction4844Signed(tx) => Transaction4844Unsigned(tx.transaction_4844_unsigned), - TransactionLegacySigned(tx) => - TransactionLegacyUnsigned(tx.transaction_legacy_unsigned), + TransactionLegacySigned(tx) => { + TransactionLegacyUnsigned(tx.transaction_legacy_unsigned) + }, } } diff --git a/bizinikiwi/pezframe/revive/src/evm/api/rpc_types_gen.rs b/bizinikiwi/pezframe/revive/src/evm/api/rpc_types_gen.rs index 5e54faa2..24ba44ca 100644 --- a/bizinikiwi/pezframe/revive/src/evm/api/rpc_types_gen.rs +++ b/bizinikiwi/pezframe/revive/src/evm/api/rpc_types_gen.rs @@ -200,11 +200,13 @@ impl<'a> serde::Deserialize<'a> for BlockNumberOrTagOrHash { BlockNumberOrTagOrHash::BlockNumber(val.into()) }, - BlockNumberOrTagOrHashWithAlias::NestedBlockNumber { block_number: val } => - BlockNumberOrTagOrHash::BlockNumber(val), - BlockNumberOrTagOrHashWithAlias::BlockHash(val) | - BlockNumberOrTagOrHashWithAlias::NestedBlockHash { block_hash: val } => - BlockNumberOrTagOrHash::BlockHash(val), + BlockNumberOrTagOrHashWithAlias::NestedBlockNumber { block_number: val } => { + BlockNumberOrTagOrHash::BlockNumber(val) + }, + BlockNumberOrTagOrHashWithAlias::BlockHash(val) + | BlockNumberOrTagOrHashWithAlias::NestedBlockHash { block_hash: val } => { + BlockNumberOrTagOrHash::BlockHash(val) + }, }) } } @@ -544,8 +546,9 @@ impl HashesOrTransactionInfos { pub fn contains_tx(&self, hash: H256) -> bool { match self { HashesOrTransactionInfos::Hashes(hashes) => hashes.iter().any(|h256| *h256 == hash), - HashesOrTransactionInfos::TransactionInfos(transaction_infos) => - transaction_infos.iter().any(|ti| ti.hash == hash), + HashesOrTransactionInfos::TransactionInfos(transaction_infos) => { + transaction_infos.iter().any(|ti| ti.hash == hash) + }, } } } diff --git a/bizinikiwi/pezframe/revive/src/evm/api/signature.rs b/bizinikiwi/pezframe/revive/src/evm/api/signature.rs index e53137e5..0c59446b 100644 --- a/bizinikiwi/pezframe/revive/src/evm/api/signature.rs +++ b/bizinikiwi/pezframe/revive/src/evm/api/signature.rs @@ -40,16 +40,21 @@ impl TransactionUnsigned { /// Extract the unsigned transaction from a signed transaction. pub fn from_signed(tx: TransactionSigned) -> Self { match tx { - TransactionSigned::TransactionLegacySigned(signed) => - Self::TransactionLegacyUnsigned(signed.transaction_legacy_unsigned), - TransactionSigned::Transaction7702Signed(signed) => - Self::Transaction7702Unsigned(signed.transaction_7702_unsigned), - TransactionSigned::Transaction4844Signed(signed) => - Self::Transaction4844Unsigned(signed.transaction_4844_unsigned), - TransactionSigned::Transaction1559Signed(signed) => - Self::Transaction1559Unsigned(signed.transaction_1559_unsigned), - TransactionSigned::Transaction2930Signed(signed) => - Self::Transaction2930Unsigned(signed.transaction_2930_unsigned), + TransactionSigned::TransactionLegacySigned(signed) => { + Self::TransactionLegacyUnsigned(signed.transaction_legacy_unsigned) + }, + TransactionSigned::Transaction7702Signed(signed) => { + Self::Transaction7702Unsigned(signed.transaction_7702_unsigned) + }, + TransactionSigned::Transaction4844Signed(signed) => { + Self::Transaction4844Unsigned(signed.transaction_4844_unsigned) + }, + TransactionSigned::Transaction1559Signed(signed) => { + Self::Transaction1559Unsigned(signed.transaction_1559_unsigned) + }, + TransactionSigned::Transaction2930Signed(signed) => { + Self::Transaction2930Unsigned(signed.transaction_2930_unsigned) + }, } } @@ -60,7 +65,7 @@ impl TransactionUnsigned { let recovery_id = signature[64]; match self { - TransactionUnsigned::Transaction7702Unsigned(transaction_7702_unsigned) => + TransactionUnsigned::Transaction7702Unsigned(transaction_7702_unsigned) => { Transaction7702Signed { transaction_7702_unsigned, r, @@ -68,8 +73,9 @@ impl TransactionUnsigned { v: None, y_parity: U256::from(recovery_id), } - .into(), - TransactionUnsigned::Transaction2930Unsigned(transaction_2930_unsigned) => + .into() + }, + TransactionUnsigned::Transaction2930Unsigned(transaction_2930_unsigned) => { Transaction2930Signed { transaction_2930_unsigned, r, @@ -77,8 +83,9 @@ impl TransactionUnsigned { v: None, y_parity: U256::from(recovery_id), } - .into(), - TransactionUnsigned::Transaction1559Unsigned(transaction_1559_unsigned) => + .into() + }, + TransactionUnsigned::Transaction1559Unsigned(transaction_1559_unsigned) => { Transaction1559Signed { transaction_1559_unsigned, r, @@ -86,16 +93,18 @@ impl TransactionUnsigned { v: None, y_parity: U256::from(recovery_id), } - .into(), + .into() + }, - TransactionUnsigned::Transaction4844Unsigned(transaction_4844_unsigned) => + TransactionUnsigned::Transaction4844Unsigned(transaction_4844_unsigned) => { Transaction4844Signed { transaction_4844_unsigned, r, s, y_parity: U256::from(recovery_id), } - .into(), + .into() + }, TransactionUnsigned::TransactionLegacyUnsigned(transaction_legacy_unsigned) => { let v = transaction_legacy_unsigned diff --git a/bizinikiwi/pezframe/revive/src/evm/block_hash/block_builder.rs b/bizinikiwi/pezframe/revive/src/evm/block_hash/block_builder.rs index 93abc93d..23062543 100644 --- a/bizinikiwi/pezframe/revive/src/evm/block_hash/block_builder.rs +++ b/bizinikiwi/pezframe/revive/src/evm/block_hash/block_builder.rs @@ -321,10 +321,10 @@ mod test { // Each mask in these vectors holds a u16. let masks_len = (hb.state_masks.len() + hb.tree_masks.len() + hb.hash_masks.len()) * 2; - let _size = hb.key.len() + - hb.value.as_slice().len() + - hb.stack.len() * 33 + - masks_len + hb.rlp_buf.len(); + let _size = hb.key.len() + + hb.value.as_slice().len() + + hb.stack.len() * 33 + + masks_len + hb.rlp_buf.len(); } hb.root().0.into() diff --git a/bizinikiwi/pezframe/revive/src/evm/block_hash/hash_builder.rs b/bizinikiwi/pezframe/revive/src/evm/block_hash/hash_builder.rs index ef4e2f7b..42a52eb3 100644 --- a/bizinikiwi/pezframe/revive/src/evm/block_hash/hash_builder.rs +++ b/bizinikiwi/pezframe/revive/src/evm/block_hash/hash_builder.rs @@ -300,15 +300,16 @@ impl IncrementalHashBuilder { #[cfg(test)] fn calculate_current_size(&self) -> usize { // Each mask in these vectors holds a u16. - let masks_len = (self.hash_builder.state_masks.len() + - self.hash_builder.tree_masks.len() + - self.hash_builder.hash_masks.len()) * - 2; + let masks_len = (self.hash_builder.state_masks.len() + + self.hash_builder.tree_masks.len() + + self.hash_builder.hash_masks.len()) + * 2; - self.hash_builder.key.len() + - self.hash_builder.value.as_slice().len() + - self.hash_builder.stack.len() * 33 + - masks_len + self.hash_builder.rlp_buf.len() + self.hash_builder.key.len() + + self.hash_builder.value.as_slice().len() + + self.hash_builder.stack.len() * 33 + + masks_len + + self.hash_builder.rlp_buf.len() } /// Update accounting metrics after processing data. @@ -415,14 +416,15 @@ impl IncrementalHashBuilderIR { // Vector metadata overhead (capacity info, etc.) let vec_overhead = 8 * core::mem::size_of::(); // 8 Vec structures - fixed_size + - key_size + builder_value_size + - stack_size + - state_masks_size + - tree_masks_size + - hash_masks_size + - rlp_buf_size + - vec_overhead + fixed_size + + key_size + + builder_value_size + + stack_size + + state_masks_size + + tree_masks_size + + hash_masks_size + + rlp_buf_size + + vec_overhead } } diff --git a/bizinikiwi/pezframe/revive/src/evm/block_hash/receipt.rs b/bizinikiwi/pezframe/revive/src/evm/block_hash/receipt.rs index 63c04c5a..ebfc221b 100644 --- a/bizinikiwi/pezframe/revive/src/evm/block_hash/receipt.rs +++ b/bizinikiwi/pezframe/revive/src/evm/block_hash/receipt.rs @@ -84,9 +84,9 @@ impl AccumulateReceipt { // Account for the size of the list header. let topics_list_header_length = topics_len + rlp::length_of_length(topics_len); // Compute the total payload length of the log. - let payload_length = rlp::Encodable::length(&contract.0) + - rlp::Encodable::length(&data) + - topics_list_header_length; + let payload_length = rlp::Encodable::length(&contract.0) + + rlp::Encodable::length(&data) + + topics_list_header_length; let header = rlp::Header { list: true, payload_length }; header.encode(&mut self.encoding); @@ -112,10 +112,10 @@ impl AccumulateReceipt { let header = rlp::Header { list: true, - payload_length: rlp::Encodable::length(&status) + - rlp::Encodable::length(&gas) + - rlp::Encodable::length(&bloom.bloom) + - list_header_length, + payload_length: rlp::Encodable::length(&status) + + rlp::Encodable::length(&gas) + + rlp::Encodable::length(&bloom.bloom) + + list_header_length, }; let mut encoded = transaction_type; diff --git a/bizinikiwi/pezframe/revive/src/evm/block_storage.rs b/bizinikiwi/pezframe/revive/src/evm/block_storage.rs index 35ba0b6d..dc95d619 100644 --- a/bizinikiwi/pezframe/revive/src/evm/block_storage.rs +++ b/bizinikiwi/pezframe/revive/src/evm/block_storage.rs @@ -158,8 +158,9 @@ pub fn with_ethereum_context( with_transaction(|| -> TransactionOutcome> { let EthereumCallResult { receipt_gas_info, result } = call(); match result { - Ok(post_info) => - TransactionOutcome::Commit(Ok((None, receipt_gas_info, post_info))), + Ok(post_info) => { + TransactionOutcome::Commit(Ok((None, receipt_gas_info, post_info))) + }, Err(err) => TransactionOutcome::Rollback(Ok(( Some(err.error), receipt_gas_info, diff --git a/bizinikiwi/pezframe/revive/src/evm/runtime.rs b/bizinikiwi/pezframe/revive/src/evm/runtime.rs index 88ed273b..b4c24e04 100644 --- a/bizinikiwi/pezframe/revive/src/evm/runtime.rs +++ b/bizinikiwi/pezframe/revive/src/evm/runtime.rs @@ -285,9 +285,9 @@ pub trait EthExtra { // Check transaction type and reject unsupported transaction types match &tx { - crate::evm::api::TransactionSigned::Transaction1559Signed(_) | - crate::evm::api::TransactionSigned::Transaction2930Signed(_) | - crate::evm::api::TransactionSigned::TransactionLegacySigned(_) => { + crate::evm::api::TransactionSigned::Transaction1559Signed(_) + | crate::evm::api::TransactionSigned::Transaction2930Signed(_) + | crate::evm::api::TransactionSigned::TransactionLegacySigned(_) => { // Supported transaction types, continue processing }, crate::evm::api::TransactionSigned::Transaction7702Signed(_) => { @@ -542,11 +542,11 @@ mod test { transaction_encoded, effective_gas_price, encoded_len, - }) if dest == tx.to.unwrap() && - value == tx.value.unwrap_or_default().as_u64().into() && - data == tx.input.to_vec() && - transaction_encoded == signed_transaction.signed_payload() && - effective_gas_price == expected_effective_gas_price => + }) if dest == tx.to.unwrap() + && value == tx.value.unwrap_or_default().as_u64().into() + && data == tx.input.to_vec() + && transaction_encoded == signed_transaction.signed_payload() + && effective_gas_price == expected_effective_gas_price => { assert_eq!(encoded_len, expected_encoded_len); assert!( @@ -581,11 +581,11 @@ mod test { transaction_encoded, effective_gas_price, encoded_len, - }) if value == expected_value && - code == expected_code && - data == expected_data && - transaction_encoded == signed_transaction.signed_payload() && - effective_gas_price == expected_effective_gas_price => + }) if value == expected_value + && code == expected_code + && data == expected_data + && transaction_encoded == signed_transaction.signed_payload() + && effective_gas_price == expected_effective_gas_price => { assert_eq!(encoded_len, expected_encoded_len); assert!( diff --git a/bizinikiwi/pezframe/revive/src/evm/tracing/call_tracing.rs b/bizinikiwi/pezframe/revive/src/evm/tracing/call_tracing.rs index c1ec7b8c..6b209700 100644 --- a/bizinikiwi/pezframe/revive/src/evm/tracing/call_tracing.rs +++ b/bizinikiwi/pezframe/revive/src/evm/tracing/call_tracing.rs @@ -200,8 +200,9 @@ impl Gas> Tracing trace.gas_used = (self.gas_mapper)(gas_used); trace.error = match error { - DispatchError::Module(pezsp_runtime::ModuleError { message, .. }) => - Some(message.unwrap_or_default().to_string()), + DispatchError::Module(pezsp_runtime::ModuleError { message, .. }) => { + Some(message.unwrap_or_default().to_string()) + }, _ => Some(format!("{:?}", error)), }; diff --git a/bizinikiwi/pezframe/revive/src/evm/tracing/prestate_tracing.rs b/bizinikiwi/pezframe/revive/src/evm/tracing/prestate_tracing.rs index a87e3293..461135a1 100644 --- a/bizinikiwi/pezframe/revive/src/evm/tracing/prestate_tracing.rs +++ b/bizinikiwi/pezframe/revive/src/evm/tracing/prestate_tracing.rs @@ -77,10 +77,10 @@ where let include_code = !self.config.disable_code; let is_empty = |info: &PrestateTraceInfo| { - !info.storage.values().any(|v| v.is_some()) && - info.balance.is_none() && - info.nonce.is_none() && - info.code.is_none() + !info.storage.values().any(|v| v.is_some()) + && info.balance.is_none() + && info.nonce.is_none() + && info.code.is_none() }; if self.config.diff_mode { diff --git a/bizinikiwi/pezframe/revive/src/exec.rs b/bizinikiwi/pezframe/revive/src/exec.rs index b3cfd0e4..16c41ef7 100644 --- a/bizinikiwi/pezframe/revive/src/exec.rs +++ b/bizinikiwi/pezframe/revive/src/exec.rs @@ -1005,12 +1005,13 @@ where // is a delegate call or not let mut contract = match (cached_info, &precompile) { (Some(info), _) => CachedContract::Cached(info), - (None, None) => + (None, None) => { if let Some(info) = AccountInfo::::load_contract(&address) { CachedContract::Cached(info) } else { return Ok(None); - }, + } + }, (None, Some(precompile)) if precompile.has_contract_info() => { log::trace!(target: LOG_TARGET, "found precompile for address {address:?}"); if let Some(info) = AccountInfo::::load_contract(&address) { @@ -1287,9 +1288,9 @@ where // - Only when not delegate calling we are executing in the context of the pre-compile. // Pre-compiles itself cannot delegate call. if let Some(precompile) = executable.as_precompile() { - if precompile.has_contract_info() && - frame.delegate.is_none() && - !>::account_exists(account_id) + if precompile.has_contract_info() + && frame.delegate.is_none() + && !>::account_exists(account_id) { // prefix matching pre-compiles cannot have a contract info // hence we only mint once per pre-compile @@ -1305,10 +1306,12 @@ where .unwrap_or_default(); let mut output = match executable { - ExecutableOrPrecompile::Executable(executable) => - executable.execute(self, entry_point, input_data), - ExecutableOrPrecompile::Precompile { instance, .. } => - instance.call(input_data, self), + ExecutableOrPrecompile::Executable(executable) => { + executable.execute(self, entry_point, input_data) + }, + ExecutableOrPrecompile::Precompile { instance, .. } => { + instance.call(input_data, self) + }, } .and_then(|output| { if u32::try_from(output.data.len()) @@ -1337,8 +1340,8 @@ where // Only keep return data for tracing and for dry runs. // When a dry-run simulates contract deployment, keep the execution result's // data. - let data = if crate::tracing::if_tracing(|_| {}).is_none() && - self.exec_config.is_dry_run.is_none() + let data = if crate::tracing::if_tracing(|_| {}).is_none() + && self.exec_config.is_dry_run.is_none() { core::mem::replace(&mut output.data, Default::default()) } else { @@ -1389,8 +1392,9 @@ where do_transaction() }; match &output { - Ok(result) if !result.did_revert() => - TransactionOutcome::Commit(Ok((true, output))), + Ok(result) if !result.did_revert() => { + TransactionOutcome::Commit(Ok((true, output))) + }, _ => TransactionOutcome::Rollback(Ok((false, output))), } }); diff --git a/bizinikiwi/pezframe/revive/src/lib.rs b/bizinikiwi/pezframe/revive/src/lib.rs index d9760dd3..7c670b35 100644 --- a/bizinikiwi/pezframe/revive/src/lib.rs +++ b/bizinikiwi/pezframe/revive/src/lib.rs @@ -1628,7 +1628,7 @@ impl Pezpallet { storage_deposit_limit.saturating_reduce(upload_deposit); (executable, upload_deposit) }, - Code::Upload(code) => + Code::Upload(code) => { if T::AllowEVMBytecode::get() { ensure!(data.is_empty(), >::EvmConstructorNonEmptyData); let origin = T::UploadOrigin::ensure_origin(origin)?; @@ -1636,7 +1636,8 @@ impl Pezpallet { (executable, Default::default()) } else { return Err(>::CodeRejected.into()); - }, + } + }, Code::Existing(code_hash) => { let executable = ContractBlob::from_storage(code_hash, &mut gas_meter)?; ensure!(executable.code_info().is_pvm(), >::EvmConstructedFromHash); @@ -2044,8 +2045,9 @@ impl Pezpallet { Self::evm_gas_from_weight as fn(Weight) -> U256, ) .into(), - TracerType::PrestateTracer(config) => - PrestateTracer::new(config.unwrap_or_default()).into(), + TracerType::PrestateTracer(config) => { + PrestateTracer::new(config.unwrap_or_default()).into() + }, } } @@ -2420,8 +2422,8 @@ impl Pezpallet { else { return Ok(()); }; - if exec::is_precompile::>(&address) || - >::is_contract(&address) + if exec::is_precompile::>(&address) + || >::is_contract(&address) { log::debug!( target: crate::LOG_TARGET, diff --git a/bizinikiwi/pezframe/revive/src/precompiles.rs b/bizinikiwi/pezframe/revive/src/precompiles.rs index 75613d43..09b2ab3a 100644 --- a/bizinikiwi/pezframe/revive/src/precompiles.rs +++ b/bizinikiwi/pezframe/revive/src/precompiles.rs @@ -312,8 +312,9 @@ impl Instance { let result = (self.function)(&self.address, input, env); match result { Ok(data) => Ok(ExecReturnValue { flags: ReturnFlags::empty(), data }), - Err(Error::Revert(msg)) => - Ok(ExecReturnValue { flags: ReturnFlags::REVERT, data: msg.abi_encode() }), + Err(Error::Revert(msg)) => { + Ok(ExecReturnValue { flags: ReturnFlags::REVERT, data: msg.abi_encode() }) + }, Err(Error::Panic(kind)) => Ok(ExecReturnValue { flags: ReturnFlags::REVERT, data: Panic::from(kind).abi_encode(), diff --git a/bizinikiwi/pezframe/revive/src/precompiles/builtin/storage.rs b/bizinikiwi/pezframe/revive/src/precompiles/builtin/storage.rs index 31fdd771..dc6b6ef5 100644 --- a/bizinikiwi/pezframe/revive/src/precompiles/builtin/storage.rs +++ b/bizinikiwi/pezframe/revive/src/precompiles/builtin/storage.rs @@ -56,7 +56,9 @@ impl BuiltinPrecompile for Storage { match input { IStorageCalls::clearStorage(_) | IStorageCalls::takeStorage(_) if env.is_read_only() => - Err(Error::Error(crate::Error::::StateChangeDenied.into())), + { + Err(Error::Error(crate::Error::::StateChangeDenied.into())) + }, IStorageCalls::clearStorage(IStorage::clearStorageCall { flags, key, isFixedKey }) => { let transient = is_transient(*flags) diff --git a/bizinikiwi/pezframe/revive/src/precompiles/builtin/system.rs b/bizinikiwi/pezframe/revive/src/precompiles/builtin/system.rs index 2873946f..b6244840 100644 --- a/bizinikiwi/pezframe/revive/src/precompiles/builtin/system.rs +++ b/bizinikiwi/pezframe/revive/src/precompiles/builtin/system.rs @@ -44,8 +44,9 @@ impl BuiltinPrecompile for System { ) -> Result, Error> { use ISystem::ISystemCalls; match input { - ISystemCalls::terminate(_) if env.is_read_only() => - Err(crate::Error::::StateChangeDenied.into()), + ISystemCalls::terminate(_) if env.is_read_only() => { + Err(crate::Error::::StateChangeDenied.into()) + }, ISystemCalls::hashBlake256(ISystem::hashBlake256Call { input }) => { env.gas_meter_mut().charge(RuntimeCosts::HashBlake256(input.len() as u32))?; let output = pezsp_io::hashing::blake2_256(input.as_bytes_ref()); diff --git a/bizinikiwi/pezframe/revive/src/primitives.rs b/bizinikiwi/pezframe/revive/src/primitives.rs index 1ca60c39..7adf081c 100644 --- a/bizinikiwi/pezframe/revive/src/primitives.rs +++ b/bizinikiwi/pezframe/revive/src/primitives.rs @@ -282,18 +282,20 @@ where match (self, rhs) { (Charge(lhs), Charge(rhs)) => Charge(lhs.saturating_add(*rhs)), (Refund(lhs), Refund(rhs)) => Refund(lhs.saturating_add(*rhs)), - (Charge(lhs), Refund(rhs)) => + (Charge(lhs), Refund(rhs)) => { if lhs >= rhs { Charge(lhs.saturating_sub(*rhs)) } else { Refund(rhs.saturating_sub(*lhs)) - }, - (Refund(lhs), Charge(rhs)) => + } + }, + (Refund(lhs), Charge(rhs)) => { if lhs > rhs { Refund(lhs.saturating_sub(*rhs)) } else { Charge(rhs.saturating_sub(*lhs)) - }, + } + }, } } @@ -303,18 +305,20 @@ where match (self, rhs) { (Charge(lhs), Refund(rhs)) => Charge(lhs.saturating_add(*rhs)), (Refund(lhs), Charge(rhs)) => Refund(lhs.saturating_add(*rhs)), - (Charge(lhs), Charge(rhs)) => + (Charge(lhs), Charge(rhs)) => { if lhs >= rhs { Charge(lhs.saturating_sub(*rhs)) } else { Refund(rhs.saturating_sub(*lhs)) - }, - (Refund(lhs), Refund(rhs)) => + } + }, + (Refund(lhs), Refund(rhs)) => { if lhs > rhs { Refund(lhs.saturating_sub(*rhs)) } else { Charge(rhs.saturating_sub(*lhs)) - }, + } + }, } } diff --git a/bizinikiwi/pezframe/revive/src/storage.rs b/bizinikiwi/pezframe/revive/src/storage.rs index 652c93e2..6f077ada 100644 --- a/bizinikiwi/pezframe/revive/src/storage.rs +++ b/bizinikiwi/pezframe/revive/src/storage.rs @@ -133,8 +133,9 @@ impl From for AccountIdOrAddress { impl AccountIdOrAddress { pub fn address(&self) -> H160 { match self { - AccountIdOrAddress::AccountId(id) => - >::to_address(id), + AccountIdOrAddress::AccountId(id) => { + >::to_address(id) + }, AccountIdOrAddress::Address(address) => *address, } } @@ -334,12 +335,13 @@ impl ContractInfo { let mut diff = meter::Diff::default(); let key_len = key.len() as u32; match (old_len, new_value.as_ref().map(|v| v.len() as u32)) { - (Some(old_len), Some(new_len)) => + (Some(old_len), Some(new_len)) => { if new_len > old_len { diff.bytes_added = new_len - old_len; } else { diff.bytes_removed = old_len - new_len; - }, + } + }, (None, Some(new_len)) => { diff.bytes_added = new_len.saturating_add(key_len); diff.items_added = 1; @@ -402,8 +404,8 @@ impl ContractInfo { /// of those keys can be deleted from the deletion queue given the supplied weight limit. pub fn deletion_budget(meter: &WeightMeter) -> (Weight, u32) { let base_weight = T::WeightInfo::on_process_deletion_queue_batch(); - let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1) - - T::WeightInfo::on_initialize_per_trie_key(0); + let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1) + - T::WeightInfo::on_initialize_per_trie_key(0); // `weight_per_key` being zero makes no sense and would constitute a failure to // benchmark properly. We opt for not removing any keys at all in this case. diff --git a/bizinikiwi/pezframe/revive/src/storage/meter.rs b/bizinikiwi/pezframe/revive/src/storage/meter.rs index 8a1a624e..86361445 100644 --- a/bizinikiwi/pezframe/revive/src/storage/meter.rs +++ b/bizinikiwi/pezframe/revive/src/storage/meter.rs @@ -162,16 +162,20 @@ impl Diff { info.storage_items = info.storage_items.saturating_add(items_added).saturating_sub(items_removed); match &bytes_deposit { - Deposit::Charge(amount) => - info.storage_byte_deposit = info.storage_byte_deposit.saturating_add(*amount), - Deposit::Refund(amount) => - info.storage_byte_deposit = info.storage_byte_deposit.saturating_sub(*amount), + Deposit::Charge(amount) => { + info.storage_byte_deposit = info.storage_byte_deposit.saturating_add(*amount) + }, + Deposit::Refund(amount) => { + info.storage_byte_deposit = info.storage_byte_deposit.saturating_sub(*amount) + }, } match &items_deposit { - Deposit::Charge(amount) => - info.storage_item_deposit = info.storage_item_deposit.saturating_add(*amount), - Deposit::Refund(amount) => - info.storage_item_deposit = info.storage_item_deposit.saturating_sub(*amount), + Deposit::Charge(amount) => { + info.storage_item_deposit = info.storage_item_deposit.saturating_add(*amount) + }, + Deposit::Refund(amount) => { + info.storage_item_deposit = info.storage_item_deposit.saturating_sub(*amount) + }, } bytes_deposit.saturating_add(&items_deposit) @@ -368,8 +372,8 @@ where ) => { *last_amount = last_amount.saturating_add(ch_amount); }, - (ContractState::Alive { amount }, ContractState::Terminated) | - (ContractState::Terminated, ContractState::Alive { amount }) => { + (ContractState::Alive { amount }, ContractState::Terminated) + | (ContractState::Terminated, ContractState::Alive { amount }) => { // undo all deposits made by a terminated contract self.total_deposit = self.total_deposit.saturating_sub(amount); last.state = ContractState::Terminated; diff --git a/bizinikiwi/pezframe/revive/src/tests.rs b/bizinikiwi/pezframe/revive/src/tests.rs index 99f3b5da..3a739451 100644 --- a/bizinikiwi/pezframe/revive/src/tests.rs +++ b/bizinikiwi/pezframe/revive/src/tests.rs @@ -177,8 +177,8 @@ pub mod test_utils { let code_info_len = CodeInfo::::max_encoded_len() as u64; // Calculate deposit to be reserved. // We add 2 storage items: one for code, other for code_info - DepositPerByte::get().saturating_mul(code_len as u64 + code_info_len) + - DepositPerItem::get().saturating_mul(2) + DepositPerByte::get().saturating_mul(code_len as u64 + code_info_len) + + DepositPerItem::get().saturating_mul(2) } pub fn ensure_stored(code_hash: pezsp_core::H256) -> usize { // Assert that code_info is stored @@ -421,8 +421,8 @@ impl SetWeightLimit for RuntimeCall { fn set_weight_limit(&mut self, weight_limit: Weight) -> Weight { match self { Self::Contracts( - Call::eth_call { gas_limit, .. } | - Call::eth_instantiate_with_code { gas_limit, .. }, + Call::eth_call { gas_limit, .. } + | Call::eth_instantiate_with_code { gas_limit, .. }, ) => { let old = *gas_limit; *gas_limit = weight_limit; diff --git a/bizinikiwi/pezframe/revive/src/tests/precompiles.rs b/bizinikiwi/pezframe/revive/src/tests/precompiles.rs index 5fb25088..ab0fda87 100644 --- a/bizinikiwi/pezframe/revive/src/tests/precompiles.rs +++ b/bizinikiwi/pezframe/revive/src/tests/precompiles.rs @@ -83,12 +83,15 @@ impl Precompile for NoInfo { match input { INoInfoCalls::identity(INoInfo::identityCall { number }) => Ok(number.abi_encode()), - INoInfoCalls::reverts(INoInfo::revertsCall { error }) => - Err(Error::Revert(error.as_str().into())), - INoInfoCalls::panics(INoInfo::panicsCall {}) => - Err(Error::Panic(PanicKind::Assert.into())), - INoInfoCalls::errors(INoInfo::errorsCall {}) => - Err(Error::Error(DispatchError::Other("precompile failed").into())), + INoInfoCalls::reverts(INoInfo::revertsCall { error }) => { + Err(Error::Revert(error.as_str().into())) + }, + INoInfoCalls::panics(INoInfo::panicsCall {}) => { + Err(Error::Panic(PanicKind::Assert.into())) + }, + INoInfoCalls::errors(INoInfo::errorsCall {}) => { + Err(Error::Error(DispatchError::Other("precompile failed").into())) + }, INoInfoCalls::consumeMaxGas(INoInfo::consumeMaxGasCall {}) => { env.gas_meter_mut().charge(MaxGasToken)?; Ok(Vec::new()) @@ -103,8 +106,9 @@ impl Precompile for NoInfo { let call = ::RuntimeCall::decode(&mut &call[..]).unwrap(); match call.dispatch(frame_origin) { Ok(_) => Ok(Vec::new()), - Err(e) => - Err(Error::Error(ExecError { error: e.error, origin: ErrorOrigin::Caller })), + Err(e) => { + Err(Error::Error(ExecError { error: e.error, origin: ErrorOrigin::Caller })) + }, } }, INoInfoCalls::passData(INoInfo::passDataCall { inputLen }) => { @@ -119,8 +123,9 @@ impl Precompile for NoInfo { )?; Ok(Vec::new()) }, - INoInfoCalls::returnData(INoInfo::returnDataCall { returnLen }) => - Ok(vec![42; *returnLen as usize]), + INoInfoCalls::returnData(INoInfo::returnDataCall { returnLen }) => { + Ok(vec![42; *returnLen as usize]) + }, } } } diff --git a/bizinikiwi/pezframe/revive/src/tests/pvm.rs b/bizinikiwi/pezframe/revive/src/tests/pvm.rs index 3b76c04a..3be9b24b 100644 --- a/bizinikiwi/pezframe/revive/src/tests/pvm.rs +++ b/bizinikiwi/pezframe/revive/src/tests/pvm.rs @@ -2946,8 +2946,8 @@ fn native_dependency_deposit_works() { .build_and_unwrap_result(); // Check updated storage_deposit due to code size changes - let deposit_diff = lockup_deposit_percent.mul_ceil(upload_deposit) - - lockup_deposit_percent.mul_ceil(get_code_deposit(&dummy_code_hash)); + let deposit_diff = lockup_deposit_percent.mul_ceil(upload_deposit) + - lockup_deposit_percent.mul_ceil(get_code_deposit(&dummy_code_hash)); let new_base_deposit = contract_base_deposit(&addr); assert_ne!(deposit_diff, 0); assert_eq!(base_deposit - new_base_deposit, deposit_diff); diff --git a/bizinikiwi/pezframe/revive/src/vm/evm.rs b/bizinikiwi/pezframe/revive/src/vm/evm.rs index c3c50ea7..395e03da 100644 --- a/bizinikiwi/pezframe/revive/src/vm/evm.rs +++ b/bizinikiwi/pezframe/revive/src/vm/evm.rs @@ -62,8 +62,8 @@ impl Token for EVMGas { impl ContractBlob { /// Create a new contract from EVM init code. pub fn from_evm_init_code(code: Vec, owner: AccountIdOf) -> Result { - if code.len() > revm::primitives::eip3860::MAX_INITCODE_SIZE && - !DebugSettings::is_unlimited_contract_size_allowed::() + if code.len() > revm::primitives::eip3860::MAX_INITCODE_SIZE + && !DebugSettings::is_unlimited_contract_size_allowed::() { return Err(>::BlobTooLarge.into()); } @@ -98,8 +98,8 @@ impl ContractBlob { code: Vec, owner: AccountIdOf, ) -> Result { - if code.len() > revm::primitives::eip170::MAX_CODE_SIZE && - !DebugSettings::is_unlimited_contract_size_allowed::() + if code.len() > revm::primitives::eip170::MAX_CODE_SIZE + && !DebugSettings::is_unlimited_contract_size_allowed::() { return Err(>::BlobTooLarge.into()); } diff --git a/bizinikiwi/pezframe/revive/src/vm/evm/instructions/arithmetic/i256.rs b/bizinikiwi/pezframe/revive/src/vm/evm/instructions/arithmetic/i256.rs index 2b4907d6..ed22bcdb 100644 --- a/bizinikiwi/pezframe/revive/src/vm/evm/instructions/arithmetic/i256.rs +++ b/bizinikiwi/pezframe/revive/src/vm/evm/instructions/arithmetic/i256.rs @@ -112,8 +112,8 @@ pub fn i256_div(mut first: U256, mut second: U256) -> U256 { // Two's complement only if the signs are different // Note: This condition has better codegen than an exhaustive match, as of #582 - if (first_sign == Sign::Minus && second_sign != Sign::Minus) || - (second_sign == Sign::Minus && first_sign != Sign::Minus) + if (first_sign == Sign::Minus && second_sign != Sign::Minus) + || (second_sign == Sign::Minus && first_sign != Sign::Minus) { two_compl(d) } else { diff --git a/bizinikiwi/pezframe/revive/src/vm/evm/instructions/contract.rs b/bizinikiwi/pezframe/revive/src/vm/evm/instructions/contract.rs index cbf7e8fb..af712fad 100644 --- a/bizinikiwi/pezframe/revive/src/vm/evm/instructions/contract.rs +++ b/bizinikiwi/pezframe/revive/src/vm/evm/instructions/contract.rs @@ -55,8 +55,8 @@ pub fn create( let mut code = Vec::new(); if len != 0 { // EIP-3860: Limit initcode - if len > revm::primitives::eip3860::MAX_INITCODE_SIZE && - !DebugSettings::is_unlimited_contract_size_allowed::() + if len > revm::primitives::eip3860::MAX_INITCODE_SIZE + && !DebugSettings::is_unlimited_contract_size_allowed::() { return ControlFlow::Break(Error::::BlobTooLarge.into()); } @@ -209,8 +209,9 @@ fn run_call<'a, E: Ext>( true, scheme.is_static_call(), ), - CallScheme::DelegateCall => - interpreter.ext.delegate_call(gas_limit, U256::MAX, callee, input), + CallScheme::DelegateCall => { + interpreter.ext.delegate_call(gas_limit, U256::MAX, callee, input) + }, CallScheme::CallCode => { unreachable!() }, diff --git a/bizinikiwi/pezframe/revive/src/vm/pvm.rs b/bizinikiwi/pezframe/revive/src/vm/pvm.rs index c0f2c049..4b401097 100644 --- a/bizinikiwi/pezframe/revive/src/vm/pvm.rs +++ b/bizinikiwi/pezframe/revive/src/vm/pvm.rs @@ -641,8 +641,9 @@ impl<'a, E: Ext, M: ?Sized + Memory> Runtime<'a, E, M> { let callee = memory.read_h160(callee_ptr)?; let precompile = >::get::(&callee.as_fixed_bytes()); match &precompile { - Some(precompile) if precompile.has_contract_info() => - self.charge_gas(RuntimeCosts::PrecompileWithInfoBase)?, + Some(precompile) if precompile.has_contract_info() => { + self.charge_gas(RuntimeCosts::PrecompileWithInfoBase)? + }, Some(_) => self.charge_gas(RuntimeCosts::PrecompileBase)?, None => self.charge_gas(call_type.cost())?, }; diff --git a/bizinikiwi/pezframe/revive/src/vm/pvm/env.rs b/bizinikiwi/pezframe/revive/src/vm/pvm/env.rs index edb4ad1d..59aaff44 100644 --- a/bizinikiwi/pezframe/revive/src/vm/pvm/env.rs +++ b/bizinikiwi/pezframe/revive/src/vm/pvm/env.rs @@ -137,8 +137,9 @@ impl<'a, E: Ext, M: PolkaVmInstance> Runtime<'a, E, M> { log::error!(target: LOG_TARGET, "polkavm execution error: {error}"); Some(Err(Error::::ExecutionFailed.into())) }, - Ok(Finished) => - Some(Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() })), + Ok(Finished) => { + Some(Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() })) + }, Ok(Trap) => Some(Err(Error::::ContractTrapped.into())), Ok(Segfault(_)) => Some(Err(Error::::ExecutionFailed.into())), Ok(NotEnoughGas) => Some(Err(Error::::OutOfGas.into())), @@ -163,11 +164,12 @@ impl<'a, E: Ext, M: PolkaVmInstance> Runtime<'a, E, M> { instance.write_output(return_value); None }, - Err(TrapReason::Return(ReturnData { flags, data })) => + Err(TrapReason::Return(ReturnData { flags, data })) => { match ReturnFlags::from_bits(flags) { None => Some(Err(Error::::InvalidCallFlags.into())), Some(flags) => Some(Ok(ExecReturnValue { flags, data })), - }, + } + }, Err(TrapReason::Termination) => Some(Ok(Default::default())), Err(TrapReason::SupervisorError(error)) => Some(Err(error.into())), } diff --git a/bizinikiwi/pezframe/revive/src/vm/runtime_costs.rs b/bizinikiwi/pezframe/revive/src/vm/runtime_costs.rs index bc014313..af163ce3 100644 --- a/bizinikiwi/pezframe/revive/src/vm/runtime_costs.rs +++ b/bizinikiwi/pezframe/revive/src/vm/runtime_costs.rs @@ -309,18 +309,20 @@ impl Token for RuntimeCosts { cost_args!(seal_call, 1, dust_transfer.into(), 0) }, CallInputCloned(len) => cost_args!(seal_call, 0, 0, len), - Instantiate { input_data_len, balance_transfer, dust_transfer } => + Instantiate { input_data_len, balance_transfer, dust_transfer } => { T::WeightInfo::seal_instantiate( balance_transfer.into(), dust_transfer.into(), input_data_len, - ), - Create { init_code_len, balance_transfer, dust_transfer } => + ) + }, + Create { init_code_len, balance_transfer, dust_transfer } => { T::WeightInfo::evm_instantiate( balance_transfer.into(), dust_transfer.into(), init_code_len, - ), + ) + }, HashSha256(len) => T::WeightInfo::sha2_256(len), Ripemd160(len) => T::WeightInfo::ripemd_160(len), HashKeccak256(len) => T::WeightInfo::seal_hash_keccak_256(len), @@ -330,8 +332,9 @@ impl Token for RuntimeCosts { P256Verify => T::WeightInfo::p256_verify(), Sr25519Verify(len) => T::WeightInfo::seal_sr25519_verify(len), Precompile(weight) => weight, - SetCodeHash { old_code_removed } => - T::WeightInfo::seal_set_code_hash(old_code_removed.into()), + SetCodeHash { old_code_removed } => { + T::WeightInfo::seal_set_code_hash(old_code_removed.into()) + }, EcdsaToEthAddress => T::WeightInfo::seal_ecdsa_to_eth_address(), GetImmutableData(len) => T::WeightInfo::seal_get_immutable_data(len), SetImmutableData(len) => T::WeightInfo::seal_set_immutable_data(len), diff --git a/bizinikiwi/pezframe/safe-mode/src/benchmarking.rs b/bizinikiwi/pezframe/safe-mode/src/benchmarking.rs index 3eff72d4..6d35da8b 100644 --- a/bizinikiwi/pezframe/safe-mode/src/benchmarking.rs +++ b/bizinikiwi/pezframe/safe-mode/src/benchmarking.rs @@ -100,8 +100,9 @@ mod benchmarks { assert_eq!( EnteredUntil::::get().unwrap(), - pezframe_system::Pezpallet::::block_number() + - 1u32.into() + T::ExtendDuration::get() + pezframe_system::Pezpallet::::block_number() + + 1u32.into() + + T::ExtendDuration::get() ); Ok(()) } diff --git a/bizinikiwi/pezframe/safe-mode/src/tests.rs b/bizinikiwi/pezframe/safe-mode/src/tests.rs index 4bf7a7fc..32ea7625 100644 --- a/bizinikiwi/pezframe/safe-mode/src/tests.rs +++ b/bizinikiwi/pezframe/safe-mode/src/tests.rs @@ -345,10 +345,10 @@ fn can_force_release_deposit_with_config_origin() { assert_ok!(SafeMode::enter(RuntimeOrigin::signed(0))); assert_ok!(SafeMode::extend(RuntimeOrigin::signed(1))); run_to( - mock::EnterDuration::get() + - mock::ExtendDuration::get() + - activated_and_extended_at_block + - 1, + mock::EnterDuration::get() + + mock::ExtendDuration::get() + + activated_and_extended_at_block + + 1, ); assert_ok!(SafeMode::force_release_deposit( @@ -498,10 +498,10 @@ fn can_slash_deposit_with_config_origin() { assert_ok!(SafeMode::enter(RuntimeOrigin::signed(0))); assert_ok!(SafeMode::extend(RuntimeOrigin::signed(1))); run_to( - mock::EnterDuration::get() + - mock::ExtendDuration::get() + - activated_and_extended_at_block + - 1, + mock::EnterDuration::get() + + mock::ExtendDuration::get() + + activated_and_extended_at_block + + 1, ); assert_ok!(SafeMode::force_slash_deposit( diff --git a/bizinikiwi/pezframe/scheduler/src/lib.rs b/bizinikiwi/pezframe/scheduler/src/lib.rs index 5e2a4964..f01fd273 100644 --- a/bizinikiwi/pezframe/scheduler/src/lib.rs +++ b/bizinikiwi/pezframe/scheduler/src/lib.rs @@ -443,9 +443,9 @@ pub mod pezpallet { fn integrity_test() { /// Calculate the maximum weight that a lookup of a given size can take. fn lookup_weight(s: usize) -> Weight { - T::WeightInfo::service_agendas_base() + - T::WeightInfo::service_agenda_base(T::MaxScheduledPerBlock::get()) + - T::WeightInfo::service_task(Some(s), true, true) + T::WeightInfo::service_agendas_base() + + T::WeightInfo::service_agenda_base(T::MaxScheduledPerBlock::get()) + + T::WeightInfo::service_task(Some(s), true, true) } let limit = pezsp_runtime::Perbill::from_percent(90) * T::MaximumWeight::get(); @@ -1408,10 +1408,11 @@ impl Pezpallet { } let wake = now.saturating_add(period); match Self::place_task(wake, task) { - Ok(new_address) => + Ok(new_address) => { if let Some(retry_config) = maybe_retry_config { Retries::::insert(new_address, retry_config); - }, + } + }, Err((_, task)) => { // TODO: Leave task in storage somewhere for it to be rescheduled // manually. @@ -1458,8 +1459,9 @@ impl Pezpallet { let dispatch_origin = origin.into(); let (maybe_actual_call_weight, result) = match call.dispatch(dispatch_origin) { Ok(post_info) => (post_info.actual_weight, Ok(())), - Err(error_and_info) => - (error_and_info.post_info.actual_weight, Err(error_and_info.error)), + Err(error_and_info) => { + (error_and_info.post_info.actual_weight, Err(error_and_info.error)) + }, }; let call_weight = maybe_actual_call_weight.unwrap_or(call_weight); let _ = weight.try_consume(base_weight); diff --git a/bizinikiwi/pezframe/scheduler/src/tests.rs b/bizinikiwi/pezframe/scheduler/src/tests.rs index c8809098..a73f08a4 100644 --- a/bizinikiwi/pezframe/scheduler/src/tests.rs +++ b/bizinikiwi/pezframe/scheduler/src/tests.rs @@ -1640,11 +1640,12 @@ fn on_initialize_weight_is_correct() { ::BlockNumberProvider::set_block_number(now); assert_eq!( Scheduler::on_initialize(42), // block number unused - TestWeightInfo::service_agendas_base() + - TestWeightInfo::service_agenda_base(1) + - ::service_task(None, true, true) + - TestWeightInfo::execute_dispatch_unsigned() + - call_weight + Weight::from_parts(4, 0) + TestWeightInfo::service_agendas_base() + + TestWeightInfo::service_agenda_base(1) + + ::service_task(None, true, true) + + TestWeightInfo::execute_dispatch_unsigned() + + call_weight + + Weight::from_parts(4, 0) ); assert_eq!(IncompleteSince::::get(), Some(now + 1)); assert_eq!(logger::log(), vec![(root(), 2600u32)]); @@ -1654,14 +1655,16 @@ fn on_initialize_weight_is_correct() { ::BlockNumberProvider::set_block_number(now); assert_eq!( Scheduler::on_initialize(123), // block number unused - TestWeightInfo::service_agendas_base() + - TestWeightInfo::service_agenda_base(2) + - ::service_task(None, false, true) + - TestWeightInfo::execute_dispatch_unsigned() + - call_weight + Weight::from_parts(3, 0) + - ::service_task(None, false, false) + - TestWeightInfo::execute_dispatch_unsigned() + - call_weight + Weight::from_parts(2, 0) + TestWeightInfo::service_agendas_base() + + TestWeightInfo::service_agenda_base(2) + + ::service_task(None, false, true) + + TestWeightInfo::execute_dispatch_unsigned() + + call_weight + + Weight::from_parts(3, 0) + + ::service_task(None, false, false) + + TestWeightInfo::execute_dispatch_unsigned() + + call_weight + + Weight::from_parts(2, 0) ); assert_eq!(IncompleteSince::::get(), Some(now + 1)); assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]); @@ -1671,11 +1674,12 @@ fn on_initialize_weight_is_correct() { ::BlockNumberProvider::set_block_number(now); assert_eq!( Scheduler::on_initialize(555), // block number unused - TestWeightInfo::service_agendas_base() + - TestWeightInfo::service_agenda_base(1) + - ::service_task(None, true, false) + - TestWeightInfo::execute_dispatch_unsigned() + - call_weight + Weight::from_parts(1, 0) + TestWeightInfo::service_agendas_base() + + TestWeightInfo::service_agenda_base(1) + + ::service_task(None, true, false) + + TestWeightInfo::execute_dispatch_unsigned() + + call_weight + + Weight::from_parts(1, 0) ); assert_eq!(IncompleteSince::::get(), Some(now + 1)); assert_eq!( diff --git a/bizinikiwi/pezframe/scored-pool/src/lib.rs b/bizinikiwi/pezframe/scored-pool/src/lib.rs index a9f6b12d..c582933f 100644 --- a/bizinikiwi/pezframe/scored-pool/src/lib.rs +++ b/bizinikiwi/pezframe/scored-pool/src/lib.rs @@ -459,10 +459,12 @@ impl, I: 'static> Pezpallet { >::put(&new_members_bounded); match notify { - ChangeReceiver::MembershipInitialized => - T::MembershipInitialized::initialize_members(&new_members_bounded), - ChangeReceiver::MembershipChanged => - T::MembershipChanged::set_members_sorted(&new_members_bounded[..], &old_members[..]), + ChangeReceiver::MembershipInitialized => { + T::MembershipInitialized::initialize_members(&new_members_bounded) + }, + ChangeReceiver::MembershipChanged => { + T::MembershipChanged::set_members_sorted(&new_members_bounded[..], &old_members[..]) + }, } } diff --git a/bizinikiwi/pezframe/session/src/mock.rs b/bizinikiwi/pezframe/session/src/mock.rs index 1dc9f22e..3c365186 100644 --- a/bizinikiwi/pezframe/session/src/mock.rs +++ b/bizinikiwi/pezframe/session/src/mock.rs @@ -113,8 +113,8 @@ pub struct TestShouldEndSession; impl ShouldEndSession for TestShouldEndSession { fn should_end_session(now: u64) -> bool { let l = SessionLength::get(); - now % l == 0 || - ForceSessionEnd::mutate(|l| { + now % l == 0 + || ForceSessionEnd::mutate(|l| { let r = *l; *l = false; r diff --git a/bizinikiwi/pezframe/society/src/lib.rs b/bizinikiwi/pezframe/society/src/lib.rs index 19f075a1..306430a7 100644 --- a/bizinikiwi/pezframe/society/src/lib.rs +++ b/bizinikiwi/pezframe/society/src/lib.rs @@ -1608,9 +1608,9 @@ impl, I: 'static> Pezpallet { let approved = candidacy.tally.clear_approval(); let rejected = candidacy.tally.clear_rejection(); match (maybe_vote, approved, rejected) { - (None, _, _) | - (Some(Vote { approve: true, .. }), false, true) | - (Some(Vote { approve: false, .. }), true, false) => { + (None, _, _) + | (Some(Vote { approve: true, .. }), false, true) + | (Some(Vote { approve: false, .. }), true, false) => { // Can't do much if the punishment doesn't work out. if Self::strike_member(&skeptic).is_ok() { candidacy.skeptic_struck = true; @@ -1640,9 +1640,9 @@ impl, I: 'static> Pezpallet { // Check defender skeptic voted and that their vote was with the majority. let skeptic_vote = DefenderVotes::::get(round, &skeptic); match (skeptic_vote, tally.more_approvals(), tally.more_rejections()) { - (None, _, _) | - (Some(Vote { approve: true, .. }), false, true) | - (Some(Vote { approve: false, .. }), true, false) => { + (None, _, _) + | (Some(Vote { approve: true, .. }), false, true) + | (Some(Vote { approve: false, .. }), true, false) => { // Punish skeptic and challenge them next. let _ = Self::strike_member(&skeptic); let founder = Founder::::get(); @@ -1738,9 +1738,9 @@ impl, I: 'static> Pezpallet { bids.retain(|bid| { // We only accept a zero bid as the first selection. total_cost.saturating_accrue(bid.value); - let accept = selections < max_selections && - (!bid.value.is_zero() || selections == 0) && - total_cost <= pot; + let accept = selections < max_selections + && (!bid.value.is_zero() || selections == 0) + && total_cost <= pot; if accept { let candidacy = Candidacy { round, @@ -1877,8 +1877,8 @@ impl, I: 'static> Pezpallet { let next_head = NextHead::::get() .filter(|old| { - old.round > candidacy.round || - old.round == candidacy.round && old.bid < candidacy.bid + old.round > candidacy.round + || old.round == candidacy.round && old.bid < candidacy.bid }) .unwrap_or_else(|| IntakeRecord { who: candidate.clone(), diff --git a/bizinikiwi/pezframe/society/src/migrations.rs b/bizinikiwi/pezframe/society/src/migrations.rs index 2b20bc28..f363edb3 100644 --- a/bizinikiwi/pezframe/society/src/migrations.rs +++ b/bizinikiwi/pezframe/society/src/migrations.rs @@ -282,8 +282,8 @@ pub fn from_original, I: Instance + 'static>( // The founder must be the first member in Society V2. If we find the founder not in index // zero, we swap it with the first member. - if member == Founder::::get().defensive_ok_or("founder must always be set")? && - member_count > 0 + if member == Founder::::get().defensive_ok_or("founder must always be set")? + && member_count > 0 { let member_to_swap = MemberByIndex::::get(0) .defensive_ok_or("member_count > 0, we must have at least 1 member")?; diff --git a/bizinikiwi/pezframe/society/src/mock.rs b/bizinikiwi/pezframe/society/src/mock.rs index a945fee8..38d4d18e 100644 --- a/bizinikiwi/pezframe/society/src/mock.rs +++ b/bizinikiwi/pezframe/society/src/mock.rs @@ -230,8 +230,9 @@ pub fn next_intake() { Period::Voting { more, .. } => System::run_to_block::( System::block_number() + more + claim_period, ), - Period::Claim { more, .. } => - System::run_to_block::(System::block_number() + more), + Period::Claim { more, .. } => { + System::run_to_block::(System::block_number() + more) + }, Period::Intake { .. } => {}, } } diff --git a/bizinikiwi/pezframe/staking-async/ah-client/src/lib.rs b/bizinikiwi/pezframe/staking-async/ah-client/src/lib.rs index 6fb50740..174f9009 100644 --- a/bizinikiwi/pezframe/staking-async/ah-client/src/lib.rs +++ b/bizinikiwi/pezframe/staking-async/ah-client/src/lib.rs @@ -794,10 +794,12 @@ pub mod pezpallet { // delegate to the fallback implementation. T::Fallback::on_offence(offenders, slash_fraction, slash_session) }, - OperatingMode::Buffered => - Self::on_offence_buffered(offenders, slash_fraction, slash_session), - OperatingMode::Active => - Self::on_offence_active(offenders, slash_fraction, slash_session), + OperatingMode::Buffered => { + Self::on_offence_buffered(offenders, slash_fraction, slash_session) + }, + OperatingMode::Active => { + Self::on_offence_active(offenders, slash_fraction, slash_session) + }, } } } diff --git a/bizinikiwi/pezframe/staking-async/ahm-test/src/ah/mock.rs b/bizinikiwi/pezframe/staking-async/ahm-test/src/ah/mock.rs index 58834bbf..2964b40e 100644 --- a/bizinikiwi/pezframe/staking-async/ahm-test/src/ah/mock.rs +++ b/bizinikiwi/pezframe/staking-async/ahm-test/src/ah/mock.rs @@ -90,8 +90,8 @@ pub(crate) fn roll_until_next_active(mut end_index: SessionIndex) -> Vec::planned_era(); let active_era = pezpallet_staking_async::session_rotation::Rotator::::active_era(); - while pezpallet_staking_async::session_rotation::Rotator::::planned_era() == - planned_era + while pezpallet_staking_async::session_rotation::Rotator::::planned_era() + == planned_era { let report = SessionReport { end_index, diff --git a/bizinikiwi/pezframe/staking-async/ahm-test/src/lib.rs b/bizinikiwi/pezframe/staking-async/ahm-test/src/lib.rs index 83b64499..9de32a18 100644 --- a/bizinikiwi/pezframe/staking-async/ahm-test/src/lib.rs +++ b/bizinikiwi/pezframe/staking-async/ahm-test/src/lib.rs @@ -141,8 +141,8 @@ mod tests { // - staking-classic is active on RC. rc::roll_until_matches( || { - staking_classic::ActiveEra::::get().map(|a| a.index).unwrap_or(0) == - 1 + staking_classic::ActiveEra::::get().map(|a| a.index).unwrap_or(0) + == 1 }, true, ); @@ -192,8 +192,8 @@ mod tests { // era. rc::roll_until_matches( || { - pezpallet_session::CurrentIndex::::get() == - current_session + ah::SessionsPerEra::get() + 1 + pezpallet_session::CurrentIndex::::get() + == current_session + ah::SessionsPerEra::get() + 1 }, true, ); @@ -221,8 +221,8 @@ mod tests { ); assert_eq!( ah_client::ValidatorPoints::::get(&11), - (migration_start_block_number - pre_migration_block_number) as u32 * - <::PointsPerBlock as Get>::get() + (migration_start_block_number - pre_migration_block_number) as u32 + * <::PointsPerBlock as Get>::get() ); // Verify buffered mode doesn't send anything to AH diff --git a/bizinikiwi/pezframe/staking-async/rc-client/src/lib.rs b/bizinikiwi/pezframe/staking-async/rc-client/src/lib.rs index edc14169..38185bae 100644 --- a/bizinikiwi/pezframe/staking-async/rc-client/src/lib.rs +++ b/bizinikiwi/pezframe/staking-async/rc-client/src/lib.rs @@ -351,8 +351,8 @@ impl SessionReport { /// Merge oneself with another instance. pub fn merge(mut self, other: Self) -> Result { - if self.end_index != other.end_index || - self.activation_timestamp != other.activation_timestamp + if self.end_index != other.end_index + || self.activation_timestamp != other.activation_timestamp { // Must be some bug -- don't merge. return Err(UnexpectedKind::SessionReportIntegrityFailed); @@ -513,14 +513,17 @@ where { Ok((_ticket, price)) => { log::debug!(target: "runtime::staking-async::xcm", "📨 validated, price: {price:?}"); - return Ok(current_messages.into_iter().map(ToXcm::convert).collect::>()); + return Ok(current_messages + .into_iter() + .map(ToXcm::convert) + .collect::>()); }, Err(SendError::ExceedsMaxMessageSize) => { log::debug!(target: "runtime::staking-async::xcm", "📨 ExceedsMaxMessageSize -- reducing chunk_size"); chunk_size = chunk_size.saturating_div(2); steps += 1; - if maybe_max_steps.is_some_and(|max_steps| steps > max_steps) || - chunk_size.is_zero() + if maybe_max_steps.is_some_and(|max_steps| steps > max_steps) + || chunk_size.is_zero() { log::error!(target: "runtime::staking-async::xcm", "📨 Exceeded max steps or chunk_size = 0"); return Err(SendError::ExceedsMaxMessageSize); diff --git a/bizinikiwi/pezframe/staking-async/runtimes/rc/src/genesis_config_presets.rs b/bizinikiwi/pezframe/staking-async/runtimes/rc/src/genesis_config_presets.rs index 1306b6b8..4e95553d 100644 --- a/bizinikiwi/pezframe/staking-async/runtimes/rc/src/genesis_config_presets.rs +++ b/bizinikiwi/pezframe/staking-async/runtimes/rc/src/genesis_config_presets.rs @@ -129,9 +129,9 @@ fn default_teyrchains_host_configuration( allowed_ancestry_len: 0, }, node_features: bitvec::vec::BitVec::from_element( - (1u8 << (FeatureIndex::ElasticScalingMVP as usize)) | - (1u8 << (FeatureIndex::EnableAssignmentsV2 as usize)) | - (1u8 << (FeatureIndex::CandidateReceiptV2 as usize)), + (1u8 << (FeatureIndex::ElasticScalingMVP as usize)) + | (1u8 << (FeatureIndex::EnableAssignmentsV2 as usize)) + | (1u8 << (FeatureIndex::CandidateReceiptV2 as usize)), ), scheduler_params: SchedulerParams { lookahead: 3, diff --git a/bizinikiwi/pezframe/staking-async/runtimes/rc/src/lib.rs b/bizinikiwi/pezframe/staking-async/runtimes/rc/src/lib.rs index 209521c3..c82bfcdf 100644 --- a/bizinikiwi/pezframe/staking-async/runtimes/rc/src/lib.rs +++ b/bizinikiwi/pezframe/staking-async/runtimes/rc/src/lib.rs @@ -1384,33 +1384,33 @@ impl InstanceFilter for ProxyType { ProxyType::Governance => matches!( c, // OpenGov calls - RuntimeCall::ConvictionVoting(..) | - RuntimeCall::Referenda(..) | - RuntimeCall::Whitelist(..) + RuntimeCall::ConvictionVoting(..) + | RuntimeCall::Referenda(..) + | RuntimeCall::Whitelist(..) ), ProxyType::IdentityJudgement => matches!( c, - RuntimeCall::Identity(pezpallet_identity::Call::provide_judgement { .. }) | - RuntimeCall::Utility(..) + RuntimeCall::Identity(pezpallet_identity::Call::provide_judgement { .. }) + | RuntimeCall::Utility(..) ), ProxyType::CancelProxy => { matches!(c, RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. })) }, ProxyType::Auction => matches!( c, - RuntimeCall::Auctions(..) | - RuntimeCall::Crowdloan(..) | - RuntimeCall::Registrar(..) | - RuntimeCall::Slots(..) + RuntimeCall::Auctions(..) + | RuntimeCall::Crowdloan(..) + | RuntimeCall::Registrar(..) + | RuntimeCall::Slots(..) ), ProxyType::ParaRegistration => matches!( c, - RuntimeCall::Registrar(paras_registrar::Call::reserve { .. }) | - RuntimeCall::Registrar(paras_registrar::Call::register { .. }) | - RuntimeCall::Utility(pezpallet_utility::Call::batch { .. }) | - RuntimeCall::Utility(pezpallet_utility::Call::batch_all { .. }) | - RuntimeCall::Utility(pezpallet_utility::Call::force_batch { .. }) | - RuntimeCall::Proxy(pezpallet_proxy::Call::remove_proxy { .. }) + RuntimeCall::Registrar(paras_registrar::Call::reserve { .. }) + | RuntimeCall::Registrar(paras_registrar::Call::register { .. }) + | RuntimeCall::Utility(pezpallet_utility::Call::batch { .. }) + | RuntimeCall::Utility(pezpallet_utility::Call::batch_all { .. }) + | RuntimeCall::Utility(pezpallet_utility::Call::force_batch { .. }) + | RuntimeCall::Proxy(pezpallet_proxy::Call::remove_proxy { .. }) ), } } diff --git a/bizinikiwi/pezframe/staking-async/runtimes/rc/src/weights/xcm/mod.rs b/bizinikiwi/pezframe/staking-async/runtimes/rc/src/weights/xcm/mod.rs index f7f4f43c..46b3d4f5 100644 --- a/bizinikiwi/pezframe/staking-async/runtimes/rc/src/weights/xcm/mod.rs +++ b/bizinikiwi/pezframe/staking-async/runtimes/rc/src/weights/xcm/mod.rs @@ -41,8 +41,9 @@ pub enum AssetTypes { impl From<&Asset> for AssetTypes { fn from(asset: &Asset) -> Self { match asset { - Asset { id: AssetId(Location { parents: 0, interior: Here }), .. } => - AssetTypes::Balances, + Asset { id: AssetId(Location { parents: 0, interior: Here }), .. } => { + AssetTypes::Balances + }, _ => AssetTypes::Unknown, } } @@ -70,8 +71,9 @@ impl WeighAssets for AssetFilter { // We don't support any NFTs on Zagros, so these two variants will always match // only 1 kind of fungible asset. Self::Wild(AllOf { .. } | AllOfCounted { .. }) => balances_weight, - Self::Wild(AllCounted(count)) => - balances_weight.saturating_mul(MAX_ASSETS.min(*count as u64)), + Self::Wild(AllCounted(count)) => { + balances_weight.saturating_mul(MAX_ASSETS.min(*count as u64)) + }, Self::Wild(All) => balances_weight.saturating_mul(MAX_ASSETS), } } diff --git a/bizinikiwi/pezframe/staking-async/runtimes/teyrchain/src/lib.rs b/bizinikiwi/pezframe/staking-async/runtimes/teyrchain/src/lib.rs index b924a1bf..f8c404d3 100644 --- a/bizinikiwi/pezframe/staking-async/runtimes/teyrchain/src/lib.rs +++ b/bizinikiwi/pezframe/staking-async/runtimes/teyrchain/src/lib.rs @@ -674,99 +674,99 @@ impl InstanceFilter for ProxyType { ProxyType::Any => true, ProxyType::NonTransfer => !matches!( c, - RuntimeCall::Balances { .. } | - RuntimeCall::Assets { .. } | - RuntimeCall::NftFractionalization { .. } | - RuntimeCall::Nfts { .. } | - RuntimeCall::Uniques { .. } + RuntimeCall::Balances { .. } + | RuntimeCall::Assets { .. } + | RuntimeCall::NftFractionalization { .. } + | RuntimeCall::Nfts { .. } + | RuntimeCall::Uniques { .. } ), ProxyType::CancelProxy => matches!( c, - RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Assets => { matches!( c, - RuntimeCall::Assets { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } | - RuntimeCall::NftFractionalization { .. } | - RuntimeCall::Nfts { .. } | - RuntimeCall::Uniques { .. } + RuntimeCall::Assets { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } + | RuntimeCall::NftFractionalization { .. } + | RuntimeCall::Nfts { .. } + | RuntimeCall::Uniques { .. } ) }, ProxyType::AssetOwner => matches!( c, - RuntimeCall::Assets(TrustBackedAssetsCall::create { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::start_destroy { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::destroy_accounts { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::destroy_approvals { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::finish_destroy { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::transfer_ownership { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::set_team { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::set_metadata { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::clear_metadata { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::set_min_balance { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::create { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::destroy { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::redeposit { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::transfer_ownership { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_team { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_collection_max_supply { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::lock_collection { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::create { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::destroy { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::transfer_ownership { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::set_team { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::set_metadata { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::set_attribute { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::set_collection_metadata { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::clear_metadata { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::clear_attribute { .. }) | - RuntimeCall::Uniques( + RuntimeCall::Assets(TrustBackedAssetsCall::create { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::start_destroy { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::destroy_accounts { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::destroy_approvals { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::finish_destroy { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::transfer_ownership { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::set_team { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::set_metadata { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::clear_metadata { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::set_min_balance { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::create { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::destroy { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::redeposit { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::transfer_ownership { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_team { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_collection_max_supply { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::lock_collection { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::create { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::destroy { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::transfer_ownership { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::set_team { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::set_metadata { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::set_attribute { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::set_collection_metadata { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::clear_metadata { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::clear_attribute { .. }) + | RuntimeCall::Uniques( pezpallet_uniques::Call::clear_collection_metadata { .. } - ) | RuntimeCall::Uniques(pezpallet_uniques::Call::set_collection_max_supply { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + ) | RuntimeCall::Uniques(pezpallet_uniques::Call::set_collection_max_supply { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::AssetManager => matches!( c, - RuntimeCall::Assets(TrustBackedAssetsCall::mint { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::burn { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::freeze { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::block { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::thaw { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::freeze_asset { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::thaw_asset { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::touch_other { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::refund_other { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::force_mint { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::update_mint_settings { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::mint_pre_signed { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_attributes_pre_signed { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::lock_item_transfer { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::unlock_item_transfer { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::lock_item_properties { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_metadata { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::clear_metadata { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_collection_metadata { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::clear_collection_metadata { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::mint { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::burn { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::freeze { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::thaw { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::freeze_collection { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::thaw_collection { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Assets(TrustBackedAssetsCall::mint { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::burn { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::freeze { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::block { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::thaw { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::freeze_asset { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::thaw_asset { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::touch_other { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::refund_other { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::force_mint { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::update_mint_settings { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::mint_pre_signed { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_attributes_pre_signed { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::lock_item_transfer { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::unlock_item_transfer { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::lock_item_properties { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_metadata { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::clear_metadata { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_collection_metadata { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::clear_collection_metadata { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::mint { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::burn { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::freeze { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::thaw { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::freeze_collection { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::thaw_collection { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Collator => matches!( c, - RuntimeCall::CollatorSelection { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::CollatorSelection { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), } } diff --git a/bizinikiwi/pezframe/staking-async/runtimes/teyrchain/src/weights/xcm/mod.rs b/bizinikiwi/pezframe/staking-async/runtimes/teyrchain/src/weights/xcm/mod.rs index 81bfbe3b..6c57ae47 100644 --- a/bizinikiwi/pezframe/staking-async/runtimes/teyrchain/src/weights/xcm/mod.rs +++ b/bizinikiwi/pezframe/staking-async/runtimes/teyrchain/src/weights/xcm/mod.rs @@ -45,8 +45,9 @@ impl WeighAssets for AssetFilter { WildFungibility::Fungible => weight, // Magic number 2 has to do with the fact that we could have up to 2 times // MaxAssetsIntoHolding in the worst-case scenario. - WildFungibility::NonFungible => - weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64), + WildFungibility::NonFungible => { + weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64) + }, }, AllCounted(count) => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), AllOfCounted { count, .. } => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), diff --git a/bizinikiwi/pezframe/staking-async/runtimes/teyrchain/src/xcm_config.rs b/bizinikiwi/pezframe/staking-async/runtimes/teyrchain/src/xcm_config.rs index 8eaa27ad..90fe5e83 100644 --- a/bizinikiwi/pezframe/staking-async/runtimes/teyrchain/src/xcm_config.rs +++ b/bizinikiwi/pezframe/staking-async/runtimes/teyrchain/src/xcm_config.rs @@ -266,9 +266,9 @@ impl Contains for FellowshipEntities { fn contains(location: &Location) -> bool { matches!( location.unpack(), - (1, [Teyrchain(COLLECTIVES_ID), Plurality { id: BodyId::Technical, .. }]) | - (1, [Teyrchain(COLLECTIVES_ID), PalletInstance(64)]) | - (1, [Teyrchain(COLLECTIVES_ID), PalletInstance(65)]) + (1, [Teyrchain(COLLECTIVES_ID), Plurality { id: BodyId::Technical, .. }]) + | (1, [Teyrchain(COLLECTIVES_ID), PalletInstance(64)]) + | (1, [Teyrchain(COLLECTIVES_ID), PalletInstance(65)]) ) } } diff --git a/bizinikiwi/pezframe/staking-async/src/benchmarking.rs b/bizinikiwi/pezframe/staking-async/src/benchmarking.rs index b9e08be2..e1a6fd4e 100644 --- a/bizinikiwi/pezframe/staking-async/src/benchmarking.rs +++ b/bizinikiwi/pezframe/staking-async/src/benchmarking.rs @@ -1230,8 +1230,8 @@ mod benchmarks { .for_each(|validator| { let exposure = pezsp_staking::Exposure::> { own: T::Currency::minimum_balance(), - total: T::Currency::minimum_balance() * - (exposed_nominators_per_validator + 1).into(), + total: T::Currency::minimum_balance() + * (exposed_nominators_per_validator + 1).into(), others: (0..exposed_nominators_per_validator) .map(|n| { let nominator = account::("nominator", n, SEED); diff --git a/bizinikiwi/pezframe/staking-async/src/ledger.rs b/bizinikiwi/pezframe/staking-async/src/ledger.rs index def723f5..3b7f79a8 100644 --- a/bizinikiwi/pezframe/staking-async/src/ledger.rs +++ b/bizinikiwi/pezframe/staking-async/src/ledger.rs @@ -148,8 +148,9 @@ impl StakingLedger { pub(crate) fn paired_account(account: StakingAccount) -> Option { match account { StakingAccount::Stash(stash) => >::get(stash), - StakingAccount::Controller(controller) => - >::get(&controller).map(|ledger| ledger.stash), + StakingAccount::Controller(controller) => { + >::get(&controller).map(|ledger| ledger.stash) + }, } } @@ -171,8 +172,9 @@ impl StakingLedger { /// stash has a controller which is bonding a ledger associated with another stash. pub(crate) fn get(account: StakingAccount) -> Result, Error> { let (stash, controller) = match account { - StakingAccount::Stash(stash) => - (stash.clone(), >::get(&stash).ok_or(Error::::NotStash)?), + StakingAccount::Stash(stash) => { + (stash.clone(), >::get(&stash).ok_or(Error::::NotStash)?) + }, StakingAccount::Controller(controller) => ( Ledger::::get(&controller) .map(|l| l.stash) @@ -210,8 +212,9 @@ impl StakingLedger { ) -> Option> { let stash = match account { StakingAccount::Stash(stash) => Some(stash), - StakingAccount::Controller(controller) => - Self::paired_account(StakingAccount::Controller(controller)), + StakingAccount::Controller(controller) => { + Self::paired_account(StakingAccount::Controller(controller)) + }, }; if let Some(stash) = stash { @@ -579,10 +582,10 @@ pub struct StakingLedgerInspect { #[cfg(test)] impl PartialEq> for StakingLedger { fn eq(&self, other: &StakingLedgerInspect) -> bool { - self.stash == other.stash && - self.total == other.total && - self.active == other.active && - self.unlocking == other.unlocking + self.stash == other.stash + && self.total == other.total + && self.active == other.active + && self.unlocking == other.unlocking } } diff --git a/bizinikiwi/pezframe/staking-async/src/pezpallet/impls.rs b/bizinikiwi/pezframe/staking-async/src/pezpallet/impls.rs index d2379664..46e862a7 100644 --- a/bizinikiwi/pezframe/staking-async/src/pezpallet/impls.rs +++ b/bizinikiwi/pezframe/staking-async/src/pezpallet/impls.rs @@ -131,7 +131,7 @@ impl Pezpallet { })?; match Ledger::::get(controller) { - Some(ledger) => + Some(ledger) => { if ledger.stash != *stash { Ok(LedgerIntegrityState::Corrupted) } else { @@ -140,7 +140,8 @@ impl Pezpallet { } else { Ok(LedgerIntegrityState::Ok) } - }, + } + }, None => Ok(LedgerIntegrityState::CorruptedKilled), } } @@ -275,8 +276,8 @@ impl Pezpallet { "consolidate_unlocked should never increase the total balance of the ledger" ); - let used_weight = if ledger.unlocking.is_empty() && - (ledger.active < Self::min_chilled_bond() || ledger.active.is_zero()) + let used_weight = if ledger.unlocking.is_empty() + && (ledger.active < Self::min_chilled_bond() || ledger.active.is_zero()) { // This account must have called `unbond()` with some value that caused the active // portion to fall below existential deposit + will have no more unlocking chunks @@ -370,7 +371,7 @@ impl Pezpallet { if Eras::::is_rewards_claimed(era, &stash, page) { return Err(Error::::AlreadyClaimed - .with_weight(T::WeightInfo::payout_stakers_alive_staked(0))) + .with_weight(T::WeightInfo::payout_stakers_alive_staked(0))); } Eras::::set_rewards_as_claimed(era, &stash, page); @@ -396,7 +397,7 @@ impl Pezpallet { // Nothing to do if they have no reward points. if validator_reward_points.is_zero() { - return Ok(Some(T::WeightInfo::payout_stakers_alive_staked(0)).into()) + return Ok(Some(T::WeightInfo::payout_stakers_alive_staked(0)).into()); } // This is the fraction of the total reward that the validator and the @@ -485,7 +486,7 @@ impl Pezpallet { ) -> Option<(PositiveImbalanceOf, RewardDestination)> { // noop if amount is zero if amount.is_zero() { - return None + return None; } let dest = Self::payee(StakingAccount::Stash(stash.clone()))?; @@ -603,8 +604,8 @@ impl Pezpallet { SnapshotStatus::Consumed => Box::new(vec![].into_iter()), }; - while all_voters.len() < page_len_prediction as usize && - voters_seen < (NPOS_MAX_ITERATIONS_COEFFICIENT * page_len_prediction as u32) + while all_voters.len() < page_len_prediction as usize + && voters_seen < (NPOS_MAX_ITERATIONS_COEFFICIENT * page_len_prediction as u32) { let voter = match sorted_voters.next() { Some(voter) => { @@ -618,7 +619,7 @@ impl Pezpallet { // if voter weight is zero, do not consider this voter for the snapshot. if voter_weight.is_zero() { log!(debug, "voter's active balance is 0. skip this voter."); - continue + continue; } if let Some(Nominations { targets, .. }) = >::get(&voter) { @@ -633,7 +634,7 @@ impl Pezpallet { Self::deposit_event(Event::::SnapshotVotersSizeExceeded { size: voters_size_tracker.size as u32, }); - break + break; } all_voters.push(voter); @@ -659,7 +660,7 @@ impl Pezpallet { Self::deposit_event(Event::::SnapshotVotersSizeExceeded { size: voters_size_tracker.size as u32, }); - break + break; } all_voters.push(self_vote); validators_taken.saturating_inc(); @@ -704,8 +705,8 @@ impl Pezpallet { let mut targets_seen = 0; let mut targets_iter = T::TargetList::iter(); - while all_targets.len() < final_predicted_len as usize && - targets_seen < (NPOS_MAX_ITERATIONS_COEFFICIENT * final_predicted_len as u32) + while all_targets.len() < final_predicted_len as usize + && targets_seen < (NPOS_MAX_ITERATIONS_COEFFICIENT * final_predicted_len as u32) { let target = match targets_iter.next() { Some(target) => { @@ -721,7 +722,7 @@ impl Pezpallet { Self::deposit_event(Event::::SnapshotTargetsSizeExceeded { size: targets_size_tracker.size as u32, }); - break + break; } if Validators::::contains_key(&target) { @@ -900,7 +901,7 @@ impl Pezpallet { // dec provider let _ = pezframe_system::Pezpallet::::dec_providers(&stash)?; - return Ok(()) + return Ok(()); } } @@ -1007,7 +1008,7 @@ impl ElectionDataProvider for Pezpallet { let targets = Self::get_npos_targets(bounds); if bounds.exhausted(None, CountBound(targets.len() as u32).into()) { - return Err("Target snapshot too big") + return Err("Target snapshot too big"); } debug_assert!(!bounds.slice_exhausted(&targets)); @@ -1201,7 +1202,7 @@ impl rc_client::AHStakingInterface for Pezpallet { // Skip if the validator is invulnerable. if invulnerables.contains(&validator) { log!(debug, "🦹 on_offence: {:?} is invulnerable; ignoring offence", validator); - continue + continue; } // ignore offence if too old to report. @@ -1345,8 +1346,8 @@ impl ScoreProvider for Pezpallet { Self::ledger(Stash(who.clone())) .ok() .and_then(|l| { - if Nominators::::contains_key(&l.stash) || - Validators::::contains_key(&l.stash) + if Nominators::::contains_key(&l.stash) + || Validators::::contains_key(&l.stash) { Some(l.active) } else { @@ -1655,7 +1656,7 @@ impl StakingInterface for Pezpallet { who: &Self::AccountId, ) -> Result, DispatchError> { if !StakingLedger::::is_bonded(StakingAccount::Stash(who.clone())) { - return Err(Error::::NotStash.into()) + return Err(Error::::NotStash.into()); } let is_validator = Validators::::contains_key(&who); @@ -1680,8 +1681,8 @@ impl StakingInterface for Pezpallet { /// There is an assumption that, this account is keyless and managed by another pezpallet in the /// runtime. Hence, it can never sign its own transactions. fn is_virtual_staker(who: &T::AccountId) -> bool { - pezframe_system::Pezpallet::::account_nonce(who).is_zero() && - VirtualStakers::::contains_key(who) + pezframe_system::Pezpallet::::account_nonce(who).is_zero() + && VirtualStakers::::contains_key(who) } fn slash_reward_fraction() -> Perbill { @@ -1732,7 +1733,7 @@ impl pezsp_staking::StakingUnchecked for Pezpallet { payee: &Self::AccountId, ) -> DispatchResult { if StakingLedger::::is_bonded(StakingAccount::Stash(keyless_who.clone())) { - return Err(Error::::AlreadyBonded.into()) + return Err(Error::::AlreadyBonded.into()); } // check if payee not same as who. @@ -1816,9 +1817,11 @@ impl Pezpallet { // if stash == controller, it means that the ledger has migrated to // post-controller. If no migration happened, we expect that the (stash, // controller) pair has only one associated ledger. + { if stash != controller { count_double += 1; - }, + } + }, (None, None) => { count_none += 1; }, @@ -1855,8 +1858,8 @@ impl Pezpallet { } ensure!( - (Ledger::::iter().count() == Payee::::iter().count()) && - (Ledger::::iter().count() == Bonded::::iter().count()), + (Ledger::::iter().count() == Payee::::iter().count()) + && (Ledger::::iter().count() == Bonded::::iter().count()), "number of entries in payee storage items does not match the number of bonded ledgers", ); @@ -1870,8 +1873,8 @@ impl Pezpallet { /// * Current validator count is bounded by the election provider's max winners. fn check_count() -> Result<(), TryRuntimeError> { ensure!( - ::VoterList::count() == - Nominators::::count() + Validators::::count(), + ::VoterList::count() + == Nominators::::count() + Validators::::count(), "wrong external count" ); ensure!( @@ -1982,11 +1985,11 @@ impl Pezpallet { ensure!( overview_and_pages.iter().all(|(metadata, pages)| { let page_count_good = metadata.page_count == pages.len() as u32; - let nominator_count_good = metadata.nominator_count == - pages.iter().map(|p| p.others.len() as u32).fold(0u32, |acc, x| acc + x); - let total_good = metadata.total == - metadata.own + - pages + let nominator_count_good = metadata.nominator_count + == pages.iter().map(|p| p.others.len() as u32).fold(0u32, |acc, x| acc + x); + let total_good = metadata.total + == metadata.own + + pages .iter() .fold(BalanceOf::::zero(), |acc, page| acc + page.page_total); @@ -1999,8 +2002,8 @@ impl Pezpallet { overview_and_pages .iter() .map(|(metadata, _pages)| metadata.total) - .fold(BalanceOf::::zero(), |acc, x| acc + x) == - ErasTotalStake::::get(era), + .fold(BalanceOf::::zero(), |acc, x| acc + x) + == ErasTotalStake::::get(era), "found bad eras total stake" ); diff --git a/bizinikiwi/pezframe/staking-async/src/pezpallet/mod.rs b/bizinikiwi/pezframe/staking-async/src/pezpallet/mod.rs index 020819a0..a1c01774 100644 --- a/bizinikiwi/pezframe/staking-async/src/pezpallet/mod.rs +++ b/bizinikiwi/pezframe/staking-async/src/pezpallet/mod.rs @@ -901,9 +901,9 @@ pub mod pezpallet { fn build(&self) { crate::log!(trace, "initializing with {:?}", self); assert!( - self.validator_count <= - ::MaxWinnersPerPage::get() * - ::Pages::get(), + self.validator_count + <= ::MaxWinnersPerPage::get() + * ::Pages::get(), "validator count is too high, `ElectionProvider` can never fulfill this" ); ValidatorCount::::put(self.validator_count); @@ -1776,8 +1776,8 @@ pub mod pezpallet { let targets: BoundedVec<_, _> = targets .into_iter() .map(|n| { - if old.contains(&n) || - (Validators::::contains_key(&n) && !Validators::::get(&n).blocked) + if old.contains(&n) + || (Validators::::contains_key(&n) && !Validators::::get(&n).blocked) { Ok(n) } else { @@ -2171,10 +2171,10 @@ pub mod pezpallet { let origin_balance = asset::total_balance::(&stash); let ledger_total = Self::ledger(Stash(stash.clone())).map(|l| l.total).unwrap_or_default(); - let reapable = origin_balance < min_chilled_bond || - origin_balance.is_zero() || - ledger_total < min_chilled_bond || - ledger_total.is_zero(); + let reapable = origin_balance < min_chilled_bond + || origin_balance.is_zero() + || ledger_total < min_chilled_bond + || ledger_total.is_zero(); ensure!(reapable, Error::::FundedTarget); // Remove all staking-related information and lock. diff --git a/bizinikiwi/pezframe/staking-async/src/session_rotation.rs b/bizinikiwi/pezframe/staking-async/src/session_rotation.rs index 684b1c0f..3f27d9a9 100644 --- a/bizinikiwi/pezframe/staking-async/src/session_rotation.rs +++ b/bizinikiwi/pezframe/staking-async/src/session_rotation.rs @@ -410,8 +410,8 @@ impl Eras { let e2 = ErasTotalStake::::contains_key(era); let active_era = Rotator::::active_era(); - let e4 = if era.saturating_sub(1) > 0 && - era.saturating_sub(1) > active_era.saturating_sub(T::HistoryDepth::get() + 1) + let e4 = if era.saturating_sub(1) > 0 + && era.saturating_sub(1) > active_era.saturating_sub(T::HistoryDepth::get() + 1) { // `ErasValidatorReward` is set at active era n for era n-1, and is not set for era 0 in // our tests. Moreover, it cannot be checked for presence in the oldest present era @@ -549,8 +549,8 @@ impl Rotator { // If we have an active era, bonded eras must always be the range // [active - bonding_duration .. active_era] ensure!( - bonded.into_iter().map(|(era, _sess)| era).collect::>() == - (active.index.saturating_sub(T::BondingDuration::get())..=active.index) + bonded.into_iter().map(|(era, _sess)| era).collect::>() + == (active.index.saturating_sub(T::BondingDuration::get())..=active.index) .collect::>(), "BondedEras range incorrect" ); @@ -916,8 +916,8 @@ impl EraElectionPlanner { ); debug_assert!( - CurrentEra::::get().unwrap_or(0) == - ActiveEra::::get().map_or(0, |a| a.index) + 1, + CurrentEra::::get().unwrap_or(0) + == ActiveEra::::get().map_or(0, |a| a.index) + 1, "Next era must be already planned." ); diff --git a/bizinikiwi/pezframe/staking-async/src/tests/election_data_provider.rs b/bizinikiwi/pezframe/staking-async/src/tests/election_data_provider.rs index b4158090..735a96c3 100644 --- a/bizinikiwi/pezframe/staking-async/src/tests/election_data_provider.rs +++ b/bizinikiwi/pezframe/staking-async/src/tests/election_data_provider.rs @@ -635,10 +635,10 @@ mod paged_snapshot { // requested. let snapshot = Staking::electable_targets(bounds, 0).unwrap(); assert!( - snapshot == all_targets && - snapshot == Staking::electable_targets(bounds, 1).unwrap() && - snapshot == Staking::electable_targets(bounds, 2).unwrap() && - snapshot == Staking::electable_targets(bounds, u32::MAX).unwrap(), + snapshot == all_targets + && snapshot == Staking::electable_targets(bounds, 1).unwrap() + && snapshot == Staking::electable_targets(bounds, 2).unwrap() + && snapshot == Staking::electable_targets(bounds, u32::MAX).unwrap(), ); }) } @@ -868,9 +868,9 @@ mod score_provider { ExtBuilder::default().build_and_execute(|| { // given 41 being a chilled staker assert!( - Ledger::::get(41).is_some() && - !Validators::::contains_key(41) && - !Nominators::::contains_key(41) + Ledger::::get(41).is_some() + && !Validators::::contains_key(41) + && !Nominators::::contains_key(41) ); // then they will not have a score when bags-list wants to update it. @@ -883,9 +883,9 @@ mod score_provider { ExtBuilder::default().build_and_execute(|| { // given 777 being neither a nominator nor a validator in this pezpallet. assert!( - !Ledger::::get(777).is_some() && - !Validators::::contains_key(777) && - !Nominators::::contains_key(777) + !Ledger::::get(777).is_some() + && !Validators::::contains_key(777) + && !Nominators::::contains_key(777) ); // then it will not have a score when bags-list wants to update it. @@ -898,9 +898,9 @@ mod score_provider { ExtBuilder::default().nominate(true).build_and_execute(|| { // Given 101 being a nominator assert!( - Ledger::::get(101).unwrap().active == 500 && - !Validators::::contains_key(101) && - Nominators::::contains_key(101) + Ledger::::get(101).unwrap().active == 500 + && !Validators::::contains_key(101) + && Nominators::::contains_key(101) ); // then it will have a score. @@ -908,9 +908,9 @@ mod score_provider { // given 11 being a validator assert!( - Ledger::::get(11).unwrap().active == 1000 && - Validators::::contains_key(11) && - !Nominators::::contains_key(11) + Ledger::::get(11).unwrap().active == 1000 + && Validators::::contains_key(11) + && !Nominators::::contains_key(11) ); // then it will have a score. diff --git a/bizinikiwi/pezframe/staking-async/src/tests/payout_stakers.rs b/bizinikiwi/pezframe/staking-async/src/tests/payout_stakers.rs index a56bcdf0..ac283991 100644 --- a/bizinikiwi/pezframe/staking-async/src/tests/payout_stakers.rs +++ b/bizinikiwi/pezframe/staking-async/src/tests/payout_stakers.rs @@ -105,9 +105,9 @@ fn rewards_with_nominator_should_work() { ); assert_eq_error_rate!( asset::total_balance::(&101), - init_balance_101 + - part_for_101_from_11 * validator_payout_0 * 2 / 3 + - part_for_101_from_21 * validator_payout_0 * 1 / 3, + init_balance_101 + + part_for_101_from_11 * validator_payout_0 * 2 / 3 + + part_for_101_from_21 * validator_payout_0 * 1 / 3, 2 ); @@ -149,9 +149,9 @@ fn rewards_with_nominator_should_work() { ); assert_eq_error_rate!( asset::total_balance::(&101), - init_balance_101 + - part_for_101_from_11 * (validator_payout_0 * 2 / 3 + total_payout_1) + - part_for_101_from_21 * validator_payout_0 * 1 / 3, + init_balance_101 + + part_for_101_from_11 * (validator_payout_0 * 2 / 3 + total_payout_1) + + part_for_101_from_21 * validator_payout_0 * 1 / 3, 2 ); }); diff --git a/bizinikiwi/pezframe/staking-async/src/tests/slashing.rs b/bizinikiwi/pezframe/staking-async/src/tests/slashing.rs index 60d30ace..ba7a1654 100644 --- a/bizinikiwi/pezframe/staking-async/src/tests/slashing.rs +++ b/bizinikiwi/pezframe/staking-async/src/tests/slashing.rs @@ -848,9 +848,9 @@ fn nominator_is_slashed_by_max_for_validator_in_era() { ); assert_eq!( asset::stakeable_balance::(&nominator), - 500 - first_slash_nominator_amount - - second_slash_nominator_amount - - third_slash_nominator_amount + 500 - first_slash_nominator_amount + - second_slash_nominator_amount + - third_slash_nominator_amount ); assert_eq!(asset::stakeable_balance::(&21), v2_stakeable); }); diff --git a/bizinikiwi/pezframe/staking/reward-curve/src/lib.rs b/bizinikiwi/pezframe/staking/reward-curve/src/lib.rs index 849f6d2c..030eaf37 100644 --- a/bizinikiwi/pezframe/staking/reward-curve/src/lib.rs +++ b/bizinikiwi/pezframe/staking/reward-curve/src/lib.rs @@ -136,10 +136,10 @@ struct Bounds { impl Bounds { fn check(&self, value: u32) -> bool { - let wrong = (self.min_strict && value <= self.min) || - (!self.min_strict && value < self.min) || - (self.max_strict && value >= self.max) || - (!self.max_strict && value > self.max); + let wrong = (self.min_strict && value <= self.min) + || (!self.min_strict && value < self.min) + || (self.max_strict && value >= self.max) + || (!self.max_strict && value > self.max); !wrong } @@ -291,8 +291,8 @@ fn compute_points(input: &INposInput) -> Vec<(u32, u32)> { // For each point p: (next_p.0 - p.0) < segment_length && (next_p.1 - p.1) < segment_length. // This ensures that the total number of segments doesn't overflow max_piece_count. - let max_length = (input.max_inflation - input.min_inflation + 1_000_000 - inpos.x_ideal) / - (input.max_piece_count - 1); + let max_length = (input.max_inflation - input.min_inflation + 1_000_000 - inpos.x_ideal) + / (input.max_piece_count - 1); let mut delta_y = max_length; let mut y = input.max_inflation; @@ -319,8 +319,8 @@ fn compute_points(input: &INposInput) -> Vec<(u32, u32)> { // Compute the y corresponding to x=1_000_000 using the current point and the previous // one. - let delta_y: u32 = ((next_x - 1_000_000) as u64 * (prev.1 - next_y) as u64 / - (next_x - prev.0) as u64) + let delta_y: u32 = ((next_x - 1_000_000) as u64 * (prev.1 - next_y) as u64 + / (next_x - prev.0) as u64) .try_into() .unwrap(); diff --git a/bizinikiwi/pezframe/staking/src/inflation.rs b/bizinikiwi/pezframe/staking/src/inflation.rs index 7cc34d70..e9b95f3d 100644 --- a/bizinikiwi/pezframe/staking/src/inflation.rs +++ b/bizinikiwi/pezframe/staking/src/inflation.rs @@ -42,8 +42,8 @@ where const MILLISECONDS_PER_YEAR: u64 = 1000 * 3600 * 24 * 36525 / 100; let portion = Perbill::from_rational(era_duration as u64, MILLISECONDS_PER_YEAR); - let payout = portion * - yearly_inflation + let payout = portion + * yearly_inflation .calculate_for_fraction_times_denominator(npos_token_staked, total_tokens.clone()); let maximum = portion * (yearly_inflation.maximum * total_tokens); (payout, maximum) diff --git a/bizinikiwi/pezframe/staking/src/ledger.rs b/bizinikiwi/pezframe/staking/src/ledger.rs index 3af26705..6c51207d 100644 --- a/bizinikiwi/pezframe/staking/src/ledger.rs +++ b/bizinikiwi/pezframe/staking/src/ledger.rs @@ -86,8 +86,9 @@ impl StakingLedger { pub(crate) fn paired_account(account: StakingAccount) -> Option { match account { StakingAccount::Stash(stash) => >::get(stash), - StakingAccount::Controller(controller) => - >::get(&controller).map(|ledger| ledger.stash), + StakingAccount::Controller(controller) => { + >::get(&controller).map(|ledger| ledger.stash) + }, } } @@ -109,8 +110,9 @@ impl StakingLedger { /// stash has a controller which is bonding a ledger associated with another stash. pub(crate) fn get(account: StakingAccount) -> Result, Error> { let (stash, controller) = match account.clone() { - StakingAccount::Stash(stash) => - (stash.clone(), >::get(&stash).ok_or(Error::::NotStash)?), + StakingAccount::Stash(stash) => { + (stash.clone(), >::get(&stash).ok_or(Error::::NotStash)?) + }, StakingAccount::Controller(controller) => ( Ledger::::get(&controller) .map(|l| l.stash) @@ -148,8 +150,9 @@ impl StakingLedger { ) -> Option> { let stash = match account { StakingAccount::Stash(stash) => Some(stash), - StakingAccount::Controller(controller) => - Self::paired_account(StakingAccount::Controller(controller)), + StakingAccount::Controller(controller) => { + Self::paired_account(StakingAccount::Controller(controller)) + }, }; if let Some(stash) = stash { @@ -296,11 +299,11 @@ pub struct StakingLedgerInspect { #[cfg(test)] impl PartialEq> for StakingLedger { fn eq(&self, other: &StakingLedgerInspect) -> bool { - self.stash == other.stash && - self.total == other.total && - self.active == other.active && - self.unlocking == other.unlocking && - self.legacy_claimed_rewards == other.legacy_claimed_rewards + self.stash == other.stash + && self.total == other.total + && self.active == other.active + && self.unlocking == other.unlocking + && self.legacy_claimed_rewards == other.legacy_claimed_rewards } } diff --git a/bizinikiwi/pezframe/staking/src/lib.rs b/bizinikiwi/pezframe/staking/src/lib.rs index 2ead7750..e86516e7 100644 --- a/bizinikiwi/pezframe/staking/src/lib.rs +++ b/bizinikiwi/pezframe/staking/src/lib.rs @@ -1220,8 +1220,8 @@ impl EraInfo { validator: &T::AccountId, page: Page, ) -> bool { - ledger.legacy_claimed_rewards.binary_search(&era).is_ok() || - Self::is_rewards_claimed(era, validator, page) + ledger.legacy_claimed_rewards.binary_search(&era).is_ok() + || Self::is_rewards_claimed(era, validator, page) } /// Check if the rewards for the given era and page index have been claimed. diff --git a/bizinikiwi/pezframe/staking/src/migrations.rs b/bizinikiwi/pezframe/staking/src/migrations.rs index 8f508071..655afade 100644 --- a/bizinikiwi/pezframe/staking/src/migrations.rs +++ b/bizinikiwi/pezframe/staking/src/migrations.rs @@ -393,7 +393,9 @@ pub mod v11 { warn, "new bags-list name is equal to the old one, only bumping the version" ); - return T::DbWeight::get().reads(1).saturating_add(T::DbWeight::get().writes(1)); + return T::DbWeight::get() + .reads(1) + .saturating_add(T::DbWeight::get().writes(1)); } move_pallet(old_pallet_name.as_bytes(), new_pallet_name.as_bytes()); diff --git a/bizinikiwi/pezframe/staking/src/pezpallet/impls.rs b/bizinikiwi/pezframe/staking/src/pezpallet/impls.rs index 10aa8762..b1b5dff7 100644 --- a/bizinikiwi/pezframe/staking/src/pezpallet/impls.rs +++ b/bizinikiwi/pezframe/staking/src/pezpallet/impls.rs @@ -113,7 +113,7 @@ impl Pezpallet { })?; match Ledger::::get(controller) { - Some(ledger) => + Some(ledger) => { if ledger.stash != *stash { Ok(LedgerIntegrityState::Corrupted) } else { @@ -122,7 +122,8 @@ impl Pezpallet { } else { Ok(LedgerIntegrityState::Ok) } - }, + } + }, None => Ok(LedgerIntegrityState::CorruptedKilled), } } @@ -480,8 +481,8 @@ impl Pezpallet { // New era. let maybe_new_era_validators = Self::try_trigger_new_era(session_index, is_genesis); - if maybe_new_era_validators.is_some() && - matches!(ForceEra::::get(), Forcing::ForceNew) + if maybe_new_era_validators.is_some() + && matches!(ForceEra::::get(), Forcing::ForceNew) { Self::set_force_era(Forcing::NotForcing); } @@ -906,8 +907,8 @@ impl Pezpallet { let mut min_active_stake = u64::MAX; let mut sorted_voters = T::VoterList::iter(); - while all_voters.len() < final_predicted_len as usize && - voters_seen < (NPOS_MAX_ITERATIONS_COEFFICIENT * final_predicted_len as u32) + while all_voters.len() < final_predicted_len as usize + && voters_seen < (NPOS_MAX_ITERATIONS_COEFFICIENT * final_predicted_len as u32) { let voter = match sorted_voters.next() { Some(voter) => { @@ -1014,8 +1015,8 @@ impl Pezpallet { let mut targets_seen = 0; let mut targets_iter = T::TargetList::iter(); - while all_targets.len() < final_predicted_len as usize && - targets_seen < (NPOS_MAX_ITERATIONS_COEFFICIENT * final_predicted_len as u32) + while all_targets.len() < final_predicted_len as usize + && targets_seen < (NPOS_MAX_ITERATIONS_COEFFICIENT * final_predicted_len as u32) { let target = match targets_iter.next() { Some(target) => { @@ -2120,8 +2121,8 @@ impl StakingInterface for Pezpallet { /// There is an assumption that, this account is keyless and managed by another pezpallet in the /// runtime. Hence, it can never sign its own transactions. fn is_virtual_staker(who: &T::AccountId) -> bool { - pezframe_system::Pezpallet::::account_nonce(who).is_zero() && - VirtualStakers::::contains_key(who) + pezframe_system::Pezpallet::::account_nonce(who).is_zero() + && VirtualStakers::::contains_key(who) } fn slash_reward_fraction() -> Perbill { @@ -2258,9 +2259,11 @@ impl Pezpallet { // if stash == controller, it means that the ledger has migrated to // post-controller. If no migration happened, we expect that the (stash, // controller) pair has only one associated ledger. + { if stash != controller { count_double += 1; - }, + } + }, (None, None) => { count_none += 1; }, @@ -2297,8 +2300,8 @@ impl Pezpallet { } ensure!( - (Ledger::::iter().count() == Payee::::iter().count()) && - (Ledger::::iter().count() == Bonded::::iter().count()), + (Ledger::::iter().count() == Payee::::iter().count()) + && (Ledger::::iter().count() == Bonded::::iter().count()), "number of entries in payee storage items does not match the number of bonded ledgers", ); @@ -2312,8 +2315,8 @@ impl Pezpallet { /// * Current validator count is bounded by the election provider's max winners. fn check_count() -> Result<(), TryRuntimeError> { ensure!( - ::VoterList::count() == - Nominators::::count() + Validators::::count(), + ::VoterList::count() + == Nominators::::count() + Validators::::count(), "wrong external count" ); ensure!( @@ -2394,9 +2397,10 @@ impl Pezpallet { ErasStakers::::iter_prefix_values(era) .map(|expo| { ensure!( - expo.total == - expo.own + - expo.others + expo.total + == expo.own + + expo + .others .iter() .map(|e| e.value) .fold(Zero::zero(), |acc, x| acc + x), @@ -2429,8 +2433,8 @@ impl Pezpallet { ErasStakersPaged::::iter_prefix((era,)) .map(|((validator, _page), expo)| { ensure!( - expo.page_total == - expo.others.iter().map(|e| e.value).fold(Zero::zero(), |acc, x| acc + x), + expo.page_total + == expo.others.iter().map(|e| e.value).fold(Zero::zero(), |acc, x| acc + x), "wrong total exposure for the page.", ); @@ -2511,10 +2515,11 @@ impl Pezpallet { match len { 0 => { /* not supporting this validator at all. */ }, 1 => sum_exposed += individual[0].value, - _ => + _ => { return Err( "nominator cannot back a validator more than once.".into() - ), + ) + }, }; Ok(()) }) diff --git a/bizinikiwi/pezframe/staking/src/pezpallet/mod.rs b/bizinikiwi/pezframe/staking/src/pezpallet/mod.rs index 77f7d22c..9ebb9b14 100644 --- a/bizinikiwi/pezframe/staking/src/pezpallet/mod.rs +++ b/bizinikiwi/pezframe/staking/src/pezpallet/mod.rs @@ -808,9 +808,9 @@ pub mod pezpallet { _ => Ok(()), }); assert!( - ValidatorCount::::get() <= - ::MaxWinnersPerPage::get() * - ::Pages::get() + ValidatorCount::::get() + <= ::MaxWinnersPerPage::get() + * ::Pages::get() ); } @@ -993,8 +993,8 @@ pub mod pezpallet { // ensure election results are always bounded with the same value assert!( - ::MaxWinnersPerPage::get() == - ::MaxWinnersPerPage::get() + ::MaxWinnersPerPage::get() + == ::MaxWinnersPerPage::get() ); assert!( @@ -1822,10 +1822,10 @@ pub mod pezpallet { let origin_balance = asset::total_balance::(&stash); let ledger_total = Self::ledger(Stash(stash.clone())).map(|l| l.total).unwrap_or_default(); - let reapable = origin_balance < ed || - origin_balance.is_zero() || - ledger_total < ed || - ledger_total.is_zero(); + let reapable = origin_balance < ed + || origin_balance.is_zero() + || ledger_total < ed + || ledger_total.is_zero(); ensure!(reapable, Error::::FundedTarget); // Remove all staking-related information and lock. diff --git a/bizinikiwi/pezframe/staking/src/tests.rs b/bizinikiwi/pezframe/staking/src/tests.rs index 5032fe58..3787e6d2 100644 --- a/bizinikiwi/pezframe/staking/src/tests.rs +++ b/bizinikiwi/pezframe/staking/src/tests.rs @@ -387,9 +387,9 @@ fn rewards_should_work() { ); assert_eq_error_rate!( asset::total_balance::(&101), - init_balance_101 + - part_for_101_from_11 * total_payout_0 * 2 / 3 + - part_for_101_from_21 * total_payout_0 * 1 / 3, + init_balance_101 + + part_for_101_from_11 * total_payout_0 * 2 / 3 + + part_for_101_from_21 * total_payout_0 * 1 / 3, 2 ); @@ -427,9 +427,9 @@ fn rewards_should_work() { ); assert_eq_error_rate!( asset::total_balance::(&101), - init_balance_101 + - part_for_101_from_11 * (total_payout_0 * 2 / 3 + total_payout_1) + - part_for_101_from_21 * total_payout_0 * 1 / 3, + init_balance_101 + + part_for_101_from_11 * (total_payout_0 * 2 / 3 + total_payout_1) + + part_for_101_from_21 * total_payout_0 * 1 / 3, 2 ); }); @@ -6540,8 +6540,8 @@ fn test_validator_exposure_is_backward_compatible_with_non_paged_rewards_payout( let actual_exposure_page_1 = ErasStakersPaged::::get((1, 11, 1)).unwrap(); expected_individual_exposures.iter().for_each(|exposure| { assert!( - actual_exposure_page_0.others.contains(exposure) || - actual_exposure_page_1.others.contains(exposure) + actual_exposure_page_0.others.contains(exposure) + || actual_exposure_page_1.others.contains(exposure) ); }); assert_eq!( @@ -9289,8 +9289,8 @@ fn manual_slashing_works() { let expected_balance_1 = initial_balance - (initial_balance / 4); // 25% slash assert!( - balance_after_first_slash <= expected_balance_1 && - balance_after_first_slash >= expected_balance_1 - 5, + balance_after_first_slash <= expected_balance_1 + && balance_after_first_slash >= expected_balance_1 - 5, "First slash was not applied correctly. Expected around {}, got {}", expected_balance_1, balance_after_first_slash @@ -9342,8 +9342,8 @@ fn manual_slashing_works() { let expected_balance_3 = initial_balance / 2; // 50% of original assert!( - balance_after_third_slash <= expected_balance_3 && - balance_after_third_slash >= expected_balance_3 - 5, + balance_after_third_slash <= expected_balance_3 + && balance_after_third_slash >= expected_balance_3 - 5, "Third slash was not applied correctly. Expected around {}, got {}", expected_balance_3, balance_after_third_slash @@ -9385,8 +9385,8 @@ fn manual_slashing_works() { let expected_balance_5 = initial_balance / 4; // 25% of original (75% slashed) assert!( - balance_after_fifth_slash <= expected_balance_5 && - balance_after_fifth_slash >= expected_balance_5 - 5, + balance_after_fifth_slash <= expected_balance_5 + && balance_after_fifth_slash >= expected_balance_5 - 5, "Fifth slash was not applied correctly. Expected around {}, got {}", expected_balance_5, balance_after_fifth_slash diff --git a/bizinikiwi/pezframe/support/procedural/src/benchmark.rs b/bizinikiwi/pezframe/support/procedural/src/benchmark.rs index 5939694f..807368c7 100644 --- a/bizinikiwi/pezframe/support/procedural/src/benchmark.rs +++ b/bizinikiwi/pezframe/support/procedural/src/benchmark.rs @@ -414,11 +414,12 @@ fn parse_call_def(item_fn: &ItemFn) -> Result<(usize, BenchmarkCallDef)> { Ok(match &call_defs[..] { [(i, call_def)] => (*i, call_def.clone()), // = 1 [] => return missing_call(item_fn), - _ => + _ => { return Err(Error::new( call_defs[1].1.attr_span(), "Only one #[extrinsic_call] or #[block] attribute is allowed per benchmark.", - )), + )) + }, }) } @@ -432,7 +433,9 @@ impl BenchmarkDef { let (verify_stmts, last_stmt) = match item_fn.sig.output { ReturnType::Default => // no return type, last_stmt should be None - (Vec::from(&item_fn.block.stmts[(i + 1)..item_fn.block.stmts.len()]), None), + { + (Vec::from(&item_fn.block.stmts[(i + 1)..item_fn.block.stmts.len()]), None) + }, ReturnType::Type(_, _) => { // defined return type, last_stmt should be Result<(), BenchmarkError> // compatible and should not be included in verify_stmts @@ -481,12 +484,13 @@ pub fn benchmarks( let module: ItemMod = syn::parse(tokens)?; let mod_span = module.span(); let where_clause = match syn::parse::(attrs.clone()) { - Ok(_) => + Ok(_) => { if instance { quote!(T: Config, I: 'static) } else { quote!(T: Config) - }, + } + }, Err(_) => { let mut where_clause_predicates = syn::parse::(attrs)?.predicates; @@ -1026,8 +1030,9 @@ fn expand_benchmark( }, ) }, - BenchmarkCallDef::Block { block, attr_span: _ } => - (quote!(), quote!(#block), quote!(#block)), + BenchmarkCallDef::Block { block, attr_span: _ } => { + (quote!(), quote!(#block), quote!(#block)) + }, }; let vis = benchmark_def.fn_vis; diff --git a/bizinikiwi/pezframe/support/procedural/src/construct_runtime/parse.rs b/bizinikiwi/pezframe/support/procedural/src/construct_runtime/parse.rs index 54cd6daf..7c1a6eda 100644 --- a/bizinikiwi/pezframe/support/procedural/src/construct_runtime/parse.rs +++ b/bizinikiwi/pezframe/support/procedural/src/construct_runtime/parse.rs @@ -96,22 +96,25 @@ impl Parse for RuntimeDeclaration { let pallets_token = pallets.token; match convert_pallets(pallets.content.inner.into_iter().collect())? { - PalletsConversion::Implicit(pallets) => - Ok(RuntimeDeclaration::Implicit(ImplicitRuntimeDeclaration { pallets })), - PalletsConversion::Explicit(pallets) => + PalletsConversion::Implicit(pallets) => { + Ok(RuntimeDeclaration::Implicit(ImplicitRuntimeDeclaration { pallets })) + }, + PalletsConversion::Explicit(pallets) => { Ok(RuntimeDeclaration::Explicit(ExplicitRuntimeDeclaration { name, where_section, pallets, pallets_token, - })), - PalletsConversion::ExplicitExpanded(pallets) => + })) + }, + PalletsConversion::ExplicitExpanded(pallets) => { Ok(RuntimeDeclaration::ExplicitExpanded(ExplicitRuntimeDeclaration { name, where_section, pallets, pallets_token, - })), + })) + }, } } } @@ -234,13 +237,13 @@ impl Parse for PalletDeclaration { let res = Some(input.parse()?); let _: Token![>] = input.parse()?; res - } else if !(input.peek(Token![::]) && input.peek3(token::Brace)) && - !input.peek(keyword::expanded) && - !input.peek(keyword::exclude_parts) && - !input.peek(keyword::use_parts) && - !input.peek(Token![=]) && - !input.peek(Token![,]) && - !input.is_empty() + } else if !(input.peek(Token![::]) && input.peek3(token::Brace)) + && !input.peek(keyword::expanded) + && !input.peek(keyword::exclude_parts) + && !input.peek(keyword::use_parts) + && !input.peek(Token![=]) + && !input.peek(Token![,]) + && !input.is_empty() { return Err(input.error( "Unexpected tokens, expected one of `::$ident` `::{`, `exclude_parts`, `use_parts`, `=`, `,`", @@ -264,11 +267,11 @@ impl Parse for PalletDeclaration { let mut parts = parse_pallet_parts(input)?; parts.extend(extra_parts.into_iter()); Some(parts) - } else if !input.peek(keyword::exclude_parts) && - !input.peek(keyword::use_parts) && - !input.peek(Token![=]) && - !input.peek(Token![,]) && - !input.is_empty() + } else if !input.peek(keyword::exclude_parts) + && !input.peek(keyword::use_parts) + && !input.peek(Token![=]) + && !input.peek(Token![,]) + && !input.is_empty() { return Err(input.error( "Unexpected tokens, expected one of `::{`, `exclude_parts`, `use_parts`, `=`, `,`", @@ -342,10 +345,10 @@ impl Parse for PalletPath { PalletPath { inner: Path { leading_colon: None, segments: Punctuated::new() } }; let lookahead = input.lookahead1(); - if lookahead.peek(Token![crate]) || - lookahead.peek(Token![self]) || - lookahead.peek(Token![super]) || - lookahead.peek(Ident) + if lookahead.peek(Token![crate]) + || lookahead.peek(Token![self]) + || lookahead.peek(Token![super]) + || lookahead.peek(Ident) { let ident = input.call(Ident::parse_any)?; res.inner.segments.push(ident.into()); @@ -720,7 +723,7 @@ fn convert_pallets(pallets: Vec) -> syn::Result + SpecifiedParts::Exclude(parts) | SpecifiedParts::Use(parts) => { for part in parts { if !available_parts.contains(part.keyword.name()) { let msg = format!( @@ -738,7 +741,8 @@ fn convert_pallets(pallets: Vec) -> syn::Result (), } diff --git a/bizinikiwi/pezframe/support/procedural/src/derive_impl.rs b/bizinikiwi/pezframe/support/procedural/src/derive_impl.rs index f5db12f2..00082fea 100644 --- a/bizinikiwi/pezframe/support/procedural/src/derive_impl.rs +++ b/bizinikiwi/pezframe/support/procedural/src/derive_impl.rs @@ -78,7 +78,9 @@ impl syn::parse::Parse for DeriveImplAttrArgs { (default_impl_path, Some(args.clone())) }, Some(PathSegment { arguments: PathArguments::None, .. }) => (default_impl_path, None), - _ => return Err(syn::Error::new(default_impl_path.span(), "Invalid default impl path")), + _ => { + return Err(syn::Error::new(default_impl_path.span(), "Invalid default impl path")) + }, }; let lookahead = input.lookahead1(); @@ -228,13 +230,14 @@ fn compute_disambiguation_path( ) -> Result { match (disambiguation_path, foreign_impl.clone().trait_) { (Some(disambiguation_path), _) => Ok(disambiguation_path), - (None, Some((_, foreign_impl_path, _))) => + (None, Some((_, foreign_impl_path, _))) => { if default_impl_path.segments.len() > 1 { let scope = default_impl_path.segments.first(); Ok(parse_quote!(#scope :: #foreign_impl_path)) } else { Ok(foreign_impl_path) - }, + } + }, _ => Err(syn::Error::new( default_impl_path.span(), "Impl statement must have a defined type being implemented \ diff --git a/bizinikiwi/pezframe/support/procedural/src/lib.rs b/bizinikiwi/pezframe/support/procedural/src/lib.rs index eb01e476..f58b6903 100644 --- a/bizinikiwi/pezframe/support/procedural/src/lib.rs +++ b/bizinikiwi/pezframe/support/procedural/src/lib.rs @@ -820,15 +820,15 @@ pub fn register_default_impl(attrs: TokenStream, tokens: TokenStream) -> TokenSt pub fn inject_runtime_type(_: TokenStream, tokens: TokenStream) -> TokenStream { let item = tokens.clone(); let item = syn::parse_macro_input!(item as TraitItemType); - if item.ident != "RuntimeCall" && - item.ident != "RuntimeEvent" && - item.ident != "RuntimeTask" && - item.ident != "RuntimeViewFunction" && - item.ident != "RuntimeOrigin" && - item.ident != "RuntimeHoldReason" && - item.ident != "RuntimeFreezeReason" && - item.ident != "RuntimeParameters" && - item.ident != "PalletInfo" + if item.ident != "RuntimeCall" + && item.ident != "RuntimeEvent" + && item.ident != "RuntimeTask" + && item.ident != "RuntimeViewFunction" + && item.ident != "RuntimeOrigin" + && item.ident != "RuntimeHoldReason" + && item.ident != "RuntimeFreezeReason" + && item.ident != "RuntimeParameters" + && item.ident != "PalletInfo" { return syn::Error::new_spanned( item, diff --git a/bizinikiwi/pezframe/support/procedural/src/no_bound/default.rs b/bizinikiwi/pezframe/support/procedural/src/no_bound/default.rs index e88ea3a3..a344ca4e 100644 --- a/bizinikiwi/pezframe/support/procedural/src/no_bound/default.rs +++ b/bizinikiwi/pezframe/support/procedural/src/no_bound/default.rs @@ -138,13 +138,14 @@ pub fn derive_default_no_bound(input: proc_macro::TokenStream) -> proc_macro::To }, } }, - Data::Union(union_) => + Data::Union(union_) => { return syn::Error::new_spanned( union_.union_token, "Union type not supported by `derive(DefaultNoBound)`", ) .to_compile_error() - .into(), + .into() + }, }; quote!( diff --git a/bizinikiwi/pezframe/support/procedural/src/no_bound/partial_ord.rs b/bizinikiwi/pezframe/support/procedural/src/no_bound/partial_ord.rs index e407eaa7..eb297c0d 100644 --- a/bizinikiwi/pezframe/support/procedural/src/no_bound/partial_ord.rs +++ b/bizinikiwi/pezframe/support/procedural/src/no_bound/partial_ord.rs @@ -27,9 +27,9 @@ pub fn derive_partial_ord_no_bound(input: proc_macro::TokenStream) -> proc_macro let name = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); - let impl_ = match input.data { - syn::Data::Struct(struct_) => - match struct_.fields { + let impl_ = + match input.data { + syn::Data::Struct(struct_) => match struct_.fields { syn::Fields::Named(named) => { let fields = named.named.iter().map(|i| &i.ident).map( @@ -66,15 +66,15 @@ pub fn derive_partial_ord_no_bound(input: proc_macro::TokenStream) -> proc_macro quote::quote!(Some(core::cmp::Ordering::Equal)) }, }, - syn::Data::Enum(_) => { - let msg = "Enum type not supported by `derive(PartialOrdNoBound)`"; - return syn::Error::new(input.span(), msg).to_compile_error().into(); - }, - syn::Data::Union(_) => { - let msg = "Union type not supported by `derive(PartialOrdNoBound)`"; - return syn::Error::new(input.span(), msg).to_compile_error().into(); - }, - }; + syn::Data::Enum(_) => { + let msg = "Enum type not supported by `derive(PartialOrdNoBound)`"; + return syn::Error::new(input.span(), msg).to_compile_error().into(); + }, + syn::Data::Union(_) => { + let msg = "Union type not supported by `derive(PartialOrdNoBound)`"; + return syn::Error::new(input.span(), msg).to_compile_error().into(); + }, + }; quote::quote!( const _: () = { diff --git a/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/documentation.rs b/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/documentation.rs index 50e56361..92f94971 100644 --- a/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/documentation.rs +++ b/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/documentation.rs @@ -50,10 +50,12 @@ fn parse_doc_value(attr: &Attribute) -> syn::Result> { match &meta.value { syn::Expr::Lit(lit) => Ok(Some(DocMetaValue::Lit(lit.lit.clone()))), - syn::Expr::Macro(mac) if mac.mac.path.is_ident("include_str") => - Ok(Some(DocMetaValue::Path(mac.mac.parse_body()?))), - _ => - Err(syn::Error::new(attr.span(), "Expected `= \"docs\"` or `= include_str!(\"PATH\")`")), + syn::Expr::Macro(mac) if mac.mac.path.is_ident("include_str") => { + Ok(Some(DocMetaValue::Path(mac.mac.parse_body()?))) + }, + _ => { + Err(syn::Error::new(attr.span(), "Expected `= \"docs\"` or `= include_str!(\"PATH\")`")) + }, } } diff --git a/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/genesis_config.rs b/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/genesis_config.rs index 7ec57f5d..12bf57b3 100644 --- a/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/genesis_config.rs +++ b/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/genesis_config.rs @@ -83,9 +83,9 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { let serde_crate = format!("{}::__private::serde", pezframe_support.to_token_stream()); match genesis_config_item { - syn::Item::Enum(syn::ItemEnum { attrs, .. }) | - syn::Item::Struct(syn::ItemStruct { attrs, .. }) | - syn::Item::Type(syn::ItemType { attrs, .. }) => { + syn::Item::Enum(syn::ItemEnum { attrs, .. }) + | syn::Item::Struct(syn::ItemStruct { attrs, .. }) + | syn::Item::Type(syn::ItemType { attrs, .. }) => { if get_doc_literals(attrs).is_empty() { attrs.push(syn::parse_quote!( #[doc = r" diff --git a/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/storage.rs b/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/storage.rs index 4bd67e0c..e61c1cf8 100644 --- a/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/storage.rs +++ b/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/storage.rs @@ -198,8 +198,8 @@ pub fn process_generics(def: &mut Def) -> syn::Result syn::Result syn::Result= args.args.len() && - matches!(storage_def.query_kind.as_ref(), Some(QueryKind::ResultQuery(_, _))) + if on_empty_idx >= args.args.len() + && matches!(storage_def.query_kind.as_ref(), Some(QueryKind::ResultQuery(_, _))) { let value_ty = match args.args[value_idx].clone() { syn::GenericArgument::Type(ty) => ty, diff --git a/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/view_functions.rs b/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/view_functions.rs index a56d4154..75adc3f9 100644 --- a/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/view_functions.rs +++ b/bizinikiwi/pezframe/support/procedural/src/pezpallet/expand/view_functions.rs @@ -21,8 +21,9 @@ use syn::spanned::Spanned; pub fn expand_view_functions(def: &Def) -> TokenStream { let (span, where_clause, view_fns) = match def.view_functions.as_ref() { - Some(view_fns) => - (view_fns.attr_span, view_fns.where_clause.clone(), view_fns.view_functions.clone()), + Some(view_fns) => { + (view_fns.attr_span, view_fns.where_clause.clone(), view_fns.view_functions.clone()) + }, None => (def.item.span(), def.config.where_clause.clone(), Vec::new()), }; diff --git a/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/call.rs b/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/call.rs index 8e45f70c..7c574113 100644 --- a/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/call.rs +++ b/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/call.rs @@ -259,7 +259,10 @@ impl CallDef { let item_impl = if let syn::Item::Impl(item) = item { item } else { - return Err(syn::Error::new(item.span(), "Invalid pezpallet::call, expected item impl")); + return Err(syn::Error::new( + item.span(), + "Invalid pezpallet::call, expected item impl", + )); }; crate::deprecation::prevent_deprecation_attr_on_outer_enum(&item_impl.attrs)?; @@ -406,11 +409,12 @@ impl CallDef { let final_index = match call_index { Some(i) => i, - None => + None => { last_index.map_or(Some(0), |idx| idx.checked_add(1)).ok_or_else(|| { let msg = "Call index doesn't fit into u8, index is 256"; syn::Error::new(method.sig.span(), msg) - })?, + })? + }, }; last_index = Some(final_index); diff --git a/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/composite.rs b/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/composite.rs index 7d966470..144db150 100644 --- a/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/composite.rs +++ b/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/composite.rs @@ -112,11 +112,12 @@ impl CompositeDef { // a fixed variant count. for variant in &item.variants { match variant.fields { - syn::Fields::Named(_) | syn::Fields::Unnamed(_) => + syn::Fields::Named(_) | syn::Fields::Unnamed(_) => { return Err(syn::Error::new( variant.ident.span(), "The composite enum does not support variants with fields!", - )), + )) + }, syn::Fields::Unit => (), } } diff --git a/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/config.rs b/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/config.rs index 782a96c2..c15b2ef4 100644 --- a/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/config.rs +++ b/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/config.rs @@ -309,16 +309,22 @@ fn has_expected_system_config(path: syn::Path, pezframe_system: &syn::Path) -> b (true, false) => // We can't use the path to `pezframe_system` from `frame` if `pezframe_system` is not // being in scope through `frame`. - return false, + { + return false + }, (false, true) => // We know that the only valid pezframe_system path is one that is `pezframe_system`, as // `frame` re-exports it as such. + { syn::parse2::(quote::quote!(pezframe_system)) - .expect("is a valid path; qed"), + .expect("is a valid path; qed") + }, (_, _) => // They are either both `pezframe_system` or both // `pezkuwi_sdk_frame::xyz::pezframe_system`. - pezframe_system.clone(), + { + pezframe_system.clone() + }, }; expected_system_config @@ -331,8 +337,8 @@ fn has_expected_system_config(path: syn::Path, pezframe_system: &syn::Path) -> b .segments .into_iter() .map(|ps| ps.ident) - .collect::>() == - path.segments.into_iter().map(|ps| ps.ident).collect::>() + .collect::>() + == path.segments.into_iter().map(|ps| ps.ident).collect::>() } /// Replace ident `Self` by `T` @@ -340,10 +346,12 @@ pub fn replace_self_by_t(input: proc_macro2::TokenStream) -> proc_macro2::TokenS input .into_iter() .map(|token_tree| match token_tree { - proc_macro2::TokenTree::Group(group) => - proc_macro2::Group::new(group.delimiter(), replace_self_by_t(group.stream())).into(), - proc_macro2::TokenTree::Ident(ident) if ident == "Self" => - proc_macro2::Ident::new("T", ident.span()).into(), + proc_macro2::TokenTree::Group(group) => { + proc_macro2::Group::new(group.delimiter(), replace_self_by_t(group.stream())).into() + }, + proc_macro2::TokenTree::Ident(ident) if ident == "Self" => { + proc_macro2::Ident::new("T", ident.span()).into() + }, other => other, }) .collect() diff --git a/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/error.rs b/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/error.rs index 2c817ac3..2ee44391 100644 --- a/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/error.rs +++ b/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/error.rs @@ -101,8 +101,8 @@ impl ErrorDef { }; match &variant.discriminant { - None | - Some((_, syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(_), .. }))) => {}, + None + | Some((_, syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(_), .. }))) => {}, Some((_, expr)) => { let msg = "Invalid pezpallet::error, only integer discriminants are supported"; return Err(syn::Error::new(expr.span(), msg)); diff --git a/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/mod.rs b/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/mod.rs index d9d30ca3..3c017438 100644 --- a/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/mod.rs +++ b/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/mod.rs @@ -285,12 +285,13 @@ impl Def { // ensure that if `task_enum` is specified, `tasks` is also specified match (&task_enum, &tasks) { - (Some(_), None) => + (Some(_), None) => { return Err(syn::Error::new( *item_span, "Missing `#[pezpallet::tasks_experimental]` impl", - )), - (None, Some(tasks)) => + )) + }, + (None, Some(tasks)) => { if tasks.tasks_attr.is_none() { return Err(syn::Error::new( tasks.item_impl.impl_token.span(), @@ -298,7 +299,8 @@ impl Def { task enum has been omitted", )); } else { - }, + } + }, _ => (), } diff --git a/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/storage.rs b/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/storage.rs index b35bf86b..02eb3b36 100644 --- a/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/storage.rs +++ b/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/storage.rs @@ -52,10 +52,10 @@ pub enum PalletStorageAttr { impl PalletStorageAttr { fn attr_span(&self) -> proc_macro2::Span { match self { - Self::Getter(_, span) | - Self::StorageName(_, span) | - Self::Unbounded(span) | - Self::WhitelistStorage(span) => *span, + Self::Getter(_, span) + | Self::StorageName(_, span) + | Self::Unbounded(span) + | Self::WhitelistStorage(span) => *span, Self::DisableTryDecodeStorage(span) => *span, } } @@ -124,17 +124,20 @@ impl PalletStorageAttrInfo { for attr in attrs { match attr { PalletStorageAttr::Getter(ident, ..) if getter.is_none() => getter = Some(ident), - PalletStorageAttr::StorageName(name, ..) if rename_as.is_none() => - rename_as = Some(name), + PalletStorageAttr::StorageName(name, ..) if rename_as.is_none() => { + rename_as = Some(name) + }, PalletStorageAttr::Unbounded(..) if !unbounded => unbounded = true, PalletStorageAttr::WhitelistStorage(..) if !whitelisted => whitelisted = true, - PalletStorageAttr::DisableTryDecodeStorage(..) if !disable_try_decode_storage => - disable_try_decode_storage = true, - attr => + PalletStorageAttr::DisableTryDecodeStorage(..) if !disable_try_decode_storage => { + disable_try_decode_storage = true + }, + attr => { return Err(syn::Error::new( attr.attr_span(), "Invalid attribute: Duplicate attribute", - )), + )) + }, } } @@ -269,10 +272,12 @@ impl StorageGenerics { Self::Map { value, key, .. } => Metadata::Map { value, key }, Self::CountedMap { value, key, .. } => Metadata::CountedMap { value, key }, Self::Value { value, .. } => Metadata::Value { value }, - Self::NMap { keygen, value, .. } => - Metadata::NMap { keys: collect_keys(&keygen)?, keygen, value }, - Self::CountedNMap { keygen, value, .. } => - Metadata::CountedNMap { keys: collect_keys(&keygen)?, keygen, value }, + Self::NMap { keygen, value, .. } => { + Metadata::NMap { keys: collect_keys(&keygen)?, keygen, value } + }, + Self::CountedNMap { keygen, value, .. } => { + Metadata::CountedNMap { keys: collect_keys(&keygen)?, keygen, value } + }, }; Ok(res) @@ -281,12 +286,12 @@ impl StorageGenerics { /// Return the query kind from the defined generics fn query_kind(&self) -> Option { match &self { - Self::DoubleMap { query_kind, .. } | - Self::Map { query_kind, .. } | - Self::CountedMap { query_kind, .. } | - Self::Value { query_kind, .. } | - Self::NMap { query_kind, .. } | - Self::CountedNMap { query_kind, .. } => query_kind.clone(), + Self::DoubleMap { query_kind, .. } + | Self::Map { query_kind, .. } + | Self::CountedMap { query_kind, .. } + | Self::Value { query_kind, .. } + | Self::NMap { query_kind, .. } + | Self::CountedNMap { query_kind, .. } => query_kind.clone(), } } } @@ -328,8 +333,8 @@ fn check_generics( }; for (gen_name, gen_binding) in map { - if !mandatory_generics.contains(&gen_name.as_str()) && - !optional_generics.contains(&gen_name.as_str()) + if !mandatory_generics.contains(&gen_name.as_str()) + && !optional_generics.contains(&gen_name.as_str()) { let msg = format!( "Invalid pezpallet::storage, Unexpected generic `{}` for `{}`. {}", @@ -600,8 +605,9 @@ fn process_unnamed_generics( }; let res = match storage { - StorageKind::Value => - (None, Metadata::Value { value: retrieve_arg(1)? }, retrieve_arg(2).ok(), false), + StorageKind::Value => { + (None, Metadata::Value { value: retrieve_arg(1)? }, retrieve_arg(2).ok(), false) + }, StorageKind::Map => ( None, Metadata::Map { key: retrieve_arg(2)?, value: retrieve_arg(3)? }, @@ -841,16 +847,22 @@ impl StorageDef { .segments .last() .map_or(false, |s| s.ident == "OptionQuery") => - return Ok(Some(QueryKind::OptionQuery)), + { + return Ok(Some(QueryKind::OptionQuery)) + }, Type::Path(TypePath { path: Path { segments, .. }, .. }) if segments.last().map_or(false, |s| s.ident == "ResultQuery") => + { segments .last() .expect("segments is checked to have the last value; qed") - .clone(), + .clone() + }, Type::Path(path) if path.path.segments.last().map_or(false, |s| s.ident == "ValueQuery") => - return Ok(Some(QueryKind::ValueQuery)), + { + return Ok(Some(QueryKind::ValueQuery)) + }, _ => return Ok(None), }; diff --git a/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/tasks.rs b/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/tasks.rs index f5171377..1d055514 100644 --- a/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/tasks.rs +++ b/bizinikiwi/pezframe/support/procedural/src/pezpallet/parse/tasks.rs @@ -415,11 +415,12 @@ impl TryFrom> for TaskIndexAttr { let colons = value.colons; match value.meta { TaskAttrMeta::TaskIndex(meta) => parse2(quote!(#pound[#pezpallet #colons #meta])), - _ => + _ => { return Err(Error::new( value.span(), format!("`{:?}` cannot be converted to a `TaskIndexAttr`", value.meta), - )), + )) + }, } } } @@ -433,11 +434,12 @@ impl TryFrom> for TaskConditionAttr { let colons = value.colons; match value.meta { TaskAttrMeta::TaskCondition(meta) => parse2(quote!(#pound[#pezpallet #colons #meta])), - _ => + _ => { return Err(Error::new( value.span(), format!("`{:?}` cannot be converted to a `TaskConditionAttr`", value.meta), - )), + )) + }, } } } @@ -451,11 +453,12 @@ impl TryFrom> for TaskWeightAttr { let colons = value.colons; match value.meta { TaskAttrMeta::TaskWeight(meta) => parse2(quote!(#pound[#pezpallet #colons #meta])), - _ => + _ => { return Err(Error::new( value.span(), format!("`{:?}` cannot be converted to a `TaskWeightAttr`", value.meta), - )), + )) + }, } } } @@ -469,11 +472,12 @@ impl TryFrom> for TaskListAttr { let colons = value.colons; match value.meta { TaskAttrMeta::TaskList(meta) => parse2(quote!(#pound[#pezpallet #colons #meta])), - _ => + _ => { return Err(Error::new( value.span(), format!("`{:?}` cannot be converted to a `TaskListAttr`", value.meta), - )), + )) + }, } } } @@ -534,12 +538,12 @@ fn partition_task_attrs(item: &ImplItemFn) -> (Vec, Vec proc_macro::TokenS let max_encoded_size = match data { syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields { - syn::Fields::Named(syn::FieldsNamed { named: fields, .. }) | - syn::Fields::Unnamed(syn::FieldsUnnamed { unnamed: fields, .. }) => { + syn::Fields::Named(syn::FieldsNamed { named: fields, .. }) + | syn::Fields::Unnamed(syn::FieldsUnnamed { unnamed: fields, .. }) => { let maybe_field_tys = fields .iter() .map(|f| generate_field_types(f, &pezframe_support)) @@ -166,8 +166,8 @@ fn generate_variant_field_types( } match &variant.fields { - syn::Fields::Named(syn::FieldsNamed { named: fields, .. }) | - syn::Fields::Unnamed(syn::FieldsUnnamed { unnamed: fields, .. }) => { + syn::Fields::Named(syn::FieldsNamed { named: fields, .. }) + | syn::Fields::Unnamed(syn::FieldsUnnamed { unnamed: fields, .. }) => { let field_tys = fields .iter() .map(|field| generate_field_types(field, scrate)) diff --git a/bizinikiwi/pezframe/support/procedural/src/runtime/expand/mod.rs b/bizinikiwi/pezframe/support/procedural/src/runtime/expand/mod.rs index 8aa7b5fd..b3946a41 100644 --- a/bizinikiwi/pezframe/support/procedural/src/runtime/expand/mod.rs +++ b/bizinikiwi/pezframe/support/procedural/src/runtime/expand/mod.rs @@ -102,8 +102,9 @@ fn construct_runtime_implicit_to_explicit( let runtime_param = &pezpallet.runtime_param; let pezpallet_segment_and_instance = match (&pezpallet.pezpallet_segment, &pezpallet.instance) { - (Some(segment), Some(instance)) => - quote::quote!(::#segment<#runtime_param, #instance>), + (Some(segment), Some(instance)) => { + quote::quote!(::#segment<#runtime_param, #instance>) + }, (Some(segment), None) => quote::quote!(::#segment<#runtime_param>), (None, Some(instance)) => quote::quote!(<#instance>), (None, None) => quote::quote!(), diff --git a/bizinikiwi/pezframe/support/procedural/src/storage_alias.rs b/bizinikiwi/pezframe/support/procedural/src/storage_alias.rs index e98347c1..c90c4578 100644 --- a/bizinikiwi/pezframe/support/procedural/src/storage_alias.rs +++ b/bizinikiwi/pezframe/support/procedural/src/storage_alias.rs @@ -228,8 +228,8 @@ impl StorageType { >; } }, - Self::CountedMap { value_ty, query_type, hasher_ty, key_ty, .. } | - Self::Map { value_ty, query_type, hasher_ty, key_ty, .. } => { + Self::CountedMap { value_ty, query_type, hasher_ty, key_ty, .. } + | Self::Map { value_ty, query_type, hasher_ty, key_ty, .. } => { let query_type = query_type.as_ref().map(|(c, t)| quote!(#c #t)); let map_type = Ident::new( match self { @@ -294,11 +294,11 @@ impl StorageType { /// The prefix for this storage type. fn prefix(&self) -> &Type { match self { - Self::Value { prefix, .. } | - Self::Map { prefix, .. } | - Self::CountedMap { prefix, .. } | - Self::NMap { prefix, .. } | - Self::DoubleMap { prefix, .. } => prefix, + Self::Value { prefix, .. } + | Self::Map { prefix, .. } + | Self::CountedMap { prefix, .. } + | Self::NMap { prefix, .. } + | Self::DoubleMap { prefix, .. } => prefix, } } } @@ -550,7 +550,7 @@ fn generate_storage_instance( .unwrap_or_default(); let (pezpallet_prefix, impl_generics, type_generics) = match prefix_type { - PrefixType::Compatibility => + PrefixType::Compatibility => { if !impl_generics_used_by_prefix.is_empty() { let type_generics = impl_generics_used_by_prefix.iter().map(|g| &g.ident); let impl_generics = impl_generics_used_by_prefix.iter(); @@ -571,15 +571,17 @@ fn generate_storage_instance( prefix, "If there are no generics, the prefix is only allowed to be an identifier.", )); - }, + } + }, PrefixType::Verbatim => { let prefix_str = match prefix.get_ident() { Some(p) => p.to_string(), - None => + None => { return Err(Error::new_spanned( prefix, "Prefix type `verbatim` requires that the prefix is an ident.", - )), + )) + }, }; (quote!(#prefix_str), quote!(), quote!()) diff --git a/bizinikiwi/pezframe/support/src/migrations.rs b/bizinikiwi/pezframe/support/src/migrations.rs index 48b32396..096de020 100644 --- a/bizinikiwi/pezframe/support/src/migrations.rs +++ b/bizinikiwi/pezframe/support/src/migrations.rs @@ -182,8 +182,9 @@ impl< match ::decode_all(&mut &versioned_post_upgrade_data_bytes[..]) .map_err(|_| "VersionedMigration post_upgrade failed to decode PreUpgradeData")? { - VersionedPostUpgradeData::MigrationExecuted(inner_bytes) => - Inner::post_upgrade(inner_bytes), + VersionedPostUpgradeData::MigrationExecuted(inner_bytes) => { + Inner::post_upgrade(inner_bytes) + }, VersionedPostUpgradeData::Noop => Ok(()), } } diff --git a/bizinikiwi/pezframe/support/src/storage/child.rs b/bizinikiwi/pezframe/support/src/storage/child.rs index 7052b5c5..655e1fed 100644 --- a/bizinikiwi/pezframe/support/src/storage/child.rs +++ b/bizinikiwi/pezframe/support/src/storage/child.rs @@ -112,8 +112,9 @@ pub fn take_or_else T>( /// Check to see if `key` has an explicit entry in storage. pub fn exists(child_info: &ChildInfo, key: &[u8]) -> bool { match child_info.child_type() { - ChildType::ParentKeyId => - pezsp_io::default_child_storage::exists(child_info.storage_key(), key), + ChildType::ParentKeyId => { + pezsp_io::default_child_storage::exists(child_info.storage_key(), key) + }, } } @@ -139,8 +140,9 @@ pub fn exists(child_info: &ChildInfo, key: &[u8]) -> bool { #[deprecated = "Use `clear_storage` instead"] pub fn kill_storage(child_info: &ChildInfo, limit: Option) -> KillStorageResult { match child_info.child_type() { - ChildType::ParentKeyId => - pezsp_io::default_child_storage::storage_kill(child_info.storage_key(), limit), + ChildType::ParentKeyId => { + pezsp_io::default_child_storage::storage_kill(child_info.storage_key(), limit) + }, } } @@ -185,8 +187,9 @@ pub fn clear_storage( // enabled. // pezsp_io::default_child_storage::storage_kill(prefix, maybe_limit, maybe_cursor) let r = match child_info.child_type() { - ChildType::ParentKeyId => - pezsp_io::default_child_storage::storage_kill(child_info.storage_key(), maybe_limit), + ChildType::ParentKeyId => { + pezsp_io::default_child_storage::storage_kill(child_info.storage_key(), maybe_limit) + }, }; use pezsp_io::KillStorageResult::*; let (maybe_cursor, backend) = match r { @@ -208,24 +211,27 @@ pub fn kill(child_info: &ChildInfo, key: &[u8]) { /// Get a Vec of bytes from storage. pub fn get_raw(child_info: &ChildInfo, key: &[u8]) -> Option> { match child_info.child_type() { - ChildType::ParentKeyId => - pezsp_io::default_child_storage::get(child_info.storage_key(), key), + ChildType::ParentKeyId => { + pezsp_io::default_child_storage::get(child_info.storage_key(), key) + }, } } /// Put a raw byte slice into storage. pub fn put_raw(child_info: &ChildInfo, key: &[u8], value: &[u8]) { match child_info.child_type() { - ChildType::ParentKeyId => - pezsp_io::default_child_storage::set(child_info.storage_key(), key, value), + ChildType::ParentKeyId => { + pezsp_io::default_child_storage::set(child_info.storage_key(), key, value) + }, } } /// Calculate current child root value. pub fn root(child_info: &ChildInfo, version: StateVersion) -> Vec { match child_info.child_type() { - ChildType::ParentKeyId => - pezsp_io::default_child_storage::root(child_info.storage_key(), version), + ChildType::ParentKeyId => { + pezsp_io::default_child_storage::root(child_info.storage_key(), version) + }, } } diff --git a/bizinikiwi/pezframe/support/src/storage/generator/mod.rs b/bizinikiwi/pezframe/support/src/storage/generator/mod.rs index 358d6af9..a1260c0c 100644 --- a/bizinikiwi/pezframe/support/src/storage/generator/mod.rs +++ b/bizinikiwi/pezframe/support/src/storage/generator/mod.rs @@ -189,9 +189,13 @@ mod tests { ); // do translation. - NumberMap::translate( - |k: u32, v: u64| if k.is_multiple_of(2) { Some(((k as u64) << 32) | v) } else { None }, - ); + NumberMap::translate(|k: u32, v: u64| { + if k.is_multiple_of(2) { + Some(((k as u64) << 32) | v) + } else { + None + } + }); assert_eq!( NumberMap::iter().collect::>(), diff --git a/bizinikiwi/pezframe/support/src/storage/stream_iter.rs b/bizinikiwi/pezframe/support/src/storage/stream_iter.rs index a95e98d7..d0bd7591 100644 --- a/bizinikiwi/pezframe/support/src/storage/stream_iter.rs +++ b/bizinikiwi/pezframe/support/src/storage/stream_iter.rs @@ -592,7 +592,10 @@ mod tests { pezsp_io::TestExternalities::default().execute_with(|| { const BUFFER_SIZE: usize = 300; // Ensure that the capacity isn't dividable by `300`. - assert!(!STORAGE_INPUT_BUFFER_CAPACITY.is_multiple_of(BUFFER_SIZE), "Please update buffer size"); + assert!( + !STORAGE_INPUT_BUFFER_CAPACITY.is_multiple_of(BUFFER_SIZE), + "Please update buffer size" + ); // Create some items where the last item is partially in the inner buffer so that // we need to fill the buffer to read the entire item. let data: Vec> = (0..=(STORAGE_INPUT_BUFFER_CAPACITY / BUFFER_SIZE)) @@ -640,7 +643,10 @@ mod tests { const BUFFER_SIZE: usize = 300; // Ensure that the capacity isn't dividable by `300`. - assert!(!STORAGE_INPUT_BUFFER_CAPACITY.is_multiple_of(BUFFER_SIZE), "Please update buffer size"); + assert!( + !STORAGE_INPUT_BUFFER_CAPACITY.is_multiple_of(BUFFER_SIZE), + "Please update buffer size" + ); // Create some items where the last item is partially in the inner buffer so that // we need to fill the buffer to read the entire item. let data: Vec> = (0..=(STORAGE_INPUT_BUFFER_CAPACITY / BUFFER_SIZE)) diff --git a/bizinikiwi/pezframe/support/src/storage/types/counted_nmap.rs b/bizinikiwi/pezframe/support/src/storage/types/counted_nmap.rs index b2a76592..79e348cb 100644 --- a/bizinikiwi/pezframe/support/src/storage/types/counted_nmap.rs +++ b/bizinikiwi/pezframe/support/src/storage/types/counted_nmap.rs @@ -1389,9 +1389,9 @@ mod test { let _ = A::clear(u32::max_value(), None); // one of the item has been removed assert!( - !A::contains_key((2, 20, 200)) && - !A::contains_key((3, 30, 300)) && - !A::contains_key((4, 40, 400)) + !A::contains_key((2, 20, 200)) + && !A::contains_key((3, 30, 300)) + && !A::contains_key((4, 40, 400)) ); assert_eq!(A::count(), 0); diff --git a/bizinikiwi/pezframe/support/src/traits/reality.rs b/bizinikiwi/pezframe/support/src/traits/reality.rs index c2665f97..8dd22b9a 100644 --- a/bizinikiwi/pezframe/support/src/traits/reality.rs +++ b/bizinikiwi/pezframe/support/src/traits/reality.rs @@ -261,8 +261,8 @@ pub mod identity { pub fn eq_platform(&self, other: &Social) -> bool { matches!( (&self, &other), - (Social::Twitter { .. }, Social::Twitter { .. }) | - (Social::Github { .. }, Social::Github { .. }) + (Social::Twitter { .. }, Social::Twitter { .. }) + | (Social::Github { .. }, Social::Github { .. }) ) } } diff --git a/bizinikiwi/pezframe/support/src/traits/tokens/fungible/union_of.rs b/bizinikiwi/pezframe/support/src/traits/tokens/fungible/union_of.rs index efa8b85c..5529fd53 100644 --- a/bizinikiwi/pezframe/support/src/traits/tokens/fungible/union_of.rs +++ b/bizinikiwi/pezframe/support/src/traits/tokens/fungible/union_of.rs @@ -154,8 +154,9 @@ impl< force: Fortitude, ) -> Self::Balance { match Criterion::convert(asset) { - Left(()) => - >::reducible_balance(who, preservation, force), + Left(()) => { + >::reducible_balance(who, preservation, force) + }, Right(a) => >::reducible_balance( a, who, @@ -171,10 +172,12 @@ impl< provenance: Provenance, ) -> DepositConsequence { match Criterion::convert(asset) { - Left(()) => - >::can_deposit(who, amount, provenance), - Right(a) => - >::can_deposit(a, who, amount, provenance), + Left(()) => { + >::can_deposit(who, amount, provenance) + }, + Right(a) => { + >::can_deposit(a, who, amount, provenance) + }, } } fn can_withdraw( @@ -211,21 +214,24 @@ impl< force: Fortitude, ) -> Self::Balance { match Criterion::convert(asset) { - Left(()) => + Left(()) => { >::reducible_total_balance_on_hold( who, force, - ), - Right(a) => + ) + }, + Right(a) => { >::reducible_total_balance_on_hold( a, who, force, - ), + ) + }, } } fn hold_available(asset: Self::AssetId, reason: &Self::Reason, who: &AccountId) -> bool { match Criterion::convert(asset) { Left(()) => >::hold_available(reason, who), - Right(a) => - >::hold_available(a, reason, who), + Right(a) => { + >::hold_available(a, reason, who) + }, } } fn total_balance_on_hold(asset: Self::AssetId, who: &AccountId) -> Self::Balance { @@ -241,8 +247,9 @@ impl< ) -> Self::Balance { match Criterion::convert(asset) { Left(()) => >::balance_on_hold(reason, who), - Right(a) => - >::balance_on_hold(a, reason, who), + Right(a) => { + >::balance_on_hold(a, reason, who) + }, } } fn can_hold( @@ -253,8 +260,9 @@ impl< ) -> bool { match Criterion::convert(asset) { Left(()) => >::can_hold(reason, who, amount), - Right(a) => - >::can_hold(a, reason, who, amount), + Right(a) => { + >::can_hold(a, reason, who, amount) + }, } } } @@ -301,10 +309,12 @@ impl< Self: Sized, { match Criterion::convert(dust.0) { - Left(()) => - >::handle_dust(fungible::Dust(dust.1)), - Right(a) => - >::handle_dust(fungibles::Dust(a, dust.1)), + Left(()) => { + >::handle_dust(fungible::Dust(dust.1)) + }, + Right(a) => { + >::handle_dust(fungibles::Dust(a, dust.1)) + }, } } fn write_balance( @@ -356,8 +366,9 @@ impl< precision: Precision, ) -> Result { match Criterion::convert(asset) { - Left(()) => - >::increase_balance(who, amount, precision), + Left(()) => { + >::increase_balance(who, amount, precision) + }, Right(a) => >::increase_balance( a, who, amount, precision, ), @@ -494,8 +505,9 @@ impl< preservation: Preservation, ) -> Result { match Criterion::convert(asset) { - Left(()) => - >::transfer(source, dest, amount, preservation), + Left(()) => { + >::transfer(source, dest, amount, preservation) + }, Right(a) => >::transfer( a, source, @@ -541,8 +553,9 @@ impl< precision: Precision, ) -> Result { match Criterion::convert(asset) { - Left(()) => - >::release(reason, who, amount, precision), + Left(()) => { + >::release(reason, who, amount, precision) + }, Right(a) => >::release( a, reason, who, amount, precision, ), @@ -634,8 +647,9 @@ impl< ) -> DispatchResult { match Criterion::convert(asset) { Left(()) => >::set_freeze(id, who, amount), - Right(a) => - >::set_freeze(a, id, who, amount), + Right(a) => { + >::set_freeze(a, id, who, amount) + }, } } fn extend_freeze( @@ -646,8 +660,9 @@ impl< ) -> DispatchResult { match Criterion::convert(asset) { Left(()) => >::extend_freeze(id, who, amount), - Right(a) => - >::extend_freeze(a, id, who, amount), + Right(a) => { + >::extend_freeze(a, id, who, amount) + }, } } fn thaw(asset: Self::AssetId, id: &Self::Id, who: &AccountId) -> DispatchResult { @@ -723,9 +738,10 @@ impl< match Criterion::convert(asset.clone()) { Left(()) => >::deposit(who, value, precision) .map(|d| fungibles::imbalance::from_fungible(d, asset)), - Right(a) => + Right(a) => { >::deposit(a, who, value, precision) - .map(|d| fungibles::imbalance::from_fungibles(d, asset)), + .map(|d| fungibles::imbalance::from_fungibles(d, asset)) + }, } } fn issue(asset: Self::AssetId, amount: Self::Balance) -> fungibles::Credit { @@ -959,8 +975,9 @@ impl< fn touch(asset: AssetKind, who: &AccountId, depositor: &AccountId) -> DispatchResult { match Criterion::convert(asset) { Left(()) => >::touch((), who, depositor), - Right(a) => - >::touch(a, who, depositor), + Right(a) => { + >::touch(a, who, depositor) + }, } } } diff --git a/bizinikiwi/pezframe/support/src/traits/tokens/fungibles/union_of.rs b/bizinikiwi/pezframe/support/src/traits/tokens/fungibles/union_of.rs index f41600cb..33fa9474 100644 --- a/bizinikiwi/pezframe/support/src/traits/tokens/fungibles/union_of.rs +++ b/bizinikiwi/pezframe/support/src/traits/tokens/fungibles/union_of.rs @@ -113,10 +113,12 @@ impl< provenance: Provenance, ) -> DepositConsequence { match Criterion::convert(asset) { - Left(a) => - >::can_deposit(a, who, amount, provenance), - Right(a) => - >::can_deposit(a, who, amount, provenance), + Left(a) => { + >::can_deposit(a, who, amount, provenance) + }, + Right(a) => { + >::can_deposit(a, who, amount, provenance) + }, } } fn can_withdraw( @@ -153,21 +155,24 @@ impl< force: Fortitude, ) -> Self::Balance { match Criterion::convert(asset) { - Left(a) => + Left(a) => { >::reducible_total_balance_on_hold( a, who, force, - ), - Right(a) => + ) + }, + Right(a) => { >::reducible_total_balance_on_hold( a, who, force, - ), + ) + }, } } fn hold_available(asset: Self::AssetId, reason: &Self::Reason, who: &AccountId) -> bool { match Criterion::convert(asset) { Left(a) => >::hold_available(a, reason, who), - Right(a) => - >::hold_available(a, reason, who), + Right(a) => { + >::hold_available(a, reason, who) + }, } } fn total_balance_on_hold(asset: Self::AssetId, who: &AccountId) -> Self::Balance { @@ -183,8 +188,9 @@ impl< ) -> Self::Balance { match Criterion::convert(asset) { Left(a) => >::balance_on_hold(a, reason, who), - Right(a) => - >::balance_on_hold(a, reason, who), + Right(a) => { + >::balance_on_hold(a, reason, who) + }, } } fn can_hold( @@ -194,10 +200,12 @@ impl< amount: Self::Balance, ) -> bool { match Criterion::convert(asset) { - Left(a) => - >::can_hold(a, reason, who, amount), - Right(a) => - >::can_hold(a, reason, who, amount), + Left(a) => { + >::can_hold(a, reason, who, amount) + }, + Right(a) => { + >::can_hold(a, reason, who, amount) + }, } } } @@ -244,10 +252,12 @@ impl< Self: Sized, { match Criterion::convert(dust.0) { - Left(a) => - >::handle_dust(fungibles::Dust(a, dust.1)), - Right(a) => - >::handle_dust(fungibles::Dust(a, dust.1)), + Left(a) => { + >::handle_dust(fungibles::Dust(a, dust.1)) + }, + Right(a) => { + >::handle_dust(fungibles::Dust(a, dust.1)) + }, } } fn write_balance( @@ -587,8 +597,9 @@ impl< ) -> DispatchResult { match Criterion::convert(asset) { Left(a) => >::set_freeze(a, id, who, amount), - Right(a) => - >::set_freeze(a, id, who, amount), + Right(a) => { + >::set_freeze(a, id, who, amount) + }, } } fn extend_freeze( @@ -598,10 +609,12 @@ impl< amount: Self::Balance, ) -> DispatchResult { match Criterion::convert(asset) { - Left(a) => - >::extend_freeze(a, id, who, amount), - Right(a) => - >::extend_freeze(a, id, who, amount), + Left(a) => { + >::extend_freeze(a, id, who, amount) + }, + Right(a) => { + >::extend_freeze(a, id, who, amount) + }, } } fn thaw(asset: Self::AssetId, id: &Self::Id, who: &AccountId) -> DispatchResult { @@ -701,9 +714,10 @@ impl< match Criterion::convert(asset.clone()) { Left(a) => >::deposit(a, who, value, precision) .map(|debt| imbalance::from_fungibles(debt, asset)), - Right(a) => + Right(a) => { >::deposit(a, who, value, precision) - .map(|debt| imbalance::from_fungibles(debt, asset)), + .map(|debt| imbalance::from_fungibles(debt, asset)) + }, } } fn issue(asset: Self::AssetId, amount: Self::Balance) -> fungibles::Credit { @@ -895,8 +909,9 @@ impl< min_balance: Self::Balance, ) -> DispatchResult { match Criterion::convert(asset) { - Left(a) => - >::create(a, admin, is_sufficient, min_balance), + Left(a) => { + >::create(a, admin, is_sufficient, min_balance) + }, Right(a) => >::create( a, admin, @@ -939,8 +954,9 @@ impl< fn touch(asset: AssetKind, who: &AccountId, depositor: &AccountId) -> DispatchResult { match Criterion::convert(asset) { Left(a) => >::touch(a, who, depositor), - Right(a) => - >::touch(a, who, depositor), + Right(a) => { + >::touch(a, who, depositor) + }, } } } diff --git a/bizinikiwi/pezframe/support/src/traits/tokens/imbalance/signed_imbalance.rs b/bizinikiwi/pezframe/support/src/traits/tokens/imbalance/signed_imbalance.rs index ce2c8409..99920e98 100644 --- a/bizinikiwi/pezframe/support/src/traits/tokens/imbalance/signed_imbalance.rs +++ b/bizinikiwi/pezframe/support/src/traits/tokens/imbalance/signed_imbalance.rs @@ -54,10 +54,12 @@ impl< /// both. pub fn merge(self, other: Self) -> Self { match (self, other) { - (SignedImbalance::Positive(one), SignedImbalance::Positive(other)) => - SignedImbalance::Positive(one.merge(other)), - (SignedImbalance::Negative(one), SignedImbalance::Negative(other)) => - SignedImbalance::Negative(one.merge(other)), + (SignedImbalance::Positive(one), SignedImbalance::Positive(other)) => { + SignedImbalance::Positive(one.merge(other)) + }, + (SignedImbalance::Negative(one), SignedImbalance::Negative(other)) => { + SignedImbalance::Negative(one.merge(other)) + }, (SignedImbalance::Positive(one), SignedImbalance::Negative(other)) => { match one.offset(other) { SameOrOther::Same(positive) => SignedImbalance::Positive(positive), diff --git a/bizinikiwi/pezframe/support/src/traits/try_runtime/mod.rs b/bizinikiwi/pezframe/support/src/traits/try_runtime/mod.rs index 8efdaacf..b441e87d 100644 --- a/bizinikiwi/pezframe/support/src/traits/try_runtime/mod.rs +++ b/bizinikiwi/pezframe/support/src/traits/try_runtime/mod.rs @@ -90,7 +90,7 @@ impl std::str::FromStr for Select { match s { "all" | "All" => Ok(Select::All), "none" | "None" => Ok(Select::None), - _ => + _ => { if s.starts_with("rr-") { let count = s .split_once('-') @@ -108,7 +108,8 @@ impl std::str::FromStr for Select { } else { let pallets = s.split(',').map(|x| x.as_bytes().to_vec()).collect::>(); Ok(Select::Only(pallets)) - }, + } + }, } } } diff --git a/bizinikiwi/pezframe/support/test/tests/authorize.rs b/bizinikiwi/pezframe/support/test/tests/authorize.rs index 6d7bde51..834071dd 100644 --- a/bizinikiwi/pezframe/support/test/tests/authorize.rs +++ b/bizinikiwi/pezframe/support/test/tests/authorize.rs @@ -365,8 +365,8 @@ fn valid_call_weight_test() { dispatch_success: true, call_weight: pallet1::CALL_2_WEIGHT, ext_weight: pallet1::CALL_2_AUTH_WEIGHT, - actual_weight: pallet1::CALL_2_REFUND + pallet1::CALL_2_AUTH_WEIGHT - - call_2_auth_weight_refund, + actual_weight: pallet1::CALL_2_REFUND + pallet1::CALL_2_AUTH_WEIGHT + - call_2_auth_weight_refund, }, Test { call: RuntimeCall::Pallet1Instance2(pallet1::Call::call3 { valid: true, some_gen: 1 }), diff --git a/bizinikiwi/pezframe/support/test/tests/pallet.rs b/bizinikiwi/pezframe/support/test/tests/pallet.rs index 9ab28a8c..766bd940 100644 --- a/bizinikiwi/pezframe/support/test/tests/pallet.rs +++ b/bizinikiwi/pezframe/support/test/tests/pallet.rs @@ -1871,9 +1871,9 @@ fn metadata_v15() { }, ]; - let empty_doc = pallets[0].event.as_ref().unwrap().ty.type_info().docs.is_empty() && - pallets[0].error.as_ref().unwrap().ty.type_info().docs.is_empty() && - pallets[0].calls.as_ref().unwrap().ty.type_info().docs.is_empty(); + let empty_doc = pallets[0].event.as_ref().unwrap().ty.type_info().docs.is_empty() + && pallets[0].error.as_ref().unwrap().ty.type_info().docs.is_empty() + && pallets[0].calls.as_ref().unwrap().ty.type_info().docs.is_empty(); if cfg!(feature = "no-metadata-docs") { assert!(empty_doc) @@ -2462,8 +2462,8 @@ fn post_runtime_upgrade_detects_storage_version_issues() { // The version isn't changed, we should detect it. assert!( - Executive::try_runtime_upgrade(UpgradeCheckSelect::PreAndPost).unwrap_err() == - "On chain and in-code storage version do not match. Missing runtime upgrade?" + Executive::try_runtime_upgrade(UpgradeCheckSelect::PreAndPost).unwrap_err() + == "On chain and in-code storage version do not match. Missing runtime upgrade?" .into() ); }); @@ -2493,8 +2493,8 @@ fn post_runtime_upgrade_detects_storage_version_issues() { // any storage version "enabled". assert!( ExecutiveWithUpgradePallet4::try_runtime_upgrade(UpgradeCheckSelect::PreAndPost) - .unwrap_err() == - "On chain storage version set, while the pezpallet \ + .unwrap_err() + == "On chain storage version set, while the pezpallet \ doesn't have the `#[pezpallet::storage_version(VERSION)]` attribute." .into() ); @@ -2523,11 +2523,11 @@ fn test_dispatch_context() { fn test_call_feature_parsing() { let call = pezpallet::Call::::check_for_dispatch_context {}; match call { - pezpallet::Call::::check_for_dispatch_context {} | - pezpallet::Call::::foo { .. } | - pezpallet::Call::foo_storage_layer { .. } | - pezpallet::Call::foo_index_out_of_order {} | - pezpallet::Call::foo_no_post_info {} => (), + pezpallet::Call::::check_for_dispatch_context {} + | pezpallet::Call::::foo { .. } + | pezpallet::Call::foo_storage_layer { .. } + | pezpallet::Call::foo_index_out_of_order {} + | pezpallet::Call::foo_no_post_info {} => (), #[cfg(feature = "frame-feature-testing")] pezpallet::Call::foo_feature_test {} => (), pezpallet::Call::__Ignore(_, _) => (), @@ -2539,11 +2539,11 @@ fn test_call_feature_parsing() { fn test_error_feature_parsing() { let err = pezpallet::Error::::InsufficientProposersBalance; match err { - pezpallet::Error::InsufficientProposersBalance | - pezpallet::Error::NonExistentStorageValue | - pezpallet::Error::Code(_) | - pezpallet::Error::Skipped(_) | - pezpallet::Error::CompactU8(_) => (), + pezpallet::Error::InsufficientProposersBalance + | pezpallet::Error::NonExistentStorageValue + | pezpallet::Error::Code(_) + | pezpallet::Error::Skipped(_) + | pezpallet::Error::CompactU8(_) => (), #[cfg(feature = "frame-feature-testing")] pezpallet::Error::FeatureTest => (), pezpallet::Error::__Ignore(_, _) => (), diff --git a/bizinikiwi/pezframe/support/test/tests/tasks.rs b/bizinikiwi/pezframe/support/test/tests/tasks.rs index 07e94a18..084fba67 100644 --- a/bizinikiwi/pezframe/support/test/tests/tasks.rs +++ b/bizinikiwi/pezframe/support/test/tests/tasks.rs @@ -121,7 +121,8 @@ fn tasks_work() { pezframe_support::assert_ok!(System::do_task(RuntimeOrigin::signed(1), task.clone(),)); assert_eq!(my_pezpallet::SomeStorage::::get(), (0, 2)); - let task = RuntimeTask::MyPallet2(my_pezpallet::Task::::Foo { _i: 0u32, _j: 2u64 }); + let task = + RuntimeTask::MyPallet2(my_pezpallet::Task::::Foo { _i: 0u32, _j: 2u64 }); pezframe_support::assert_ok!(System::do_task(RuntimeOrigin::signed(1), task.clone(),)); assert_eq!(my_pezpallet::SomeStorage::::get(), (0, 2)); diff --git a/bizinikiwi/pezframe/system/benchmarking/src/extensions.rs b/bizinikiwi/pezframe/system/benchmarking/src/extensions.rs index 645c753f..863f84aa 100644 --- a/bizinikiwi/pezframe/system/benchmarking/src/extensions.rs +++ b/bizinikiwi/pezframe/system/benchmarking/src/extensions.rs @@ -247,9 +247,9 @@ mod benchmarks { assert_eq!( System::::block_weight().total(), - initial_block_weight + - base_extrinsic + - post_info.actual_weight.unwrap().saturating_add(extension_weight), + initial_block_weight + + base_extrinsic + + post_info.actual_weight.unwrap().saturating_add(extension_weight), ); Ok(()) } @@ -292,9 +292,9 @@ mod benchmarks { assert_eq!( System::::block_weight().total(), - initial_block_weight + - base_extrinsic + - post_info.actual_weight.unwrap().saturating_add(extension_weight), + initial_block_weight + + base_extrinsic + + post_info.actual_weight.unwrap().saturating_add(extension_weight), ); Ok(()) } diff --git a/bizinikiwi/pezframe/system/src/extensions/check_weight.rs b/bizinikiwi/pezframe/system/src/extensions/check_weight.rs index 6af2bbdf..f8bb9823 100644 --- a/bizinikiwi/pezframe/system/src/extensions/check_weight.rs +++ b/bizinikiwi/pezframe/system/src/extensions/check_weight.rs @@ -366,8 +366,8 @@ mod tests { fn normal_extrinsic_limited_by_maximum_extrinsic_weight() { new_test_ext().execute_with(|| { let max = DispatchInfo { - call_weight: block_weights().get(DispatchClass::Normal).max_extrinsic.unwrap() + - Weight::from_parts(1, 0), + call_weight: block_weights().get(DispatchClass::Normal).max_extrinsic.unwrap() + + Weight::from_parts(1, 0), class: DispatchClass::Normal, ..Default::default() }; @@ -710,9 +710,9 @@ mod tests { .0; assert_eq!( BlockWeight::::get().total(), - info.total_weight() + - Weight::from_parts(128, 0) + - block_weights().get(DispatchClass::Normal).base_extrinsic, + info.total_weight() + + Weight::from_parts(128, 0) + + block_weights().get(DispatchClass::Normal).base_extrinsic, ); assert_ok!(CheckWeight::::post_dispatch_details( @@ -724,9 +724,9 @@ mod tests { )); assert_eq!( BlockWeight::::get().total(), - info.total_weight() + - Weight::from_parts(128, 0) + - block_weights().get(DispatchClass::Normal).base_extrinsic, + info.total_weight() + + Weight::from_parts(128, 0) + + block_weights().get(DispatchClass::Normal).base_extrinsic, ); }) } diff --git a/bizinikiwi/pezframe/system/src/lib.rs b/bizinikiwi/pezframe/system/src/lib.rs index 5f204984..3dbf0e58 100644 --- a/bizinikiwi/pezframe/system/src/lib.rs +++ b/bizinikiwi/pezframe/system/src/lib.rs @@ -887,8 +887,9 @@ pub mod pezpallet { match Self::can_set_code(&code, res.check_version) { CanSetCodeResult::Ok => {}, - CanSetCodeResult::MultiBlockMigrationsOngoing => - return Err(Error::::MultiBlockMigrationsOngoing.into()), + CanSetCodeResult::MultiBlockMigrationsOngoing => { + return Err(Error::::MultiBlockMigrationsOngoing.into()) + }, CanSetCodeResult::InvalidVersion(error) => { // The upgrade is invalid and there is no benefit in trying to apply this again. Self::deposit_event(Event::RejectedInvalidAuthorizedUpgrade { @@ -1549,8 +1550,9 @@ impl CanSetCodeResult { pub fn into_result(self) -> Result<(), DispatchError> { match self { Self::Ok => Ok(()), - Self::MultiBlockMigrationsOngoing => - Err(Error::::MultiBlockMigrationsOngoing.into()), + Self::MultiBlockMigrationsOngoing => { + Err(Error::::MultiBlockMigrationsOngoing.into()) + }, Self::InvalidVersion(err) => Err(err.into()), } } diff --git a/bizinikiwi/pezframe/tips/src/benchmarking.rs b/bizinikiwi/pezframe/tips/src/benchmarking.rs index c88eb559..c148b82a 100644 --- a/bizinikiwi/pezframe/tips/src/benchmarking.rs +++ b/bizinikiwi/pezframe/tips/src/benchmarking.rs @@ -34,9 +34,9 @@ const SEED: u32 = 0; // Create the pre-requisite information needed to create a `report_awesome`. fn setup_awesome, I: 'static>(length: u32) -> (T::AccountId, Vec, T::AccountId) { let caller = whitelisted_caller(); - let value = T::TipReportDepositBase::get() + - T::DataDepositPerByte::get() * length.into() + - T::Currency::minimum_balance(); + let value = T::TipReportDepositBase::get() + + T::DataDepositPerByte::get() * length.into() + + T::Currency::minimum_balance(); let _ = T::Currency::make_free_balance_be(&caller, value); let reason = vec![0; length as usize]; let awesome_person = account("awesome", 0, SEED); diff --git a/bizinikiwi/pezframe/tips/src/lib.rs b/bizinikiwi/pezframe/tips/src/lib.rs index 6a8281b0..51d4ef48 100644 --- a/bizinikiwi/pezframe/tips/src/lib.rs +++ b/bizinikiwi/pezframe/tips/src/lib.rs @@ -270,8 +270,8 @@ pub mod pezpallet { let hash = T::Hashing::hash_of(&(&reason_hash, &who)); ensure!(!Tips::::contains_key(&hash), Error::::AlreadyKnown); - let deposit = T::TipReportDepositBase::get() + - T::DataDepositPerByte::get() * (reason.len() as u32).into(); + let deposit = T::TipReportDepositBase::get() + + T::DataDepositPerByte::get() * (reason.len() as u32).into(); T::Currency::reserve(&finder, deposit)?; Reasons::::insert(&reason_hash, &reason); diff --git a/bizinikiwi/pezframe/tips/src/migrations/unreserve_deposits.rs b/bizinikiwi/pezframe/tips/src/migrations/unreserve_deposits.rs index 83980935..c7ba3b30 100644 --- a/bizinikiwi/pezframe/tips/src/migrations/unreserve_deposits.rs +++ b/bizinikiwi/pezframe/tips/src/migrations/unreserve_deposits.rs @@ -151,8 +151,8 @@ where // If it is higher, there is either a bug with the pezpallet or a bug in the calculation of // the deposit amount. ensure!( - account_deposits.iter().all(|(account, deposit)| *deposit <= - *account_reserved_before.get(account).unwrap_or(&Zero::zero())), + account_deposits.iter().all(|(account, deposit)| *deposit + <= *account_reserved_before.get(account).unwrap_or(&Zero::zero())), "Deposit amount is greater than reserved amount" ); @@ -290,17 +290,17 @@ mod test { // Verify the expected amount is reserved assert_eq!( ::Currency::reserved_balance(&tipper_0), - tipper_0_initial_reserved + - ::TipReportDepositBase::get() + - ::DataDepositPerByte::get() * - tip_0_reason.len() as u64 + tipper_0_initial_reserved + + ::TipReportDepositBase::get() + + ::DataDepositPerByte::get() + * tip_0_reason.len() as u64 ); assert_eq!( ::Currency::reserved_balance(&tipper_1), - tipper_1_initial_reserved + - ::TipReportDepositBase::get() + - ::DataDepositPerByte::get() * - tip_1_reason.len() as u64 + tipper_1_initial_reserved + + ::TipReportDepositBase::get() + + ::DataDepositPerByte::get() + * tip_1_reason.len() as u64 ); // Execute the migration diff --git a/bizinikiwi/pezframe/transaction-payment/asset-conversion-tx-payment/src/lib.rs b/bizinikiwi/pezframe/transaction-payment/asset-conversion-tx-payment/src/lib.rs index 0d88bc1a..39c87f89 100644 --- a/bizinikiwi/pezframe/transaction-payment/asset-conversion-tx-payment/src/lib.rs +++ b/bizinikiwi/pezframe/transaction-payment/asset-conversion-tx-payment/src/lib.rs @@ -352,8 +352,9 @@ where _result: &DispatchResult, ) -> Result { let (tip, who, initial_payment, extension_weight) = match pre { - Pre::Charge { tip, who, initial_payment, weight } => - (tip, who, initial_payment, weight), + Pre::Charge { tip, who, initial_payment, weight } => { + (tip, who, initial_payment, weight) + }, Pre::NoCharge { refund } => { // No-op: Refund everything return Ok(refund); diff --git a/bizinikiwi/pezframe/transaction-payment/asset-conversion-tx-payment/src/payment.rs b/bizinikiwi/pezframe/transaction-payment/asset-conversion-tx-payment/src/payment.rs index 7d9da04d..eb1da2ba 100644 --- a/bizinikiwi/pezframe/transaction-payment/asset-conversion-tx-payment/src/payment.rs +++ b/bizinikiwi/pezframe/transaction-payment/asset-conversion-tx-payment/src/payment.rs @@ -184,15 +184,16 @@ where if asset_id == A::get() { // The `asset_id` is the target asset, we do not need to swap. match F::can_withdraw(asset_id.clone(), who, fee) { - WithdrawConsequence::BalanceLow | - WithdrawConsequence::UnknownAsset | - WithdrawConsequence::Underflow | - WithdrawConsequence::Overflow | - WithdrawConsequence::Frozen => - return Err(TransactionValidityError::from(InvalidTransaction::Payment)), - WithdrawConsequence::Success | - WithdrawConsequence::ReducedToZero(_) | - WithdrawConsequence::WouldDie => return Ok(()), + WithdrawConsequence::BalanceLow + | WithdrawConsequence::UnknownAsset + | WithdrawConsequence::Underflow + | WithdrawConsequence::Overflow + | WithdrawConsequence::Frozen => { + return Err(TransactionValidityError::from(InvalidTransaction::Payment)) + }, + WithdrawConsequence::Success + | WithdrawConsequence::ReducedToZero(_) + | WithdrawConsequence::WouldDie => return Ok(()), } } @@ -202,15 +203,16 @@ where // Ensure we can withdraw enough `asset_id` for the swap. match F::can_withdraw(asset_id.clone(), who, asset_fee) { - WithdrawConsequence::BalanceLow | - WithdrawConsequence::UnknownAsset | - WithdrawConsequence::Underflow | - WithdrawConsequence::Overflow | - WithdrawConsequence::Frozen => - return Err(TransactionValidityError::from(InvalidTransaction::Payment)), - WithdrawConsequence::Success | - WithdrawConsequence::ReducedToZero(_) | - WithdrawConsequence::WouldDie => {}, + WithdrawConsequence::BalanceLow + | WithdrawConsequence::UnknownAsset + | WithdrawConsequence::Underflow + | WithdrawConsequence::Overflow + | WithdrawConsequence::Frozen => { + return Err(TransactionValidityError::from(InvalidTransaction::Payment)) + }, + WithdrawConsequence::Success + | WithdrawConsequence::ReducedToZero(_) + | WithdrawConsequence::WouldDie => {}, }; Ok(()) @@ -227,8 +229,8 @@ where ) -> Result, TransactionValidityError> { let (fee_paid, initial_asset_consumed) = already_withdrawn; let refund_amount = fee_paid.peek().saturating_sub(corrected_fee); - let (fee_in_asset, adjusted_paid) = if refund_amount.is_zero() || - F::total_balance(asset_id.clone(), who).is_zero() + let (fee_in_asset, adjusted_paid) = if refund_amount.is_zero() + || F::total_balance(asset_id.clone(), who).is_zero() { // Nothing to refund or the account was removed be the dispatched function. (initial_asset_consumed, fee_paid) diff --git a/bizinikiwi/pezframe/transaction-payment/asset-tx-payment/src/lib.rs b/bizinikiwi/pezframe/transaction-payment/asset-tx-payment/src/lib.rs index de24a974..5f84b2b1 100644 --- a/bizinikiwi/pezframe/transaction-payment/asset-tx-payment/src/lib.rs +++ b/bizinikiwi/pezframe/transaction-payment/asset-tx-payment/src/lib.rs @@ -377,8 +377,9 @@ where result: &DispatchResult, ) -> Result { let (tip, who, initial_payment, asset_id, extension_weight) = match pre { - Pre::Charge { tip, who, initial_payment, asset_id, weight } => - (tip, who, initial_payment, asset_id, weight), + Pre::Charge { tip, who, initial_payment, asset_id, weight } => { + (tip, who, initial_payment, asset_id, weight) + }, Pre::NoCharge { refund } => { // No-op: Refund everything return Ok(refund); diff --git a/bizinikiwi/pezframe/transaction-payment/asset-tx-payment/src/tests.rs b/bizinikiwi/pezframe/transaction-payment/asset-tx-payment/src/tests.rs index e9228269..d9ba675b 100644 --- a/bizinikiwi/pezframe/transaction-payment/asset-tx-payment/src/tests.rs +++ b/bizinikiwi/pezframe/transaction-payment/asset-tx-payment/src/tests.rs @@ -333,8 +333,9 @@ fn asset_transaction_payment_with_tip_and_refund() { let len = 10; // we convert the from weight to fee based on the ratio between asset min balance and // existential deposit - let fee_with_tip = (base_weight + weight + ext_weight.ref_time() + len as u64 + tip) * - min_balance / ExistentialDeposit::get(); + let fee_with_tip = (base_weight + weight + ext_weight.ref_time() + len as u64 + tip) + * min_balance + / ExistentialDeposit::get(); let mut info = info_from_weight(Weight::from_parts(weight, 0)); info.extension_weight = ext_weight; let (pre, _) = @@ -360,10 +361,10 @@ fn asset_transaction_payment_with_tip_and_refund() { len, &Ok(()), )); - let final_fee = fee_with_tip - - (weight - final_weight + ext_weight.ref_time() - - MockWeights::charge_asset_tx_payment_asset().ref_time()) * - min_balance / ExistentialDeposit::get(); + let final_fee = fee_with_tip + - (weight - final_weight + ext_weight.ref_time() + - MockWeights::charge_asset_tx_payment_asset().ref_time()) + * min_balance / ExistentialDeposit::get(); assert_eq!(Assets::balance(asset_id, caller), balance - (final_fee)); assert_eq!(Assets::balance(asset_id, BLOCK_AUTHOR), final_fee); diff --git a/bizinikiwi/pezframe/transaction-payment/src/lib.rs b/bizinikiwi/pezframe/transaction-payment/src/lib.rs index facf9712..a3f1558e 100644 --- a/bizinikiwi/pezframe/transaction-payment/src/lib.rs +++ b/bizinikiwi/pezframe/transaction-payment/src/lib.rs @@ -254,8 +254,8 @@ where let diff = Multiplier::saturating_from_rational(diff_abs, max_limiting_dimension.max(1)); let diff_squared = diff.saturating_mul(diff); - let v_squared_2 = adjustment_variable.saturating_mul(adjustment_variable) / - Multiplier::saturating_from_integer(2); + let v_squared_2 = adjustment_variable.saturating_mul(adjustment_variable) + / Multiplier::saturating_from_integer(2); let first_term = adjustment_variable.saturating_mul(diff); let second_term = v_squared_2.saturating_mul(diff_squared); @@ -475,15 +475,15 @@ pub mod pezpallet { // at most be maximum block weight. Make sure that this can fit in a multiplier without // loss. assert!( - ::max_value() >= - Multiplier::checked_from_integer::( + ::max_value() + >= Multiplier::checked_from_integer::( T::BlockWeights::get().max_block.ref_time().try_into().unwrap() ) .unwrap(), ); - let target = T::FeeMultiplierUpdate::target() * - T::BlockWeights::get().get(DispatchClass::Normal).max_total.expect( + let target = T::FeeMultiplierUpdate::target() + * T::BlockWeights::get().get(DispatchClass::Normal).max_total.expect( "Setting `max_total` for `Normal` dispatch class is not compatible with \ `transaction-payment` pezpallet.", ); diff --git a/bizinikiwi/pezframe/uniques/src/lib.rs b/bizinikiwi/pezframe/uniques/src/lib.rs index 6196b501..389d259c 100644 --- a/bizinikiwi/pezframe/uniques/src/lib.rs +++ b/bizinikiwi/pezframe/uniques/src/lib.rs @@ -1133,8 +1133,9 @@ pub mod pezpallet { } let maybe_is_frozen = match maybe_item { None => CollectionMetadataOf::::get(collection.clone()).map(|v| v.is_frozen), - Some(item) => - ItemMetadataOf::::get(collection.clone(), item).map(|v| v.is_frozen), + Some(item) => { + ItemMetadataOf::::get(collection.clone(), item).map(|v| v.is_frozen) + }, }; ensure!(!maybe_is_frozen.unwrap_or(false), Error::::Frozen); @@ -1196,8 +1197,9 @@ pub mod pezpallet { } let maybe_is_frozen = match maybe_item { None => CollectionMetadataOf::::get(collection.clone()).map(|v| v.is_frozen), - Some(item) => - ItemMetadataOf::::get(collection.clone(), item).map(|v| v.is_frozen), + Some(item) => { + ItemMetadataOf::::get(collection.clone(), item).map(|v| v.is_frozen) + }, }; ensure!(!maybe_is_frozen.unwrap_or(false), Error::::Frozen); diff --git a/bizinikiwi/pezframe/utility/src/lib.rs b/bizinikiwi/pezframe/utility/src/lib.rs index e7ca2d44..60d4d122 100644 --- a/bizinikiwi/pezframe/utility/src/lib.rs +++ b/bizinikiwi/pezframe/utility/src/lib.rs @@ -143,8 +143,8 @@ pub mod pezpallet { fn batched_calls_limit() -> u32 { let allocator_limit = pezsp_core::MAX_POSSIBLE_ALLOCATION; let call_size = (core::mem::size_of::<::RuntimeCall>() as u32) - .div_ceil(CALL_ALIGN) * - CALL_ALIGN; + .div_ceil(CALL_ALIGN) + * CALL_ALIGN; // The margin to take into account vec doubling capacity. let margin_factor = 3; diff --git a/bizinikiwi/pezframe/vesting/src/lib.rs b/bizinikiwi/pezframe/vesting/src/lib.rs index 9e46fac1..709d4a8c 100644 --- a/bizinikiwi/pezframe/vesting/src/lib.rs +++ b/bizinikiwi/pezframe/vesting/src/lib.rs @@ -703,8 +703,8 @@ impl Pezpallet { }; debug_assert!( - locked_now > Zero::zero() && schedules.len() > 0 || - locked_now == Zero::zero() && schedules.len() == 0 + locked_now > Zero::zero() && schedules.len() > 0 + || locked_now == Zero::zero() && schedules.len() == 0 ); Ok((schedules, locked_now)) diff --git a/bizinikiwi/pezframe/vesting/src/tests.rs b/bizinikiwi/pezframe/vesting/src/tests.rs index 497863d9..4e25d10b 100644 --- a/bizinikiwi/pezframe/vesting/src/tests.rs +++ b/bizinikiwi/pezframe/vesting/src/tests.rs @@ -1156,16 +1156,16 @@ fn vested_transfer_less_than_existential_deposit_fails() { ExtBuilder::default().existential_deposit(4 * ED).build().execute_with(|| { // MinVestedTransfer is less the ED. assert!( - ::Currency::minimum_balance() > - ::MinVestedTransfer::get() + ::Currency::minimum_balance() + > ::MinVestedTransfer::get() ); let sched = VestingInfo::new(::MinVestedTransfer::get() as u64, 1u64, 10u64); // The new account balance with the schedule's locked amount would be less than ED. assert!( - Balances::free_balance(&99) + sched.locked() < - ::Currency::minimum_balance() + Balances::free_balance(&99) + sched.locked() + < ::Currency::minimum_balance() ); // vested_transfer fails. diff --git a/bizinikiwi/pezframe/vesting/src/vesting_info.rs b/bizinikiwi/pezframe/vesting/src/vesting_info.rs index f8911410..07316e8d 100644 --- a/bizinikiwi/pezframe/vesting/src/vesting_info.rs +++ b/bizinikiwi/pezframe/vesting/src/vesting_info.rs @@ -110,8 +110,8 @@ where // the block after starting. One::one() } else { - self.locked / self.per_block() + - if (self.locked % self.per_block()).is_zero() { + self.locked / self.per_block() + + if (self.locked % self.per_block()).is_zero() { Zero::zero() } else { // `per_block` does not perfectly divide `locked`, so we need an extra block to diff --git a/bizinikiwi/primitives/api/proc-macro/src/decl_runtime_apis.rs b/bizinikiwi/primitives/api/proc-macro/src/decl_runtime_apis.rs index ba1d1cf9..1058d421 100644 --- a/bizinikiwi/primitives/api/proc-macro/src/decl_runtime_apis.rs +++ b/bizinikiwi/primitives/api/proc-macro/src/decl_runtime_apis.rs @@ -221,8 +221,9 @@ fn generate_runtime_decls(decls: &[ItemTrait]) -> Result { ); let err2 = match found_attributes.get(&API_VERSION_ATTRIBUTE) { - Some(attr) => - Error::new(attr.span(), "Trait version is set here."), + Some(attr) => { + Error::new(attr.span(), "Trait version is set here.") + }, None => Error::new( decl_span, "Trait version is not set so it is implicitly equal to 1.", @@ -676,12 +677,13 @@ impl<'ast> Visit<'ast> for CheckTraitDecl { fn visit_generic_param(&mut self, input: &'ast GenericParam) { match input { - GenericParam::Type(ty) if ty.ident == BLOCK_GENERIC_IDENT => + GenericParam::Type(ty) if ty.ident == BLOCK_GENERIC_IDENT => { self.errors.push(Error::new( input.span(), "`Block: BlockT` generic parameter will be added automatically by the \ `decl_runtime_apis!` macro!", - )), + )) + }, _ => {}, } diff --git a/bizinikiwi/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs b/bizinikiwi/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs index adc0ad51..ef2b73f3 100644 --- a/bizinikiwi/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs +++ b/bizinikiwi/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs @@ -213,7 +213,10 @@ fn get_at_param_name( let ptype_and_borrows = param_types_and_borrows.remove(0); let span = ptype_and_borrows.1.span(); if ptype_and_borrows.1 { - return Err(Error::new(span, "`Hash` needs to be taken by value and not by reference!")); + return Err(Error::new( + span, + "`Hash` needs to be taken by value and not by reference!", + )); } let name = param_names.remove(0); @@ -378,7 +381,7 @@ fn generate_runtime_api_impls(impls: &[ItemImpl]) -> Result + Some(self_ty) => { if self_ty == impl_.self_ty { Some(self_ty) } else { @@ -390,12 +393,13 @@ fn generate_runtime_api_impls(impls: &[ItemImpl]) -> Result Some(impl_.self_ty.clone()), }; global_block_type = match global_block_type.take() { - Some(global_block_type) => + Some(global_block_type) => { if global_block_type == *block_type { Some(global_block_type) } else { @@ -410,7 +414,8 @@ fn generate_runtime_api_impls(impls: &[ItemImpl]) -> Result Some(block_type.clone()), }; diff --git a/bizinikiwi/primitives/api/proc-macro/src/utils.rs b/bizinikiwi/primitives/api/proc-macro/src/utils.rs index 3a10ce46..66c07548 100644 --- a/bizinikiwi/primitives/api/proc-macro/src/utils.rs +++ b/bizinikiwi/primitives/api/proc-macro/src/utils.rs @@ -146,12 +146,14 @@ pub fn extract_parameter_names_types_and_borrows( let name = sanitize_pattern((*arg.pat).clone(), &mut generated_pattern_counter); result.push((name, ty, borrow)); }, - FnArg::Receiver(_) if matches!(allow_self, AllowSelfRefInParameters::No) => - return Err(Error::new(input.span(), "`self` parameter not supported!")), - FnArg::Receiver(recv) => + FnArg::Receiver(_) if matches!(allow_self, AllowSelfRefInParameters::No) => { + return Err(Error::new(input.span(), "`self` parameter not supported!")) + }, + FnArg::Receiver(recv) => { if recv.mutability.is_some() || recv.reference.is_none() { return Err(Error::new(recv.span(), "Only `&self` is supported!")); - }, + } + }, } } @@ -186,8 +188,9 @@ pub fn extract_block_type_from_trait_path(trait_: &Path) -> Result<&TypePath> { let span = trait_.segments.last().as_ref().unwrap().span(); Err(Error::new(span, "Missing `Block` generic parameter.")) }, - PathArguments::Parenthesized(_) => - Err(Error::new(generics.arguments.span(), "Unexpected parentheses in path!")), + PathArguments::Parenthesized(_) => { + Err(Error::new(generics.arguments.span(), "Unexpected parentheses in path!")) + }, } } diff --git a/bizinikiwi/primitives/arithmetic/fuzzer/src/fixed_point.rs b/bizinikiwi/primitives/arithmetic/fuzzer/src/fixed_point.rs index 97535fd2..9f50d313 100644 --- a/bizinikiwi/primitives/arithmetic/fuzzer/src/fixed_point.rs +++ b/bizinikiwi/primitives/arithmetic/fuzzer/src/fixed_point.rs @@ -76,8 +76,8 @@ fn main() { let a = FixedI64::saturating_from_rational(2, 5); let b = a.saturating_mul_acc_int(x); let xx = FixedI64::saturating_from_integer(x); - let d = a.saturating_mul(xx).saturating_add(xx).into_inner() as i128 / - FixedI64::accuracy() as i128; + let d = a.saturating_mul(xx).saturating_add(xx).into_inner() as i128 + / FixedI64::accuracy() as i128; assert_eq!(b, d); }); } diff --git a/bizinikiwi/primitives/arithmetic/fuzzer/src/multiply_by_rational_with_rounding.rs b/bizinikiwi/primitives/arithmetic/fuzzer/src/multiply_by_rational_with_rounding.rs index c385e662..f966854d 100644 --- a/bizinikiwi/primitives/arithmetic/fuzzer/src/multiply_by_rational_with_rounding.rs +++ b/bizinikiwi/primitives/arithmetic/fuzzer/src/multiply_by_rational_with_rounding.rs @@ -74,19 +74,21 @@ where fn round(f: Fraction, r: Rounding) -> Fraction { match r { Up => f.ceil(), - NearestPrefUp => + NearestPrefUp => { if f.fract() < Fraction::from(0.5) { f.floor() } else { f.ceil() - }, + } + }, Down => f.floor(), - NearestPrefDown => + NearestPrefDown => { if f.fract() > Fraction::from(0.5) { f.ceil() } else { f.floor() - }, + } + }, } } diff --git a/bizinikiwi/primitives/arithmetic/fuzzer/src/per_thing_from_rational.rs b/bizinikiwi/primitives/arithmetic/fuzzer/src/per_thing_from_rational.rs index f8725bd3..eaf05249 100644 --- a/bizinikiwi/primitives/arithmetic/fuzzer/src/per_thing_from_rational.rs +++ b/bizinikiwi/primitives/arithmetic/fuzzer/src/per_thing_from_rational.rs @@ -74,19 +74,21 @@ where fn round(f: Fraction, r: Rounding) -> Fraction { match r { Up => f.ceil(), - NearestPrefUp => + NearestPrefUp => { if f.fract() < Fraction::from(0.5) { f.floor() } else { f.ceil() - }, + } + }, Down => f.floor(), - NearestPrefDown => + NearestPrefDown => { if f.fract() > Fraction::from(0.5) { f.ceil() } else { f.floor() - }, + } + }, } } diff --git a/bizinikiwi/primitives/arithmetic/src/biguint.rs b/bizinikiwi/primitives/arithmetic/src/biguint.rs index 4ab96ac4..e00c036c 100644 --- a/bizinikiwi/primitives/arithmetic/src/biguint.rs +++ b/bizinikiwi/primitives/arithmetic/src/biguint.rs @@ -273,9 +273,9 @@ impl BigUint { let mut k = 0; for i in 0..m { // PROOF: (B−1) × (B−1) + (B−1) + (B−1) = B^2 −1 < B^2. addition is safe. - let t = mul_single(self.get(j), other.get(i)) + - Double::from(w.get(i + j)) + - Double::from(k); + let t = mul_single(self.get(j), other.get(i)) + + Double::from(w.get(i + j)) + + Double::from(k); w.set(i + j, (t % B) as Single); // PROOF: (B^2 - 1) / B < B. conversion is safe. k = (t / B) as Single; diff --git a/bizinikiwi/primitives/arithmetic/src/per_things.rs b/bizinikiwi/primitives/arithmetic/src/per_things.rs index b9d5b0d5..e747f26f 100644 --- a/bizinikiwi/primitives/arithmetic/src/per_things.rs +++ b/bizinikiwi/primitives/arithmetic/src/per_things.rs @@ -490,10 +490,12 @@ impl Rounding { match (rounding, negative) { (Low, true) | (Major, _) | (High, false) => Up, (High, true) | (Minor, _) | (Low, false) => Down, - (NearestPrefMajor, _) | (NearestPrefHigh, false) | (NearestPrefLow, true) => - NearestPrefUp, - (NearestPrefMinor, _) | (NearestPrefLow, false) | (NearestPrefHigh, true) => - NearestPrefDown, + (NearestPrefMajor, _) | (NearestPrefHigh, false) | (NearestPrefLow, true) => { + NearestPrefUp + }, + (NearestPrefMinor, _) | (NearestPrefLow, false) | (NearestPrefHigh, true) => { + NearestPrefDown + }, } } } diff --git a/bizinikiwi/primitives/consensus/babe/src/lib.rs b/bizinikiwi/primitives/consensus/babe/src/lib.rs index 5efbba90..258509f3 100644 --- a/bizinikiwi/primitives/consensus/babe/src/lib.rs +++ b/bizinikiwi/primitives/consensus/babe/src/lib.rs @@ -311,8 +311,8 @@ where // both headers must be targeting the same slot and it must // be the same as the one in the proof. - if proof.slot != first_pre_digest.slot() || - first_pre_digest.slot() != second_pre_digest.slot() + if proof.slot != first_pre_digest.slot() + || first_pre_digest.slot() != second_pre_digest.slot() { return None; } diff --git a/bizinikiwi/primitives/consensus/beefy/src/commitment.rs b/bizinikiwi/primitives/consensus/beefy/src/commitment.rs index 531d46e5..b2cbfa4d 100644 --- a/bizinikiwi/primitives/consensus/beefy/src/commitment.rs +++ b/bizinikiwi/primitives/consensus/beefy/src/commitment.rs @@ -153,9 +153,9 @@ impl SignedCommitment { TAuthorityId: RuntimeAppPublic + BeefyAuthorityId, MsgHash: Hash, { - if self.signatures.len() != validator_set.len() || - self.commitment.validator_set_id != validator_set.id() || - self.commitment.block_number != target_number + if self.signatures.len() != validator_set.len() + || self.commitment.validator_set_id != validator_set.id() + || self.commitment.block_number != target_number { return Err(0); } diff --git a/bizinikiwi/primitives/consensus/beefy/src/lib.rs b/bizinikiwi/primitives/consensus/beefy/src/lib.rs index dbf0d661..de341c1e 100644 --- a/bizinikiwi/primitives/consensus/beefy/src/lib.rs +++ b/bizinikiwi/primitives/consensus/beefy/src/lib.rs @@ -405,10 +405,10 @@ where // have different validator set ids, // or both votes have the same commitment, // --> the equivocation is invalid. - if first.id != second.id || - first.commitment.block_number != second.commitment.block_number || - first.commitment.validator_set_id != second.commitment.validator_set_id || - first.commitment.payload == second.commitment.payload + if first.id != second.id + || first.commitment.block_number != second.commitment.block_number + || first.commitment.validator_set_id != second.commitment.validator_set_id + || first.commitment.payload == second.commitment.payload { return false; } diff --git a/bizinikiwi/primitives/consensus/grandpa/src/lib.rs b/bizinikiwi/primitives/consensus/grandpa/src/lib.rs index 9c4861f3..8cf436c8 100644 --- a/bizinikiwi/primitives/consensus/grandpa/src/lib.rs +++ b/bizinikiwi/primitives/consensus/grandpa/src/lib.rs @@ -355,8 +355,8 @@ where macro_rules! check { ( $equivocation:expr, $message:expr ) => { // if both votes have the same target the equivocation is invalid. - if $equivocation.first.0.target_hash == $equivocation.second.0.target_hash && - $equivocation.first.0.target_number == $equivocation.second.0.target_number + if $equivocation.first.0.target_hash == $equivocation.second.0.target_hash + && $equivocation.first.0.target_number == $equivocation.second.0.target_number { return false; } diff --git a/bizinikiwi/primitives/core/src/bandersnatch.rs b/bizinikiwi/primitives/core/src/bandersnatch.rs index f8d27226..8f38d1a9 100644 --- a/bizinikiwi/primitives/core/src/bandersnatch.rs +++ b/bizinikiwi/primitives/core/src/bandersnatch.rs @@ -391,9 +391,9 @@ pub mod ring_vrf { const OVERHEAD_SIZE: usize = 16; const G2_POINTS_NUM: usize = 2; let g1_points_num = ark_vrf::ring::pcs_domain_size::(ring_size); - OVERHEAD_SIZE + - g1_points_num * G1_POINT_UNCOMPRESSED_SIZE + - G2_POINTS_NUM * G2_POINT_UNCOMPRESSED_SIZE + OVERHEAD_SIZE + + g1_points_num * G1_POINT_UNCOMPRESSED_SIZE + + G2_POINTS_NUM * G2_POINT_UNCOMPRESSED_SIZE } /// [`RingVerifierKey`] serialized size. diff --git a/bizinikiwi/primitives/core/src/bls.rs b/bizinikiwi/primitives/core/src/bls.rs index 082255f6..ce619c9d 100644 --- a/bizinikiwi/primitives/core/src/bls.rs +++ b/bizinikiwi/primitives/core/src/bls.rs @@ -121,8 +121,8 @@ pub const SIGNATURE_SERIALIZED_SIZE: usize = as SerializableToBytes>::SERIALIZED_BYTES_SIZE; /// Signature serialized size (for back cert) + Nugget BLS PoP size -pub const PROOF_OF_POSSESSION_SERIALIZED_SIZE: usize = SIGNATURE_SERIALIZED_SIZE + - as SerializableToBytes>::SERIALIZED_BYTES_SIZE; +pub const PROOF_OF_POSSESSION_SERIALIZED_SIZE: usize = SIGNATURE_SERIALIZED_SIZE + + as SerializableToBytes>::SERIALIZED_BYTES_SIZE; /// A secret seed. /// diff --git a/bizinikiwi/primitives/core/src/crypto.rs b/bizinikiwi/primitives/core/src/crypto.rs index 08231d7f..f69b0c6b 100644 --- a/bizinikiwi/primitives/core/src/crypto.rs +++ b/bizinikiwi/primitives/core/src/crypto.rs @@ -1299,14 +1299,16 @@ mod tests { password, path: path.into_iter().chain(path_iter).collect(), }, - TestPair::GeneratedFromPhrase { phrase, password } => - TestPair::Standard { phrase, password, path: path_iter.collect() }, - x => + TestPair::GeneratedFromPhrase { phrase, password } => { + TestPair::Standard { phrase, password, path: path_iter.collect() } + }, + x => { if path_iter.count() == 0 { x } else { return Err(DeriveError::SoftKeyInPath); - }, + } + }, }, None, )) diff --git a/bizinikiwi/primitives/core/src/offchain/storage.rs b/bizinikiwi/primitives/core/src/offchain/storage.rs index fc6e953e..0f8b40a1 100644 --- a/bizinikiwi/primitives/core/src/offchain/storage.rs +++ b/bizinikiwi/primitives/core/src/offchain/storage.rs @@ -75,13 +75,14 @@ impl OffchainStorage for InMemOffchainStorage { let key = prefix.iter().chain(key).cloned().collect(); match self.storage.entry(key) { - Entry::Vacant(entry) => + Entry::Vacant(entry) => { if old_value.is_none() { entry.insert(new_value.to_vec()); true } else { false - }, + } + }, Entry::Occupied(ref mut entry) if Some(entry.get().as_slice()) == old_value => { entry.insert(new_value.to_vec()); true @@ -161,8 +162,9 @@ impl DbExternalities for OffchainDb { "CAS", ); match kind { - StorageKind::PERSISTENT => - self.persistent.compare_and_set(STORAGE_PREFIX, key, old_value, new_value), + StorageKind::PERSISTENT => { + self.persistent.compare_and_set(STORAGE_PREFIX, key, old_value, new_value) + }, StorageKind::LOCAL => unavailable_yet(LOCAL_DB), } } diff --git a/bizinikiwi/primitives/core/src/offchain/testing.rs b/bizinikiwi/primitives/core/src/offchain/testing.rs index 22776424..9eeaee81 100644 --- a/bizinikiwi/primitives/core/src/offchain/testing.rs +++ b/bizinikiwi/primitives/core/src/offchain/testing.rs @@ -80,8 +80,9 @@ impl TestPersistentOffchainDB { let mut me = self.persistent.write(); for ((_prefix, key), value_operation) in changes { match value_operation { - OffchainOverlayedChange::SetValue(val) => - me.set(Self::PREFIX, key.as_slice(), val.as_slice()), + OffchainOverlayedChange::SetValue(val) => { + me.set(Self::PREFIX, key.as_slice(), val.as_slice()) + }, OffchainOverlayedChange::Remove => me.remove(Self::PREFIX, key.as_slice()), } } @@ -381,10 +382,12 @@ impl offchain::DbExternalities for TestOffchainExt { ) -> bool { let mut state = self.0.write(); match kind { - StorageKind::LOCAL => - state.local_storage.compare_and_set(b"", key, old_value, new_value), - StorageKind::PERSISTENT => - state.persistent_storage.compare_and_set(b"", key, old_value, new_value), + StorageKind::LOCAL => { + state.local_storage.compare_and_set(b"", key, old_value, new_value) + }, + StorageKind::PERSISTENT => { + state.persistent_storage.compare_and_set(b"", key, old_value, new_value) + }, } } diff --git a/bizinikiwi/primitives/core/src/sr25519.rs b/bizinikiwi/primitives/core/src/sr25519.rs index f617c4ef..262db005 100644 --- a/bizinikiwi/primitives/core/src/sr25519.rs +++ b/bizinikiwi/primitives/core/src/sr25519.rs @@ -520,25 +520,34 @@ pub mod vrf { NotMarkedSchnorrkel => "Signature error: `NotMarkedSchnorrkel`".into(), BytesLengthError { .. } => "Signature error: `BytesLengthError`".into(), InvalidKey => "Signature error: `InvalidKey`".into(), - MuSigAbsent { musig_stage: Commitment } => - "Signature error: `MuSigAbsent` at stage `Commitment`".into(), - MuSigAbsent { musig_stage: Reveal } => - "Signature error: `MuSigAbsent` at stage `Reveal`".into(), - MuSigAbsent { musig_stage: Cosignature } => - "Signature error: `MuSigAbsent` at stage `Commitment`".into(), - MuSigInconsistent { musig_stage: Commitment, duplicate: true } => - "Signature error: `MuSigInconsistent` at stage `Commitment` on duplicate".into(), - MuSigInconsistent { musig_stage: Commitment, duplicate: false } => - "Signature error: `MuSigInconsistent` at stage `Commitment` on not duplicate".into(), - MuSigInconsistent { musig_stage: Reveal, duplicate: true } => - "Signature error: `MuSigInconsistent` at stage `Reveal` on duplicate".into(), - MuSigInconsistent { musig_stage: Reveal, duplicate: false } => - "Signature error: `MuSigInconsistent` at stage `Reveal` on not duplicate".into(), - MuSigInconsistent { musig_stage: Cosignature, duplicate: true } => - "Signature error: `MuSigInconsistent` at stage `Cosignature` on duplicate".into(), - MuSigInconsistent { musig_stage: Cosignature, duplicate: false } => + MuSigAbsent { musig_stage: Commitment } => { + "Signature error: `MuSigAbsent` at stage `Commitment`".into() + }, + MuSigAbsent { musig_stage: Reveal } => { + "Signature error: `MuSigAbsent` at stage `Reveal`".into() + }, + MuSigAbsent { musig_stage: Cosignature } => { + "Signature error: `MuSigAbsent` at stage `Commitment`".into() + }, + MuSigInconsistent { musig_stage: Commitment, duplicate: true } => { + "Signature error: `MuSigInconsistent` at stage `Commitment` on duplicate".into() + }, + MuSigInconsistent { musig_stage: Commitment, duplicate: false } => { + "Signature error: `MuSigInconsistent` at stage `Commitment` on not duplicate".into() + }, + MuSigInconsistent { musig_stage: Reveal, duplicate: true } => { + "Signature error: `MuSigInconsistent` at stage `Reveal` on duplicate".into() + }, + MuSigInconsistent { musig_stage: Reveal, duplicate: false } => { + "Signature error: `MuSigInconsistent` at stage `Reveal` on not duplicate".into() + }, + MuSigInconsistent { musig_stage: Cosignature, duplicate: true } => { + "Signature error: `MuSigInconsistent` at stage `Cosignature` on duplicate".into() + }, + MuSigInconsistent { musig_stage: Cosignature, duplicate: false } => { "Signature error: `MuSigInconsistent` at stage `Cosignature` on not duplicate" - .into(), + .into() + }, } } diff --git a/bizinikiwi/primitives/crypto/hashing/proc-macro/src/impls.rs b/bizinikiwi/primitives/crypto/hashing/proc-macro/src/impls.rs index 6144a98c..2a566ad8 100644 --- a/bizinikiwi/primitives/crypto/hashing/proc-macro/src/impls.rs +++ b/bizinikiwi/primitives/crypto/hashing/proc-macro/src/impls.rs @@ -48,17 +48,19 @@ impl Parse for InputBytes { syn::Expr::Lit(lit) => match &lit.lit { syn::Lit::Int(b) => bytes.push(b.base10_parse()?), syn::Lit::Byte(b) => bytes.push(b.value()), - _ => + _ => { return Err(syn::Error::new( input.span(), "Expected array of u8 elements.".to_string(), - )), + )) + }, }, - _ => + _ => { return Err(syn::Error::new( input.span(), "Expected array of u8 elements.".to_string(), - )), + )) + }, } } return Ok(InputBytes(bytes)); diff --git a/bizinikiwi/primitives/debug-derive/src/impls.rs b/bizinikiwi/primitives/debug-derive/src/impls.rs index 90bef017..88f280c5 100644 --- a/bizinikiwi/primitives/debug-derive/src/impls.rs +++ b/bizinikiwi/primitives/debug-derive/src/impls.rs @@ -179,8 +179,9 @@ mod implementation { name_str, Fields::new(f.named.iter(), Some(syn::Token!(self)(Span::call_site()))), ), - syn::Fields::Unnamed(ref f) => - derive_fields(name_str, Fields::new(f.unnamed.iter(), None)), + syn::Fields::Unnamed(ref f) => { + derive_fields(name_str, Fields::new(f.unnamed.iter(), None)) + }, syn::Fields::Unit => derive_fields(name_str, Fields::Indexed { indices: vec![] }), } } diff --git a/bizinikiwi/primitives/inherents/src/lib.rs b/bizinikiwi/primitives/inherents/src/lib.rs index 7941b97b..b6647c06 100644 --- a/bizinikiwi/primitives/inherents/src/lib.rs +++ b/bizinikiwi/primitives/inherents/src/lib.rs @@ -367,9 +367,9 @@ impl CheckInherentsResult { #[cfg(feature = "std")] impl PartialEq for CheckInherentsResult { fn eq(&self, other: &Self) -> bool { - self.fatal_error == other.fatal_error && - self.okay == other.okay && - self.errors.data == other.errors.data + self.fatal_error == other.fatal_error + && self.okay == other.okay + && self.errors.data == other.errors.data } } diff --git a/bizinikiwi/primitives/metadata-ir/src/v16.rs b/bizinikiwi/primitives/metadata-ir/src/v16.rs index 5875356b..664f645c 100644 --- a/bizinikiwi/primitives/metadata-ir/src/v16.rs +++ b/bizinikiwi/primitives/metadata-ir/src/v16.rs @@ -205,10 +205,12 @@ impl From for EnumDeprecationInfo { impl From for VariantDeprecationInfo { fn from(ir: VariantDeprecationInfoIR) -> Self { match ir { - VariantDeprecationInfoIR::DeprecatedWithoutNote => - VariantDeprecationInfo::DeprecatedWithoutNote, - VariantDeprecationInfoIR::Deprecated { note, since } => - VariantDeprecationInfo::Deprecated { note, since }, + VariantDeprecationInfoIR::DeprecatedWithoutNote => { + VariantDeprecationInfo::DeprecatedWithoutNote + }, + VariantDeprecationInfoIR::Deprecated { note, since } => { + VariantDeprecationInfo::Deprecated { note, since } + }, } } } @@ -217,10 +219,12 @@ impl From for ItemDeprecationInfo { fn from(ir: ItemDeprecationInfoIR) -> Self { match ir { ItemDeprecationInfoIR::NotDeprecated => ItemDeprecationInfo::NotDeprecated, - ItemDeprecationInfoIR::DeprecatedWithoutNote => - ItemDeprecationInfo::DeprecatedWithoutNote, - ItemDeprecationInfoIR::Deprecated { note, since } => - ItemDeprecationInfo::Deprecated { note, since }, + ItemDeprecationInfoIR::DeprecatedWithoutNote => { + ItemDeprecationInfo::DeprecatedWithoutNote + }, + ItemDeprecationInfoIR::Deprecated { note, since } => { + ItemDeprecationInfo::Deprecated { note, since } + }, } } } diff --git a/bizinikiwi/primitives/npos-elections/fuzzer/src/common.rs b/bizinikiwi/primitives/npos-elections/fuzzer/src/common.rs index 4235b3d8..3ad56422 100644 --- a/bizinikiwi/primitives/npos-elections/fuzzer/src/common.rs +++ b/bizinikiwi/primitives/npos-elections/fuzzer/src/common.rs @@ -158,10 +158,12 @@ pub fn generate_random_npos_result( ( match election_type { - ElectionType::Phragmen(conf) => - seq_phragmen(to_elect, candidates.clone(), voters.clone(), conf).unwrap(), - ElectionType::Phragmms(conf) => - phragmms(to_elect, candidates.clone(), voters.clone(), conf).unwrap(), + ElectionType::Phragmen(conf) => { + seq_phragmen(to_elect, candidates.clone(), voters.clone(), conf).unwrap() + }, + ElectionType::Phragmms(conf) => { + phragmms(to_elect, candidates.clone(), voters.clone(), conf).unwrap() + }, }, candidates, voters, diff --git a/bizinikiwi/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs b/bizinikiwi/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs index 1489d80d..5e277244 100644 --- a/bizinikiwi/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs +++ b/bizinikiwi/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs @@ -86,9 +86,9 @@ fn main() { // The only guarantee of balancing is such that the first and third element of the // score cannot decrease. assert!( - balanced_score.minimal_stake >= unbalanced_score.minimal_stake && - balanced_score.sum_stake == unbalanced_score.sum_stake && - balanced_score.sum_stake_squared <= unbalanced_score.sum_stake_squared + balanced_score.minimal_stake >= unbalanced_score.minimal_stake + && balanced_score.sum_stake == unbalanced_score.sum_stake + && balanced_score.sum_stake_squared <= unbalanced_score.sum_stake_squared ); } }); diff --git a/bizinikiwi/primitives/npos-elections/fuzzer/src/phragmms_balancing.rs b/bizinikiwi/primitives/npos-elections/fuzzer/src/phragmms_balancing.rs index f732fc39..3432b0dd 100644 --- a/bizinikiwi/primitives/npos-elections/fuzzer/src/phragmms_balancing.rs +++ b/bizinikiwi/primitives/npos-elections/fuzzer/src/phragmms_balancing.rs @@ -85,9 +85,9 @@ fn main() { // The only guarantee of balancing is such that the first and third element of the score // cannot decrease. assert!( - balanced_score.minimal_stake >= unbalanced_score.minimal_stake && - balanced_score.sum_stake == unbalanced_score.sum_stake && - balanced_score.sum_stake_squared <= unbalanced_score.sum_stake_squared + balanced_score.minimal_stake >= unbalanced_score.minimal_stake + && balanced_score.sum_stake == unbalanced_score.sum_stake + && balanced_score.sum_stake_squared <= unbalanced_score.sum_stake_squared ); }); } diff --git a/bizinikiwi/primitives/npos-elections/src/pjr.rs b/bizinikiwi/primitives/npos-elections/src/pjr.rs index 47dfd961..e88242e5 100644 --- a/bizinikiwi/primitives/npos-elections/src/pjr.rs +++ b/bizinikiwi/primitives/npos-elections/src/pjr.rs @@ -51,8 +51,8 @@ pub fn standard_threshold( ) -> Threshold { weights .into_iter() - .fold(Threshold::zero(), |acc, elem| acc.saturating_add(elem)) / - committee_size.max(1) as Threshold + .fold(Threshold::zero(), |acc, elem| acc.saturating_add(elem)) + / committee_size.max(1) as Threshold } /// Check a solution to be PJR. diff --git a/bizinikiwi/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs b/bizinikiwi/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs index 9bdcb72b..acc0697b 100644 --- a/bizinikiwi/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs +++ b/bizinikiwi/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs @@ -467,14 +467,15 @@ fn generate_wasm_interface_signature_for_host_function(sig: &Signature) -> Resul /// Generate the variable name that stores the FFI value. fn generate_ffi_value_var_name(pat: &Pat) -> Result { match pat { - Pat::Ident(pat_ident) => + Pat::Ident(pat_ident) => { if let Some(by_ref) = pat_ident.by_ref { Err(Error::new(by_ref.span(), "`ref` not supported!")) } else if let Some(sub_pattern) = &pat_ident.subpat { Err(Error::new(sub_pattern.0.span(), "Not supported!")) } else { Ok(Ident::new(&format!("{}_ffi_value", pat_ident.ident), Span::call_site())) - }, + } + }, _ => Err(Error::new(pat.span(), "Not supported as variable name!")), } } diff --git a/bizinikiwi/primitives/runtime-interface/proc-macro/src/utils.rs b/bizinikiwi/primitives/runtime-interface/proc-macro/src/utils.rs index 666354c4..f66f56dc 100644 --- a/bizinikiwi/primitives/runtime-interface/proc-macro/src/utils.rs +++ b/bizinikiwi/primitives/runtime-interface/proc-macro/src/utils.rs @@ -128,8 +128,8 @@ impl RuntimeInterfaceFunctionSet { self.versions .insert(version.version, RuntimeInterfaceFunction::new(trait_item)?); - if self.latest_version_to_call.map_or(true, |v| v < version.version) && - version.is_callable() + if self.latest_version_to_call.map_or(true, |v| v < version.version) + && version.is_callable() { self.latest_version_to_call = Some(version.version); } @@ -360,9 +360,10 @@ pub fn host_inner_return_ty(ty: &syn::ReturnType) -> syn::ReturnType { let crate_ = generate_crate_access(); match ty { syn::ReturnType::Default => syn::ReturnType::Default, - syn::ReturnType::Type(ref arrow, ref ty) => + syn::ReturnType::Type(ref arrow, ref ty) => { syn::parse2::(quote! { #arrow <#ty as #crate_::RIType>::Inner }) - .expect("parsing doesn't fail"), + .expect("parsing doesn't fail") + }, } } diff --git a/bizinikiwi/primitives/runtime/src/generic/checked_extrinsic.rs b/bizinikiwi/primitives/runtime/src/generic/checked_extrinsic.rs index 429e81de..d1adbf5a 100644 --- a/bizinikiwi/primitives/runtime/src/generic/checked_extrinsic.rs +++ b/bizinikiwi/primitives/runtime/src/generic/checked_extrinsic.rs @@ -147,8 +147,9 @@ impl> pub fn extension_weight(&self) -> Weight { match &self.format { ExtrinsicFormat::Bare => Weight::zero(), - ExtrinsicFormat::Signed(_, ext) | ExtrinsicFormat::General(_, ext) => - ext.weight(&self.function), + ExtrinsicFormat::Signed(_, ext) | ExtrinsicFormat::General(_, ext) => { + ext.weight(&self.function) + }, } } } diff --git a/bizinikiwi/primitives/runtime/src/generic/digest.rs b/bizinikiwi/primitives/runtime/src/generic/digest.rs index 5c3b24ff..3f5d007f 100644 --- a/bizinikiwi/primitives/runtime/src/generic/digest.rs +++ b/bizinikiwi/primitives/runtime/src/generic/digest.rs @@ -356,11 +356,13 @@ impl<'a> DigestItemRef<'a> { /// return the opaque data it contains. pub fn try_as_raw(&self, id: OpaqueDigestItemId) -> Option<&'a [u8]> { match (id, self) { - (OpaqueDigestItemId::Consensus(w), &Self::Consensus(v, s)) | - (OpaqueDigestItemId::Seal(w), &Self::Seal(v, s)) | - (OpaqueDigestItemId::PreRuntime(w), &Self::PreRuntime(v, s)) + (OpaqueDigestItemId::Consensus(w), &Self::Consensus(v, s)) + | (OpaqueDigestItemId::Seal(w), &Self::Seal(v, s)) + | (OpaqueDigestItemId::PreRuntime(w), &Self::PreRuntime(v, s)) if v == w => - Some(s), + { + Some(s) + }, (OpaqueDigestItemId::Other, &Self::Other(s)) => Some(s), _ => None, } @@ -445,14 +447,18 @@ mod tests { let check = |digest_item_type: DigestItemType| { let (variant_name, digest_item) = match digest_item_type { DigestItemType::Other => ("Other", DigestItem::Other(Default::default())), - DigestItemType::Consensus => - ("Consensus", DigestItem::Consensus(Default::default(), Default::default())), - DigestItemType::Seal => - ("Seal", DigestItem::Seal(Default::default(), Default::default())), - DigestItemType::PreRuntime => - ("PreRuntime", DigestItem::PreRuntime(Default::default(), Default::default())), - DigestItemType::RuntimeEnvironmentUpdated => - ("RuntimeEnvironmentUpdated", DigestItem::RuntimeEnvironmentUpdated), + DigestItemType::Consensus => { + ("Consensus", DigestItem::Consensus(Default::default(), Default::default())) + }, + DigestItemType::Seal => { + ("Seal", DigestItem::Seal(Default::default(), Default::default())) + }, + DigestItemType::PreRuntime => { + ("PreRuntime", DigestItem::PreRuntime(Default::default(), Default::default())) + }, + DigestItemType::RuntimeEnvironmentUpdated => { + ("RuntimeEnvironmentUpdated", DigestItem::RuntimeEnvironmentUpdated) + }, }; let encoded = digest_item.encode(); let variant = variants diff --git a/bizinikiwi/primitives/runtime/src/generic/era.rs b/bizinikiwi/primitives/runtime/src/generic/era.rs index a92c004d..d381b60f 100644 --- a/bizinikiwi/primitives/runtime/src/generic/era.rs +++ b/bizinikiwi/primitives/runtime/src/generic/era.rs @@ -105,8 +105,8 @@ impl Encode for Era { Self::Immortal => output.push_byte(0), Self::Mortal(period, phase) => { let quantize_factor = (*period as u64 >> 12).max(1); - let encoded = (period.trailing_zeros() - 1).clamp(1, 15) as u16 | - ((phase / quantize_factor) << 4) as u16; + let encoded = (period.trailing_zeros() - 1).clamp(1, 15) as u16 + | ((phase / quantize_factor) << 4) as u16; encoded.encode_to(output); }, } diff --git a/bizinikiwi/primitives/runtime/src/generic/unchecked_extrinsic.rs b/bizinikiwi/primitives/runtime/src/generic/unchecked_extrinsic.rs index 0b2a5692..ec863134 100644 --- a/bizinikiwi/primitives/runtime/src/generic/unchecked_extrinsic.rs +++ b/bizinikiwi/primitives/runtime/src/generic/unchecked_extrinsic.rs @@ -421,8 +421,9 @@ where format: ExtrinsicFormat::General(extension_version, tx_ext), function: self.function, }, - Preamble::Bare(_) => - CheckedExtrinsic { format: ExtrinsicFormat::Bare, function: self.function }, + Preamble::Bare(_) => { + CheckedExtrinsic { format: ExtrinsicFormat::Bare, function: self.function } + }, }) } @@ -443,8 +444,9 @@ where format: ExtrinsicFormat::General(extension_version, tx_ext), function: self.function, }, - Preamble::Bare(_) => - CheckedExtrinsic { format: ExtrinsicFormat::Bare, function: self.function }, + Preamble::Bare(_) => { + CheckedExtrinsic { format: ExtrinsicFormat::Bare, function: self.function } + }, }) } } diff --git a/bizinikiwi/primitives/runtime/src/lib.rs b/bizinikiwi/primitives/runtime/src/lib.rs index 8a1d4e34..68f1ebb3 100644 --- a/bizinikiwi/primitives/runtime/src/lib.rs +++ b/bizinikiwi/primitives/runtime/src/lib.rs @@ -529,8 +529,8 @@ impl Verify for AnySignature { let msg = msg.get(); sr25519::Signature::try_from(self.0.as_fixed_bytes().as_ref()) .map(|s| s.verify(msg, signer)) - .unwrap_or(false) || - ed25519::Signature::try_from(self.0.as_fixed_bytes().as_ref()) + .unwrap_or(false) + || ed25519::Signature::try_from(self.0.as_fixed_bytes().as_ref()) .map(|s| match ed25519::Public::from_slice(signer.as_ref()) { Err(()) => false, Ok(signer) => s.verify(msg, &signer), @@ -693,8 +693,9 @@ impl DispatchError { /// Return the same error but without the attached message. pub fn stripped(self) -> Self { match self { - DispatchError::Module(ModuleError { index, error, message: Some(_) }) => - DispatchError::Module(ModuleError { index, error, message: None }), + DispatchError::Module(ModuleError { index, error, message: Some(_) }) => { + DispatchError::Module(ModuleError { index, error, message: None }) + }, m => m, } } @@ -770,8 +771,9 @@ impl From for &'static str { TokenError::UnknownAsset => "The asset in question is unknown", TokenError::Frozen => "Funds exist but are frozen", TokenError::Unsupported => "Operation is not supported by the asset", - TokenError::CannotCreateHold => - "Account cannot be created for recording amount on hold", + TokenError::CannotCreateHold => { + "Account cannot be created for recording amount on hold" + }, TokenError::NotExpendable => "Account that is desired to remain would die", TokenError::Blocked => "Account cannot receive the assets", } @@ -973,8 +975,8 @@ pub fn verify_encoded_lazy( macro_rules! assert_eq_error_rate { ($x:expr, $y:expr, $error:expr $(,)?) => { assert!( - ($x >= $crate::Saturating::saturating_sub($y, $error)) && - ($x <= $crate::Saturating::saturating_add($y, $error)), + ($x >= $crate::Saturating::saturating_sub($y, $error)) + && ($x <= $crate::Saturating::saturating_add($y, $error)), "{:?} != {:?} (with error rate {:?})", $x, $y, diff --git a/bizinikiwi/primitives/runtime/src/offchain/storage_lock.rs b/bizinikiwi/primitives/runtime/src/offchain/storage_lock.rs index f070b635..4fe40696 100644 --- a/bizinikiwi/primitives/runtime/src/offchain/storage_lock.rs +++ b/bizinikiwi/primitives/runtime/src/offchain/storage_lock.rs @@ -222,8 +222,8 @@ impl Lockable for BlockAndTime { type Deadline = BlockAndTimeDeadline; fn deadline(&self) -> Self::Deadline { - let block_number = ::current_block_number() + - self.expiration_block_number_offset.into(); + let block_number = ::current_block_number() + + self.expiration_block_number_offset.into(); BlockAndTimeDeadline { timestamp: offchain::timestamp().add(self.expiration_duration), block_number, @@ -231,8 +231,8 @@ impl Lockable for BlockAndTime { } fn has_expired(deadline: &Self::Deadline) -> bool { - offchain::timestamp() > deadline.timestamp && - ::current_block_number() > deadline.block_number + offchain::timestamp() > deadline.timestamp + && ::current_block_number() > deadline.block_number } fn snooze(deadline: &Self::Deadline) { diff --git a/bizinikiwi/primitives/runtime/src/proving_trie/mod.rs b/bizinikiwi/primitives/runtime/src/proving_trie/mod.rs index 7d32313d..64215665 100644 --- a/bizinikiwi/primitives/runtime/src/proving_trie/mod.rs +++ b/bizinikiwi/primitives/runtime/src/proving_trie/mod.rs @@ -107,8 +107,9 @@ impl From for &'static str { match e { TrieError::InvalidStateRoot => "The state root is not in the database.", TrieError::IncompleteDatabase => "A trie item was not found in the database.", - TrieError::ValueAtIncompleteKey => - "A value was found with a key that is not byte-aligned.", + TrieError::ValueAtIncompleteKey => { + "A value was found with a key that is not byte-aligned." + }, TrieError::DecoderError => "A corrupt trie item was encountered.", TrieError::InvalidHash => "The hash does not match the expected value.", TrieError::DuplicateKey => "The proof contains duplicate keys.", diff --git a/bizinikiwi/primitives/runtime/src/traits/transaction_extension/dispatch_transaction.rs b/bizinikiwi/primitives/runtime/src/traits/transaction_extension/dispatch_transaction.rs index 6d333ecd..f25ec048 100644 --- a/bizinikiwi/primitives/runtime/src/traits/transaction_extension/dispatch_transaction.rs +++ b/bizinikiwi/primitives/runtime/src/traits/transaction_extension/dispatch_transaction.rs @@ -115,8 +115,9 @@ where source, ) { // After validation, some origin must have been authorized. - Ok((_, _, origin)) if !origin.is_transaction_authorized() => - Err(InvalidTransaction::UnknownOrigin.into()), + Ok((_, _, origin)) if !origin.is_transaction_authorized() => { + Err(InvalidTransaction::UnknownOrigin.into()) + }, res => res, } } diff --git a/bizinikiwi/primitives/runtime/src/transaction_validity.rs b/bizinikiwi/primitives/runtime/src/transaction_validity.rs index 6fd1a668..e3405ff7 100644 --- a/bizinikiwi/primitives/runtime/src/transaction_validity.rs +++ b/bizinikiwi/primitives/runtime/src/transaction_validity.rs @@ -109,18 +109,23 @@ impl From for &'static str { InvalidTransaction::BadProof => "Transaction has a bad signature", InvalidTransaction::AncientBirthBlock => "Transaction has an ancient birth block", InvalidTransaction::ExhaustsResources => "Transaction would exhaust the block limits", - InvalidTransaction::Payment => - "Inability to pay some fees (e.g. account balance too low)", - InvalidTransaction::BadMandatory => - "A call was labelled as mandatory, but resulted in an Error.", - InvalidTransaction::MandatoryValidation => - "Transaction dispatch is mandatory; transactions must not be validated.", + InvalidTransaction::Payment => { + "Inability to pay some fees (e.g. account balance too low)" + }, + InvalidTransaction::BadMandatory => { + "A call was labelled as mandatory, but resulted in an Error." + }, + InvalidTransaction::MandatoryValidation => { + "Transaction dispatch is mandatory; transactions must not be validated." + }, InvalidTransaction::Custom(_) => "InvalidTransaction custom error", InvalidTransaction::BadSigner => "Invalid signing address", - InvalidTransaction::IndeterminateImplicit => - "The implicit data was unable to be calculated", - InvalidTransaction::UnknownOrigin => - "The transaction extension did not authorize any origin", + InvalidTransaction::IndeterminateImplicit => { + "The implicit data was unable to be calculated" + }, + InvalidTransaction::UnknownOrigin => { + "The transaction extension did not authorize any origin" + }, } } } @@ -140,10 +145,12 @@ pub enum UnknownTransaction { impl From for &'static str { fn from(unknown: UnknownTransaction) -> &'static str { match unknown { - UnknownTransaction::CannotLookup => - "Could not lookup information required to validate the transaction", - UnknownTransaction::NoUnsignedValidator => - "Could not find an unsigned validator for the unsigned transaction", + UnknownTransaction::CannotLookup => { + "Could not lookup information required to validate the transaction" + }, + UnknownTransaction::NoUnsignedValidator => { + "Could not find an unsigned validator for the unsigned transaction" + }, UnknownTransaction::Custom(_) => "UnknownTransaction custom error", } } diff --git a/bizinikiwi/primitives/state-machine/src/basic.rs b/bizinikiwi/primitives/state-machine/src/basic.rs index 27b46629..466e1205 100644 --- a/bizinikiwi/primitives/state-machine/src/basic.rs +++ b/bizinikiwi/primitives/state-machine/src/basic.rs @@ -127,13 +127,14 @@ impl PartialEq for BasicExternalities { self.overlay .changes() .map(|(k, v)| (k, v.value_ref().materialize())) - .collect::>() == - other + .collect::>() + == other .overlay .changes() .map(|(k, v)| (k, v.value_ref().materialize())) - .collect::>() && - self.overlay + .collect::>() + && self + .overlay .children() .map(|(iter, i)| { ( @@ -142,8 +143,8 @@ impl PartialEq for BasicExternalities { .collect::>(), ) }) - .collect::>() == - other + .collect::>() + == other .overlay .children() .map(|(iter, i)| { diff --git a/bizinikiwi/primitives/state-machine/src/lib.rs b/bizinikiwi/primitives/state-machine/src/lib.rs index 7ddb2b93..f5ae01ac 100644 --- a/bizinikiwi/primitives/state-machine/src/lib.rs +++ b/bizinikiwi/primitives/state-machine/src/lib.rs @@ -626,8 +626,9 @@ mod execution { let storage_key = PrefixedStorageKey::new_ref(storage_key); ( Some(match ChildType::from_prefixed_key(storage_key) { - Some((ChildType::ParentKeyId, storage_key)) => - ChildInfo::new_default(storage_key), + Some((ChildType::ParentKeyId, storage_key)) => { + ChildInfo::new_default(storage_key) + }, None => return Err(Box::new("Invalid range start child trie key.")), }), 2, @@ -650,8 +651,8 @@ mod execution { while let Some(item) = iter.next() { let (key, value) = item.map_err(|e| Box::new(e) as Box)?; - if depth < MAX_NESTED_TRIE_DEPTH && - pezsp_core::storage::well_known_keys::is_child_storage_key(key.as_slice()) + if depth < MAX_NESTED_TRIE_DEPTH + && pezsp_core::storage::well_known_keys::is_child_storage_key(key.as_slice()) { count += 1; // do not add two child trie with same root @@ -1025,8 +1026,9 @@ mod execution { let storage_key = PrefixedStorageKey::new_ref(storage_key); ( Some(match ChildType::from_prefixed_key(storage_key) { - Some((ChildType::ParentKeyId, storage_key)) => - ChildInfo::new_default(storage_key), + Some((ChildType::ParentKeyId, storage_key)) => { + ChildInfo::new_default(storage_key) + }, None => return Err(Box::new("Invalid range start child trie key.")), }), 2, @@ -1057,8 +1059,8 @@ mod execution { let (key, value) = item.map_err(|e| Box::new(e) as Box)?; values.push((key.to_vec(), value.to_vec())); - if depth < MAX_NESTED_TRIE_DEPTH && - pezsp_core::storage::well_known_keys::is_child_storage_key(key.as_slice()) + if depth < MAX_NESTED_TRIE_DEPTH + && pezsp_core::storage::well_known_keys::is_child_storage_key(key.as_slice()) { // Do not add two chid trie with same root. if !child_roots.contains(value.as_slice()) { diff --git a/bizinikiwi/primitives/state-machine/src/overlayed_changes/changeset.rs b/bizinikiwi/primitives/state-machine/src/overlayed_changes/changeset.rs index f1ecad28..3ef7cd77 100644 --- a/bizinikiwi/primitives/state-machine/src/overlayed_changes/changeset.rs +++ b/bizinikiwi/primitives/state-machine/src/overlayed_changes/changeset.rs @@ -654,8 +654,8 @@ impl OverlayedMap { fn close_transaction_offchain(&mut self, rollback: bool) -> Result<(), NoOpenTransaction> { // runtime is not allowed to close transactions started by the client - if matches!(self.execution_mode, ExecutionMode::Runtime) && - !self.has_open_runtime_transactions() + if matches!(self.execution_mode, ExecutionMode::Runtime) + && !self.has_open_runtime_transactions() { return Err(NoOpenTransaction); } @@ -725,8 +725,8 @@ impl OverlayedChangeSet { fn close_transaction(&mut self, rollback: bool) -> Result<(), NoOpenTransaction> { // runtime is not allowed to close transactions started by the client - if matches!(self.execution_mode, ExecutionMode::Runtime) && - !self.has_open_runtime_transactions() + if matches!(self.execution_mode, ExecutionMode::Runtime) + && !self.has_open_runtime_transactions() { return Err(NoOpenTransaction); } diff --git a/bizinikiwi/primitives/state-machine/src/trie_backend.rs b/bizinikiwi/primitives/state-machine/src/trie_backend.rs index 2b0313a7..96d445f3 100644 --- a/bizinikiwi/primitives/state-machine/src/trie_backend.rs +++ b/bizinikiwi/primitives/state-machine/src/trie_backend.rs @@ -1015,8 +1015,8 @@ pub mod tests { .storage_root(iter::once((&b"new-key"[..], Some(&b"new-value"[..]))), state_version); assert!(!tx.drain().is_empty()); assert!( - new_root != - test_trie(state_version, None, None) + new_root + != test_trie(state_version, None, None) .storage_root(iter::empty(), state_version) .0 ); diff --git a/bizinikiwi/primitives/state-machine/src/trie_backend_essence.rs b/bizinikiwi/primitives/state-machine/src/trie_backend_essence.rs index 7c5a0d16..de180ef7 100644 --- a/bizinikiwi/primitives/state-machine/src/trie_backend_essence.rs +++ b/bizinikiwi/primitives/state-machine/src/trie_backend_essence.rs @@ -128,8 +128,8 @@ where None }, Some(Err(error)) => { - if matches!(*error, TrieError::IncompleteDatabase(_)) && - self.stop_on_incomplete_database + if matches!(*error, TrieError::IncompleteDatabase(_)) + && self.stop_on_incomplete_database { self.state = IterState::FinishedIncomplete; None @@ -681,7 +681,7 @@ where self.with_recorder_and_cache_for_storage_root(Some(child_root), |recorder, cache| { let mut eph = Ephemeral::new(self.backend_storage(), &mut write_overlay); match match state_version { - StateVersion::V0 => + StateVersion::V0 => { child_delta_trie_root::, _, _, _, _, _, _>( child_info.keyspace(), &mut eph, @@ -689,8 +689,9 @@ where delta, recorder, cache, - ), - StateVersion::V1 => + ) + }, + StateVersion::V1 => { child_delta_trie_root::, _, _, _, _, _, _>( child_info.keyspace(), &mut eph, @@ -698,7 +699,8 @@ where delta, recorder, cache, - ), + ) + }, } { Ok(ret) => (Some(ret), ret), Err(e) => { diff --git a/bizinikiwi/primitives/statement-store/src/lib.rs b/bizinikiwi/primitives/statement-store/src/lib.rs index 2f4ee1b0..8f6648e2 100644 --- a/bizinikiwi/primitives/statement-store/src/lib.rs +++ b/bizinikiwi/primitives/statement-store/src/lib.rs @@ -134,8 +134,9 @@ impl Proof { match self { Proof::Sr25519 { signer, .. } => *signer, Proof::Ed25519 { signer, .. } => *signer, - Proof::Secp256k1Ecdsa { signer, .. } => - ::hash(signer).into(), + Proof::Secp256k1Ecdsa { signer, .. } => { + ::hash(signer).into() + }, Proof::OnChain { who, .. } => *who, } } @@ -477,12 +478,12 @@ impl Statement { fn encoded(&self, for_signing: bool) -> Vec { // Encoding matches that of Vec. Basically this just means accepting that there // will be a prefix of vector length. - let num_fields = if !for_signing && self.proof.is_some() { 1 } else { 0 } + - if self.decryption_key.is_some() { 1 } else { 0 } + - if self.priority.is_some() { 1 } else { 0 } + - if self.channel.is_some() { 1 } else { 0 } + - if self.data.is_some() { 1 } else { 0 } + - self.num_topics as u32; + let num_fields = if !for_signing && self.proof.is_some() { 1 } else { 0 } + + if self.decryption_key.is_some() { 1 } else { 0 } + + if self.priority.is_some() { 1 } else { 0 } + + if self.channel.is_some() { 1 } else { 0 } + + if self.data.is_some() { 1 } else { 0 } + + self.num_topics as u32; let mut output = Vec::new(); // When encoding signature payload, the length prefix is omitted. diff --git a/bizinikiwi/primitives/storage/src/lib.rs b/bizinikiwi/primitives/storage/src/lib.rs index 1003ff41..c2ebafb7 100644 --- a/bizinikiwi/primitives/storage/src/lib.rs +++ b/bizinikiwi/primitives/storage/src/lib.rs @@ -298,8 +298,9 @@ impl ChildInfo { /// this trie. pub fn prefixed_storage_key(&self) -> PrefixedStorageKey { match self { - ChildInfo::ParentKeyId(ChildTrieParentKeyId { data }) => - ChildType::ParentKeyId.new_prefixed_key(data.as_slice()), + ChildInfo::ParentKeyId(ChildTrieParentKeyId { data }) => { + ChildType::ParentKeyId.new_prefixed_key(data.as_slice()) + }, } } diff --git a/bizinikiwi/primitives/trie/src/accessed_nodes_tracker.rs b/bizinikiwi/primitives/trie/src/accessed_nodes_tracker.rs index e19dd443..c51fc83d 100644 --- a/bizinikiwi/primitives/trie/src/accessed_nodes_tracker.rs +++ b/bizinikiwi/primitives/trie/src/accessed_nodes_tracker.rs @@ -58,9 +58,9 @@ impl AccessedNodesTracker { impl TrieRecorder for AccessedNodesTracker { fn record(&mut self, access: TrieAccess) { match access { - TrieAccess::NodeOwned { hash, .. } | - TrieAccess::EncodedNode { hash, .. } | - TrieAccess::Value { hash, .. } => { + TrieAccess::NodeOwned { hash, .. } + | TrieAccess::EncodedNode { hash, .. } + | TrieAccess::Value { hash, .. } => { self.recorder.insert(hash); }, _ => {}, diff --git a/bizinikiwi/primitives/trie/src/cache/mod.rs b/bizinikiwi/primitives/trie/src/cache/mod.rs index 17977922..6f6ea286 100644 --- a/bizinikiwi/primitives/trie/src/cache/mod.rs +++ b/bizinikiwi/primitives/trie/src/cache/mod.rs @@ -654,13 +654,14 @@ impl ValueCache<'_, H> { stats.local_fetch_attempts.fetch_add(1, Ordering::Relaxed); match self { - Self::Fresh(map) => + Self::Fresh(map) => { if let Some(value) = map.get(key) { stats.local_hits.fetch_add(1, Ordering::Relaxed); Some(value) } else { None - }, + } + }, Self::ForStorageRoot { local_value_cache, shared_value_cache_access, diff --git a/bizinikiwi/primitives/trie/src/cache/shared_cache.rs b/bizinikiwi/primitives/trie/src/cache/shared_cache.rs index 6cb004fe..40299156 100644 --- a/bizinikiwi/primitives/trie/src/cache/shared_cache.rs +++ b/bizinikiwi/primitives/trie/src/cache/shared_cache.rs @@ -410,8 +410,8 @@ where H: AsRef<[u8]>, { fn eq(&self, rhs: &ValueCacheKey) -> bool { - self.storage_root.as_ref() == rhs.storage_root.as_ref() && - self.storage_key == &*rhs.storage_key + self.storage_root.as_ref() == rhs.storage_root.as_ref() + && self.storage_key == &*rhs.storage_key } } diff --git a/bizinikiwi/primitives/trie/src/node_codec.rs b/bizinikiwi/primitives/trie/src/node_codec.rs index 94498868..2bdd33de 100644 --- a/bizinikiwi/primitives/trie/src/node_codec.rs +++ b/bizinikiwi/primitives/trie/src/node_codec.rs @@ -231,12 +231,15 @@ where ) -> Vec { let contains_hash = matches!(&value, Some(Value::Node(..))); let mut output = match (&value, contains_hash) { - (&None, _) => - partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchNoValue), - (_, false) => - partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchWithValue), - (_, true) => - partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueBranch), + (&None, _) => { + partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchNoValue) + }, + (_, false) => { + partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchWithValue) + }, + (_, true) => { + partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueBranch) + }, }; let bitmap_index = output.len(); @@ -287,10 +290,12 @@ fn partial_from_iterator_encode>( NodeKind::Leaf => NodeHeader::Leaf(nibble_count).encode_to(&mut output), NodeKind::BranchWithValue => NodeHeader::Branch(true, nibble_count).encode_to(&mut output), NodeKind::BranchNoValue => NodeHeader::Branch(false, nibble_count).encode_to(&mut output), - NodeKind::HashedValueLeaf => - NodeHeader::HashedValueLeaf(nibble_count).encode_to(&mut output), - NodeKind::HashedValueBranch => - NodeHeader::HashedValueBranch(nibble_count).encode_to(&mut output), + NodeKind::HashedValueLeaf => { + NodeHeader::HashedValueLeaf(nibble_count).encode_to(&mut output) + }, + NodeKind::HashedValueBranch => { + NodeHeader::HashedValueBranch(nibble_count).encode_to(&mut output) + }, }; output.extend(partial); output diff --git a/bizinikiwi/primitives/trie/src/node_header.rs b/bizinikiwi/primitives/trie/src/node_header.rs index e3709eb2..962e44bb 100644 --- a/bizinikiwi/primitives/trie/src/node_header.rs +++ b/bizinikiwi/primitives/trie/src/node_header.rs @@ -54,16 +54,18 @@ impl Encode for NodeHeader { fn encode_to(&self, output: &mut T) { match self { NodeHeader::Null => output.push_byte(trie_constants::EMPTY_TRIE), - NodeHeader::Branch(true, nibble_count) => - encode_size_and_prefix(*nibble_count, trie_constants::BRANCH_WITH_MASK, 2, output), + NodeHeader::Branch(true, nibble_count) => { + encode_size_and_prefix(*nibble_count, trie_constants::BRANCH_WITH_MASK, 2, output) + }, NodeHeader::Branch(false, nibble_count) => encode_size_and_prefix( *nibble_count, trie_constants::BRANCH_WITHOUT_MASK, 2, output, ), - NodeHeader::Leaf(nibble_count) => - encode_size_and_prefix(*nibble_count, trie_constants::LEAF_PREFIX_MASK, 2, output), + NodeHeader::Leaf(nibble_count) => { + encode_size_and_prefix(*nibble_count, trie_constants::LEAF_PREFIX_MASK, 2, output) + }, NodeHeader::HashedValueBranch(nibble_count) => encode_size_and_prefix( *nibble_count, trie_constants::ALT_HASHING_BRANCH_WITH_MASK, @@ -90,10 +92,12 @@ impl Decode for NodeHeader { } match i & (0b11 << 6) { trie_constants::LEAF_PREFIX_MASK => Ok(NodeHeader::Leaf(decode_size(i, input, 2)?)), - trie_constants::BRANCH_WITH_MASK => - Ok(NodeHeader::Branch(true, decode_size(i, input, 2)?)), - trie_constants::BRANCH_WITHOUT_MASK => - Ok(NodeHeader::Branch(false, decode_size(i, input, 2)?)), + trie_constants::BRANCH_WITH_MASK => { + Ok(NodeHeader::Branch(true, decode_size(i, input, 2)?)) + }, + trie_constants::BRANCH_WITHOUT_MASK => { + Ok(NodeHeader::Branch(false, decode_size(i, input, 2)?)) + }, trie_constants::EMPTY_TRIE => { if i & (0b111 << 5) == trie_constants::ALT_HASHING_LEAF_PREFIX_MASK { Ok(NodeHeader::HashedValueLeaf(decode_size(i, input, 3)?)) diff --git a/bizinikiwi/primitives/trie/src/trie_stream.rs b/bizinikiwi/primitives/trie/src/trie_stream.rs index 9e209b51..ee22e2a0 100644 --- a/bizinikiwi/primitives/trie/src/trie_stream.rs +++ b/bizinikiwi/primitives/trie/src/trie_stream.rs @@ -57,14 +57,18 @@ fn fuse_nibbles_node(nibbles: &[u8], kind: NodeKind) -> impl Iterator let size = nibbles.len(); let iter_start = match kind { NodeKind::Leaf => size_and_prefix_iterator(size, trie_constants::LEAF_PREFIX_MASK, 2), - NodeKind::BranchNoValue => - size_and_prefix_iterator(size, trie_constants::BRANCH_WITHOUT_MASK, 2), - NodeKind::BranchWithValue => - size_and_prefix_iterator(size, trie_constants::BRANCH_WITH_MASK, 2), - NodeKind::HashedValueLeaf => - size_and_prefix_iterator(size, trie_constants::ALT_HASHING_LEAF_PREFIX_MASK, 3), - NodeKind::HashedValueBranch => - size_and_prefix_iterator(size, trie_constants::ALT_HASHING_BRANCH_WITH_MASK, 4), + NodeKind::BranchNoValue => { + size_and_prefix_iterator(size, trie_constants::BRANCH_WITHOUT_MASK, 2) + }, + NodeKind::BranchWithValue => { + size_and_prefix_iterator(size, trie_constants::BRANCH_WITH_MASK, 2) + }, + NodeKind::HashedValueLeaf => { + size_and_prefix_iterator(size, trie_constants::ALT_HASHING_LEAF_PREFIX_MASK, 3) + }, + NodeKind::HashedValueBranch => { + size_and_prefix_iterator(size, trie_constants::ALT_HASHING_BRANCH_WITH_MASK, 4) + }, }; iter_start .chain(if nibbles.len() % 2 == 1 { Some(nibbles[0]) } else { None }) diff --git a/bizinikiwi/primitives/version/proc-macro/src/decl_runtime_version.rs b/bizinikiwi/primitives/version/proc-macro/src/decl_runtime_version.rs index c9293232..26f2ff61 100644 --- a/bizinikiwi/primitives/version/proc-macro/src/decl_runtime_version.rs +++ b/bizinikiwi/primitives/version/proc-macro/src/decl_runtime_version.rs @@ -88,8 +88,12 @@ impl ParseRuntimeVersion { fn parse_expr(init_expr: &Expr) -> Result<(ParseRuntimeVersion, Vec)> { let init_expr = match init_expr { Expr::Struct(ref e) => e, - _ => - return Err(Error::new(init_expr.span(), "expected a struct initializer expression")), + _ => { + return Err(Error::new( + init_expr.span(), + "expected a struct initializer expression", + )) + }, }; let mut parsed = ParseRuntimeVersion::default(); @@ -103,8 +107,9 @@ impl ParseRuntimeVersion { fn parse_field_value(&mut self, field_value: &FieldValue) -> Result> { let field_name = match field_value.member { syn::Member::Named(ref ident) => ident, - syn::Member::Unnamed(_) => - return Err(Error::new(field_value.span(), "only named members must be used")), + syn::Member::Unnamed(_) => { + return Err(Error::new(field_value.span(), "only named members must be used")) + }, }; fn parse_once( @@ -160,11 +165,12 @@ impl ParseRuntimeVersion { fn parse_num_literal(expr: &Expr) -> Result { let lit = match *expr { Expr::Lit(ExprLit { lit: Lit::Int(ref lit), .. }) => lit, - _ => + _ => { return Err(Error::new( expr.span(), "only numeric literals (e.g. `10`) are supported here", - )), + )) + }, }; lit.base10_parse::() } @@ -172,11 +178,12 @@ impl ParseRuntimeVersion { fn parse_num_literal_u8(expr: &Expr) -> Result { let lit = match *expr { Expr::Lit(ExprLit { lit: Lit::Int(ref lit), .. }) => lit, - _ => + _ => { return Err(Error::new( expr.span(), "only numeric literals (e.g. `10`) are supported here", - )), + )) + }, }; lit.base10_parse::() } diff --git a/bizinikiwi/primitives/version/src/lib.rs b/bizinikiwi/primitives/version/src/lib.rs index 1ba433f7..370d28ea 100644 --- a/bizinikiwi/primitives/version/src/lib.rs +++ b/bizinikiwi/primitives/version/src/lib.rs @@ -376,43 +376,48 @@ impl<'de> serde::Deserialize<'de> for RuntimeVersion { { let spec_name = match seq.next_element()? { Some(spec_name) => spec_name, - None => + None => { return Err(serde::de::Error::invalid_length( 0usize, &"struct RuntimeVersion with 8 elements", - )), + )) + }, }; let impl_name = match seq.next_element()? { Some(impl_name) => impl_name, - None => + None => { return Err(serde::de::Error::invalid_length( 1usize, &"struct RuntimeVersion with 8 elements", - )), + )) + }, }; let authoring_version = match seq.next_element()? { Some(authoring_version) => authoring_version, - None => + None => { return Err(serde::de::Error::invalid_length( 2usize, &"struct RuntimeVersion with 8 elements", - )), + )) + }, }; let spec_version = match seq.next_element()? { Some(spec_version) => spec_version, - None => + None => { return Err(serde::de::Error::invalid_length( 3usize, &"struct RuntimeVersion with 8 elements", - )), + )) + }, }; let impl_version = match seq.next_element()? { Some(impl_version) => impl_version, - None => + None => { return Err(serde::de::Error::invalid_length( 4usize, &"struct RuntimeVersion with 8 elements", - )), + )) + }, }; let apis = match { struct DeserializeWith<'de> { @@ -436,27 +441,30 @@ impl<'de> serde::Deserialize<'de> for RuntimeVersion { seq.next_element::>()?.map(|wrap| wrap.value) } { Some(apis) => apis, - None => + None => { return Err(serde::de::Error::invalid_length( 5usize, &"struct RuntimeVersion with 8 elements", - )), + )) + }, }; let transaction_version = match seq.next_element()? { Some(transaction_version) => transaction_version, - None => + None => { return Err(serde::de::Error::invalid_length( 6usize, &"struct RuntimeVersion with 8 elements", - )), + )) + }, }; let system_version = match seq.next_element()? { Some(system_version) => system_version, - None => + None => { return Err(serde::de::Error::invalid_length( 7usize, &"struct RuntimeVersion with 8 elements", - )), + )) + }, }; Ok(RuntimeVersion { spec_name, @@ -528,7 +536,9 @@ impl<'de> serde::Deserialize<'de> for RuntimeVersion { }, Field::Apis => { if apis.is_some() { - return Err(::duplicate_field("apis")); + return Err(::duplicate_field( + "apis", + )); } apis = Some({ struct DeserializeWith<'de> { @@ -558,7 +568,7 @@ impl<'de> serde::Deserialize<'de> for RuntimeVersion { } transaction_version = Some(map.next_value()?); }, - Field::SystemVersion => + Field::SystemVersion => { if let Some(system_version) = system_version { let new_value = map.next_value::()?; if system_version != new_value { @@ -572,7 +582,8 @@ impl<'de> serde::Deserialize<'de> for RuntimeVersion { } } else { system_version = Some(map.next_value()?); - }, + } + }, _ => { map.next_value::()?; }, @@ -700,9 +711,9 @@ pub fn core_version_from_apis(apis: &ApisVec) -> Option { impl RuntimeVersion { /// Check if this version matches other version for calling into runtime. pub fn can_call_with(&self, other: &RuntimeVersion) -> bool { - self.spec_version == other.spec_version && - self.spec_name == other.spec_name && - self.authoring_version == other.authoring_version + self.spec_version == other.spec_version + && self.spec_name == other.spec_name + && self.authoring_version == other.authoring_version } /// Check if the given api with `api_id` is implemented and the version passes the given @@ -766,8 +777,8 @@ impl NativeVersion { "`spec_name` does not match `{}` vs `{}`", self.runtime_version.spec_name, other.spec_name, )) - } else if self.runtime_version.authoring_version != other.authoring_version && - !self.can_author_with.contains(&other.authoring_version) + } else if self.runtime_version.authoring_version != other.authoring_version + && !self.can_author_with.contains(&other.authoring_version) { Err(format!( "`authoring_version` does not match `{version}` vs `{other_version}` and \ diff --git a/bizinikiwi/test-utils/cli/src/lib.rs b/bizinikiwi/test-utils/cli/src/lib.rs index 8dda36e7..576f64d6 100644 --- a/bizinikiwi/test-utils/cli/src/lib.rs +++ b/bizinikiwi/test-utils/cli/src/lib.rs @@ -44,8 +44,7 @@ fn bizinikiwi_node_path() -> PathBuf { } // Fall back to finding in target directory - let target_dir = - std::env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| "target".to_string()); + let target_dir = std::env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| "target".to_string()); let profile = if cfg!(debug_assertions) { "debug" } else { "release" }; PathBuf::from(target_dir).join(profile).join("bizinikiwi-node") } @@ -285,8 +284,9 @@ pub async fn block_hash(block_number: u64, url: &str) -> Result { .map_err(|_| "Couldn't get block hash".to_string())?; match result { - ListOrValue::Value(maybe_block_hash) if maybe_block_hash.is_some() => - Ok(maybe_block_hash.unwrap()), + ListOrValue::Value(maybe_block_hash) if maybe_block_hash.is_some() => { + Ok(maybe_block_hash.unwrap()) + }, _ => Err("Couldn't get block hash".to_string()), } } diff --git a/bizinikiwi/test-utils/runtime/src/bizinikiwi_test_pallet.rs b/bizinikiwi/test-utils/runtime/src/bizinikiwi_test_pallet.rs index 7c69757b..f0cabe71 100644 --- a/bizinikiwi/test-utils/runtime/src/bizinikiwi_test_pallet.rs +++ b/bizinikiwi/test-utils/runtime/src/bizinikiwi_test_pallet.rs @@ -227,10 +227,10 @@ pub mod pezpallet { // Some tests do not need to be complicated with signer and nonce, some need // reproducible block hash (call signature can't be there). // Offchain testing requires storage_change. - Call::deposit_log_digest_item { .. } | - Call::storage_change { .. } | - Call::read { .. } | - Call::read_and_panic { .. } => Ok(ValidTransaction { + Call::deposit_log_digest_item { .. } + | Call::storage_change { .. } + | Call::read { .. } + | Call::read_and_panic { .. } => Ok(ValidTransaction { provides: vec![BlakeTwo256::hash_of(&call).encode()], ..Default::default() }), @@ -245,10 +245,12 @@ pub fn validate_runtime_call( ) -> TransactionValidity { log::trace!(target: LOG_TARGET, "validate_runtime_call {call:?}"); match call { - Call::call_do_not_propagate {} => - Ok(ValidTransaction { propagate: false, ..Default::default() }), - Call::call_with_priority { priority } => - Ok(ValidTransaction { priority: *priority, ..Default::default() }), + Call::call_do_not_propagate {} => { + Ok(ValidTransaction { propagate: false, ..Default::default() }) + }, + Call::call_with_priority { priority } => { + Ok(ValidTransaction { priority: *priority, ..Default::default() }) + }, _ => Ok(Default::default()), } } diff --git a/bizinikiwi/test-utils/runtime/src/lib.rs b/bizinikiwi/test-utils/runtime/src/lib.rs index a9505ba8..462dc137 100644 --- a/bizinikiwi/test-utils/runtime/src/lib.rs +++ b/bizinikiwi/test-utils/runtime/src/lib.rs @@ -331,8 +331,9 @@ impl pezsp_runtime::traits::TransactionExtension for CheckBizinikiw > { log::trace!(target: LOG_TARGET, "validate"); let v = match call { - RuntimeCall::BizinikiwiTest(ref bizinikiwi_test_call) => - bizinikiwi_test_pallet::validate_runtime_call(bizinikiwi_test_call)?, + RuntimeCall::BizinikiwiTest(ref bizinikiwi_test_call) => { + bizinikiwi_test_pallet::validate_runtime_call(bizinikiwi_test_call)? + }, _ => Default::default(), }; Ok((v, (), origin)) diff --git a/bizinikiwi/test-utils/runtime/transaction-pool/src/lib.rs b/bizinikiwi/test-utils/runtime/transaction-pool/src/lib.rs index 6069d302..c04ab057 100644 --- a/bizinikiwi/test-utils/runtime/transaction-pool/src/lib.rs +++ b/bizinikiwi/test-utils/runtime/transaction-pool/src/lib.rs @@ -397,8 +397,9 @@ impl ChainApi for TestApi { )))); } }, - Ok(None) => - return Ok(Err(TransactionValidityError::Invalid(InvalidTransaction::Custom(2)))), + Ok(None) => { + return Ok(Err(TransactionValidityError::Invalid(InvalidTransaction::Custom(2)))) + }, Err(e) => return Err(e), } @@ -484,8 +485,9 @@ impl ChainApi for TestApi { at: &BlockId, ) -> Result>, Error> { Ok(match at { - generic::BlockId::Hash(x) => - self.chain.read().block_by_hash.get(x).map(|b| *b.header.number()), + generic::BlockId::Hash(x) => { + self.chain.read().block_by_hash.get(x).map(|b| *b.header.number()) + }, generic::BlockId::Number(num) => Some(*num), }) } @@ -496,10 +498,11 @@ impl ChainApi for TestApi { ) -> Result::Hash>, Error> { Ok(match at { generic::BlockId::Hash(x) => Some(*x), - generic::BlockId::Number(num) => + generic::BlockId::Number(num) => { self.chain.read().block_by_number.get(num).and_then(|blocks| { blocks.iter().find(|b| b.1.is_best()).map(|b| b.0.header().hash()) - }), + }) + }, }) } diff --git a/bizinikiwi/utils/pez-fork-tree/src/lib.rs b/bizinikiwi/utils/pez-fork-tree/src/lib.rs index 7935d401..8f598a23 100644 --- a/bizinikiwi/utils/pez-fork-tree/src/lib.rs +++ b/bizinikiwi/utils/pez-fork-tree/src/lib.rs @@ -420,8 +420,8 @@ where // not a descendant of `hash`. let children = std::mem::take(&mut curr.children); for child in children { - if child.number == *number && child.hash == *hash || - *number < child.number && is_descendent_of(hash, &child.hash)? + if child.number == *number && child.hash == *hash + || *number < child.number && is_descendent_of(hash, &child.hash)? { curr.children.push(child); } else { @@ -544,9 +544,10 @@ where let is_finalized = root.hash == *hash; let is_descendant = !is_finalized && root.number > number && is_descendent_of(hash, &root.hash)?; - let is_ancestor = !is_finalized && - !is_descendant && root.number < number && - is_descendent_of(&root.hash, hash)?; + let is_ancestor = !is_finalized + && !is_descendant + && root.number < number + && is_descendent_of(&root.hash, hash)?; (is_finalized, is_descendant, is_ancestor) }; @@ -617,8 +618,8 @@ where if predicate(&node.data) && (node.hash == *hash || is_descendent_of(&node.hash, hash)?) { for child in node.children.iter() { - if child.number <= number && - (child.hash == *hash || is_descendent_of(&child.hash, hash)?) + if child.number <= number + && (child.hash == *hash || is_descendent_of(&child.hash, hash)?) { return Err(Error::UnfinalizedAncestor); } @@ -664,8 +665,8 @@ where if predicate(&root.data) && (root.hash == *hash || is_descendent_of(&root.hash, hash)?) { for child in root.children.iter() { - if child.number <= number && - (child.hash == *hash || is_descendent_of(&child.hash, hash)?) + if child.number <= number + && (child.hash == *hash || is_descendent_of(&child.hash, hash)?) { return Err(Error::UnfinalizedAncestor); } @@ -692,9 +693,9 @@ where let roots = std::mem::take(&mut self.roots); for root in roots { - let retain = root.number > number && is_descendent_of(hash, &root.hash)? || - root.number == number && root.hash == *hash || - is_descendent_of(&root.hash, hash)?; + let retain = root.number > number && is_descendent_of(hash, &root.hash)? + || root.number == number && root.hash == *hash + || is_descendent_of(&root.hash, hash)?; if retain { self.roots.push(root); @@ -1162,15 +1163,15 @@ mod test { // finalizing "D" will finalize a block from the tree, but it can't be applied yet // since it is not a root change. assert_eq!( - tree.finalizes_any_with_descendent_if(&"D", 10, &is_descendent_of, |c| c.effective == - 10), + tree.finalizes_any_with_descendent_if(&"D", 10, &is_descendent_of, |c| c.effective + == 10), Ok(Some(false)), ); // finalizing "E" is not allowed since there are not finalized ancestors. assert_eq!( - tree.finalizes_any_with_descendent_if(&"E", 15, &is_descendent_of, |c| c.effective == - 10), + tree.finalizes_any_with_descendent_if(&"E", 15, &is_descendent_of, |c| c.effective + == 10), Err(Error::UnfinalizedAncestor) ); @@ -1203,15 +1204,15 @@ mod test { // finalizing "F" will fail since it would finalize past "E" without finalizing "D" first assert_eq!( - tree.finalizes_any_with_descendent_if(&"F", 100, &is_descendent_of, |c| c.effective <= - 100,), + tree.finalizes_any_with_descendent_if(&"F", 100, &is_descendent_of, |c| c.effective + <= 100,), Err(Error::UnfinalizedAncestor), ); // it will work with "G" though since it is not in the same branch as "E" assert_eq!( - tree.finalizes_any_with_descendent_if(&"G", 100, &is_descendent_of, |c| c.effective <= - 100), + tree.finalizes_any_with_descendent_if(&"G", 100, &is_descendent_of, |c| c.effective + <= 100), Ok(Some(true)), ); diff --git a/bizinikiwi/utils/pezframe/benchmarking-cli/src/extrinsic/cmd.rs b/bizinikiwi/utils/pezframe/benchmarking-cli/src/extrinsic/cmd.rs index ee4d3d73..4a0120e6 100644 --- a/bizinikiwi/utils/pezframe/benchmarking-cli/src/extrinsic/cmd.rs +++ b/bizinikiwi/utils/pezframe/benchmarking-cli/src/extrinsic/cmd.rs @@ -114,8 +114,9 @@ impl ExtrinsicCmd { let extrinsic = self.params.extrinsic.clone().unwrap_or_default(); let ext_builder = match ext_factory.try_get(&pezpallet, &extrinsic) { Some(ext_builder) => ext_builder, - None => - return Err("Unknown pezpallet or extrinsic. Use --list for a complete list.".into()), + None => { + return Err("Unknown pezpallet or extrinsic. Use --list for a complete list.".into()) + }, }; let bench = diff --git a/bizinikiwi/utils/pezframe/benchmarking-cli/src/machine/mod.rs b/bizinikiwi/utils/pezframe/benchmarking-cli/src/machine/mod.rs index 8fdf57d8..f844ed3f 100644 --- a/bizinikiwi/utils/pezframe/benchmarking-cli/src/machine/mod.rs +++ b/bizinikiwi/utils/pezframe/benchmarking-cli/src/machine/mod.rs @@ -150,8 +150,9 @@ impl MachineCmd { let score = match metric { Metric::Blake2256 => benchmark_cpu(hash_limit), - Metric::Blake2256Parallel { num_cores } => - benchmark_cpu_parallelism(hash_limit, *num_cores), + Metric::Blake2256Parallel { num_cores } => { + benchmark_cpu_parallelism(hash_limit, *num_cores) + }, Metric::Sr25519Verify => benchmark_sr25519_verify(verify_limit), Metric::MemCopy => benchmark_memory(memory_limit), Metric::DiskSeqWrite => benchmark_disk_sequential_writes(disk_limit, dir)?, diff --git a/bizinikiwi/utils/pezframe/benchmarking-cli/src/overhead/command.rs b/bizinikiwi/utils/pezframe/benchmarking-cli/src/overhead/command.rs index 2690fda0..98040154 100644 --- a/bizinikiwi/utils/pezframe/benchmarking-cli/src/overhead/command.rs +++ b/bizinikiwi/utils/pezframe/benchmarking-cli/src/overhead/command.rs @@ -42,6 +42,7 @@ use genesis_state::WARN_SPEC_GENESIS_CTOR; use log::info; use pezcumulus_client_teyrchain_inherent::MockValidationDataInherentDataProvider; use pezframe_support::Deserialize; +use pezkuwi_subxt::{client::RuntimeVersion, ext::futures, Metadata}; use pezkuwi_teyrchain_primitives::primitives::Id as ParaId; use pezsc_block_builder::BlockBuilderApi; use pezsc_chain_spec::{ChainSpec, ChainSpecExtension, GenesisBlockBuilder}; @@ -70,7 +71,6 @@ use std::{ path::PathBuf, sync::Arc, }; -use pezkuwi_subxt::{client::RuntimeVersion, ext::futures, Metadata}; const DEFAULT_PARA_ID: u32 = 100; const LOG_TARGET: &'static str = "pezkuwi_sdk_frame::benchmark::overhead"; @@ -273,8 +273,9 @@ impl OverheadCmd { chain_spec_from_api: Option>, ) -> Result<(GenesisStateHandler, Option)> { let genesis_builder_to_source = || match self.params.genesis_builder { - Some(GenesisBuilderPolicy::Runtime) | Some(GenesisBuilderPolicy::SpecRuntime) => - SpecGenesisSource::Runtime(self.params.genesis_builder_preset.clone()), + Some(GenesisBuilderPolicy::Runtime) | Some(GenesisBuilderPolicy::SpecRuntime) => { + SpecGenesisSource::Runtime(self.params.genesis_builder_preset.clone()) + }, Some(GenesisBuilderPolicy::SpecGenesis) | None => { log::warn!(target: LOG_TARGET, "{WARN_SPEC_GENESIS_CTOR}"); SpecGenesisSource::SpecJson @@ -328,9 +329,9 @@ impl OverheadCmd { &self, chain_spec: &Option>, ) -> std::result::Result<(), (ErrorKind, String)> { - if chain_spec.is_none() && - self.params.runtime.is_none() && - self.shared_params.chain.is_none() + if chain_spec.is_none() + && self.params.runtime.is_none() + && self.shared_params.chain.is_none() { return Err(( ErrorKind::MissingRequiredArgument, @@ -340,13 +341,14 @@ impl OverheadCmd { } match self.params.genesis_builder { - Some(GenesisBuilderPolicy::SpecGenesis | GenesisBuilderPolicy::SpecRuntime) => + Some(GenesisBuilderPolicy::SpecGenesis | GenesisBuilderPolicy::SpecRuntime) => { if chain_spec.is_none() && self.shared_params.chain.is_none() { return Err(( ErrorKind::MissingRequiredArgument, "Provide a chain spec via `--chain`.".to_string(), )); - }, + } + }, _ => {}, }; Ok(()) @@ -414,8 +416,9 @@ impl OverheadCmd { // If we are dealing with a teyrchain, make sure that the para id in genesis will // match what we expect. let genesis_patcher = match chain_type { - Teyrchain(para_id) => - Some(Box::new(move |value| patch_genesis(value, Some(para_id))) as Box<_>), + Teyrchain(para_id) => { + Some(Box::new(move |value| patch_genesis(value, Some(para_id))) as Box<_>) + }, _ => None, }; diff --git a/bizinikiwi/utils/pezframe/benchmarking-cli/src/overhead/remark_builder.rs b/bizinikiwi/utils/pezframe/benchmarking-cli/src/overhead/remark_builder.rs index 0f1a1a5b..2bd2ac3e 100644 --- a/bizinikiwi/utils/pezframe/benchmarking-cli/src/overhead/remark_builder.rs +++ b/bizinikiwi/utils/pezframe/benchmarking-cli/src/overhead/remark_builder.rs @@ -17,15 +17,15 @@ use crate::extrinsic::ExtrinsicBuilder; use codec::{Decode, Encode}; +use pezkuwi_subxt::{ + client::RuntimeVersion as SubxtRuntimeVersion, + config::{bizinikiwi::BizinikiwiExtrinsicParamsBuilder as ParamsBuilder, HashFor}, + BizinikiwConfig, Config, OfflineClient, +}; use pezsc_client_api::UsageProvider; use pezsp_api::{ApiExt, Core, Metadata, ProvideRuntimeApi}; use pezsp_runtime::{traits::Block as BlockT, OpaqueExtrinsic}; use std::sync::Arc; -use pezkuwi_subxt::{ - client::RuntimeVersion as SubxtRuntimeVersion, - config::{bizinikiwi::BizinikiwiExtrinsicParamsBuilder as ParamsBuilder, HashFor}, - Config, OfflineClient, BizinikiwConfig, -}; /// Bizinikiwi configuration pub type BizinikiwiConfig = BizinikiwConfig; diff --git a/bizinikiwi/utils/pezframe/benchmarking-cli/src/pezpallet/command.rs b/bizinikiwi/utils/pezframe/benchmarking-cli/src/pezpallet/command.rs index a0de87ba..4e5db32f 100644 --- a/bizinikiwi/utils/pezframe/benchmarking-cli/src/pezpallet/command.rs +++ b/bizinikiwi/utils/pezframe/benchmarking-cli/src/pezpallet/command.rs @@ -166,8 +166,9 @@ impl PalletCmd { chain_spec_from_api: Option>, ) -> Result { let genesis_builder_to_source = || match self.genesis_builder { - Some(GenesisBuilderPolicy::Runtime) | Some(GenesisBuilderPolicy::SpecRuntime) => - SpecGenesisSource::Runtime(self.genesis_builder_preset.clone()), + Some(GenesisBuilderPolicy::Runtime) | Some(GenesisBuilderPolicy::SpecRuntime) => { + SpecGenesisSource::Runtime(self.genesis_builder_preset.clone()) + }, Some(GenesisBuilderPolicy::SpecGenesis) | None => { log::warn!(target: LOG_TARGET, "{WARN_SPEC_GENESIS_CTOR}"); SpecGenesisSource::SpecJson @@ -244,13 +245,15 @@ impl PalletCmd { if let Some(json_input) = &self.json_input { let raw_data = match std::fs::read(json_input) { Ok(raw_data) => raw_data, - Err(error) => - return Err(format!("Failed to read {:?}: {}", json_input, error).into()), + Err(error) => { + return Err(format!("Failed to read {:?}: {}", json_input, error).into()) + }, }; let batches: Vec = match serde_json::from_slice(&raw_data) { Ok(batches) => batches, - Err(error) => - return Err(format!("Failed to deserialize {:?}: {}", json_input, error).into()), + Err(error) => { + return Err(format!("Failed to deserialize {:?}: {}", json_input, error).into()) + }, }; return self.output_from_results(&batches); } @@ -632,10 +635,10 @@ impl PalletCmd { fn pezpallet_selected(&self, pezpallet: &Vec) -> bool { let include = self.pallets.clone(); - let included = include.is_empty() || - include.iter().any(|p| p.as_bytes() == pezpallet) || - include.iter().any(|p| p == "*") || - include.iter().any(|p| p == "all"); + let included = include.is_empty() + || include.iter().any(|p| p.as_bytes() == pezpallet) + || include.iter().any(|p| p == "*") + || include.iter().any(|p| p == "all"); let excluded = self.exclude_pallets.iter().any(|p| p.as_bytes() == pezpallet); included && !excluded @@ -651,10 +654,10 @@ impl PalletCmd { let extrinsic_split: Vec<&str> = extrinsic_filter.split(',').collect(); let extrinsics: Vec<_> = extrinsic_split.iter().map(|x| x.trim().as_bytes()).collect(); - let included = extrinsic_filter.is_empty() || - extrinsic_filter == "*" || - extrinsic_filter == "all" || - extrinsics.contains(&&extrinsic[..]); + let included = extrinsic_filter.is_empty() + || extrinsic_filter == "*" + || extrinsic_filter == "all" + || extrinsics.contains(&&extrinsic[..]); let excluded = self .excluded_extrinsics() @@ -964,12 +967,13 @@ impl PalletCmd { .or_default() .entry((pov_pallet.to_string(), pov_storage.to_string())) { - Entry::Occupied(_) => + Entry::Occupied(_) => { return Err(format!( "Cannot specify pov_mode tag twice for the same key: {}", pezpallet_storage ) - .into()), + .into()) + }, Entry::Vacant(e) => { e.insert(mode); }, @@ -1031,13 +1035,14 @@ impl PalletCmd { } match self.genesis_builder { - Some(GenesisBuilderPolicy::SpecGenesis | GenesisBuilderPolicy::SpecRuntime) => + Some(GenesisBuilderPolicy::SpecGenesis | GenesisBuilderPolicy::SpecRuntime) => { if chain_spec.is_none() && self.shared_params.chain.is_none() { return Err(( ErrorKind::MissingRequiredArgument, "Provide a chain spec via `--chain`.".to_string(), )); - }, + } + }, _ => {}, } diff --git a/bizinikiwi/utils/pezframe/benchmarking-cli/src/pezpallet/writer.rs b/bizinikiwi/utils/pezframe/benchmarking-cli/src/pezpallet/writer.rs index 85eaca02..6eb04409 100644 --- a/bizinikiwi/utils/pezframe/benchmarking-cli/src/pezpallet/writer.rs +++ b/bizinikiwi/utils/pezframe/benchmarking-cli/src/pezpallet/writer.rs @@ -583,8 +583,9 @@ pub(crate) fn process_storage_results( let mut prefix_result = result.clone(); let key_info = storage_info_map.get(&prefix); let pezpallet_name = match key_info { - Some(k) => - String::from_utf8(k.pezpallet_name.clone()).expect("encoded from string"), + Some(k) => { + String::from_utf8(k.pezpallet_name.clone()).expect("encoded from string") + }, None => "".to_string(), }; let storage_name = match key_info { @@ -606,8 +607,8 @@ pub(crate) fn process_storage_results( }, None => None, }; - let is_all_ignored = pov_modes.get(&("ALL".to_string(), "ALL".to_string())) == - Some(&PovEstimationMode::Ignored); + let is_all_ignored = pov_modes.get(&("ALL".to_string(), "ALL".to_string())) + == Some(&PovEstimationMode::Ignored); if is_all_ignored && override_pov_mode != Some(&PovEstimationMode::Ignored) { panic!("The syntax currently does not allow to exclude single keys from a top-level `Ignored` pov-mode."); } diff --git a/bizinikiwi/utils/pezframe/benchmarking-cli/src/shared/genesis_state.rs b/bizinikiwi/utils/pezframe/benchmarking-cli/src/shared/genesis_state.rs index a2028e54..37a2fb64 100644 --- a/bizinikiwi/utils/pezframe/benchmarking-cli/src/shared/genesis_state.rs +++ b/bizinikiwi/utils/pezframe/benchmarking-cli/src/shared/genesis_state.rs @@ -75,8 +75,9 @@ impl GenesisStateHandler { .map_err(|e| format!("{ERROR_CANNOT_BUILD_GENESIS}\nError: {e}").into()), SpecGenesisSource::None => Ok(Storage::default()), }, - GenesisStateHandler::Runtime(code_bytes, Some(preset)) => - genesis_from_code::(code_bytes.as_slice(), preset, json_patcher), + GenesisStateHandler::Runtime(code_bytes, Some(preset)) => { + genesis_from_code::(code_bytes.as_slice(), preset, json_patcher) + }, GenesisStateHandler::Runtime(_, None) => Ok(Storage::default()), } } diff --git a/bizinikiwi/utils/pezframe/benchmarking-cli/src/storage/read.rs b/bizinikiwi/utils/pezframe/benchmarking-cli/src/storage/read.rs index 3476f428..e2ac4a29 100644 --- a/bizinikiwi/utils/pezframe/benchmarking-cli/src/storage/read.rs +++ b/bizinikiwi/utils/pezframe/benchmarking-cli/src/storage/read.rs @@ -48,8 +48,8 @@ impl StorageCmd { if self.params.is_validate_block_mode() && self.params.disable_pov_recorder { return Err("PoV recorder must be activated to provide a storage proof for block validation at runtime. Remove `--disable-pov-recorder` from the command line.".into()); } - if self.params.is_validate_block_mode() && - self.params.batch_size > MAX_BATCH_SIZE_FOR_BLOCK_VALIDATION + if self.params.is_validate_block_mode() + && self.params.batch_size > MAX_BATCH_SIZE_FOR_BLOCK_VALIDATION { return Err(format!("Batch size is too large. This may cause problems with runtime memory allocation. Better set `--batch-size {}` or less.", MAX_BATCH_SIZE_FOR_BLOCK_VALIDATION).into()); } @@ -158,8 +158,8 @@ impl StorageCmd { record.append(v.len(), start.elapsed())?; } read_in_batch += 1; - let is_batch_full = read_in_batch >= self.params.batch_size || - (last_child_key == key && last_child_info == info); + let is_batch_full = read_in_batch >= self.params.batch_size + || (last_child_key == key && last_child_info == info); // Read child keys on block validation if is_batch_full && self.params.is_validate_block_mode() { diff --git a/bizinikiwi/utils/pezframe/benchmarking-cli/src/storage/write.rs b/bizinikiwi/utils/pezframe/benchmarking-cli/src/storage/write.rs index 3c66a3b4..c7fce0a3 100644 --- a/bizinikiwi/utils/pezframe/benchmarking-cli/src/storage/write.rs +++ b/bizinikiwi/utils/pezframe/benchmarking-cli/src/storage/write.rs @@ -61,8 +61,8 @@ impl StorageCmd { if self.params.is_validate_block_mode() && self.params.disable_pov_recorder { return Err("PoV recorder must be activated to provide a storage proof for block validation at runtime. Remove `--disable-pov-recorder`.".into()); } - if self.params.is_validate_block_mode() && - self.params.batch_size > MAX_BATCH_SIZE_FOR_BLOCK_VALIDATION + if self.params.is_validate_block_mode() + && self.params.batch_size > MAX_BATCH_SIZE_FOR_BLOCK_VALIDATION { return Err(format!("Batch size is too large. This may cause problems with runtime memory allocation. Better set `--batch-size {}` or less.", MAX_BATCH_SIZE_FOR_BLOCK_VALIDATION).into()); } diff --git a/bizinikiwi/utils/pezframe/remote-externalities/src/lib.rs b/bizinikiwi/utils/pezframe/remote-externalities/src/lib.rs index f065bf60..d82c9424 100644 --- a/bizinikiwi/utils/pezframe/remote-externalities/src/lib.rs +++ b/bizinikiwi/utils/pezframe/remote-externalities/src/lib.rs @@ -1396,8 +1396,8 @@ mod remote_tests { // there should be more keys in the child ext. assert!( - child_ext.as_backend().backend_storage().keys().len() > - ext.as_backend().backend_storage().keys().len() + child_ext.as_backend().backend_storage().keys().len() + > ext.as_backend().backend_storage().keys().len() ); } diff --git a/bizinikiwi/utils/pezframe/rpc/state-trie-migration-rpc/src/lib.rs b/bizinikiwi/utils/pezframe/rpc/state-trie-migration-rpc/src/lib.rs index 73a5b666..875891e2 100644 --- a/bizinikiwi/utils/pezframe/rpc/state-trie-migration-rpc/src/lib.rs +++ b/bizinikiwi/utils/pezframe/rpc/state-trie-migration-rpc/src/lib.rs @@ -58,8 +58,8 @@ fn count_migrate<'a, H: Hasher>( NodePlan::Leaf { value, .. } | NodePlan::NibbledBranch { value: Some(value), .. } => { total_nb += 1; if let ValuePlan::Inline(range) = value { - if (range.end - range.start) as u32 >= - pezsp_core::storage::TRIE_VALUE_NODE_THRESHOLD + if (range.end - range.start) as u32 + >= pezsp_core::storage::TRIE_VALUE_NODE_THRESHOLD { nb += 1; } diff --git a/bizinikiwi/utils/pezframe/storage-access-test-runtime/src/lib.rs b/bizinikiwi/utils/pezframe/storage-access-test-runtime/src/lib.rs index 3aee09e1..a096b7f7 100644 --- a/bizinikiwi/utils/pezframe/storage-access-test-runtime/src/lib.rs +++ b/bizinikiwi/utils/pezframe/storage-access-test-runtime/src/lib.rs @@ -125,7 +125,7 @@ pub fn proceed_storage_access(mut params: &[u8]) { } match payload { - StorageAccessPayload::Read(keys) => + StorageAccessPayload::Read(keys) => { for (key, maybe_child_info) in keys { match maybe_child_info { Some(child_info) => { @@ -141,7 +141,8 @@ pub fn proceed_storage_access(mut params: &[u8]) { .ok_or("Value unexpectedly empty"); }, } - }, + } + }, StorageAccessPayload::Write((changes, maybe_child_info)) => { let delta = changes.iter().map(|(key, value)| (key.as_ref(), Some(value.as_ref()))); match maybe_child_info { diff --git a/bizinikiwi/utils/txtesttool/bin/main.rs b/bizinikiwi/utils/txtesttool/bin/main.rs index f91c721c..2a9fa08e 100644 --- a/bizinikiwi/utils/txtesttool/bin/main.rs +++ b/bizinikiwi/utils/txtesttool/bin/main.rs @@ -13,21 +13,23 @@ use bizinikiwi_txtesttool::{ runner::DefaultTxTask, scenario::{AccountsDescription, ChainType, ScenarioBuilder, ScenarioType}, subxt_transaction::{ - self, generate_ecdsa_keypair, generate_sr25519_keypair, EthRuntimeConfig, EthTransaction, - EthTransactionsSink, BizinikiwTransaction, BizinikiwTransactionsSink, SENDER_SEED, + self, generate_ecdsa_keypair, generate_sr25519_keypair, BizinikiwTransaction, + BizinikiwTransactionsSink, EthRuntimeConfig, EthTransaction, EthTransactionsSink, + SENDER_SEED, }, }; use clap::Parser; use codec::Compact; -use std::{fs, fs::File, io::BufReader, time::Duration}; use pezkuwi_subxt::{ext::frame_metadata::RuntimeMetadataPrefixed, PezkuwiConfig}; +use std::{fs, fs::File, io::BufReader, time::Duration}; use tracing::info; macro_rules! populate_scenario_builder { ($scenario_builder:expr, $scenario_type:expr) => {{ match $scenario_type { - ScenarioType::OneShot { account, nonce } => - $scenario_builder.with_account_id(account.clone()).with_nonce_from(*nonce), + ScenarioType::OneShot { account, nonce } => { + $scenario_builder.with_account_id(account.clone()).with_nonce_from(*nonce) + }, ScenarioType::FromSingleAccount { account, from, count } => $scenario_builder .with_account_id(account.clone()) .with_nonce_from(*from) @@ -161,7 +163,8 @@ async fn main() -> Result<(), Box> { CliCommand::Metadata { ws } => { // Handle metadata command use codec::Decode; - let api = pezkuwi_subxt::OnlineClient::::from_insecure_url(ws).await?; + let api = + pezkuwi_subxt::OnlineClient::::from_insecure_url(ws).await?; let runtime_apis = api.runtime_api().at_latest().await?; let raw_bytes: Vec = runtime_apis.call_raw("Metadata_metadata", None).await?; let (_, meta): (Compact, RuntimeMetadataPrefixed) = diff --git a/bizinikiwi/utils/txtesttool/src/execution_log.rs b/bizinikiwi/utils/txtesttool/src/execution_log.rs index 1dc0db8d..b21646e1 100644 --- a/bizinikiwi/utils/txtesttool/src/execution_log.rs +++ b/bizinikiwi/utils/txtesttool/src/execution_log.rs @@ -9,6 +9,7 @@ use crate::{ }; use average::{Estimate, Max, Mean, Min, Quantile}; use parking_lot::RwLock; +use pezkuwi_subxt_core::config::Hash as BlockHash; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use std::{ collections::HashMap, @@ -22,7 +23,6 @@ use std::{ }, time::{Duration, SystemTime}, }; -use pezkuwi_subxt_core::config::Hash as BlockHash; use tracing::{debug, info, trace}; pub const STAT_TARGET: &str = "stat"; @@ -115,11 +115,11 @@ impl Counters { } pub fn buffered(&self) -> usize { - self.popped.load(Ordering::Relaxed) - - (self.submit_and_watch_success.load(Ordering::Relaxed) + - self.submit_and_watch_error.load(Ordering::Relaxed)) - - (self.submit_success.load(Ordering::Relaxed) + - self.submit_error.load(Ordering::Relaxed)) + self.popped.load(Ordering::Relaxed) + - (self.submit_and_watch_success.load(Ordering::Relaxed) + + self.submit_and_watch_error.load(Ordering::Relaxed)) + - (self.submit_success.load(Ordering::Relaxed) + + self.submit_error.load(Ordering::Relaxed)) } fn count_event(&self, event: &ExecutionEvent) { @@ -128,10 +128,12 @@ impl Counters { ExecutionEvent::Sent(_) => Self::inc(&self.sent), ExecutionEvent::SubmitResult(_, Ok(_)) => Self::inc(&self.submit_success), ExecutionEvent::SubmitResult(_, Err(_)) => Self::inc(&self.submit_error), - ExecutionEvent::SubmitAndWatchResult(_, Ok(_)) => - Self::inc(&self.submit_and_watch_success), - ExecutionEvent::SubmitAndWatchResult(_, Err(_)) => - Self::inc(&self.submit_and_watch_error), + ExecutionEvent::SubmitAndWatchResult(_, Ok(_)) => { + Self::inc(&self.submit_and_watch_success) + }, + ExecutionEvent::SubmitAndWatchResult(_, Err(_)) => { + Self::inc(&self.submit_and_watch_error) + }, ExecutionEvent::FinalizedMonitor(_, _) => Self::inc(&self.finalized_monitor), ExecutionEvent::TxPoolEvent(_, status) => match status { TransactionStatus::Validated => Self::inc(&self.ts_validated), @@ -314,8 +316,9 @@ impl ExecutionLog for TransactionExecutionLog { if match event { // note: dedup in block events - on the stats line we want to see transactions included, // not events count - ExecutionEvent::TxPoolEvent(_, TransactionStatus::InBlock(_)) => - self.in_blocks().is_empty(), + ExecutionEvent::TxPoolEvent(_, TransactionStatus::InBlock(_)) => { + self.in_blocks().is_empty() + }, _ => true, } { self.total_counters.count_event(&event); @@ -437,8 +440,9 @@ impl ExecutionLog for TransactionExecutionLog { fn time_to_result(&self) -> Option { let ets = self.events.read().iter().find_map(|e| match e { - ExecutionEvent::SubmitAndWatchResult(i, _) | ExecutionEvent::SubmitResult(i, _) => - Some(*i), + ExecutionEvent::SubmitAndWatchResult(i, _) | ExecutionEvent::SubmitResult(i, _) => { + Some(*i) + }, _ => None, }); Self::duration_since_timestamp(self.get_sent_time_stamp(), ets) @@ -449,8 +453,9 @@ impl ExecutionLog for TransactionExecutionLog { .read() .iter() .filter_map(|e| match e { - ExecutionEvent::TxPoolEvent(_, TransactionStatus::Invalid(reason)) => - Some(reason.clone()), + ExecutionEvent::TxPoolEvent(_, TransactionStatus::Invalid(reason)) => { + Some(reason.clone()) + }, _ => None, }) .collect() @@ -461,8 +466,9 @@ impl ExecutionLog for TransactionExecutionLog { .read() .iter() .filter_map(|e| match e { - ExecutionEvent::TxPoolEvent(_, TransactionStatus::Error(reason)) => - Some(reason.clone()), + ExecutionEvent::TxPoolEvent(_, TransactionStatus::Error(reason)) => { + Some(reason.clone()) + }, _ => None, }) .collect() @@ -473,8 +479,9 @@ impl ExecutionLog for TransactionExecutionLog { .read() .iter() .filter_map(|e| match e { - ExecutionEvent::TxPoolEvent(_, TransactionStatus::Dropped(reason)) => - Some(reason.clone()), + ExecutionEvent::TxPoolEvent(_, TransactionStatus::Dropped(reason)) => { + Some(reason.clone()) + }, _ => None, }) .collect() diff --git a/bizinikiwi/utils/txtesttool/src/fake_transaction.rs b/bizinikiwi/utils/txtesttool/src/fake_transaction.rs index a75b5cbb..c0171525 100644 --- a/bizinikiwi/utils/txtesttool/src/fake_transaction.rs +++ b/bizinikiwi/utils/txtesttool/src/fake_transaction.rs @@ -9,6 +9,7 @@ use crate::{ }; use futures::stream::{self}; use futures_util::StreamExt; +use pezkuwi_subxt::ext::codec::{Decode, Encode}; use serde::{Deserialize, Serialize}; use std::{ any::Any, @@ -17,7 +18,6 @@ use std::{ sync::atomic::{AtomicUsize, Ordering}, time::Duration, }; -use pezkuwi_subxt::ext::codec::{Decode, Encode}; use tokio::task::yield_now; use tracing::trace; @@ -319,16 +319,19 @@ impl FakeTransaction { trace!(target:LOG_TARGET, "submit_result: delayed: {:?}", self.hash); match event { TransactionStatus::Finalized(_) => Ok(self.hash), - TransactionStatus::Dropped(message) => - Err(Error::Other(format!("submit-error:dropped:{message}").to_string())), - TransactionStatus::Invalid(message) => - Err(Error::Other(format!("submit-error:invalid:{message}").to_string())), - TransactionStatus::Error(message) => - Err(Error::Other(format!("submit-error:error:{message}").to_string())), - TransactionStatus::Validated | - TransactionStatus::NoLongerInBestBlock | - TransactionStatus::Broadcasted | - TransactionStatus::InBlock(_) => todo!(), + TransactionStatus::Dropped(message) => { + Err(Error::Other(format!("submit-error:dropped:{message}").to_string())) + }, + TransactionStatus::Invalid(message) => { + Err(Error::Other(format!("submit-error:invalid:{message}").to_string())) + }, + TransactionStatus::Error(message) => { + Err(Error::Other(format!("submit-error:error:{message}").to_string())) + }, + TransactionStatus::Validated + | TransactionStatus::NoLongerInBestBlock + | TransactionStatus::Broadcasted + | TransactionStatus::InBlock(_) => todo!(), } } } diff --git a/bizinikiwi/utils/txtesttool/src/lib.rs b/bizinikiwi/utils/txtesttool/src/lib.rs index f3dbca88..2fca7218 100644 --- a/bizinikiwi/utils/txtesttool/src/lib.rs +++ b/bizinikiwi/utils/txtesttool/src/lib.rs @@ -83,8 +83,8 @@ pub fn init_logger() { } impl Filter for F { fn enabled(&self, meta: &Metadata<'_>, cx: &Context<'_, S>) -> bool { - !self.env_filter.enabled(meta, cx.clone()) && - meta.target() == execution_log::STAT_TARGET + !self.env_filter.enabled(meta, cx.clone()) + && meta.target() == execution_log::STAT_TARGET } } diff --git a/bizinikiwi/utils/txtesttool/src/runner.rs b/bizinikiwi/utils/txtesttool/src/runner.rs index 7e0907ca..10f8fa89 100644 --- a/bizinikiwi/utils/txtesttool/src/runner.rs +++ b/bizinikiwi/utils/txtesttool/src/runner.rs @@ -12,13 +12,13 @@ use crate::{ }; use async_trait::async_trait; use futures::{stream::FuturesUnordered, Future, StreamExt}; +use pezkuwi_subxt_core::config::Hash as BlockHash; use std::{ path::Path, pin::Pin, sync::Arc, time::{Duration, Instant, SystemTime}, }; -use pezkuwi_subxt_core::config::Hash as BlockHash; use tokio::{ select, sync::mpsc::{channel, Receiver, Sender}, diff --git a/bizinikiwi/utils/txtesttool/src/scenario.rs b/bizinikiwi/utils/txtesttool/src/scenario.rs index dcbd84ee..b933d855 100644 --- a/bizinikiwi/utils/txtesttool/src/scenario.rs +++ b/bizinikiwi/utils/txtesttool/src/scenario.rs @@ -18,12 +18,12 @@ use crate::{ runner::{DefaultTxTask, Runner, TxTask}, subxt_transaction::{ eth_transfer_payload_builder, generate_ecdsa_keypair, generate_sr25519_keypair, - remark_payload_builder, sub_transfer_payload_builder, EthPayloadBuilderFn, EthTransaction, - EthTransactionsSink, EthTxBuildContext, SubPayloadBuilderFn, SubTxBuildContext, - BizinikiwTransaction, BizinikiwTransactionsSink, + remark_payload_builder, sub_transfer_payload_builder, BizinikiwTransaction, + BizinikiwTransactionsSink, EthPayloadBuilderFn, EthTransaction, EthTransactionsSink, + EthTxBuildContext, SubPayloadBuilderFn, SubTxBuildContext, }, transaction::{ - BuildTransactionParams, EthTransactionBuilder, BizinikiwTransactionBuilder, Transaction, + BizinikiwTransactionBuilder, BuildTransactionParams, EthTransactionBuilder, Transaction, TransactionBuilder, TransactionCall, TransactionRecipe, TransactionsSink, }, }; diff --git a/bizinikiwi/utils/txtesttool/src/subxt_api_connector.rs b/bizinikiwi/utils/txtesttool/src/subxt_api_connector.rs index 940c7302..11408d68 100644 --- a/bizinikiwi/utils/txtesttool/src/subxt_api_connector.rs +++ b/bizinikiwi/utils/txtesttool/src/subxt_api_connector.rs @@ -2,8 +2,8 @@ // This file is dual-licensed as Apache-2.0 or GPL-3.0. // see LICENSE for license details. -use std::{error::Error, sync::Arc, time::Duration}; use pezkuwi_subxt::OnlineClient; +use std::{error::Error, sync::Arc, time::Duration}; use tracing::info; use crate::helpers; diff --git a/bizinikiwi/utils/txtesttool/src/subxt_transaction.rs b/bizinikiwi/utils/txtesttool/src/subxt_transaction.rs index 5797fb21..dbfc5ec0 100644 --- a/bizinikiwi/utils/txtesttool/src/subxt_transaction.rs +++ b/bizinikiwi/utils/txtesttool/src/subxt_transaction.rs @@ -10,12 +10,6 @@ use crate::{ use async_trait::async_trait; use futures::StreamExt; use parking_lot::RwLock; -use std::{ - any::Any, - collections::HashMap, - sync::Arc, - time::{Duration, Instant}, -}; pub use pezkuwi_subxt::dynamic; use pezkuwi_subxt::{ backend::rpc::RpcClient, @@ -36,6 +30,12 @@ use pezkuwi_subxt_signer::{ eth::{dev as eth_dev, Keypair as EthKeypair, Signature}, sr25519::{dev as sr25519_dev, Keypair as SrPair}, }; +use std::{ + any::Any, + collections::HashMap, + sync::Arc, + time::{Duration, Instant}, +}; use tracing::{debug, error, trace}; const LOG_TARGET: &str = "subxt_tx"; @@ -49,14 +49,17 @@ impl pezkuwi_subxt::Config for EthRuntimeConfig { type Address = AccountId20; type Signature = Signature; type Hasher = pezkuwi_subxt::config::bizinikiwi::BlakeTwo256; - type Header = - pezkuwi_subxt::config::bizinikiwi::BizinikiwiHeader; + type Header = pezkuwi_subxt::config::bizinikiwi::BizinikiwiHeader< + u32, + pezkuwi_subxt::config::bizinikiwi::BlakeTwo256, + >; type ExtrinsicParams = pezkuwi_subxt::config::DefaultExtrinsicParams; type AssetId = u32; } /// Type alias for subxt config hash (Output of Hasher). -pub(crate) type HashOf = <::Hasher as pezkuwi_subxt::config::Hasher>::Output; +pub(crate) type HashOf = + <::Hasher as pezkuwi_subxt::config::Hasher>::Output; /// Type alias for subxt account id. pub(crate) type AccountIdOf = ::AccountId; @@ -325,9 +328,8 @@ where .ok_or_else(|| { format!("Sender account {:?} does not exist", hex::encode(account.clone())) })?; - let value: pezkuwi_subxt::dynamic::Value = storage_value - .decode() - .map_err(|e| format!("Failed to decode storage: {e:?}"))?; + let value: pezkuwi_subxt::dynamic::Value = + storage_value.decode().map_err(|e| format!("Failed to decode storage: {e:?}"))?; debug!(target:LOG_TARGET,"account has free balance: {:?}", value.at("data").at("free")); debug!(target:LOG_TARGET,"account has nonce: {:?}", value.at("nonce")); @@ -612,8 +614,9 @@ where for _ in 0..DEFAULT_RETRIES_FOR_PARTIAL_TX_CREATION { let params = tx_params(mortality, nonce as u64, tip); match sink.api().tx().create_partial(&tx_call, from_account_id, params.into()).await { - Ok(tx) => - return subxt_transaction(sink, tx, from_keypair, nonce, mortality, account).await, + Ok(tx) => { + return subxt_transaction(sink, tx, from_keypair, nonce, mortality, account).await + }, Err(_) => continue, } } diff --git a/bizinikiwi/utils/txtesttool/src/transaction.rs b/bizinikiwi/utils/txtesttool/src/transaction.rs index aa60e035..77295e76 100644 --- a/bizinikiwi/utils/txtesttool/src/transaction.rs +++ b/bizinikiwi/utils/txtesttool/src/transaction.rs @@ -9,15 +9,15 @@ use crate::{ helpers::StreamOf, runner::DefaultTxTask, subxt_transaction::{ - build_subxt_tx, EthPayloadBuilderFn, EthRuntimeConfig, EthTransaction, EthTransactionsSink, - HashOf, SubPayloadBuilderFn, BizinikiwTransaction, BizinikiwTransactionsSink, + build_subxt_tx, BizinikiwTransaction, BizinikiwTransactionsSink, EthPayloadBuilderFn, + EthRuntimeConfig, EthTransaction, EthTransactionsSink, HashOf, SubPayloadBuilderFn, }, }; use async_trait::async_trait; -use serde::{Deserialize, Serialize}; -use std::any::Any; use pezkuwi_subxt::{tx::TxStatus, OnlineClient, PezkuwiConfig}; use pezkuwi_subxt_core::config::Hash as BlockHash; +use serde::{Deserialize, Serialize}; +use std::any::Any; /// Parameters for building a transaction. pub(crate) struct BuildTransactionParams<'a> { diff --git a/bizinikiwi/utils/wasm-builder/src/lib.rs b/bizinikiwi/utils/wasm-builder/src/lib.rs index 9d3b013d..b422a111 100644 --- a/bizinikiwi/utils/wasm-builder/src/lib.rs +++ b/bizinikiwi/utils/wasm-builder/src/lib.rs @@ -303,8 +303,8 @@ impl CargoCommand { /// Returns whether this version of the toolchain supports nightly features. fn supports_nightly_features(&self) -> bool { - self.version.map_or(false, |version| version.is_nightly) || - env::var("RUSTC_BOOTSTRAP").is_ok() + self.version.map_or(false, |version| version.is_nightly) + || env::var("RUSTC_BOOTSTRAP").is_ok() } /// Check if the supplied cargo command supports our runtime environment. @@ -433,12 +433,13 @@ impl RuntimeTarget { /// Figures out the target parameter value for rustc. fn rustc_target(self, cargo_command: &CargoCommand) -> String { match self { - RuntimeTarget::Wasm => + RuntimeTarget::Wasm => { if cargo_command.is_wasm32v1_none_target_available() { "wasm32v1-none".into() } else { "wasm32-unknown-unknown".into() - }, + } + }, RuntimeTarget::Riscv => { let path = polkavm_linker::target_json_32_path().expect("riscv not found"); path.into_os_string().into_string().unwrap() @@ -449,12 +450,13 @@ impl RuntimeTarget { /// Figures out the target directory name used by cargo. fn rustc_target_dir(self, cargo_command: &CargoCommand) -> &'static str { match self { - RuntimeTarget::Wasm => + RuntimeTarget::Wasm => { if cargo_command.is_wasm32v1_none_target_available() { "wasm32v1-none".into() } else { "wasm32-unknown-unknown".into() - }, + } + }, RuntimeTarget::Riscv => "riscv32emac-unknown-none-polkavm", } } diff --git a/bizinikiwi/utils/wasm-builder/src/prerequisites.rs b/bizinikiwi/utils/wasm-builder/src/prerequisites.rs index 5a272784..86f1df41 100644 --- a/bizinikiwi/utils/wasm-builder/src/prerequisites.rs +++ b/bizinikiwi/utils/wasm-builder/src/prerequisites.rs @@ -267,8 +267,8 @@ fn check_wasm_toolchain_installed( } } - if cargo_command.supports_wasm32v1_none_target() && - !cargo_command.is_wasm32v1_none_target_installed() + if cargo_command.supports_wasm32v1_none_target() + && !cargo_command.is_wasm32v1_none_target_installed() { build_helper::warning!("You are building WASM runtime using `wasm32-unknown-unknown` target, although Rust >= 1.84 supports `wasm32v1-none` target!"); build_helper::warning!("You can install it with `rustup target add wasm32v1-none --toolchain {toolchain}` if you're using `rustup`."); diff --git a/bizinikiwi/utils/wasm-builder/src/wasm_project.rs b/bizinikiwi/utils/wasm-builder/src/wasm_project.rs index b4279f4b..217af75a 100644 --- a/bizinikiwi/utils/wasm-builder/src/wasm_project.rs +++ b/bizinikiwi/utils/wasm-builder/src/wasm_project.rs @@ -421,10 +421,11 @@ fn get_wasm_workspace_root() -> PathBuf { loop { match out_dir.parent() { Some(parent) if out_dir.ends_with("build") => return parent.to_path_buf(), - _ => + _ => { if !out_dir.pop() { break; - }, + } + }, } } @@ -613,18 +614,18 @@ fn project_enabled_features( // this heuristic anymore. However, for the transition phase between now and namespaced // features already being present in nightly, we need this code to make // runtimes compile with all the possible rustc versions. - if v.len() == 1 && - v.get(0).map_or(false, |v| *v == format!("dep:{}", f)) && - std_enabled.as_ref().map(|e| e.iter().any(|ef| ef == *f)).unwrap_or(false) + if v.len() == 1 + && v.get(0).map_or(false, |v| *v == format!("dep:{}", f)) + && std_enabled.as_ref().map(|e| e.iter().any(|ef| ef == *f)).unwrap_or(false) { return false; } // We don't want to enable the `std`/`default` feature for the wasm build and // we need to check if the feature is enabled by checking the env variable. - *f != "std" && - *f != "default" && - env::var(format!("CARGO_FEATURE_{feature_env}")) + *f != "std" + && *f != "default" + && env::var(format!("CARGO_FEATURE_{feature_env}")) .map(|v| v == "1") .unwrap_or_default() }) diff --git a/docs/sdk/src/reference_docs/frame_storage_derives.rs b/docs/sdk/src/reference_docs/frame_storage_derives.rs index db6449ee..f26cf20c 100644 --- a/docs/sdk/src/reference_docs/frame_storage_derives.rs +++ b/docs/sdk/src/reference_docs/frame_storage_derives.rs @@ -21,14 +21,14 @@ //! pub type Something = StorageValue<_, NewType>; //! } //! ``` -//! +//! //! This raises a number of compiler errors, like: //! ```text //! the trait `MaxEncodedLen` is not implemented for `NewType`, which is required by //! `frame::prelude::StorageValue<_GeneratedPrefixForStorageSomething, NewType>: //! StorageInfoTrait` //! ``` -//! +//! //! This implies the following set of traits that need to be derived for a type to be stored in //! `frame` storage: //! ```rust @@ -46,7 +46,7 @@ //! pub type Something = StorageValue<_, NewType>; //! } //! ``` -//! +//! //! Next, let's look at how this will differ if we are to store a type that is derived from `T` in //! storage, such as [`frame::prelude::BlockNumberFor`]: //! ```compile_fail @@ -64,14 +64,14 @@ //! pub type Something = StorageValue<_, NewType>; //! } //! ``` -//! +//! //! Surprisingly, this will also raise a number of errors, like: //! ```text //! the trait `TypeInfo` is not implemented for `T`, which is required //! by`pezframe_support::pezpallet_prelude::StorageValue, //! pezpallet_2::NewType>:StorageEntryMetadataBuilder //! ``` -//! +//! //! Why is that? The underlying reason is that the `TypeInfo` `derive` macro will only work for //! `NewType` if all of `NewType`'s generics also implement `TypeInfo`. This is not the case for `T` //! in the example above. @@ -99,7 +99,7 @@ //! pub type Something = StorageValue<_, NewType>; //! } //! ``` -//! +//! //! Next, let's say we wish to store `NewType` as [`frame::prelude::ValueQuery`], which means it //! must also implement `Default`. This should be as simple as adding `derive(Default)` to it, //! right? @@ -119,7 +119,7 @@ //! pub type Something = StorageValue<_, NewType, ValueQuery>; //! } //! ``` -//! +//! //! Under the hood, the expansion of the `derive(Default)` will suffer from the same restriction as //! before: it will only work if `T: Default`, and `T` is not `Default`. Note that this is an //! expected issue: `T` is merely a wrapper of many other types, such as `BlockNumberFor`. @@ -163,7 +163,7 @@ //! pub type Something = StorageValue<_, NewType, ValueQuery>; //! } //! ``` -//! +//! //! Finally, if a custom type that is provided through `Config` is to be stored in the storage, it //! is subject to the same trait requirements. The following does not work: //! ```compile_fail @@ -180,7 +180,7 @@ //! pub type Something = StorageValue<_, T::CustomType>; //! } //! ``` -//! +//! //! But adding the right trait bounds will fix it. //! ```rust //! #[frame::pezpallet] diff --git a/pezbridges/bin/runtime-common/src/extensions.rs b/pezbridges/bin/runtime-common/src/extensions.rs index 70f6a48f..e82ccbf1 100644 --- a/pezbridges/bin/runtime-common/src/extensions.rs +++ b/pezbridges/bin/runtime-common/src/extensions.rs @@ -174,8 +174,8 @@ where // we are only interested in associated pezpallet submissions let Some(update) = maybe_update else { return }; // we are only interested in failed or unneeded transactions - let has_failed = has_failed || - !SubmitTeyrchainHeadsHelper::::was_successful(&update); + let has_failed = has_failed + || !SubmitTeyrchainHeadsHelper::::was_successful(&update); if !has_failed { return; diff --git a/pezbridges/bin/runtime-common/src/mock.rs b/pezbridges/bin/runtime-common/src/mock.rs index 647899a4..541f9993 100644 --- a/pezbridges/bin/runtime-common/src/mock.rs +++ b/pezbridges/bin/runtime-common/src/mock.rs @@ -240,8 +240,8 @@ impl MessageDispatch for DummyMessageDispatch { type LaneId = TestLaneIdType; fn is_active(lane: Self::LaneId) -> bool { - pezframe_support::storage::unhashed::take::(&(b"inactive", lane).encode()[..]) != - Some(false) + pezframe_support::storage::unhashed::take::(&(b"inactive", lane).encode()[..]) + != Some(false) } fn dispatch_weight( diff --git a/pezbridges/modules/beefy/src/utils.rs b/pezbridges/modules/beefy/src/utils.rs index e8fe6caf..ea51a81c 100644 --- a/pezbridges/modules/beefy/src/utils.rs +++ b/pezbridges/modules/beefy/src/utils.rs @@ -240,9 +240,9 @@ mod tests { let mut header = ChainBuilder::new(20).append_finalized_header().to_header(); header.customize_signatures(|signatures| { let first_signature_idx = signatures.iter().position(Option::is_some).unwrap(); - let last_signature_idx = signatures.len() - - signatures.iter().rev().position(Option::is_some).unwrap() - - 1; + let last_signature_idx = signatures.len() + - signatures.iter().rev().position(Option::is_some).unwrap() + - 1; signatures[first_signature_idx] = signatures[last_signature_idx].clone(); }); assert_noop!( diff --git a/pezbridges/modules/grandpa/src/call_ext.rs b/pezbridges/modules/grandpa/src/call_ext.rs index 9a56838c..52679d3b 100644 --- a/pezbridges/modules/grandpa/src/call_ext.rs +++ b/pezbridges/modules/grandpa/src/call_ext.rs @@ -248,8 +248,9 @@ pub trait CallSubType, I: 'static>: let result = SubmitFinalityProofHelper::::check_obsolete_from_extension(&call_info); match result { - Ok(improved_by) => - Ok(Some(VerifiedSubmitFinalityProofInfo { base: call_info, improved_by })), + Ok(improved_by) => { + Ok(Some(VerifiedSubmitFinalityProofInfo { base: call_info, improved_by })) + }, Err(Error::::OldHeader) => Err(InvalidTransaction::Stale.into()), Err(_) => Err(InvalidTransaction::Call.into()), } diff --git a/pezbridges/modules/messages/src/benchmarking.rs b/pezbridges/modules/messages/src/benchmarking.rs index 053f0701..d609ff00 100644 --- a/pezbridges/modules/messages/src/benchmarking.rs +++ b/pezbridges/modules/messages/src/benchmarking.rs @@ -196,8 +196,8 @@ mod benchmarks { // fn max_msgs, I: 'static>() -> u32 { - T::BridgedChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX as u32 - - ReceiveMessagesProofSetup::::LATEST_RECEIVED_NONCE as u32 + T::BridgedChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX as u32 + - ReceiveMessagesProofSetup::::LATEST_RECEIVED_NONCE as u32 } // Benchmark `receive_messages_proof` extrinsic with single minimal-weight message and following diff --git a/pezbridges/modules/messages/src/call_ext.rs b/pezbridges/modules/messages/src/call_ext.rs index 71ca81c2..3ce7d5a0 100644 --- a/pezbridges/modules/messages/src/call_ext.rs +++ b/pezbridges/modules/messages/src/call_ext.rs @@ -53,8 +53,8 @@ impl, I: 'static> CallHelper { // `is_obsolete` and every relayer has delivered at least one message, // so if relayer slots are released, then message slots are also // released - return post_occupation.free_message_slots > - info.unrewarded_relayers.free_message_slots; + return post_occupation.free_message_slots + > info.unrewarded_relayers.free_message_slots; } inbound_lane_data.last_delivered_nonce() == *info.base.bundled_range.end() @@ -154,8 +154,8 @@ impl< // confirmation. Because of that, we can't assume that our state has been confirmed // to the bridged chain. So we are accepting any proof that brings new // confirmations. - bundled_range: outbound_lane_data.latest_received_nonce + 1..= - relayers_state.last_delivered_nonce, + bundled_range: outbound_lane_data.latest_received_nonce + 1 + ..=relayers_state.last_delivered_nonce, best_stored_nonce: outbound_lane_data.latest_received_nonce, })); } diff --git a/pezbridges/modules/messages/src/lib.rs b/pezbridges/modules/messages/src/lib.rs index dd7916f3..dcb4f107 100644 --- a/pezbridges/modules/messages/src/lib.rs +++ b/pezbridges/modules/messages/src/lib.rs @@ -223,8 +223,8 @@ pub mod pezpallet { // reject transactions that are declaring too many messages ensure!( - MessageNonce::from(messages_count) <= - BridgedChainOf::::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, + MessageNonce::from(messages_count) + <= BridgedChainOf::::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, Error::::TooManyMessagesInTheProof ); @@ -320,9 +320,9 @@ pub mod pezpallet { valid_messages += 1; dispatch_result.unspent_weight }, - ReceptionResult::InvalidNonce | - ReceptionResult::TooManyUnrewardedRelayers | - ReceptionResult::TooManyUnconfirmedMessages => message_dispatch_weight, + ReceptionResult::InvalidNonce + | ReceptionResult::TooManyUnrewardedRelayers + | ReceptionResult::TooManyUnconfirmedMessages => message_dispatch_weight, }; messages_received_status.push(message.key.nonce, receival_result); @@ -733,8 +733,8 @@ where /// Ensure that the pezpallet is in normal operational mode. fn ensure_normal_operating_mode, I: 'static>() -> Result<(), Error> { - if PalletOperatingMode::::get() == - MessagesOperatingMode::Basic(BasicOperatingMode::Normal) + if PalletOperatingMode::::get() + == MessagesOperatingMode::Basic(BasicOperatingMode::Normal) { return Ok(()); } diff --git a/pezbridges/modules/messages/src/tests/messages_generation.rs b/pezbridges/modules/messages/src/tests/messages_generation.rs index 014bcfb8..03551b93 100644 --- a/pezbridges/modules/messages/src/tests/messages_generation.rs +++ b/pezbridges/modules/messages/src/tests/messages_generation.rs @@ -78,12 +78,13 @@ where for (i, nonce) in message_nonces.into_iter().enumerate() { let message_key = MessageKey { lane_id: lane, nonce }; let message_payload = match encode_message(nonce, &generate_message(nonce)) { - Some(message_payload) => + Some(message_payload) => { if i == 0 { grow_storage_value(message_payload, &proof_params) } else { message_payload - }, + } + }, None => continue, }; let storage_key = storage_keys::message_key( diff --git a/pezbridges/modules/messages/src/weights_ext.rs b/pezbridges/modules/messages/src/weights_ext.rs index 178d6176..8f0c752a 100644 --- a/pezbridges/modules/messages/src/weights_ext.rs +++ b/pezbridges/modules/messages/src/weights_ext.rs @@ -411,8 +411,8 @@ pub trait WeightInfoExt: WeightInfo { /// is less than that cost). fn storage_proof_size_overhead(proof_size: u32) -> Weight { let proof_size_in_bytes = proof_size; - let byte_weight = Self::receive_single_n_bytes_message_proof(2) - - Self::receive_single_n_bytes_message_proof(1); + let byte_weight = Self::receive_single_n_bytes_message_proof(2) + - Self::receive_single_n_bytes_message_proof(1); proof_size_in_bytes * byte_weight } diff --git a/pezbridges/modules/relayers/src/extension/grandpa_adapter.rs b/pezbridges/modules/relayers/src/extension/grandpa_adapter.rs index 6855a486..73cc0bff 100644 --- a/pezbridges/modules/relayers/src/extension/grandpa_adapter.rs +++ b/pezbridges/modules/relayers/src/extension/grandpa_adapter.rs @@ -109,8 +109,9 @@ where calls.next().transpose()?.and_then(|c| c.submit_finality_proof_info()); Ok(match (total_calls, relay_finality_call, msgs_call) { - (2, Some(relay_finality_call), Some(msgs_call)) => - Some(ExtensionCallInfo::RelayFinalityAndMsgs(relay_finality_call, msgs_call)), + (2, Some(relay_finality_call), Some(msgs_call)) => { + Some(ExtensionCallInfo::RelayFinalityAndMsgs(relay_finality_call, msgs_call)) + }, (1, None, Some(msgs_call)) => Some(ExtensionCallInfo::Msgs(msgs_call)), _ => None, }) @@ -129,8 +130,8 @@ where call_data: &mut ExtensionCallData, relayer: &R::AccountId, ) -> bool { - verify_submit_finality_proof_succeeded::(call_info, call_data, relayer) && - verify_messages_call_succeeded::(call_info, call_data, relayer) + verify_submit_finality_proof_succeeded::(call_info, call_data, relayer) + && verify_messages_call_succeeded::(call_info, call_data, relayer) } } diff --git a/pezbridges/modules/relayers/src/extension/mod.rs b/pezbridges/modules/relayers/src/extension/mod.rs index 3f3f21dc..64bf745e 100644 --- a/pezbridges/modules/relayers/src/extension/mod.rs +++ b/pezbridges/modules/relayers/src/extension/mod.rs @@ -407,11 +407,12 @@ where "Has registered reward" ); }, - RelayerAccountAction::Slash(relayer, slash_account) => + RelayerAccountAction::Slash(relayer, slash_account) => { RelayersPallet::::slash_and_deregister( &relayer, ExplicitOrAccountParams::Params(slash_account), - ), + ) + }, } Ok(Weight::zero()) @@ -676,8 +677,8 @@ mod tests { test_lane_id(), ) .unwrap() - .last_delivered_nonce() + - 1, + .last_delivered_nonce() + + 1, nonces_end: best_message, }), messages_count: 1, diff --git a/pezbridges/modules/relayers/src/extension/priority.rs b/pezbridges/modules/relayers/src/extension/priority.rs index 6d006fb6..db827847 100644 --- a/pezbridges/modules/relayers/src/extension/priority.rs +++ b/pezbridges/modules/relayers/src/extension/priority.rs @@ -98,9 +98,9 @@ mod integrity_tests { let priority_with_tip = estimate_priority(1, tip); const ERROR_MARGIN: TransactionPriority = 5; // 5% - if priority_with_boost.abs_diff(priority_with_tip).saturating_mul(100) / - priority_with_tip > - ERROR_MARGIN + if priority_with_boost.abs_diff(priority_with_tip).saturating_mul(100) + / priority_with_tip + > ERROR_MARGIN { panic!( "The {param_name} value ({}) must be fixed to: {}", diff --git a/pezbridges/modules/relayers/src/extension/teyrchain_adapter.rs b/pezbridges/modules/relayers/src/extension/teyrchain_adapter.rs index 28e90356..3eb194dc 100644 --- a/pezbridges/modules/relayers/src/extension/teyrchain_adapter.rs +++ b/pezbridges/modules/relayers/src/extension/teyrchain_adapter.rs @@ -122,14 +122,16 @@ where let relay_finality_call = calls.next().transpose()?.and_then(|c| c.submit_finality_proof_info()); Ok(match (total_calls, relay_finality_call, para_finality_call, msgs_call) { - (3, Some(relay_finality_call), Some(para_finality_call), Some(msgs_call)) => + (3, Some(relay_finality_call), Some(para_finality_call), Some(msgs_call)) => { Some(ExtensionCallInfo::AllFinalityAndMsgs( relay_finality_call, para_finality_call, msgs_call, - )), - (2, None, Some(para_finality_call), Some(msgs_call)) => - Some(ExtensionCallInfo::TeyrchainFinalityAndMsgs(para_finality_call, msgs_call)), + )) + }, + (2, None, Some(para_finality_call), Some(msgs_call)) => { + Some(ExtensionCallInfo::TeyrchainFinalityAndMsgs(para_finality_call, msgs_call)) + }, (1, None, None, Some(msgs_call)) => Some(ExtensionCallInfo::Msgs(msgs_call)), _ => None, }) @@ -151,8 +153,8 @@ where ) -> bool { verify_submit_finality_proof_succeeded::( call_info, call_data, relayer, - ) && verify_submit_teyrchain_head_succeeded::(call_info, call_data, relayer) && - verify_messages_call_succeeded::(call_info, call_data, relayer) + ) && verify_submit_teyrchain_head_succeeded::(call_info, call_data, relayer) + && verify_messages_call_succeeded::(call_info, call_data, relayer) } } diff --git a/pezbridges/modules/relayers/src/mock.rs b/pezbridges/modules/relayers/src/mock.rs index b3ae7d3a..ed460988 100644 --- a/pezbridges/modules/relayers/src/mock.rs +++ b/pezbridges/modules/relayers/src/mock.rs @@ -381,8 +381,8 @@ impl MessageDispatch for DummyMessageDispatch { type LaneId = TestLaneIdType; fn is_active(lane: Self::LaneId) -> bool { - pezframe_support::storage::unhashed::take::(&(b"inactive", lane).encode()[..]) != - Some(false) + pezframe_support::storage::unhashed::take::(&(b"inactive", lane).encode()[..]) + != Some(false) } fn dispatch_weight( diff --git a/pezbridges/modules/teyrchains/src/call_ext.rs b/pezbridges/modules/teyrchains/src/call_ext.rs index 9c4d6373..54d150ed 100644 --- a/pezbridges/modules/teyrchains/src/call_ext.rs +++ b/pezbridges/modules/teyrchains/src/call_ext.rs @@ -158,12 +158,13 @@ impl, I: 'static> SubmitTeyrchainHeadsHelper { /// Check if the `SubmitTeyrchainHeads` was successfully executed. pub fn was_successful(update: &SubmitTeyrchainHeadsInfo) -> bool { match crate::ParasInfo::::get(update.para_id) { - Some(stored_best_head) => - stored_best_head.best_head_hash == - BestParaHeadHash { + Some(stored_best_head) => { + stored_best_head.best_head_hash + == BestParaHeadHash { at_relay_block_number: update.at_relay_block.0, head_hash: update.para_head_hash, - }, + } + }, None => false, } } diff --git a/pezbridges/modules/teyrchains/src/lib.rs b/pezbridges/modules/teyrchains/src/lib.rs index 238e0995..7cdef142 100644 --- a/pezbridges/modules/teyrchains/src/lib.rs +++ b/pezbridges/modules/teyrchains/src/lib.rs @@ -526,14 +526,16 @@ pub mod pezpallet { let update_result: Result<_, ()> = ParasInfo::::try_mutate(teyrchain, |stored_best_head| { - let is_free = teyrchain_head_size < - T::ParaStoredHeaderDataBuilder::max_free_head_size() as usize && - match stored_best_head { + let is_free = teyrchain_head_size + < T::ParaStoredHeaderDataBuilder::max_free_head_size() as usize + && match stored_best_head { Some(ref best_head) if at_relay_block.0.saturating_sub( best_head.best_head_hash.at_relay_block_number, ) >= free_headers_interval => - true, + { + true + }, Some(_) => false, None => true, }; @@ -699,8 +701,8 @@ pub mod pezpallet { at_relay_block_number: new_at_relay_block.0, head_hash: new_head_hash, }, - next_imported_hash_position: (next_imported_hash_position + 1) % - T::HeadsToKeep::get(), + next_imported_hash_position: (next_imported_hash_position + 1) + % T::HeadsToKeep::get(), }; ImportedParaHashes::::insert( teyrchain, diff --git a/pezbridges/modules/teyrchains/src/weights_ext.rs b/pezbridges/modules/teyrchains/src/weights_ext.rs index 3a5aebe8..be4fdb74 100644 --- a/pezbridges/modules/teyrchains/src/weights_ext.rs +++ b/pezbridges/modules/teyrchains/src/weights_ext.rs @@ -104,9 +104,9 @@ pub trait WeightInfoExt: WeightInfo { /// Returns weight that needs to be accounted when storage proof of given size is received. fn storage_proof_size_overhead(extra_proof_bytes: u32) -> Weight { - let extra_byte_weight = (Self::submit_teyrchain_heads_with_16kb_proof() - - Self::submit_teyrchain_heads_with_1kb_proof()) / - (15 * 1024); + let extra_byte_weight = (Self::submit_teyrchain_heads_with_16kb_proof() + - Self::submit_teyrchain_heads_with_1kb_proof()) + / (15 * 1024); extra_byte_weight.saturating_mul(extra_proof_bytes as u64) } } diff --git a/pezbridges/modules/xcm-bridge-hub-router/src/lib.rs b/pezbridges/modules/xcm-bridge-hub-router/src/lib.rs index f8da03bd..54b7faf0 100644 --- a/pezbridges/modules/xcm-bridge-hub-router/src/lib.rs +++ b/pezbridges/modules/xcm-bridge-hub-router/src/lib.rs @@ -279,7 +279,9 @@ impl, I: 'static> ExporterFor for Pezpallet { match T::Bridges::exporter_for(network, remote_location, message) { Some((bridge_hub_location, maybe_payment)) if bridge_hub_location.eq(&T::SiblingBridgeHubLocation::get()) => - (bridge_hub_location, maybe_payment), + { + (bridge_hub_location, maybe_payment) + }, _ => { tracing::trace!( target: LOG_TARGET, @@ -504,8 +506,8 @@ mod tests { Bridge::::put(uncongested_bridge(initial_fee_factor)); // it should eventually decrease to one - while XcmBridgeHubRouter::bridge().delivery_fee_factor > - Pezpallet::::MIN_FEE_FACTOR + while XcmBridgeHubRouter::bridge().delivery_fee_factor + > Pezpallet::::MIN_FEE_FACTOR { XcmBridgeHubRouter::on_initialize(One::one()); } @@ -637,10 +639,10 @@ mod tests { let factor = FixedU128::from_rational(125, 100); Bridge::::put(uncongested_bridge(factor)); let expected_fee = - (FixedU128::saturating_from_integer(BASE_FEE + BYTE_FEE * (msg_size as u128)) * - factor) - .into_inner() / FixedU128::DIV + - HRMP_FEE; + (FixedU128::saturating_from_integer(BASE_FEE + BYTE_FEE * (msg_size as u128)) + * factor) + .into_inner() / FixedU128::DIV + + HRMP_FEE; assert_eq!( XcmBridgeHubRouter::validate(&mut Some(dest), &mut Some(xcm)).unwrap().1.get(0), Some(&(BridgeFeeAsset::get(), expected_fee).into()), diff --git a/pezbridges/modules/xcm-bridge-hub/src/lib.rs b/pezbridges/modules/xcm-bridge-hub/src/lib.rs index 6fe56783..93d2c880 100644 --- a/pezbridges/modules/xcm-bridge-hub/src/lib.rs +++ b/pezbridges/modules/xcm-bridge-hub/src/lib.rs @@ -767,8 +767,9 @@ pub mod pezpallet { let lane_id = match maybe_lane_id { Some(lane_id) => *lane_id, - None => - locations.calculate_lane_id(xcm::latest::VERSION).expect("Valid locations"), + None => { + locations.calculate_lane_id(xcm::latest::VERSION).expect("Valid locations") + }, }; Pezpallet::::do_open_bridge(locations, lane_id, true) diff --git a/pezbridges/modules/xcm-bridge-hub/src/mock.rs b/pezbridges/modules/xcm-bridge-hub/src/mock.rs index 497628ff..9ff60978 100644 --- a/pezbridges/modules/xcm-bridge-hub/src/mock.rs +++ b/pezbridges/modules/xcm-bridge-hub/src/mock.rs @@ -643,8 +643,8 @@ impl MessageDispatch for TestMessageDispatch { type LaneId = TestLaneIdType; fn is_active(lane: Self::LaneId) -> bool { - pezframe_support::storage::unhashed::take::(&(b"inactive", lane).encode()[..]) != - Some(false) + pezframe_support::storage::unhashed::take::(&(b"inactive", lane).encode()[..]) + != Some(false) } fn dispatch_weight( diff --git a/pezbridges/primitives/header-chain/src/justification/verification/mod.rs b/pezbridges/primitives/header-chain/src/justification/verification/mod.rs index 0cb5ac1e..f22db5c0 100644 --- a/pezbridges/primitives/header-chain/src/justification/verification/mod.rs +++ b/pezbridges/primitives/header-chain/src/justification/verification/mod.rs @@ -242,8 +242,8 @@ trait JustificationVerifier { justification: &GrandpaJustification
, ) -> Result<(), Error> { // ensure that it is justification for the expected header - if (justification.commit.target_hash, justification.commit.target_number) != - finalized_target + if (justification.commit.target_hash, justification.commit.target_number) + != finalized_target { return Err(Error::InvalidJustificationTarget); } diff --git a/pezbridges/primitives/header-chain/src/lib.rs b/pezbridges/primitives/header-chain/src/lib.rs index fdae2361..9ae1fc4d 100644 --- a/pezbridges/primitives/header-chain/src/lib.rs +++ b/pezbridges/primitives/header-chain/src/lib.rs @@ -434,8 +434,8 @@ mod tests { #[test] fn max_expected_submit_finality_proof_arguments_size_respects_mandatory_argument() { assert!( - max_expected_submit_finality_proof_arguments_size::(true, 100) > - max_expected_submit_finality_proof_arguments_size::(false, 100), + max_expected_submit_finality_proof_arguments_size::(true, 100) + > max_expected_submit_finality_proof_arguments_size::(false, 100), ); } diff --git a/pezbridges/primitives/messages/src/lib.rs b/pezbridges/primitives/messages/src/lib.rs index b71ea353..4152432a 100644 --- a/pezbridges/primitives/messages/src/lib.rs +++ b/pezbridges/primitives/messages/src/lib.rs @@ -291,8 +291,9 @@ impl InboundLaneData { pub fn total_unrewarded_messages(&self) -> MessageNonce { let relayers = &self.relayers; match (relayers.front(), relayers.back()) { - (Some(front), Some(back)) => - (front.messages.begin..=back.messages.end).saturating_len(), + (Some(front), Some(back)) => { + (front.messages.begin..=back.messages.end).saturating_len() + }, _ => 0, } } diff --git a/pezbridges/primitives/relayers/src/extension.rs b/pezbridges/primitives/relayers/src/extension.rs index 6b0fd5d4..1acac2e8 100644 --- a/pezbridges/primitives/relayers/src/extension.rs +++ b/pezbridges/primitives/relayers/src/extension.rs @@ -183,7 +183,9 @@ where match call.is_sub_type() { Some(UtilityCall::::batch_all { ref calls }) if calls.len() <= max_packed_calls as usize => - calls.iter().collect(), + { + calls.iter().collect() + }, Some(_) => vec![], None => vec![call], } diff --git a/pezbridges/primitives/relayers/src/registration.rs b/pezbridges/primitives/relayers/src/registration.rs index 4453a112..79a72cb6 100644 --- a/pezbridges/primitives/relayers/src/registration.rs +++ b/pezbridges/primitives/relayers/src/registration.rs @@ -71,8 +71,9 @@ impl IdentifyAccount fn into_account(self) -> Self::AccountId { match self { ExplicitOrAccountParams::Explicit(account_id) => account_id, - ExplicitOrAccountParams::Params(params) => - PayRewardFromAccount::<(), AccountId, LaneId, ()>::rewards_account(params), + ExplicitOrAccountParams::Params(params) => { + PayRewardFromAccount::<(), AccountId, LaneId, ()>::rewards_account(params) + }, } } } diff --git a/pezbridges/primitives/runtime/src/chain.rs b/pezbridges/primitives/runtime/src/chain.rs index 51927398..b330d344 100644 --- a/pezbridges/primitives/runtime/src/chain.rs +++ b/pezbridges/primitives/runtime/src/chain.rs @@ -44,8 +44,9 @@ impl EncodedOrDecodedCall { /// Returns decoded call. pub fn to_decoded(&self) -> Result { match self { - Self::Encoded(ref encoded_call) => - ChainCall::decode(&mut &encoded_call[..]).map_err(Into::into), + Self::Encoded(ref encoded_call) => { + ChainCall::decode(&mut &encoded_call[..]).map_err(Into::into) + }, Self::Decoded(ref decoded_call) => Ok(decoded_call.clone()), } } @@ -53,8 +54,9 @@ impl EncodedOrDecodedCall { /// Converts self to decoded call. pub fn into_decoded(self) -> Result { match self { - Self::Encoded(encoded_call) => - ChainCall::decode(&mut &encoded_call[..]).map_err(Into::into), + Self::Encoded(encoded_call) => { + ChainCall::decode(&mut &encoded_call[..]).map_err(Into::into) + }, Self::Decoded(decoded_call) => Ok(decoded_call), } } diff --git a/pezbridges/primitives/runtime/src/lib.rs b/pezbridges/primitives/runtime/src/lib.rs index 6a206855..9494a3d1 100644 --- a/pezbridges/primitives/runtime/src/lib.rs +++ b/pezbridges/primitives/runtime/src/lib.rs @@ -311,10 +311,10 @@ pub trait StorageDoubleMapKeyProvider { let storage_prefix_hashed = pezframe_support::Twox128::hash(Self::MAP_NAME.as_bytes()); let mut final_key = Vec::with_capacity( - pezpallet_prefix_hashed.len() + - storage_prefix_hashed.len() + - key1_hashed.as_ref().len() + - key2_hashed.as_ref().len(), + pezpallet_prefix_hashed.len() + + storage_prefix_hashed.len() + + key1_hashed.as_ref().len() + + key2_hashed.as_ref().len(), ); final_key.extend_from_slice(&pezpallet_prefix_hashed[..]); @@ -398,7 +398,9 @@ pub trait OwnedBridgeModule { Ok(RawOrigin::Root) => Ok(()), Ok(RawOrigin::Signed(ref signer)) if Self::OwnerStorage::get().as_ref() == Some(signer) => - Ok(()), + { + Ok(()) + }, _ => Err(BadOrigin), } } diff --git a/pezbridges/relays/client-bizinikiwi/src/client/rpc.rs b/pezbridges/relays/client-bizinikiwi/src/client/rpc.rs index 07a8fbc9..49859443 100644 --- a/pezbridges/relays/client-bizinikiwi/src/client/rpc.rs +++ b/pezbridges/relays/client-bizinikiwi/src/client/rpc.rs @@ -173,8 +173,9 @@ impl RpcClient { // same and we need to abort if actual version is > than expected let actual = SimpleRuntimeVersion::from_runtime_version(&env.runtime_version().await?); match actual.spec_version.cmp(&expected.spec_version) { - Ordering::Less => - Err(Error::WaitingForRuntimeUpgrade { chain: C::NAME.into(), expected, actual }), + Ordering::Less => { + Err(Error::WaitingForRuntimeUpgrade { chain: C::NAME.into(), expected, actual }) + }, Ordering::Equal => Ok(()), Ordering::Greater => { tracing::error!( diff --git a/pezbridges/relays/client-bizinikiwi/src/metrics/float_storage_value.rs b/pezbridges/relays/client-bizinikiwi/src/metrics/float_storage_value.rs index 1fbbf601..2b102c0a 100644 --- a/pezbridges/relays/client-bizinikiwi/src/metrics/float_storage_value.rs +++ b/pezbridges/relays/client-bizinikiwi/src/metrics/float_storage_value.rs @@ -126,8 +126,8 @@ impl, V: FloatStorageValue> StandaloneMetric .await?; self.value_converter.decode(maybe_storage_value).map(|maybe_fixed_point_value| { maybe_fixed_point_value.map(|fixed_point_value| { - fixed_point_value.into_inner().unique_saturated_into() as f64 / - V::Value::DIV.unique_saturated_into() as f64 + fixed_point_value.into_inner().unique_saturated_into() as f64 + / V::Value::DIV.unique_saturated_into() as f64 }) }) } diff --git a/pezbridges/relays/client-bizinikiwi/src/transaction_tracker.rs b/pezbridges/relays/client-bizinikiwi/src/transaction_tracker.rs index b108f1ea..1993d177 100644 --- a/pezbridges/relays/client-bizinikiwi/src/transaction_tracker.rs +++ b/pezbridges/relays/client-bizinikiwi/src/transaction_tracker.rs @@ -121,10 +121,12 @@ impl> TransactionTracker { (TrackedTransactionStatus::Lost, None) }, Either::Right((invalidation_status, _)) => match invalidation_status { - InvalidationStatus::Finalized(at_block) => - (TrackedTransactionStatus::Finalized(at_block), Some(invalidation_status)), - InvalidationStatus::Invalid => - (TrackedTransactionStatus::Lost, Some(invalidation_status)), + InvalidationStatus::Finalized(at_block) => { + (TrackedTransactionStatus::Finalized(at_block), Some(invalidation_status)) + }, + InvalidationStatus::Invalid => { + (TrackedTransactionStatus::Lost, Some(invalidation_status)) + }, InvalidationStatus::Lost => { // wait for the rest of stall timeout - this way we'll be sure that the // transaction is actually dead if it has been crafted properly @@ -228,9 +230,9 @@ async fn watch_transaction_status< ); return InvalidationStatus::Invalid; }, - Some(TransactionStatusOf::::Future) | - Some(TransactionStatusOf::::Ready) | - Some(TransactionStatusOf::::Broadcast(_)) => { + Some(TransactionStatusOf::::Future) + | Some(TransactionStatusOf::::Ready) + | Some(TransactionStatusOf::::Broadcast(_)) => { // nothing important (for us) has happened }, Some(TransactionStatusOf::::InBlock(block_hash)) => { diff --git a/pezbridges/relays/equivocation/src/block_checker.rs b/pezbridges/relays/equivocation/src/block_checker.rs index 6fab38bc..1f24c699 100644 --- a/pezbridges/relays/equivocation/src/block_checker.rs +++ b/pezbridges/relays/equivocation/src/block_checker.rs @@ -39,8 +39,9 @@ impl ReadSyncedHeaders

{ target_client: &mut TC, ) -> Result, Self> { match target_client.synced_headers_finality_info(self.target_block_num).await { - Ok(synced_headers) => - Ok(ReadContext { target_block_num: self.target_block_num, synced_headers }), + Ok(synced_headers) => { + Ok(ReadContext { target_block_num: self.target_block_num, synced_headers }) + }, Err(e) => { tracing::error!( target: "bridge", @@ -127,13 +128,14 @@ impl FindEquivocations

{ &synced_header.finality_proof, finality_proofs_buf.buf().as_slice(), ) { - Ok(equivocations) => + Ok(equivocations) => { if !equivocations.is_empty() { result.push(ReportEquivocations { source_block_hash: self.context.synced_header_hash, equivocations, }) - }, + } + }, Err(e) => { tracing::error!( target: "bridge", @@ -272,23 +274,23 @@ mod tests { impl PartialEq for ReadContext { fn eq(&self, other: &Self) -> bool { - self.target_block_num == other.target_block_num && - self.synced_headers == other.synced_headers + self.target_block_num == other.target_block_num + && self.synced_headers == other.synced_headers } } impl PartialEq for FindEquivocations { fn eq(&self, other: &Self) -> bool { - self.target_block_num == other.target_block_num && - self.synced_headers == other.synced_headers && - self.context == other.context + self.target_block_num == other.target_block_num + && self.synced_headers == other.synced_headers + && self.context == other.context } } impl PartialEq for ReportEquivocations { fn eq(&self, other: &Self) -> bool { - self.source_block_hash == other.source_block_hash && - self.equivocations == other.equivocations + self.source_block_hash == other.source_block_hash + && self.equivocations == other.equivocations } } diff --git a/pezbridges/relays/finality/src/finality_loop.rs b/pezbridges/relays/finality/src/finality_loop.rs index 6220e6b7..91e95b76 100644 --- a/pezbridges/relays/finality/src/finality_loop.rs +++ b/pezbridges/relays/finality/src/finality_loop.rs @@ -289,11 +289,11 @@ impl, TC: TargetClient

> Finality let (prev_time, prev_best_number_at_target) = self.progress; let now = Instant::now(); - let needs_update = now - prev_time > Duration::from_secs(10) || - prev_best_number_at_target + let needs_update = now - prev_time > Duration::from_secs(10) + || prev_best_number_at_target .map(|prev_best_number_at_target| { - info.best_number_at_target.saturating_sub(prev_best_number_at_target) > - 10.into() + info.best_number_at_target.saturating_sub(prev_best_number_at_target) + > 10.into() }) .unwrap_or(true); diff --git a/pezbridges/relays/finality/src/headers.rs b/pezbridges/relays/finality/src/headers.rs index c16ed3f0..8f9a9b7f 100644 --- a/pezbridges/relays/finality/src/headers.rs +++ b/pezbridges/relays/finality/src/headers.rs @@ -128,8 +128,9 @@ impl JustifiedHeaderSelector

{ ) -> Option> { let (unjustified_headers, maybe_justified_header) = match self { JustifiedHeaderSelector::Mandatory(justified_header) => return Some(justified_header), - JustifiedHeaderSelector::Regular(unjustified_headers, justified_header) => - (unjustified_headers, Some(justified_header)), + JustifiedHeaderSelector::Regular(unjustified_headers, justified_header) => { + (unjustified_headers, Some(justified_header)) + }, JustifiedHeaderSelector::None(unjustified_headers) => (unjustified_headers, None), }; @@ -194,14 +195,15 @@ fn need_to_relay( match headers_to_relay { HeadersToRelay::All => true, HeadersToRelay::Mandatory => header.is_mandatory(), - HeadersToRelay::Free => - header.is_mandatory() || - free_headers_interval + HeadersToRelay::Free => { + header.is_mandatory() + || free_headers_interval .map(|free_headers_interval| { - header.number().saturating_sub(info.best_number_at_target) >= - free_headers_interval + header.number().saturating_sub(info.best_number_at_target) + >= free_headers_interval }) - .unwrap_or(false), + .unwrap_or(false) + }, } } diff --git a/pezbridges/relays/lib-bizinikiwi-relay/src/messages/mod.rs b/pezbridges/relays/lib-bizinikiwi-relay/src/messages/mod.rs index 0291a01f..33a9cbdf 100644 --- a/pezbridges/relays/lib-bizinikiwi-relay/src/messages/mod.rs +++ b/pezbridges/relays/lib-bizinikiwi-relay/src/messages/mod.rs @@ -213,13 +213,14 @@ where let max_messages_size_in_single_batch = P::TargetChain::max_extrinsic_size() / 3; let limits = match params.limits { Some(limits) => limits, - None => + None => { select_delivery_transaction_limits_rpc( ¶ms, P::TargetChain::max_extrinsic_weight(), P::SourceChain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX, ) - .await?, + .await? + }, }; let (max_messages_in_single_batch, max_messages_weight_in_single_batch) = (limits.max_messages_in_single_batch / 2, limits.max_messages_weight_in_single_batch / 2); @@ -706,8 +707,9 @@ mod tests { impl From> for RuntimeCall { fn from(value: MockUtilityCall) -> RuntimeCall { match value { - MockUtilityCall::batch_all(calls) => - RuntimeCall::Utility(UtilityCall::::batch_all(calls)), + MockUtilityCall::batch_all(calls) => { + RuntimeCall::Utility(UtilityCall::::batch_all(calls)) + }, } } } diff --git a/pezbridges/relays/lib-bizinikiwi-relay/src/teyrchains/target.rs b/pezbridges/relays/lib-bizinikiwi-relay/src/teyrchains/target.rs index 4889a937..e9e3835a 100644 --- a/pezbridges/relays/lib-bizinikiwi-relay/src/teyrchains/target.rs +++ b/pezbridges/relays/lib-bizinikiwi-relay/src/teyrchains/target.rs @@ -197,8 +197,9 @@ where let storage_value: Option = self.target_client.storage_value(at_block.hash(), storage_key).await?; let para_head_number = match storage_value { - Some(para_head_data) => - para_head_data.decode_teyrchain_head_data::()?.number, + Some(para_head_data) => { + para_head_data.decode_teyrchain_head_data::()?.number + }, None => return Ok(None), }; diff --git a/pezbridges/relays/messages/src/message_lane_loop.rs b/pezbridges/relays/messages/src/message_lane_loop.rs index f94c1c2e..d2e8a7e6 100644 --- a/pezbridges/relays/messages/src/message_lane_loop.rs +++ b/pezbridges/relays/messages/src/message_lane_loop.rs @@ -1068,8 +1068,8 @@ pub(crate) mod tests { data.source_state.best_finalized_self = data.source_state.best_self; // syncing target headers -> source chain if let Some(last_requirement) = data.target_to_source_header_requirements.last() { - if *last_requirement != - data.source_state.best_finalized_peer_at_best_self.unwrap() + if *last_requirement + != data.source_state.best_finalized_peer_at_best_self.unwrap() { data.source_state.best_finalized_peer_at_best_self = Some(*last_requirement); @@ -1091,8 +1091,8 @@ pub(crate) mod tests { data.target_state.best_finalized_self = data.target_state.best_self; // syncing source headers -> target chain if let Some(last_requirement) = data.source_to_target_header_requirements.last() { - if *last_requirement != - data.target_state.best_finalized_peer_at_best_self.unwrap() + if *last_requirement + != data.target_state.best_finalized_peer_at_best_self.unwrap() { data.target_state.best_finalized_peer_at_best_self = Some(*last_requirement); @@ -1148,15 +1148,15 @@ pub(crate) mod tests { // headers relay must only be started when we need new target headers at source node if data.target_to_source_header_required.is_some() { assert!( - data.source_state.best_finalized_peer_at_best_self.unwrap().0 < - data.target_state.best_self.0 + data.source_state.best_finalized_peer_at_best_self.unwrap().0 + < data.target_state.best_self.0 ); data.target_to_source_header_required = None; } // syncing target headers -> source chain if let Some(last_requirement) = data.target_to_source_header_requirements.last() { - if *last_requirement != - data.source_state.best_finalized_peer_at_best_self.unwrap() + if *last_requirement + != data.source_state.best_finalized_peer_at_best_self.unwrap() { data.source_state.best_finalized_peer_at_best_self = Some(*last_requirement); @@ -1172,15 +1172,15 @@ pub(crate) mod tests { // headers relay must only be started when we need new source headers at target node if data.source_to_target_header_required.is_some() { assert!( - data.target_state.best_finalized_peer_at_best_self.unwrap().0 < - data.source_state.best_self.0 + data.target_state.best_finalized_peer_at_best_self.unwrap().0 + < data.source_state.best_self.0 ); data.source_to_target_header_required = None; } // syncing source headers -> target chain if let Some(last_requirement) = data.source_to_target_header_requirements.last() { - if *last_requirement != - data.target_state.best_finalized_peer_at_best_self.unwrap() + if *last_requirement + != data.target_state.best_finalized_peer_at_best_self.unwrap() { data.target_state.best_finalized_peer_at_best_self = Some(*last_requirement); diff --git a/pezbridges/relays/messages/src/message_race_delivery.rs b/pezbridges/relays/messages/src/message_race_delivery.rs index df1bc146..6aa34b15 100644 --- a/pezbridges/relays/messages/src/message_race_delivery.rs +++ b/pezbridges/relays/messages/src/message_race_delivery.rs @@ -411,10 +411,10 @@ where // "unrewarded relayers" set. If we are unable to prove new rewards to the target node, then // we should wait for confirmations race. let unrewarded_limit_reached = - target_nonces.nonces_data.unrewarded_relayers.unrewarded_relayer_entries >= - self.max_unrewarded_relayer_entries_at_target || - target_nonces.nonces_data.unrewarded_relayers.total_messages >= - self.max_unconfirmed_nonces_at_target; + target_nonces.nonces_data.unrewarded_relayers.unrewarded_relayer_entries + >= self.max_unrewarded_relayer_entries_at_target + || target_nonces.nonces_data.unrewarded_relayers.total_messages + >= self.max_unconfirmed_nonces_at_target; if unrewarded_limit_reached { // so there are already too many unrewarded relayer entries in the set // @@ -422,8 +422,8 @@ where // be paid let number_of_rewards_being_proved = latest_confirmed_nonce_at_source.saturating_sub(latest_confirmed_nonce_at_target); - let enough_rewards_being_proved = number_of_rewards_being_proved >= - target_nonces.nonces_data.unrewarded_relayers.messages_in_oldest_entry; + let enough_rewards_being_proved = number_of_rewards_being_proved + >= target_nonces.nonces_data.unrewarded_relayers.messages_in_oldest_entry; if !enough_rewards_being_proved { return None; } diff --git a/pezbridges/relays/messages/src/message_race_limits.rs b/pezbridges/relays/messages/src/message_race_limits.rs index 9cf1f060..50bd94f1 100644 --- a/pezbridges/relays/messages/src/message_race_limits.rs +++ b/pezbridges/relays/messages/src/message_race_limits.rs @@ -114,7 +114,9 @@ impl MessageRaceLimits { Some(new_selected_weight) if new_selected_weight .all_lte(reference.max_messages_weight_in_single_batch) => - new_selected_weight, + { + new_selected_weight + }, new_selected_weight if selected_count == 0 => { tracing::warn!( target: "bridge", @@ -132,7 +134,9 @@ impl MessageRaceLimits { let new_selected_size = match relay_reference.selected_size.checked_add(details.size) { Some(new_selected_size) if new_selected_size <= reference.max_messages_size_in_single_batch => - new_selected_size, + { + new_selected_size + }, new_selected_size if selected_count == 0 => { tracing::warn!( target: "bridge", diff --git a/pezbridges/relays/messages/src/message_race_strategy.rs b/pezbridges/relays/messages/src/message_race_strategy.rs index ba33f5fe..471dc0f8 100644 --- a/pezbridges/relays/messages/src/message_race_strategy.rs +++ b/pezbridges/relays/messages/src/message_race_strategy.rs @@ -221,8 +221,9 @@ where fn best_at_source(&self) -> Option { let best_in_queue = self.source_queue.back().map(|(_, range)| range.end()); match (best_in_queue, self.best_target_nonce) { - (Some(best_in_queue), Some(best_target_nonce)) if best_in_queue > best_target_nonce => - Some(best_in_queue), + (Some(best_in_queue), Some(best_target_nonce)) if best_in_queue > best_target_nonce => { + Some(best_in_queue) + }, (_, Some(best_target_nonce)) => Some(best_target_nonce), (_, None) => None, } diff --git a/pezbridges/relays/teyrchains/src/teyrchains_loop.rs b/pezbridges/relays/teyrchains/src/teyrchains_loop.rs index 4155b18f..b426802f 100644 --- a/pezbridges/relays/teyrchains/src/teyrchains_loop.rs +++ b/pezbridges/relays/teyrchains/src/teyrchains_loop.rs @@ -359,8 +359,8 @@ where // find last free relay chain header in the range that we are interested in let scan_range_begin = relay_of_head_at_target.number(); let scan_range_end = best_finalized_relay_block_at_target.number(); - if scan_range_end.saturating_sub(scan_range_begin) < - free_source_relay_headers_interval + if scan_range_end.saturating_sub(scan_range_begin) + < free_source_relay_headers_interval { // there are no new **free** relay chain headers in the range tracing::trace!( @@ -647,7 +647,9 @@ impl SubmittedHeadsTracker

{ let is_head_updated = match (self.submitted_head, head_at_target) { (AvailableHeader::Available(submitted_head), Some(head_at_target)) if head_at_target.number() >= submitted_head.number() => - true, + { + true + }, (AvailableHeader::Missing, None) => true, _ => false, }; @@ -669,8 +671,9 @@ impl SubmittedHeadsTracker

{ // then restart our sync let transaction_tracker = self.transaction_tracker.clone(); match poll!(transaction_tracker) { - Poll::Ready(TrackedTransactionStatus::Lost) => - return SubmittedHeadStatus::Final(TrackedTransactionStatus::Lost), + Poll::Ready(TrackedTransactionStatus::Lost) => { + return SubmittedHeadStatus::Final(TrackedTransactionStatus::Lost) + }, Poll::Ready(TrackedTransactionStatus::Finalized(_)) => { // so we are here and our transaction is mined+finalized, but some of heads were not // updated => we're considering our loop as stalled diff --git a/pezbridges/snowbridge/pezpallets/ethereum-client/src/impls.rs b/pezbridges/snowbridge/pezpallets/ethereum-client/src/impls.rs index ab4c660a..084e61cd 100644 --- a/pezbridges/snowbridge/pezpallets/ethereum-client/src/impls.rs +++ b/pezbridges/snowbridge/pezpallets/ethereum-client/src/impls.rs @@ -54,9 +54,9 @@ impl Pezpallet { } fn check_log_match(log: &Log, receipt_log: &AlloyLog) -> bool { - let equal = receipt_log.data.data.0 == log.data && - receipt_log.address.0 == log.address.0 && - receipt_log.topics().len() == log.topics.len(); + let equal = receipt_log.data.data.0 == log.data + && receipt_log.address.0 == log.address.0 + && receipt_log.topics().len() == log.topics.len(); if !equal { return false; } diff --git a/pezbridges/snowbridge/pezpallets/ethereum-client/src/lib.rs b/pezbridges/snowbridge/pezpallets/ethereum-client/src/lib.rs index 6dd17e3d..ab424bef 100644 --- a/pezbridges/snowbridge/pezpallets/ethereum-client/src/lib.rs +++ b/pezbridges/snowbridge/pezpallets/ethereum-client/src/lib.rs @@ -317,8 +317,8 @@ pub mod pezpallet { // Verify update does not skip a sync committee period. ensure!( - update.signature_slot > update.attested_header.slot && - update.attested_header.slot >= update.finalized_header.slot, + update.signature_slot > update.attested_header.slot + && update.attested_header.slot >= update.finalized_header.slot, Error::::InvalidUpdateSlot ); // Retrieve latest finalized state. @@ -339,12 +339,12 @@ pub mod pezpallet { // Verify update is relevant. let update_attested_period = compute_period(update.attested_header.slot); let update_finalized_period = compute_period(update.finalized_header.slot); - let update_has_next_sync_committee = !>::exists() && - (update.next_sync_committee_update.is_some() && - update_attested_period == store_period); + let update_has_next_sync_committee = !>::exists() + && (update.next_sync_committee_update.is_some() + && update_attested_period == store_period); ensure!( - update.attested_header.slot > latest_finalized_state.slot || - update_has_next_sync_committee, + update.attested_header.slot > latest_finalized_state.slot + || update_has_next_sync_committee, Error::::IrrelevantUpdate ); @@ -354,8 +354,8 @@ pub mod pezpallet { ensure!( latest_finalized_state .slot - .saturating_add(config::SLOTS_PER_HISTORICAL_ROOT as u64) >= - update.finalized_header.slot, + .saturating_add(config::SLOTS_PER_HISTORICAL_ROOT as u64) + >= update.finalized_header.slot, Error::::InvalidFinalizedHeaderGap ); @@ -706,8 +706,8 @@ pub mod pezpallet { // If the latest finalized header is larger than the minimum slot interval, the header // import transaction is free. - if update.finalized_header.slot >= - latest_slot.saturating_add(T::FreeHeadersInterval::get() as u64) + if update.finalized_header.slot + >= latest_slot.saturating_add(T::FreeHeadersInterval::get() as u64) { return Pays::No; } diff --git a/pezbridges/snowbridge/pezpallets/inbound-queue/src/lib.rs b/pezbridges/snowbridge/pezpallets/inbound-queue/src/lib.rs index cce87ec0..071a5bc3 100644 --- a/pezbridges/snowbridge/pezpallets/inbound-queue/src/lib.rs +++ b/pezbridges/snowbridge/pezpallets/inbound-queue/src/lib.rs @@ -210,10 +210,12 @@ pub mod pezpallet { XcmpSendError::NotApplicable => Error::::Send(SendError::NotApplicable), XcmpSendError::Unroutable => Error::::Send(SendError::NotRoutable), XcmpSendError::Transport(_) => Error::::Send(SendError::Transport), - XcmpSendError::DestinationUnsupported => - Error::::Send(SendError::DestinationUnsupported), - XcmpSendError::ExceedsMaxMessageSize => - Error::::Send(SendError::ExceedsMaxMessageSize), + XcmpSendError::DestinationUnsupported => { + Error::::Send(SendError::DestinationUnsupported) + }, + XcmpSendError::ExceedsMaxMessageSize => { + Error::::Send(SendError::ExceedsMaxMessageSize) + }, XcmpSendError::MissingArgument => Error::::Send(SendError::MissingArgument), XcmpSendError::Fees => Error::::Send(SendError::Fees), } diff --git a/pezbridges/snowbridge/pezpallets/inbound-queue/src/mock.rs b/pezbridges/snowbridge/pezpallets/inbound-queue/src/mock.rs index 01736791..9c03e2c6 100644 --- a/pezbridges/snowbridge/pezpallets/inbound-queue/src/mock.rs +++ b/pezbridges/snowbridge/pezpallets/inbound-queue/src/mock.rs @@ -182,8 +182,8 @@ impl StaticLookup for MockChannelLookup { type Target = Channel; fn lookup(channel_id: Self::Source) -> Option { - if channel_id != - hex!("c173fac324158e77fb5840738a1a541f633cbec8884c6a601c567d2b376a0539").into() + if channel_id + != hex!("c173fac324158e77fb5840738a1a541f633cbec8884c6a601c567d2b376a0539").into() { return None; } diff --git a/pezbridges/snowbridge/pezpallets/outbound-queue/src/lib.rs b/pezbridges/snowbridge/pezpallets/outbound-queue/src/lib.rs index 114cebc4..2b15db55 100644 --- a/pezbridges/snowbridge/pezpallets/outbound-queue/src/lib.rs +++ b/pezbridges/snowbridge/pezpallets/outbound-queue/src/lib.rs @@ -308,8 +308,8 @@ pub mod pezpallet { // Yield if the maximum number of messages has been processed this block. // This ensures that the weight of `on_finalize` has a known maximum bound. ensure!( - MessageLeaves::::decode_len().unwrap_or(0) < - T::MaxMessagesPerBlock::get() as usize, + MessageLeaves::::decode_len().unwrap_or(0) + < T::MaxMessagesPerBlock::get() as usize, Yield ); diff --git a/pezbridges/snowbridge/pezpallets/system-frontend/src/mock.rs b/pezbridges/snowbridge/pezpallets/system-frontend/src/mock.rs index 5d800982..a481fa7f 100644 --- a/pezbridges/snowbridge/pezpallets/system-frontend/src/mock.rs +++ b/pezbridges/snowbridge/pezpallets/system-frontend/src/mock.rs @@ -80,8 +80,9 @@ pub struct AccountIdConverter; impl xcm_executor::traits::ConvertLocation for AccountIdConverter { fn convert_location(ml: &Location) -> Option { match ml.unpack() { - (0, [Junction::AccountId32 { id, .. }]) => - Some(::decode(&mut &*id.to_vec()).unwrap()), + (0, [Junction::AccountId32 { id, .. }]) => { + Some(::decode(&mut &*id.to_vec()).unwrap()) + }, (1, [Teyrchain(id)]) => Some(ParaId::from(*id).into_account_truncating()), _ => None, } diff --git a/pezbridges/snowbridge/primitives/beacon/src/receipt.rs b/pezbridges/snowbridge/primitives/beacon/src/receipt.rs index 195d3ce7..bf54b66f 100644 --- a/pezbridges/snowbridge/primitives/beacon/src/receipt.rs +++ b/pezbridges/snowbridge/primitives/beacon/src/receipt.rs @@ -7,8 +7,9 @@ use pezsp_std::prelude::*; pub fn verify_receipt_proof(receipts_root: H256, values: &[Vec]) -> Option { match apply_merkle_proof(values) { - Some((root, data)) if root == receipts_root => - ReceiptEnvelope::decode(&mut data.as_slice()).ok(), + Some((root, data)) if root == receipts_root => { + ReceiptEnvelope::decode(&mut data.as_slice()).ok() + }, Some((_, _)) => None, None => None, } diff --git a/pezbridges/snowbridge/primitives/beacon/src/types.rs b/pezbridges/snowbridge/primitives/beacon/src/types.rs index b87e5fbe..cc124504 100644 --- a/pezbridges/snowbridge/primitives/beacon/src/types.rs +++ b/pezbridges/snowbridge/primitives/beacon/src/types.rs @@ -412,41 +412,49 @@ pub enum VersionedExecutionPayloadHeader { impl VersionedExecutionPayloadHeader { pub fn hash_tree_root(&self) -> Result { match self { - VersionedExecutionPayloadHeader::Capella(execution_payload_header) => + VersionedExecutionPayloadHeader::Capella(execution_payload_header) => { hash_tree_root::( execution_payload_header.clone().try_into()?, - ), - VersionedExecutionPayloadHeader::Deneb(execution_payload_header) => + ) + }, + VersionedExecutionPayloadHeader::Deneb(execution_payload_header) => { hash_tree_root::( execution_payload_header.clone().try_into()?, - ), + ) + }, } } pub fn block_hash(&self) -> H256 { match self { - VersionedExecutionPayloadHeader::Capella(execution_payload_header) => - execution_payload_header.block_hash, - VersionedExecutionPayloadHeader::Deneb(execution_payload_header) => - execution_payload_header.block_hash, + VersionedExecutionPayloadHeader::Capella(execution_payload_header) => { + execution_payload_header.block_hash + }, + VersionedExecutionPayloadHeader::Deneb(execution_payload_header) => { + execution_payload_header.block_hash + }, } } pub fn block_number(&self) -> u64 { match self { - VersionedExecutionPayloadHeader::Capella(execution_payload_header) => - execution_payload_header.block_number, - VersionedExecutionPayloadHeader::Deneb(execution_payload_header) => - execution_payload_header.block_number, + VersionedExecutionPayloadHeader::Capella(execution_payload_header) => { + execution_payload_header.block_number + }, + VersionedExecutionPayloadHeader::Deneb(execution_payload_header) => { + execution_payload_header.block_number + }, } } pub fn receipts_root(&self) -> H256 { match self { - VersionedExecutionPayloadHeader::Capella(execution_payload_header) => - execution_payload_header.receipts_root, - VersionedExecutionPayloadHeader::Deneb(execution_payload_header) => - execution_payload_header.receipts_root, + VersionedExecutionPayloadHeader::Capella(execution_payload_header) => { + execution_payload_header.receipts_root + }, + VersionedExecutionPayloadHeader::Deneb(execution_payload_header) => { + execution_payload_header.receipts_root + }, } } } diff --git a/pezbridges/snowbridge/primitives/core/src/location.rs b/pezbridges/snowbridge/primitives/core/src/location.rs index 4613f337..31e762b3 100644 --- a/pezbridges/snowbridge/primitives/core/src/location.rs +++ b/pezbridges/snowbridge/primitives/core/src/location.rs @@ -83,15 +83,19 @@ impl DescribeLocation for DescribeTokenTerminal { // Pezpallet [PalletInstance(instance)] => Some((b"PalletInstance", *instance).encode()), - [PalletInstance(instance), GeneralIndex(index)] => - Some((b"PalletInstance", *instance, b"GeneralIndex", *index).encode()), - [PalletInstance(instance), GeneralKey { data, .. }] => - Some((b"PalletInstance", *instance, b"GeneralKey", *data).encode()), + [PalletInstance(instance), GeneralIndex(index)] => { + Some((b"PalletInstance", *instance, b"GeneralIndex", *index).encode()) + }, + [PalletInstance(instance), GeneralKey { data, .. }] => { + Some((b"PalletInstance", *instance, b"GeneralKey", *data).encode()) + }, - [PalletInstance(instance), AccountKey20 { key, .. }] => - Some((b"PalletInstance", *instance, b"AccountKey20", *key).encode()), - [PalletInstance(instance), AccountId32 { id, .. }] => - Some((b"PalletInstance", *instance, b"AccountId32", *id).encode()), + [PalletInstance(instance), AccountKey20 { key, .. }] => { + Some((b"PalletInstance", *instance, b"AccountKey20", *key).encode()) + }, + [PalletInstance(instance), AccountId32 { id, .. }] => { + Some((b"PalletInstance", *instance, b"AccountId32", *id).encode()) + }, // Reject all other locations _ => None, diff --git a/pezbridges/snowbridge/primitives/inbound-queue/src/lib.rs b/pezbridges/snowbridge/primitives/inbound-queue/src/lib.rs index 9eb7f5e9..07484bb9 100644 --- a/pezbridges/snowbridge/primitives/inbound-queue/src/lib.rs +++ b/pezbridges/snowbridge/primitives/inbound-queue/src/lib.rs @@ -20,10 +20,12 @@ where { fn convert_location(location: &Location) -> Option { match location.unpack() { - (2, [GlobalConsensus(Ethereum { chain_id })]) => - Some(Self::from_chain_id(chain_id).into()), - (2, [GlobalConsensus(Ethereum { chain_id }), AccountKey20 { network: _, key }]) => - Some(Self::from_chain_id_with_key(chain_id, *key).into()), + (2, [GlobalConsensus(Ethereum { chain_id })]) => { + Some(Self::from_chain_id(chain_id).into()) + }, + (2, [GlobalConsensus(Ethereum { chain_id }), AccountKey20 { network: _, key }]) => { + Some(Self::from_chain_id_with_key(chain_id, *key).into()) + }, _ => None, } } diff --git a/pezbridges/snowbridge/primitives/inbound-queue/src/v1.rs b/pezbridges/snowbridge/primitives/inbound-queue/src/v1.rs index 5257b333..65a72fa2 100644 --- a/pezbridges/snowbridge/primitives/inbound-queue/src/v1.rs +++ b/pezbridges/snowbridge/primitives/inbound-queue/src/v1.rs @@ -185,10 +185,12 @@ where use Command::*; use VersionedMessage::*; match message { - V1(MessageV1 { chain_id, command: RegisterToken { token, fee } }) => - Ok(Self::convert_register_token(message_id, chain_id, token, fee)), - V1(MessageV1 { chain_id, command: SendToken { token, destination, amount, fee } }) => - Ok(Self::convert_send_token(message_id, chain_id, token, destination, amount, fee)), + V1(MessageV1 { chain_id, command: RegisterToken { token, fee } }) => { + Ok(Self::convert_register_token(message_id, chain_id, token, fee)) + }, + V1(MessageV1 { chain_id, command: SendToken { token, destination, amount, fee } }) => { + Ok(Self::convert_send_token(message_id, chain_id, token, destination, amount, fee)) + }, V1(MessageV1 { chain_id, command: SendNativeToken { token_id, destination, amount, fee }, @@ -309,8 +311,9 @@ where let (dest_para_id, beneficiary, dest_para_fee) = match destination { // Final destination is a 32-byte account on AssetHub - Destination::AccountId32 { id } => - (None, Location::new(0, [AccountId32 { network: None, id }]), 0), + Destination::AccountId32 { id } => { + (None, Location::new(0, [AccountId32 { network: None, id }]), 0) + }, // Final destination is a 32-byte account on a sibling of AssetHub Destination::ForeignAccountId32 { para_id, id, fee } => ( Some(para_id), @@ -416,8 +419,9 @@ where let beneficiary = match destination { // Final destination is a 32-byte account on AssetHub - Destination::AccountId32 { id } => - Ok(Location::new(0, [AccountId32 { network: None, id }])), + Destination::AccountId32 { id } => { + Ok(Location::new(0, [AccountId32 { network: None, id }])) + }, // Forwarding to a destination teyrchain is not allowed for PNA and is validated on the // Ethereum side. https://github.com/Snowfork/snowbridge/blob/e87ddb2215b513455c844463a25323bb9c01ff36/contracts/src/Assets.sol#L216-L224 _ => Err(ConvertMessageError::InvalidDestination), diff --git a/pezbridges/snowbridge/primitives/outbound-queue/src/v1/converter/mod.rs b/pezbridges/snowbridge/primitives/outbound-queue/src/v1/converter/mod.rs index 26fe906d..cc840f16 100644 --- a/pezbridges/snowbridge/primitives/outbound-queue/src/v1/converter/mod.rs +++ b/pezbridges/snowbridge/primitives/outbound-queue/src/v1/converter/mod.rs @@ -290,8 +290,9 @@ where Asset { id: AssetId(inner_location), fun: Fungible(amount) } => { match inner_location.unpack() { // Get the ERC20 contract address of the token. - (0, [AccountKey20 { network, key }]) if self.network_matches(network) => - Some((H160(*key), *amount)), + (0, [AccountKey20 { network, key }]) if self.network_matches(network) => { + Some((H160(*key), *amount)) + }, // If there is no ERC20 contract address in the location then signal to the // gateway that is a native Ether transfer by using // `0x0000000000000000000000000000000000000000` as the token address. @@ -403,8 +404,9 @@ where } let (asset_id, amount) = match reserve_asset { - Asset { id: AssetId(inner_location), fun: Fungible(amount) } => - Some((inner_location.clone(), *amount)), + Asset { id: AssetId(inner_location), fun: Fungible(amount) } => { + Some((inner_location.clone(), *amount)) + }, _ => None, } .ok_or(AssetResolutionFailed)?; diff --git a/pezbridges/snowbridge/primitives/outbound-queue/src/v1/message.rs b/pezbridges/snowbridge/primitives/outbound-queue/src/v1/message.rs index 4e2992bf..10e1826e 100644 --- a/pezbridges/snowbridge/primitives/outbound-queue/src/v1/message.rs +++ b/pezbridges/snowbridge/primitives/outbound-queue/src/v1/message.rs @@ -152,14 +152,16 @@ impl Command { Token::FixedBytes(agent_id.as_bytes().to_owned()), Token::Bytes(command.abi_encode()), ])]), - Command::Upgrade { impl_address, impl_code_hash, initializer, .. } => + Command::Upgrade { impl_address, impl_code_hash, initializer, .. } => { ethabi::encode(&[Token::Tuple(vec![ Token::Address(*impl_address), Token::FixedBytes(impl_code_hash.as_bytes().to_owned()), initializer.clone().map_or(Token::Bytes(vec![]), |i| Token::Bytes(i.params)), - ])]), - Command::SetOperatingMode { mode } => - ethabi::encode(&[Token::Tuple(vec![Token::Uint(U256::from((*mode) as u64))])]), + ])]) + }, + Command::SetOperatingMode { mode } => { + ethabi::encode(&[Token::Tuple(vec![Token::Uint(U256::from((*mode) as u64))])]) + }, Command::SetTokenTransferFees { create_asset_xcm, transfer_asset_xcm, @@ -169,32 +171,36 @@ impl Command { Token::Uint(U256::from(*transfer_asset_xcm)), Token::Uint(*register_token), ])]), - Command::SetPricingParameters { exchange_rate, delivery_cost, multiplier } => + Command::SetPricingParameters { exchange_rate, delivery_cost, multiplier } => { ethabi::encode(&[Token::Tuple(vec![ Token::Uint(exchange_rate.clone().into_inner()), Token::Uint(U256::from(*delivery_cost)), Token::Uint(multiplier.clone().into_inner()), - ])]), - Command::UnlockNativeToken { agent_id, token, recipient, amount } => + ])]) + }, + Command::UnlockNativeToken { agent_id, token, recipient, amount } => { ethabi::encode(&[Token::Tuple(vec![ Token::FixedBytes(agent_id.as_bytes().to_owned()), Token::Address(*token), Token::Address(*recipient), Token::Uint(U256::from(*amount)), - ])]), - Command::RegisterForeignToken { token_id, name, symbol, decimals } => + ])]) + }, + Command::RegisterForeignToken { token_id, name, symbol, decimals } => { ethabi::encode(&[Token::Tuple(vec![ Token::FixedBytes(token_id.as_bytes().to_owned()), Token::String(name.to_owned()), Token::String(symbol.to_owned()), Token::Uint(U256::from(*decimals)), - ])]), - Command::MintForeignToken { token_id, recipient, amount } => + ])]) + }, + Command::MintForeignToken { token_id, recipient, amount } => { ethabi::encode(&[Token::Tuple(vec![ Token::FixedBytes(token_id.as_bytes().to_owned()), Token::Address(*recipient), Token::Uint(U256::from(*amount)), - ])]), + ])]) + }, } } } diff --git a/pezbridges/snowbridge/primitives/outbound-queue/src/v2/converter/convert.rs b/pezbridges/snowbridge/primitives/outbound-queue/src/v2/converter/convert.rs index dd195403..458530d3 100644 --- a/pezbridges/snowbridge/primitives/outbound-queue/src/v2/converter/convert.rs +++ b/pezbridges/snowbridge/primitives/outbound-queue/src/v2/converter/convert.rs @@ -133,8 +133,9 @@ where let (token, amount) = match ena { Asset { id: AssetId(inner_location), fun: Fungible(amount) } => { match inner_location.unpack() { - (0, [AccountKey20 { network, key }]) if self.network_matches(network) => - Ok((H160(*key), amount)), + (0, [AccountKey20 { network, key }]) if self.network_matches(network) => { + Ok((H160(*key), amount)) + }, // To allow ether (0, []) => Ok((H160([0; 20]), amount)), _ => Err(AssetResolutionFailed), diff --git a/pezbridges/snowbridge/primitives/outbound-queue/src/v2/message.rs b/pezbridges/snowbridge/primitives/outbound-queue/src/v2/message.rs index af9d10e8..1e25fd9b 100644 --- a/pezbridges/snowbridge/primitives/outbound-queue/src/v2/message.rs +++ b/pezbridges/snowbridge/primitives/outbound-queue/src/v2/message.rs @@ -214,23 +214,26 @@ impl Command { initParams: Bytes::from(initializer.params.clone()), } .abi_encode(), - Command::SetOperatingMode { mode } => - SetOperatingModeParams { mode: (*mode) as u8 }.abi_encode(), - Command::UnlockNativeToken { token, recipient, amount, .. } => + Command::SetOperatingMode { mode } => { + SetOperatingModeParams { mode: (*mode) as u8 }.abi_encode() + }, + Command::UnlockNativeToken { token, recipient, amount, .. } => { UnlockNativeTokenParams { token: Address::from(token.as_fixed_bytes()), recipient: Address::from(recipient.as_fixed_bytes()), amount: *amount, } - .abi_encode(), - Command::RegisterForeignToken { token_id, name, symbol, decimals } => + .abi_encode() + }, + Command::RegisterForeignToken { token_id, name, symbol, decimals } => { RegisterForeignTokenParams { foreignTokenID: FixedBytes::from(token_id.as_fixed_bytes()), name: Bytes::from(name.to_vec()), symbol: Bytes::from(symbol.to_vec()), decimals: *decimals, } - .abi_encode(), + .abi_encode() + }, Command::MintForeignToken { token_id, recipient, amount } => MintForeignTokenParams { foreignTokenID: FixedBytes::from(token_id.as_fixed_bytes()), recipient: Address::from(recipient.as_fixed_bytes()), diff --git a/pezcumulus/client/bootnodes/src/advertisement.rs b/pezcumulus/client/bootnodes/src/advertisement.rs index 690fc9a5..fc6cee3a 100644 --- a/pezcumulus/client/bootnodes/src/advertisement.rs +++ b/pezcumulus/client/bootnodes/src/advertisement.rs @@ -441,7 +441,7 @@ impl BootnodeAdvertisement { fn handle_dht_event(&mut self, event: DhtEvent) { match event { - DhtEvent::StartedProviding(key) => + DhtEvent::StartedProviding(key) => { if Some(&key) == self.current_epoch_key.as_ref() { debug!( target: LOG_TARGET, @@ -454,7 +454,8 @@ impl BootnodeAdvertisement { "Successfully published provider for next epoch key {}", hex::encode(key.as_ref()), ); - }, + } + }, DhtEvent::StartProvidingFailed(key) => { if Some(&key) == self.current_epoch_key.as_ref() { debug!( diff --git a/pezcumulus/client/bootnodes/src/discovery.rs b/pezcumulus/client/bootnodes/src/discovery.rs index 5cbd4779..dbcb0555 100644 --- a/pezcumulus/client/bootnodes/src/discovery.rs +++ b/pezcumulus/client/bootnodes/src/discovery.rs @@ -180,9 +180,9 @@ impl BootnodeDiscovery { /// Schedule bootnode discovery if needed. Returns `false` if the discovery event loop should be /// terminated. fn maybe_retry_discovery(&mut self) -> bool { - let discovery_in_progress = self.key_being_discovered.is_some() || - !self.pending_responses.is_empty() || - !self.find_node_queries.is_empty(); + let discovery_in_progress = self.key_being_discovered.is_some() + || !self.pending_responses.is_empty() + || !self.find_node_queries.is_empty(); let discovery_scheduled = !self.pending_start_discovery.is_terminated(); if discovery_in_progress || discovery_scheduled { @@ -310,8 +310,8 @@ impl BootnodeDiscovery { match (response.genesis_hash, response.fork_id) { (genesis_hash, fork_id) - if genesis_hash == self.teyrchain_genesis_hash && - fork_id == self.teyrchain_fork_id => {}, + if genesis_hash == self.teyrchain_genesis_hash + && fork_id == self.teyrchain_fork_id => {}, (genesis_hash, fork_id) => { warn!( target: LOG_TARGET, diff --git a/pezcumulus/client/consensus/aura/src/collator.rs b/pezcumulus/client/consensus/aura/src/collator.rs index fc88776d..623780b0 100644 --- a/pezcumulus/client/consensus/aura/src/collator.rs +++ b/pezcumulus/client/consensus/aura/src/collator.rs @@ -148,10 +148,11 @@ where let paras_inherent_data = match paras_inherent_data { Some(p) => p, - None => + None => { return Err( format!("Could not create paras inherent data at {:?}", relay_parent).into() - ), + ) + }, }; let mut other_inherent_data = self diff --git a/pezcumulus/client/consensus/aura/src/collators/basic.rs b/pezcumulus/client/consensus/aura/src/collators/basic.rs index b02091ca..8968f275 100644 --- a/pezcumulus/client/consensus/aura/src/collators/basic.rs +++ b/pezcumulus/client/consensus/aura/src/collators/basic.rs @@ -118,13 +118,14 @@ where async move { let mut collation_requests = match params.collation_request_receiver { Some(receiver) => receiver, - None => + None => { pezcumulus_client_collator::relay_chain_driven::init( params.collator_key, params.para_id, params.overseer_handle, ) - .await, + .await + }, }; let mut collator = { @@ -225,8 +226,8 @@ where // // With https://github.com/pezkuwichain/pezkuwi-sdk/issues/127 this implementation will be // obsolete and also the underlying issue will be fixed. - if last_processed_slot >= *claim.slot() && - last_relay_chain_block < *relay_parent_header.number() + if last_processed_slot >= *claim.slot() + && last_relay_chain_block < *relay_parent_header.number() { continue; } diff --git a/pezcumulus/client/consensus/aura/src/collators/mod.rs b/pezcumulus/client/consensus/aura/src/collators/mod.rs index dcb4265e..53a3a23d 100644 --- a/pezcumulus/client/consensus/aura/src/collators/mod.rs +++ b/pezcumulus/client/consensus/aura/src/collators/mod.rs @@ -138,7 +138,7 @@ async fn check_validation_code_or_log( }; match state_validation_code_hash { - Some(state) => + Some(state) => { if state != *local_validation_code_hash { tracing::warn!( target: super::LOG_TARGET, @@ -148,7 +148,8 @@ async fn check_validation_code_or_log( relay_validation_code_hash = ?state, "Teyrchain code doesn't match validation code stored in the relay chain state.", ); - }, + } + }, None => { tracing::warn!( target: super::LOG_TARGET, @@ -183,8 +184,8 @@ async fn scheduling_lookahead( ) .unwrap_or_default(); - if teyrchain_host_runtime_api_version < - RuntimeApiRequest::SCHEDULING_LOOKAHEAD_RUNTIME_REQUIREMENT + if teyrchain_host_runtime_api_version + < RuntimeApiRequest::SCHEDULING_LOOKAHEAD_RUNTIME_REQUIREMENT { return None; } diff --git a/pezcumulus/client/consensus/aura/src/collators/slot_based/block_builder_task.rs b/pezcumulus/client/consensus/aura/src/collators/slot_based/block_builder_task.rs index bd0d1028..13cc3eef 100644 --- a/pezcumulus/client/consensus/aura/src/collators/slot_based/block_builder_task.rs +++ b/pezcumulus/client/consensus/aura/src/collators/slot_based/block_builder_task.rs @@ -607,10 +607,11 @@ pub(crate) async fn determine_core last_relay_parent != relay_parent.hash(), - None => + None => { rpsr_digest::extract_relay_parent_storage_root(para_parent.digest()) .ok_or(())? - .0 != *relay_parent.state_root(), + .0 != *relay_parent.state_root() + }, } }; diff --git a/pezcumulus/client/consensus/aura/src/collators/slot_based/slot_timer.rs b/pezcumulus/client/consensus/aura/src/collators/slot_based/slot_timer.rs index c3f80043..5bf72ae7 100644 --- a/pezcumulus/client/consensus/aura/src/collators/slot_based/slot_timer.rs +++ b/pezcumulus/client/consensus/aura/src/collators/slot_based/slot_timer.rs @@ -101,8 +101,8 @@ fn compute_next_wake_up_time( // we should still produce two blocks if we are scheduled on every relay block. let mut block_production_interval = min(para_slot_duration.as_duration(), relay_slot_duration); - if assigned_core_num > para_slots_per_relay_block && - para_slot_duration.as_duration() >= relay_slot_duration + if assigned_core_num > para_slots_per_relay_block + && para_slot_duration.as_duration() >= relay_slot_duration { block_production_interval = max(relay_slot_duration / assigned_core_num, BLOCK_PRODUCTION_MINIMUM_INTERVAL_MS); @@ -204,8 +204,8 @@ fn adjust_authoring_duration( // without issues. // - Block 11: next slot change in 0.993s - skipped by the deadline // - Block 12: next slot change in 0.493s - skipped by the deadline - if authoring_duration < - BLOCK_PRODUCTION_MINIMUM_INTERVAL_MS.saturating_sub(BLOCK_PRODUCTION_THRESHOLD_MS) + if authoring_duration + < BLOCK_PRODUCTION_MINIMUM_INTERVAL_MS.saturating_sub(BLOCK_PRODUCTION_THRESHOLD_MS) { tracing::debug!( target: LOG_TARGET, @@ -233,9 +233,9 @@ fn time_until_next_attempt( ) -> (Duration, Timestamp) { let now = now.as_millis().saturating_sub(offset.as_millis()); - let next_slot_time = ((now + block_production_interval.as_millis()) / - block_production_interval.as_millis()) * - block_production_interval.as_millis(); + let next_slot_time = ((now + block_production_interval.as_millis()) + / block_production_interval.as_millis()) + * block_production_interval.as_millis(); let remaining_millis = next_slot_time - now; (Duration::from_millis(remaining_millis as u64), Timestamp::from(next_slot_time as u64)) } diff --git a/pezcumulus/client/consensus/aura/src/equivocation_import_queue.rs b/pezcumulus/client/consensus/aura/src/equivocation_import_queue.rs index a6baa859..5169229a 100644 --- a/pezcumulus/client/consensus/aura/src/equivocation_import_queue.rs +++ b/pezcumulus/client/consensus/aura/src/equivocation_import_queue.rs @@ -177,8 +177,8 @@ where let relay_parent = match CumulusDigestItem::find_relay_block_identifier(pre_header.digest()) { None => Default::default(), - Some(RelayBlockIdentifier::ByHash(h)) | - Some(RelayBlockIdentifier::ByStorageRoot { + Some(RelayBlockIdentifier::ByHash(h)) + | Some(RelayBlockIdentifier::ByStorageRoot { storage_root: h, .. }) => h, }; @@ -219,11 +219,12 @@ where post_hash, slot )); }, - Err(e) => + Err(e) => { return Err(format!( "Rejecting block ({:?}) with invalid seal ({:?})", post_hash, e - )), + )) + }, } } diff --git a/pezcumulus/client/consensus/common/src/parent_search.rs b/pezcumulus/client/consensus/common/src/parent_search.rs index 56310506..8510ad7a 100644 --- a/pezcumulus/client/consensus/common/src/parent_search.rs +++ b/pezcumulus/client/consensus/common/src/parent_search.rs @@ -396,9 +396,9 @@ pub fn search_child_branches_for_parents( for child in backend.blockchain().children(hash).ok().into_iter().flatten() { tracing::trace!(target: PARENT_SEARCH_LOG_TARGET, ?child, child_depth, ?pending_distance, "Looking at child."); - let aligned_with_pending = parent_aligned_with_pending && - (pending_distance.map_or(true, |dist| child_depth > dist) || - is_child_pending(child)); + let aligned_with_pending = parent_aligned_with_pending + && (pending_distance.map_or(true, |dist| child_depth > dist) + || is_child_pending(child)); if ignore_alternative_branches && !aligned_with_pending { tracing::trace!(target: PARENT_SEARCH_LOG_TARGET, ?child, "Child is not aligned with pending block."); diff --git a/pezcumulus/client/network/src/lib.rs b/pezcumulus/client/network/src/lib.rs index 4c4393f2..1af3d646 100644 --- a/pezcumulus/client/network/src/lib.rs +++ b/pezcumulus/client/network/src/lib.rs @@ -290,8 +290,8 @@ where // If the relay chain runtime does not support the new runtime API, fallback to the // deprecated one. - let candidate_receipts = if teyrchain_host_runtime_api_version < - RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT + let candidate_receipts = if teyrchain_host_runtime_api_version + < RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT { #[allow(deprecated)] relay_chain_interface @@ -389,11 +389,12 @@ where let block_announce_data = match BlockAnnounceData::decode_all(&mut data.as_slice()) { Ok(r) => r, - Err(err) => + Err(err) => { return Err(Box::new(BlockAnnounceError(format!( "Can not decode the `BlockAnnounceData`: {:?}", err - ))) as Box<_>), + ))) as Box<_>) + }, }; if let Err(e) = block_announce_data.validate(header_encoded) { diff --git a/pezcumulus/client/network/src/tests.rs b/pezcumulus/client/network/src/tests.rs index a431e962..c886207e 100644 --- a/pezcumulus/client/network/src/tests.rs +++ b/pezcumulus/client/network/src/tests.rs @@ -166,8 +166,8 @@ impl RelayChainInterface for DummyRelayChainInterface { _: PHash, _: ParaId, ) -> RelayChainResult> { - if self.data.lock().runtime_version >= - RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT + if self.data.lock().runtime_version + >= RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT { panic!("Should have used candidates_pending_availability instead"); } @@ -184,8 +184,8 @@ impl RelayChainInterface for DummyRelayChainInterface { _: PHash, _: ParaId, ) -> RelayChainResult> { - if self.data.lock().runtime_version < - RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT + if self.data.lock().runtime_version + < RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT { panic!("Should have used candidate_pending_availability instead"); } @@ -289,12 +289,13 @@ impl RelayChainInterface for DummyRelayChainInterface { async fn header(&self, block_id: BlockId) -> RelayChainResult> { let hash = match block_id { BlockId::Hash(hash) => hash, - BlockId::Number(num) => + BlockId::Number(num) => { if let Some(hash) = self.relay_client.hash(num)? { hash } else { return Ok(None); - }, + } + }, }; let header = self.relay_client.header(hash)?; diff --git a/pezcumulus/client/pov-recovery/src/lib.rs b/pezcumulus/client/pov-recovery/src/lib.rs index 05c43519..47e69330 100644 --- a/pezcumulus/client/pov-recovery/src/lib.rs +++ b/pezcumulus/client/pov-recovery/src/lib.rs @@ -390,7 +390,7 @@ where self.candidates_in_retry.remove(&block_hash); pov }, - None => + None => { if self.candidates_in_retry.insert(block_hash) { tracing::debug!(target: LOG_TARGET, ?block_hash, "Recovery failed, retrying."); self.candidate_recovery_queue.push_recovery(block_hash); @@ -404,7 +404,8 @@ where self.candidates_in_retry.remove(&block_hash); self.reset_candidate(block_hash); return; - }, + } + }, }; let raw_block_data = diff --git a/pezcumulus/client/pov-recovery/src/tests.rs b/pezcumulus/client/pov-recovery/src/tests.rs index db7dab6c..8be8b316 100644 --- a/pezcumulus/client/pov-recovery/src/tests.rs +++ b/pezcumulus/client/pov-recovery/src/tests.rs @@ -390,8 +390,8 @@ impl RelayChainInterface for Relaychain { hash: PHash, _: ParaId, ) -> RelayChainResult> { - if self.inner.lock().expect("Poisoned lock").runtime_version >= - RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT + if self.inner.lock().expect("Poisoned lock").runtime_version + >= RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT { panic!("Should have used candidates_pending_availability instead"); } @@ -413,8 +413,8 @@ impl RelayChainInterface for Relaychain { hash: PHash, _: ParaId, ) -> RelayChainResult> { - if self.inner.lock().expect("Poisoned lock").runtime_version < - RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT + if self.inner.lock().expect("Poisoned lock").runtime_version + < RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT { panic!("Should have used candidate_pending_availability instead"); } diff --git a/pezcumulus/client/relay-chain-inprocess-interface/src/lib.rs b/pezcumulus/client/relay-chain-inprocess-interface/src/lib.rs index cbdfc90e..5f2711b1 100644 --- a/pezcumulus/client/relay-chain-inprocess-interface/src/lib.rs +++ b/pezcumulus/client/relay-chain-inprocess-interface/src/lib.rs @@ -109,12 +109,13 @@ impl RelayChainInterface for RelayChainInProcessInterface { async fn header(&self, block_id: BlockId) -> RelayChainResult> { let hash = match block_id { BlockId::Hash(hash) => hash, - BlockId::Number(num) => + BlockId::Number(num) => { if let Some(hash) = self.full_client.hash(num)? { hash } else { return Ok(None); - }, + } + }, }; let header = self.full_client.header(hash)?; diff --git a/pezcumulus/client/relay-chain-minimal-node/src/lib.rs b/pezcumulus/client/relay-chain-minimal-node/src/lib.rs index 805cbbf7..6873e37d 100644 --- a/pezcumulus/client/relay-chain-minimal-node/src/lib.rs +++ b/pezcumulus/client/relay-chain-minimal-node/src/lib.rs @@ -109,19 +109,21 @@ async fn build_interface( let blockchain_rpc_client = Arc::new(BlockChainRpcClient::new(client.clone())); let collator_node = match pezkuwi_config.network.network_backend { - pezsc_network::config::NetworkBackendType::Libp2p => + pezsc_network::config::NetworkBackendType::Libp2p => { new_minimal_relay_chain::< RelayBlock, pezsc_network::NetworkWorker, >(pezkuwi_config, collator_pair.clone(), blockchain_rpc_client) - .await?, - pezsc_network::config::NetworkBackendType::Litep2p => + .await? + }, + pezsc_network::config::NetworkBackendType::Litep2p => { new_minimal_relay_chain::( pezkuwi_config, collator_pair.clone(), blockchain_rpc_client, ) - .await?, + .await? + }, }; task_manager.add_child(collator_node.task_manager); Ok(( diff --git a/pezcumulus/client/relay-chain-minimal-node/src/network.rs b/pezcumulus/client/relay-chain-minimal-node/src/network.rs index 49bf3e81..732e3584 100644 --- a/pezcumulus/client/relay-chain-minimal-node/src/network.rs +++ b/pezcumulus/client/relay-chain-minimal-node/src/network.rs @@ -110,8 +110,8 @@ pub(crate) fn build_collator_network>( } fn adjust_network_config_light_in_peers(config: &mut NetworkConfiguration) { - let light_client_in_peers = (config.default_peers_set.in_peers + - config.default_peers_set.out_peers) + let light_client_in_peers = (config.default_peers_set.in_peers + + config.default_peers_set.out_peers) .saturating_sub(config.default_peers_set_num_full); if light_client_in_peers > 0 { tracing::debug!(target: crate::LOG_TARGET, "Detected {light_client_in_peers} peer slots for light clients. Since this minimal node does support\ diff --git a/pezcumulus/client/relay-chain-rpc-interface/src/reconnecting_ws_client.rs b/pezcumulus/client/relay-chain-rpc-interface/src/reconnecting_ws_client.rs index a6279142..50e05d8e 100644 --- a/pezcumulus/client/relay-chain-rpc-interface/src/reconnecting_ws_client.rs +++ b/pezcumulus/client/relay-chain-rpc-interface/src/reconnecting_ws_client.rs @@ -125,8 +125,8 @@ async fn connect_next_available_rpc_server( if current_iteration > prev_iteration { // Safe conversion given we convert positive i32s which are lower than u64::MAX. tokio::time::sleep(Duration::from_millis( - DEFAULT_SLEEP_TIME_MS_BETWEEN_RETRIES * - DEFAULT_SLEEP_EXP_BACKOFF_BETWEEN_RETRIES.pow(prev_iteration) as u64, + DEFAULT_SLEEP_TIME_MS_BETWEEN_RETRIES + * DEFAULT_SLEEP_EXP_BACKOFF_BETWEEN_RETRIES.pow(prev_iteration) as u64, )) .await; prev_iteration = current_iteration; diff --git a/pezcumulus/client/relay-chain-streams/src/lib.rs b/pezcumulus/client/relay-chain-streams/src/lib.rs index 06c850e1..f53bd65e 100644 --- a/pezcumulus/client/relay-chain-streams/src/lib.rs +++ b/pezcumulus/client/relay-chain-streams/src/lib.rs @@ -78,8 +78,8 @@ pub async fn pending_candidates( // If the relay chain runtime does not support the new runtime API, fallback to the // deprecated one. - let pending_availability_result = if teyrchain_host_runtime_api_version < - RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT + let pending_availability_result = if teyrchain_host_runtime_api_version + < RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT { #[allow(deprecated)] client diff --git a/pezcumulus/client/service/src/lib.rs b/pezcumulus/client/service/src/lib.rs index f579d078..4df5ae54 100644 --- a/pezcumulus/client/service/src/lib.rs +++ b/pezcumulus/client/service/src/lib.rs @@ -244,14 +244,15 @@ pub async fn build_relay_chain_interface( task_manager, hwbench, ), - pezcumulus_client_cli::RelayChainMode::ExternalRpc(rpc_target_urls) => + pezcumulus_client_cli::RelayChainMode::ExternalRpc(rpc_target_urls) => { build_minimal_relay_chain_node_with_rpc( relay_chain_config, teyrchain_config.prometheus_registry(), task_manager, rpc_target_urls, ) - .await, + .await + }, } } diff --git a/pezcumulus/pezkuwi-omni-node/lib/src/command.rs b/pezcumulus/pezkuwi-omni-node/lib/src/command.rs index d13867b7..0f3e58b1 100644 --- a/pezcumulus/pezkuwi-omni-node/lib/src/command.rs +++ b/pezcumulus/pezkuwi-omni-node/lib/src/command.rs @@ -88,10 +88,12 @@ fn new_node_spec( Ok(match runtime { Runtime::Omni(block_number, consensus) => match (block_number, consensus) { - (BlockNumber::U32, Consensus::Aura(aura_id)) => - new_aura_node_spec::>(aura_id, extra_args), - (BlockNumber::U64, Consensus::Aura(aura_id)) => - new_aura_node_spec::>(aura_id, extra_args), + (BlockNumber::U32, Consensus::Aura(aura_id)) => { + new_aura_node_spec::>(aura_id, extra_args) + }, + (BlockNumber::U64, Consensus::Aura(aura_id)) => { + new_aura_node_spec::>(aura_id, extra_args) + }, }, }) } @@ -188,8 +190,9 @@ where node.prepare_revert_cmd(config, cmd) }) }, - Some(Subcommand::ChainSpecBuilder(cmd)) => - cmd.run().map_err(|err| pezsc_cli::Error::Application(err.into())), + Some(Subcommand::ChainSpecBuilder(cmd)) => { + cmd.run().map_err(|err| pezsc_cli::Error::Application(err.into())) + }, Some(Subcommand::PurgeChain(cmd)) => { let runner = cli.create_runner(cmd)?; diff --git a/pezcumulus/pezkuwi-omni-node/lib/src/common/runtime.rs b/pezcumulus/pezkuwi-omni-node/lib/src/common/runtime.rs index 7f2d5439..4365c4fd 100644 --- a/pezcumulus/pezkuwi-omni-node/lib/src/common/runtime.rs +++ b/pezcumulus/pezkuwi-omni-node/lib/src/common/runtime.rs @@ -18,12 +18,12 @@ use codec::Decode; use pezcumulus_client_service::TeyrchainHostFunctions; +use pezkuwi_subxt_metadata::Metadata; use pezsc_chain_spec::ChainSpec; use pezsc_executor::WasmExecutor; use pezsc_runtime_utilities::fetch_latest_metadata_from_code_blob; use scale_info::{form::PortableForm, TypeDef, TypeDefPrimitive}; use std::fmt::Display; -use pezkuwi_subxt_metadata::Metadata; /// Expected teyrchain system pezpallet runtime type name. pub const DEFAULT_TEYRCHAIN_SYSTEM_PALLET_NAME: &str = "TeyrchainSystem"; diff --git a/pezcumulus/pezkuwi-omni-node/lib/src/common/spec.rs b/pezcumulus/pezkuwi-omni-node/lib/src/common/spec.rs index 207260df..94c64468 100644 --- a/pezcumulus/pezkuwi-omni-node/lib/src/common/spec.rs +++ b/pezcumulus/pezkuwi-omni-node/lib/src/common/spec.rs @@ -613,22 +613,24 @@ where node_extra_args: NodeExtraArgs, ) -> Pin>>> { match teyrchain_config.network.network_backend { - pezsc_network::config::NetworkBackendType::Libp2p => + pezsc_network::config::NetworkBackendType::Libp2p => { ::start_node::>( teyrchain_config, pezkuwi_config, collator_options, hwbench, node_extra_args, - ), - pezsc_network::config::NetworkBackendType::Litep2p => + ) + }, + pezsc_network::config::NetworkBackendType::Litep2p => { ::start_node::( teyrchain_config, pezkuwi_config, collator_options, hwbench, node_extra_args, - ), + ) + }, } } } diff --git a/pezcumulus/pezkuwi-teyrchain/src/chain_spec/bridge_hubs.rs b/pezcumulus/pezkuwi-teyrchain/src/chain_spec/bridge_hubs.rs index 23fb069c..201fdde2 100644 --- a/pezcumulus/pezkuwi-teyrchain/src/chain_spec/bridge_hubs.rs +++ b/pezcumulus/pezkuwi-teyrchain/src/chain_spec/bridge_hubs.rs @@ -51,10 +51,12 @@ impl FromStr for BridgeHubRuntimeType { zagros::BRIDGE_HUB_ZAGROS_LOCAL => Ok(BridgeHubRuntimeType::ZagrosLocal), zagros::BRIDGE_HUB_ZAGROS_DEVELOPMENT => Ok(BridgeHubRuntimeType::ZagrosDevelopment), pezkuwichain::BRIDGE_HUB_PEZKUWICHAIN => Ok(BridgeHubRuntimeType::Pezkuwichain), - pezkuwichain::BRIDGE_HUB_PEZKUWICHAIN_LOCAL => - Ok(BridgeHubRuntimeType::PezkuwichainLocal), - pezkuwichain::BRIDGE_HUB_PEZKUWICHAIN_DEVELOPMENT => - Ok(BridgeHubRuntimeType::PezkuwichainDevelopment), + pezkuwichain::BRIDGE_HUB_PEZKUWICHAIN_LOCAL => { + Ok(BridgeHubRuntimeType::PezkuwichainLocal) + }, + pezkuwichain::BRIDGE_HUB_PEZKUWICHAIN_DEVELOPMENT => { + Ok(BridgeHubRuntimeType::PezkuwichainDevelopment) + }, _ => Err(format!("Value '{}' is not configured yet", value)), } } @@ -96,14 +98,15 @@ impl BridgeHubRuntimeType { |_| (), ChainType::Local, ))), - BridgeHubRuntimeType::PezkuwichainDevelopment => + BridgeHubRuntimeType::PezkuwichainDevelopment => { Ok(Box::new(pezkuwichain::local_config( pezkuwichain::BRIDGE_HUB_PEZKUWICHAIN_DEVELOPMENT, "Pezkuwichain BridgeHub Development", "pezkuwichain-dev", |_| (), ChainType::Development, - ))), + ))) + }, other => Err(std::format!("No default config present for {:?}", other)), } } diff --git a/pezcumulus/pezkuwi-teyrchain/src/chain_spec/coretime.rs b/pezcumulus/pezkuwi-teyrchain/src/chain_spec/coretime.rs index 9c81b3ef..f4d9999b 100644 --- a/pezcumulus/pezkuwi-teyrchain/src/chain_spec/coretime.rs +++ b/pezcumulus/pezkuwi-teyrchain/src/chain_spec/coretime.rs @@ -53,8 +53,9 @@ impl FromStr for CoretimeRuntimeType { pezkuwi::CORETIME_PEZKUWI_LOCAL => Ok(CoretimeRuntimeType::PezkuwiLocal), pezkuwichain::CORETIME_PEZKUWICHAIN => Ok(CoretimeRuntimeType::Pezkuwichain), pezkuwichain::CORETIME_PEZKUWICHAIN_LOCAL => Ok(CoretimeRuntimeType::PezkuwichainLocal), - pezkuwichain::CORETIME_PEZKUWICHAIN_DEVELOPMENT => - Ok(CoretimeRuntimeType::PezkuwichainDevelopment), + pezkuwichain::CORETIME_PEZKUWICHAIN_DEVELOPMENT => { + Ok(CoretimeRuntimeType::PezkuwichainDevelopment) + }, zagros::CORETIME_ZAGROS => Ok(CoretimeRuntimeType::Zagros), zagros::CORETIME_ZAGROS_LOCAL => Ok(CoretimeRuntimeType::ZagrosLocal), zagros::CORETIME_ZAGROS_DEVELOPMENT => Ok(CoretimeRuntimeType::ZagrosDevelopment), @@ -72,8 +73,9 @@ impl From for &str { CoretimeRuntimeType::PezkuwiLocal => pezkuwi::CORETIME_PEZKUWI_LOCAL, CoretimeRuntimeType::Pezkuwichain => pezkuwichain::CORETIME_PEZKUWICHAIN, CoretimeRuntimeType::PezkuwichainLocal => pezkuwichain::CORETIME_PEZKUWICHAIN_LOCAL, - CoretimeRuntimeType::PezkuwichainDevelopment => - pezkuwichain::CORETIME_PEZKUWICHAIN_DEVELOPMENT, + CoretimeRuntimeType::PezkuwichainDevelopment => { + pezkuwichain::CORETIME_PEZKUWICHAIN_DEVELOPMENT + }, CoretimeRuntimeType::Zagros => zagros::CORETIME_ZAGROS, CoretimeRuntimeType::ZagrosLocal => zagros::CORETIME_ZAGROS_LOCAL, CoretimeRuntimeType::ZagrosDevelopment => zagros::CORETIME_ZAGROS_DEVELOPMENT, @@ -84,16 +86,16 @@ impl From for &str { impl From for ChainType { fn from(runtime_type: CoretimeRuntimeType) -> Self { match runtime_type { - CoretimeRuntimeType::Kusama | - CoretimeRuntimeType::Pezkuwi | - CoretimeRuntimeType::Pezkuwichain | - CoretimeRuntimeType::Zagros => ChainType::Live, - CoretimeRuntimeType::KusamaLocal | - CoretimeRuntimeType::PezkuwiLocal | - CoretimeRuntimeType::PezkuwichainLocal | - CoretimeRuntimeType::ZagrosLocal => ChainType::Local, - CoretimeRuntimeType::PezkuwichainDevelopment | - CoretimeRuntimeType::ZagrosDevelopment => ChainType::Development, + CoretimeRuntimeType::Kusama + | CoretimeRuntimeType::Pezkuwi + | CoretimeRuntimeType::Pezkuwichain + | CoretimeRuntimeType::Zagros => ChainType::Live, + CoretimeRuntimeType::KusamaLocal + | CoretimeRuntimeType::PezkuwiLocal + | CoretimeRuntimeType::PezkuwichainLocal + | CoretimeRuntimeType::ZagrosLocal => ChainType::Local, + CoretimeRuntimeType::PezkuwichainDevelopment + | CoretimeRuntimeType::ZagrosDevelopment => ChainType::Development, } } } @@ -112,17 +114,21 @@ impl CoretimeRuntimeType { CoretimeRuntimeType::Pezkuwichain => Ok(Box::new(GenericChainSpec::from_json_bytes( &include_bytes!("../../chain-specs/coretime-pezkuwichain.json")[..], )?)), - CoretimeRuntimeType::PezkuwichainLocal => - Ok(Box::new(pezkuwichain::local_config(*self, "pezkuwichain-local"))), - CoretimeRuntimeType::PezkuwichainDevelopment => - Ok(Box::new(pezkuwichain::local_config(*self, "pezkuwichain-dev"))), + CoretimeRuntimeType::PezkuwichainLocal => { + Ok(Box::new(pezkuwichain::local_config(*self, "pezkuwichain-local"))) + }, + CoretimeRuntimeType::PezkuwichainDevelopment => { + Ok(Box::new(pezkuwichain::local_config(*self, "pezkuwichain-dev"))) + }, CoretimeRuntimeType::Zagros => Ok(Box::new(GenericChainSpec::from_json_bytes( &include_bytes!("../../../teyrchains/chain-specs/coretime-zagros.json")[..], )?)), - CoretimeRuntimeType::ZagrosLocal => - Ok(Box::new(zagros::local_config(*self, "zagros-local"))), - CoretimeRuntimeType::ZagrosDevelopment => - Ok(Box::new(zagros::local_config(*self, "zagros-dev"))), + CoretimeRuntimeType::ZagrosLocal => { + Ok(Box::new(zagros::local_config(*self, "zagros-local"))) + }, + CoretimeRuntimeType::ZagrosDevelopment => { + Ok(Box::new(zagros::local_config(*self, "zagros-dev"))) + }, other => Err(std::format!( "No default config present for {:?}, you should provide a chain-spec as json file!", other diff --git a/pezcumulus/pezkuwi-teyrchain/src/chain_spec/mod.rs b/pezcumulus/pezkuwi-teyrchain/src/chain_spec/mod.rs index 282c72ee..099bc8f0 100644 --- a/pezcumulus/pezkuwi-teyrchain/src/chain_spec/mod.rs +++ b/pezcumulus/pezkuwi-teyrchain/src/chain_spec/mod.rs @@ -58,8 +58,9 @@ impl LoadSpec for ChainSpecLoader { fn load_spec(&self, id: &str) -> Result, String> { Ok(match id { // - Default-like - "staging" => - Box::new(pezkuwichain_teyrchain::pezstaging_pezkuwichain_teyrchain_local_config()), + "staging" => { + Box::new(pezkuwichain_teyrchain::pezstaging_pezkuwichain_teyrchain_local_config()) + }, "tick" => Box::new(GenericChainSpec::from_json_bytes( &include_bytes!("../../chain-specs/tick.json")[..], )?), @@ -81,25 +82,31 @@ impl LoadSpec for ChainSpecLoader { )?), // -- Asset Hub Pezkuwichain - "asset-hub-pezkuwichain-dev" => - Box::new(asset_hubs::asset_hub_pezkuwichain_development_config()), - "asset-hub-pezkuwichain-local" => - Box::new(asset_hubs::asset_hub_pezkuwichain_local_config()), + "asset-hub-pezkuwichain-dev" => { + Box::new(asset_hubs::asset_hub_pezkuwichain_development_config()) + }, + "asset-hub-pezkuwichain-local" => { + Box::new(asset_hubs::asset_hub_pezkuwichain_local_config()) + }, // the chain spec as used for generating the upgrade genesis values - "asset-hub-pezkuwichain-genesis" => - Box::new(asset_hubs::asset_hub_pezkuwichain_genesis_config()), + "asset-hub-pezkuwichain-genesis" => { + Box::new(asset_hubs::asset_hub_pezkuwichain_genesis_config()) + }, "asset-hub-pezkuwichain" => Box::new(GenericChainSpec::from_json_bytes( &include_bytes!("../../chain-specs/asset-hub-pezkuwichain.json")[..], )?), // -- Asset Hub Zagros - "asset-hub-zagros-dev" | "westmint-dev" => - Box::new(asset_hubs::asset_hub_zagros_development_config()), - "asset-hub-zagros-local" | "westmint-local" => - Box::new(asset_hubs::asset_hub_zagros_local_config()), + "asset-hub-zagros-dev" | "westmint-dev" => { + Box::new(asset_hubs::asset_hub_zagros_development_config()) + }, + "asset-hub-zagros-local" | "westmint-local" => { + Box::new(asset_hubs::asset_hub_zagros_local_config()) + }, // the chain spec as used for generating the upgrade genesis values - "asset-hub-zagros-genesis" | "westmint-genesis" => - Box::new(asset_hubs::asset_hub_zagros_config()), + "asset-hub-zagros-genesis" | "westmint-genesis" => { + Box::new(asset_hubs::asset_hub_zagros_config()) + }, // the shell-based chain spec as used for syncing "asset-hub-zagros" | "westmint" => Box::new(GenericChainSpec::from_json_bytes( &include_bytes!("../../chain-specs/asset-hub-zagros.json")[..], @@ -111,8 +118,9 @@ impl LoadSpec for ChainSpecLoader { )?), // -- Zagros Collectives - "collectives-zagros-dev" => - Box::new(collectives::collectives_zagros_development_config()), + "collectives-zagros-dev" => { + Box::new(collectives::collectives_zagros_development_config()) + }, "collectives-zagros-local" => Box::new(collectives::collectives_zagros_local_config()), "collectives-zagros" => Box::new(GenericChainSpec::from_json_bytes( &include_bytes!("../../chain-specs/collectives-zagros.json")[..], @@ -121,18 +129,22 @@ impl LoadSpec for ChainSpecLoader { // -- BridgeHub bridge_like_id if bridge_like_id.starts_with(bridge_hubs::BridgeHubRuntimeType::ID_PREFIX) => + { bridge_like_id .parse::() .expect("invalid value") - .load_config()?, + .load_config()? + }, // -- Coretime coretime_like_id if coretime_like_id.starts_with(coretime::CoretimeRuntimeType::ID_PREFIX) => + { coretime_like_id .parse::() .expect("invalid value") - .load_config()?, + .load_config()? + }, // -- Penpal id if id.starts_with("penpal-pezkuwichain") => { @@ -197,11 +209,12 @@ impl LoadSpec for ChainSpecLoader { }, // -- People - people_like_id if people_like_id.starts_with(people::PeopleRuntimeType::ID_PREFIX) => + people_like_id if people_like_id.starts_with(people::PeopleRuntimeType::ID_PREFIX) => { people_like_id .parse::() .expect("invalid value") - .load_config()?, + .load_config()? + }, // -- Fallback (generic chainspec) "" => { @@ -236,12 +249,12 @@ impl LegacyRuntime { if id.starts_with("asset-hub-pezkuwi") | id.starts_with("statemint") { LegacyRuntime::AssetHubPezkuwi - } else if id.starts_with("asset-hub-kusama") | - id.starts_with("statemine") | - id.starts_with("asset-hub-pezkuwichain") | - id.starts_with("rockmine") | - id.starts_with("asset-hub-zagros") | - id.starts_with("westmint") + } else if id.starts_with("asset-hub-kusama") + | id.starts_with("statemine") + | id.starts_with("asset-hub-pezkuwichain") + | id.starts_with("rockmine") + | id.starts_with("asset-hub-zagros") + | id.starts_with("westmint") { LegacyRuntime::AssetHub } else if id.starts_with("penpal") { @@ -278,17 +291,19 @@ impl RuntimeResolverT for RuntimeResolver { fn runtime(&self, chain_spec: &dyn ChainSpec) -> pezsc_cli::Result { let legacy_runtime = LegacyRuntime::from_id(chain_spec.id()); Ok(match legacy_runtime { - LegacyRuntime::AssetHubPezkuwi => - Runtime::Omni(BlockNumber::U32, Consensus::Aura(AuraConsensusId::Ed25519)), - LegacyRuntime::AssetHub | - LegacyRuntime::BridgeHub(_) | - LegacyRuntime::Collectives | - LegacyRuntime::Coretime(_) | - LegacyRuntime::People(_) | - LegacyRuntime::Glutton | - LegacyRuntime::Penpal | - LegacyRuntime::Omni => - Runtime::Omni(BlockNumber::U32, Consensus::Aura(AuraConsensusId::Sr25519)), + LegacyRuntime::AssetHubPezkuwi => { + Runtime::Omni(BlockNumber::U32, Consensus::Aura(AuraConsensusId::Ed25519)) + }, + LegacyRuntime::AssetHub + | LegacyRuntime::BridgeHub(_) + | LegacyRuntime::Collectives + | LegacyRuntime::Coretime(_) + | LegacyRuntime::People(_) + | LegacyRuntime::Glutton + | LegacyRuntime::Penpal + | LegacyRuntime::Omni => { + Runtime::Omni(BlockNumber::U32, Consensus::Aura(AuraConsensusId::Sr25519)) + }, }) } } diff --git a/pezcumulus/pezkuwi-teyrchain/src/chain_spec/people.rs b/pezcumulus/pezkuwi-teyrchain/src/chain_spec/people.rs index d11a20b4..df4ab019 100644 --- a/pezcumulus/pezkuwi-teyrchain/src/chain_spec/people.rs +++ b/pezcumulus/pezkuwi-teyrchain/src/chain_spec/people.rs @@ -44,8 +44,9 @@ impl FromStr for PeopleRuntimeType { pezkuwi::PEOPLE_PEZKUWI_LOCAL => Ok(PeopleRuntimeType::PezkuwiLocal), pezkuwichain::PEOPLE_PEZKUWICHAIN => Ok(PeopleRuntimeType::Pezkuwichain), pezkuwichain::PEOPLE_PEZKUWICHAIN_LOCAL => Ok(PeopleRuntimeType::PezkuwichainLocal), - pezkuwichain::PEOPLE_PEZKUWICHAIN_DEVELOPMENT => - Ok(PeopleRuntimeType::PezkuwichainDevelopment), + pezkuwichain::PEOPLE_PEZKUWICHAIN_DEVELOPMENT => { + Ok(PeopleRuntimeType::PezkuwichainDevelopment) + }, zagros::PEOPLE_ZAGROS => Ok(PeopleRuntimeType::Zagros), zagros::PEOPLE_ZAGROS_LOCAL => Ok(PeopleRuntimeType::ZagrosLocal), zagros::PEOPLE_ZAGROS_DEVELOPMENT => Ok(PeopleRuntimeType::ZagrosDevelopment), diff --git a/pezcumulus/pezpallets/collator-selection/src/benchmarking.rs b/pezcumulus/pezpallets/collator-selection/src/benchmarking.rs index 978d878a..53046978 100644 --- a/pezcumulus/pezpallets/collator-selection/src/benchmarking.rs +++ b/pezcumulus/pezpallets/collator-selection/src/benchmarking.rs @@ -274,8 +274,8 @@ mod benchmarks { let caller = CandidateList::::get()[0].who.clone(); v2::whitelist!(caller); - let bond_amount: BalanceOf = ::Currency::minimum_balance() + - ::Currency::minimum_balance(); + let bond_amount: BalanceOf = ::Currency::minimum_balance() + + ::Currency::minimum_balance(); #[extrinsic_call] _(RawOrigin::Signed(caller.clone()), bond_amount); @@ -284,8 +284,8 @@ mod benchmarks { Event::CandidateBondUpdated { account_id: caller, deposit: bond_amount }.into(), ); assert!( - CandidateList::::get().iter().last().unwrap().deposit == - ::Currency::minimum_balance() * 2u32.into() + CandidateList::::get().iter().last().unwrap().deposit + == ::Currency::minimum_balance() * 2u32.into() ); Ok(()) } diff --git a/pezcumulus/pezpallets/collator-selection/src/lib.rs b/pezcumulus/pezpallets/collator-selection/src/lib.rs index a0e7d21d..83e6bae8 100644 --- a/pezcumulus/pezpallets/collator-selection/src/lib.rs +++ b/pezcumulus/pezpallets/collator-selection/src/lib.rs @@ -352,8 +352,8 @@ pub mod pezpallet { fn integrity_test() { assert!(T::MinEligibleCollators::get() > 0, "chain must require at least one collator"); assert!( - T::MaxInvulnerables::get().saturating_add(T::MaxCandidates::get()) >= - T::MinEligibleCollators::get(), + T::MaxInvulnerables::get().saturating_add(T::MaxCandidates::get()) + >= T::MinEligibleCollators::get(), "invulnerables and candidates must be able to satisfy collator demand" ); } @@ -388,8 +388,8 @@ pub mod pezpallet { if new.is_empty() { // Casting `u32` to `usize` should be safe on all machines running this. ensure!( - CandidateList::::decode_len().unwrap_or_default() >= - T::MinEligibleCollators::get() as usize, + CandidateList::::decode_len().unwrap_or_default() + >= T::MinEligibleCollators::get() as usize, Error::::TooFewEligibleCollators ); } @@ -696,8 +696,8 @@ pub mod pezpallet { } else if new_deposit < old_deposit { // Casting `u32` to `usize` should be safe on all machines running this. ensure!( - idx.saturating_add(DesiredCandidates::::get() as usize) < - candidate_count, + idx.saturating_add(DesiredCandidates::::get() as usize) + < candidate_count, Error::::InvalidUnreserve ); T::Currency::unreserve(&who, old_deposit - new_deposit); diff --git a/pezcumulus/pezpallets/teyrchain-system/proc-macro/src/lib.rs b/pezcumulus/pezpallets/teyrchain-system/proc-macro/src/lib.rs index af4025b1..6917161b 100644 --- a/pezcumulus/pezpallets/teyrchain-system/proc-macro/src/lib.rs +++ b/pezcumulus/pezpallets/teyrchain-system/proc-macro/src/lib.rs @@ -80,8 +80,9 @@ impl Parse for Input { fn crate_() -> Result { match crate_name("pezcumulus-pezpallet-teyrchain-system") { - Ok(FoundCrate::Itself) => - Ok(syn::Ident::new("pezcumulus_pezpallet_teyrchain_system", Span::call_site())), + Ok(FoundCrate::Itself) => { + Ok(syn::Ident::new("pezcumulus_pezpallet_teyrchain_system", Span::call_site())) + }, Ok(FoundCrate::Name(name)) => Ok(Ident::new(&name, Span::call_site())), Err(e) => Err(Error::new(Span::call_site(), e)), } diff --git a/pezcumulus/pezpallets/teyrchain-system/src/lib.rs b/pezcumulus/pezpallets/teyrchain-system/src/lib.rs index 86a734eb..5a0a87ed 100644 --- a/pezcumulus/pezpallets/teyrchain-system/src/lib.rs +++ b/pezcumulus/pezpallets/teyrchain-system/src/lib.rs @@ -1705,7 +1705,7 @@ impl UpwardMessageSender for Pezpallet { const MAX_CODE_SIZE: u32 = 3 * 1024 * 1024; HostConfiguration::::mutate(|cfg| match cfg { Some(cfg) => cfg.max_upward_message_size = MAX_UPWARD_MESSAGE_SIZE, - None => + None => { *cfg = Some(AbridgedHostConfiguration { max_code_size: MAX_CODE_SIZE, max_head_data_size: 32 * 1024, @@ -1720,7 +1720,8 @@ impl UpwardMessageSender for Pezpallet { allowed_ancestry_len: 0, max_candidate_depth: 0, }, - }), + }) + }, }) } } diff --git a/pezcumulus/pezpallets/teyrchain-system/src/mock.rs b/pezcumulus/pezpallets/teyrchain-system/src/mock.rs index 5502e05c..bf562a1c 100644 --- a/pezcumulus/pezpallets/teyrchain-system/src/mock.rs +++ b/pezcumulus/pezpallets/teyrchain-system/src/mock.rs @@ -166,10 +166,10 @@ impl XcmpMessageSource for FromThreadLocal { let msg_len = m.1.len(); - if !ids.contains(&m.0) && - taken_messages < maximum_channels && - msg_len <= max_size_ever && - taken_bytes + msg_len <= max_size_now + if !ids.contains(&m.0) + && taken_messages < maximum_channels + && msg_len <= max_size_ever + && taken_bytes + msg_len <= max_size_now { ids.insert(m.0); taken_messages += 1; diff --git a/pezcumulus/pezpallets/teyrchain-system/src/validate_block/trie_recorder.rs b/pezcumulus/pezpallets/teyrchain-system/src/validate_block/trie_recorder.rs index a875cd0f..3772c723 100644 --- a/pezcumulus/pezpallets/teyrchain-system/src/validate_block/trie_recorder.rs +++ b/pezcumulus/pezpallets/teyrchain-system/src/validate_block/trie_recorder.rs @@ -43,15 +43,17 @@ impl<'a, H: trie_db::Hasher> trie_db::TrieRecorder for SizeOnlyRecorder< fn record(&mut self, access: TrieAccess<'_, H::Out>) { let mut encoded_size_update = 0; match access { - TrieAccess::NodeOwned { hash, node_owned } => + TrieAccess::NodeOwned { hash, node_owned } => { if self.seen_nodes.insert(hash) { let node = node_owned.to_encoded::>(); encoded_size_update += node.encoded_size(); - }, - TrieAccess::EncodedNode { hash, encoded_node } => + } + }, + TrieAccess::EncodedNode { hash, encoded_node } => { if self.seen_nodes.insert(hash) { encoded_size_update += encoded_node.encoded_size(); - }, + } + }, TrieAccess::Value { hash, value, full_key } => { if self.seen_nodes.insert(hash) { encoded_size_update += value.encoded_size(); diff --git a/pezcumulus/pezpallets/weight-reclaim/src/tests.rs b/pezcumulus/pezpallets/weight-reclaim/src/tests.rs index 65cc6baa..cbb007f4 100644 --- a/pezcumulus/pezpallets/weight-reclaim/src/tests.rs +++ b/pezcumulus/pezpallets/weight-reclaim/src/tests.rs @@ -584,8 +584,8 @@ fn test_series() { block_weight_pre_dispatch: Weight::from_parts(1000, 1000), mock_ext_refund: Weight::from_parts(0, 0), assert_post_info_weight: None, - assert_block_weight_post_dispatch: base_extrinsic + - Weight::from_parts(1100, 1300 + LEN as u64), + assert_block_weight_post_dispatch: base_extrinsic + + Weight::from_parts(1100, 1300 + LEN as u64), }, // some tx ext refund is ignored, because post info is None. TestCfg { @@ -597,8 +597,8 @@ fn test_series() { block_weight_pre_dispatch: Weight::from_parts(1000, 1000), mock_ext_refund: Weight::from_parts(20, 20), assert_post_info_weight: None, - assert_block_weight_post_dispatch: base_extrinsic + - Weight::from_parts(1100, 1300 + LEN as u64), + assert_block_weight_post_dispatch: base_extrinsic + + Weight::from_parts(1100, 1300 + LEN as u64), }, // some tx ext refund is ignored on proof size because lower than actual measure. TestCfg { @@ -610,8 +610,8 @@ fn test_series() { block_weight_pre_dispatch: Weight::from_parts(1000, 1000), mock_ext_refund: Weight::from_parts(20, 20), assert_post_info_weight: Some(Weight::from_parts(80, 300)), - assert_block_weight_post_dispatch: base_extrinsic + - Weight::from_parts(1080, 1300 + LEN as u64), + assert_block_weight_post_dispatch: base_extrinsic + + Weight::from_parts(1080, 1300 + LEN as u64), }, // post info doesn't double refund the call and is missing some. TestCfg { @@ -624,8 +624,8 @@ fn test_series() { mock_ext_refund: Weight::from_parts(20, 20), // 50 are missed in pov because 100 is unspent in post info but it should be only 50. assert_post_info_weight: Some(Weight::from_parts(40, 200)), - assert_block_weight_post_dispatch: base_extrinsic + - Weight::from_parts(1040, 1250 + LEN as u64), + assert_block_weight_post_dispatch: base_extrinsic + + Weight::from_parts(1040, 1250 + LEN as u64), }, // post info doesn't double refund the call and is accurate. TestCfg { @@ -637,8 +637,8 @@ fn test_series() { block_weight_pre_dispatch: Weight::from_parts(1000, 1000), mock_ext_refund: Weight::from_parts(20, 20), assert_post_info_weight: Some(Weight::from_parts(40, 150)), - assert_block_weight_post_dispatch: base_extrinsic + - Weight::from_parts(1040, 1150 + LEN as u64), + assert_block_weight_post_dispatch: base_extrinsic + + Weight::from_parts(1040, 1150 + LEN as u64), }, // post info doesn't double refund the call and is accurate. Even if mock ext is refunding // too much. @@ -651,8 +651,8 @@ fn test_series() { block_weight_pre_dispatch: Weight::from_parts(1000, 1000), mock_ext_refund: Weight::from_parts(20, 300), assert_post_info_weight: Some(Weight::from_parts(40, 150)), - assert_block_weight_post_dispatch: base_extrinsic + - Weight::from_parts(1040, 1150 + LEN as u64), + assert_block_weight_post_dispatch: base_extrinsic + + Weight::from_parts(1040, 1150 + LEN as u64), }, ]; @@ -1034,11 +1034,11 @@ fn test_ref_time_weight_reclaim() { pezframe_system::BlockWeight::::get() .get(DispatchClass::Normal) .ref_time(), - block_pre_dispatch + - base_extrinsic.ref_time() + - bench_post_dispatch_actual + - bench_mock_ext_weight - - bench_mock_ext_refund, + block_pre_dispatch + + base_extrinsic.ref_time() + + bench_post_dispatch_actual + + bench_mock_ext_weight + - bench_mock_ext_refund, ); assert_eq!( pezframe_system::ExtrinsicWeightReclaimed::::get().ref_time(), diff --git a/pezcumulus/pezpallets/xcmp-queue/src/lib.rs b/pezcumulus/pezpallets/xcmp-queue/src/lib.rs index 552ce397..3af8fb87 100644 --- a/pezcumulus/pezpallets/xcmp-queue/src/lib.rs +++ b/pezcumulus/pezpallets/xcmp-queue/src/lib.rs @@ -442,9 +442,9 @@ impl QueueConfigData { /// /// Should be called prior to accepting this as new config. pub fn validate(&self) -> pezsp_runtime::DispatchResult { - if self.resume_threshold < self.suspend_threshold && - self.suspend_threshold <= self.drop_threshold && - self.resume_threshold > 0 + if self.resume_threshold < self.suspend_threshold + && self.suspend_threshold <= self.drop_threshold + && self.resume_threshold > 0 { Ok(()) } else { @@ -946,8 +946,8 @@ impl XcmpMessageHandler for Pezpallet { } } }, - XcmpMessageFormat::ConcatenatedVersionedXcm | - XcmpMessageFormat::ConcatenatedOpaqueVersionedXcm => { + XcmpMessageFormat::ConcatenatedVersionedXcm + | XcmpMessageFormat::ConcatenatedOpaqueVersionedXcm => { let encoding = match format { XcmpMessageFormat::ConcatenatedVersionedXcm => XcmEncoding::Simple, XcmpMessageFormat::ConcatenatedOpaqueVersionedXcm => XcmEncoding::Double, @@ -1223,10 +1223,12 @@ impl InspectMessageQueues for Pezpallet { let mut decoded_messages = Vec::new(); while !data.is_empty() { let message_bytes = match decoded_format { - XcmpMessageFormat::ConcatenatedVersionedXcm => - Self::take_first_concatenated_xcm(data, &mut WeightMeter::new()), - XcmpMessageFormat::ConcatenatedOpaqueVersionedXcm => - Self::take_first_concatenated_opaque_xcm(data), + XcmpMessageFormat::ConcatenatedVersionedXcm => { + Self::take_first_concatenated_xcm(data, &mut WeightMeter::new()) + }, + XcmpMessageFormat::ConcatenatedOpaqueVersionedXcm => { + Self::take_first_concatenated_opaque_xcm(data) + }, unexpected_format => { panic!("Unexpected XCMP format: {unexpected_format:?}!") }, diff --git a/pezcumulus/pezpallets/xcmp-queue/src/migration.rs b/pezcumulus/pezpallets/xcmp-queue/src/migration.rs index d5d823b0..29fd05c6 100644 --- a/pezcumulus/pezpallets/xcmp-queue/src/migration.rs +++ b/pezcumulus/pezpallets/xcmp-queue/src/migration.rs @@ -279,9 +279,9 @@ pub mod v4 { let pre_default = v2::QueueConfigData::default(); // If the previous values are the default ones, let's replace them with the new // default. - if pre.suspend_threshold == pre_default.suspend_threshold && - pre.drop_threshold == pre_default.drop_threshold && - pre.resume_threshold == pre_default.resume_threshold + if pre.suspend_threshold == pre_default.suspend_threshold + && pre.drop_threshold == pre_default.drop_threshold + && pre.resume_threshold == pre_default.resume_threshold { return QueueConfigData::default(); } diff --git a/pezcumulus/pezpallets/xcmp-queue/src/mock.rs b/pezcumulus/pezpallets/xcmp-queue/src/mock.rs index 96028cd8..812e6b19 100644 --- a/pezcumulus/pezpallets/xcmp-queue/src/mock.rs +++ b/pezcumulus/pezpallets/xcmp-queue/src/mock.rs @@ -126,8 +126,8 @@ impl ConvertOrigin kind: OriginKind, ) -> Result { let origin = origin.into(); - if kind == OriginKind::Superuser && - matches!( + if kind == OriginKind::Superuser + && matches!( origin.unpack(), (1, [Teyrchain(id)]) if ParaId::from(*id).is_system(), ) { diff --git a/pezcumulus/primitives/core/src/lib.rs b/pezcumulus/primitives/core/src/lib.rs index ac000f32..e67cf8a4 100644 --- a/pezcumulus/primitives/core/src/lib.rs +++ b/pezcumulus/primitives/core/src/lib.rs @@ -353,11 +353,12 @@ impl CumulusDigestItem { /// well-behaving runtimes should not produce headers with more than one. pub fn extract_relay_parent(digest: &Digest) -> Option { digest.convert_first(|d| match d { - DigestItem::Consensus(id, val) if id == &CUMULUS_CONSENSUS_ID => + DigestItem::Consensus(id, val) if id == &CUMULUS_CONSENSUS_ID => { match CumulusDigestItem::decode(&mut &val[..]) { Ok(CumulusDigestItem::RelayParent(hash)) => Some(hash), _ => None, - }, + } + }, _ => None, }) } diff --git a/pezcumulus/primitives/timestamp/src/lib.rs b/pezcumulus/primitives/timestamp/src/lib.rs index 6381afbe..d105a366 100644 --- a/pezcumulus/primitives/timestamp/src/lib.rs +++ b/pezcumulus/primitives/timestamp/src/lib.rs @@ -61,8 +61,8 @@ impl InherentDataProvider { pub fn provide_inherent_data(&self, inherent_data: &mut InherentData) -> Result<(), Error> { // As the teyrchain starts building at around `relay_chain_slot + 1` we use that slot to // calculate the timestamp. - let data: InherentType = ((*self.relay_chain_slot + 1) * - self.relay_chain_slot_duration.as_millis() as u64) + let data: InherentType = ((*self.relay_chain_slot + 1) + * self.relay_chain_slot_duration.as_millis() as u64) .into(); inherent_data.put_data(INHERENT_IDENTIFIER, &data) diff --git a/pezcumulus/primitives/utility/src/tests/swap_first.rs b/pezcumulus/primitives/utility/src/tests/swap_first.rs index b97fe8e5..5b62558e 100644 --- a/pezcumulus/primitives/utility/src/tests/swap_first.rs +++ b/pezcumulus/primitives/utility/src/tests/swap_first.rs @@ -538,12 +538,14 @@ pub mod mock { a: &Asset, ) -> core::result::Result<(AssetId, Balance), xcm_executor::traits::Error> { match a { - Asset { fun: Fungible(amount), id: AssetId(inner_location) } => + Asset { fun: Fungible(amount), id: AssetId(inner_location) } => { match inner_location.unpack() { - (0, [Junction::GeneralIndex(id)]) => - Ok(((*id).try_into().unwrap(), *amount)), + (0, [Junction::GeneralIndex(id)]) => { + Ok(((*id).try_into().unwrap(), *amount)) + }, _ => Err(xcm_executor::traits::Error::AssetNotHandled), - }, + } + }, _ => Err(xcm_executor::traits::Error::AssetNotHandled), } } diff --git a/pezcumulus/test/runtime/src/genesis_config_presets.rs b/pezcumulus/test/runtime/src/genesis_config_presets.rs index 1c6b1a78..0a887e8a 100644 --- a/pezcumulus/test/runtime/src/genesis_config_presets.rs +++ b/pezcumulus/test/runtime/src/genesis_config_presets.rs @@ -59,9 +59,10 @@ pub fn preset_names() -> Vec { /// Provides the JSON representation of predefined genesis config for given `id`. pub fn get_preset(id: &PresetId) -> Option> { let patch = match id.as_ref() { - pezsp_genesis_builder::DEV_RUNTIME_PRESET | - pezsp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET => - testnet_genesis_with_default_endowed(100.into()), + pezsp_genesis_builder::DEV_RUNTIME_PRESET + | pezsp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET => { + testnet_genesis_with_default_endowed(100.into()) + }, _ => return None, }; Some( diff --git a/pezcumulus/test/service/src/cli.rs b/pezcumulus/test/service/src/cli.rs index 87a9736f..01d5b368 100644 --- a/pezcumulus/test/service/src/cli.rs +++ b/pezcumulus/test/service/src/cli.rs @@ -328,10 +328,11 @@ impl BizinikiwiCli for TestCollatorCli { 2500, )))) as Box<_> }, - "relay-parent-offset" => + "relay-parent-offset" => { Box::new(pezcumulus_test_service::get_relay_parent_offset_chain_spec(Some( ParaId::from(2600), - ))) as Box<_>, + ))) as Box<_> + }, path => { let chain_spec: pezsc_chain_spec::GenericChainSpec = pezsc_chain_spec::GenericChainSpec::from_json_file(path.into())?; diff --git a/pezcumulus/test/service/src/lib.rs b/pezcumulus/test/service/src/lib.rs index f4822996..3a2ef611 100644 --- a/pezcumulus/test/service/src/lib.rs +++ b/pezcumulus/test/service/src/lib.rs @@ -273,7 +273,7 @@ async fn build_relay_chain_interface( Some("Relaychain"), ) .map_err(|e| RelayChainError::Application(Box::new(e) as Box<_>))?, - pezcumulus_client_cli::RelayChainMode::ExternalRpc(rpc_target_urls) => + pezcumulus_client_cli::RelayChainMode::ExternalRpc(rpc_target_urls) => { return build_minimal_relay_chain_node_with_rpc( relay_chain_config, teyrchain_prometheus_registry, @@ -281,7 +281,8 @@ async fn build_relay_chain_interface( rpc_target_urls, ) .await - .map(|r| r.0), + .map(|r| r.0) + }, }; task_manager.add_child(relay_chain_node.task_manager); @@ -716,7 +717,7 @@ impl TestNodeBuilder { let (task_manager, client, network, rpc_handlers, transaction_pool, backend) = match relay_chain_config.network.network_backend { - pezsc_network::config::NetworkBackendType::Libp2p => + pezsc_network::config::NetworkBackendType::Libp2p => { start_node_impl::<_, pezsc_network::NetworkWorker<_, _>>( teyrchain_config, self.collator_key, @@ -729,8 +730,9 @@ impl TestNodeBuilder { false, ) .await - .expect("could not create Pezcumulus test service"), - pezsc_network::config::NetworkBackendType::Litep2p => + .expect("could not create Pezcumulus test service") + }, + pezsc_network::config::NetworkBackendType::Litep2p => { start_node_impl::<_, pezsc_network::Litep2pNetworkBackend>( teyrchain_config, self.collator_key, @@ -743,7 +745,8 @@ impl TestNodeBuilder { false, ) .await - .expect("could not create Pezcumulus test service"), + .expect("could not create Pezcumulus test service") + }, }; let peer_id = network.local_peer_id(); let multiaddr = pezkuwi_test_service::get_listen_address(network.clone()).await; diff --git a/pezcumulus/test/service/src/main.rs b/pezcumulus/test/service/src/main.rs index 8b9b41e9..df89d0e9 100644 --- a/pezcumulus/test/service/src/main.rs +++ b/pezcumulus/test/service/src/main.rs @@ -100,7 +100,7 @@ fn main() -> Result<(), pezsc_cli::Error> { let (mut task_manager, _, _, _, _, _) = tokio_runtime .block_on(async move { match relay_chain_config.network.network_backend { - pezsc_network::config::NetworkBackendType::Libp2p => + pezsc_network::config::NetworkBackendType::Libp2p => { pezcumulus_test_service::start_node_impl::< _, pezsc_network::NetworkWorker<_, _>, @@ -115,8 +115,9 @@ fn main() -> Result<(), pezsc_cli::Error> { true, use_slot_based_collator, ) - .await, - pezsc_network::config::NetworkBackendType::Litep2p => + .await + }, + pezsc_network::config::NetworkBackendType::Litep2p => { pezcumulus_test_service::start_node_impl::< _, pezsc_network::Litep2pNetworkBackend, @@ -131,7 +132,8 @@ fn main() -> Result<(), pezsc_cli::Error> { true, use_slot_based_collator, ) - .await, + .await + }, } }) .expect("could not create Pezcumulus test service"); diff --git a/pezcumulus/teyrchains/common/src/impls.rs b/pezcumulus/teyrchains/common/src/impls.rs index cd085724..23adb9c4 100644 --- a/pezcumulus/teyrchains/common/src/impls.rs +++ b/pezcumulus/teyrchains/common/src/impls.rs @@ -132,8 +132,8 @@ pub struct AssetsFrom(PhantomData); impl> ContainsPair for AssetsFrom { fn contains(asset: &Asset, origin: &Location) -> bool { let loc = T::get(); - &loc == origin && - matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) } + &loc == origin + && matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) } if asset_loc.match_and_split(&loc).is_some()) } } diff --git a/pezcumulus/teyrchains/common/src/pay.rs b/pezcumulus/teyrchains/common/src/pay.rs index 05981b5c..def27b9a 100644 --- a/pezcumulus/teyrchains/common/src/pay.rs +++ b/pezcumulus/teyrchains/common/src/pay.rs @@ -101,20 +101,24 @@ where fn match_location(who: &VersionedLocatableAccount) -> Result { // only applicable for the local accounts let account_id = match who { - VersionedLocatableAccount::V4 { location, account_id } if location.is_here() => - &account_id.clone().try_into().map_err(|_| ())?, - VersionedLocatableAccount::V5 { location, account_id } if location.is_here() => - account_id, + VersionedLocatableAccount::V4 { location, account_id } if location.is_here() => { + &account_id.clone().try_into().map_err(|_| ())? + }, + VersionedLocatableAccount::V5 { location, account_id } if location.is_here() => { + account_id + }, _ => return Err(()), }; C::convert_location(account_id).ok_or(()) } fn match_asset(asset: &VersionedLocatableAsset) -> Result { match asset { - VersionedLocatableAsset::V4 { location, asset_id } if location.is_here() => - asset_id.clone().try_into().map(|a: xcm::v5::AssetId| a.0).map_err(|_| ()), - VersionedLocatableAsset::V5 { location, asset_id } if location.is_here() => - Ok(asset_id.clone().0), + VersionedLocatableAsset::V4 { location, asset_id } if location.is_here() => { + asset_id.clone().try_into().map(|a: xcm::v5::AssetId| a.0).map_err(|_| ()) + }, + VersionedLocatableAsset::V5 { location, asset_id } if location.is_here() => { + Ok(asset_id.clone().0) + }, _ => Err(()), } } diff --git a/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/lib.rs b/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/lib.rs index 2320af56..6ce90f46 100644 --- a/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/lib.rs +++ b/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/lib.rs @@ -70,12 +70,8 @@ mod imports { LocalTeleportableToAssetHub as PenpalLocalTeleportableToAssetHub, UsdtFromAssetHub as PenpalUsdtFromAssetHub, }, - PenpalAParaPezpallet, - PenpalAParaPezpallet as PenpalAPallet, - PenpalAssetOwner, - PenpalBParaPezpallet, - PenpalBParaPezpallet as PenpalBPallet, - ED as PENPAL_ED, + PenpalAParaPezpallet, PenpalAParaPezpallet as PenpalAPallet, PenpalAssetOwner, + PenpalBParaPezpallet, PenpalBParaPezpallet as PenpalBPallet, ED as PENPAL_ED, }, pezkuwichain_emulated_chain::{ genesis::ED as PEZKUWICHAIN_ED, @@ -85,8 +81,7 @@ mod imports { xcm_config::UniversalLocation as PezkuwichainUniversalLocation, Dmp, OriginCaller as PezkuwichainOriginCaller, }, - PezkuwichainRelayPezpallet, - PezkuwichainRelayPezpallet as PezkuwichainPallet, + PezkuwichainRelayPezpallet, PezkuwichainRelayPezpallet as PezkuwichainPallet, }, AssetHubPezkuwichainPara as AssetHubPezkuwichain, AssetHubPezkuwichainParaReceiver as AssetHubPezkuwichainReceiver, diff --git a/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/tests/reserve_transfer.rs b/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/tests/reserve_transfer.rs index c7f6ec13..6f9d3869 100644 --- a/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/tests/reserve_transfer.rs +++ b/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/tests/reserve_transfer.rs @@ -1067,8 +1067,8 @@ fn reserve_transfer_multiple_assets_from_asset_hub_to_para() { // bought_execution`; `delivery_fees` might be paid from transfer or JIT, also // `bought_execution` is unknown but should be non-zero assert!( - receiver_system_native_assets_after < - receiver_system_native_assets_before + fee_amount_to_send + receiver_system_native_assets_after + < receiver_system_native_assets_before + fee_amount_to_send ); // Sender's asset balance is reduced by exact amount diff --git a/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/tests/treasury.rs b/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/tests/treasury.rs index 9a246aef..f19edbec 100644 --- a/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/tests/treasury.rs +++ b/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/tests/treasury.rs @@ -16,9 +16,7 @@ use crate::imports::*; use emulated_integration_tests_common::accounts::{ALICE, BOB}; use pezframe_support::{ - dispatch::RawOrigin, - pezsp_runtime::traits::Dispatchable, - traits::fungible::Inspect, + dispatch::RawOrigin, pezsp_runtime::traits::Dispatchable, traits::fungible::Inspect, }; use pezkuwi_runtime_common::impls::VersionedLocatableAsset; use pezkuwichain_runtime_constants::currency::GRAND; @@ -171,98 +169,105 @@ mod disabled_usdt_treasury_test { #[test] fn create_and_claim_treasury_spend_in_usdt() { - const SPEND_AMOUNT: u128 = 10_000_000; - // treasury location from a sibling teyrchain. - let treasury_location: Location = Location::new(1, PalletInstance(18)); - // treasury account on a sibling teyrchain. - let treasury_account = - ahr_xcm_config::LocationToAccountId::convert_location(&treasury_location).unwrap(); - let asset_hub_location = Location::new(0, Teyrchain(AssetHubPezkuwichain::para_id().into())); - let root = ::RuntimeOrigin::root(); - // asset kind to be spent from the treasury. - let asset_kind: VersionedLocatableAsset = - (asset_hub_location, AssetId((PalletInstance(50), GeneralIndex(USDT_ID.into())).into())) + const SPEND_AMOUNT: u128 = 10_000_000; + // treasury location from a sibling teyrchain. + let treasury_location: Location = Location::new(1, PalletInstance(18)); + // treasury account on a sibling teyrchain. + let treasury_account = + ahr_xcm_config::LocationToAccountId::convert_location(&treasury_location).unwrap(); + let asset_hub_location = + Location::new(0, Teyrchain(AssetHubPezkuwichain::para_id().into())); + let root = ::RuntimeOrigin::root(); + // asset kind to be spent from the treasury. + let asset_kind: VersionedLocatableAsset = ( + asset_hub_location, + AssetId((PalletInstance(50), GeneralIndex(USDT_ID.into())).into()), + ) .into(); - // treasury spend beneficiary. - let alice: AccountId = Pezkuwichain::account_id_of(ALICE); - let bob: AccountId = Pezkuwichain::account_id_of(BOB); - let bob_signed = ::RuntimeOrigin::signed(bob.clone()); + // treasury spend beneficiary. + let alice: AccountId = Pezkuwichain::account_id_of(ALICE); + let bob: AccountId = Pezkuwichain::account_id_of(BOB); + let bob_signed = ::RuntimeOrigin::signed(bob.clone()); - AssetHubPezkuwichain::execute_with(|| { - type Assets = ::Assets; + AssetHubPezkuwichain::execute_with(|| { + type Assets = ::Assets; - // USDT created at genesis, mint some assets to the treasury account. - assert_ok!(>::mint_into(USDT_ID, &treasury_account, SPEND_AMOUNT * 4)); - // beneficiary has zero balance. - assert_eq!(>::balance(USDT_ID, &alice,), 0u128,); - }); + // USDT created at genesis, mint some assets to the treasury account. + assert_ok!(>::mint_into( + USDT_ID, + &treasury_account, + SPEND_AMOUNT * 4 + )); + // beneficiary has zero balance. + assert_eq!(>::balance(USDT_ID, &alice,), 0u128,); + }); - Pezkuwichain::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - type Treasury = ::Treasury; - type AssetRate = ::AssetRate; + Pezkuwichain::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; + type Treasury = ::Treasury; + type AssetRate = ::AssetRate; - // create a conversion rate from `asset_kind` to the native currency. - assert_ok!(AssetRate::create(root.clone(), Box::new(asset_kind.clone()), 2.into())); + // create a conversion rate from `asset_kind` to the native currency. + assert_ok!(AssetRate::create(root.clone(), Box::new(asset_kind.clone()), 2.into())); - Dmp::make_teyrchain_reachable(1000); + Dmp::make_teyrchain_reachable(1000); - // create and approve a treasury spend. - assert_ok!(Treasury::spend( - root, - Box::new(asset_kind), - SPEND_AMOUNT, - Box::new(Location::new(0, Into::<[u8; 32]>::into(alice.clone())).into()), - None, - )); - // claim the spend. - assert_ok!(Treasury::payout(bob_signed.clone(), 0)); + // create and approve a treasury spend. + assert_ok!(Treasury::spend( + root, + Box::new(asset_kind), + SPEND_AMOUNT, + Box::new(Location::new(0, Into::<[u8; 32]>::into(alice.clone())).into()), + None, + )); + // claim the spend. + assert_ok!(Treasury::payout(bob_signed.clone(), 0)); - assert_expected_events!( - Pezkuwichain, - vec![ - RuntimeEvent::Treasury(pezpallet_treasury::Event::Paid { .. }) => {}, - ] - ); - }); + assert_expected_events!( + Pezkuwichain, + vec![ + RuntimeEvent::Treasury(pezpallet_treasury::Event::Paid { .. }) => {}, + ] + ); + }); - AssetHubPezkuwichain::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - type Assets = ::Assets; + AssetHubPezkuwichain::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; + type Assets = ::Assets; - // assert events triggered by xcm pay program - // 1. treasury asset transferred to spend beneficiary - // 2. response to Relay Chain treasury pezpallet instance sent back - // 3. XCM program completed - assert_expected_events!( - AssetHubPezkuwichain, - vec![ - RuntimeEvent::Assets(pezpallet_assets::Event::Transferred { asset_id: id, from, to, amount }) => { - id: id == &USDT_ID, - from: from == &treasury_account, - to: to == &alice, - amount: amount == &SPEND_AMOUNT, - }, - RuntimeEvent::TeyrchainSystem(pezcumulus_pezpallet_teyrchain_system::Event::UpwardMessageSent { .. }) => {}, - RuntimeEvent::MessageQueue(pezpallet_message_queue::Event::Processed { success: true ,.. }) => {}, - ] - ); - // beneficiary received the assets from the treasury. - assert_eq!(>::balance(USDT_ID, &alice,), SPEND_AMOUNT,); - }); + // assert events triggered by xcm pay program + // 1. treasury asset transferred to spend beneficiary + // 2. response to Relay Chain treasury pezpallet instance sent back + // 3. XCM program completed + assert_expected_events!( + AssetHubPezkuwichain, + vec![ + RuntimeEvent::Assets(pezpallet_assets::Event::Transferred { asset_id: id, from, to, amount }) => { + id: id == &USDT_ID, + from: from == &treasury_account, + to: to == &alice, + amount: amount == &SPEND_AMOUNT, + }, + RuntimeEvent::TeyrchainSystem(pezcumulus_pezpallet_teyrchain_system::Event::UpwardMessageSent { .. }) => {}, + RuntimeEvent::MessageQueue(pezpallet_message_queue::Event::Processed { success: true ,.. }) => {}, + ] + ); + // beneficiary received the assets from the treasury. + assert_eq!(>::balance(USDT_ID, &alice,), SPEND_AMOUNT,); + }); - Pezkuwichain::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - type Treasury = ::Treasury; + Pezkuwichain::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; + type Treasury = ::Treasury; - // check the payment status to ensure the response from the AssetHub was received. - assert_ok!(Treasury::check_status(bob_signed, 0)); - assert_expected_events!( - Pezkuwichain, - vec![ - RuntimeEvent::Treasury(pezpallet_treasury::Event::SpendProcessed { .. }) => {}, - ] - ); - }); + // check the payment status to ensure the response from the AssetHub was received. + assert_ok!(Treasury::check_status(bob_signed, 0)); + assert_expected_events!( + Pezkuwichain, + vec![ + RuntimeEvent::Treasury(pezpallet_treasury::Event::SpendProcessed { .. }) => {}, + ] + ); + }); } } diff --git a/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/tests/xcm_fee_estimation.rs b/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/tests/xcm_fee_estimation.rs index f2926f38..9ba896e8 100644 --- a/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/tests/xcm_fee_estimation.rs +++ b/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-pezkuwichain/src/tests/xcm_fee_estimation.rs @@ -279,10 +279,10 @@ fn multi_hop_works() { ); assert_eq!( receiver_assets_after, - receiver_assets_before + amount_to_send - - intermediate_execution_fees - - intermediate_delivery_fees_amount - - final_execution_fees + receiver_assets_before + amount_to_send + - intermediate_execution_fees + - intermediate_delivery_fees_amount + - final_execution_fees ); } diff --git a/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-zagros/src/lib.rs b/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-zagros/src/lib.rs index 151f34a2..caf0de1a 100644 --- a/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-zagros/src/lib.rs +++ b/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-zagros/src/lib.rs @@ -65,8 +65,7 @@ mod imports { ExistentialDeposit as AssetHubZagrosExistentialDeposit, ForeignAssetReserveData, }, genesis::{AssetHubZagrosAssetOwner, ED as ASSET_HUB_ZAGROS_ED}, - AssetHubZagrosParaPezpallet, - AssetHubZagrosParaPezpallet as AssetHubZagrosPallet, + AssetHubZagrosParaPezpallet, AssetHubZagrosParaPezpallet as AssetHubZagrosPallet, }, collectives_zagros_emulated_chain::{ CollectivesZagrosParaPezpallet, @@ -82,11 +81,8 @@ mod imports { UniversalLocation as PenpalUniversalLocation, UsdtFromAssetHub as PenpalUsdtFromAssetHub, }, - PenpalAParaPezpallet, - PenpalAParaPezpallet as PenpalAPallet, - PenpalAssetOwner, - PenpalBParaPezpallet, - PenpalBParaPezpallet as PenpalBPallet, + PenpalAParaPezpallet, PenpalAParaPezpallet as PenpalAPallet, PenpalAssetOwner, + PenpalBParaPezpallet, PenpalBParaPezpallet as PenpalBPallet, }, pezbridge_hub_zagros_emulated_chain::{ pezbridge_hub_zagros_runtime::xcm_config::{self as bhw_xcm_config}, @@ -101,8 +97,7 @@ mod imports { }, Dmp, }, - ZagrosRelayPezpallet, - ZagrosRelayPezpallet as ZagrosPallet, + ZagrosRelayPezpallet, ZagrosRelayPezpallet as ZagrosPallet, }, AssetHubZagrosPara as AssetHubZagros, AssetHubZagrosParaReceiver as AssetHubZagrosReceiver, AssetHubZagrosParaSender as AssetHubZagrosSender, BridgeHubZagrosPara as BridgeHubZagros, diff --git a/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-zagros/src/tests/reserve_transfer.rs b/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-zagros/src/tests/reserve_transfer.rs index 29427caa..951a7ac4 100644 --- a/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-zagros/src/tests/reserve_transfer.rs +++ b/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-zagros/src/tests/reserve_transfer.rs @@ -1039,8 +1039,8 @@ fn reserve_transfer_multiple_assets_from_asset_hub_to_para() { // bought_execution`; `delivery_fees` might be paid from transfer or JIT, also // `bought_execution` is unknown but should be non-zero assert!( - receiver_system_native_assets_after < - receiver_system_native_assets_before + fee_amount_to_send + receiver_system_native_assets_after + < receiver_system_native_assets_before + fee_amount_to_send ); // Sender's asset balance is reduced by exact amount diff --git a/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-zagros/src/tests/xcm_fee_estimation.rs b/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-zagros/src/tests/xcm_fee_estimation.rs index 0e21fd5d..ce9db841 100644 --- a/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-zagros/src/tests/xcm_fee_estimation.rs +++ b/pezcumulus/teyrchains/integration-tests/emulated/tests/assets/asset-hub-zagros/src/tests/xcm_fee_estimation.rs @@ -327,10 +327,10 @@ fn multi_hop_works() { ); assert_eq!( receiver_assets_after, - receiver_assets_before + amount_to_send - - intermediate_execution_fees - - intermediate_delivery_fees_amount - - final_execution_fees + receiver_assets_before + amount_to_send + - intermediate_execution_fees + - intermediate_delivery_fees_amount + - final_execution_fees ); } diff --git a/pezcumulus/teyrchains/integration-tests/emulated/tests/collectives/collectives-zagros/src/lib.rs b/pezcumulus/teyrchains/integration-tests/emulated/tests/collectives/collectives-zagros/src/lib.rs index 5b4e167a..c2a7e8a9 100644 --- a/pezcumulus/teyrchains/integration-tests/emulated/tests/collectives/collectives-zagros/src/lib.rs +++ b/pezcumulus/teyrchains/integration-tests/emulated/tests/collectives/collectives-zagros/src/lib.rs @@ -27,8 +27,7 @@ mod imports { pub(crate) use zagros_system_emulated_network::{ asset_hub_zagros_emulated_chain::{ asset_hub_zagros_runtime::xcm_config::LocationToAccountId as AssetHubLocationToAccountId, - genesis::ED as ASSET_HUB_ZAGROS_ED, - AssetHubZagrosParaPezpallet, + genesis::ED as ASSET_HUB_ZAGROS_ED, AssetHubZagrosParaPezpallet, AssetHubZagrosParaPezpallet as AssetHubZagrosPallet, }, collectives_zagros_emulated_chain::{ @@ -42,16 +41,12 @@ mod imports { }, coretime_zagros_emulated_chain::CoretimeZagrosParaPezpallet, people_zagros_emulated_chain::PeopleZagrosParaPezpallet, - pez_penpal_emulated_chain::{ - PenpalAssetOwner, - PenpalBParaPezpallet, - }, + pez_penpal_emulated_chain::{PenpalAssetOwner, PenpalBParaPezpallet}, pezbridge_hub_zagros_emulated_chain::BridgeHubZagrosParaPezpallet, zagros_emulated_chain::{ genesis::ED as ZAGROS_ED, zagros_runtime::{governance as zagros_governance, OriginCaller as ZagrosOriginCaller}, - ZagrosRelayPezpallet, - ZagrosRelayPezpallet as ZagrosPallet, + ZagrosRelayPezpallet, ZagrosRelayPezpallet as ZagrosPallet, }, AssetHubZagrosPara as AssetHubZagros, AssetHubZagrosParaReceiver as AssetHubZagrosReceiver, AssetHubZagrosParaSender as AssetHubZagrosSender, BridgeHubZagrosPara as BridgeHubZagros, diff --git a/pezcumulus/teyrchains/integration-tests/emulated/tests/coretime/coretime-pezkuwichain/src/lib.rs b/pezcumulus/teyrchains/integration-tests/emulated/tests/coretime/coretime-pezkuwichain/src/lib.rs index 14ccbc43..2504625a 100644 --- a/pezcumulus/teyrchains/integration-tests/emulated/tests/coretime/coretime-pezkuwichain/src/lib.rs +++ b/pezcumulus/teyrchains/integration-tests/emulated/tests/coretime/coretime-pezkuwichain/src/lib.rs @@ -30,14 +30,10 @@ mod imports { asset_hub_pezkuwichain_emulated_chain::genesis::ED as ASSET_HUB_PEZKUWICHAIN_ED, coretime_pezkuwichain_emulated_chain::{ coretime_pezkuwichain_runtime::ExistentialDeposit as CoretimePezkuwichainExistentialDeposit, - genesis::ED as CORETIME_PEZKUWICHAIN_ED, - CoretimePezkuwichainParaPezpallet, + genesis::ED as CORETIME_PEZKUWICHAIN_ED, CoretimePezkuwichainParaPezpallet, CoretimePezkuwichainParaPezpallet as CoretimePezkuwichainPallet, }, - pezkuwichain_emulated_chain::{ - genesis::ED as PEZKUWICHAIN_ED, - PezkuwichainRelayPezpallet, - }, + pezkuwichain_emulated_chain::{genesis::ED as PEZKUWICHAIN_ED, PezkuwichainRelayPezpallet}, AssetHubPezkuwichainPara as AssetHubPezkuwichain, AssetHubPezkuwichainParaReceiver as AssetHubPezkuwichainReceiver, AssetHubPezkuwichainParaSender as AssetHubPezkuwichainSender, diff --git a/pezcumulus/teyrchains/integration-tests/emulated/tests/coretime/coretime-zagros/src/lib.rs b/pezcumulus/teyrchains/integration-tests/emulated/tests/coretime/coretime-zagros/src/lib.rs index 322cac54..8e837c61 100644 --- a/pezcumulus/teyrchains/integration-tests/emulated/tests/coretime/coretime-zagros/src/lib.rs +++ b/pezcumulus/teyrchains/integration-tests/emulated/tests/coretime/coretime-zagros/src/lib.rs @@ -28,26 +28,18 @@ mod imports { }; pub(crate) use zagros_system_emulated_network::{ asset_hub_zagros_emulated_chain::{ - genesis::ED as ASSET_HUB_ZAGROS_ED, - AssetHubZagrosParaPezpallet, + genesis::ED as ASSET_HUB_ZAGROS_ED, AssetHubZagrosParaPezpallet, }, collectives_zagros_emulated_chain::CollectivesZagrosParaPezpallet, coretime_zagros_emulated_chain::{ self, coretime_zagros_runtime::ExistentialDeposit as CoretimeZagrosExistentialDeposit, - genesis::ED as CORETIME_ZAGROS_ED, - CoretimeZagrosParaPezpallet, + genesis::ED as CORETIME_ZAGROS_ED, CoretimeZagrosParaPezpallet, CoretimeZagrosParaPezpallet as CoretimeZagrosPallet, }, people_zagros_emulated_chain::PeopleZagrosParaPezpallet, - pez_penpal_emulated_chain::{ - PenpalAssetOwner, - PenpalBParaPezpallet, - }, + pez_penpal_emulated_chain::{PenpalAssetOwner, PenpalBParaPezpallet}, pezbridge_hub_zagros_emulated_chain::BridgeHubZagrosParaPezpallet, - zagros_emulated_chain::{ - genesis::ED as ZAGROS_ED, - ZagrosRelayPezpallet, - }, + zagros_emulated_chain::{genesis::ED as ZAGROS_ED, ZagrosRelayPezpallet}, AssetHubZagrosPara as AssetHubZagros, AssetHubZagrosParaReceiver as AssetHubZagrosReceiver, AssetHubZagrosParaSender as AssetHubZagrosSender, BridgeHubZagrosPara as BridgeHubZagros, CollectivesZagrosPara as CollectivesZagros, CoretimeZagrosPara as CoretimeZagros, diff --git a/pezcumulus/teyrchains/integration-tests/emulated/tests/people/people-pezkuwichain/src/lib.rs b/pezcumulus/teyrchains/integration-tests/emulated/tests/people/people-pezkuwichain/src/lib.rs index c4a0d42b..6d70a5b2 100644 --- a/pezcumulus/teyrchains/integration-tests/emulated/tests/people/people-pezkuwichain/src/lib.rs +++ b/pezcumulus/teyrchains/integration-tests/emulated/tests/people/people-pezkuwichain/src/lib.rs @@ -35,10 +35,7 @@ mod imports { PeoplePezkuwichainParaPezpallet, PeoplePezkuwichainParaPezpallet as PeoplePezkuwichainPallet, }, - pezkuwichain_emulated_chain::{ - genesis::ED as PEZKUWICHAIN_ED, - PezkuwichainRelayPezpallet, - }, + pezkuwichain_emulated_chain::{genesis::ED as PEZKUWICHAIN_ED, PezkuwichainRelayPezpallet}, AssetHubPezkuwichainPara as AssetHubPezkuwichain, AssetHubPezkuwichainParaReceiver as AssetHubPezkuwichainReceiver, PeoplePezkuwichainPara as PeoplePezkuwichain, diff --git a/pezcumulus/teyrchains/integration-tests/emulated/tests/people/people-zagros/src/lib.rs b/pezcumulus/teyrchains/integration-tests/emulated/tests/people/people-zagros/src/lib.rs index bf288d28..f1698df8 100644 --- a/pezcumulus/teyrchains/integration-tests/emulated/tests/people/people-zagros/src/lib.rs +++ b/pezcumulus/teyrchains/integration-tests/emulated/tests/people/people-zagros/src/lib.rs @@ -28,8 +28,7 @@ mod imports { pub(crate) use zagros_system_emulated_network::{ self, asset_hub_zagros_emulated_chain::{ - AssetHubZagrosParaPezpallet, - AssetHubZagrosParaPezpallet as AssetHubZagrosPallet, + AssetHubZagrosParaPezpallet, AssetHubZagrosParaPezpallet as AssetHubZagrosPallet, }, collectives_zagros_emulated_chain::CollectivesZagrosParaPezpallet, coretime_zagros_emulated_chain::CoretimeZagrosParaPezpallet, @@ -38,18 +37,11 @@ mod imports { self, xcm_config::XcmConfig as PeopleZagrosXcmConfig, ExistentialDeposit as PeopleZagrosExistentialDeposit, }, - PeopleZagrosParaPezpallet, - PeopleZagrosParaPezpallet as PeopleZagrosPallet, - }, - pez_penpal_emulated_chain::{ - PenpalAssetOwner, - PenpalBParaPezpallet, + PeopleZagrosParaPezpallet, PeopleZagrosParaPezpallet as PeopleZagrosPallet, }, + pez_penpal_emulated_chain::{PenpalAssetOwner, PenpalBParaPezpallet}, pezbridge_hub_zagros_emulated_chain::BridgeHubZagrosParaPezpallet, - zagros_emulated_chain::{ - genesis::ED as ZAGROS_ED, - ZagrosRelayPezpallet, - }, + zagros_emulated_chain::{genesis::ED as ZAGROS_ED, ZagrosRelayPezpallet}, AssetHubZagrosPara as AssetHubZagros, AssetHubZagrosParaReceiver as AssetHubZagrosReceiver, BridgeHubZagrosPara as BridgeHubZagros, CollectivesZagrosPara as CollectivesZagros, CoretimeZagrosPara as CoretimeZagros, PenpalBPara as PenpalB, diff --git a/pezcumulus/teyrchains/integration-tests/emulated/tests/pezbridges/bridge-hub-pezkuwichain/src/lib.rs b/pezcumulus/teyrchains/integration-tests/emulated/tests/pezbridges/bridge-hub-pezkuwichain/src/lib.rs index 9381becd..f924346e 100644 --- a/pezcumulus/teyrchains/integration-tests/emulated/tests/pezbridges/bridge-hub-pezkuwichain/src/lib.rs +++ b/pezcumulus/teyrchains/integration-tests/emulated/tests/pezbridges/bridge-hub-pezkuwichain/src/lib.rs @@ -58,16 +58,14 @@ mod imports { CustomizableAssetFromSystemAssetHub as PenpalCustomizableAssetFromSystemAssetHub, UniversalLocation as PenpalUniversalLocation, }, - PenpalAParaPezpallet as PenpalAPallet, - PenpalAssetOwner, + PenpalAParaPezpallet as PenpalAPallet, PenpalAssetOwner, }, pezbridge_hub_pezkuwichain_emulated_chain::{ genesis::ED as BRIDGE_HUB_PEZKUWICHAIN_ED, BridgeHubPezkuwichainExistentialDeposit, BridgeHubPezkuwichainParaPezpallet, }, pezkuwichain_emulated_chain::{ - genesis::ED as PEZKUWICHAIN_ED, - PezkuwichainRelayPezpallet, + genesis::ED as PEZKUWICHAIN_ED, PezkuwichainRelayPezpallet, PezkuwichainRelayPezpallet as PezkuwichainPallet, }, AssetHubPezkuwichainPara as AssetHubPezkuwichain, diff --git a/pezcumulus/teyrchains/integration-tests/emulated/tests/pezbridges/bridge-hub-zagros/src/lib.rs b/pezcumulus/teyrchains/integration-tests/emulated/tests/pezbridges/bridge-hub-zagros/src/lib.rs index 937bd662..5e5814ab 100644 --- a/pezcumulus/teyrchains/integration-tests/emulated/tests/pezbridges/bridge-hub-zagros/src/lib.rs +++ b/pezcumulus/teyrchains/integration-tests/emulated/tests/pezbridges/bridge-hub-zagros/src/lib.rs @@ -54,8 +54,7 @@ mod imports { }, asset_hub_zagros_emulated_chain::{ genesis::{AssetHubZagrosAssetOwner, ED as ASSET_HUB_ZAGROS_ED}, - AssetHubZagrosParaPezpallet, - AssetHubZagrosParaPezpallet as AssetHubZagrosPallet, + AssetHubZagrosParaPezpallet, AssetHubZagrosParaPezpallet as AssetHubZagrosPallet, }, pez_penpal_emulated_chain::{ self, @@ -64,24 +63,17 @@ mod imports { LocalTeleportableToAssetHub as PenpalLocalTeleportableToAssetHub, UniversalLocation as PenpalUniversalLocation, }, - PenpalAParaPezpallet, - PenpalAParaPezpallet as PenpalAPallet, - PenpalAssetOwner, - PenpalBParaPezpallet, - PenpalBParaPezpallet as PenpalBPallet, + PenpalAParaPezpallet, PenpalAParaPezpallet as PenpalAPallet, PenpalAssetOwner, + PenpalBParaPezpallet, PenpalBParaPezpallet as PenpalBPallet, }, pezbridge_hub_zagros_emulated_chain::{ genesis::ED as BRIDGE_HUB_ZAGROS_ED, pezbridge_hub_zagros_runtime, - BridgeHubZagrosExistentialDeposit, - BridgeHubZagrosParaPezpallet, - BridgeHubZagrosParaPezpallet as BridgeHubZagrosPallet, - BridgeHubZagrosRuntimeOrigin, + BridgeHubZagrosExistentialDeposit, BridgeHubZagrosParaPezpallet, + BridgeHubZagrosParaPezpallet as BridgeHubZagrosPallet, BridgeHubZagrosRuntimeOrigin, }, pezkuwichain_emulated_chain::PezkuwichainRelayPezpallet as PezkuwichainPallet, zagros_emulated_chain::{ - genesis::ED as ZAGROS_ED, - ZagrosRelayPezpallet, - ZagrosRelayPezpallet as ZagrosPallet, + genesis::ED as ZAGROS_ED, ZagrosRelayPezpallet, ZagrosRelayPezpallet as ZagrosPallet, }, AssetHubPezkuwichainPara as AssetHubPezkuwichain, AssetHubPezkuwichainParaReceiver as AssetHubPezkuwichainReceiver, diff --git a/pezcumulus/teyrchains/pezpallets/identity-kyc/src/mock.rs b/pezcumulus/teyrchains/pezpallets/identity-kyc/src/mock.rs index 46c338b1..c6f9b50f 100644 --- a/pezcumulus/teyrchains/pezpallets/identity-kyc/src/mock.rs +++ b/pezcumulus/teyrchains/pezpallets/identity-kyc/src/mock.rs @@ -1,8 +1,5 @@ use crate as pezpallet_identity_kyc; -use pezframe_support::{ - construct_runtime, derive_impl, parameter_types, - traits::ConstU128, -}; +use pezframe_support::{construct_runtime, derive_impl, parameter_types, traits::ConstU128}; use pezframe_system::EnsureRoot; use pezsp_core::H256; use pezsp_runtime::BuildStorage; diff --git a/pezcumulus/teyrchains/pezpallets/pez-rewards/src/tests.rs b/pezcumulus/teyrchains/pezpallets/pez-rewards/src/tests.rs index 69af0d56..b5d09147 100644 --- a/pezcumulus/teyrchains/pezpallets/pez-rewards/src/tests.rs +++ b/pezcumulus/teyrchains/pezpallets/pez-rewards/src/tests.rs @@ -141,9 +141,9 @@ fn finalize_epoch_calculates_rewards_correctly() { assert_ok!(PezRewards::record_trust_score(RuntimeOrigin::signed(bob()))); // 50 assert_ok!(PezRewards::record_trust_score(RuntimeOrigin::signed(charlie()))); // 75 let total_trust: u128 = 100 + 50 + 75; - let expected_deadline = System::block_number() + - crate::BLOCKS_PER_EPOCH as u64 + - crate::CLAIM_PERIOD_BLOCKS as u64; + let expected_deadline = System::block_number() + + crate::BLOCKS_PER_EPOCH as u64 + + crate::CLAIM_PERIOD_BLOCKS as u64; let incentive_pot = PezRewards::incentive_pot_account_id(); let initial_pot_balance = pez_balance(&incentive_pot); diff --git a/pezcumulus/teyrchains/pezpallets/pez-treasury/src/migrations.rs b/pezcumulus/teyrchains/pezpallets/pez-treasury/src/migrations.rs index 2336696e..8bb82ab2 100644 --- a/pezcumulus/teyrchains/pezpallets/pez-treasury/src/migrations.rs +++ b/pezcumulus/teyrchains/pezpallets/pez-treasury/src/migrations.rs @@ -39,10 +39,10 @@ pub mod v1 { let has_genesis_done = if GenesisDistributionDone::::get() { 1u64 } else { 0u64 }; - let migrated = monthly_releases_count + - has_halving_info + - has_treasury_start + - has_genesis_done; + let migrated = monthly_releases_count + + has_halving_info + + has_treasury_start + + has_genesis_done; // Update storage version STORAGE_VERSION.put::>(); diff --git a/pezcumulus/teyrchains/pezpallets/ping/src/lib.rs b/pezcumulus/teyrchains/pezpallets/ping/src/lib.rs index b27ca83d..1b96f88b 100644 --- a/pezcumulus/teyrchains/pezpallets/ping/src/lib.rs +++ b/pezcumulus/teyrchains/pezpallets/ping/src/lib.rs @@ -220,8 +220,9 @@ pub mod pezpallet { fallback_max_weight: None, }]), ) { - Ok((hash, cost)) => - Self::deposit_event(Event::PongSent(para, seq, payload, hash, cost)), + Ok((hash, cost)) => { + Self::deposit_event(Event::PongSent(para, seq, payload, hash, cost)) + }, Err(e) => Self::deposit_event(Event::ErrorSendingPong(e, para, seq, payload)), } Ok(()) diff --git a/pezcumulus/teyrchains/pezpallets/presale/src/benchmarking.rs b/pezcumulus/teyrchains/pezpallets/presale/src/benchmarking.rs index 1462da40..052aa27c 100644 --- a/pezcumulus/teyrchains/pezpallets/presale/src/benchmarking.rs +++ b/pezcumulus/teyrchains/pezpallets/presale/src/benchmarking.rs @@ -52,16 +52,8 @@ mod benchmarks { let _ = T::Assets::mint_into(payment_asset, caller, payment_amount); // Mint payment tokens to platform accounts for fee distribution - let _ = T::Assets::mint_into( - payment_asset, - &T::PlatformTreasury::get(), - payment_amount, - ); - let _ = T::Assets::mint_into( - payment_asset, - &T::StakingRewardPool::get(), - payment_amount, - ); + let _ = T::Assets::mint_into(payment_asset, &T::PlatformTreasury::get(), payment_amount); + let _ = T::Assets::mint_into(payment_asset, &T::StakingRewardPool::get(), payment_amount); // Mint reward tokens to presale treasury for distribution let reward_amount: T::Balance = 10_000_000_000u128.into(); @@ -289,8 +281,7 @@ mod benchmarks { let (payment_asset, reward_asset) = setup_benchmark_assets::(&caller, &presale_treasury); // Create presale (will get the presale_id we calculated) - let _ = - create_test_presale::(&caller, payment_asset, reward_asset, false, false); + let _ = create_test_presale::(&caller, payment_asset, reward_asset, false, false); // Make a contribution let amount: u128 = 10_000u128; @@ -325,13 +316,7 @@ mod benchmarks { let (payment_asset, reward_asset) = setup_benchmark_assets::(&caller, &presale_treasury); // Create presale (will get the presale_id we calculated) - let _ = create_test_presale::( - &caller, - payment_asset, - reward_asset, - false, - false, - ); + let _ = create_test_presale::(&caller, payment_asset, reward_asset, false, false); // Add n contributors for i in 0..n { @@ -382,7 +367,7 @@ mod benchmarks { limits: crate::ContributionLimits { min_contribution: 100u128, max_contribution: 10_000_000u128, - soft_cap: 1_000_000_000_000u128, // very high - will fail + soft_cap: 1_000_000_000_000u128, // very high - will fail hard_cap: 2_000_000_000_000u128, }, vesting: None, diff --git a/pezcumulus/teyrchains/pezpallets/presale/src/lib.rs b/pezcumulus/teyrchains/pezpallets/presale/src/lib.rs index 16ee5279..792d523d 100644 --- a/pezcumulus/teyrchains/pezpallets/presale/src/lib.rs +++ b/pezcumulus/teyrchains/pezpallets/presale/src/lib.rs @@ -60,7 +60,18 @@ pub mod pezpallet { pub type PresaleId = u32; - #[derive(Clone, Copy, Encode, Decode, DecodeWithMemTracking, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] + #[derive( + Clone, + Copy, + Encode, + Decode, + DecodeWithMemTracking, + Eq, + PartialEq, + RuntimeDebug, + MaxEncodedLen, + TypeInfo, + )] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] pub enum PresaleStatus { Pending, // Not started yet @@ -72,7 +83,18 @@ pub mod pezpallet { Finalized, // Tokens distributed (after Successful) } - #[derive(Clone, Copy, Encode, Decode, DecodeWithMemTracking, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] + #[derive( + Clone, + Copy, + Encode, + Decode, + DecodeWithMemTracking, + Eq, + PartialEq, + RuntimeDebug, + MaxEncodedLen, + TypeInfo, + )] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] #[codec(dumb_trait_bound)] pub enum AccessControl { @@ -80,7 +102,18 @@ pub mod pezpallet { Whitelist, // Only whitelisted accounts } - #[derive(Clone, Copy, Encode, Decode, DecodeWithMemTracking, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] + #[derive( + Clone, + Copy, + Encode, + Decode, + DecodeWithMemTracking, + Eq, + PartialEq, + RuntimeDebug, + MaxEncodedLen, + TypeInfo, + )] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] #[codec(dumb_trait_bound)] pub struct BonusTier { @@ -90,7 +123,18 @@ pub mod pezpallet { pub bonus_percentage: u8, } - #[derive(Clone, Copy, Encode, Decode, DecodeWithMemTracking, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] + #[derive( + Clone, + Copy, + Encode, + Decode, + DecodeWithMemTracking, + Eq, + PartialEq, + RuntimeDebug, + MaxEncodedLen, + TypeInfo, + )] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] #[codec(dumb_trait_bound)] pub struct VestingSchedule { @@ -102,7 +146,18 @@ pub mod pezpallet { pub cliff_blocks: BlockNumber, } - #[derive(Clone, Copy, Encode, Decode, DecodeWithMemTracking, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] + #[derive( + Clone, + Copy, + Encode, + Decode, + DecodeWithMemTracking, + Eq, + PartialEq, + RuntimeDebug, + MaxEncodedLen, + TypeInfo, + )] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] #[codec(dumb_trait_bound)] pub struct ContributionLimits { @@ -116,7 +171,18 @@ pub mod pezpallet { pub hard_cap: u128, } - #[derive(Clone, Copy, Encode, Decode, DecodeWithMemTracking, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] + #[derive( + Clone, + Copy, + Encode, + Decode, + DecodeWithMemTracking, + Eq, + PartialEq, + RuntimeDebug, + MaxEncodedLen, + TypeInfo, + )] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] #[codec(dumb_trait_bound)] pub struct RefundConfig { @@ -128,7 +194,18 @@ pub mod pezpallet { pub grace_refund_fee_percent: u8, } - #[derive(Clone, Copy, Encode, Decode, DecodeWithMemTracking, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] + #[derive( + Clone, + Copy, + Encode, + Decode, + DecodeWithMemTracking, + Eq, + PartialEq, + RuntimeDebug, + MaxEncodedLen, + TypeInfo, + )] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] #[codec(dumb_trait_bound)] pub struct PresaleCreationParams { @@ -146,7 +223,18 @@ pub mod pezpallet { pub refund_config: RefundConfig, } - #[derive(Clone, Copy, Encode, Decode, DecodeWithMemTracking, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] + #[derive( + Clone, + Copy, + Encode, + Decode, + DecodeWithMemTracking, + Eq, + PartialEq, + RuntimeDebug, + MaxEncodedLen, + TypeInfo, + )] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] #[codec(dumb_trait_bound)] pub struct ContributionInfo { @@ -162,7 +250,17 @@ pub mod pezpallet { pub refund_fee_paid: u128, } - #[derive(Clone, Encode, Decode, DecodeWithMemTracking, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] + #[derive( + Clone, + Encode, + Decode, + DecodeWithMemTracking, + Eq, + PartialEq, + RuntimeDebug, + TypeInfo, + MaxEncodedLen, + )] #[scale_info(skip_type_params(T, MaxBonusTiers))] #[codec(mel_bound(T: Config, MaxBonusTiers: Get))] pub struct PresaleConfig> { @@ -428,9 +526,15 @@ pub mod pezpallet { ensure!(params.tokens_for_sale > 0, Error::::InvalidTokensForSale); ensure!(params.limits.soft_cap > 0, Error::::InvalidTokensForSale); - ensure!(params.limits.soft_cap <= params.limits.hard_cap, Error::::InvalidTokensForSale); + ensure!( + params.limits.soft_cap <= params.limits.hard_cap, + Error::::InvalidTokensForSale + ); ensure!(params.refund_config.refund_fee_percent <= 100, Error::::InvalidFeePercent); - ensure!(params.refund_config.grace_refund_fee_percent <= 100, Error::::InvalidFeePercent); + ensure!( + params.refund_config.grace_refund_fee_percent <= 100, + Error::::InvalidFeePercent + ); let presale_id = NextPresaleId::::get(); let start_block = >::block_number(); @@ -639,8 +743,8 @@ pub mod pezpallet { // Handle vesting if let Some(ref vesting) = presale.vesting { let immediate = total_reward - .saturating_mul(vesting.immediate_release_percent as u128) / - 100; + .saturating_mul(vesting.immediate_release_percent as u128) + / 100; if immediate > 0 { let immediate_balance: T::Balance = immediate.into(); @@ -737,8 +841,7 @@ pub mod pezpallet { let treasury = Self::presale_account_id(presale_id); // Step 1: Transfer refund amount to user - let refund_amount_balance: T::Balance = - refund_amount.into(); + let refund_amount_balance: T::Balance = refund_amount.into(); T::Assets::transfer( presale.payment_asset, &treasury, @@ -819,10 +922,9 @@ pub mod pezpallet { let vested_percent = elapsed_u128.saturating_mul(100) / duration_u128; let immediate_percent = vesting.immediate_release_percent as u128; let vesting_percent = 100u128.saturating_sub(immediate_percent); - let vested_amount = total_with_bonus - .saturating_mul(vesting_percent) - .saturating_mul(vested_percent) / - 10000; + let vested_amount = + total_with_bonus.saturating_mul(vesting_percent).saturating_mul(vested_percent) + / 10000; let total_unlocked = vested_amount.saturating_add(already_claimed); total_unlocked.saturating_sub(already_claimed) }; @@ -831,8 +933,7 @@ pub mod pezpallet { // Transfer tokens let treasury = Self::presale_account_id(presale_id); - let claimable_balance: T::Balance = - claimable.into(); + let claimable_balance: T::Balance = claimable.into(); T::Assets::transfer( presale.reward_asset, &treasury, @@ -920,15 +1021,13 @@ pub mod pezpallet { // Calculate non-refundable portion (burn + stakers = 50% of platform fee) let platform_fee = contribution_info .amount - .saturating_mul(T::PlatformFeePercent::get() as u128) / - 100; + .saturating_mul(T::PlatformFeePercent::get() as u128) + / 100; let non_refundable = platform_fee.saturating_mul(50) / 100; // 1% (burn 25% + stakers 25%) // Refund = 99% (contribution - non_refundable portion) - let refund_amount: T::Balance = contribution_info - .amount - .saturating_sub(non_refundable) - .into(); + let refund_amount: T::Balance = + contribution_info.amount.saturating_sub(non_refundable).into(); T::Assets::transfer( presale.payment_asset, @@ -998,15 +1097,13 @@ pub mod pezpallet { // Calculate non-refundable portion (burn + stakers = 50% of platform fee) let platform_fee = contribution_info .amount - .saturating_mul(T::PlatformFeePercent::get() as u128) / - 100; + .saturating_mul(T::PlatformFeePercent::get() as u128) + / 100; let non_refundable = platform_fee.saturating_mul(50) / 100; // 1% (burn 25% + stakers 25%) // Refund = 99% (contribution - non_refundable portion) - let refund_amount: T::Balance = contribution_info - .amount - .saturating_sub(non_refundable) - .into(); + let refund_amount: T::Balance = + contribution_info.amount.saturating_sub(non_refundable).into(); T::Assets::transfer( presale.payment_asset, @@ -1082,12 +1179,9 @@ pub mod pezpallet { let to_burn = total_fee.saturating_mul(25) / 100; // 25% let to_stakers = total_fee.saturating_mul(25) / 100; // 25% - let to_treasury_balance: T::Balance = - to_treasury.into(); - let to_burn_balance: T::Balance = - to_burn.into(); - let to_stakers_balance: T::Balance = - to_stakers.into(); + let to_treasury_balance: T::Balance = to_treasury.into(); + let to_burn_balance: T::Balance = to_burn.into(); + let to_stakers_balance: T::Balance = to_stakers.into(); // Note: Balance check removed - rely on Preservation::Expendable to handle insufficient // balance gracefully The operations below will transfer/burn as much as possible diff --git a/pezcumulus/teyrchains/pezpallets/presale/src/tests.rs b/pezcumulus/teyrchains/pezpallets/presale/src/tests.rs index fe05a720..65b1e240 100644 --- a/pezcumulus/teyrchains/pezpallets/presale/src/tests.rs +++ b/pezcumulus/teyrchains/pezpallets/presale/src/tests.rs @@ -1,4 +1,7 @@ -use crate::{mock::*, Error, Event, PresaleStatus, ContributionLimits, VestingSchedule, RefundConfig, PresaleCreationParams}; +use crate::{ + mock::*, ContributionLimits, Error, Event, PresaleCreationParams, PresaleStatus, RefundConfig, + VestingSchedule, +}; use pezframe_support::{assert_noop, assert_ok}; /// Helper function to create presale params with common defaults @@ -33,12 +36,7 @@ fn make_presale_params( tokens_for_sale, duration, is_whitelist, - limits: ContributionLimits { - min_contribution, - max_contribution, - soft_cap, - hard_cap, - }, + limits: ContributionLimits { min_contribution, max_contribution, soft_cap, hard_cap }, vesting, refund_config: RefundConfig { grace_period_blocks, @@ -108,12 +106,48 @@ fn create_multiple_presales_works() { // Alice creates first presale assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Bob creates second presale assert_ok!(Presale::create_presale( RuntimeOrigin::signed(2), - 2, 1, make_presale_params(20_000_000_000_000_000_000, 200, false, 20_000_000, 2_000_000_000, 10_000_000_000, 20_000_000_000, false, 0, 0, 0, 48, 10, 5))); + 2, + 1, + make_presale_params( + 20_000_000_000_000_000_000, + 200, + false, + 20_000_000, + 2_000_000_000, + 10_000_000_000, + 20_000_000_000, + false, + 0, + 0, + 0, + 48, + 10, + 5 + ) + )); // Check both presales exist assert!(Presale::presales(0).is_some()); @@ -137,7 +171,25 @@ fn contribute_works() { mint_assets(1, 1, 100_000_000_000_000_000_000); assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Mint wUSDT to Bob mint_assets(2, 2, 1_000_000_000); // 1000 USDT @@ -204,7 +256,25 @@ fn contribute_multiple_times_works() { assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // First contribution assert_ok!(Presale::contribute(RuntimeOrigin::signed(2), 0, 50_000_000)); @@ -234,14 +304,50 @@ fn contribute_to_different_presales_works() { // Create two presales assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Fund presale 0 treasury with reward tokens mint_assets(1, presale_treasury(0), 10_000_000_000_000_000_000); assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(15_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 15_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Fund presale 1 treasury with reward tokens mint_assets(1, presale_treasury(1), 15_000_000_000_000_000_000); @@ -279,7 +385,25 @@ fn contribute_below_min_fails() { assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Try to contribute less than minimum (10 USDT) assert_noop!( @@ -298,7 +422,25 @@ fn contribute_above_max_fails() { assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Try to contribute more than maximum (1000 USDT) assert_noop!( @@ -369,7 +511,25 @@ fn contribute_after_presale_ended_fails() { assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Move past presale end (block 1 + 100 = 101) System::set_block_number(102); @@ -390,7 +550,25 @@ fn finalize_presale_works() { mint_assets(1, 1, 100_000_000_000_000_000_000); // 100,000 PEZ assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Mint PEZ to presale treasury for distribution let treasury = presale_treasury(0); @@ -428,8 +606,8 @@ fn finalize_presale_works() { let contributor_pez = Assets::balance(1, i); // Allow for small rounding differences (within 0.1%) assert!( - contributor_pez >= expected_pez - 10_000_000_000_000_000 && - contributor_pez <= expected_pez + 10_000_000_000_000_000, + contributor_pez >= expected_pez - 10_000_000_000_000_000 + && contributor_pez <= expected_pez + 10_000_000_000_000_000, "Contributor {i} PEZ: {contributor_pez} (expected ~{expected_pez})" ); } @@ -449,7 +627,25 @@ fn finalize_presale_before_end_fails() { assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Try to finalize immediately (use root to test the actual business logic error) assert_noop!( @@ -467,7 +663,25 @@ fn finalize_presale_non_root_fails() { assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); System::set_block_number(101); @@ -488,7 +702,25 @@ fn refund_works() { assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Bob contributes let contribution = 100_000_000; // 100 USDT @@ -596,7 +828,25 @@ fn refund_with_no_contribution_fails() { assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Bob tries to refund without contributing assert_noop!(Presale::refund(RuntimeOrigin::signed(2), 0), Error::::NoContribution); @@ -612,7 +862,25 @@ fn cancel_presale_works() { assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Bob contributes assert_ok!(Presale::contribute(RuntimeOrigin::signed(2), 0, 100_000_000)); @@ -637,7 +905,25 @@ fn cancel_presale_non_authorized_fails() { assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Non-authorized user tries to cancel (needs EmergencyOrigin or Root) assert_noop!( @@ -655,7 +941,25 @@ fn emergency_cancel_by_root_works() { assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Root can cancel any presale (emergency) assert_ok!(Presale::cancel_presale(RuntimeOrigin::root(), 0)); @@ -675,8 +979,25 @@ fn whitelist_presale_works() { // Create whitelist presale assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, true, // whitelist enabled - 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + true, // whitelist enabled + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Bob tries to contribute (not whitelisted) assert_noop!( @@ -700,7 +1021,25 @@ fn add_to_whitelist_non_owner_fails() { assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, true, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + true, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Charlie tries to add Bob to Alice's presale whitelist assert_noop!( @@ -722,7 +1061,25 @@ fn finalize_presale_soft_cap_reached_success() { mint_assets(1, 1, 100_000_000_000_000_000_000); // 100,000 PEZ assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Mint PEZ to presale treasury let treasury = presale_treasury(0); @@ -769,7 +1126,25 @@ fn finalize_presale_soft_cap_not_reached_fails() { mint_assets(1, 1, 100_000_000_000_000_000_000); assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Contributors below soft cap (max is 1000 USDT each) // Need to contribute less than soft cap of 5000 USDT @@ -811,7 +1186,25 @@ fn batch_refund_failed_presale_works() { mint_assets(1, 1, 100_000_000_000_000_000_000); assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Fund presale treasury with wUSDT for refunds let treasury = presale_treasury(0); @@ -864,7 +1257,25 @@ fn batch_refund_successful_presale_fails() { mint_assets(1, 1, 100_000_000_000_000_000_000); assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); let treasury = presale_treasury(0); mint_assets(1, treasury, 100_000_000_000_000_000_000); @@ -906,7 +1317,25 @@ fn create_presale_with_soft_cap_greater_than_hard_cap_fails() { assert_noop!( Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000_000_000_000, 100, false, 10_000_000, 1_000_000_000, 15_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2)), + 2, + 1, + make_presale_params( + 10_000_000_000_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 15_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + ), Error::::InvalidTokensForSale ); }); @@ -925,7 +1354,25 @@ fn debug_finalize_presale() { // Create presale assert_ok!(Presale::create_presale( RuntimeOrigin::signed(1), - 2, 1, make_presale_params(10_000_000_000, 100, false, 10_000_000, 1_000_000_000, 5_000_000_000, 10_000_000_000, false, 0, 0, 0, 24, 5, 2))); + 2, + 1, + make_presale_params( + 10_000_000_000, + 100, + false, + 10_000_000, + 1_000_000_000, + 5_000_000_000, + 10_000_000_000, + false, + 0, + 0, + 0, + 24, + 5, + 2 + ) + )); // Fund presale treasury with reward tokens let treasury = presale_treasury(0); diff --git a/pezcumulus/teyrchains/pezpallets/referral/src/lib.rs b/pezcumulus/teyrchains/pezpallets/referral/src/lib.rs index 589e07e2..c2d1e8b7 100644 --- a/pezcumulus/teyrchains/pezpallets/referral/src/lib.rs +++ b/pezcumulus/teyrchains/pezpallets/referral/src/lib.rs @@ -266,8 +266,8 @@ pub mod pezpallet { fn on_kyc_approved(who: &T::AccountId, referrer: &T::AccountId) { // Security check: Verify on-chain that the user's KYC status is actually // "Approved" before confirming the referral. - if pezpallet_identity_kyc::Pezpallet::::get_kyc_status(who) == - pezpallet_identity_kyc::types::KycLevel::Approved + if pezpallet_identity_kyc::Pezpallet::::get_kyc_status(who) + == pezpallet_identity_kyc::types::KycLevel::Approved { // Check if this referral already exists (prevent double-counting) if Referrals::::contains_key(who) { diff --git a/pezcumulus/teyrchains/pezpallets/referral/src/mock.rs b/pezcumulus/teyrchains/pezpallets/referral/src/mock.rs index b558f021..709b41e9 100644 --- a/pezcumulus/teyrchains/pezpallets/referral/src/mock.rs +++ b/pezcumulus/teyrchains/pezpallets/referral/src/mock.rs @@ -1,10 +1,7 @@ // pezkuwi/pallets/referral/src/mock.rs (Updated for new trustless model) use crate as pezpallet_referral; -use pezframe_support::{ - construct_runtime, derive_impl, parameter_types, - traits::ConstU128, -}; +use pezframe_support::{construct_runtime, derive_impl, parameter_types, traits::ConstU128}; use pezframe_system::EnsureRoot; use pezsp_core::H256; use pezsp_runtime::BuildStorage; diff --git a/pezcumulus/teyrchains/pezpallets/referral/src/tests.rs b/pezcumulus/teyrchains/pezpallets/referral/src/tests.rs index bfada5df..cd8d2b97 100644 --- a/pezcumulus/teyrchains/pezpallets/referral/src/tests.rs +++ b/pezcumulus/teyrchains/pezpallets/referral/src/tests.rs @@ -1,6 +1,5 @@ use crate::{ - mock::*, Error, Event, PendingReferrals, ReferralCount, Referrals, - ReferrerStatsStorage, + mock::*, Error, Event, PendingReferrals, ReferralCount, Referrals, ReferrerStatsStorage, }; use pezframe_support::{assert_noop, assert_ok}; use pezpallet_identity_kyc::types::{OnCitizenshipRevoked, OnKycApproved}; diff --git a/pezcumulus/teyrchains/pezpallets/staking-score/src/mock.rs b/pezcumulus/teyrchains/pezpallets/staking-score/src/mock.rs index 19131374..1361be13 100644 --- a/pezcumulus/teyrchains/pezpallets/staking-score/src/mock.rs +++ b/pezcumulus/teyrchains/pezpallets/staking-score/src/mock.rs @@ -261,13 +261,15 @@ impl ExtBuilder { invulnerables: self .stakers .iter() - .filter_map(|(stash, _, _, status)| { - if let StakerStatus::Validator = status { - Some(*stash) - } else { - None - } - }) + .filter_map( + |(stash, _, _, status)| { + if let StakerStatus::Validator = status { + Some(*stash) + } else { + None + } + }, + ) .collect(), force_era: pezpallet_staking::Forcing::ForceNew, // Yeni era başlatmaya zorla min_nominator_bond: MinNominatorBond::get(), // Tanımlanan minimum değerleri kullan diff --git a/pezcumulus/teyrchains/pezpallets/tiki/src/benchmarking.rs b/pezcumulus/teyrchains/pezpallets/tiki/src/benchmarking.rs index b4f41c42..cce631cc 100644 --- a/pezcumulus/teyrchains/pezpallets/tiki/src/benchmarking.rs +++ b/pezcumulus/teyrchains/pezpallets/tiki/src/benchmarking.rs @@ -49,7 +49,9 @@ mod benchmarks { } // Helper to ensure user has a citizen NFT - fn ensure_citizen_nft(who: T::AccountId) -> Result<(), DispatchError> + fn ensure_citizen_nft( + who: T::AccountId, + ) -> Result<(), DispatchError> where T::CollectionId: Default + PartialOrd, { diff --git a/pezcumulus/teyrchains/pezpallets/tiki/src/lib.rs b/pezcumulus/teyrchains/pezpallets/tiki/src/lib.rs index 7ae0f66b..305f8838 100644 --- a/pezcumulus/teyrchains/pezpallets/tiki/src/lib.rs +++ b/pezcumulus/teyrchains/pezpallets/tiki/src/lib.rs @@ -677,15 +677,16 @@ pub mod pezpallet { Tiki::Welati => RoleAssignmentType::Automatic, // Elected roles - Tiki::Parlementer | Tiki::SerokiMeclise | Tiki::Serok => - RoleAssignmentType::Elected, + Tiki::Parlementer | Tiki::SerokiMeclise | Tiki::Serok => { + RoleAssignmentType::Elected + }, // Earned roles (automatically given by pezpallet-referral) - Tiki::Axa | - Tiki::Mamoste | - Tiki::Rewsenbîr | - Tiki::SerokêKomele | - Tiki::ModeratorêCivakê => RoleAssignmentType::Earned, + Tiki::Axa + | Tiki::Mamoste + | Tiki::Rewsenbîr + | Tiki::SerokêKomele + | Tiki::ModeratorêCivakê => RoleAssignmentType::Earned, // Appointed roles (default) _ => RoleAssignmentType::Appointed, diff --git a/pezcumulus/teyrchains/pezpallets/tiki/src/migrations.rs b/pezcumulus/teyrchains/pezpallets/tiki/src/migrations.rs index c28d257f..4b599dec 100644 --- a/pezcumulus/teyrchains/pezpallets/tiki/src/migrations.rs +++ b/pezcumulus/teyrchains/pezpallets/tiki/src/migrations.rs @@ -101,9 +101,7 @@ pub mod v1 { let post_tiki_holder_count = TikiHolder::::iter().count() as u32; log::info!(" CitizenNft entries: {pre_citizen_count} -> {post_citizen_count}"); - log::info!( - " UserTikis entries: {pre_user_tikis_count} -> {post_user_tikis_count}" - ); + log::info!(" UserTikis entries: {pre_user_tikis_count} -> {post_user_tikis_count}"); log::info!( " TikiHolder entries: {pre_tiki_holder_count} -> {post_tiki_holder_count}" ); diff --git a/pezcumulus/teyrchains/pezpallets/tiki/src/mock.rs b/pezcumulus/teyrchains/pezpallets/tiki/src/mock.rs index 397b3930..cc12832f 100644 --- a/pezcumulus/teyrchains/pezpallets/tiki/src/mock.rs +++ b/pezcumulus/teyrchains/pezpallets/tiki/src/mock.rs @@ -20,10 +20,13 @@ use pezsp_runtime::RuntimeAppPublic; pub struct IdentityBenchmarkHelper; #[cfg(feature = "runtime-benchmarks")] -impl pezpallet_identity::BenchmarkHelper for IdentityBenchmarkHelper { +impl pezpallet_identity::BenchmarkHelper + for IdentityBenchmarkHelper +{ fn sign_message(message: &[u8]) -> (UintAuthorityId, TestSignature) { let signer = UintAuthorityId(0); - let signature = ::sign(&signer, &message.to_vec()).unwrap(); + let signature = + ::sign(&signer, &message.to_vec()).unwrap(); (signer, signature) } } @@ -33,7 +36,9 @@ impl pezpallet_identity::BenchmarkHelper for Ide pub struct NftsBenchmarkHelper; #[cfg(feature = "runtime-benchmarks")] -impl pezpallet_nfts::BenchmarkHelper for NftsBenchmarkHelper { +impl pezpallet_nfts::BenchmarkHelper + for NftsBenchmarkHelper +{ fn collection(i: u16) -> u32 { i.into() } diff --git a/pezcumulus/teyrchains/pezpallets/tiki/src/tests.rs b/pezcumulus/teyrchains/pezpallets/tiki/src/tests.rs index cc80147e..57b4dc18 100644 --- a/pezcumulus/teyrchains/pezpallets/tiki/src/tests.rs +++ b/pezcumulus/teyrchains/pezpallets/tiki/src/tests.rs @@ -49,11 +49,7 @@ fn grant_appointed_role_works() { assert_ok!(TikiPallet::force_mint_citizen_nft(RuntimeOrigin::root(), user_account)); // Tiki ver - assert_ok!(TikiPallet::grant_tiki( - RuntimeOrigin::root(), - user_account, - tiki_to_grant - )); + assert_ok!(TikiPallet::grant_tiki(RuntimeOrigin::root(), user_account, tiki_to_grant)); // Kullanıcının rollerini kontrol et let user_tikis = TikiPallet::user_tikis(user_account); @@ -189,11 +185,7 @@ fn grant_earned_role_works() { assert_ok!(TikiPallet::force_mint_citizen_nft(RuntimeOrigin::root(), user_account)); // Earned rolü ver - assert_ok!(TikiPallet::grant_earned_role( - RuntimeOrigin::root(), - user_account, - earned_role - )); + assert_ok!(TikiPallet::grant_earned_role(RuntimeOrigin::root(), user_account, earned_role)); // Rolün eklendiğini kontrol et assert!(TikiPallet::user_tikis(user_account).contains(&earned_role)); @@ -237,11 +229,7 @@ fn unique_roles_work_correctly() { assert_ok!(TikiPallet::force_mint_citizen_nft(RuntimeOrigin::root(), user2)); // İlk kullanıcıya unique rolü ver (elected role olarak) - assert_ok!(TikiPallet::grant_elected_role( - RuntimeOrigin::root(), - user1, - unique_role - )); + assert_ok!(TikiPallet::grant_elected_role(RuntimeOrigin::root(), user1, unique_role)); // İkinci kullanıcıya aynı rolü vermeye çalış assert_noop!( @@ -279,21 +267,13 @@ fn revoke_tiki_works() { // NFT bas ve role ver assert_ok!(TikiPallet::force_mint_citizen_nft(RuntimeOrigin::root(), user_account)); - assert_ok!(TikiPallet::grant_tiki( - RuntimeOrigin::root(), - user_account, - tiki_to_revoke - )); + assert_ok!(TikiPallet::grant_tiki(RuntimeOrigin::root(), user_account, tiki_to_revoke)); // Rolün eklendiğini kontrol et assert!(TikiPallet::user_tikis(user_account).contains(&tiki_to_revoke)); // Rolü kaldır - assert_ok!(TikiPallet::revoke_tiki( - RuntimeOrigin::root(), - user_account, - tiki_to_revoke - )); + assert_ok!(TikiPallet::revoke_tiki(RuntimeOrigin::root(), user_account, tiki_to_revoke)); // Rolün kaldırıldığını kontrol et assert!(!TikiPallet::user_tikis(user_account).contains(&tiki_to_revoke)); @@ -332,11 +312,7 @@ fn revoke_unique_role_clears_holder() { // NFT bas ve unique rolü ver assert_ok!(TikiPallet::force_mint_citizen_nft(RuntimeOrigin::root(), user)); - assert_ok!(TikiPallet::grant_elected_role( - RuntimeOrigin::root(), - user, - unique_role - )); + assert_ok!(TikiPallet::grant_elected_role(RuntimeOrigin::root(), user, unique_role)); // TikiHolder'da kayıtlı olduğunu kontrol et assert_eq!(TikiPallet::tiki_holder(unique_role), Some(user)); diff --git a/pezcumulus/teyrchains/pezpallets/trust/src/lib.rs b/pezcumulus/teyrchains/pezpallets/trust/src/lib.rs index c1388fad..bde70256 100644 --- a/pezcumulus/teyrchains/pezpallets/trust/src/lib.rs +++ b/pezcumulus/teyrchains/pezpallets/trust/src/lib.rs @@ -152,7 +152,9 @@ pub mod pezpallet { pub struct Pezpallet(_); #[pezpallet::config] - pub trait Config: pezframe_system::Config>> + pezpallet_identity_kyc::Config { + pub trait Config: + pezframe_system::Config>> + pezpallet_identity_kyc::Config + { type WeightInfo: WeightInfo; type Score: Member diff --git a/pezcumulus/teyrchains/pezpallets/trust/src/tests.rs b/pezcumulus/teyrchains/pezpallets/trust/src/tests.rs index 5bc87283..7a4ad19b 100644 --- a/pezcumulus/teyrchains/pezpallets/trust/src/tests.rs +++ b/pezcumulus/teyrchains/pezpallets/trust/src/tests.rs @@ -303,8 +303,8 @@ fn update_all_trust_scores_emits_event() { let events = System::events(); let bulk_update_event = events.iter().any(|event| { - matches!(event.event, RuntimeEvent::TrustPallet(Event::BulkTrustScoreUpdate { .. })) || - matches!( + matches!(event.event, RuntimeEvent::TrustPallet(Event::BulkTrustScoreUpdate { .. })) + || matches!( event.event, RuntimeEvent::TrustPallet(Event::AllTrustScoresUpdated { .. }) ) @@ -412,7 +412,6 @@ fn multiple_users_independent_scores() { #[test] fn trust_score_provider_trait_returns_zero_initially() { new_test_ext().execute_with(|| { - let account = 1u64; let score = TrustPallet::trust_score_of(account); assert_eq!(score, 0); @@ -422,7 +421,6 @@ fn trust_score_provider_trait_returns_zero_initially() { #[test] fn trust_score_provider_trait_returns_updated_score() { new_test_ext().execute_with(|| { - let account = 1u64; TrustPallet::update_score_for_account(&account).unwrap(); @@ -434,7 +432,6 @@ fn trust_score_provider_trait_returns_updated_score() { #[test] fn trust_score_provider_trait_multiple_users() { new_test_ext().execute_with(|| { - TrustPallet::update_score_for_account(&1u64).unwrap(); TrustPallet::update_score_for_account(&2u64).unwrap(); diff --git a/pezcumulus/teyrchains/pezpallets/welati/src/lib.rs b/pezcumulus/teyrchains/pezpallets/welati/src/lib.rs index 2db43925..f26f6519 100644 --- a/pezcumulus/teyrchains/pezpallets/welati/src/lib.rs +++ b/pezcumulus/teyrchains/pezpallets/welati/src/lib.rs @@ -928,9 +928,7 @@ pub mod pezpallet { // Create appointment process let documents: BoundedVec>, ConstU32<10>> = - vec![justification] - .try_into() - .map_err(|_| Error::::CalculationOverflow)?; + vec![justification].try_into().map_err(|_| Error::::CalculationOverflow)?; let appointment_process = AppointmentProcess { process_id, @@ -1099,9 +1097,9 @@ pub mod pezpallet { // For Parliament decisions, voter must be a parliament member match proposal.decision_type { - CollectiveDecisionType::ParliamentSimpleMajority | - CollectiveDecisionType::ParliamentSuperMajority | - CollectiveDecisionType::ParliamentAbsoluteMajority => { + CollectiveDecisionType::ParliamentSimpleMajority + | CollectiveDecisionType::ParliamentSuperMajority + | CollectiveDecisionType::ParliamentAbsoluteMajority => { // Check if voter is in parliament let members = ParliamentMembers::::get(); let is_member = members.iter().any(|m| m.account == voter); @@ -1127,12 +1125,15 @@ pub mod pezpallet { ActiveProposals::::mutate(proposal_id, |proposal_opt| { if let Some(proposal) = proposal_opt { match vote { - VoteChoice::Aye => - proposal.aye_votes = proposal.aye_votes.saturating_add(1), - VoteChoice::Nay => - proposal.nay_votes = proposal.nay_votes.saturating_add(1), - VoteChoice::Abstain => - proposal.abstain_votes = proposal.abstain_votes.saturating_add(1), + VoteChoice::Aye => { + proposal.aye_votes = proposal.aye_votes.saturating_add(1) + }, + VoteChoice::Nay => { + proposal.nay_votes = proposal.nay_votes.saturating_add(1) + }, + VoteChoice::Abstain => { + proposal.abstain_votes = proposal.abstain_votes.saturating_add(1) + }, } proposal.votes_cast = proposal.votes_cast.saturating_add(1); } @@ -1350,14 +1351,15 @@ pub mod pezpallet { winners: &[T::AccountId], ) -> Result<(), Error> { match election_type { - ElectionType::Presidential => + ElectionType::Presidential => { if let Some(winner) = winners.first() { CurrentOfficials::::insert(GovernmentPosition::Serok, winner); - }, + } + }, ElectionType::Parliamentary => { let current_block = pezframe_system::Pezpallet::::block_number(); - let term_end = current_block + - BlockNumberFor::::from(4u32 * 365u32 * 24u32 * 60u32 * 10u32); + let term_end = current_block + + BlockNumberFor::::from(4u32 * 365u32 * 24u32 * 60u32 * 10u32); let parliament_members: Result, _> = winners .iter() @@ -1382,10 +1384,11 @@ pub mod pezpallet { term_start: current_block, }); }, - ElectionType::SpeakerElection => + ElectionType::SpeakerElection => { if let Some(winner) = winners.first() { CurrentOfficials::::insert(GovernmentPosition::MeclisBaskanı, winner); - }, + } + }, _ => {}, } Ok(()) @@ -1397,15 +1400,16 @@ pub mod pezpallet { decision_type: &CollectiveDecisionType, ) -> Result> { match decision_type { - CollectiveDecisionType::ExecutiveDecision => - Ok(CurrentOfficials::::get(GovernmentPosition::Serok) == - Some(proposer.clone())), + CollectiveDecisionType::ExecutiveDecision => { + Ok(CurrentOfficials::::get(GovernmentPosition::Serok) + == Some(proposer.clone())) + }, _ => { let is_parliamentarian = ParliamentMembers::::get() .iter() .any(|member| member.account == *proposer); - let is_president = CurrentOfficials::::get(GovernmentPosition::Serok) == - Some(proposer.clone()); + let is_president = CurrentOfficials::::get(GovernmentPosition::Serok) + == Some(proposer.clone()); Ok(is_parliamentarian || is_president) }, @@ -1415,12 +1419,15 @@ pub mod pezpallet { /// Calculate voting threshold fn get_voting_threshold(decision_type: &CollectiveDecisionType) -> u32 { match decision_type { - CollectiveDecisionType::ParliamentSimpleMajority => - (T::ParliamentSize::get() / 2) + 1, - CollectiveDecisionType::ParliamentSuperMajority => - (T::ParliamentSize::get() * 2) / 3, - CollectiveDecisionType::ParliamentAbsoluteMajority => - (T::ParliamentSize::get() * 3) / 4, + CollectiveDecisionType::ParliamentSimpleMajority => { + (T::ParliamentSize::get() / 2) + 1 + }, + CollectiveDecisionType::ParliamentSuperMajority => { + (T::ParliamentSize::get() * 2) / 3 + }, + CollectiveDecisionType::ParliamentAbsoluteMajority => { + (T::ParliamentSize::get() * 3) / 4 + }, CollectiveDecisionType::ConstitutionalReview => (T::DiwanSize::get() * 2) / 3, CollectiveDecisionType::ConstitutionalUnanimous => T::DiwanSize::get(), _ => T::ParliamentSize::get() / 2 + 1, @@ -1553,10 +1560,10 @@ impl Pezpallet { /// Check if an account is any type of governance member /// Used for fee exemption in governance-related transactions pub fn is_governance_member(who: &T::AccountId) -> bool { - Self::is_serok(who) || - Self::is_parliament_member(who) || - Self::is_diwan_member(who) || - Self::is_minister(who) + Self::is_serok(who) + || Self::is_parliament_member(who) + || Self::is_diwan_member(who) + || Self::is_minister(who) } /// Check if account is Serok (President) diff --git a/pezcumulus/teyrchains/pezpallets/welati/src/migrations.rs b/pezcumulus/teyrchains/pezpallets/welati/src/migrations.rs index dbd57702..e714b88f 100644 --- a/pezcumulus/teyrchains/pezpallets/welati/src/migrations.rs +++ b/pezcumulus/teyrchains/pezpallets/welati/src/migrations.rs @@ -41,7 +41,8 @@ pub mod v1 { let elections_count = ActiveElections::::iter().count() as u64; let proposals_count = ActiveProposals::::iter().count() as u64; - let migrated = officials_count + ministers_count + elections_count + proposals_count; + let migrated = + officials_count + ministers_count + elections_count + proposals_count; // Update storage version STORAGE_VERSION.put::>(); @@ -143,9 +144,8 @@ pub mod v1 { pre_appointments_count, pre_proposals_count, pre_collective_votes_count, - ): PreUpgradeState = - Decode::decode(&mut &state[..]) - .map_err(|_| "Failed to decode pre-upgrade state")?; + ): PreUpgradeState = Decode::decode(&mut &state[..]) + .map_err(|_| "Failed to decode pre-upgrade state")?; log::info!("🔍 Post-upgrade check for pezpallet-welati"); @@ -170,19 +170,33 @@ pub mod v1 { let post_proposals_count = ActiveProposals::::iter().count() as u32; let post_collective_votes_count = CollectiveVotes::::iter().count() as u32; - log::info!(" CurrentOfficials entries: {pre_officials_count} -> {post_officials_count}"); - log::info!(" CurrentMinisters entries: {pre_ministers_count} -> {post_ministers_count}"); - log::info!(" ParliamentMembers entries: {pre_parliament_count} -> {post_parliament_count}"); + log::info!( + " CurrentOfficials entries: {pre_officials_count} -> {post_officials_count}" + ); + log::info!( + " CurrentMinisters entries: {pre_ministers_count} -> {post_ministers_count}" + ); + log::info!( + " ParliamentMembers entries: {pre_parliament_count} -> {post_parliament_count}" + ); log::info!(" DiwanMembers entries: {pre_diwan_count} -> {post_diwan_count}"); - log::info!(" AppointedOfficials entries: {pre_appointed_count} -> {post_appointed_count}"); - log::info!(" ActiveElections entries: {pre_elections_count} -> {post_elections_count}"); - log::info!(" ElectionCandidates entries: {pre_candidates_count} -> {post_candidates_count}"); + log::info!( + " AppointedOfficials entries: {pre_appointed_count} -> {post_appointed_count}" + ); + log::info!( + " ActiveElections entries: {pre_elections_count} -> {post_elections_count}" + ); + log::info!( + " ElectionCandidates entries: {pre_candidates_count} -> {post_candidates_count}" + ); log::info!(" ElectionVotes entries: {pre_votes_count} -> {post_votes_count}"); log::info!(" ElectionResults entries: {pre_results_count} -> {post_results_count}"); log::info!(" ElectoralDistrictConfig entries: {pre_districts_count} -> {post_districts_count}"); log::info!(" PendingNominations entries: {pre_nominations_count} -> {post_nominations_count}"); log::info!(" AppointmentProcesses entries: {pre_appointments_count} -> {post_appointments_count}"); - log::info!(" ActiveProposals entries: {pre_proposals_count} -> {post_proposals_count}"); + log::info!( + " ActiveProposals entries: {pre_proposals_count} -> {post_proposals_count}" + ); log::info!(" CollectiveVotes entries: {pre_collective_votes_count} -> {post_collective_votes_count}"); // Verify no data was lost diff --git a/pezcumulus/teyrchains/pezpallets/welati/src/mock.rs b/pezcumulus/teyrchains/pezpallets/welati/src/mock.rs index 60a397b0..681f16e7 100644 --- a/pezcumulus/teyrchains/pezpallets/welati/src/mock.rs +++ b/pezcumulus/teyrchains/pezpallets/welati/src/mock.rs @@ -125,7 +125,9 @@ parameter_types! { pub struct NftsBenchmarkHelper; #[cfg(feature = "runtime-benchmarks")] -impl pezpallet_nfts::BenchmarkHelper for NftsBenchmarkHelper { +impl pezpallet_nfts::BenchmarkHelper + for NftsBenchmarkHelper +{ fn collection(i: u16) -> u32 { i.into() } @@ -192,10 +194,13 @@ parameter_types! { pub struct IdentityBenchmarkHelper; #[cfg(feature = "runtime-benchmarks")] -impl pezpallet_identity::BenchmarkHelper for IdentityBenchmarkHelper { +impl pezpallet_identity::BenchmarkHelper + for IdentityBenchmarkHelper +{ fn sign_message(message: &[u8]) -> (UintAuthorityId, TestSignature) { let signer = UintAuthorityId(0); - let signature = ::sign(&signer, &message.to_vec()).unwrap(); + let signature = + ::sign(&signer, &message.to_vec()).unwrap(); (signer, signature) } } diff --git a/pezcumulus/teyrchains/pezpallets/welati/src/types.rs b/pezcumulus/teyrchains/pezpallets/welati/src/types.rs index daa131e0..540484c0 100644 --- a/pezcumulus/teyrchains/pezpallets/welati/src/types.rs +++ b/pezcumulus/teyrchains/pezpallets/welati/src/types.rs @@ -1339,31 +1339,33 @@ impl OfficialRoleInfo for OfficialRole { fn nominating_minister(&self) -> MinisterRole { match self { - OfficialRole::Dadger | - OfficialRole::Dozger | - OfficialRole::Hiquqnas | - OfficialRole::Noter => MinisterRole::AdvaletWeziri, + OfficialRole::Dadger + | OfficialRole::Dozger + | OfficialRole::Hiquqnas + | OfficialRole::Noter => MinisterRole::AdvaletWeziri, - OfficialRole::Xezinedar | OfficialRole::Bacgir | OfficialRole::GerinendeyeCavkaniye => - MinisterRole::XezineWeziri, + OfficialRole::Xezinedar | OfficialRole::Bacgir | OfficialRole::GerinendeyeCavkaniye => { + MinisterRole::XezineWeziri + }, - OfficialRole::OperatoreTore | - OfficialRole::PisporeEwlehiyaSiber | - OfficialRole::GerinendeyeDaneye => MinisterRole::TeknolojîWeziri, + OfficialRole::OperatoreTore + | OfficialRole::PisporeEwlehiyaSiber + | OfficialRole::GerinendeyeDaneye => MinisterRole::TeknolojîWeziri, OfficialRole::Berdevk | OfficialRole::Qeydkar => MinisterRole::NavxweWeziri, - OfficialRole::Balyoz | OfficialRole::Navbeynkar | OfficialRole::ParezvaneCandi => - MinisterRole::DerveWeziri, + OfficialRole::Balyoz | OfficialRole::Navbeynkar | OfficialRole::ParezvaneCandi => { + MinisterRole::DerveWeziri + }, OfficialRole::Mufetis | OfficialRole::KaliteKontrolker => MinisterRole::DenetimWeziri, OfficialRole::Bazargan | OfficialRole::RêvebereProjeyê => MinisterRole::AbûrîWeziri, - OfficialRole::Feqi | - OfficialRole::Perwerdekar | - OfficialRole::Rewsenbir | - OfficialRole::Mamoste => MinisterRole::PerwerdeDiyanetWeziri, + OfficialRole::Feqi + | OfficialRole::Perwerdekar + | OfficialRole::Rewsenbir + | OfficialRole::Mamoste => MinisterRole::PerwerdeDiyanetWeziri, // Mela özel durum - doğrudan Serok atar OfficialRole::Mela => MinisterRole::AdvaletWeziri, // Placeholder @@ -1373,11 +1375,11 @@ impl OfficialRoleInfo for OfficialRole { fn requires_parliament_approval(&self) -> bool { match self { // Yüksek düzey pozisyonlar Parlamento onayı gerektirir - OfficialRole::Dadger | - OfficialRole::Xezinedar | - OfficialRole::PisporeEwlehiyaSiber | - OfficialRole::Mufetis | - OfficialRole::Balyoz => true, + OfficialRole::Dadger + | OfficialRole::Xezinedar + | OfficialRole::PisporeEwlehiyaSiber + | OfficialRole::Mufetis + | OfficialRole::Balyoz => true, // Diğerleri sadece Serok onayı _ => false, } diff --git a/pezcumulus/teyrchains/runtimes/assets/asset-hub-pezkuwichain/src/genesis_config_presets.rs b/pezcumulus/teyrchains/runtimes/assets/asset-hub-pezkuwichain/src/genesis_config_presets.rs index 6e7f78dd..dc432814 100644 --- a/pezcumulus/teyrchains/runtimes/assets/asset-hub-pezkuwichain/src/genesis_config_presets.rs +++ b/pezcumulus/teyrchains/runtimes/assets/asset-hub-pezkuwichain/src/genesis_config_presets.rs @@ -101,7 +101,10 @@ fn asset_hub_pezkuwichain_genesis( ) -> serde_json::Value { // Verify total PEZ minted at genesis equals PEZ_TOTAL_SUPPLY (5 billion) debug_assert_eq!( - PEZ_TREASURY_ALLOCATION + PEZ_REWARDS_POOL + PEZ_FOUNDER_ALLOCATION + PEZ_PRESALE_ALLOCATION, + PEZ_TREASURY_ALLOCATION + + PEZ_REWARDS_POOL + + PEZ_FOUNDER_ALLOCATION + + PEZ_PRESALE_ALLOCATION, PEZ_TOTAL_SUPPLY, "PEZ genesis allocations must equal total supply" ); diff --git a/pezcumulus/teyrchains/runtimes/assets/asset-hub-pezkuwichain/src/lib.rs b/pezcumulus/teyrchains/runtimes/assets/asset-hub-pezkuwichain/src/lib.rs index b7b7a2e1..347620cc 100644 --- a/pezcumulus/teyrchains/runtimes/assets/asset-hub-pezkuwichain/src/lib.rs +++ b/pezcumulus/teyrchains/runtimes/assets/asset-hub-pezkuwichain/src/lib.rs @@ -609,99 +609,99 @@ impl InstanceFilter for ProxyType { ProxyType::Any => true, ProxyType::NonTransfer => !matches!( c, - RuntimeCall::Balances { .. } | - RuntimeCall::Assets { .. } | - RuntimeCall::NftFractionalization { .. } | - RuntimeCall::Nfts { .. } | - RuntimeCall::Uniques { .. } + RuntimeCall::Balances { .. } + | RuntimeCall::Assets { .. } + | RuntimeCall::NftFractionalization { .. } + | RuntimeCall::Nfts { .. } + | RuntimeCall::Uniques { .. } ), ProxyType::CancelProxy => matches!( c, - RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Assets => { matches!( c, - RuntimeCall::Assets { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } | - RuntimeCall::NftFractionalization { .. } | - RuntimeCall::Nfts { .. } | - RuntimeCall::Uniques { .. } + RuntimeCall::Assets { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } + | RuntimeCall::NftFractionalization { .. } + | RuntimeCall::Nfts { .. } + | RuntimeCall::Uniques { .. } ) }, ProxyType::AssetOwner => matches!( c, - RuntimeCall::Assets(TrustBackedAssetsCall::create { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::start_destroy { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::destroy_accounts { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::destroy_approvals { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::finish_destroy { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::transfer_ownership { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::set_team { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::set_metadata { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::clear_metadata { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::set_min_balance { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::create { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::destroy { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::redeposit { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::transfer_ownership { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_team { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_collection_max_supply { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::lock_collection { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::create { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::destroy { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::transfer_ownership { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::set_team { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::set_metadata { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::set_attribute { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::set_collection_metadata { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::clear_metadata { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::clear_attribute { .. }) | - RuntimeCall::Uniques( + RuntimeCall::Assets(TrustBackedAssetsCall::create { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::start_destroy { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::destroy_accounts { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::destroy_approvals { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::finish_destroy { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::transfer_ownership { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::set_team { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::set_metadata { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::clear_metadata { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::set_min_balance { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::create { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::destroy { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::redeposit { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::transfer_ownership { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_team { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_collection_max_supply { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::lock_collection { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::create { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::destroy { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::transfer_ownership { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::set_team { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::set_metadata { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::set_attribute { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::set_collection_metadata { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::clear_metadata { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::clear_attribute { .. }) + | RuntimeCall::Uniques( pezpallet_uniques::Call::clear_collection_metadata { .. } - ) | RuntimeCall::Uniques(pezpallet_uniques::Call::set_collection_max_supply { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + ) | RuntimeCall::Uniques(pezpallet_uniques::Call::set_collection_max_supply { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::AssetManager => matches!( c, - RuntimeCall::Assets(TrustBackedAssetsCall::mint { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::burn { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::freeze { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::block { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::thaw { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::freeze_asset { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::thaw_asset { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::touch_other { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::refund_other { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::force_mint { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::update_mint_settings { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::mint_pre_signed { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_attributes_pre_signed { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::lock_item_transfer { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::unlock_item_transfer { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::lock_item_properties { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_metadata { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::clear_metadata { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_collection_metadata { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::clear_collection_metadata { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::mint { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::burn { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::freeze { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::thaw { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::freeze_collection { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::thaw_collection { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Assets(TrustBackedAssetsCall::mint { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::burn { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::freeze { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::block { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::thaw { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::freeze_asset { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::thaw_asset { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::touch_other { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::refund_other { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::force_mint { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::update_mint_settings { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::mint_pre_signed { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_attributes_pre_signed { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::lock_item_transfer { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::unlock_item_transfer { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::lock_item_properties { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_metadata { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::clear_metadata { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_collection_metadata { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::clear_collection_metadata { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::mint { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::burn { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::freeze { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::thaw { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::freeze_collection { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::thaw_collection { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Collator => matches!( c, - RuntimeCall::CollatorSelection { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::CollatorSelection { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), } } diff --git a/pezcumulus/teyrchains/runtimes/assets/asset-hub-pezkuwichain/src/weights/xcm/mod.rs b/pezcumulus/teyrchains/runtimes/assets/asset-hub-pezkuwichain/src/weights/xcm/mod.rs index 2c04b11e..53131f42 100644 --- a/pezcumulus/teyrchains/runtimes/assets/asset-hub-pezkuwichain/src/weights/xcm/mod.rs +++ b/pezcumulus/teyrchains/runtimes/assets/asset-hub-pezkuwichain/src/weights/xcm/mod.rs @@ -44,12 +44,14 @@ impl WeighAssets for AssetFilter { WildFungibility::Fungible => weight, // Magic number 2 has to do with the fact that we could have up to 2 times // MaxAssetsIntoHolding in the worst-case scenario. - WildFungibility::NonFungible => - weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64), + WildFungibility::NonFungible => { + weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64) + }, }, AllCounted(count) => weight.saturating_mul(MAX_ASSETS.min((*count as u64).max(1))), - AllOfCounted { count, .. } => - weight.saturating_mul(MAX_ASSETS.min((*count as u64).max(1))), + AllOfCounted { count, .. } => { + weight.saturating_mul(MAX_ASSETS.min((*count as u64).max(1))) + }, }, } } diff --git a/pezcumulus/teyrchains/runtimes/assets/asset-hub-zagros/src/lib.rs b/pezcumulus/teyrchains/runtimes/assets/asset-hub-zagros/src/lib.rs index 86feb785..23eff436 100644 --- a/pezcumulus/teyrchains/runtimes/assets/asset-hub-zagros/src/lib.rs +++ b/pezcumulus/teyrchains/runtimes/assets/asset-hub-zagros/src/lib.rs @@ -722,10 +722,10 @@ impl InstanceFilter for ProxyType { fn filter(&self, c: &RuntimeCall) -> bool { match self { ProxyType::Any => true, - ProxyType::OldSudoBalances | - ProxyType::OldIdentityJudgement | - ProxyType::OldAuction | - ProxyType::OldParaRegistration => false, + ProxyType::OldSudoBalances + | ProxyType::OldIdentityJudgement + | ProxyType::OldAuction + | ProxyType::OldParaRegistration => false, ProxyType::NonTransfer => !matches!( c, RuntimeCall::Balances { .. } | @@ -744,109 +744,109 @@ impl InstanceFilter for ProxyType { ), ProxyType::CancelProxy => matches!( c, - RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Assets => { matches!( c, - RuntimeCall::Assets { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } | - RuntimeCall::NftFractionalization { .. } | - RuntimeCall::Nfts { .. } | - RuntimeCall::Uniques { .. } + RuntimeCall::Assets { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } + | RuntimeCall::NftFractionalization { .. } + | RuntimeCall::Nfts { .. } + | RuntimeCall::Uniques { .. } ) }, ProxyType::AssetOwner => matches!( c, - RuntimeCall::Assets(TrustBackedAssetsCall::create { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::start_destroy { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::destroy_accounts { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::destroy_approvals { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::finish_destroy { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::transfer_ownership { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::set_team { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::set_metadata { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::clear_metadata { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::set_min_balance { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::create { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::destroy { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::redeposit { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::transfer_ownership { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_team { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_collection_max_supply { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::lock_collection { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::create { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::destroy { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::transfer_ownership { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::set_team { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::set_metadata { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::set_attribute { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::set_collection_metadata { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::clear_metadata { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::clear_attribute { .. }) | - RuntimeCall::Uniques( + RuntimeCall::Assets(TrustBackedAssetsCall::create { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::start_destroy { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::destroy_accounts { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::destroy_approvals { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::finish_destroy { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::transfer_ownership { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::set_team { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::set_metadata { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::clear_metadata { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::set_min_balance { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::create { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::destroy { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::redeposit { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::transfer_ownership { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_team { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_collection_max_supply { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::lock_collection { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::create { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::destroy { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::transfer_ownership { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::set_team { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::set_metadata { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::set_attribute { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::set_collection_metadata { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::clear_metadata { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::clear_attribute { .. }) + | RuntimeCall::Uniques( pezpallet_uniques::Call::clear_collection_metadata { .. } - ) | RuntimeCall::Uniques(pezpallet_uniques::Call::set_collection_max_supply { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + ) | RuntimeCall::Uniques(pezpallet_uniques::Call::set_collection_max_supply { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::AssetManager => matches!( c, - RuntimeCall::Assets(TrustBackedAssetsCall::mint { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::burn { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::freeze { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::block { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::thaw { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::freeze_asset { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::thaw_asset { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::touch_other { .. }) | - RuntimeCall::Assets(TrustBackedAssetsCall::refund_other { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::force_mint { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::update_mint_settings { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::mint_pre_signed { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_attributes_pre_signed { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::lock_item_transfer { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::unlock_item_transfer { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::lock_item_properties { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_metadata { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::clear_metadata { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::set_collection_metadata { .. }) | - RuntimeCall::Nfts(pezpallet_nfts::Call::clear_collection_metadata { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::mint { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::burn { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::freeze { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::thaw { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::freeze_collection { .. }) | - RuntimeCall::Uniques(pezpallet_uniques::Call::thaw_collection { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Assets(TrustBackedAssetsCall::mint { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::burn { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::freeze { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::block { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::thaw { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::freeze_asset { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::thaw_asset { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::touch_other { .. }) + | RuntimeCall::Assets(TrustBackedAssetsCall::refund_other { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::force_mint { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::update_mint_settings { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::mint_pre_signed { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_attributes_pre_signed { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::lock_item_transfer { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::unlock_item_transfer { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::lock_item_properties { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_metadata { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::clear_metadata { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::set_collection_metadata { .. }) + | RuntimeCall::Nfts(pezpallet_nfts::Call::clear_collection_metadata { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::mint { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::burn { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::freeze { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::thaw { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::freeze_collection { .. }) + | RuntimeCall::Uniques(pezpallet_uniques::Call::thaw_collection { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Collator => matches!( c, - RuntimeCall::CollatorSelection { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::CollatorSelection { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), // New variants introduced by the Asset Hub Migration from the Relay Chain. ProxyType::Governance => matches!( c, - RuntimeCall::Treasury(..) | - RuntimeCall::Utility(..) | - RuntimeCall::ConvictionVoting(..) | - RuntimeCall::Referenda(..) | - RuntimeCall::Whitelist(..) + RuntimeCall::Treasury(..) + | RuntimeCall::Utility(..) + | RuntimeCall::ConvictionVoting(..) + | RuntimeCall::Referenda(..) + | RuntimeCall::Whitelist(..) ), ProxyType::Staking => { matches!( c, - RuntimeCall::Staking(..) | - RuntimeCall::Session(..) | - RuntimeCall::Utility(..) | - RuntimeCall::NominationPools(..) | - RuntimeCall::VoterList(..) + RuntimeCall::Staking(..) + | RuntimeCall::Session(..) + | RuntimeCall::Utility(..) + | RuntimeCall::NominationPools(..) + | RuntimeCall::VoterList(..) ) }, ProxyType::NominationPools => { @@ -864,10 +864,10 @@ impl InstanceFilter for ProxyType { (ProxyType::Assets, ProxyType::AssetManager) => true, ( ProxyType::NonTransfer, - ProxyType::Collator | - ProxyType::Governance | - ProxyType::Staking | - ProxyType::NominationPools, + ProxyType::Collator + | ProxyType::Governance + | ProxyType::Staking + | ProxyType::NominationPools, ) => true, _ => false, } diff --git a/pezcumulus/teyrchains/runtimes/assets/asset-hub-zagros/src/weights/xcm/mod.rs b/pezcumulus/teyrchains/runtimes/assets/asset-hub-zagros/src/weights/xcm/mod.rs index 5085da8e..8f7a214a 100644 --- a/pezcumulus/teyrchains/runtimes/assets/asset-hub-zagros/src/weights/xcm/mod.rs +++ b/pezcumulus/teyrchains/runtimes/assets/asset-hub-zagros/src/weights/xcm/mod.rs @@ -47,12 +47,14 @@ impl WeighAssets for AssetFilter { WildFungibility::Fungible => weight, // Magic number 2 has to do with the fact that we could have up to 2 times // MaxAssetsIntoHolding in the worst-case scenario. - WildFungibility::NonFungible => - weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64), + WildFungibility::NonFungible => { + weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64) + }, }, AllCounted(count) => weight.saturating_mul(MAX_ASSETS.min((*count as u64).max(1))), - AllOfCounted { count, .. } => - weight.saturating_mul(MAX_ASSETS.min((*count as u64).max(1))), + AllOfCounted { count, .. } => { + weight.saturating_mul(MAX_ASSETS.min((*count as u64).max(1))) + }, }, } } diff --git a/pezcumulus/teyrchains/runtimes/assets/asset-hub-zagros/src/xcm_config.rs b/pezcumulus/teyrchains/runtimes/assets/asset-hub-zagros/src/xcm_config.rs index c67fdffc..2636d23d 100644 --- a/pezcumulus/teyrchains/runtimes/assets/asset-hub-zagros/src/xcm_config.rs +++ b/pezcumulus/teyrchains/runtimes/assets/asset-hub-zagros/src/xcm_config.rs @@ -284,9 +284,9 @@ impl Contains for FellowshipEntities { fn contains(location: &Location) -> bool { matches!( location.unpack(), - (1, [Teyrchain(COLLECTIVES_ID), Plurality { id: BodyId::Technical, .. }]) | - (1, [Teyrchain(COLLECTIVES_ID), PalletInstance(64)]) | - (1, [Teyrchain(COLLECTIVES_ID), PalletInstance(65)]) + (1, [Teyrchain(COLLECTIVES_ID), Plurality { id: BodyId::Technical, .. }]) + | (1, [Teyrchain(COLLECTIVES_ID), PalletInstance(64)]) + | (1, [Teyrchain(COLLECTIVES_ID), PalletInstance(65)]) ) } } diff --git a/pezcumulus/teyrchains/runtimes/assets/common/src/migrations.rs b/pezcumulus/teyrchains/runtimes/assets/common/src/migrations.rs index e3e464e5..79ee603c 100644 --- a/pezcumulus/teyrchains/runtimes/assets/common/src/migrations.rs +++ b/pezcumulus/teyrchains/runtimes/assets/common/src/migrations.rs @@ -113,8 +113,9 @@ pub mod foreign_assets_reserves { // At first, start migrating assets. None => Self::asset_step(None), // Migrate any remaining assets. - Some(MigrationState::Asset(maybe_last_asset)) => - Self::asset_step(Some(maybe_last_asset)), + Some(MigrationState::Asset(maybe_last_asset)) => { + Self::asset_step(Some(maybe_last_asset)) + }, // After the last asset, migration is finished. Some(MigrationState::Finished) => { tracing::info!(target: "runtime::ForeignAssetsReservesMigration", "migration finished"); diff --git a/pezcumulus/teyrchains/runtimes/assets/test-utils/src/lib.rs b/pezcumulus/teyrchains/runtimes/assets/test-utils/src/lib.rs index f3747523..549ffa8c 100644 --- a/pezcumulus/teyrchains/runtimes/assets/test-utils/src/lib.rs +++ b/pezcumulus/teyrchains/runtimes/assets/test-utils/src/lib.rs @@ -73,8 +73,9 @@ pub(crate) fn assert_matches_reserve_asset_deposited_instructions - Ok(()), + DepositAsset { assets: _, beneficiary } if beneficiary == expected_beneficiary => { + Ok(()) + }, _ => Err(ProcessMessageError::BadFormat), }) .expect("expected instruction DepositAsset"); diff --git a/pezcumulus/teyrchains/runtimes/assets/test-utils/src/test_cases.rs b/pezcumulus/teyrchains/runtimes/assets/test-utils/src/test_cases.rs index cc472a53..fa38cddc 100644 --- a/pezcumulus/teyrchains/runtimes/assets/test-utils/src/test_cases.rs +++ b/pezcumulus/teyrchains/runtimes/assets/test-utils/src/test_cases.rs @@ -615,9 +615,9 @@ pub fn teleports_for_foreign_assets_works< ); let asset_to_teleport_away = asset_minimum_asset_balance * 3; assert!( - asset_to_teleport_away < - (target_account_balance_before_teleport - - asset_minimum_asset_balance.into()) + asset_to_teleport_away + < (target_account_balance_before_teleport + - asset_minimum_asset_balance.into()) .into() ); @@ -1190,12 +1190,12 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_teyrchain_assets_wor .with_session_keys(collator_session_keys.session_keys()) .with_balances(vec![( foreign_creator_as_account_id.clone(), - existential_deposit + - asset_deposit + - metadata_deposit_base + - metadata_deposit_per_byte_eta + - buy_execution_fee_amount.into() + - buy_execution_fee_amount.into(), + existential_deposit + + asset_deposit + + metadata_deposit_base + + metadata_deposit_per_byte_eta + + buy_execution_fee_amount.into() + + buy_execution_fee_amount.into(), )]) .with_tracing() .build() @@ -1209,11 +1209,11 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_teyrchain_assets_wor >::free_balance( &foreign_creator_as_account_id ), - existential_deposit + - asset_deposit + metadata_deposit_base + - metadata_deposit_per_byte_eta + - buy_execution_fee_amount.into() + - buy_execution_fee_amount.into() + existential_deposit + + asset_deposit + metadata_deposit_base + + metadata_deposit_per_byte_eta + + buy_execution_fee_amount.into() + + buy_execution_fee_amount.into() ); additional_checks_before(); @@ -1549,9 +1549,9 @@ pub fn reserve_transfer_native_asset_to_non_teleport_para_works< // then verify the arithmetics check out on final balance. let delivery_fees_buffer = 40_000_000_000u128; // drip 2xED + transfer_amount + delivery_fees_buffer to Alice account - let alice_account_init_balance = existential_deposit.saturating_mul(2.into()) + - balance_to_transfer.into() + - delivery_fees_buffer.into(); + let alice_account_init_balance = existential_deposit.saturating_mul(2.into()) + + balance_to_transfer.into() + + delivery_fees_buffer.into(); let _ = >::deposit_creating( &alice_account, alice_account_init_balance, @@ -1565,9 +1565,9 @@ pub fn reserve_transfer_native_asset_to_non_teleport_para_works< // we just check here, that user retains enough balance after withdrawal // and also we check if `balance_to_transfer` is more than `existential_deposit`, assert!( - (>::free_balance(&alice_account) - - balance_to_transfer.into()) >= - existential_deposit + (>::free_balance(&alice_account) + - balance_to_transfer.into()) + >= existential_deposit ); // SA has just ED assert_eq!( @@ -1609,8 +1609,9 @@ pub fn reserve_transfer_native_asset_to_non_teleport_para_works< .into_iter() .filter_map(|e| unwrap_xcmp_queue_event(e.event.encode())) .find_map(|e| match e { - pezcumulus_pezpallet_xcmp_queue::Event::XcmpMessageSent { message_hash } => - Some(message_hash), + pezcumulus_pezpallet_xcmp_queue::Event::XcmpMessageSent { message_hash } => { + Some(message_hash) + }, _ => None, }); diff --git a/pezcumulus/teyrchains/runtimes/assets/test-utils/src/test_cases_over_bridge.rs b/pezcumulus/teyrchains/runtimes/assets/test-utils/src/test_cases_over_bridge.rs index e0cd369e..7b1b9a6e 100644 --- a/pezcumulus/teyrchains/runtimes/assets/test-utils/src/test_cases_over_bridge.rs +++ b/pezcumulus/teyrchains/runtimes/assets/test-utils/src/test_cases_over_bridge.rs @@ -153,9 +153,9 @@ pub fn limited_reserve_transfer_assets_for_native_asset_works< // we just check here, that user retains enough balance after withdrawal // and also we check if `balance_to_transfer` is more than `existential_deposit`, assert!( - (>::free_balance(&alice_account) - - balance_to_transfer.into()) >= - existential_deposit + (>::free_balance(&alice_account) + - balance_to_transfer.into()) + >= existential_deposit ); // SA has just ED assert_eq!( @@ -220,8 +220,9 @@ pub fn limited_reserve_transfer_assets_for_native_asset_works< .into_iter() .filter_map(|e| unwrap_xcmp_queue_event(e.event.encode())) .find_map(|e| match e { - pezcumulus_pezpallet_xcmp_queue::Event::XcmpMessageSent { message_hash } => - Some(message_hash), + pezcumulus_pezpallet_xcmp_queue::Event::XcmpMessageSent { message_hash } => { + Some(message_hash) + }, _ => None, }); @@ -268,7 +269,9 @@ pub fn limited_reserve_transfer_assets_for_native_asset_works< // explicit unpaid execution on BridgeHub) UnpaidExecution { weight_limit, check_origin } if weight_limit == &Unlimited && check_origin.is_none() => - Ok(()), + { + Ok(()) + }, _ => Err(ProcessMessageError::BadFormat), }) .expect("contains UnpaidExecution") @@ -322,8 +325,8 @@ pub fn limited_reserve_transfer_assets_for_native_asset_works< let delivery_fees_account_balance_after = >::free_balance(&delivery_fees_account); assert!( - delivery_fees_account_balance_after - delivery_fees.into() >= - delivery_fees_account_balance_before + delivery_fees_account_balance_after - delivery_fees.into() + >= delivery_fees_account_balance_before ); } }) diff --git a/pezcumulus/teyrchains/runtimes/bridge-hubs/bridge-hub-pezkuwichain/src/weights/xcm/mod.rs b/pezcumulus/teyrchains/runtimes/bridge-hubs/bridge-hub-pezkuwichain/src/weights/xcm/mod.rs index 4cc0dad0..0697aacf 100644 --- a/pezcumulus/teyrchains/runtimes/bridge-hubs/bridge-hub-pezkuwichain/src/weights/xcm/mod.rs +++ b/pezcumulus/teyrchains/runtimes/bridge-hubs/bridge-hub-pezkuwichain/src/weights/xcm/mod.rs @@ -44,8 +44,9 @@ impl WeighAssets for AssetFilter { WildFungibility::Fungible => weight, // Magic number 2 has to do with the fact that we could have up to 2 times // MaxAssetsIntoHolding in the worst-case scenario. - WildFungibility::NonFungible => - weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64), + WildFungibility::NonFungible => { + weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64) + }, }, AllCounted(count) => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), AllOfCounted { count, .. } => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), diff --git a/pezcumulus/teyrchains/runtimes/bridge-hubs/bridge-hub-zagros/src/bridge_to_ethereum_config.rs b/pezcumulus/teyrchains/runtimes/bridge-hubs/bridge-hub-zagros/src/bridge_to_ethereum_config.rs index 8bbd92df..edd725c8 100644 --- a/pezcumulus/teyrchains/runtimes/bridge-hubs/bridge-hub-zagros/src/bridge_to_ethereum_config.rs +++ b/pezcumulus/teyrchains/runtimes/bridge-hubs/bridge-hub-zagros/src/bridge_to_ethereum_config.rs @@ -302,8 +302,9 @@ pub struct AllowFromEthereumFrontend; impl Contains for AllowFromEthereumFrontend { fn contains(location: &Location) -> bool { match location.unpack() { - (1, [Teyrchain(para_id), PalletInstance(index)]) => - return *para_id == ASSET_HUB_ID && *index == FRONTEND_PALLET_INDEX, + (1, [Teyrchain(para_id), PalletInstance(index)]) => { + return *para_id == ASSET_HUB_ID && *index == FRONTEND_PALLET_INDEX + }, _ => false, } } diff --git a/pezcumulus/teyrchains/runtimes/bridge-hubs/bridge-hub-zagros/src/weights/xcm/mod.rs b/pezcumulus/teyrchains/runtimes/bridge-hubs/bridge-hub-zagros/src/weights/xcm/mod.rs index 297ab815..c2c20e9e 100644 --- a/pezcumulus/teyrchains/runtimes/bridge-hubs/bridge-hub-zagros/src/weights/xcm/mod.rs +++ b/pezcumulus/teyrchains/runtimes/bridge-hubs/bridge-hub-zagros/src/weights/xcm/mod.rs @@ -45,8 +45,9 @@ impl WeighAssets for AssetFilter { WildFungibility::Fungible => weight, // Magic number 2 has to do with the fact that we could have up to 2 times // MaxAssetsIntoHolding in the worst-case scenario. - WildFungibility::NonFungible => - weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64), + WildFungibility::NonFungible => { + weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64) + }, }, AllCounted(count) => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), AllOfCounted { count, .. } => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), diff --git a/pezcumulus/teyrchains/runtimes/bridge-hubs/common/src/barriers.rs b/pezcumulus/teyrchains/runtimes/bridge-hubs/common/src/barriers.rs index 3b2aaafa..53211bf1 100644 --- a/pezcumulus/teyrchains/runtimes/bridge-hubs/common/src/barriers.rs +++ b/pezcumulus/teyrchains/runtimes/bridge-hubs/common/src/barriers.rs @@ -47,8 +47,9 @@ where message.matcher().match_next_inst_while( |_| true, |inst| match inst { - ExportMessage { network, .. } if ToGlobalConsensus::contains(network) => - Err(ProcessMessageError::Unsupported), + ExportMessage { network, .. } if ToGlobalConsensus::contains(network) => { + Err(ProcessMessageError::Unsupported) + }, _ => Ok(ControlFlow::Continue(())), }, )?; diff --git a/pezcumulus/teyrchains/runtimes/bridge-hubs/common/src/message_queue.rs b/pezcumulus/teyrchains/runtimes/bridge-hubs/common/src/message_queue.rs index 50bad1bc..474feacc 100644 --- a/pezcumulus/teyrchains/runtimes/bridge-hubs/common/src/message_queue.rs +++ b/pezcumulus/teyrchains/runtimes/bridge-hubs/common/src/message_queue.rs @@ -122,8 +122,9 @@ where ) -> Result { use AggregateMessageOrigin::*; match origin { - Here | Parent | Sibling(_) => - XcmpProcessor::process_message(message, origin, meter, id), + Here | Parent | Sibling(_) => { + XcmpProcessor::process_message(message, origin, meter, id) + }, Snowbridge(_) => SnowbridgeProcessor::process_message(message, origin, meter, id), SnowbridgeV2(_) => Err(ProcessMessageError::Unsupported), } @@ -155,8 +156,9 @@ where ) -> Result { use AggregateMessageOrigin::*; match origin { - Here | Parent | Sibling(_) => - XcmpProcessor::process_message(message, origin, meter, id), + Here | Parent | Sibling(_) => { + XcmpProcessor::process_message(message, origin, meter, id) + }, Snowbridge(_) => SnowbridgeProcessor::process_message(message, origin, meter, id), SnowbridgeV2(_) => SnowbridgeProcessorV2::process_message(message, origin, meter, id), } diff --git a/pezcumulus/teyrchains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs b/pezcumulus/teyrchains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs index 25cad3ed..efc85f3b 100644 --- a/pezcumulus/teyrchains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs +++ b/pezcumulus/teyrchains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs @@ -303,8 +303,8 @@ pub fn relayed_incoming_message_works( // value here is tricky - there are several transaction payment pallets and we don't // want to introduce additional bounds and traits here just for that, so let's just // select some presumably large value - core::cmp::max::(Runtime::ExistentialDeposit::get(), 1u32.into()) * - 100_000_000u32.into(), + core::cmp::max::(Runtime::ExistentialDeposit::get(), 1u32.into()) + * 100_000_000u32.into(), )], || { let mut alice = [0u8; 32]; @@ -445,8 +445,8 @@ pub(crate) mod for_pallet_xcm_bridge_hub { let buy_execution_fee_amount = 5_000_000_000_000_u128; let buy_execution_fee = (TokenLocation::get(), buy_execution_fee_amount).into(); - let balance_needed = ::ExistentialDeposit::get() + - buy_execution_fee_amount.into(); + let balance_needed = ::ExistentialDeposit::get() + + buy_execution_fee_amount.into(); let source_account_id = LocationToAccountId::convert_location(&source).expect("valid location"); let _ = >::mint_into( @@ -563,8 +563,8 @@ pub(crate) mod for_pallet_xcm_bridge_hub { let buy_execution_fee_amount = 2_500_000_000_000_u128; let buy_execution_fee = (TokenLocation::get(), buy_execution_fee_amount).into(); - let balance_needed = ::ExistentialDeposit::get() + - buy_execution_fee_amount.into(); + let balance_needed = ::ExistentialDeposit::get() + + buy_execution_fee_amount.into(); let source_account_id = LocationToAccountId::convert_location(&expected_source).expect("valid location"); let _ = >::mint_into( diff --git a/pezcumulus/teyrchains/runtimes/collectives/collectives-zagros/src/lib.rs b/pezcumulus/teyrchains/runtimes/collectives/collectives-zagros/src/lib.rs index a6a448a1..d874ba99 100644 --- a/pezcumulus/teyrchains/runtimes/collectives/collectives-zagros/src/lib.rs +++ b/pezcumulus/teyrchains/runtimes/collectives/collectives-zagros/src/lib.rs @@ -332,49 +332,49 @@ impl InstanceFilter for ProxyType { ProxyType::NonTransfer => !matches!(c, RuntimeCall::Balances { .. }), ProxyType::CancelProxy => matches!( c, - RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Collator => matches!( c, - RuntimeCall::CollatorSelection { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::CollatorSelection { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Alliance => matches!( c, - RuntimeCall::AllianceMotion { .. } | - RuntimeCall::Alliance { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::AllianceMotion { .. } + | RuntimeCall::Alliance { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Fellowship => matches!( c, - RuntimeCall::FellowshipCollective { .. } | - RuntimeCall::FellowshipReferenda { .. } | - RuntimeCall::FellowshipCore { .. } | - RuntimeCall::FellowshipSalary { .. } | - RuntimeCall::FellowshipTreasury { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::FellowshipCollective { .. } + | RuntimeCall::FellowshipReferenda { .. } + | RuntimeCall::FellowshipCore { .. } + | RuntimeCall::FellowshipSalary { .. } + | RuntimeCall::FellowshipTreasury { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Ambassador => matches!( c, - RuntimeCall::AmbassadorCollective { .. } | - RuntimeCall::AmbassadorReferenda { .. } | - RuntimeCall::AmbassadorContent { .. } | - RuntimeCall::AmbassadorCore { .. } | - RuntimeCall::AmbassadorSalary { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::AmbassadorCollective { .. } + | RuntimeCall::AmbassadorReferenda { .. } + | RuntimeCall::AmbassadorContent { .. } + | RuntimeCall::AmbassadorCore { .. } + | RuntimeCall::AmbassadorSalary { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Secretary => matches!( c, - RuntimeCall::SecretaryCollective { .. } | - RuntimeCall::SecretarySalary { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::SecretaryCollective { .. } + | RuntimeCall::SecretarySalary { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), } } diff --git a/pezcumulus/teyrchains/runtimes/collectives/collectives-zagros/src/weights/xcm/mod.rs b/pezcumulus/teyrchains/runtimes/collectives/collectives-zagros/src/weights/xcm/mod.rs index 76954761..aed68c48 100644 --- a/pezcumulus/teyrchains/runtimes/collectives/collectives-zagros/src/weights/xcm/mod.rs +++ b/pezcumulus/teyrchains/runtimes/collectives/collectives-zagros/src/weights/xcm/mod.rs @@ -44,8 +44,9 @@ impl WeighAssets for AssetFilter { WildFungibility::Fungible => weight, // Magic number 2 has to do with the fact that we could have up to 2 times // MaxAssetsIntoHolding in the worst-case scenario. - WildFungibility::NonFungible => - weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64), + WildFungibility::NonFungible => { + weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64) + }, }, AllCounted(count) => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), AllOfCounted { count, .. } => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), diff --git a/pezcumulus/teyrchains/runtimes/coretime/coretime-pezkuwichain/src/lib.rs b/pezcumulus/teyrchains/runtimes/coretime/coretime-pezkuwichain/src/lib.rs index a24ef6b3..495e3d01 100644 --- a/pezcumulus/teyrchains/runtimes/coretime/coretime-pezkuwichain/src/lib.rs +++ b/pezcumulus/teyrchains/runtimes/coretime/coretime-pezkuwichain/src/lib.rs @@ -524,39 +524,39 @@ impl InstanceFilter for ProxyType { ), ProxyType::CancelProxy => matches!( c, - RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Broker => { matches!( c, - RuntimeCall::Broker { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Broker { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ) }, ProxyType::CoretimeRenewer => { matches!( c, - RuntimeCall::Broker(pezpallet_broker::Call::renew { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Broker(pezpallet_broker::Call::renew { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ) }, ProxyType::OnDemandPurchaser => { matches!( c, - RuntimeCall::Broker(pezpallet_broker::Call::purchase_credit { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Broker(pezpallet_broker::Call::purchase_credit { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ) }, ProxyType::Collator => matches!( c, - RuntimeCall::CollatorSelection { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::CollatorSelection { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), } } diff --git a/pezcumulus/teyrchains/runtimes/coretime/coretime-pezkuwichain/src/weights/xcm/mod.rs b/pezcumulus/teyrchains/runtimes/coretime/coretime-pezkuwichain/src/weights/xcm/mod.rs index 628740fe..df42aecf 100644 --- a/pezcumulus/teyrchains/runtimes/coretime/coretime-pezkuwichain/src/weights/xcm/mod.rs +++ b/pezcumulus/teyrchains/runtimes/coretime/coretime-pezkuwichain/src/weights/xcm/mod.rs @@ -44,8 +44,9 @@ impl WeighAssets for AssetFilter { WildFungibility::Fungible => weight, // Magic number 2 has to do with the fact that we could have up to 2 times // MaxAssetsIntoHolding in the worst-case scenario. - WildFungibility::NonFungible => - weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64), + WildFungibility::NonFungible => { + weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64) + }, }, AllCounted(count) => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), AllOfCounted { count, .. } => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), diff --git a/pezcumulus/teyrchains/runtimes/coretime/coretime-zagros/src/lib.rs b/pezcumulus/teyrchains/runtimes/coretime/coretime-zagros/src/lib.rs index 90b544f9..406c1f38 100644 --- a/pezcumulus/teyrchains/runtimes/coretime/coretime-zagros/src/lib.rs +++ b/pezcumulus/teyrchains/runtimes/coretime/coretime-zagros/src/lib.rs @@ -522,39 +522,39 @@ impl InstanceFilter for ProxyType { ), ProxyType::CancelProxy => matches!( c, - RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Broker => { matches!( c, - RuntimeCall::Broker { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Broker { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ) }, ProxyType::CoretimeRenewer => { matches!( c, - RuntimeCall::Broker(pezpallet_broker::Call::renew { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Broker(pezpallet_broker::Call::renew { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ) }, ProxyType::OnDemandPurchaser => { matches!( c, - RuntimeCall::Broker(pezpallet_broker::Call::purchase_credit { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Broker(pezpallet_broker::Call::purchase_credit { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ) }, ProxyType::Collator => matches!( c, - RuntimeCall::CollatorSelection { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::CollatorSelection { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), } } diff --git a/pezcumulus/teyrchains/runtimes/coretime/coretime-zagros/src/weights/xcm/mod.rs b/pezcumulus/teyrchains/runtimes/coretime/coretime-zagros/src/weights/xcm/mod.rs index a892da4d..2bf5e52f 100644 --- a/pezcumulus/teyrchains/runtimes/coretime/coretime-zagros/src/weights/xcm/mod.rs +++ b/pezcumulus/teyrchains/runtimes/coretime/coretime-zagros/src/weights/xcm/mod.rs @@ -43,8 +43,9 @@ impl WeighAssets for AssetFilter { WildFungibility::Fungible => weight, // Magic number 2 has to do with the fact that we could have up to 2 times // MaxAssetsIntoHolding in the worst-case scenario. - WildFungibility::NonFungible => - weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64), + WildFungibility::NonFungible => { + weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64) + }, }, AllCounted(count) => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), AllOfCounted { count, .. } => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), diff --git a/pezcumulus/teyrchains/runtimes/people/people-pezkuwichain/src/lib.rs b/pezcumulus/teyrchains/runtimes/people/people-pezkuwichain/src/lib.rs index d8f84725..e2b203f3 100644 --- a/pezcumulus/teyrchains/runtimes/people/people-pezkuwichain/src/lib.rs +++ b/pezcumulus/teyrchains/runtimes/people/people-pezkuwichain/src/lib.rs @@ -562,29 +562,29 @@ impl InstanceFilter for ProxyType { ), ProxyType::CancelProxy => matches!( c, - RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Identity => { matches!( c, - RuntimeCall::Identity { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Identity { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ) }, ProxyType::IdentityJudgement => matches!( c, - RuntimeCall::Identity(pezpallet_identity::Call::provide_judgement { .. }) | - RuntimeCall::Utility(..) | - RuntimeCall::Multisig { .. } + RuntimeCall::Identity(pezpallet_identity::Call::provide_judgement { .. }) + | RuntimeCall::Utility(..) + | RuntimeCall::Multisig { .. } ), ProxyType::Collator => matches!( c, - RuntimeCall::CollatorSelection { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::CollatorSelection { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), } } diff --git a/pezcumulus/teyrchains/runtimes/people/people-pezkuwichain/src/weights/xcm/mod.rs b/pezcumulus/teyrchains/runtimes/people/people-pezkuwichain/src/weights/xcm/mod.rs index f8ace756..42ca9c60 100644 --- a/pezcumulus/teyrchains/runtimes/people/people-pezkuwichain/src/weights/xcm/mod.rs +++ b/pezcumulus/teyrchains/runtimes/people/people-pezkuwichain/src/weights/xcm/mod.rs @@ -43,8 +43,9 @@ impl WeighAssets for AssetFilter { WildFungibility::Fungible => weight, // Magic number 2 has to do with the fact that we could have up to 2 times // MaxAssetsIntoHolding in the worst-case scenario. - WildFungibility::NonFungible => - weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64), + WildFungibility::NonFungible => { + weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64) + }, }, AllCounted(count) => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), AllOfCounted { count, .. } => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), diff --git a/pezcumulus/teyrchains/runtimes/people/people-zagros/src/lib.rs b/pezcumulus/teyrchains/runtimes/people/people-zagros/src/lib.rs index 559eec27..04cc3660 100644 --- a/pezcumulus/teyrchains/runtimes/people/people-zagros/src/lib.rs +++ b/pezcumulus/teyrchains/runtimes/people/people-zagros/src/lib.rs @@ -477,29 +477,29 @@ impl InstanceFilter for ProxyType { ), ProxyType::CancelProxy => matches!( c, - RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. }) + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), ProxyType::Identity => { matches!( c, - RuntimeCall::Identity { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::Identity { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ) }, ProxyType::IdentityJudgement => matches!( c, - RuntimeCall::Identity(pezpallet_identity::Call::provide_judgement { .. }) | - RuntimeCall::Utility(..) | - RuntimeCall::Multisig { .. } + RuntimeCall::Identity(pezpallet_identity::Call::provide_judgement { .. }) + | RuntimeCall::Utility(..) + | RuntimeCall::Multisig { .. } ), ProxyType::Collator => matches!( c, - RuntimeCall::CollatorSelection { .. } | - RuntimeCall::Utility { .. } | - RuntimeCall::Multisig { .. } + RuntimeCall::CollatorSelection { .. } + | RuntimeCall::Utility { .. } + | RuntimeCall::Multisig { .. } ), } } diff --git a/pezcumulus/teyrchains/runtimes/people/people-zagros/src/weights/xcm/mod.rs b/pezcumulus/teyrchains/runtimes/people/people-zagros/src/weights/xcm/mod.rs index 440e53ff..b18e0753 100644 --- a/pezcumulus/teyrchains/runtimes/people/people-zagros/src/weights/xcm/mod.rs +++ b/pezcumulus/teyrchains/runtimes/people/people-zagros/src/weights/xcm/mod.rs @@ -43,8 +43,9 @@ impl WeighAssets for AssetFilter { WildFungibility::Fungible => weight, // Magic number 2 has to do with the fact that we could have up to 2 times // MaxAssetsIntoHolding in the worst-case scenario. - WildFungibility::NonFungible => - weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64), + WildFungibility::NonFungible => { + weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64) + }, }, AllCounted(count) => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), AllOfCounted { count, .. } => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), diff --git a/pezcumulus/teyrchains/runtimes/test-utils/src/lib.rs b/pezcumulus/teyrchains/runtimes/test-utils/src/lib.rs index a42eaddb..1e6f7687 100644 --- a/pezcumulus/teyrchains/runtimes/test-utils/src/lib.rs +++ b/pezcumulus/teyrchains/runtimes/test-utils/src/lib.rs @@ -525,14 +525,17 @@ impl< GovernanceOrigin::Location(location) if location == Location::here() => { panic!("Location::here() not supported, use GovernanceOrigin::Origin instead") }, - GovernanceOrigin::Location(location) => - execute_xcm(call, location, None).ensure_complete().map_err(Either::Right), - GovernanceOrigin::LocationAndDescendOrigin(location, descend_origin) => + GovernanceOrigin::Location(location) => { + execute_xcm(call, location, None).ensure_complete().map_err(Either::Right) + }, + GovernanceOrigin::LocationAndDescendOrigin(location, descend_origin) => { execute_xcm(call, location, Some(descend_origin)) .ensure_complete() - .map_err(Either::Right), - GovernanceOrigin::Origin(origin) => - call.dispatch(origin).map(|_| ()).map_err(|e| Either::Left(e.error)), + .map_err(Either::Right) + }, + GovernanceOrigin::Origin(origin) => { + call.dispatch(origin).map(|_| ()).map_err(|e| Either::Left(e.error)) + }, } } @@ -640,8 +643,9 @@ impl< .into_iter() .filter_map(|e| unwrap_xcmp_queue_event(e.event.encode())) .find_map(|e| match e { - pezcumulus_pezpallet_xcmp_queue::Event::XcmpMessageSent { message_hash } => - Some(message_hash), + pezcumulus_pezpallet_xcmp_queue::Event::XcmpMessageSent { message_hash } => { + Some(message_hash) + }, _ => None, }) } diff --git a/pezcumulus/teyrchains/runtimes/testing/penpal/src/xcm_config.rs b/pezcumulus/teyrchains/runtimes/testing/penpal/src/xcm_config.rs index 89fe860d..bb759f66 100644 --- a/pezcumulus/teyrchains/runtimes/testing/penpal/src/xcm_config.rs +++ b/pezcumulus/teyrchains/runtimes/testing/penpal/src/xcm_config.rs @@ -272,8 +272,8 @@ where { fn contains(asset: &Asset, origin: &Location) -> bool { let loc = Origin::get(); - &loc == origin && - matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) } + &loc == origin + && matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) } if asset_loc.starts_with(&Prefix::get())) } } @@ -331,8 +331,8 @@ impl, Origin: Get> ContainsPair bool { tracing::trace!(target: "xcm::contains", ?asset, ?origin, "AssetFromChain"); - *origin == Origin::get() && - matches!(asset.id.clone(), AssetId(id) if id == AssetLocation::get()) + *origin == Origin::get() + && matches!(asset.id.clone(), AssetId(id) if id == AssetLocation::get()) } } diff --git a/pezcumulus/teyrchains/runtimes/testing/pezkuwichain-teyrchain/src/genesis_config_presets.rs b/pezcumulus/teyrchains/runtimes/testing/pezkuwichain-teyrchain/src/genesis_config_presets.rs index 30a8111d..20b957b3 100644 --- a/pezcumulus/teyrchains/runtimes/testing/pezkuwichain-teyrchain/src/genesis_config_presets.rs +++ b/pezcumulus/teyrchains/runtimes/testing/pezkuwichain-teyrchain/src/genesis_config_presets.rs @@ -59,8 +59,9 @@ pub fn get_preset(id: &PresetId) -> Option> { }; let patch = match id.as_ref() { - pezsp_genesis_builder::DEV_RUNTIME_PRESET => - genesis_fn(vec![Sr25519Keyring::Alice.public().into()]), + pezsp_genesis_builder::DEV_RUNTIME_PRESET => { + genesis_fn(vec![Sr25519Keyring::Alice.public().into()]) + }, pezsp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET => genesis_fn(vec![ Sr25519Keyring::Alice.public().into(), Sr25519Keyring::Bob.public().into(), diff --git a/pezcumulus/teyrchains/runtimes/testing/yet-another-teyrchain/src/lib.rs b/pezcumulus/teyrchains/runtimes/testing/yet-another-teyrchain/src/lib.rs index fa6337ed..45de8630 100644 --- a/pezcumulus/teyrchains/runtimes/testing/yet-another-teyrchain/src/lib.rs +++ b/pezcumulus/teyrchains/runtimes/testing/yet-another-teyrchain/src/lib.rs @@ -401,8 +401,8 @@ impl WeightToFeePolynomial for WeightToFee { // in Pezkuwichain, extrinsic base weight (smallest non-zero weight) is mapped to 1 // MILLI_UNIT: in our template, we map to 1/10 of that, or 1/10 MILLI_UNIT let p = YAP / 10; - let q = 100 * - Balance::from( + let q = 100 + * Balance::from( pezframe_support::weights::constants::ExtrinsicBaseWeight::get().ref_time(), ); vec![WeightToFeeCoefficient { diff --git a/pezcumulus/zombienet/zombienet-sdk-helpers/src/lib.rs b/pezcumulus/zombienet/zombienet-sdk-helpers/src/lib.rs index 853055ae..0c52e034 100644 --- a/pezcumulus/zombienet/zombienet-sdk-helpers/src/lib.rs +++ b/pezcumulus/zombienet/zombienet-sdk-helpers/src/lib.rs @@ -19,7 +19,7 @@ use tokio::{ use zombienet_sdk::subxt::{ self, blocks::Block, - config::{pezkuwi::PezkuwiExtrinsicParamsBuilder, bizinikiwi::DigestItem}, + config::{bizinikiwi::DigestItem, pezkuwi::PezkuwiExtrinsicParamsBuilder}, events::Events, ext::scale_value::value, tx::{signer::Signer, DynamicPayload, TxStatus}, @@ -367,9 +367,9 @@ pub async fn submit_extrinsic_and_wait_for_finalization_success { + TxStatus::Error { message } + | TxStatus::Invalid { message } + | TxStatus::Dropped { message } => { return Err(anyhow::format_err!("Error submitting tx: {message}")); }, _ => continue, @@ -423,10 +423,8 @@ pub async fn assert_para_is_registered( let storage = block.storage(); let teyrchains_result = storage.try_fetch(&query, ()).await?; - let teyrchains: Vec = teyrchains_result - .map(|v| v.decode()) - .transpose()? - .unwrap_or_default(); + let teyrchains: Vec = + teyrchains_result.map(|v| v.decode()).transpose()?.unwrap_or_default(); log::debug!("Registered para_ids: {teyrchains:?}"); @@ -503,7 +501,7 @@ pub async fn wait_for_upgrade( if version == expected_version { break; } - } + }, Err(e) => return Err(e.into()), } } diff --git a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/bootnodes.rs b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/bootnodes.rs index 99e7992c..95a629f0 100644 --- a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/bootnodes.rs +++ b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/bootnodes.rs @@ -6,7 +6,7 @@ use tokio::time::Duration; use crate::utils::initialize_network; -use pezcumulus_zombienet_sdk_helpers::{wait_for_nth_session_change}; +use pezcumulus_zombienet_sdk_helpers::wait_for_nth_session_change; use zombienet_orchestrator::network::node::LogLineCountOptions; use zombienet_sdk::{ subxt::{OnlineClient, PezkuwiConfig}, @@ -30,7 +30,9 @@ async fn build_network_config() -> Result { // Have to set a `with_node` outside of the loop below, so that `r` has the right // type. .with_validator(|node| node.with_name("validator-0")); - (1..3).fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))) + (1..3).fold(r, |acc, i| { + acc.with_validator(|node| node.with_name(&format!("validator-{i}"))) + }) }) .with_teyrchain(|p| { p.with_id(1000) diff --git a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/multiple_blocks_per_slot.rs b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/multiple_blocks_per_slot.rs index 21da449c..1f85b556 100644 --- a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/multiple_blocks_per_slot.rs +++ b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/multiple_blocks_per_slot.rs @@ -95,7 +95,9 @@ async fn build_network_config() -> Result { // Have to set a `with_node` outside of the loop below, so that `r` has the right // type. .with_validator(|node| node.with_name("validator-0")); - (1..9).fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))) + (1..9).fold(r, |acc, i| { + acc.with_validator(|node| node.with_name(&format!("validator-{i}"))) + }) }) .with_teyrchain(|p| { p.with_id(PARA_ID) diff --git a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/pov_recovery.rs b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/pov_recovery.rs index f0ec2642..e2aaa9fa 100644 --- a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/pov_recovery.rs +++ b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/pov_recovery.rs @@ -7,7 +7,7 @@ use std::{sync::Arc, time::Duration}; use crate::utils::{initialize_network, BEST_BLOCK_METRIC}; use pezcumulus_zombienet_sdk_helpers::{ - assert_para_is_registered, assert_para_throughput, assign_cores, + assert_para_is_registered, assert_para_throughput, assign_cores, }; use pezkuwi_primitives::Id as ParaId; use serde_json::json; diff --git a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/slot_based_authoring.rs b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/slot_based_authoring.rs index 50200b73..122fcf9b 100644 --- a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/slot_based_authoring.rs +++ b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/slot_based_authoring.rs @@ -6,7 +6,7 @@ use std::time::Duration; use crate::utils::{initialize_network, BEST_BLOCK_METRIC}; -use pezcumulus_zombienet_sdk_helpers::{assign_cores}; +use pezcumulus_zombienet_sdk_helpers::assign_cores; use serde_json::json; use zombienet_orchestrator::network::node::LogLineCountOptions; use zombienet_sdk::{NetworkConfig, NetworkConfigBuilder}; diff --git a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/slot_based_rp_offset.rs b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/slot_based_rp_offset.rs index 85a40848..bfacaa0e 100644 --- a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/slot_based_rp_offset.rs +++ b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/slot_based_rp_offset.rs @@ -44,7 +44,9 @@ async fn elastic_scaling_slot_based_relay_parent_offset_test() -> Result<(), any // type. .with_validator(|node| node.with_name("validator-0")); - (1..6).fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))) + (1..6).fold(r, |acc, i| { + acc.with_validator(|node| node.with_name(&format!("validator-{i}"))) + }) }) .with_teyrchain(|p| { p.with_id(2400) diff --git a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/upgrade_to_3_cores.rs b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/upgrade_to_3_cores.rs index a3b82278..b2c49827 100644 --- a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/upgrade_to_3_cores.rs +++ b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/elastic_scaling/upgrade_to_3_cores.rs @@ -8,7 +8,7 @@ use std::time::Duration; use crate::utils::initialize_network; use pezcumulus_zombienet_sdk_helpers::{ - assert_para_throughput, assign_cores, runtime_upgrade, wait_for_upgrade, + assert_para_throughput, assign_cores, runtime_upgrade, wait_for_upgrade, }; use pezkuwi_primitives::Id as ParaId; use rstest::rstest; diff --git a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/full_node_catching_up.rs b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/full_node_catching_up.rs index 88050ddc..5097bcb5 100644 --- a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/full_node_catching_up.rs +++ b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/full_node_catching_up.rs @@ -6,7 +6,7 @@ use tokio::time::Duration; use crate::utils::{initialize_network, BEST_BLOCK_METRIC}; -use pezcumulus_zombienet_sdk_helpers::{assert_para_throughput}; +use pezcumulus_zombienet_sdk_helpers::assert_para_throughput; use pezkuwi_primitives::Id as ParaId; use zombienet_orchestrator::network::node::LogLineCountOptions; use zombienet_sdk::{ diff --git a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/full_node_warp_sync.rs b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/full_node_warp_sync.rs index dd6e6bf9..e8ae1f14 100644 --- a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/full_node_warp_sync.rs +++ b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/full_node_warp_sync.rs @@ -116,7 +116,7 @@ use anyhow::anyhow; use pezkuwi_primitives::Id as ParaId; use crate::utils::{initialize_network, BEST_BLOCK_METRIC}; -use pezcumulus_zombienet_sdk_helpers::{assert_para_is_registered}; +use pezcumulus_zombienet_sdk_helpers::assert_para_is_registered; use zombienet_sdk::{ subxt::{OnlineClient, PezkuwiConfig}, NetworkConfig, NetworkConfigBuilder, @@ -180,8 +180,12 @@ async fn build_network_config() -> Result { .with_default_image(images.polkadot.as_str()) .with_chain_spec_path("tests/zombie_ci/warp-sync-relaychain-spec.json") .with_default_args(vec![("-lteyrchain=debug").into()]) - .with_validator(|node| node.with_name("alice").with_db_snapshot(DB_SNAPSHOT_RELAYCHAIN)) - .with_validator(|node| node.with_name("bob").with_db_snapshot(DB_SNAPSHOT_RELAYCHAIN)) + .with_validator(|node| { + node.with_name("alice").with_db_snapshot(DB_SNAPSHOT_RELAYCHAIN) + }) + .with_validator(|node| { + node.with_name("bob").with_db_snapshot(DB_SNAPSHOT_RELAYCHAIN) + }) .with_validator(|node| { node.with_name("charlie").with_db_snapshot(DB_SNAPSHOT_RELAYCHAIN) }) diff --git a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/migrate_solo.rs b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/migrate_solo.rs index 9e05693a..718829e5 100644 --- a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/migrate_solo.rs +++ b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/migrate_solo.rs @@ -7,7 +7,7 @@ use std::{path::Path, str::FromStr}; use crate::utils::{initialize_network, BEST_BLOCK_METRIC}; -use pezcumulus_zombienet_sdk_helpers::{assert_para_throughput}; +use pezcumulus_zombienet_sdk_helpers::assert_para_throughput; use pezkuwi_primitives::Id as ParaId; use pezsp_core::{hexdisplay::AsBytesRef, Bytes}; use zombienet_sdk::{ diff --git a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/rpc_collator_build_blocks.rs b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/rpc_collator_build_blocks.rs index 941e6105..ef5ee967 100644 --- a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/rpc_collator_build_blocks.rs +++ b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/rpc_collator_build_blocks.rs @@ -6,7 +6,7 @@ use std::time::Duration; use crate::utils::{initialize_network, BEST_BLOCK_METRIC}; -use pezcumulus_zombienet_sdk_helpers::{assert_para_throughput}; +use pezcumulus_zombienet_sdk_helpers::assert_para_throughput; use pezkuwi_primitives::Id as ParaId; use zombienet_orchestrator::network::node::LogLineCountOptions; use zombienet_sdk::{ diff --git a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/statement_store.rs b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/statement_store.rs index 7add1934..dac1117a 100644 --- a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/statement_store.rs +++ b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/statement_store.rs @@ -27,7 +27,9 @@ async fn statement_store() -> Result<(), anyhow::Error> { // type. .with_validator(|node| node.with_name("validator-0")); - (1..6).fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))) + (1..6).fold(r, |acc, i| { + acc.with_validator(|node| node.with_name(&format!("validator-{i}"))) + }) }) .with_teyrchain(|p| { p.with_id(2400) diff --git a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/statement_store_bench.rs b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/statement_store_bench.rs index 4fd922f7..d1d62aae 100644 --- a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/statement_store_bench.rs +++ b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/statement_store_bench.rs @@ -201,9 +201,7 @@ async fn statement_store_memory_stress_bench() -> Result<(), anyhow::Error> { break; } - info!( - "Failed to submit statement, retrying in {RETRY_DELAY_MS}ms: {err:?}" - ); + info!("Failed to submit statement, retrying in {RETRY_DELAY_MS}ms: {err:?}"); tokio::time::sleep(Duration::from_millis(RETRY_DELAY_MS)).await; } } diff --git a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/sync_blocks.rs b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/sync_blocks.rs index cef24f26..3eb82267 100644 --- a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/sync_blocks.rs +++ b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/sync_blocks.rs @@ -5,7 +5,7 @@ use anyhow::anyhow; use crate::utils::{initialize_network, BEST_BLOCK_METRIC}; -use pezcumulus_zombienet_sdk_helpers::{assert_para_throughput}; +use pezcumulus_zombienet_sdk_helpers::assert_para_throughput; use pezkuwi_primitives::Id as ParaId; use zombienet_sdk::{ subxt::{OnlineClient, PezkuwiConfig}, diff --git a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/teyrchain_extrinsic_get_finalized.rs b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/teyrchain_extrinsic_get_finalized.rs index e2326ab6..4481cfd7 100644 --- a/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/teyrchain_extrinsic_get_finalized.rs +++ b/pezcumulus/zombienet/zombienet-sdk/tests/zombie_ci/teyrchain_extrinsic_get_finalized.rs @@ -5,7 +5,7 @@ use anyhow::anyhow; use tokio::time::Duration; use crate::utils::{initialize_network, BEST_BLOCK_METRIC}; -use pezcumulus_zombienet_sdk_helpers::{submit_extrinsic_and_wait_for_finalization_success_with_timeout}; +use pezcumulus_zombienet_sdk_helpers::submit_extrinsic_and_wait_for_finalization_success_with_timeout; use zombienet_orchestrator::network::node::{LogLineCount, LogLineCountOptions}; use zombienet_sdk::{ subxt::{self, dynamic::Value, OnlineClient, PezkuwiConfig}, diff --git a/pezkuwi/node/collation-generation/src/lib.rs b/pezkuwi/node/collation-generation/src/lib.rs index de04dfae..1e65f4d9 100644 --- a/pezkuwi/node/collation-generation/src/lib.rs +++ b/pezkuwi/node/collation-generation/src/lib.rs @@ -551,7 +551,10 @@ async fn construct_and_distribute_receipt( // As such, honest collators never produce an uncompressed PoV which starts with // a compression magic number, which would lead validators to reject the collation. if encoded_size > validation_data.max_pov_size as usize { - return Err(Error::POVSizeExceeded(encoded_size, validation_data.max_pov_size as usize)); + return Err(Error::POVSizeExceeded( + encoded_size, + validation_data.max_pov_size as usize, + )); } pov diff --git a/pezkuwi/node/core/approval-voting-parallel/src/lib.rs b/pezkuwi/node/core/approval-voting-parallel/src/lib.rs index 28d60823..fac2a25d 100644 --- a/pezkuwi/node/core/approval-voting-parallel/src/lib.rs +++ b/pezkuwi/node/core/approval-voting-parallel/src/lib.rs @@ -519,7 +519,7 @@ fn validator_index_for_msg( ) { match msg { pezkuwi_node_network_protocol::ValidationProtocols::V3(ref message) => match message { - pezkuwi_node_network_protocol::v3::ApprovalDistributionMessage::Assignments(msgs) => + pezkuwi_node_network_protocol::v3::ApprovalDistributionMessage::Assignments(msgs) => { if let Ok(validator) = msgs.iter().map(|(msg, _)| msg.validator).all_equal_value() { (Some((validator, msg)), None) } else { @@ -537,8 +537,9 @@ fn validator_index_for_msg( }) .collect_vec(); (None, Some(split)) - }, - pezkuwi_node_network_protocol::v3::ApprovalDistributionMessage::Approvals(msgs) => + } + }, + pezkuwi_node_network_protocol::v3::ApprovalDistributionMessage::Approvals(msgs) => { if let Ok(validator) = msgs.iter().map(|msg| msg.validator).all_equal_value() { (Some((validator, msg)), None) } else { @@ -556,7 +557,8 @@ fn validator_index_for_msg( }) .collect_vec(); (None, Some(split)) - }, + } + }, }, } } @@ -733,8 +735,9 @@ impl overseer::SubsystemSender for ToWorker { match P::priority() { pezkuwi_overseer::PriorityLevel::Normal => self.send_message(msg), - pezkuwi_overseer::PriorityLevel::High => - async { self.send_unbounded_message(msg) }.boxed(), + pezkuwi_overseer::PriorityLevel::High => { + async { self.send_unbounded_message(msg) }.boxed() + }, } } @@ -821,10 +824,12 @@ impl> ) -> Result<(), metered::TrySendError> { self.0.try_send_message(msg.into()).map_err(|err| match err { // Safe to unwrap because it was built from the same type. - metered::TrySendError::Closed(msg) => - metered::TrySendError::Closed(msg.try_into().unwrap()), - metered::TrySendError::Full(msg) => - metered::TrySendError::Full(msg.try_into().unwrap()), + metered::TrySendError::Closed(msg) => { + metered::TrySendError::Closed(msg.try_into().unwrap()) + }, + metered::TrySendError::Full(msg) => { + metered::TrySendError::Full(msg.try_into().unwrap()) + }, }) } @@ -869,10 +874,12 @@ impl> ) -> Result<(), metered::TrySendError> { self.0.try_send_message_with_priority::

(msg.into()).map_err(|err| match err { // Safe to unwrap because it was built from the same type. - metered::TrySendError::Closed(msg) => - metered::TrySendError::Closed(msg.try_into().unwrap()), - metered::TrySendError::Full(msg) => - metered::TrySendError::Full(msg.try_into().unwrap()), + metered::TrySendError::Closed(msg) => { + metered::TrySendError::Closed(msg.try_into().unwrap()) + }, + metered::TrySendError::Full(msg) => { + metered::TrySendError::Full(msg.try_into().unwrap()) + }, }) } } diff --git a/pezkuwi/node/core/approval-voting/src/approval_checking.rs b/pezkuwi/node/core/approval-voting/src/approval_checking.rs index 1e9f6736..9b30c81d 100644 --- a/pezkuwi/node/core/approval-voting/src/approval_checking.rs +++ b/pezkuwi/node/core/approval-voting/src/approval_checking.rs @@ -93,8 +93,9 @@ impl Check { pub fn is_approved(&self, max_assignment_tick: Tick) -> bool { match *self { Check::Unapproved => false, - Check::Approved(_, last_assignment_tick) => - last_assignment_tick.map_or(true, |t| t <= max_assignment_tick), + Check::Approved(_, last_assignment_tick) => { + last_assignment_tick.map_or(true, |t| t <= max_assignment_tick) + }, Check::ApprovedOneThird => true, } } @@ -304,8 +305,8 @@ impl State { // validators. // If there are a lot then we've got bigger problems and no need to make this // array unnecessarily large. - if self.no_show_validators.len() + no_show_validators.len() < - MAX_RECORDED_NO_SHOW_VALIDATORS_PER_CANDIDATE + if self.no_show_validators.len() + no_show_validators.len() + < MAX_RECORDED_NO_SHOW_VALIDATORS_PER_CANDIDATE { self.no_show_validators.extend(no_show_validators); } diff --git a/pezkuwi/node/core/approval-voting/src/approval_db/v2/tests.rs b/pezkuwi/node/core/approval-voting/src/approval_db/v2/tests.rs index 200cfcd0..bd438d97 100644 --- a/pezkuwi/node/core/approval-voting/src/approval_db/v2/tests.rs +++ b/pezkuwi/node/core/approval-voting/src/approval_db/v2/tests.rs @@ -409,8 +409,9 @@ fn canonicalize_works() { .is_none()); continue; }, - Some(i) => - (load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &hash).unwrap().unwrap(), i), + Some(i) => { + (load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &hash).unwrap().unwrap(), i) + }, }; assert_eq!(entry.candidates.len(), with_candidates.len()); diff --git a/pezkuwi/node/core/approval-voting/src/approval_db/v3/tests.rs b/pezkuwi/node/core/approval-voting/src/approval_db/v3/tests.rs index cf861602..248f0287 100644 --- a/pezkuwi/node/core/approval-voting/src/approval_db/v3/tests.rs +++ b/pezkuwi/node/core/approval-voting/src/approval_db/v3/tests.rs @@ -415,8 +415,9 @@ fn canonicalize_works() { .is_none()); continue; }, - Some(i) => - (load_block_entry(store.as_ref(), &TEST_CONFIG, &hash).unwrap().unwrap(), i), + Some(i) => { + (load_block_entry(store.as_ref(), &TEST_CONFIG, &hash).unwrap().unwrap(), i) + }, }; assert_eq!(entry.candidates.len(), with_candidates.len()); diff --git a/pezkuwi/node/core/approval-voting/src/backend.rs b/pezkuwi/node/core/approval-voting/src/backend.rs index b8066819..e7f55178 100644 --- a/pezkuwi/node/core/approval-voting/src/backend.rs +++ b/pezkuwi/node/core/approval-voting/src/backend.rs @@ -132,10 +132,10 @@ impl<'a, B: 'a + Backend> OverlayedBackend<'a, B> { } pub fn is_empty(&self) -> bool { - self.block_entries.is_empty() && - self.candidate_entries.is_empty() && - self.blocks_at_height.is_empty() && - self.stored_block_range == BlockRangeStatus::NotModified + self.block_entries.is_empty() + && self.candidate_entries.is_empty() + && self.blocks_at_height.is_empty() + && self.stored_block_range == BlockRangeStatus::NotModified } pub fn load_all_blocks(&self) -> SubsystemResult> { diff --git a/pezkuwi/node/core/approval-voting/src/criteria.rs b/pezkuwi/node/core/approval-voting/src/criteria.rs index 2517cc2d..3d155d4a 100644 --- a/pezkuwi/node/core/approval-voting/src/criteria.rs +++ b/pezkuwi/node/core/approval-voting/src/criteria.rs @@ -241,9 +241,9 @@ pub fn compute_assignments( leaving_cores: impl IntoIterator + Clone, enable_v2_assignments: bool, ) -> HashMap { - if config.n_cores == 0 || - config.assignment_keys.is_empty() || - config.validator_groups.is_empty() + if config.n_cores == 0 + || config.assignment_keys.is_empty() + || config.validator_groups.is_empty() { gum::trace!( target: LOG_TARGET, @@ -262,8 +262,9 @@ pub fn compute_assignments( Ok(Some(pair)) => Some((ValidatorIndex(i as _), pair)), Ok(None) => None, Err(pezsc_keystore::Error::Unavailable) => None, - Err(pezsc_keystore::Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => - None, + Err(pezsc_keystore::Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => { + None + }, Err(e) => { gum::warn!(target: LOG_TARGET, "Encountered keystore error: {:?}", e); None @@ -504,13 +505,14 @@ fn compute_relay_vrf_delay_assignments( let _ = e.insert(our_assignment); true }, - Entry::Occupied(mut e) => + Entry::Occupied(mut e) => { if e.get().tranche() > our_assignment.tranche() { e.insert(our_assignment); true } else { false - }, + } + }, }; if used { @@ -556,8 +558,8 @@ pub(crate) fn check_assignment_cert( .map_err(|_| InvalidAssignment(Reason::InvalidAssignmentKey))?; // Check that we have all backing groups for claimed cores. - if claimed_core_indices.count_ones() == 0 || - claimed_core_indices.count_ones() != backing_groups.len() + if claimed_core_indices.count_ones() == 0 + || claimed_core_indices.count_ones() != backing_groups.len() { return Err(InvalidAssignment(Reason::InvalidArguments)); } @@ -1070,8 +1072,8 @@ mod tests { fn check_rejects_modulo_core_wrong() { check_mutated_assignments(200, 100, 25, |m| { match m.cert.kind.clone() { - AssignmentCertKindV2::RelayVRFModulo { .. } | - AssignmentCertKindV2::RelayVRFModuloCompact { .. } => { + AssignmentCertKindV2::RelayVRFModulo { .. } + | AssignmentCertKindV2::RelayVRFModuloCompact { .. } => { m.cores = CoreIndex((m.cores.first_one().unwrap() + 1) as u32 % 100).into(); Some(false) diff --git a/pezkuwi/node/core/approval-voting/src/import.rs b/pezkuwi/node/core/approval-voting/src/import.rs index 9a629a51..ea68a73d 100644 --- a/pezkuwi/node/core/approval-voting/src/import.rs +++ b/pezkuwi/node/core/approval-voting/src/import.rs @@ -135,15 +135,17 @@ async fn imported_block_info>( let events: Vec = match c_rx.await { Ok(Ok(events)) => events, Ok(Err(error)) => return Err(ImportedBlockInfoError::RuntimeError(error)), - Err(error) => - return Err(ImportedBlockInfoError::FutureCancelled("CandidateEvents", error)), + Err(error) => { + return Err(ImportedBlockInfoError::FutureCancelled("CandidateEvents", error)) + }, }; events .into_iter() .filter_map(|e| match e { - CandidateEvent::CandidateIncluded(receipt, _, core, group) => - Some((receipt.hash(), receipt, core, group)), + CandidateEvent::CandidateIncluded(receipt, _, core, group) => { + Some((receipt.hash(), receipt, core, group)) + }, _ => None, }) .collect() @@ -163,8 +165,9 @@ async fn imported_block_info>( let session_index = match s_rx.await { Ok(Ok(s)) => s, Ok(Err(error)) => return Err(ImportedBlockInfoError::RuntimeError(error)), - Err(error) => - return Err(ImportedBlockInfoError::FutureCancelled("SessionIndexForChild", error)), + Err(error) => { + return Err(ImportedBlockInfoError::FutureCancelled("SessionIndexForChild", error)) + }, }; // We can't determine if the block is finalized or not - try processing it @@ -214,8 +217,9 @@ async fn imported_block_info>( match s_rx.await { Ok(Ok(s)) => s, Ok(Err(error)) => return Err(ImportedBlockInfoError::RuntimeError(error)), - Err(error) => - return Err(ImportedBlockInfoError::FutureCancelled("CurrentBabeEpoch", error)), + Err(error) => { + return Err(ImportedBlockInfoError::FutureCancelled("CurrentBabeEpoch", error)) + }, } }; diff --git a/pezkuwi/node/core/approval-voting/src/lib.rs b/pezkuwi/node/core/approval-voting/src/lib.rs index fdbb2caf..26fa1457 100644 --- a/pezkuwi/node/core/approval-voting/src/lib.rs +++ b/pezkuwi/node/core/approval-voting/src/lib.rs @@ -941,8 +941,8 @@ impl NoShowStats { // Print the no-show stats if NO_SHOW_DUMP_FREQUENCY blocks have passed since the last // print. fn maybe_print(&mut self, current_block_number: BlockNumber) { - if self.last_dumped_block_number > current_block_number || - current_block_number - self.last_dumped_block_number < NO_SHOW_DUMP_FREQUENCY + if self.last_dumped_block_number > current_block_number + || current_block_number - self.last_dumped_block_number < NO_SHOW_DUMP_FREQUENCY { return; } @@ -1763,10 +1763,12 @@ fn get_core_indices_on_startup( ) -> CoreBitfield { match &assignment { AssignmentCertKindV2::RelayVRFModuloCompact { core_bitfield } => core_bitfield.clone(), - AssignmentCertKindV2::RelayVRFModulo { sample: _ } => - CoreBitfield::try_from(vec![block_entry_core_index]).expect("Not an empty vec; qed"), - AssignmentCertKindV2::RelayVRFDelay { core_index } => - CoreBitfield::try_from(vec![*core_index]).expect("Not an empty vec; qed"), + AssignmentCertKindV2::RelayVRFModulo { sample: _ } => { + CoreBitfield::try_from(vec![block_entry_core_index]).expect("Not an empty vec; qed") + }, + AssignmentCertKindV2::RelayVRFDelay { core_index } => { + CoreBitfield::try_from(vec![*core_index]).expect("Not an empty vec; qed") + }, } } @@ -1779,8 +1781,9 @@ fn get_assignment_core_indices( block_entry: &BlockEntry, ) -> Option { match &assignment { - AssignmentCertKindV2::RelayVRFModuloCompact { core_bitfield } => - Some(core_bitfield.clone()), + AssignmentCertKindV2::RelayVRFModuloCompact { core_bitfield } => { + Some(core_bitfield.clone()) + }, AssignmentCertKindV2::RelayVRFModulo { sample: _ } => block_entry .candidates() .iter() @@ -1788,8 +1791,9 @@ fn get_assignment_core_indices( .map(|(core_index, _candidate_hash)| { CoreBitfield::try_from(vec![*core_index]).expect("Not an empty vec; qed") }), - AssignmentCertKindV2::RelayVRFDelay { core_index } => - Some(CoreBitfield::try_from(vec![*core_index]).expect("Not an empty vec; qed")), + AssignmentCertKindV2::RelayVRFDelay { core_index } => { + Some(CoreBitfield::try_from(vec![*core_index]).expect("Not an empty vec; qed")) + }, } } @@ -2701,13 +2705,14 @@ where let block_entry = match db.load_block_entry(&assignment.block_hash)? { Some(b) => b, - None => + None => { return Ok(( AssignmentCheckResult::Bad(AssignmentCheckError::UnknownBlock( assignment.block_hash, )), Vec::new(), - )), + )) + }, }; let session_info = match get_session_info_by_index( @@ -2719,13 +2724,14 @@ where .await { Some(s) => s, - None => + None => { return Ok(( AssignmentCheckResult::Bad(AssignmentCheckError::UnknownSessionIndex( block_entry.session(), )), Vec::new(), - )), + )) + }, }; let n_cores = session_info.n_cores as usize; @@ -2756,25 +2762,27 @@ where let (claimed_core_index, assigned_candidate_hash) = match block_entry.candidate(candidate_index) { Some((c, h)) => (*c, *h), - None => + None => { return Ok(( AssignmentCheckResult::Bad(AssignmentCheckError::InvalidCandidateIndex( candidate_index as _, )), Vec::new(), - )), // no candidate at core. + )) + }, // no candidate at core. }; let mut candidate_entry = match db.load_candidate_entry(&assigned_candidate_hash)? { Some(c) => c, - None => + None => { return Ok(( AssignmentCheckResult::Bad(AssignmentCheckError::InvalidCandidate( candidate_index as _, assigned_candidate_hash, )), Vec::new(), - )), // no candidate at core. + )) + }, // no candidate at core. }; if candidate_entry.approval_entry_mut(&assignment.block_hash).is_none() { @@ -2811,26 +2819,28 @@ where { let mut candidate_entry = match db.load_candidate_entry(&assigned_candidate_hash)? { Some(c) => c, - None => + None => { return Ok(( AssignmentCheckResult::Bad(AssignmentCheckError::InvalidCandidate( candidate_index as _, *assigned_candidate_hash, )), Vec::new(), - )), + )) + }, }; let approval_entry = match candidate_entry.approval_entry_mut(&assignment.block_hash) { Some(a) => a, - None => + None => { return Ok(( AssignmentCheckResult::Bad(AssignmentCheckError::Internal( assignment.block_hash, *assigned_candidate_hash, )), Vec::new(), - )), + )) + }, }; let is_duplicate_for_candidate = approval_entry.is_assigned(assignment.validator); @@ -3024,8 +3034,8 @@ enum ApprovalStateTransition { impl ApprovalStateTransition { fn validator_index(&self) -> Option { match *self { - ApprovalStateTransition::RemoteApproval(v) | - ApprovalStateTransition::LocalApproval(v) => Some(v), + ApprovalStateTransition::RemoteApproval(v) + | ApprovalStateTransition::LocalApproval(v) => Some(v), ApprovalStateTransition::WakeupProcessed => None, } } @@ -3210,9 +3220,9 @@ where .as_ref() .map(|validator_index| fork_approval_entry.is_assigned(*validator_index)) .unwrap_or_default(); - if wakeups.wakeup_for(*fork_block_hash, candidate_hash).is_none() && - !fork_approval_entry.is_approved() && - assigned_on_fork_block + if wakeups.wakeup_for(*fork_block_hash, candidate_hash).is_none() + && !fork_approval_entry.is_approved() + && assigned_on_fork_block { let fork_block_entry = db.load_block_entry(fork_block_hash); if let Ok(Some(fork_block_entry)) = fork_block_entry { @@ -3275,8 +3285,8 @@ fn should_trigger_assignment( RequiredTranches::Pending { maximum_broadcast, clock_drift, .. } => { let drifted_tranche_now = tranche_now.saturating_sub(clock_drift as DelayTranche); - assignment.tranche() <= maximum_broadcast && - assignment.tranche() <= drifted_tranche_now + assignment.tranche() <= maximum_broadcast + && assignment.tranche() <= drifted_tranche_now }, RequiredTranches::Exact { .. } => { // indicates that no new assignments are needed at the moment. diff --git a/pezkuwi/node/core/approval-voting/src/persisted_entries.rs b/pezkuwi/node/core/approval-voting/src/persisted_entries.rs index 3c255aca..9872d00f 100644 --- a/pezkuwi/node/core/approval-voting/src/persisted_entries.rs +++ b/pezkuwi/node/core/approval-voting/src/persisted_entries.rs @@ -642,8 +642,8 @@ impl BlockEntry { .map(|val| val.sign_no_later_than_tick); if let Some(sign_no_later_than_tick) = sign_no_later_than_tick { - if sign_no_later_than_tick <= tick_now || - self.num_candidates_pending_signature() >= max_approval_coalesce_count as usize + if sign_no_later_than_tick <= tick_now + || self.num_candidates_pending_signature() >= max_approval_coalesce_count as usize { ( self.candidate_indices_pending_signature().and_then(|candidate_indices| { diff --git a/pezkuwi/node/core/approval-voting/src/tests.rs b/pezkuwi/node/core/approval-voting/src/tests.rs index 508873e5..9d66e2ac 100644 --- a/pezkuwi/node/core/approval-voting/src/tests.rs +++ b/pezkuwi/node/core/approval-voting/src/tests.rs @@ -5722,8 +5722,8 @@ fn test_gathering_assignments_statements() { CandidateHash(Hash::repeat_byte(i as u8)), ); assert!( - state.per_block_assignments_gathering_times.len() <= - MAX_BLOCKS_WITH_ASSIGNMENT_TIMESTAMPS as usize + state.per_block_assignments_gathering_times.len() + <= MAX_BLOCKS_WITH_ASSIGNMENT_TIMESTAMPS as usize ); assert_eq!( diff --git a/pezkuwi/node/core/av-store/src/tests.rs b/pezkuwi/node/core/av-store/src/tests.rs index ef7af022..eebad80c 100644 --- a/pezkuwi/node/core/av-store/src/tests.rs +++ b/pezkuwi/node/core/av-store/src/tests.rs @@ -1263,8 +1263,8 @@ async fn has_all_chunks( expect_present: bool, ) -> bool { for i in 0..n_validators { - if query_chunk(virtual_overseer, candidate_hash, ValidatorIndex(i)).await.is_some() != - expect_present + if query_chunk(virtual_overseer, candidate_hash, ValidatorIndex(i)).await.is_some() + != expect_present { return false; } diff --git a/pezkuwi/node/core/backing/src/lib.rs b/pezkuwi/node/core/backing/src/lib.rs index d6b4ead7..09cfa28d 100644 --- a/pezkuwi/node/core/backing/src/lib.rs +++ b/pezkuwi/node/core/backing/src/lib.rs @@ -831,7 +831,7 @@ async fn validate_and_make_available( let pov = match pov { PoVData::Ready(pov) => pov, - PoVData::FetchFromValidator { from_validator, candidate_hash, pov_hash } => + PoVData::FetchFromValidator { from_validator, candidate_hash, pov_hash } => { match request_pov( &mut sender, relay_parent, @@ -854,7 +854,8 @@ async fn validate_and_make_available( }, Err(err) => return Err(err), Ok(pov) => pov, - }, + } + }, }; let v = { @@ -945,10 +946,12 @@ async fn handle_communication( CandidateBackingMessage::Statement(relay_parent, statement) => { handle_statement_message(ctx, state, relay_parent, statement, metrics).await?; }, - CandidateBackingMessage::GetBackableCandidates(requested_candidates, tx) => - handle_get_backable_candidates_message(state, requested_candidates, tx, metrics)?, - CandidateBackingMessage::CanSecond(request, tx) => - handle_can_second_request(ctx, state, request, tx).await, + CandidateBackingMessage::GetBackableCandidates(requested_candidates, tx) => { + handle_get_backable_candidates_message(state, requested_candidates, tx, metrics)? + }, + CandidateBackingMessage::CanSecond(request, tx) => { + handle_can_second_request(ctx, state, request, tx).await + }, } Ok(()) diff --git a/pezkuwi/node/core/backing/src/tests/mod.rs b/pezkuwi/node/core/backing/src/tests/mod.rs index c5183b95..8b71d387 100644 --- a/pezkuwi/node/core/backing/src/tests/mod.rs +++ b/pezkuwi/node/core/backing/src/tests/mod.rs @@ -51,8 +51,9 @@ struct TestLeaf { fn table_statement_to_primitive(statement: TableStatement) -> Statement { match statement { - TableStatement::Seconded(committed_candidate_receipt) => - Statement::Seconded(committed_candidate_receipt), + TableStatement::Seconded(committed_candidate_receipt) => { + Statement::Seconded(committed_candidate_receipt) + }, TableStatement::Valid(candidate_hash) => Statement::Valid(candidate_hash), } } diff --git a/pezkuwi/node/core/candidate-validation/src/lib.rs b/pezkuwi/node/core/candidate-validation/src/lib.rs index 7982b8df..c5680c1f 100644 --- a/pezkuwi/node/core/candidate-validation/src/lib.rs +++ b/pezkuwi/node/core/candidate-validation/src/lib.rs @@ -421,8 +421,9 @@ async fn handle_active_leaves_update( if let Some(activated) = update.activated { let maybe_new_session_index = match (prepare_state.session_index, maybe_session_index) { - (Some(existing_index), Some(new_index)) => - (new_index > existing_index).then_some(new_index), + (Some(existing_index), Some(new_index)) => { + (new_index > existing_index).then_some(new_index) + }, (None, Some(new_index)) => Some(new_index), _ => None, }; @@ -837,12 +838,13 @@ where match validation_backend.precheck_pvf(pvf).await { Ok(_) => PreCheckOutcome::Valid, - Err(prepare_err) => + Err(prepare_err) => { if prepare_err.is_deterministic() { PreCheckOutcome::Invalid } else { PreCheckOutcome::Failed - }, + } + }, } } @@ -875,10 +877,11 @@ async fn validate_candidate_exhaustive( // We only check the session index for backing. match (exec_kind, candidate_receipt.descriptor.session_index()) { - (PvfExecKind::Backing(_) | PvfExecKind::BackingSystemParas(_), Some(session_index)) => + (PvfExecKind::Backing(_) | PvfExecKind::BackingSystemParas(_), Some(session_index)) => { if session_index != expected_session_index { return Ok(ValidationResult::Invalid(InvalidCandidate::InvalidSessionIndex)); - }, + } + }, (_, _) => {}, }; @@ -918,7 +921,7 @@ async fn validate_candidate_exhaustive( ) .await }, - PvfExecKind::Approval | PvfExecKind::Dispute => + PvfExecKind::Approval | PvfExecKind::Dispute => { validation_backend .validate_candidate_with_retry( validation_code.0, @@ -931,7 +934,8 @@ async fn validate_candidate_exhaustive( exec_kind, validation_code_bomb_limit, ) - .await, + .await + }, }; if let Err(ref error) = result { @@ -949,27 +953,35 @@ async fn validate_candidate_exhaustive( ); Err(ValidationFailed(e.to_string())) }, - Err(ValidationError::Invalid(WasmInvalidCandidate::HardTimeout)) => - Ok(ValidationResult::Invalid(InvalidCandidate::Timeout)), - Err(ValidationError::Invalid(WasmInvalidCandidate::WorkerReportedInvalid(e))) => - Ok(ValidationResult::Invalid(InvalidCandidate::ExecutionError(e))), - Err(ValidationError::Invalid(WasmInvalidCandidate::PoVDecompressionFailure)) => - Ok(ValidationResult::Invalid(InvalidCandidate::PoVDecompressionFailure)), - Err(ValidationError::PossiblyInvalid(PossiblyInvalidError::AmbiguousWorkerDeath)) => + Err(ValidationError::Invalid(WasmInvalidCandidate::HardTimeout)) => { + Ok(ValidationResult::Invalid(InvalidCandidate::Timeout)) + }, + Err(ValidationError::Invalid(WasmInvalidCandidate::WorkerReportedInvalid(e))) => { + Ok(ValidationResult::Invalid(InvalidCandidate::ExecutionError(e))) + }, + Err(ValidationError::Invalid(WasmInvalidCandidate::PoVDecompressionFailure)) => { + Ok(ValidationResult::Invalid(InvalidCandidate::PoVDecompressionFailure)) + }, + Err(ValidationError::PossiblyInvalid(PossiblyInvalidError::AmbiguousWorkerDeath)) => { Ok(ValidationResult::Invalid(InvalidCandidate::ExecutionError( "ambiguous worker death".to_string(), - ))), - Err(ValidationError::PossiblyInvalid(PossiblyInvalidError::JobError(err))) => - Ok(ValidationResult::Invalid(InvalidCandidate::ExecutionError(err))), - Err(ValidationError::PossiblyInvalid(PossiblyInvalidError::RuntimeConstruction(err))) => - Ok(ValidationResult::Invalid(InvalidCandidate::ExecutionError(err))), - Err(ValidationError::PossiblyInvalid(err @ PossiblyInvalidError::CorruptedArtifact)) => - Ok(ValidationResult::Invalid(InvalidCandidate::ExecutionError(err.to_string()))), + ))) + }, + Err(ValidationError::PossiblyInvalid(PossiblyInvalidError::JobError(err))) => { + Ok(ValidationResult::Invalid(InvalidCandidate::ExecutionError(err))) + }, + Err(ValidationError::PossiblyInvalid(PossiblyInvalidError::RuntimeConstruction(err))) => { + Ok(ValidationResult::Invalid(InvalidCandidate::ExecutionError(err))) + }, + Err(ValidationError::PossiblyInvalid(err @ PossiblyInvalidError::CorruptedArtifact)) => { + Ok(ValidationResult::Invalid(InvalidCandidate::ExecutionError(err.to_string()))) + }, - Err(ValidationError::PossiblyInvalid(PossiblyInvalidError::AmbiguousJobDeath(err))) => + Err(ValidationError::PossiblyInvalid(PossiblyInvalidError::AmbiguousJobDeath(err))) => { Ok(ValidationResult::Invalid(InvalidCandidate::ExecutionError(format!( "ambiguous job death: {err}" - )))), + )))) + }, Err(ValidationError::Preparation(e)) => { gum::warn!( target: LOG_TARGET, @@ -1005,8 +1017,8 @@ async fn validate_candidate_exhaustive( }, }; - if candidate_receipt.commitments_hash != - committed_candidate_receipt.commitments.hash() + if candidate_receipt.commitments_hash + != committed_candidate_receipt.commitments.hash() { gum::info!( target: LOG_TARGET, @@ -1158,8 +1170,8 @@ trait ValidationBackend { let mut retry_immediately = false; match validation_result { Err(ValidationError::PossiblyInvalid( - PossiblyInvalidError::AmbiguousWorkerDeath | - PossiblyInvalidError::AmbiguousJobDeath(_), + PossiblyInvalidError::AmbiguousWorkerDeath + | PossiblyInvalidError::AmbiguousJobDeath(_), )) => break_if_no_retries_left!(num_death_retries_left), Err(ValidationError::PossiblyInvalid(PossiblyInvalidError::JobError(_))) => { @@ -1171,8 +1183,8 @@ trait ValidationBackend { }, Err(ValidationError::PossiblyInvalid( - PossiblyInvalidError::RuntimeConstruction(_) | - PossiblyInvalidError::CorruptedArtifact, + PossiblyInvalidError::RuntimeConstruction(_) + | PossiblyInvalidError::CorruptedArtifact, )) => { break_if_no_retries_left!(num_execution_error_retries_left); self.precheck_pvf(pvf.clone()).await?; @@ -1183,11 +1195,11 @@ trait ValidationBackend { retry_immediately = true; }, - Ok(_) | - Err( - ValidationError::Invalid(_) | - ValidationError::Preparation(_) | - ValidationError::ExecutionDeadline, + Ok(_) + | Err( + ValidationError::Invalid(_) + | ValidationError::Preparation(_) + | ValidationError::ExecutionDeadline, ) => break, } diff --git a/pezkuwi/node/core/chain-selection/src/db_backend/v1.rs b/pezkuwi/node/core/chain-selection/src/db_backend/v1.rs index f165c854..fd185f11 100644 --- a/pezkuwi/node/core/chain-selection/src/db_backend/v1.rs +++ b/pezkuwi/node/core/chain-selection/src/db_backend/v1.rs @@ -290,7 +290,7 @@ impl Backend for DbBackend { block_entry.encode(), ); }, - BackendWriteOp::WriteBlocksByNumber(block_number, v) => + BackendWriteOp::WriteBlocksByNumber(block_number, v) => { if v.is_empty() { tx.delete(self.config.col_data, &block_height_key(block_number)); } else { @@ -299,7 +299,8 @@ impl Backend for DbBackend { &block_height_key(block_number), v.encode(), ); - }, + } + }, BackendWriteOp::WriteViableLeaves(leaves) => { let leaves: LeafEntrySet = leaves.into(); if leaves.inner.is_empty() { diff --git a/pezkuwi/node/core/chain-selection/src/tree.rs b/pezkuwi/node/core/chain-selection/src/tree.rs index d091de56..bce18ea3 100644 --- a/pezkuwi/node/core/chain-selection/src/tree.rs +++ b/pezkuwi/node/core/chain-selection/src/tree.rs @@ -224,10 +224,11 @@ fn propagate_viability_update( // finalized block is implicitly the viable leaf. continue; }, - Some(entry) => + Some(entry) => { if entry.children.len() == pivot_count { viable_leaves.insert(entry.leaf_entry()); - }, + } + }, } } diff --git a/pezkuwi/node/core/dispute-coordinator/src/backend.rs b/pezkuwi/node/core/dispute-coordinator/src/backend.rs index 72dd1699..7b6cb031 100644 --- a/pezkuwi/node/core/dispute-coordinator/src/backend.rs +++ b/pezkuwi/node/core/dispute-coordinator/src/backend.rs @@ -86,9 +86,9 @@ impl<'a, B: 'a + Backend> OverlayedBackend<'a, B> { /// Returns true if the are no write operations to perform. pub fn is_empty(&self) -> bool { - self.earliest_session.is_none() && - self.recent_disputes.is_none() && - self.candidate_votes.is_empty() + self.earliest_session.is_none() + && self.recent_disputes.is_none() + && self.candidate_votes.is_empty() } /// Load the earliest session, if any. diff --git a/pezkuwi/node/core/dispute-coordinator/src/import.rs b/pezkuwi/node/core/dispute-coordinator/src/import.rs index 6e341ef7..f4fbb3fa 100644 --- a/pezkuwi/node/core/dispute-coordinator/src/import.rs +++ b/pezkuwi/node/core/dispute-coordinator/src/import.rs @@ -81,8 +81,9 @@ impl<'a> CandidateEnvironment<'a> { .get_session_info_by_index(ctx.sender(), relay_parent, session_index) .await { - Ok(extended_session_info) => - (&extended_session_info.session_info, &extended_session_info.executor_params), + Ok(extended_session_info) => { + (&extended_session_info.session_info, &extended_session_info.executor_params) + }, Err(_) => return None, }; @@ -553,8 +554,8 @@ impl ImportResult { /// Whether or not the invalid vote count for the dispute went beyond the byzantine threshold /// after the last import pub fn has_fresh_byzantine_threshold_against(&self) -> bool { - !self.old_state().byzantine_threshold_against && - self.new_state().byzantine_threshold_against + !self.old_state().byzantine_threshold_against + && self.new_state().byzantine_threshold_against } /// Modify this `ImportResult`s, by importing additional approval votes. diff --git a/pezkuwi/node/core/dispute-coordinator/src/initialized.rs b/pezkuwi/node/core/dispute-coordinator/src/initialized.rs index 11b54438..6c8b87a5 100644 --- a/pezkuwi/node/core/dispute-coordinator/src/initialized.rs +++ b/pezkuwi/node/core/dispute-coordinator/src/initialized.rs @@ -279,8 +279,9 @@ impl Initialized { self.scraper.process_finalized_block(&n); default_confirm }, - FromOrchestra::Communication { msg } => - self.handle_incoming(ctx, &mut overlay_db, msg, clock.now()).await?, + FromOrchestra::Communication { msg } => { + self.handle_incoming(ctx, &mut overlay_db, msg, clock.now()).await? + }, }, }; @@ -948,8 +949,9 @@ impl Initialized { let candidate_hash = candidate_receipt.hash(); let votes_in_db = overlay_db.load_candidate_votes(session, &candidate_hash)?; let relay_parent = match &candidate_receipt { - MaybeCandidateReceipt::Provides(candidate_receipt) => - candidate_receipt.descriptor().relay_parent(), + MaybeCandidateReceipt::Provides(candidate_receipt) => { + candidate_receipt.descriptor().relay_parent() + }, MaybeCandidateReceipt::AssumeBackingVotePresent(candidate_hash) => match &votes_in_db { Some(votes) => votes.candidate_receipt.descriptor().relay_parent(), None => { @@ -1006,7 +1008,7 @@ impl Initialized { // not have a `CandidateReceipt` available. let old_state = match votes_in_db.map(CandidateVotes::from) { Some(votes) => CandidateVoteState::new(votes, &env, now), - None => + None => { if let MaybeCandidateReceipt::Provides(candidate_receipt) = candidate_receipt { CandidateVoteState::new_from_receipt(candidate_receipt) } else { @@ -1017,7 +1019,8 @@ impl Initialized { "Cannot import votes, without `CandidateReceipt` available!" ); return Ok(ImportStatementsResult::InvalidImport); - }, + } + }, }; gum::trace!(target: LOG_TARGET, ?candidate_hash, ?session, "Loaded votes"); @@ -1026,8 +1029,8 @@ impl Initialized { let own_statements = statements .iter() .filter(|(statement, validator_index)| { - controlled_indices.contains(validator_index) && - *statement.candidate_hash() == candidate_hash + controlled_indices.contains(validator_index) + && *statement.candidate_hash() == candidate_hash }) .cloned() .collect::>(); @@ -1039,8 +1042,8 @@ impl Initialized { // // See guide: We import on fresh disputes to maximize likelihood of fetching votes for // dead forks and once concluded to maximize time for approval votes to trickle in. - if intermediate_result.is_freshly_disputed() || - intermediate_result.is_freshly_concluded() + if intermediate_result.is_freshly_disputed() + || intermediate_result.is_freshly_concluded() { gum::trace!( target: LOG_TARGET, @@ -1587,8 +1590,8 @@ impl Initialized { continue; }; // Check if all invalid voters (raising parties) are disabled - if !votes.invalid.is_empty() && - votes.invalid.iter().all(|(_, validator_index, _)| { + if !votes.invalid.is_empty() + && votes.invalid.iter().all(|(_, validator_index, _)| { self.offchain_disabled_validators.is_disabled(session, *validator_index) }) { disputes_to_remove.push((*dispute_session, *candidate_hash)); @@ -1833,9 +1836,9 @@ impl OffchainDisabledValidators { self.per_session .get(&session_index) .map(|session_disputes| { - session_disputes.backers_for_invalid.peek(&validator_index).is_some() || - session_disputes.for_invalid.peek(&validator_index).is_some() || - session_disputes.against_valid.peek(&validator_index).is_some() + session_disputes.backers_for_invalid.peek(&validator_index).is_some() + || session_disputes.for_invalid.peek(&validator_index).is_some() + || session_disputes.against_valid.peek(&validator_index).is_some() }) .unwrap_or(false) } diff --git a/pezkuwi/node/core/dispute-coordinator/src/participation/queues/mod.rs b/pezkuwi/node/core/dispute-coordinator/src/participation/queues/mod.rs index 3f149a40..56956cab 100644 --- a/pezkuwi/node/core/dispute-coordinator/src/participation/queues/mod.rs +++ b/pezkuwi/node/core/dispute-coordinator/src/participation/queues/mod.rs @@ -171,10 +171,10 @@ impl PartialEq for ParticipationRequest { executor_params, request_timer: _, } = self; - candidate_receipt == other.candidate_receipt() && - candidate_hash == other.candidate_hash() && - *session == other.session() && - executor_params.hash() == other.executor_params.hash() + candidate_receipt == other.candidate_receipt() + && candidate_hash == other.candidate_hash() + && *session == other.session() + && executor_params.hash() == other.executor_params.hash() } } #[cfg(test)] diff --git a/pezkuwi/node/core/dispute-coordinator/src/participation/tests.rs b/pezkuwi/node/core/dispute-coordinator/src/participation/tests.rs index 334ab536..803c72db 100644 --- a/pezkuwi/node/core/dispute-coordinator/src/participation/tests.rs +++ b/pezkuwi/node/core/dispute-coordinator/src/participation/tests.rs @@ -256,8 +256,8 @@ fn reqs_get_queued_when_out_of_capacity() { let mut recover_available_data_msg_count = 0; let mut block_number_msg_count = 0; - while recover_available_data_msg_count < MAX_PARALLEL_PARTICIPATIONS + 1 || - block_number_msg_count < 1 + while recover_available_data_msg_count < MAX_PARALLEL_PARTICIPATIONS + 1 + || block_number_msg_count < 1 { match ctx_handle.recv().await { AllMessages::AvailabilityRecovery( diff --git a/pezkuwi/node/core/dispute-coordinator/src/scraping/mod.rs b/pezkuwi/node/core/dispute-coordinator/src/scraping/mod.rs index e108924b..de7bcdc3 100644 --- a/pezkuwi/node/core/dispute-coordinator/src/scraping/mod.rs +++ b/pezkuwi/node/core/dispute-coordinator/src/scraping/mod.rs @@ -427,9 +427,9 @@ impl ChainScraper { for (block_number, hash) in block_numbers.zip(&hashes) { // Return if we either met target/cached block or // hit the size limit for the returned ancestry of head. - if self.last_observed_blocks.get(hash).is_some() || - block_number <= target_ancestor || - ancestors.len() >= Self::ANCESTRY_SIZE_LIMIT as usize + if self.last_observed_blocks.get(hash).is_some() + || block_number <= target_ancestor + || ancestors.len() >= Self::ANCESTRY_SIZE_LIMIT as usize { return Ok(ancestors); } diff --git a/pezkuwi/node/core/dispute-coordinator/src/scraping/tests.rs b/pezkuwi/node/core/dispute-coordinator/src/scraping/tests.rs index a6c7be5f..b5cb8183 100644 --- a/pezkuwi/node/core/dispute-coordinator/src/scraping/tests.rs +++ b/pezkuwi/node/core/dispute-coordinator/src/scraping/tests.rs @@ -427,8 +427,8 @@ fn scraper_requests_candidates_of_non_finalized_ancestors() { &mut virtual_overseer, &chain, finalized_block_number, - BLOCKS_TO_SKIP - - (finalized_block_number - DISPUTE_CANDIDATE_LIFETIME_AFTER_FINALIZATION) as usize, /* Expect the provider not to go past finalized block. */ + BLOCKS_TO_SKIP + - (finalized_block_number - DISPUTE_CANDIDATE_LIFETIME_AFTER_FINALIZATION) as usize, /* Expect the provider not to go past finalized block. */ get_backed_and_included_candidate_events, ); join(process_active_leaves_update(ctx.sender(), &mut ordering, next_update), overseer_fut) @@ -532,8 +532,8 @@ fn scraper_handles_backed_but_not_included_candidate() { // Bump the finalized block outside `BACKED_CANDIDATE_LIFETIME_AFTER_FINALIZATION`. // The candidate should be removed. assert!( - finalized_block_number < - TEST_TARGET_BLOCK_NUMBER + DISPUTE_CANDIDATE_LIFETIME_AFTER_FINALIZATION + finalized_block_number + < TEST_TARGET_BLOCK_NUMBER + DISPUTE_CANDIDATE_LIFETIME_AFTER_FINALIZATION ); finalized_block_number += TEST_TARGET_BLOCK_NUMBER + DISPUTE_CANDIDATE_LIFETIME_AFTER_FINALIZATION; @@ -583,8 +583,8 @@ fn scraper_handles_the_same_candidate_included_in_two_different_block_heights() // Finalize blocks to enforce pruning of scraped events. // The magic candidate was added twice, so it shouldn't be removed if we finalize two more // blocks. - finalized_block_number = test_targets.first().expect("there are two block nums") + - DISPUTE_CANDIDATE_LIFETIME_AFTER_FINALIZATION; + finalized_block_number = test_targets.first().expect("there are two block nums") + + DISPUTE_CANDIDATE_LIFETIME_AFTER_FINALIZATION; process_finalized_block(&mut scraper, &finalized_block_number); let magic_candidate = make_candidate_receipt(get_magic_candidate_hash()); diff --git a/pezkuwi/node/core/dispute-coordinator/src/tests.rs b/pezkuwi/node/core/dispute-coordinator/src/tests.rs index af20cf30..f33d9810 100644 --- a/pezkuwi/node/core/dispute-coordinator/src/tests.rs +++ b/pezkuwi/node/core/dispute-coordinator/src/tests.rs @@ -123,8 +123,9 @@ async fn generate_opposing_votes_pair( valid_vote_type: VoteType, ) -> (SignedDisputeStatement, SignedDisputeStatement) { let valid_vote = match valid_vote_type { - VoteType::Backing => - test_state.issue_backing_statement_with_index(valid_voter_idx, candidate_hash, session), + VoteType::Backing => { + test_state.issue_backing_statement_with_index(valid_voter_idx, candidate_hash, session) + }, VoteType::Explicit => test_state.issue_explicit_statement_with_index( valid_voter_idx, candidate_hash, diff --git a/pezkuwi/node/core/prospective-teyrchains/src/fragment_chain/mod.rs b/pezkuwi/node/core/prospective-teyrchains/src/fragment_chain/mod.rs index 38ce8d6d..015096f0 100644 --- a/pezkuwi/node/core/prospective-teyrchains/src/fragment_chain/mod.rs +++ b/pezkuwi/node/core/prospective-teyrchains/src/fragment_chain/mod.rs @@ -768,8 +768,8 @@ impl FragmentChain { /// Return whether this candidate is backed in this chain or the unconnected storage. pub fn is_candidate_backed(&self, hash: &CandidateHash) -> bool { - self.best_chain.candidates.contains(hash) || - matches!( + self.best_chain.candidates.contains(hash) + || matches!( self.unconnected.by_candidate_hash.get(hash), Some(candidate) if candidate.state == CandidateState::Backed ) diff --git a/pezkuwi/node/core/prospective-teyrchains/src/lib.rs b/pezkuwi/node/core/prospective-teyrchains/src/lib.rs index 8bf4a2d9..bd0358bb 100644 --- a/pezkuwi/node/core/prospective-teyrchains/src/lib.rs +++ b/pezkuwi/node/core/prospective-teyrchains/src/lib.rs @@ -156,10 +156,12 @@ async fn run_iteration( }, FromOrchestra::Signal(OverseerSignal::BlockFinalized(..)) => {}, FromOrchestra::Communication { msg } => match msg { - ProspectiveTeyrchainsMessage::IntroduceSecondedCandidate(request, tx) => - handle_introduce_seconded_candidate(view, request, tx, metrics).await, - ProspectiveTeyrchainsMessage::CandidateBacked(para, candidate_hash) => - handle_candidate_backed(view, para, candidate_hash, metrics).await, + ProspectiveTeyrchainsMessage::IntroduceSecondedCandidate(request, tx) => { + handle_introduce_seconded_candidate(view, request, tx, metrics).await + }, + ProspectiveTeyrchainsMessage::CandidateBacked(para, candidate_hash) => { + handle_candidate_backed(view, para, candidate_hash, metrics).await + }, ProspectiveTeyrchainsMessage::GetBackableCandidates( relay_parent, para, @@ -167,12 +169,15 @@ async fn run_iteration( ancestors, tx, ) => answer_get_backable_candidates(&view, relay_parent, para, count, ancestors, tx), - ProspectiveTeyrchainsMessage::GetHypotheticalMembership(request, tx) => - answer_hypothetical_membership_request(&view, request, tx, metrics), - ProspectiveTeyrchainsMessage::GetMinimumRelayParents(relay_parent, tx) => - answer_minimum_relay_parents_request(&view, relay_parent, tx), - ProspectiveTeyrchainsMessage::GetProspectiveValidationData(request, tx) => - answer_prospective_validation_data_request(&view, request, tx), + ProspectiveTeyrchainsMessage::GetHypotheticalMembership(request, tx) => { + answer_hypothetical_membership_request(&view, request, tx, metrics) + }, + ProspectiveTeyrchainsMessage::GetMinimumRelayParents(relay_parent, tx) => { + answer_minimum_relay_parents_request(&view, relay_parent, tx) + }, + ProspectiveTeyrchainsMessage::GetProspectiveValidationData(request, tx) => { + answer_prospective_validation_data_request(&view, request, tx) + }, }, } } diff --git a/pezkuwi/node/core/prospective-teyrchains/src/tests.rs b/pezkuwi/node/core/prospective-teyrchains/src/tests.rs index e0b9ae56..0f615b39 100644 --- a/pezkuwi/node/core/prospective-teyrchains/src/tests.rs +++ b/pezkuwi/node/core/prospective-teyrchains/src/tests.rs @@ -343,9 +343,9 @@ async fn handle_leaf_activation( AllMessages::RuntimeApi(RuntimeApiMessage::Request( parent, RuntimeApiRequest::BackingConstraints(p_id, tx), - )) if parent == *hash && - test_state.runtime_api_version >= - RuntimeApiRequest::CONSTRAINTS_RUNTIME_REQUIREMENT => + )) if parent == *hash + && test_state.runtime_api_version + >= RuntimeApiRequest::CONSTRAINTS_RUNTIME_REQUIREMENT => { let PerParaData { min_relay_parent, head_data, pending_availability: _ } = leaf.para_data(p_id); @@ -362,9 +362,9 @@ async fn handle_leaf_activation( AllMessages::RuntimeApi(RuntimeApiMessage::Request( parent, RuntimeApiRequest::BackingConstraints(_p_id, tx), - )) if parent == *hash && - test_state.runtime_api_version < - RuntimeApiRequest::CONSTRAINTS_RUNTIME_REQUIREMENT => + )) if parent == *hash + && test_state.runtime_api_version + < RuntimeApiRequest::CONSTRAINTS_RUNTIME_REQUIREMENT => { tx.send(Err(RUNTIME_API_NOT_SUPPORTED)).unwrap(); None diff --git a/pezkuwi/node/core/provisioner/src/disputes/prioritized_selection/mod.rs b/pezkuwi/node/core/provisioner/src/disputes/prioritized_selection/mod.rs index d9ae0412..2f91957a 100644 --- a/pezkuwi/node/core/provisioner/src/disputes/prioritized_selection/mod.rs +++ b/pezkuwi/node/core/provisioner/src/disputes/prioritized_selection/mod.rs @@ -332,8 +332,8 @@ fn concluded_onchain(onchain_state: &DisputeState) -> bool { // Check if there are enough onchain votes for or against to conclude the dispute let supermajority = supermajority_threshold(onchain_state.validators_for.len()); - onchain_state.validators_for.count_ones() >= supermajority || - onchain_state.validators_against.count_ones() >= supermajority + onchain_state.validators_for.count_ones() >= supermajority + || onchain_state.validators_against.count_ones() >= supermajority } fn partition_recent_disputes( @@ -347,7 +347,7 @@ fn partition_recent_disputes( let key = (session_index, candidate_hash); if dispute_is_inactive(&dispute_state, time_now) { match onchain.get(&key) { - Some(onchain_state) => + Some(onchain_state) => { if concluded_onchain(onchain_state) { partitioned .inactive_concluded_onchain @@ -356,16 +356,19 @@ fn partition_recent_disputes( partitioned .inactive_unconcluded_onchain .push((session_index, candidate_hash)); - }, + } + }, None => partitioned.inactive_unknown_onchain.push((session_index, candidate_hash)), } } else { match onchain.get(&(session_index, candidate_hash)) { Some(d) => match concluded_onchain(d) { - true => - partitioned.active_concluded_onchain.push((session_index, candidate_hash)), - false => - partitioned.active_unconcluded_onchain.push((session_index, candidate_hash)), + true => { + partitioned.active_concluded_onchain.push((session_index, candidate_hash)) + }, + false => { + partitioned.active_unconcluded_onchain.push((session_index, candidate_hash)) + }, }, None => partitioned.active_unknown_onchain.push((session_index, candidate_hash)), } @@ -389,8 +392,8 @@ fn is_vote_worth_to_keep( // punished when misbehaving. if let Some(kind) = valid_kind { match kind { - ValidDisputeStatementKind::BackingValid(_) | - ValidDisputeStatementKind::BackingSeconded(_) => return true, + ValidDisputeStatementKind::BackingValid(_) + | ValidDisputeStatementKind::BackingSeconded(_) => return true, _ => (), } } @@ -491,10 +494,12 @@ where .map_err(|_| GetOnchainDisputesError::Channel) .and_then(|res| { res.map_err(|e| match e { - RuntimeApiError::Execution { .. } => - GetOnchainDisputesError::Execution(e, relay_parent), - RuntimeApiError::NotSupported { .. } => - GetOnchainDisputesError::NotSupported(e, relay_parent), + RuntimeApiError::Execution { .. } => { + GetOnchainDisputesError::Execution(e, relay_parent) + }, + RuntimeApiError::NotSupported { .. } => { + GetOnchainDisputesError::NotSupported(e, relay_parent) + }, }) }) .map(|v| v.into_iter().map(|e| ((e.0, e.1), e.2)).collect()) diff --git a/pezkuwi/node/core/provisioner/src/disputes/prioritized_selection/tests.rs b/pezkuwi/node/core/provisioner/src/disputes/prioritized_selection/tests.rs index ae205679..bb8e4240 100644 --- a/pezkuwi/node/core/provisioner/src/disputes/prioritized_selection/tests.rs +++ b/pezkuwi/node/core/provisioner/src/disputes/prioritized_selection/tests.rs @@ -666,8 +666,8 @@ fn many_batches() { let vote_count = result.iter().map(|d| d.statements.len()).fold(0, |acc, v| acc + v); assert!( - MAX_DISPUTE_VOTES_FORWARDED_TO_RUNTIME - VALIDATOR_COUNT <= vote_count && - vote_count <= MAX_DISPUTE_VOTES_FORWARDED_TO_RUNTIME, + MAX_DISPUTE_VOTES_FORWARDED_TO_RUNTIME - VALIDATOR_COUNT <= vote_count + && vote_count <= MAX_DISPUTE_VOTES_FORWARDED_TO_RUNTIME, "vote_count: {}", vote_count ); @@ -720,8 +720,8 @@ fn votes_above_limit() { let vote_count = result.iter().map(|d| d.statements.len()).fold(0, |acc, v| acc + v); assert!( - MAX_DISPUTE_VOTES_FORWARDED_TO_RUNTIME - VALIDATOR_COUNT <= vote_count && - vote_count <= MAX_DISPUTE_VOTES_FORWARDED_TO_RUNTIME, + MAX_DISPUTE_VOTES_FORWARDED_TO_RUNTIME - VALIDATOR_COUNT <= vote_count + && vote_count <= MAX_DISPUTE_VOTES_FORWARDED_TO_RUNTIME, "vote_count: {}", vote_count ); diff --git a/pezkuwi/node/core/provisioner/src/lib.rs b/pezkuwi/node/core/provisioner/src/lib.rs index 78738798..f5631cd6 100644 --- a/pezkuwi/node/core/provisioner/src/lib.rs +++ b/pezkuwi/node/core/provisioner/src/lib.rs @@ -396,8 +396,9 @@ fn note_provisionable_data( provisionable_data: ProvisionableData, ) { match provisionable_data { - ProvisionableData::Bitfield(_, signed_bitfield) => - per_relay_parent.signed_bitfields.push(signed_bitfield), + ProvisionableData::Bitfield(_, signed_bitfield) => { + per_relay_parent.signed_bitfields.push(signed_bitfield) + }, // We choose not to punish these forms of misbehavior for the time being. // Risks from misbehavior are sufficiently mitigated at the protocol level // via reputation changes. Punitive actions here may become desirable diff --git a/pezkuwi/node/core/provisioner/src/tests.rs b/pezkuwi/node/core/provisioner/src/tests.rs index 7fef03a3..ff80b3f3 100644 --- a/pezkuwi/node/core/provisioner/src/tests.rs +++ b/pezkuwi/node/core/provisioner/src/tests.rs @@ -572,8 +572,9 @@ mod select_candidates { _parent_hash, PersistedValidationDataReq(_para_id, _assumption, tx), )) => tx.send(Ok(Some(Default::default()))).unwrap(), - AllMessages::RuntimeApi(Request(_parent_hash, AvailabilityCores(tx))) => - tx.send(Ok(mock_availability_cores.clone())).unwrap(), + AllMessages::RuntimeApi(Request(_parent_hash, AvailabilityCores(tx))) => { + tx.send(Ok(mock_availability_cores.clone())).unwrap() + }, AllMessages::CandidateBacking(CandidateBackingMessage::GetBackableCandidates( hashes, sender, diff --git a/pezkuwi/node/core/pvf-checker/src/lib.rs b/pezkuwi/node/core/pvf-checker/src/lib.rs index 8e3664ad..ea95f085 100644 --- a/pezkuwi/node/core/pvf-checker/src/lib.rs +++ b/pezkuwi/node/core/pvf-checker/src/lib.rs @@ -380,14 +380,15 @@ async fn examine_activation( }; let new_session_index = match runtime_api::session_index_for_child(sender, leaf_hash).await { - Ok(session_index) => + Ok(session_index) => { if state.latest_session.map_or(true, |l| l < session_index) { let signing_credentials = check_signing_credentials(sender, keystore, leaf_hash).await; Some((session_index, signing_credentials)) } else { None - }, + } + }, Err(e) => { gum::warn!( target: LOG_TARGET, diff --git a/pezkuwi/node/core/pvf/common/src/error.rs b/pezkuwi/node/core/pvf/common/src/error.rs index f38320a8..15a0be07 100644 --- a/pezkuwi/node/core/pvf/common/src/error.rs +++ b/pezkuwi/node/core/pvf/common/src/error.rs @@ -110,17 +110,17 @@ impl PrepareError { pub fn is_deterministic(&self) -> bool { use PrepareError::*; match self { - Prevalidation(_) | - Preparation(_) | - JobError(_) | - OutOfMemory | - CouldNotDecompressCodeBlob(_) => true, - IoErr(_) | - JobDied { .. } | - CreateTmpFile(_) | - RenameTmpFile { .. } | - ClearWorkerDir(_) | - Kernel(_) => false, + Prevalidation(_) + | Preparation(_) + | JobError(_) + | OutOfMemory + | CouldNotDecompressCodeBlob(_) => true, + IoErr(_) + | JobDied { .. } + | CreateTmpFile(_) + | RenameTmpFile { .. } + | ClearWorkerDir(_) + | Kernel(_) => false, // Can occur due to issues with the PVF, but also due to factors like local load. TimedOut => false, // Can occur due to issues with the PVF, but also due to local errors. diff --git a/pezkuwi/node/core/pvf/common/src/executor_interface.rs b/pezkuwi/node/core/pvf/common/src/executor_interface.rs index c09537ee..a909218a 100644 --- a/pezkuwi/node/core/pvf/common/src/executor_interface.rs +++ b/pezkuwi/node/core/pvf/common/src/executor_interface.rs @@ -160,16 +160,17 @@ pub fn params_to_wasmtime_semantics(par: &ExecutorParams) -> (Semantics, Determi for p in par.iter() { match p { - ExecutorParam::MaxMemoryPages(max_pages) => + ExecutorParam::MaxMemoryPages(max_pages) => { sem.heap_alloc_strategy = HeapAllocStrategy::Dynamic { maximum_pages: Some((*max_pages).saturating_add(DEFAULT_HEAP_PAGES_ESTIMATE)), - }, + } + }, ExecutorParam::StackLogicalMax(slm) => stack_limit.logical_max = *slm, ExecutorParam::StackNativeMax(snm) => stack_limit.native_stack_max = *snm, ExecutorParam::WasmExtBulkMemory => sem.wasm_bulk_memory = true, - ExecutorParam::PrecheckingMaxMemory(_) | - ExecutorParam::PvfPrepTimeout(_, _) | - ExecutorParam::PvfExecTimeout(_, _) => (), /* Not used here */ + ExecutorParam::PrecheckingMaxMemory(_) + | ExecutorParam::PvfPrepTimeout(_, _) + | ExecutorParam::PvfExecTimeout(_, _) => (), /* Not used here */ } } sem.deterministic_stack_limit = Some(stack_limit.clone()); diff --git a/pezkuwi/node/core/pvf/common/src/pvf.rs b/pezkuwi/node/core/pvf/common/src/pvf.rs index 84d32c0c..436446f4 100644 --- a/pezkuwi/node/core/pvf/common/src/pvf.rs +++ b/pezkuwi/node/core/pvf/common/src/pvf.rs @@ -133,8 +133,8 @@ impl fmt::Debug for PvfPrepData { impl PartialEq for PvfPrepData { fn eq(&self, other: &Self) -> bool { - self.code_hash == other.code_hash && - self.executor_params.hash() == other.executor_params.hash() + self.code_hash == other.code_hash + && self.executor_params.hash() == other.executor_params.hash() } } diff --git a/pezkuwi/node/core/pvf/common/src/worker/mod.rs b/pezkuwi/node/core/pvf/common/src/worker/mod.rs index 9cd6a86a..7bf01496 100644 --- a/pezkuwi/node/core/pvf/common/src/worker/mod.rs +++ b/pezkuwi/node/core/pvf/common/src/worker/mod.rs @@ -562,8 +562,8 @@ fn recv_worker_handshake(stream: &mut UnixStream) -> io::Result /// /// Returns a `Duration` representing the total CPU time. pub fn get_total_cpu_usage(rusage: Usage) -> Duration { - let micros = (((rusage.user_time().tv_sec() + rusage.system_time().tv_sec()) * 1_000_000) + - (rusage.system_time().tv_usec() + rusage.user_time().tv_usec()) as i64) as u64; + let micros = (((rusage.user_time().tv_sec() + rusage.system_time().tv_sec()) * 1_000_000) + + (rusage.system_time().tv_usec() + rusage.user_time().tv_usec()) as i64) as u64; return Duration::from_micros(micros); } diff --git a/pezkuwi/node/core/pvf/common/src/worker/security/change_root.rs b/pezkuwi/node/core/pvf/common/src/worker/security/change_root.rs index b07e1639..60992749 100644 --- a/pezkuwi/node/core/pvf/common/src/worker/security/change_root.rs +++ b/pezkuwi/node/core/pvf/common/src/worker/security/change_root.rs @@ -121,11 +121,12 @@ fn try_restrict(worker_info: &WorkerInfo) -> Result<()> { worker_dir_path_c.as_ptr(), worker_dir_path_c.as_ptr(), ptr::null(), // ignored when MS_BIND is used - libc::MS_BIND | - libc::MS_REC | libc::MS_NOEXEC | - libc::MS_NODEV | libc::MS_NOSUID | - libc::MS_NOATIME | - additional_flags, + libc::MS_BIND + | libc::MS_REC | libc::MS_NOEXEC + | libc::MS_NODEV + | libc::MS_NOSUID + | libc::MS_NOATIME + | additional_flags, ptr::null(), // ignored when MS_BIND is used ) < 0 { diff --git a/pezkuwi/node/core/pvf/common/src/worker/security/clone.rs b/pezkuwi/node/core/pvf/common/src/worker/security/clone.rs index 739e2ae5..337bd1e7 100644 --- a/pezkuwi/node/core/pvf/common/src/worker/security/clone.rs +++ b/pezkuwi/node/core/pvf/common/src/worker/security/clone.rs @@ -82,12 +82,12 @@ fn clone_flags(have_unshare_newuser: bool) -> CloneFlags { // SIGCHLD flag is used to inform clone that the parent process is // expecting a child termination signal, without this flag `waitpid` function // return `ECHILD` error. - maybe_clone_newuser | - CloneFlags::CLONE_NEWCGROUP | - CloneFlags::CLONE_NEWIPC | - CloneFlags::CLONE_NEWNET | - CloneFlags::CLONE_NEWNS | - CloneFlags::CLONE_NEWPID | - CloneFlags::CLONE_NEWUTS | - CloneFlags::from_bits_retain(libc::SIGCHLD) + maybe_clone_newuser + | CloneFlags::CLONE_NEWCGROUP + | CloneFlags::CLONE_NEWIPC + | CloneFlags::CLONE_NEWNET + | CloneFlags::CLONE_NEWNS + | CloneFlags::CLONE_NEWPID + | CloneFlags::CLONE_NEWUTS + | CloneFlags::from_bits_retain(libc::SIGCHLD) } diff --git a/pezkuwi/node/core/pvf/execute-worker/src/lib.rs b/pezkuwi/node/core/pvf/execute-worker/src/lib.rs index f3513482..9b845508 100644 --- a/pezkuwi/node/core/pvf/execute-worker/src/lib.rs +++ b/pezkuwi/node/core/pvf/execute-worker/src/lib.rs @@ -319,18 +319,20 @@ fn validate_using_artifact( // [`executor_interface::prepare`]. execute_artifact(compiled_artifact_blob, executor_params, params) } { - Err(ExecuteError::RuntimeConstruction(wasmerr)) => - return JobResponse::runtime_construction("execute", &wasmerr.to_string()), + Err(ExecuteError::RuntimeConstruction(wasmerr)) => { + return JobResponse::runtime_construction("execute", &wasmerr.to_string()) + }, Err(err) => return JobResponse::format_invalid("execute", &err.to_string()), Ok(d) => d, }; let result_descriptor = match ValidationResult::decode(&mut &descriptor_bytes[..]) { - Err(err) => + Err(err) => { return JobResponse::format_invalid( "validation result decoding failed", &err.to_string(), - ), + ) + }, Ok(r) => r, }; @@ -383,8 +385,9 @@ fn handle_clone( pov_size, execution_timeout, ), - Err(security::clone::Error::Clone(errno)) => - Ok(Err(internal_error_from_errno("clone", errno))), + Err(security::clone::Error::Clone(errno)) => { + Ok(Err(internal_error_from_errno("clone", errno))) + }, } } diff --git a/pezkuwi/node/core/pvf/src/artifacts.rs b/pezkuwi/node/core/pvf/src/artifacts.rs index 28c06837..89f6ad75 100644 --- a/pezkuwi/node/core/pvf/src/artifacts.rs +++ b/pezkuwi/node/core/pvf/src/artifacts.rs @@ -243,8 +243,8 @@ impl Artifacts { let Some(file_name) = path.file_name().and_then(|f| f.to_str()) else { continue }; if path.is_dir() && file_name.starts_with(WORKER_DIR_PREFIX) { let _ = fs::remove_dir_all(path); - } else if path.extension().map_or(false, |ext| ext == ARTIFACT_EXTENSION) || - file_name.starts_with(ARTIFACT_OLD_PREFIX) + } else if path.extension().map_or(false, |ext| ext == ARTIFACT_EXTENSION) + || file_name.starts_with(ARTIFACT_OLD_PREFIX) { let _ = fs::remove_file(path); } diff --git a/pezkuwi/node/core/pvf/src/execute/queue.rs b/pezkuwi/node/core/pvf/src/execute/queue.rs index 1c39b627..221161a7 100644 --- a/pezkuwi/node/core/pvf/src/execute/queue.rs +++ b/pezkuwi/node/core/pvf/src/execute/queue.rs @@ -524,14 +524,16 @@ async fn handle_job_finish( ) }, - Err(WorkerInterfaceError::InternalError(err)) | - Err(WorkerInterfaceError::WorkerError(WorkerError::InternalError(err))) => - (None, Err(ValidationError::Internal(err)), None, None, None), + Err(WorkerInterfaceError::InternalError(err)) + | Err(WorkerInterfaceError::WorkerError(WorkerError::InternalError(err))) => { + (None, Err(ValidationError::Internal(err)), None, None, None) + }, // Either the worker or the job timed out. Kill the worker in either case. Treated as // definitely-invalid, because if we timed out, there's no time left for a retry. - Err(WorkerInterfaceError::HardTimeout) | - Err(WorkerInterfaceError::WorkerError(WorkerError::JobTimedOut)) => - (None, Err(ValidationError::Invalid(InvalidCandidate::HardTimeout)), None, None, None), + Err(WorkerInterfaceError::HardTimeout) + | Err(WorkerInterfaceError::WorkerError(WorkerError::JobTimedOut)) => { + (None, Err(ValidationError::Invalid(InvalidCandidate::HardTimeout)), None, None, None) + }, // "Maybe invalid" errors (will retry). Err(WorkerInterfaceError::CommunicationErr(_err)) => ( None, diff --git a/pezkuwi/node/core/pvf/src/host.rs b/pezkuwi/node/core/pvf/src/host.rs index 476f4c62..09cb4c5c 100644 --- a/pezkuwi/node/core/pvf/src/host.rs +++ b/pezkuwi/node/core/pvf/src/host.rs @@ -533,10 +533,12 @@ async fn handle_to_host( handle_execute_pvf(artifacts, prepare_queue, execute_queue, awaiting_prepare, inputs) .await?; }, - ToHost::HeadsUp { active_pvfs } => - handle_heads_up(artifacts, prepare_queue, active_pvfs).await?, - ToHost::UpdateActiveLeaves { update, ancestors } => - handle_update_active_leaves(execute_queue, update, ancestors).await?, + ToHost::HeadsUp { active_pvfs } => { + handle_heads_up(artifacts, prepare_queue, active_pvfs).await? + }, + ToHost::UpdateActiveLeaves { update, ancestors } => { + handle_update_active_leaves(execute_queue, update, ancestors).await? + }, #[cfg(feature = "test-utils")] ToHost::ReplaceArtifactChecksum { checksum, new_checksum } => { artifacts.replace_artifact_checksum(checksum, new_checksum); @@ -567,8 +569,9 @@ async fn handle_precheck_pvf( *last_time_needed = SystemTime::now(); let _ = result_sender.send(Ok(())); }, - ArtifactState::Preparing { waiting_for_response, num_failures: _ } => - waiting_for_response.push(result_sender), + ArtifactState::Preparing { waiting_for_response, num_failures: _ } => { + waiting_for_response.push(result_sender) + }, ArtifactState::FailedToProcess { error, .. } => { // Do not retry an artifact that previously failed preparation. let _ = result_sender.send(PrecheckResult::Err(error.clone())); @@ -887,8 +890,9 @@ async fn handle_prepare_done( } *state = match result { - Ok(PrepareSuccess { checksum, path, size, .. }) => - ArtifactState::Prepared { checksum, path, last_time_needed: SystemTime::now(), size }, + Ok(PrepareSuccess { checksum, path, size, .. }) => { + ArtifactState::Prepared { checksum, path, last_time_needed: SystemTime::now(), size } + }, Err(error) => { let last_time_failed = SystemTime::now(); let num_failures = *num_failures + 1; @@ -1033,8 +1037,8 @@ fn can_retry_prepare_after_failure( // Retry if the retry cooldown has elapsed and if we have already retried less than // `NUM_PREPARE_RETRIES` times. IO errors may resolve themselves. - SystemTime::now() >= last_time_failed + PREPARE_FAILURE_COOLDOWN && - num_failures <= NUM_PREPARE_RETRIES + SystemTime::now() >= last_time_failed + PREPARE_FAILURE_COOLDOWN + && num_failures <= NUM_PREPARE_RETRIES } /// A stream that yields a pulse continuously at a given interval. diff --git a/pezkuwi/node/core/pvf/src/prepare/pool.rs b/pezkuwi/node/core/pvf/src/prepare/pool.rs index d6e5a2c7..79f80481 100644 --- a/pezkuwi/node/core/pvf/src/prepare/pool.rs +++ b/pezkuwi/node/core/pvf/src/prepare/pool.rs @@ -330,8 +330,9 @@ fn handle_mux( // If we receive an outcome that the worker is unreachable or that an error occurred on // the worker, we attempt to kill the worker process. match outcome { - Outcome::Concluded { worker: idle, result } => - handle_concluded_no_rip(from_pool, spawned, worker, idle, result), + Outcome::Concluded { worker: idle, result } => { + handle_concluded_no_rip(from_pool, spawned, worker, idle, result) + }, // Return `Concluded`, but do not kill the worker since the error was on the host // side. Outcome::CreateTmpFileErr { worker: idle, err } => handle_concluded_no_rip( diff --git a/pezkuwi/node/core/pvf/src/prepare/queue.rs b/pezkuwi/node/core/pvf/src/prepare/queue.rs index f579a584..93a97e66 100644 --- a/pezkuwi/node/core/pvf/src/prepare/queue.rs +++ b/pezkuwi/node/core/pvf/src/prepare/queue.rs @@ -271,8 +271,9 @@ async fn handle_from_pool(queue: &mut Queue, from_pool: pool::FromPool) -> Resul use pool::FromPool; match from_pool { FromPool::Spawned(worker) => handle_worker_spawned(queue, worker).await?, - FromPool::Concluded { worker, rip, result } => - handle_worker_concluded(queue, worker, rip, result).await?, + FromPool::Concluded { worker, rip, result } => { + handle_worker_concluded(queue, worker, rip, result).await? + }, FromPool::Rip(worker) => handle_worker_rip(queue, worker).await?, } Ok(()) diff --git a/pezkuwi/node/core/pvf/src/prepare/worker_interface.rs b/pezkuwi/node/core/pvf/src/prepare/worker_interface.rs index 9059a38d..d9df5027 100644 --- a/pezkuwi/node/core/pvf/src/prepare/worker_interface.rs +++ b/pezkuwi/node/core/pvf/src/prepare/worker_interface.rs @@ -157,7 +157,7 @@ pub async fn start_work( match result { // Received bytes from worker within the time limit. - Ok(Ok(prepare_worker_result)) => + Ok(Ok(prepare_worker_result)) => { handle_response( metrics, IdleWorker { stream, pid, worker_dir }, @@ -167,7 +167,8 @@ pub async fn start_work( &cache_path, preparation_timeout, ) - .await, + .await + }, Ok(Err(err)) => { // Communication error within the time limit. gum::warn!( diff --git a/pezkuwi/node/core/pvf/src/security.rs b/pezkuwi/node/core/pvf/src/security.rs index 610fa20f..19629fa7 100644 --- a/pezkuwi/node/core/pvf/src/security.rs +++ b/pezkuwi/node/core/pvf/src/security.rs @@ -105,8 +105,8 @@ impl FullSecurityStatus { } fn all_errs_allowed(&self) -> bool { - !self.partial.secure_validator_mode || - self.errs.iter().all(|err| err.is_allowed_in_secure_mode(&self.partial)) + !self.partial.secure_validator_mode + || self.errs.iter().all(|err| err.is_allowed_in_secure_mode(&self.partial)) } fn errs_string(&self) -> String { @@ -141,8 +141,9 @@ impl SecureModeError { match self { // Landlock is present on relatively recent Linuxes. This is optional if the unshare // capability is present, providing FS sandboxing a different way. - CannotEnableLandlock { .. } => - security_status.can_unshare_user_namespace_and_change_root, + CannotEnableLandlock { .. } => { + security_status.can_unshare_user_namespace_and_change_root + }, // seccomp should be present on all modern Linuxes unless it's been disabled. CannotEnableSeccomp(_) => false, // Should always be present on modern Linuxes. If not, Landlock also provides FS diff --git a/pezkuwi/node/core/runtime-api/src/lib.rs b/pezkuwi/node/core/runtime-api/src/lib.rs index f2967b9a..4d6d3461 100644 --- a/pezkuwi/node/core/runtime-api/src/lib.rs +++ b/pezkuwi/node/core/runtime-api/src/lib.rs @@ -97,17 +97,21 @@ where use RequestResult::*; match result { - Authorities(relay_parent, authorities) => - self.requests_cache.cache_authorities(relay_parent, authorities), - Validators(relay_parent, validators) => - self.requests_cache.cache_validators(relay_parent, validators), + Authorities(relay_parent, authorities) => { + self.requests_cache.cache_authorities(relay_parent, authorities) + }, + Validators(relay_parent, validators) => { + self.requests_cache.cache_validators(relay_parent, validators) + }, MinimumBackingVotes(session_index, minimum_backing_votes) => self .requests_cache .cache_minimum_backing_votes(session_index, minimum_backing_votes), - ValidatorGroups(relay_parent, groups) => - self.requests_cache.cache_validator_groups(relay_parent, groups), - AvailabilityCores(relay_parent, cores) => - self.requests_cache.cache_availability_cores(relay_parent, cores), + ValidatorGroups(relay_parent, groups) => { + self.requests_cache.cache_validator_groups(relay_parent, groups) + }, + AvailabilityCores(relay_parent, cores) => { + self.requests_cache.cache_availability_cores(relay_parent, cores) + }, PersistedValidationData(relay_parent, para_id, assumption, data) => self .requests_cache .cache_persisted_validation_data((relay_parent, para_id, assumption), data), @@ -123,66 +127,82 @@ where CheckValidationOutputs(relay_parent, para_id, commitments, b) => self .requests_cache .cache_check_validation_outputs((relay_parent, para_id, commitments), b), - SessionIndexForChild(relay_parent, session_index) => - self.requests_cache.cache_session_index_for_child(relay_parent, session_index), + SessionIndexForChild(relay_parent, session_index) => { + self.requests_cache.cache_session_index_for_child(relay_parent, session_index) + }, ValidationCode(relay_parent, para_id, assumption, code) => self .requests_cache .cache_validation_code((relay_parent, para_id, assumption), code), - ValidationCodeByHash(_relay_parent, validation_code_hash, code) => - self.requests_cache.cache_validation_code_by_hash(validation_code_hash, code), + ValidationCodeByHash(_relay_parent, validation_code_hash, code) => { + self.requests_cache.cache_validation_code_by_hash(validation_code_hash, code) + }, CandidatePendingAvailability(relay_parent, para_id, candidate) => self .requests_cache .cache_candidate_pending_availability((relay_parent, para_id), candidate), CandidatesPendingAvailability(relay_parent, para_id, candidates) => self .requests_cache .cache_candidates_pending_availability((relay_parent, para_id), candidates), - CandidateEvents(relay_parent, events) => - self.requests_cache.cache_candidate_events(relay_parent, events), - SessionExecutorParams(_relay_parent, session_index, index) => - self.requests_cache.cache_session_executor_params(session_index, index), - SessionInfo(_relay_parent, session_index, info) => + CandidateEvents(relay_parent, events) => { + self.requests_cache.cache_candidate_events(relay_parent, events) + }, + SessionExecutorParams(_relay_parent, session_index, index) => { + self.requests_cache.cache_session_executor_params(session_index, index) + }, + SessionInfo(_relay_parent, session_index, info) => { if let Some(info) = info { self.requests_cache.cache_session_info(session_index, info); - }, - DmqContents(relay_parent, para_id, messages) => - self.requests_cache.cache_dmq_contents((relay_parent, para_id), messages), + } + }, + DmqContents(relay_parent, para_id, messages) => { + self.requests_cache.cache_dmq_contents((relay_parent, para_id), messages) + }, InboundHrmpChannelsContents(relay_parent, para_id, contents) => self .requests_cache .cache_inbound_hrmp_channel_contents((relay_parent, para_id), contents), - CurrentBabeEpoch(relay_parent, epoch) => - self.requests_cache.cache_current_babe_epoch(relay_parent, epoch), - FetchOnChainVotes(relay_parent, scraped) => - self.requests_cache.cache_on_chain_votes(relay_parent, scraped), - PvfsRequirePrecheck(relay_parent, pvfs) => - self.requests_cache.cache_pvfs_require_precheck(relay_parent, pvfs), + CurrentBabeEpoch(relay_parent, epoch) => { + self.requests_cache.cache_current_babe_epoch(relay_parent, epoch) + }, + FetchOnChainVotes(relay_parent, scraped) => { + self.requests_cache.cache_on_chain_votes(relay_parent, scraped) + }, + PvfsRequirePrecheck(relay_parent, pvfs) => { + self.requests_cache.cache_pvfs_require_precheck(relay_parent, pvfs) + }, SubmitPvfCheckStatement(()) => {}, ValidationCodeHash(relay_parent, para_id, assumption, hash) => self .requests_cache .cache_validation_code_hash((relay_parent, para_id, assumption), hash), - Version(relay_parent, version) => - self.requests_cache.cache_version(relay_parent, version), - Disputes(relay_parent, disputes) => - self.requests_cache.cache_disputes(relay_parent, disputes), - UnappliedSlashes(relay_parent, unapplied_slashes) => - self.requests_cache.cache_unapplied_slashes(relay_parent, unapplied_slashes), + Version(relay_parent, version) => { + self.requests_cache.cache_version(relay_parent, version) + }, + Disputes(relay_parent, disputes) => { + self.requests_cache.cache_disputes(relay_parent, disputes) + }, + UnappliedSlashes(relay_parent, unapplied_slashes) => { + self.requests_cache.cache_unapplied_slashes(relay_parent, unapplied_slashes) + }, UnappliedSlashesV2(relay_parent, unapplied_slashes_v2) => self .requests_cache .cache_unapplied_slashes_v2(relay_parent, unapplied_slashes_v2), KeyOwnershipProof(relay_parent, validator_id, key_ownership_proof) => self .requests_cache .cache_key_ownership_proof((relay_parent, validator_id), key_ownership_proof), - ApprovalVotingParams(_relay_parent, session_index, params) => - self.requests_cache.cache_approval_voting_params(session_index, params), + ApprovalVotingParams(_relay_parent, session_index, params) => { + self.requests_cache.cache_approval_voting_params(session_index, params) + }, SubmitReportDisputeLost(_) => {}, - DisabledValidators(relay_parent, disabled_validators) => - self.requests_cache.cache_disabled_validators(relay_parent, disabled_validators), + DisabledValidators(relay_parent, disabled_validators) => { + self.requests_cache.cache_disabled_validators(relay_parent, disabled_validators) + }, ParaBackingState(relay_parent, para_id, constraints) => self .requests_cache .cache_para_backing_state((relay_parent, para_id), constraints), - AsyncBackingParams(relay_parent, params) => - self.requests_cache.cache_async_backing_params(relay_parent, params), - NodeFeatures(session_index, params) => - self.requests_cache.cache_node_features(session_index, params), + AsyncBackingParams(relay_parent, params) => { + self.requests_cache.cache_async_backing_params(relay_parent, params) + }, + NodeFeatures(session_index, params) => { + self.requests_cache.cache_node_features(session_index, params) + }, ClaimQueue(relay_parent, sender) => { self.requests_cache.cache_claim_queue(relay_parent, sender); }, @@ -192,8 +212,9 @@ where SchedulingLookahead(session_index, scheduling_lookahead) => self .requests_cache .cache_scheduling_lookahead(session_index, scheduling_lookahead), - ValidationCodeBombLimit(session_index, limit) => - self.requests_cache.cache_validation_code_bomb_limit(session_index, limit), + ValidationCodeBombLimit(session_index, limit) => { + self.requests_cache.cache_validation_code_bomb_limit(session_index, limit) + }, ParaIds(session_index, para_ids) => { self.requests_cache.cache_para_ids(session_index, para_ids); }, @@ -227,19 +248,24 @@ where } match request { - Request::Version(sender) => - query!(version(), sender).map(|sender| Request::Version(sender)), - Request::Authorities(sender) => - query!(authorities(), sender).map(|sender| Request::Authorities(sender)), - Request::Validators(sender) => - query!(validators(), sender).map(|sender| Request::Validators(sender)), - Request::ValidatorGroups(sender) => - query!(validator_groups(), sender).map(|sender| Request::ValidatorGroups(sender)), + Request::Version(sender) => { + query!(version(), sender).map(|sender| Request::Version(sender)) + }, + Request::Authorities(sender) => { + query!(authorities(), sender).map(|sender| Request::Authorities(sender)) + }, + Request::Validators(sender) => { + query!(validators(), sender).map(|sender| Request::Validators(sender)) + }, + Request::ValidatorGroups(sender) => { + query!(validator_groups(), sender).map(|sender| Request::ValidatorGroups(sender)) + }, Request::AvailabilityCores(sender) => query!(availability_cores(), sender) .map(|sender| Request::AvailabilityCores(sender)), - Request::PersistedValidationData(para, assumption, sender) => + Request::PersistedValidationData(para, assumption, sender) => { query!(persisted_validation_data(para, assumption), sender) - .map(|sender| Request::PersistedValidationData(para, assumption, sender)), + .map(|sender| Request::PersistedValidationData(para, assumption, sender)) + }, Request::AssumedValidationData( para, expected_persisted_validation_data_hash, @@ -255,25 +281,31 @@ where sender, ) }), - Request::CheckValidationOutputs(para, commitments, sender) => + Request::CheckValidationOutputs(para, commitments, sender) => { query!(check_validation_outputs(para, commitments), sender) - .map(|sender| Request::CheckValidationOutputs(para, commitments, sender)), + .map(|sender| Request::CheckValidationOutputs(para, commitments, sender)) + }, Request::SessionIndexForChild(sender) => query!(session_index_for_child(), sender) .map(|sender| Request::SessionIndexForChild(sender)), - Request::ValidationCode(para, assumption, sender) => + Request::ValidationCode(para, assumption, sender) => { query!(validation_code(para, assumption), sender) - .map(|sender| Request::ValidationCode(para, assumption, sender)), - Request::ValidationCodeByHash(validation_code_hash, sender) => + .map(|sender| Request::ValidationCode(para, assumption, sender)) + }, + Request::ValidationCodeByHash(validation_code_hash, sender) => { query!(validation_code_by_hash(validation_code_hash), sender) - .map(|sender| Request::ValidationCodeByHash(validation_code_hash, sender)), - Request::CandidatePendingAvailability(para, sender) => + .map(|sender| Request::ValidationCodeByHash(validation_code_hash, sender)) + }, + Request::CandidatePendingAvailability(para, sender) => { query!(candidate_pending_availability(para), sender) - .map(|sender| Request::CandidatePendingAvailability(para, sender)), - Request::CandidatesPendingAvailability(para, sender) => + .map(|sender| Request::CandidatePendingAvailability(para, sender)) + }, + Request::CandidatesPendingAvailability(para, sender) => { query!(candidates_pending_availability(para), sender) - .map(|sender| Request::CandidatesPendingAvailability(para, sender)), - Request::CandidateEvents(sender) => - query!(candidate_events(), sender).map(|sender| Request::CandidateEvents(sender)), + .map(|sender| Request::CandidatesPendingAvailability(para, sender)) + }, + Request::CandidateEvents(sender) => { + query!(candidate_events(), sender).map(|sender| Request::CandidateEvents(sender)) + }, Request::SessionExecutorParams(session_index, sender) => { if let Some(executor_params) = self.requests_cache.session_executor_params(session_index) @@ -294,42 +326,52 @@ where Some(Request::SessionInfo(index, sender)) } }, - Request::DmqContents(id, sender) => - query!(dmq_contents(id), sender).map(|sender| Request::DmqContents(id, sender)), - Request::InboundHrmpChannelsContents(id, sender) => + Request::DmqContents(id, sender) => { + query!(dmq_contents(id), sender).map(|sender| Request::DmqContents(id, sender)) + }, + Request::InboundHrmpChannelsContents(id, sender) => { query!(inbound_hrmp_channels_contents(id), sender) - .map(|sender| Request::InboundHrmpChannelsContents(id, sender)), - Request::CurrentBabeEpoch(sender) => - query!(current_babe_epoch(), sender).map(|sender| Request::CurrentBabeEpoch(sender)), - Request::FetchOnChainVotes(sender) => - query!(on_chain_votes(), sender).map(|sender| Request::FetchOnChainVotes(sender)), + .map(|sender| Request::InboundHrmpChannelsContents(id, sender)) + }, + Request::CurrentBabeEpoch(sender) => { + query!(current_babe_epoch(), sender).map(|sender| Request::CurrentBabeEpoch(sender)) + }, + Request::FetchOnChainVotes(sender) => { + query!(on_chain_votes(), sender).map(|sender| Request::FetchOnChainVotes(sender)) + }, Request::PvfsRequirePrecheck(sender) => query!(pvfs_require_precheck(), sender) .map(|sender| Request::PvfsRequirePrecheck(sender)), request @ Request::SubmitPvfCheckStatement(_, _, _) => { // This request is side-effecting and thus cannot be cached. Some(request) }, - Request::ValidationCodeHash(para, assumption, sender) => + Request::ValidationCodeHash(para, assumption, sender) => { query!(validation_code_hash(para, assumption), sender) - .map(|sender| Request::ValidationCodeHash(para, assumption, sender)), - Request::Disputes(sender) => - query!(disputes(), sender).map(|sender| Request::Disputes(sender)), - Request::UnappliedSlashes(sender) => - query!(unapplied_slashes(), sender).map(|sender| Request::UnappliedSlashes(sender)), + .map(|sender| Request::ValidationCodeHash(para, assumption, sender)) + }, + Request::Disputes(sender) => { + query!(disputes(), sender).map(|sender| Request::Disputes(sender)) + }, + Request::UnappliedSlashes(sender) => { + query!(unapplied_slashes(), sender).map(|sender| Request::UnappliedSlashes(sender)) + }, Request::UnappliedSlashesV2(sender) => query!(unapplied_slashes_v2(), sender) .map(|sender| Request::UnappliedSlashesV2(sender)), - Request::KeyOwnershipProof(validator_id, sender) => + Request::KeyOwnershipProof(validator_id, sender) => { query!(key_ownership_proof(validator_id), sender) - .map(|sender| Request::KeyOwnershipProof(validator_id, sender)), - Request::SubmitReportDisputeLost(dispute_proof, key_ownership_proof, sender) => + .map(|sender| Request::KeyOwnershipProof(validator_id, sender)) + }, + Request::SubmitReportDisputeLost(dispute_proof, key_ownership_proof, sender) => { query!(submit_report_dispute_lost(dispute_proof, key_ownership_proof), sender).map( |sender| { Request::SubmitReportDisputeLost(dispute_proof, key_ownership_proof, sender) }, - ), - Request::ApprovalVotingParams(session_index, sender) => + ) + }, + Request::ApprovalVotingParams(session_index, sender) => { query!(approval_voting_params(session_index), sender) - .map(|sender| Request::ApprovalVotingParams(session_index, sender)), + .map(|sender| Request::ApprovalVotingParams(session_index, sender)) + }, Request::DisabledValidators(sender) => query!(disabled_validators(), sender) .map(|sender| Request::DisabledValidators(sender)), Request::ParaBackingState(para, sender) => query!(para_backing_state(para), sender) @@ -354,8 +396,9 @@ where Some(Request::NodeFeatures(index, sender)) } }, - Request::ClaimQueue(sender) => - query!(claim_queue(), sender).map(|sender| Request::ClaimQueue(sender)), + Request::ClaimQueue(sender) => { + query!(claim_queue(), sender).map(|sender| Request::ClaimQueue(sender)) + }, Request::BackingConstraints(para, sender) => query!(backing_constraints(para), sender) .map(|sender| Request::BackingConstraints(para, sender)), Request::SchedulingLookahead(index, sender) => { diff --git a/pezkuwi/node/malus/src/variants/common.rs b/pezkuwi/node/malus/src/variants/common.rs index 8cdd5166..0ac2047a 100644 --- a/pezkuwi/node/malus/src/variants/common.rs +++ b/pezkuwi/node/malus/src/variants/common.rs @@ -67,8 +67,9 @@ impl FakeCandidateValidation { use FakeCandidateValidation::*; match *self { - BackingInvalid | BackingAndApprovalInvalid | BackingValid | BackingAndApprovalValid => - true, + BackingInvalid | BackingAndApprovalInvalid | BackingValid | BackingAndApprovalValid => { + true + }, _ => false, } } @@ -77,10 +78,10 @@ impl FakeCandidateValidation { use FakeCandidateValidation::*; match *self { - ApprovalInvalid | - BackingAndApprovalInvalid | - ApprovalValid | - BackingAndApprovalValid => true, + ApprovalInvalid + | BackingAndApprovalInvalid + | ApprovalValid + | BackingAndApprovalValid => true, _ => false, } } @@ -126,20 +127,23 @@ pub enum FakeCandidateValidationError { impl Into for FakeCandidateValidationError { fn into(self) -> InvalidCandidate { match self { - FakeCandidateValidationError::ExecutionError => - InvalidCandidate::ExecutionError("Malus".into()), + FakeCandidateValidationError::ExecutionError => { + InvalidCandidate::ExecutionError("Malus".into()) + }, FakeCandidateValidationError::InvalidOutputs => InvalidCandidate::InvalidOutputs, FakeCandidateValidationError::Timeout => InvalidCandidate::Timeout, FakeCandidateValidationError::ParamsTooLarge => InvalidCandidate::ParamsTooLarge(666), FakeCandidateValidationError::CodeTooLarge => InvalidCandidate::CodeTooLarge(666), - FakeCandidateValidationError::POVDecompressionFailure => - InvalidCandidate::PoVDecompressionFailure, + FakeCandidateValidationError::POVDecompressionFailure => { + InvalidCandidate::PoVDecompressionFailure + }, FakeCandidateValidationError::BadReturn => InvalidCandidate::BadReturn, FakeCandidateValidationError::BadParent => InvalidCandidate::BadParent, FakeCandidateValidationError::POVHashMismatch => InvalidCandidate::PoVHashMismatch, FakeCandidateValidationError::BadSignature => InvalidCandidate::BadSignature, - FakeCandidateValidationError::ParaHeadHashMismatch => - InvalidCandidate::ParaHeadHashMismatch, + FakeCandidateValidationError::ParaHeadHashMismatch => { + InvalidCandidate::ParaHeadHashMismatch + }, FakeCandidateValidationError::CodeHashMismatch => InvalidCandidate::CodeHashMismatch, } } diff --git a/pezkuwi/node/malus/src/variants/dispute_finalized_candidates.rs b/pezkuwi/node/malus/src/variants/dispute_finalized_candidates.rs index a2746f12..a986401b 100644 --- a/pezkuwi/node/malus/src/variants/dispute_finalized_candidates.rs +++ b/pezkuwi/node/malus/src/variants/dispute_finalized_candidates.rs @@ -148,8 +148,9 @@ where matches!(event, CandidateEvent::CandidateIncluded(_, _, _, _)) }); let candidate = match event { - Some(CandidateEvent::CandidateIncluded(candidate, _, _, _)) => - candidate, + Some(CandidateEvent::CandidateIncluded(candidate, _, _, _)) => { + candidate + }, _ => { gum::error!( target: MALUS, diff --git a/pezkuwi/node/metrics/src/runtime/mod.rs b/pezkuwi/node/metrics/src/runtime/mod.rs index b84f9ef5..50037248 100644 --- a/pezkuwi/node/metrics/src/runtime/mod.rs +++ b/pezkuwi/node/metrics/src/runtime/mod.rs @@ -184,12 +184,15 @@ impl RuntimeMetricsProvider { // Parse end execute the update operation. fn parse_metric_update(&self, update: RuntimeMetricUpdate) { match update.op { - RuntimeMetricOp::IncrementCounterVec(value, ref labels) => - self.inc_counter_vec_by(update.metric_name(), value, labels), - RuntimeMetricOp::IncrementCounter(value) => - self.inc_counter_by(update.metric_name(), value), - RuntimeMetricOp::ObserveHistogram(value) => - self.observe_histogram(update.metric_name(), value), + RuntimeMetricOp::IncrementCounterVec(value, ref labels) => { + self.inc_counter_vec_by(update.metric_name(), value, labels) + }, + RuntimeMetricOp::IncrementCounter(value) => { + self.inc_counter_by(update.metric_name(), value) + }, + RuntimeMetricOp::ObserveHistogram(value) => { + self.observe_histogram(update.metric_name(), value) + }, } } diff --git a/pezkuwi/node/network/approval-distribution/src/lib.rs b/pezkuwi/node/network/approval-distribution/src/lib.rs index 712a03fb..c2cc1a85 100644 --- a/pezkuwi/node/network/approval-distribution/src/lib.rs +++ b/pezkuwi/node/network/approval-distribution/src/lib.rs @@ -419,8 +419,8 @@ impl Knowledge { // we need to share the same `MessageSubject` with the followup approval candidate index. if kind == MessageKind::Assignment && success && message.1.count_ones() > 1 { for candidate_index in message.1.iter_ones() { - success = success && - self.insert( + success = success + && self.insert( MessageSubject( message.0, vec![candidate_index as u32].try_into().expect("Non-empty vec; qed"), @@ -1300,8 +1300,8 @@ impl State { let age = max_age.saturating_sub(min_age); - aggression_config.should_trigger_aggression(age) && - topology.map(|topology| topology.is_validator(&peer)).unwrap_or(false) + aggression_config.should_trigger_aggression(age) + && topology.map(|topology| topology.is_validator(&peer)).unwrap_or(false) } async fn import_and_circulate_assignment( @@ -2282,11 +2282,11 @@ impl State { }) .unwrap_or(true); - if resend == Resend::Yes && - config.resend_unfinalized_period.as_ref().map_or(false, |p| { - block_age > 0 && - block_age % p == 0 && diff_from_min_age == 0 && - can_resend_at_this_age + if resend == Resend::Yes + && config.resend_unfinalized_period.as_ref().map_or(false, |p| { + block_age > 0 + && block_age % p == 0 && diff_from_min_age == 0 + && can_resend_at_this_age }) { // Retry sending to all peers. for (_, knowledge) in block_entry.known_by.iter_mut() { @@ -2372,8 +2372,9 @@ impl State { // We assume `candidate_bitfield` length for the core bitfield and we just check // against `MAX_BITFIELD_SIZE` later. AssignmentCertKindV2::RelayVRFModulo { .. } => candidate_bitfield.len(), - AssignmentCertKindV2::RelayVRFModuloCompact { core_bitfield } => - core_bitfield.len(), + AssignmentCertKindV2::RelayVRFModuloCompact { core_bitfield } => { + core_bitfield.len() + }, }; let candidate_bitfield_bits = candidate_bitfield.len(); @@ -2411,8 +2412,8 @@ impl State { let mut sanitized_approvals = Vec::new(); for approval in approval.into_iter() { let has_no_approved_candidates = approval.candidate_indices.first_one().is_none(); - if approval.candidate_indices.len() as usize > MAX_BITFIELD_SIZE || - has_no_approved_candidates + if approval.candidate_indices.len() as usize > MAX_BITFIELD_SIZE + || has_no_approved_candidates { // Punish the peer for the invalid message. modify_reputation( @@ -2687,7 +2688,7 @@ impl ApprovalDistribution { session_info_provider: &mut RuntimeInfo, ) -> bool { match message { - FromOrchestra::Communication { msg } => + FromOrchestra::Communication { msg } => { Self::handle_incoming( approval_voting_sender, network_sender, @@ -2700,7 +2701,8 @@ impl ApprovalDistribution { self.clock.as_ref(), session_info_provider, ) - .await, + .await + }, FromOrchestra::Signal(OverseerSignal::ActiveLeaves(_update)) => { gum::trace!(target: LOG_TARGET, "active leaves signal (ignored)"); // the relay chain blocks relevant to the approval subsystems @@ -2849,9 +2851,9 @@ const fn ensure_size_not_zero(size: usize) -> usize { /// assignments we send in a single message to peers. Exceeding `MAX_NOTIFICATION_SIZE` will violate /// the protocol configuration. pub const MAX_ASSIGNMENT_BATCH_SIZE: usize = ensure_size_not_zero( - MAX_NOTIFICATION_SIZE as usize / - std::mem::size_of::<(IndirectAssignmentCertV2, CandidateIndex)>() / - 3, + MAX_NOTIFICATION_SIZE as usize + / std::mem::size_of::<(IndirectAssignmentCertV2, CandidateIndex)>() + / 3, ); /// The maximum amount of approvals per batch is 33% of maximum allowed by protocol. diff --git a/pezkuwi/node/network/availability-distribution/src/error.rs b/pezkuwi/node/network/availability-distribution/src/error.rs index b28b2bf9..3e6eb437 100644 --- a/pezkuwi/node/network/availability-distribution/src/error.rs +++ b/pezkuwi/node/network/availability-distribution/src/error.rs @@ -106,17 +106,17 @@ pub fn log_error( Ok(()) => Ok(()), Err(jfyi) => { match jfyi { - JfyiError::UnexpectedPoV | - JfyiError::InvalidValidatorIndex | - JfyiError::NoSuchCachedSession { .. } | - JfyiError::QueryAvailableDataResponseChannel(_) | - JfyiError::QueryChunkResponseChannel(_) | - JfyiError::FailedNodeFeatures(_) | - JfyiError::ErasureCoding(_) => gum::warn!(target: LOG_TARGET, error = %jfyi, ctx), - JfyiError::FetchPoV(_) | - JfyiError::SendResponse | - JfyiError::NoSuchPoV | - JfyiError::Runtime(_) => { + JfyiError::UnexpectedPoV + | JfyiError::InvalidValidatorIndex + | JfyiError::NoSuchCachedSession { .. } + | JfyiError::QueryAvailableDataResponseChannel(_) + | JfyiError::QueryChunkResponseChannel(_) + | JfyiError::FailedNodeFeatures(_) + | JfyiError::ErasureCoding(_) => gum::warn!(target: LOG_TARGET, error = %jfyi, ctx), + JfyiError::FetchPoV(_) + | JfyiError::SendResponse + | JfyiError::NoSuchPoV + | JfyiError::Runtime(_) => { gum::warn_if_frequent!(freq: warn_freq, max_rate: gum::Times::PerHour(100), target: LOG_TARGET, error = ?jfyi, ctx) }, } diff --git a/pezkuwi/node/network/availability-distribution/src/lib.rs b/pezkuwi/node/network/availability-distribution/src/lib.rs index 1af9b91e..152280e4 100644 --- a/pezkuwi/node/network/availability-distribution/src/lib.rs +++ b/pezkuwi/node/network/availability-distribution/src/lib.rs @@ -143,8 +143,9 @@ impl AvailabilityDistributionSubsystem { // Handle task messages sending: let message = match action { - Either::Left(subsystem_msg) => - subsystem_msg.map_err(|e| FatalError::IncomingMessageChannel(e))?, + Either::Left(subsystem_msg) => { + subsystem_msg.map_err(|e| FatalError::IncomingMessageChannel(e))? + }, Either::Right(from_task) => { let from_task = from_task.ok_or(FatalError::RequesterExhausted)?; ctx.send_message(from_task).await; diff --git a/pezkuwi/node/network/availability-distribution/src/requester/fetch_task/mod.rs b/pezkuwi/node/network/availability-distribution/src/requester/fetch_task/mod.rs index 63434761..6d33cf91 100644 --- a/pezkuwi/node/network/availability-distribution/src/requester/fetch_task/mod.rs +++ b/pezkuwi/node/network/availability-distribution/src/requester/fetch_task/mod.rs @@ -369,7 +369,7 @@ impl RunningTask { match response_recv.await { Ok((bytes, protocol)) => match protocol { - _ if protocol == self.req_v2_protocol_name => + _ if protocol == self.req_v2_protocol_name => { match v2::ChunkFetchingResponse::decode(&mut &bytes[..]) { Ok(chunk_response) => Ok(Option::::from(chunk_response)), Err(e) => { @@ -386,8 +386,9 @@ impl RunningTask { ); Err(TaskError::PeerError) }, - }, - _ if protocol == self.req_v1_protocol_name => + } + }, + _ if protocol == self.req_v1_protocol_name => { match v1::ChunkFetchingResponse::decode(&mut &bytes[..]) { Ok(chunk_response) => Ok(Option::::from(chunk_response) .map(|c| c.recombine_into_chunk(&self.request.into()))), @@ -405,7 +406,8 @@ impl RunningTask { ); Err(TaskError::PeerError) }, - }, + } + }, _ => { gum::warn!( target: LOG_TARGET, diff --git a/pezkuwi/node/network/availability-distribution/src/requester/fetch_task/tests.rs b/pezkuwi/node/network/availability-distribution/src/requester/fetch_task/tests.rs index 2309063b..52726301 100644 --- a/pezkuwi/node/network/availability-distribution/src/requester/fetch_task/tests.rs +++ b/pezkuwi/node/network/availability-distribution/src/requester/fetch_task/tests.rs @@ -296,15 +296,15 @@ impl TestRun { self.chunk_responses.get(&req.peer).ok_or(network::RequestFailure::Refused); if let Ok((resp, protocol)) = response { - let chunk = if protocol == - &self.req_protocol_names.get_name(Protocol::ChunkFetchingV1) + let chunk = if protocol + == &self.req_protocol_names.get_name(Protocol::ChunkFetchingV1) { Into::>::into( v1::ChunkFetchingResponse::decode(&mut &resp[..]).unwrap(), ) .map(|c| c.chunk) - } else if protocol == - &self.req_protocol_names.get_name(Protocol::ChunkFetchingV2) + } else if protocol + == &self.req_protocol_names.get_name(Protocol::ChunkFetchingV2) { Into::>::into( v2::ChunkFetchingResponse::decode(&mut &resp[..]).unwrap(), diff --git a/pezkuwi/node/network/availability-distribution/src/tests/mod.rs b/pezkuwi/node/network/availability-distribution/src/tests/mod.rs index 689390bb..d6ae92f5 100644 --- a/pezkuwi/node/network/availability-distribution/src/tests/mod.rs +++ b/pezkuwi/node/network/availability-distribution/src/tests/mod.rs @@ -94,8 +94,8 @@ fn check_basic(#[case] node_features: NodeFeatures, #[case] chunk_resp_protocol: let state = TestState::new(node_features.clone(), req_protocol_names.clone(), chunk_resp_protocol); - if node_features == node_features_with_mapping_enabled() && - chunk_resp_protocol == Protocol::ChunkFetchingV1 + if node_features == node_features_with_mapping_enabled() + && chunk_resp_protocol == Protocol::ChunkFetchingV1 { // For this specific case, chunk fetching is not possible, because the ValidatorIndex is not // equal to the ChunkIndex and the peer does not send back the actual ChunkIndex. @@ -128,8 +128,8 @@ fn check_fetch_tries_all( v.push(None); } - if node_features == node_features_with_mapping_enabled() && - chunk_resp_protocol == Protocol::ChunkFetchingV1 + if node_features == node_features_with_mapping_enabled() + && chunk_resp_protocol == Protocol::ChunkFetchingV1 { // For this specific case, chunk fetching is not possible, because the ValidatorIndex is not // equal to the ChunkIndex and the peer does not send back the actual ChunkIndex. @@ -186,8 +186,8 @@ fn check_fetch_retry(#[case] node_features: NodeFeatures, #[case] chunk_resp_pro v.push(None); } - if node_features == node_features_with_mapping_enabled() && - chunk_resp_protocol == Protocol::ChunkFetchingV1 + if node_features == node_features_with_mapping_enabled() + && chunk_resp_protocol == Protocol::ChunkFetchingV1 { // For this specific case, chunk fetching is not possible, because the ValidatorIndex is not // equal to the ChunkIndex and the peer does not send back the actual ChunkIndex. diff --git a/pezkuwi/node/network/availability-recovery/src/lib.rs b/pezkuwi/node/network/availability-recovery/src/lib.rs index 1273e16a..7ffec0e6 100644 --- a/pezkuwi/node/network/availability-recovery/src/lib.rs +++ b/pezkuwi/node/network/availability-recovery/src/lib.rs @@ -418,8 +418,8 @@ async fn handle_recover( let mut small_pov_size = true; match recovery_strategy_kind { - RecoveryStrategyKind::BackersFirstIfSizeLower(fetch_chunks_threshold) | - RecoveryStrategyKind::BackersFirstIfSizeLowerThenSystematicChunks( + RecoveryStrategyKind::BackersFirstIfSizeLower(fetch_chunks_threshold) + | RecoveryStrategyKind::BackersFirstIfSizeLowerThenSystematicChunks( fetch_chunks_threshold, ) => { // Get our own chunk size to get an estimate of the PoV size. @@ -448,16 +448,17 @@ async fn handle_recover( }; match (&recovery_strategy_kind, small_pov_size) { - (RecoveryStrategyKind::BackersFirstAlways, _) | - (RecoveryStrategyKind::BackersFirstIfSizeLower(_), true) | - ( + (RecoveryStrategyKind::BackersFirstAlways, _) + | (RecoveryStrategyKind::BackersFirstIfSizeLower(_), true) + | ( RecoveryStrategyKind::BackersFirstIfSizeLowerThenSystematicChunks(_), true, - ) | - (RecoveryStrategyKind::BackersThenSystematicChunks, _) => + ) + | (RecoveryStrategyKind::BackersThenSystematicChunks, _) => { recovery_strategies.push_back(Box::new(FetchFull::new( FetchFullParams { validators: backing_validators.to_vec() }, - ))), + ))) + }, _ => {}, }; @@ -479,9 +480,9 @@ async fn handle_recover( if let Some(core_index) = maybe_core_index { if matches!( recovery_strategy_kind, - RecoveryStrategyKind::BackersThenSystematicChunks | - RecoveryStrategyKind::SystematicChunks | - RecoveryStrategyKind::BackersFirstIfSizeLowerThenSystematicChunks(_) + RecoveryStrategyKind::BackersThenSystematicChunks + | RecoveryStrategyKind::SystematicChunks + | RecoveryStrategyKind::BackersFirstIfSizeLowerThenSystematicChunks(_) ) && chunk_mapping_enabled { let chunk_indices = @@ -507,8 +508,8 @@ async fn handle_recover( .into_iter() .filter(|(c_index, _)| { usize::try_from(c_index.0) - .expect("usize is at least u32 bytes on all modern targets.") < - systematic_threshold + .expect("usize is at least u32 bytes on all modern targets.") + < systematic_threshold }) .collect(); diff --git a/pezkuwi/node/network/availability-recovery/src/task/mod.rs b/pezkuwi/node/network/availability-recovery/src/task/mod.rs index 6db43730..e5215bb1 100644 --- a/pezkuwi/node/network/availability-recovery/src/task/mod.rs +++ b/pezkuwi/node/network/availability-recovery/src/task/mod.rs @@ -158,7 +158,7 @@ where let res = current_strategy.run(&mut self.state, &mut self.sender, &self.params).await; match res { - Err(RecoveryError::Unavailable) => + Err(RecoveryError::Unavailable) => { if self.strategies.front().is_some() { gum::debug!( target: LOG_TARGET, @@ -167,11 +167,13 @@ where display_name ); continue; - }, + } + }, Err(err) => { match &err { - RecoveryError::Invalid => - self.params.metrics.on_recovery_invalid(strategy_type), + RecoveryError::Invalid => { + self.params.metrics.on_recovery_invalid(strategy_type) + }, _ => self.params.metrics.on_recovery_failed(strategy_type), } return Err(err); diff --git a/pezkuwi/node/network/availability-recovery/src/task/strategy/chunks.rs b/pezkuwi/node/network/availability-recovery/src/task/strategy/chunks.rs index 47e14471..cb58bde2 100644 --- a/pezkuwi/node/network/availability-recovery/src/task/strategy/chunks.rs +++ b/pezkuwi/node/network/availability-recovery/src/task/strategy/chunks.rs @@ -191,8 +191,8 @@ impl RecoveryStrategy // No need to query the validators that have the chunks we already received or that we know // don't have the data from previous strategies. self.validators.retain(|v_index| { - !state.received_chunks.values().any(|c| v_index == &c.validator_index) && - state.can_retry_request( + !state.received_chunks.values().any(|c| v_index == &c.validator_index) + && state.can_retry_request( &(common_params.validator_authority_keys[v_index.0 as usize].clone(), *v_index), REGULAR_CHUNKS_REQ_RETRY_LIMIT, ) @@ -279,8 +279,8 @@ impl RecoveryStrategy in_flight_reqs, chunk_count, _systematic_chunk_count| { - chunk_count >= common_params.threshold || - Self::is_unavailable( + chunk_count >= common_params.threshold + || Self::is_unavailable( unrequested_validators, in_flight_reqs, chunk_count, diff --git a/pezkuwi/node/network/availability-recovery/src/task/strategy/full.rs b/pezkuwi/node/network/availability-recovery/src/task/strategy/full.rs index fd1f5697..c5163876 100644 --- a/pezkuwi/node/network/availability-recovery/src/task/strategy/full.rs +++ b/pezkuwi/node/network/availability-recovery/src/task/strategy/full.rs @@ -113,8 +113,9 @@ impl RecoveryStrategy reencode_rx.await.map_err(|_| RecoveryError::ChannelClosed)? }, - PostRecoveryCheck::PovHash => - (data.pov.hash() == common_params.pov_hash).then_some(data), + PostRecoveryCheck::PovHash => { + (data.pov.hash() == common_params.pov_hash).then_some(data) + }, }; match maybe_data { @@ -150,8 +151,9 @@ impl RecoveryStrategy Err(e) => { match &e { RequestError::Canceled(_) => common_params.metrics.on_full_request_error(), - RequestError::InvalidResponse(_) => - common_params.metrics.on_full_request_invalid(), + RequestError::InvalidResponse(_) => { + common_params.metrics.on_full_request_invalid() + }, RequestError::NetworkError(req_failure) => { if let RequestFailure::Network(OutboundFailure::Timeout) = req_failure { common_params.metrics.on_full_request_timeout(); diff --git a/pezkuwi/node/network/availability-recovery/src/task/strategy/mod.rs b/pezkuwi/node/network/availability-recovery/src/task/strategy/mod.rs index 71056203..d2f411a3 100644 --- a/pezkuwi/node/network/availability-recovery/src/task/strategy/mod.rs +++ b/pezkuwi/node/network/availability-recovery/src/task/strategy/mod.rs @@ -385,10 +385,12 @@ impl State { Ok((bytes, protocol)) => { if v2_protocol_name == protocol { match req_res::v2::ChunkFetchingResponse::decode(&mut &bytes[..]) { - Ok(req_res::v2::ChunkFetchingResponse::Chunk(chunk)) => - Ok((Some(chunk.into()), protocol)), - Ok(req_res::v2::ChunkFetchingResponse::NoSuchChunk) => - Ok((None, protocol)), + Ok(req_res::v2::ChunkFetchingResponse::Chunk(chunk)) => { + Ok((Some(chunk.into()), protocol)) + }, + Ok(req_res::v2::ChunkFetchingResponse::NoSuchChunk) => { + Ok((None, protocol)) + }, Err(e) => Err(RequestError::InvalidResponse(e)), } } else if v1_protocol_name == protocol { @@ -413,8 +415,9 @@ impl State { Some(chunk.recombine_into_chunk(&raw_request_v1)), protocol, )), - Ok(req_res::v1::ChunkFetchingResponse::NoSuchChunk) => - Ok((None, protocol)), + Ok(req_res::v1::ChunkFetchingResponse::NoSuchChunk) => { + Ok((None, protocol)) + }, Err(e) => Err(RequestError::InvalidResponse(e)), } } else { @@ -485,10 +488,12 @@ impl State { match request_result { Ok((maybe_chunk, protocol)) => { match protocol { - name if name == params.req_v1_protocol_name => - params.metrics.on_chunk_response_v1(), - name if name == params.req_v2_protocol_name => - params.metrics.on_chunk_response_v2(), + name if name == params.req_v1_protocol_name => { + params.metrics.on_chunk_response_v1() + }, + name if name == params.req_v2_protocol_name => { + params.metrics.on_chunk_response_v2() + }, _ => {}, } diff --git a/pezkuwi/node/network/availability-recovery/src/task/strategy/systematic.rs b/pezkuwi/node/network/availability-recovery/src/task/strategy/systematic.rs index c2bcc3ac..9fc557cc 100644 --- a/pezkuwi/node/network/availability-recovery/src/task/strategy/systematic.rs +++ b/pezkuwi/node/network/availability-recovery/src/task/strategy/systematic.rs @@ -104,8 +104,8 @@ impl FetchSystematicChunks { let chunks = state .received_chunks .range( - ChunkIndex(0).. - ChunkIndex( + ChunkIndex(0) + ..ChunkIndex( u32::try_from(self.threshold) .expect("validator count should not exceed u32"), ), @@ -180,8 +180,8 @@ impl RecoveryStrategy for (_, our_c_index) in &local_chunk_indices { // If we are among the systematic validators but hold an invalid chunk, we cannot // perform the systematic recovery. Fall through to the next strategy. - if self.validators.iter().any(|(c_index, _)| c_index == our_c_index) && - !state.received_chunks.contains_key(our_c_index) + if self.validators.iter().any(|(c_index, _)| c_index == our_c_index) + && !state.received_chunks.contains_key(our_c_index) { gum::debug!( target: LOG_TARGET, @@ -201,8 +201,8 @@ impl RecoveryStrategy // No need to query the validators that have the chunks we already received or that we know // don't have the data from previous strategies. self.validators.retain(|(c_index, v_index)| { - !state.received_chunks.contains_key(c_index) && - state.can_retry_request( + !state.received_chunks.contains_key(c_index) + && state.can_retry_request( &(common_params.validator_authority_keys[v_index.0 as usize].clone(), *v_index), SYSTEMATIC_CHUNKS_REQ_RETRY_LIMIT, ) diff --git a/pezkuwi/node/network/availability-recovery/src/tests.rs b/pezkuwi/node/network/availability-recovery/src/tests.rs index 64ffa390..101641ae 100644 --- a/pezkuwi/node/network/availability-recovery/src/tests.rs +++ b/pezkuwi/node/network/availability-recovery/src/tests.rs @@ -2499,8 +2499,8 @@ fn systematic_chunks_are_not_requested_again_in_regular_recovery() { &mut virtual_overseer, 1, |i| { - if (test_state.chunks.get(i).unwrap().index.0 as usize) < - test_state.systematic_threshold() + if (test_state.chunks.get(i).unwrap().index.0 as usize) + < test_state.systematic_threshold() { panic!("Already requested") } else { diff --git a/pezkuwi/node/network/bitfield-distribution/src/lib.rs b/pezkuwi/node/network/bitfield-distribution/src/lib.rs index eee16f5c..f77eca5d 100644 --- a/pezkuwi/node/network/bitfield-distribution/src/lib.rs +++ b/pezkuwi/node/network/bitfield-distribution/src/lib.rs @@ -90,11 +90,12 @@ impl BitfieldGossipMessage { recipient_version: ProtocolVersion, ) -> net_protocol::BitfieldDistributionMessage { match ValidationVersion::try_from(recipient_version).ok() { - Some(ValidationVersion::V3) => + Some(ValidationVersion::V3) => { ValidationProtocols::V3(protocol_v3::BitfieldDistributionMessage::Bitfield( self.relay_parent, self.signed_availability.into(), - )), + )) + }, None => { gum::warn!( target: LOG_TARGET, @@ -187,8 +188,9 @@ impl PerRelayParentData { self.message_sent_to_peer .get(peer) .map(|pubkeys| !pubkeys.contains(signed_by)) - .unwrap_or(true) && - self.message_received_from_peer + .unwrap_or(true) + && self + .message_received_from_peer .get(peer) .map(|pubkeys| !pubkeys.contains(signed_by)) .unwrap_or(true) @@ -729,8 +731,9 @@ async fn handle_network_msg( gum::trace!(target: LOG_TARGET, ?new_view, "Our view change"); handle_our_view_change(state, new_view); }, - NetworkBridgeEvent::PeerMessage(remote, message) => - process_incoming_peer_message(ctx, state, metrics, remote, message, rng).await, + NetworkBridgeEvent::PeerMessage(remote, message) => { + process_incoming_peer_message(ctx, state, metrics, remote, message, rng).await + }, NetworkBridgeEvent::UpdatedAuthorityIds(peer_id, authority_ids) => { state .topologies @@ -794,8 +797,8 @@ async fn handle_peer_view_change( let topology = state.topologies.get_current_topology().local_grid_neighbors(); let is_gossip_peer = topology.route_to_peer(RequiredRouting::GridXY, &origin); - let lucky = is_gossip_peer || - util::gen_ratio_rng( + let lucky = is_gossip_peer + || util::gen_ratio_rng( util::MIN_GOSSIP_PEERS.saturating_sub(topology.len()), util::MIN_GOSSIP_PEERS, rng, @@ -904,8 +907,9 @@ async fn query_basics( .await; match (validators_rx.await?, session_rx.await?) { - (Ok(validators), Ok(session_index)) => - Ok(Some((validators, SigningContext { parent_hash: relay_parent, session_index }))), + (Ok(validators), Ok(session_index)) => { + Ok(Some((validators, SigningContext { parent_hash: relay_parent, session_index }))) + }, (Err(err), _) | (_, Err(err)) => { gum::warn!( target: LOG_TARGET, diff --git a/pezkuwi/node/network/bridge/src/rx/mod.rs b/pezkuwi/node/network/bridge/src/rx/mod.rs index 31d1f984..49e6a520 100644 --- a/pezkuwi/node/network/bridge/src/rx/mod.rs +++ b/pezkuwi/node/network/bridge/src/rx/mod.rs @@ -1024,8 +1024,8 @@ fn handle_peer_messages>( outgoing_events.push(match message { WireMessage::ViewUpdate(new_view) => { - if new_view.len() > MAX_VIEW_HEADS || - new_view.finalized_number < peer_data.view.finalized_number + if new_view.len() > MAX_VIEW_HEADS + || new_view.finalized_number < peer_data.view.finalized_number { reports.push(MALFORMED_VIEW_COST); continue; @@ -1040,8 +1040,9 @@ fn handle_peer_messages>( NetworkBridgeEvent::PeerViewChange(peer, peer_data.view.clone()) } }, - WireMessage::ProtocolMessage(message) => - NetworkBridgeEvent::PeerMessage(peer, message.into()), + WireMessage::ProtocolMessage(message) => { + NetworkBridgeEvent::PeerMessage(peer, message.into()) + }, }) } @@ -1123,9 +1124,9 @@ async fn dispatch_validation_events_to_all( // NetworkBridgeEvent::OurViewChange(..) must also be here, // but it is sent via an unbounded channel. // See https://github.com/pezkuwichain/pezkuwi-sdk/issues/108 - NetworkBridgeEvent::PeerConnected(..) | - NetworkBridgeEvent::PeerDisconnected(..) | - NetworkBridgeEvent::PeerViewChange(..) + NetworkBridgeEvent::PeerConnected(..) + | NetworkBridgeEvent::PeerDisconnected(..) + | NetworkBridgeEvent::PeerViewChange(..) ); let message = $message::from(event); if has_high_priority { diff --git a/pezkuwi/node/network/bridge/src/rx/tests.rs b/pezkuwi/node/network/bridge/src/rx/tests.rs index 2902d538..b94b85be 100644 --- a/pezkuwi/node/network/bridge/src/rx/tests.rs +++ b/pezkuwi/node/network/bridge/src/rx/tests.rs @@ -488,8 +488,8 @@ async fn await_peer_connections( loop { { let shared = shared.0.lock(); - if shared.validation_peers.len() == num_validation_peers && - shared.collation_peers.len() == num_collation_peers + if shared.validation_peers.len() == num_validation_peers + && shared.collation_peers.len() == num_collation_peers { break; } @@ -1516,13 +1516,16 @@ fn network_protocol_versioning_view_update() { for &(peer_id, peer_set, version) in &peers { let wire_msg = match (version.into(), peer_set) { - (1, PeerSet::Collation) => - WireMessage::::ViewUpdate(view.clone()).encode(), - (2, PeerSet::Collation) => - WireMessage::::ViewUpdate(view.clone()).encode(), - (3, PeerSet::Validation) => + (1, PeerSet::Collation) => { + WireMessage::::ViewUpdate(view.clone()).encode() + }, + (2, PeerSet::Collation) => { + WireMessage::::ViewUpdate(view.clone()).encode() + }, + (3, PeerSet::Validation) => { WireMessage::::ViewUpdate(view.clone()) - .encode(), + .encode() + }, _ => unreachable!(), }; assert_network_actions_contains( diff --git a/pezkuwi/node/network/bridge/src/tx/mod.rs b/pezkuwi/node/network/bridge/src/tx/mod.rs index 7e25a05e..2dc482fe 100644 --- a/pezkuwi/node/network/bridge/src/tx/mod.rs +++ b/pezkuwi/node/network/bridge/src/tx/mod.rs @@ -288,8 +288,9 @@ where metrics.on_message("chunk_fetching_v1") } }, - Requests::AvailableDataFetchingV1(_) => - metrics.on_message("available_data_fetching_v1"), + Requests::AvailableDataFetchingV1(_) => { + metrics.on_message("available_data_fetching_v1") + }, Requests::CollationFetchingV1(_) => metrics.on_message("collation_fetching_v1"), Requests::CollationFetchingV2(_) => metrics.on_message("collation_fetching_v2"), Requests::PoVFetchingV1(_) => metrics.on_message("pov_fetching_v1"), diff --git a/pezkuwi/node/network/collator-protocol/src/collator_side/mod.rs b/pezkuwi/node/network/collator-protocol/src/collator_side/mod.rs index 05958d59..8b8a8029 100644 --- a/pezkuwi/node/network/collator-protocol/src/collator_side/mod.rs +++ b/pezkuwi/node/network/collator-protocol/src/collator_side/mod.rs @@ -1052,8 +1052,8 @@ async fn handle_incoming_peer_message( )) .await; }, - CollationProtocols::V1(V1::AdvertiseCollation(_)) | - CollationProtocols::V2(V2::AdvertiseCollation { .. }) => { + CollationProtocols::V1(V1::AdvertiseCollation(_)) + | CollationProtocols::V2(V2::AdvertiseCollation { .. }) => { gum::trace!( target: LOG_TARGET, ?origin, @@ -1174,8 +1174,9 @@ async fn handle_incoming_request( }; let collation_with_core = match &req { - VersionedCollationRequest::V2(req) => - per_relay_parent.collations.get_mut(&req.payload.candidate_hash), + VersionedCollationRequest::V2(req) => { + per_relay_parent.collations.get_mut(&req.payload.candidate_hash) + }, }; let (receipt, pov, parent_head_data) = if let Some(collation_with_core) = collation_with_core { @@ -1634,7 +1635,7 @@ fn process_out_of_view_collation( let candidate_hash = collation.receipt.hash(); match collation.status { - CollationStatus::Created => + CollationStatus::Created => { if is_same_session { gum::warn!( target: LOG_TARGET, @@ -1649,7 +1650,8 @@ fn process_out_of_view_collation( pov_hash = ?collation.pov.hash(), "Collation wasn't advertised because it was built on a relay chain block that is now part of an old session.", ) - }, + } + }, CollationStatus::Advertised => gum::debug!( target: LOG_TARGET, ?candidate_hash, diff --git a/pezkuwi/node/network/collator-protocol/src/collator_side/tests/mod.rs b/pezkuwi/node/network/collator-protocol/src/collator_side/tests/mod.rs index b9d5284a..f9370d7b 100644 --- a/pezkuwi/node/network/collator-protocol/src/collator_side/tests/mod.rs +++ b/pezkuwi/node/network/collator-protocol/src/collator_side/tests/mod.rs @@ -548,8 +548,9 @@ fn decode_collation_response(bytes: &[u8]) -> (CandidateReceipt, PoV) { CollationFetchingResponse::Collation(_, _) => { panic!("Expected to always receive CollationWithParentHeadData") }, - CollationFetchingResponse::CollationWithParentHeadData { receipt, pov, .. } => - (receipt, pov), + CollationFetchingResponse::CollationWithParentHeadData { receipt, pov, .. } => { + (receipt, pov) + }, } } diff --git a/pezkuwi/node/network/collator-protocol/src/lib.rs b/pezkuwi/node/network/collator-protocol/src/lib.rs index 13f9ca1e..8633b928 100644 --- a/pezkuwi/node/network/collator-protocol/src/lib.rs +++ b/pezkuwi/node/network/collator-protocol/src/lib.rs @@ -151,14 +151,16 @@ impl CollatorProtocolSubsystem { .boxed() }, #[cfg(feature = "experimental-collator-protocol")] - ProtocolSide::ValidatorExperimental { keystore, metrics } => + ProtocolSide::ValidatorExperimental { keystore, metrics } => { validator_side_experimental::run(ctx, keystore, metrics) .map_err(|e| SubsystemError::with_origin("collator-protocol", e)) - .boxed(), - ProtocolSide::Collator { peer_id, collator_pair, request_receiver_v2, metrics } => + .boxed() + }, + ProtocolSide::Collator { peer_id, collator_pair, request_receiver_v2, metrics } => { collator_side::run(ctx, peer_id, collator_pair, request_receiver_v2, metrics) .map_err(|e| SubsystemError::with_origin("collator-protocol", e)) - .boxed(), + .boxed() + }, ProtocolSide::None => return DummySubsystem.start(ctx), }; diff --git a/pezkuwi/node/network/collator-protocol/src/validator_side/error.rs b/pezkuwi/node/network/collator-protocol/src/validator_side/error.rs index 31193775..cf78358d 100644 --- a/pezkuwi/node/network/collator-protocol/src/validator_side/error.rs +++ b/pezkuwi/node/network/collator-protocol/src/validator_side/error.rs @@ -98,13 +98,13 @@ impl SecondingError { use SecondingError::*; matches!( self, - PersistedValidationDataMismatch | - CandidateHashMismatch | - RelayParentMismatch | - ParentHeadDataMismatch | - InvalidCoreIndex(_, _) | - InvalidSessionIndex(_, _) | - InvalidReceiptVersion(_) + PersistedValidationDataMismatch + | CandidateHashMismatch + | RelayParentMismatch + | ParentHeadDataMismatch + | InvalidCoreIndex(_, _) + | InvalidSessionIndex(_, _) + | InvalidReceiptVersion(_) ) } } diff --git a/pezkuwi/node/network/collator-protocol/src/validator_side/mod.rs b/pezkuwi/node/network/collator-protocol/src/validator_side/mod.rs index dd35746b..d5e41564 100644 --- a/pezkuwi/node/network/collator-protocol/src/validator_side/mod.rs +++ b/pezkuwi/node/network/collator-protocol/src/validator_side/mod.rs @@ -335,8 +335,9 @@ impl PeerData { fn is_inactive(&self, policy: &crate::CollatorEvictionPolicy) -> bool { match self.state { PeerState::Connected(connected_at) => connected_at.elapsed() >= policy.undeclared, - PeerState::Collating(ref state) => - state.last_active.elapsed() >= policy.inactive_collator, + PeerState::Collating(ref state) => { + state.last_active.elapsed() >= policy.inactive_collator + }, } } } @@ -540,8 +541,8 @@ impl State { acc + blocked_collations .iter() .filter(|pc| { - pc.candidate_receipt.descriptor.para_id() == *para_id && - pc.candidate_receipt.descriptor.relay_parent() == *relay_parent + pc.candidate_receipt.descriptor.para_id() == *para_id + && pc.candidate_receipt.descriptor.relay_parent() == *relay_parent }) .count() }); @@ -747,14 +748,16 @@ async fn notify_collation_seconded( ) { let statement = statement.into(); let wire_message = match version { - CollationVersion::V1 => + CollationVersion::V1 => { CollationProtocols::V1(protocol_v1::CollationProtocol::CollatorProtocol( protocol_v1::CollatorProtocolMessage::CollationSeconded(relay_parent, statement), - )), - CollationVersion::V2 => + )) + }, + CollationVersion::V2 => { CollationProtocols::V2(protocol_v2::CollationProtocol::CollatorProtocol( protocol_v2::CollatorProtocolMessage::CollationSeconded(relay_parent, statement), - )), + )) + }, }; sender .send_message(NetworkBridgeTxMessage::SendCollationMessage(vec![peer_id], wire_message)) @@ -879,8 +882,8 @@ async fn process_incoming_peer_message( use protocol_v2::CollatorProtocolMessage as V2; match msg { - CollationProtocols::V1(V1::Declare(collator_id, para_id, signature)) | - CollationProtocols::V2(V2::Declare(collator_id, para_id, signature)) => { + CollationProtocols::V1(V1::Declare(collator_id, para_id, signature)) + | CollationProtocols::V2(V2::Declare(collator_id, para_id, signature)) => { if collator_peer_id(&state.peer_data, &collator_id).is_some() { modify_reputation( &mut state.reputation, @@ -1022,8 +1025,8 @@ async fn process_incoming_peer_message( } } }, - CollationProtocols::V1(V1::CollationSeconded(..)) | - CollationProtocols::V2(V2::CollationSeconded(..)) => { + CollationProtocols::V1(V1::CollationSeconded(..)) + | CollationProtocols::V2(V2::CollationSeconded(..)) => { gum::warn!( target: LOG_TARGET, peer_id = ?origin, @@ -1053,9 +1056,9 @@ fn hold_off_asset_hub_collation_if_needed( let peer_is_invulnerable = state.ah_invulnerables.contains(&peer_id); let invulnerables_set_is_empty = state.ah_invulnerables.is_empty(); - if maybe_para_id != Some(ASSET_HUB_PARA_ID) || - peer_is_invulnerable || - invulnerables_set_is_empty + if maybe_para_id != Some(ASSET_HUB_PARA_ID) + || peer_is_invulnerable + || invulnerables_set_is_empty { gum::trace!( target: LOG_TARGET, @@ -1269,8 +1272,8 @@ fn ensure_seconding_limit_is_respected( for path in paths { let mut cq_state = ClaimQueueState::new(); for ancestor in &path { - let seconded_and_pending = state.seconded_and_pending_for_para(&ancestor, ¶_id) + - state.in_waiting_queue_for_para(relay_parent, ¶_id); + let seconded_and_pending = state.seconded_and_pending_for_para(&ancestor, ¶_id) + + state.in_waiting_queue_for_para(relay_parent, ¶_id); cq_state.add_leaf( &ancestor, &state @@ -1847,9 +1850,11 @@ async fn process_msg( let candidate_hash = fetched_collation.candidate_hash; let id = match state.fetched_candidates.entry(fetched_collation) { Entry::Occupied(entry) - if entry.get().pending_collation.commitments_hash == - Some(candidate_receipt.commitments_hash) => - entry.remove().collator_id, + if entry.get().pending_collation.commitments_hash + == Some(candidate_receipt.commitments_hash) => + { + entry.remove().collator_id + }, Entry::Occupied(_) => { gum::error!( target: LOG_TARGET, @@ -2400,10 +2405,10 @@ async fn handle_collation_fetch_response( Err(None) }, Ok( - request_v1::CollationFetchingResponse::Collation(receipt, _) | - request_v2::CollationFetchingResponse::Collation(receipt, _) | - request_v1::CollationFetchingResponse::CollationWithParentHeadData { receipt, .. } | - request_v2::CollationFetchingResponse::CollationWithParentHeadData { receipt, .. }, + request_v1::CollationFetchingResponse::Collation(receipt, _) + | request_v2::CollationFetchingResponse::Collation(receipt, _) + | request_v1::CollationFetchingResponse::CollationWithParentHeadData { receipt, .. } + | request_v2::CollationFetchingResponse::CollationWithParentHeadData { receipt, .. }, ) if receipt.descriptor().para_id() != pending_collation.para_id => { gum::debug!( target: LOG_TARGET, @@ -2550,8 +2555,8 @@ fn get_next_collation_to_fetch( // to replace it. if let Some((collator_id, maybe_candidate_hash)) = rp_state.collations.fetching_from.as_ref() { // If a candidate hash was saved previously, `finished_one` must include this too. - if collator_id != &finished_one.0 && - maybe_candidate_hash.map_or(true, |hash| Some(&hash) != finished_one.1.as_ref()) + if collator_id != &finished_one.0 + && maybe_candidate_hash.map_or(true, |hash| Some(&hash) != finished_one.1.as_ref()) { gum::trace!( target: LOG_TARGET, diff --git a/pezkuwi/node/network/collator-protocol/src/validator_side/tests/mod.rs b/pezkuwi/node/network/collator-protocol/src/validator_side/tests/mod.rs index f90cd3b2..9f592aac 100644 --- a/pezkuwi/node/network/collator-protocol/src/validator_side/tests/mod.rs +++ b/pezkuwi/node/network/collator-protocol/src/validator_side/tests/mod.rs @@ -416,18 +416,20 @@ async fn connect_and_declare_collator( .await; let wire_message = match version { - CollationVersion::V1 => + CollationVersion::V1 => { CollationProtocols::V1(protocol_v1::CollatorProtocolMessage::Declare( collator.public(), para_id, collator.sign(&protocol_v1::declare_signature_payload(&peer)), - )), - CollationVersion::V2 => + )) + }, + CollationVersion::V2 => { CollationProtocols::V2(protocol_v2::CollatorProtocolMessage::Declare( collator.public(), para_id, collator.sign(&protocol_v1::declare_signature_payload(&peer)), - )), + )) + }, }; overseer_send( @@ -448,12 +450,13 @@ async fn advertise_collation( candidate: Option<(CandidateHash, Hash)>, // Candidate hash + parent head data hash. ) { let wire_message = match candidate { - Some((candidate_hash, parent_head_data_hash)) => + Some((candidate_hash, parent_head_data_hash)) => { CollationProtocols::V2(protocol_v2::CollatorProtocolMessage::AdvertiseCollation { relay_parent, candidate_hash, parent_head_data_hash, - }), + }) + }, None => CollationProtocols::V1(protocol_v1::CollatorProtocolMessage::AdvertiseCollation( relay_parent, )), diff --git a/pezkuwi/node/network/collator-protocol/src/validator_side_experimental/peer_manager/connected.rs b/pezkuwi/node/network/collator-protocol/src/validator_side_experimental/peer_manager/connected.rs index 0f40a331..360ab471 100644 --- a/pezkuwi/node/network/collator-protocol/src/validator_side_experimental/peer_manager/connected.rs +++ b/pezkuwi/node/network/collator-protocol/src/validator_side_experimental/peer_manager/connected.rs @@ -104,12 +104,13 @@ impl ConnectedPeers { outcome = outcome.combine(res); } }, - PeerState::Connected => + PeerState::Connected => { for (para_id, per_para) in self.per_para.iter_mut() { let past_reputation = reputation_query_fn(peer_id, *para_id).await; let res = per_para.try_accept(peer_id, past_reputation); outcome = outcome.combine(res); - }, + } + }, } match outcome { @@ -567,12 +568,15 @@ mod tests { let rep_query_fn = |peer_id, para_id| async move { match (peer_id, para_id) { (peer_id, para_id) if peer_id == first_peer => Score::new(10).unwrap(), - (peer_id, para_id) if peer_id == second_peer && para_id == para_1 => - Score::new(20).unwrap(), - (peer_id, para_id) if peer_id == third_peer && para_id == para_2 => - Score::new(20).unwrap(), - (peer_id, para_id) if peer_id == new_peer && para_id == para_1 => - Score::new(5).unwrap(), + (peer_id, para_id) if peer_id == second_peer && para_id == para_1 => { + Score::new(20).unwrap() + }, + (peer_id, para_id) if peer_id == third_peer && para_id == para_2 => { + Score::new(20).unwrap() + }, + (peer_id, para_id) if peer_id == new_peer && para_id == para_1 => { + Score::new(5).unwrap() + }, (_, _) => Score::default(), } @@ -714,12 +718,15 @@ mod tests { let rep_query_fn = |peer_id, para_id| async move { match (peer_id, para_id) { (peer_id, para_id) if peer_id == first_peer => Score::new(10).unwrap(), - (peer_id, para_id) if peer_id == second_peer && para_id == para_1 => - Score::new(20).unwrap(), - (peer_id, para_id) if peer_id == third_peer && para_id == para_2 => - Score::new(20).unwrap(), - (peer_id, para_id) if peer_id == fourth_peer && para_id == para_2 => - Score::new(15).unwrap(), + (peer_id, para_id) if peer_id == second_peer && para_id == para_1 => { + Score::new(20).unwrap() + }, + (peer_id, para_id) if peer_id == third_peer && para_id == para_2 => { + Score::new(20).unwrap() + }, + (peer_id, para_id) if peer_id == fourth_peer && para_id == para_2 => { + Score::new(15).unwrap() + }, (peer_id, para_id) if peer_id == new_peer => Score::new(30).unwrap(), (_, _) => Score::default(), @@ -863,12 +870,15 @@ mod tests { let rep_query_fn = |peer_id, para_id| async move { match (peer_id, para_id) { (peer_id, para_id) if peer_id == first_peer => Score::new(10).unwrap(), - (peer_id, para_id) if peer_id == second_peer && para_id == para_1 => - Score::new(5).unwrap(), - (peer_id, para_id) if peer_id == third_peer && para_id == para_2 => - Score::new(5).unwrap(), - (peer_id, para_id) if peer_id == new_peer && para_id == para_1 => - Score::new(8).unwrap(), + (peer_id, para_id) if peer_id == second_peer && para_id == para_1 => { + Score::new(5).unwrap() + }, + (peer_id, para_id) if peer_id == third_peer && para_id == para_2 => { + Score::new(5).unwrap() + }, + (peer_id, para_id) if peer_id == new_peer && para_id == para_1 => { + Score::new(8).unwrap() + }, (_, _) => Score::default(), } diff --git a/pezkuwi/node/network/dispute-distribution/src/lib.rs b/pezkuwi/node/network/dispute-distribution/src/lib.rs index 9af53be3..4643e6dc 100644 --- a/pezkuwi/node/network/dispute-distribution/src/lib.rs +++ b/pezkuwi/node/network/dispute-distribution/src/lib.rs @@ -210,8 +210,9 @@ where Err(f) => Err(f), } }, - FromOrchestra::Communication { msg } => - self.handle_subsystem_message(&mut ctx, msg).await, + FromOrchestra::Communication { msg } => { + self.handle_subsystem_message(&mut ctx, msg).await + }, }; log_error(result, "on FromOrchestra")?; }, @@ -254,8 +255,9 @@ where msg: DisputeDistributionMessage, ) -> Result<()> { match msg { - DisputeDistributionMessage::SendDispute(dispute_msg) => - self.disputes_sender.start_sender(ctx, &mut self.runtime, dispute_msg).await?, + DisputeDistributionMessage::SendDispute(dispute_msg) => { + self.disputes_sender.start_sender(ctx, &mut self.runtime, dispute_msg).await? + }, } Ok(()) } diff --git a/pezkuwi/node/network/dispute-distribution/src/receiver/batches/batch.rs b/pezkuwi/node/network/dispute-distribution/src/receiver/batches/batch.rs index 90a2d1fa..5c0d5625 100644 --- a/pezkuwi/node/network/dispute-distribution/src/receiver/batches/batch.rs +++ b/pezkuwi/node/network/dispute-distribution/src/receiver/batches/batch.rs @@ -177,8 +177,8 @@ impl Batch { /// This function is supposed to be called at instants given at construction and as returned as /// part of `TickResult`. pub(super) fn tick(mut self, now: Instant) -> TickResult { - if self.votes_batched_since_last_tick >= MIN_KEEP_BATCH_ALIVE_VOTES && - now < self.best_before + if self.votes_batched_since_last_tick >= MIN_KEEP_BATCH_ALIVE_VOTES + && now < self.best_before { // Still good: let next_tick = self.calculate_next_tick(now); diff --git a/pezkuwi/node/network/dispute-distribution/src/sender/send_task.rs b/pezkuwi/node/network/dispute-distribution/src/sender/send_task.rs index 1707c462..ef1e2a47 100644 --- a/pezkuwi/node/network/dispute-distribution/src/sender/send_task.rs +++ b/pezkuwi/node/network/dispute-distribution/src/sender/send_task.rs @@ -315,8 +315,9 @@ async fn wait_response_task( let result = pending_response.await; let msg = match result { Err(err) => TaskFinish { candidate_hash, receiver, result: TaskResult::Failed(err) }, - Ok(DisputeResponse::Confirmed) => - TaskFinish { candidate_hash, receiver, result: TaskResult::Succeeded }, + Ok(DisputeResponse::Confirmed) => { + TaskFinish { candidate_hash, receiver, result: TaskResult::Succeeded } + }, }; if let Err(err) = tx.send_message(msg).await { gum::debug!( diff --git a/pezkuwi/node/network/gossip-support/src/lib.rs b/pezkuwi/node/network/gossip-support/src/lib.rs index c54f9eb0..e920b967 100644 --- a/pezkuwi/node/network/gossip-support/src/lib.rs +++ b/pezkuwi/node/network/gossip-support/src/lib.rs @@ -210,7 +210,7 @@ where gum::debug!(target: LOG_TARGET, error = ?e); } }, - FromOrchestra::Signal(OverseerSignal::BlockFinalized(_hash, _number)) => + FromOrchestra::Signal(OverseerSignal::BlockFinalized(_hash, _number)) => { if let Some(session_index) = self.last_session_index { if let Err(e) = self .build_topology_for_last_finalized_if_needed( @@ -225,7 +225,8 @@ where e ); } - }, + } + }, FromOrchestra::Signal(OverseerSignal::Conclude) => return self, } } @@ -394,8 +395,8 @@ where .await .await??; - if finalized_session_index < self.min_known_session && - Some(finalized_session_index) != self.finalized_needed_session + if finalized_session_index < self.min_known_session + && Some(finalized_session_index) != self.finalized_needed_session { gum::debug!( target: LOG_TARGET, diff --git a/pezkuwi/node/network/protocol/src/grid_topology.rs b/pezkuwi/node/network/protocol/src/grid_topology.rs index 7726a423..c4fdacbb 100644 --- a/pezkuwi/node/network/protocol/src/grid_topology.rs +++ b/pezkuwi/node/network/protocol/src/grid_topology.rs @@ -586,12 +586,12 @@ impl RequiredRouting { match (self, other) { (RequiredRouting::All, _) | (_, RequiredRouting::All) => RequiredRouting::All, (RequiredRouting::GridXY, _) | (_, RequiredRouting::GridXY) => RequiredRouting::GridXY, - (RequiredRouting::GridX, RequiredRouting::GridY) | - (RequiredRouting::GridY, RequiredRouting::GridX) => RequiredRouting::GridXY, + (RequiredRouting::GridX, RequiredRouting::GridY) + | (RequiredRouting::GridY, RequiredRouting::GridX) => RequiredRouting::GridXY, (RequiredRouting::GridX, RequiredRouting::GridX) => RequiredRouting::GridX, (RequiredRouting::GridY, RequiredRouting::GridY) => RequiredRouting::GridY, - (RequiredRouting::None, RequiredRouting::PendingTopology) | - (RequiredRouting::PendingTopology, RequiredRouting::None) => RequiredRouting::PendingTopology, + (RequiredRouting::None, RequiredRouting::PendingTopology) + | (RequiredRouting::PendingTopology, RequiredRouting::None) => RequiredRouting::PendingTopology, (RequiredRouting::None, _) | (RequiredRouting::PendingTopology, _) => other, (_, RequiredRouting::None) | (_, RequiredRouting::PendingTopology) => self, } diff --git a/pezkuwi/node/network/protocol/src/lib.rs b/pezkuwi/node/network/protocol/src/lib.rs index d4e7f137..55f2d021 100644 --- a/pezkuwi/node/network/protocol/src/lib.rs +++ b/pezkuwi/node/network/protocol/src/lib.rs @@ -346,8 +346,9 @@ macro_rules! impl_versioned_validation_try_from { fn try_from(x: &'a $from) -> Result<$out, Self::Error> { #[allow(unreachable_patterns)] // when there is only one variant match x { - ValidationProtocols::V3($v3_pat) => - Ok(ValidationProtocols::V3($v3_out.clone())), + ValidationProtocols::V3($v3_pat) => { + Ok(ValidationProtocols::V3($v3_out.clone())) + }, _ => Err(crate::WrongVariant), } } diff --git a/pezkuwi/node/network/protocol/src/peer_set.rs b/pezkuwi/node/network/protocol/src/peer_set.rs index 98ae763a..1f9f295f 100644 --- a/pezkuwi/node/network/protocol/src/peer_set.rs +++ b/pezkuwi/node/network/protocol/src/peer_set.rs @@ -168,20 +168,22 @@ impl PeerSet { // Unfortunately, labels must be static strings, so we must manually cover them // for all protocol versions here. match self { - PeerSet::Validation => + PeerSet::Validation => { if version == ValidationVersion::V3.into() { Some("validation/3") } else { None - }, - PeerSet::Collation => + } + }, + PeerSet::Collation => { if version == CollationVersion::V1.into() { Some("collation/1") } else if version == CollationVersion::V2.into() { Some("collation/2") } else { None - }, + } + }, } } } @@ -320,7 +322,7 @@ impl PeerSetProtocolNames { let mut names = HashMap::new(); for protocol in PeerSet::iter() { match protocol { - PeerSet::Validation => + PeerSet::Validation => { for version in ValidationVersion::iter() { Self::register_main_protocol( &mut protocols, @@ -330,7 +332,8 @@ impl PeerSetProtocolNames { &genesis_hash, fork_id, ); - }, + } + }, PeerSet::Collation => { for version in CollationVersion::iter() { Self::register_main_protocol( @@ -566,7 +569,7 @@ mod tests { for protocol in PeerSet::iter() { match protocol { - PeerSet::Validation => + PeerSet::Validation => { for version in ValidationVersion::iter() { assert_eq!( protocol_names.get_name(protocol, version.into()), @@ -577,8 +580,9 @@ mod tests { version.into(), ), ); - }, - PeerSet::Collation => + } + }, + PeerSet::Collation => { for version in CollationVersion::iter() { assert_eq!( protocol_names.get_name(protocol, version.into()), @@ -589,7 +593,8 @@ mod tests { version.into(), ), ); - }, + } + }, } } } @@ -598,18 +603,20 @@ mod tests { fn all_protocol_versions_have_labels() { for protocol in PeerSet::iter() { match protocol { - PeerSet::Validation => + PeerSet::Validation => { for version in ValidationVersion::iter() { protocol .get_protocol_label(version.into()) .expect("All validation protocol versions must have a label."); - }, - PeerSet::Collation => + } + }, + PeerSet::Collation => { for version in CollationVersion::iter() { protocol .get_protocol_label(version.into()) .expect("All collation protocol versions must have a label."); - }, + } + }, } } } diff --git a/pezkuwi/node/network/protocol/src/reputation.rs b/pezkuwi/node/network/protocol/src/reputation.rs index 2ced9c82..d9b8ba95 100644 --- a/pezkuwi/node/network/protocol/src/reputation.rs +++ b/pezkuwi/node/network/protocol/src/reputation.rs @@ -74,10 +74,10 @@ impl UnifiedReputationChange { /// Whether the reputation change is for good behavior. pub const fn is_benefit(&self) -> bool { match self { - Self::BenefitMajorFirst(_) | - Self::BenefitMajor(_) | - Self::BenefitMinorFirst(_) | - Self::BenefitMinor(_) => true, + Self::BenefitMajorFirst(_) + | Self::BenefitMajor(_) + | Self::BenefitMinorFirst(_) + | Self::BenefitMinor(_) => true, _ => false, } } diff --git a/pezkuwi/node/network/protocol/src/request_response/mod.rs b/pezkuwi/node/network/protocol/src/request_response/mod.rs index d0e1e1ba..8fadc906 100644 --- a/pezkuwi/node/network/protocol/src/request_response/mod.rs +++ b/pezkuwi/node/network/protocol/src/request_response/mod.rs @@ -281,8 +281,8 @@ impl Protocol { // wasting precious time. let available_bandwidth = 7 * MIN_BANDWIDTH_BYTES / 10; let size = u64::saturating_sub( - ATTESTED_CANDIDATE_TIMEOUT.as_millis() as u64 * available_bandwidth / - (1000 * MAX_CODE_SIZE as u64), + ATTESTED_CANDIDATE_TIMEOUT.as_millis() as u64 * available_bandwidth + / (1000 * MAX_CODE_SIZE as u64), MAX_PARALLEL_ATTESTED_CANDIDATE_REQUESTS as u64, ); debug_assert!( diff --git a/pezkuwi/node/network/protocol/src/request_response/outgoing.rs b/pezkuwi/node/network/protocol/src/request_response/outgoing.rs index 073f262b..edb418ed 100644 --- a/pezkuwi/node/network/protocol/src/request_response/outgoing.rs +++ b/pezkuwi/node/network/protocol/src/request_response/outgoing.rs @@ -91,9 +91,9 @@ impl RequestError { /// Whether the error represents some kind of timeout condition. pub fn is_timed_out(&self) -> bool { match self { - Self::Canceled(_) | - Self::NetworkError(network::RequestFailure::Obsolete) | - Self::NetworkError(network::RequestFailure::Network( + Self::Canceled(_) + | Self::NetworkError(network::RequestFailure::Obsolete) + | Self::NetworkError(network::RequestFailure::Network( network::OutboundFailure::Timeout, )) => true, _ => false, diff --git a/pezkuwi/node/network/statement-distribution/src/v2/candidates.rs b/pezkuwi/node/network/statement-distribution/src/v2/candidates.rs index b7fcd7ac..24902517 100644 --- a/pezkuwi/node/network/statement-distribution/src/v2/candidates.rs +++ b/pezkuwi/node/network/statement-distribution/src/v2/candidates.rs @@ -185,9 +185,9 @@ impl Candidates { let mut reckoning = PostConfirmationReckoning::default(); for (leaf_hash, x) in u.unconfirmed_importable_under { - if x.relay_parent == relay_parent && - x.parent_hash == parent_hash && - x.para_id == para_id + if x.relay_parent == relay_parent + && x.parent_hash == parent_hash + && x.para_id == para_id { new_confirmed.importable_under.insert(leaf_hash); } @@ -296,8 +296,9 @@ impl Candidates { ) { for (c_hash, candidate) in i { match candidate { - CandidateState::Unconfirmed(u) => - u.extend_hypotheticals(*c_hash, v, maybe_required_parent), + CandidateState::Unconfirmed(u) => { + u.extend_hypotheticals(*c_hash, v, maybe_required_parent) + }, CandidateState::Confirmed(c) => v.push(c.to_hypothetical(*c_hash)), } } @@ -335,7 +336,7 @@ impl Candidates { } }; self.candidates.retain(|c_hash, state| match state { - CandidateState::Confirmed(ref mut c) => + CandidateState::Confirmed(ref mut c) => { if !relay_parent_live(&c.relay_parent()) { remove_parent_claims(*c_hash, c.parent_head_data_hash(), c.para_id()); false @@ -344,7 +345,8 @@ impl Candidates { c.importable_under.remove(leaf_hash); } true - }, + } + }, CandidateState::Unconfirmed(ref mut c) => { c.on_deactivate_leaves( leaves, @@ -393,9 +395,9 @@ impl CandidateClaims { parent_hash: Hash, para_id: ParaId, ) -> bool { - self.relay_parent == relay_parent && - self.group_index == group_index && - self.parent_hash_and_id.map_or(true, |p| p == (parent_hash, para_id)) + self.relay_parent == relay_parent + && self.group_index == group_index + && self.parent_hash_and_id.map_or(true, |p| p == (parent_hash, para_id)) } } diff --git a/pezkuwi/node/network/statement-distribution/src/v2/cluster.rs b/pezkuwi/node/network/statement-distribution/src/v2/cluster.rs index faf61ce1..3a8c86df 100644 --- a/pezkuwi/node/network/statement-distribution/src/v2/cluster.rs +++ b/pezkuwi/node/network/statement-distribution/src/v2/cluster.rs @@ -320,16 +320,16 @@ impl ClusterTracker { ) -> bool { // we sent, they sent, or they signed and we received from someone else. - self.we_sent_seconded(validator, candidate_hash) || - self.they_sent_seconded(validator, candidate_hash) || - self.validator_seconded(validator, candidate_hash) + self.we_sent_seconded(validator, candidate_hash) + || self.they_sent_seconded(validator, candidate_hash) + || self.validator_seconded(validator, candidate_hash) } /// Whether a validator can request a candidate from us. pub fn can_request(&self, target: ValidatorIndex, candidate_hash: CandidateHash) -> bool { - self.validators.contains(&target) && - self.we_sent_seconded(target, candidate_hash) && - !self.they_sent_seconded(target, candidate_hash) + self.validators.contains(&target) + && self.we_sent_seconded(target, candidate_hash) + && !self.they_sent_seconded(target, candidate_hash) } /// Returns a Vec of pending statements to be sent to a particular validator diff --git a/pezkuwi/node/network/statement-distribution/src/v2/grid.rs b/pezkuwi/node/network/statement-distribution/src/v2/grid.rs index 690ba0e2..840c9805 100644 --- a/pezkuwi/node/network/statement-distribution/src/v2/grid.rs +++ b/pezkuwi/node/network/statement-distribution/src/v2/grid.rs @@ -283,11 +283,13 @@ impl GridTracker { // * They are in the sending set for the group AND we have sent them a manifest AND // the received manifest is partial. ManifestKind::Full => receiving_from, - ManifestKind::Acknowledgement => - sending_to && - self.confirmed_backed + ManifestKind::Acknowledgement => { + sending_to + && self + .confirmed_backed .get(&candidate_hash) - .map_or(false, |c| c.has_sent_manifest_to(sender)), + .map_or(false, |c| c.has_sent_manifest_to(sender)) + }, }; if !manifest_allowed { @@ -1083,10 +1085,10 @@ impl KnownBackedCandidate { .filter(|k| k.local_knowledge.is_some()) .and_then(|k| k.remote_knowledge.as_ref()) .map(|remote| StatementFilter { - seconded_in_group: full_local.seconded_in_group.clone() & - !remote.seconded_in_group.clone(), - validated_in_group: full_local.validated_in_group.clone() & - !remote.validated_in_group.clone(), + seconded_in_group: full_local.seconded_in_group.clone() + & !remote.seconded_in_group.clone(), + validated_in_group: full_local.validated_in_group.clone() + & !remote.validated_in_group.clone(), }) } } diff --git a/pezkuwi/node/network/statement-distribution/src/v2/mod.rs b/pezkuwi/node/network/statement-distribution/src/v2/mod.rs index 7a0caf39..72da546d 100644 --- a/pezkuwi/node/network/statement-distribution/src/v2/mod.rs +++ b/pezkuwi/node/network/statement-distribution/src/v2/mod.rs @@ -494,7 +494,7 @@ pub(crate) async fn handle_network_update( NetworkBridgeEvent::PeerMessage(peer_id, message) => match message { net_protocol::StatementDistributionMessage::V3( protocol_v3::StatementDistributionMessage::Statement(relay_parent, statement), - ) => + ) => { handle_incoming_statement( ctx, state, @@ -504,18 +504,21 @@ pub(crate) async fn handle_network_update( reputation, metrics, ) - .await, + .await + }, net_protocol::StatementDistributionMessage::V3( protocol_v3::StatementDistributionMessage::BackedCandidateManifest(inner), ) => handle_incoming_manifest(ctx, state, peer_id, inner, reputation, metrics).await, net_protocol::StatementDistributionMessage::V3( protocol_v3::StatementDistributionMessage::BackedCandidateKnown(inner), - ) => + ) => { handle_incoming_acknowledgement(ctx, state, peer_id, inner, reputation, metrics) - .await, + .await + }, + }, + NetworkBridgeEvent::PeerViewChange(peer_id, view) => { + handle_peer_view_update(ctx, state, peer_id, view, metrics).await }, - NetworkBridgeEvent::PeerViewChange(peer_id, view) => - handle_peer_view_update(ctx, state, peer_id, view, metrics).await, NetworkBridgeEvent::OurViewChange(_view) => { // handled by `handle_activated_leaf` }, @@ -1161,10 +1164,12 @@ pub(crate) async fn share_local_statement( // Two possibilities: either the statement is `Seconded` or we already // have the candidate. Sanity: check the para-id is valid. let expected = match statement.payload() { - FullStatementWithPVD::Seconded(ref c, _) => - Some((c.descriptor.para_id(), c.descriptor.relay_parent())), - FullStatementWithPVD::Valid(hash) => - state.candidates.get_confirmed(&hash).map(|c| (c.para_id(), c.relay_parent())), + FullStatementWithPVD::Seconded(ref c, _) => { + Some((c.descriptor.para_id(), c.descriptor.relay_parent())) + }, + FullStatementWithPVD::Valid(hash) => { + state.candidates.get_confirmed(&hash).map(|c| (c.para_id(), c.relay_parent())) + }, }; let is_seconded = match statement.payload() { @@ -1183,8 +1188,8 @@ pub(crate) async fn share_local_statement( let seconding_limit = local_assignments.len(); - if is_seconded && - per_relay_parent.statement_store.seconded_count(&local_index) >= seconding_limit + if is_seconded + && per_relay_parent.statement_store.seconded_count(&local_index) >= seconding_limit { gum::warn!( target: LOG_TARGET, @@ -1789,8 +1794,9 @@ fn handle_cluster_statement( Ok(ClusterAccept::Ok) => true, Ok(ClusterAccept::WithPrejudice) => false, Err(ClusterRejectIncoming::ExcessiveSeconded) => return Err(COST_EXCESSIVE_SECONDED), - Err(ClusterRejectIncoming::CandidateUnknown | ClusterRejectIncoming::Duplicate) => - return Err(COST_UNEXPECTED_STATEMENT_CLUSTER_REJECTED), + Err(ClusterRejectIncoming::CandidateUnknown | ClusterRejectIncoming::Duplicate) => { + return Err(COST_UNEXPECTED_STATEMENT_CLUSTER_REJECTED) + }, Err(ClusterRejectIncoming::NotInGroup) => { // sanity: shouldn't be possible; we already filtered this // out above. @@ -1989,12 +1995,13 @@ async fn provide_candidate_to_grid( for (v, action) in actions { let p = match connected_validator_peer(authorities, per_session, v) { None => continue, - Some(p) => + Some(p) => { if peers.get(&p).map_or(false, |d| d.knows_relay_parent(&relay_parent)) { (p, peers.get(&p).expect("Qed, was checked above").protocol_version.into()) } else { continue; - }, + } + }, }; match action { @@ -2940,8 +2947,9 @@ pub(crate) async fn receive_response(response_manager: &mut ResponseManager) -> /// this API must call `dispatch_requests`. pub(crate) async fn next_retry(request_manager: &mut RequestManager) { match request_manager.next_retry_time() { - Some(instant) => - futures_timer::Delay::new(instant.saturating_duration_since(Instant::now())).await, + Some(instant) => { + futures_timer::Delay::new(instant.saturating_duration_since(Instant::now())).await + }, None => futures::future::pending().await, } } diff --git a/pezkuwi/node/network/statement-distribution/src/v2/requests.rs b/pezkuwi/node/network/statement-distribution/src/v2/requests.rs index 1435c82a..8fd2a01e 100644 --- a/pezkuwi/node/network/statement-distribution/src/v2/requests.rs +++ b/pezkuwi/node/network/statement-distribution/src/v2/requests.rs @@ -583,12 +583,13 @@ impl UnhandledResponse { // it could also happen in the case that we had a request in-flight // and the request entry was garbage-collected on outdated relay parent. let entry = match manager.requests.get_mut(&identifier) { - None => + None => { return ResponseValidationOutput { requested_peer, reputation_changes: Vec::new(), request_status: CandidateRequestStatus::Outdated, - }, + } + }, Some(e) => e, }; @@ -710,8 +711,8 @@ fn validate_complete_response( return invalid_candidate_output(COST_INVALID_RESPONSE); } - if response.candidate_receipt.descriptor.persisted_validation_data_hash() != - response.persisted_validation_data.hash() + if response.candidate_receipt.descriptor.persisted_validation_data_hash() + != response.persisted_validation_data.hash() { return invalid_candidate_output(COST_INVALID_RESPONSE); } @@ -730,8 +731,8 @@ fn validate_complete_response( let candidate_hash = response.candidate_receipt.hash(); // V2 descriptors are invalid if not enabled by runtime. - if !allow_v2_descriptors && - response.candidate_receipt.descriptor.version() == CandidateDescriptorVersion::V2 + if !allow_v2_descriptors + && response.candidate_receipt.descriptor.version() == CandidateDescriptorVersion::V2 { gum::debug!( target: LOG_TARGET, @@ -794,8 +795,8 @@ fn validate_complete_response( }; // ensure statement is on the correct candidate hash. - if unchecked_statement.unchecked_payload().candidate_hash() != - &identifier.candidate_hash + if unchecked_statement.unchecked_payload().candidate_hash() + != &identifier.candidate_hash { rep_changes.push((requested_peer, COST_UNREQUESTED_RESPONSE_STATEMENT)); continue; diff --git a/pezkuwi/node/network/statement-distribution/src/v2/tests/mod.rs b/pezkuwi/node/network/statement-distribution/src/v2/tests/mod.rs index b7ce6f38..bddb4f32 100644 --- a/pezkuwi/node/network/statement-distribution/src/v2/tests/mod.rs +++ b/pezkuwi/node/network/statement-distribution/src/v2/tests/mod.rs @@ -914,7 +914,7 @@ fn next_group_index( group_size: usize, ) -> GroupIndex { let next_group = group_index.0 + 1; - let num_groups = - validator_count / group_size + if !validator_count.is_multiple_of(group_size) { 1 } else { 0 }; + let num_groups = validator_count / group_size + + if !validator_count.is_multiple_of(group_size) { 1 } else { 0 }; GroupIndex::from(next_group % num_groups as u32) } diff --git a/pezkuwi/node/overseer/src/lib.rs b/pezkuwi/node/overseer/src/lib.rs index 303a7e80..c3e23bd2 100644 --- a/pezkuwi/node/overseer/src/lib.rs +++ b/pezkuwi/node/overseer/src/lib.rs @@ -698,7 +698,7 @@ where #[cfg(any(target_os = "linux", feature = "jemalloc-allocator"))] let collect_memory_stats: Box = match memory_stats::MemoryAllocationTracker::new() { - Ok(memory_stats) => + Ok(memory_stats) => { Box::new(move |metrics: &OverseerMetrics| match memory_stats.snapshot() { Ok(memory_stats_snapshot) => { gum::trace!( @@ -711,7 +711,8 @@ where Err(e) => { gum::debug!(target: LOG_TARGET, "Failed to obtain memory stats: {:?}", e) }, - }), + }) + }, Err(_) => { gum::debug!( target: LOG_TARGET, diff --git a/pezkuwi/node/overseer/src/tests.rs b/pezkuwi/node/overseer/src/tests.rs index c4ab1763..3a55df95 100644 --- a/pezkuwi/node/overseer/src/tests.rs +++ b/pezkuwi/node/overseer/src/tests.rs @@ -447,8 +447,8 @@ fn overseer_start_stop_works() { complete => break, } - if ss5_results.len() == expected_heartbeats.len() && - ss6_results.len() == expected_heartbeats.len() + if ss5_results.len() == expected_heartbeats.len() + && ss6_results.len() == expected_heartbeats.len() { handle.stop().await; } @@ -551,8 +551,8 @@ fn overseer_finalize_works() { complete => break, } - if ss5_results.len() == expected_heartbeats.len() && - ss6_results.len() == expected_heartbeats.len() + if ss5_results.len() == expected_heartbeats.len() + && ss6_results.len() == expected_heartbeats.len() { handle.stop().await; } @@ -654,8 +654,8 @@ fn overseer_finalize_leaf_preserves_it() { complete => break, } - if ss5_results.len() == expected_heartbeats.len() && - ss6_results.len() == expected_heartbeats.len() + if ss5_results.len() == expected_heartbeats.len() + && ss6_results.len() == expected_heartbeats.len() { handle.stop().await; } diff --git a/pezkuwi/node/primitives/src/approval/mod.rs b/pezkuwi/node/primitives/src/approval/mod.rs index a3b1ffd4..8ef55e0c 100644 --- a/pezkuwi/node/primitives/src/approval/mod.rs +++ b/pezkuwi/node/primitives/src/approval/mod.rs @@ -412,10 +412,12 @@ pub mod v2 { fn from(cert: super::v1::AssignmentCert) -> Self { Self { kind: match cert.kind { - super::v1::AssignmentCertKind::RelayVRFDelay { core_index } => - AssignmentCertKindV2::RelayVRFDelay { core_index }, - super::v1::AssignmentCertKind::RelayVRFModulo { sample } => - AssignmentCertKindV2::RelayVRFModulo { sample }, + super::v1::AssignmentCertKind::RelayVRFDelay { core_index } => { + AssignmentCertKindV2::RelayVRFDelay { core_index } + }, + super::v1::AssignmentCertKind::RelayVRFModulo { sample } => { + AssignmentCertKindV2::RelayVRFModulo { sample } + }, }, vrf: cert.vrf, } @@ -434,10 +436,12 @@ pub mod v2 { fn try_from(cert: AssignmentCertV2) -> Result { Ok(Self { kind: match cert.kind { - AssignmentCertKindV2::RelayVRFDelay { core_index } => - super::v1::AssignmentCertKind::RelayVRFDelay { core_index }, - AssignmentCertKindV2::RelayVRFModulo { sample } => - super::v1::AssignmentCertKind::RelayVRFModulo { sample }, + AssignmentCertKindV2::RelayVRFDelay { core_index } => { + super::v1::AssignmentCertKind::RelayVRFDelay { core_index } + }, + AssignmentCertKindV2::RelayVRFModulo { sample } => { + super::v1::AssignmentCertKind::RelayVRFModulo { sample } + }, // Not supported _ => return Err(AssignmentConversionError::CertificateNotSupported), }, diff --git a/pezkuwi/node/primitives/src/disputes/mod.rs b/pezkuwi/node/primitives/src/disputes/mod.rs index 56d85843..a56ddee7 100644 --- a/pezkuwi/node/primitives/src/disputes/mod.rs +++ b/pezkuwi/node/primitives/src/disputes/mod.rs @@ -113,11 +113,11 @@ impl ValidCandidateVotes { true }, Bentry::Occupied(mut occupied) => match occupied.get().0 { - ValidDisputeStatementKind::BackingValid(_) | - ValidDisputeStatementKind::BackingSeconded(_) => false, - ValidDisputeStatementKind::Explicit | - ValidDisputeStatementKind::ApprovalChecking | - ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(_) => { + ValidDisputeStatementKind::BackingValid(_) + | ValidDisputeStatementKind::BackingSeconded(_) => false, + ValidDisputeStatementKind::Explicit + | ValidDisputeStatementKind::ApprovalChecking + | ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(_) => { occupied.insert((kind.clone(), sig)); kind != occupied.get().0 }, diff --git a/pezkuwi/node/primitives/src/disputes/status.rs b/pezkuwi/node/primitives/src/disputes/status.rs index be827e64..40e3ff0b 100644 --- a/pezkuwi/node/primitives/src/disputes/status.rs +++ b/pezkuwi/node/primitives/src/disputes/status.rs @@ -67,9 +67,9 @@ impl DisputeStatus { /// Check whether the dispute is not a spam dispute. pub fn is_confirmed_concluded(&self) -> bool { match self { - &DisputeStatus::Confirmed | - &DisputeStatus::ConcludedFor(_) | - DisputeStatus::ConcludedAgainst(_) => true, + &DisputeStatus::Confirmed + | &DisputeStatus::ConcludedFor(_) + | DisputeStatus::ConcludedAgainst(_) => true, &DisputeStatus::Active => false, } } @@ -103,21 +103,24 @@ impl DisputeStatus { /// candidate. This may be a no-op if the status was already concluded. pub fn conclude_against(self, now: Timestamp) -> DisputeStatus { match self { - DisputeStatus::Active | DisputeStatus::Confirmed => - DisputeStatus::ConcludedAgainst(now), - DisputeStatus::ConcludedFor(at) => - DisputeStatus::ConcludedAgainst(std::cmp::min(at, now)), - DisputeStatus::ConcludedAgainst(at) => - DisputeStatus::ConcludedAgainst(std::cmp::min(at, now)), + DisputeStatus::Active | DisputeStatus::Confirmed => { + DisputeStatus::ConcludedAgainst(now) + }, + DisputeStatus::ConcludedFor(at) => { + DisputeStatus::ConcludedAgainst(std::cmp::min(at, now)) + }, + DisputeStatus::ConcludedAgainst(at) => { + DisputeStatus::ConcludedAgainst(std::cmp::min(at, now)) + }, } } /// Whether the disputed candidate is possibly invalid. pub fn is_possibly_invalid(&self) -> bool { match self { - DisputeStatus::Active | - DisputeStatus::Confirmed | - DisputeStatus::ConcludedAgainst(_) => true, + DisputeStatus::Active + | DisputeStatus::Confirmed + | DisputeStatus::ConcludedAgainst(_) => true, DisputeStatus::ConcludedFor(_) => false, } } diff --git a/pezkuwi/node/service/src/builder/mod.rs b/pezkuwi/node/service/src/builder/mod.rs index b111f706..87956ed8 100644 --- a/pezkuwi/node/service/src/builder/mod.rs +++ b/pezkuwi/node/service/src/builder/mod.rs @@ -231,8 +231,8 @@ where let force_authoring = config.force_authoring; let disable_grandpa = config.disable_grandpa; let name = config.network.node_name.clone(); - let backoff_authoring_blocks = if !force_authoring_backoff && - (config.chain_spec.is_pezkuwi() || config.chain_spec.is_kusama()) + let backoff_authoring_blocks = if !force_authoring_backoff + && (config.chain_spec.is_pezkuwi() || config.chain_spec.is_kusama()) { // the block authoring backoff is disabled by default on production networks None @@ -240,9 +240,9 @@ where let mut backoff = pezsc_consensus_slots::BackoffAuthoringOnFinalizedHeadLagging::default(); - if config.chain_spec.is_pezkuwichain() || - config.chain_spec.is_versi() || - config.chain_spec.is_dev() + if config.chain_spec.is_pezkuwichain() + || config.chain_spec.is_versi() + || config.chain_spec.is_dev() { // on testnets that are in flux (like pezkuwichain or versi), finality has stalled // sometimes due to operational issues and it's annoying to slow down block @@ -316,8 +316,8 @@ where // // Collators and teyrchain full nodes require the collator and validator networking to send // collations and to be able to recover PoVs. - let notification_services = if role.is_authority() || - is_teyrchain_node.is_running_alongside_teyrchain_node() + let notification_services = if role.is_authority() + || is_teyrchain_node.is_running_alongside_teyrchain_node() { use pezkuwi_network_bridge::{peer_sets_info, IsAuthority}; let is_authority = if role.is_authority() { IsAuthority::Yes } else { IsAuthority::No }; diff --git a/pezkuwi/node/service/src/lib.rs b/pezkuwi/node/service/src/lib.rs index ac18deec..98bb87e5 100644 --- a/pezkuwi/node/service/src/lib.rs +++ b/pezkuwi/node/service/src/lib.rs @@ -450,10 +450,12 @@ pub fn build_full( }); match config.network.network_backend { - pezsc_network::config::NetworkBackendType::Libp2p => - new_full::<_, pezsc_network::NetworkWorker>(config, params), - pezsc_network::config::NetworkBackendType::Litep2p => - new_full::<_, pezsc_network::Litep2pNetworkBackend>(config, params), + pezsc_network::config::NetworkBackendType::Libp2p => { + new_full::<_, pezsc_network::NetworkWorker>(config, params) + }, + pezsc_network::config::NetworkBackendType::Litep2p => { + new_full::<_, pezsc_network::Litep2pNetworkBackend>(config, params) + }, } } diff --git a/pezkuwi/node/service/src/overseer.rs b/pezkuwi/node/service/src/overseer.rs index 342ed06c..52f7ba87 100644 --- a/pezkuwi/node/service/src/overseer.rs +++ b/pezkuwi/node/service/src/overseer.rs @@ -295,10 +295,11 @@ where .collation_generation(DummySubsystem) .collator_protocol({ let side = match is_teyrchain_node { - IsTeyrchainNode::Collator(_) | IsTeyrchainNode::FullNode => + IsTeyrchainNode::Collator(_) | IsTeyrchainNode::FullNode => { return Err(Error::Overseer(SubsystemError::Context( "build validator overseer for teyrchain node".to_owned(), - ))), + ))) + }, IsTeyrchainNode::No => ProtocolSide::Validator { keystore: keystore.clone(), eviction_policy: Default::default(), @@ -466,10 +467,11 @@ where .collation_generation(CollationGenerationSubsystem::new(Metrics::register(registry)?)) .collator_protocol({ let side = match is_teyrchain_node { - IsTeyrchainNode::No => + IsTeyrchainNode::No => { return Err(Error::Overseer(SubsystemError::Context( "build teyrchain node overseer for validator".to_owned(), - ))), + ))) + }, IsTeyrchainNode::Collator(collator_pair) => ProtocolSide::Collator { peer_id: network_service.local_peer_id(), collator_pair, diff --git a/pezkuwi/node/service/src/relay_chain_selection.rs b/pezkuwi/node/service/src/relay_chain_selection.rs index 155eaf4a..382a1dc7 100644 --- a/pezkuwi/node/service/src/relay_chain_selection.rs +++ b/pezkuwi/node/service/src/relay_chain_selection.rs @@ -251,8 +251,9 @@ where fn block_header(&self, hash: Hash) -> Result { match HeaderProvider::header(self.backend.header_provider(), hash) { Ok(Some(header)) => Ok(header), - Ok(None) => - Err(ConsensusError::ChainLookup(format!("Missing header with hash {:?}", hash,))), + Ok(None) => { + Err(ConsensusError::ChainLookup(format!("Missing header with hash {:?}", hash,))) + }, Err(e) => Err(ConsensusError::ChainLookup(format!( "Lookup failed for header with hash {:?}: {:?}", hash, e, @@ -263,8 +264,9 @@ where fn block_number(&self, hash: Hash) -> Result { match HeaderProvider::number(self.backend.header_provider(), hash) { Ok(Some(number)) => Ok(number), - Ok(None) => - Err(ConsensusError::ChainLookup(format!("Missing number with hash {:?}", hash,))), + Ok(None) => { + Err(ConsensusError::ChainLookup(format!("Missing number with hash {:?}", hash,))) + }, Err(e) => Err(ConsensusError::ChainLookup(format!( "Lookup failed for number with hash {:?}: {:?}", hash, e, @@ -490,8 +492,9 @@ where { // No approved ancestors means target hash is maximal vote. None => (target_hash, target_number, Vec::new()), - Some(HighestApprovedAncestorBlock { number, hash, descriptions }) => - (hash, number, descriptions), + Some(HighestApprovedAncestorBlock { number, hash, descriptions }) => { + (hash, number, descriptions) + }, } }; @@ -523,8 +526,8 @@ where let (lag, subchain_head) = { // Prevent sending flawed data to the dispute-coordinator. - if Some(subchain_block_descriptions.len() as _) != - subchain_number.checked_sub(target_number) + if Some(subchain_block_descriptions.len() as _) + != subchain_number.checked_sub(target_number) { gum::error!( LOG_TARGET, diff --git a/pezkuwi/node/service/src/teyrchains_db/upgrade.rs b/pezkuwi/node/service/src/teyrchains_db/upgrade.rs index a6d52780..aad3a3f3 100644 --- a/pezkuwi/node/service/src/teyrchains_db/upgrade.rs +++ b/pezkuwi/node/service/src/teyrchains_db/upgrade.rs @@ -119,8 +119,9 @@ pub(crate) fn try_upgrade_db_to_next_version( None if db_kind == DatabaseKind::RocksDB => CURRENT_VERSION, // No version file. `ParityDB` did not previously have a version defined. // We handle this as a `0 -> 1` migration. - None if db_kind == DatabaseKind::ParityDB => - migrate_from_version_0_to_1(db_path, db_kind)?, + None if db_kind == DatabaseKind::ParityDB => { + migrate_from_version_0_to_1(db_path, db_kind)? + }, None => unreachable!(), } } else { diff --git a/pezkuwi/node/subsystem-bench/src/lib/approval/helpers.rs b/pezkuwi/node/subsystem-bench/src/lib/approval/helpers.rs index 8b7035a5..1e98433b 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/approval/helpers.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/approval/helpers.rs @@ -64,8 +64,8 @@ impl PastSystemClock { impl Clock for PastSystemClock { fn tick_now(&self) -> Tick { - self.real_system_clock.tick_now() - - self.delta_ticks.load(std::sync::atomic::Ordering::SeqCst) + self.real_system_clock.tick_now() + - self.delta_ticks.load(std::sync::atomic::Ordering::SeqCst) } fn wait( diff --git a/pezkuwi/node/subsystem-bench/src/lib/approval/message_generator.rs b/pezkuwi/node/subsystem-bench/src/lib/approval/message_generator.rs index b010e9c1..e3ebc677 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/approval/message_generator.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/approval/message_generator.rs @@ -210,7 +210,7 @@ impl PeerMessagesGenerator { // Receive all messages and sort them by Tick they have to be sent. loop { match rx.try_next() { - Ok(Some((block_hash, messages))) => + Ok(Some((block_hash, messages))) => { for message in messages { let block_info = blocks .iter() @@ -223,7 +223,8 @@ impl PeerMessagesGenerator { ); let to_add = all_messages.entry(tick_to_send).or_default(); to_add.push(message); - }, + } + }, Ok(None) => break, Err(_) => { std::thread::sleep(Duration::from_millis(50)); @@ -326,8 +327,9 @@ impl PeerMessagesGenerator { let mut unique_assignments = HashSet::new(); for (core_index, assignment) in assignments { let assigned_cores = match &assignment.cert().kind { - approval::v2::AssignmentCertKindV2::RelayVRFModuloCompact { core_bitfield } => - core_bitfield.iter_ones().map(|val| CoreIndex::from(val as u32)).collect_vec(), + approval::v2::AssignmentCertKindV2::RelayVRFModuloCompact { core_bitfield } => { + core_bitfield.iter_ones().map(|val| CoreIndex::from(val as u32)).collect_vec() + }, approval::v2::AssignmentCertKindV2::RelayVRFDelay { core_index } => { vec![*core_index] }, @@ -495,10 +497,10 @@ fn issue_approvals( .map(|val| val.assignment.tranche) .unwrap_or(message.tranche); - if queued_to_sign.len() >= num_coalesce || - (!queued_to_sign.is_empty() && - current_validator_index != assignment.0.validator) || - message.tranche - earliest_tranche >= options.coalesce_tranche_diff + if queued_to_sign.len() >= num_coalesce + || (!queued_to_sign.is_empty() + && current_validator_index != assignment.0.validator) + || message.tranche - earliest_tranche >= options.coalesce_tranche_diff { approvals_to_create.push(TestSignInfo::sign_candidates( &mut queued_to_sign, @@ -642,23 +644,23 @@ fn neighbours_that_would_sent_message( .unwrap(); let originator_y = topology_originator.validator_indices_y.iter().find(|validator| { - topology_node_under_test.required_routing_by_index(**validator, false) == - RequiredRouting::GridY + topology_node_under_test.required_routing_by_index(**validator, false) + == RequiredRouting::GridY }); assert!(originator_y != Some(&ValidatorIndex(NODE_UNDER_TEST))); let originator_x = topology_originator.validator_indices_x.iter().find(|validator| { - topology_node_under_test.required_routing_by_index(**validator, false) == - RequiredRouting::GridX + topology_node_under_test.required_routing_by_index(**validator, false) + == RequiredRouting::GridX }); assert!(originator_x != Some(&ValidatorIndex(NODE_UNDER_TEST))); let is_neighbour = topology_originator .validator_indices_x - .contains(&ValidatorIndex(NODE_UNDER_TEST)) || - topology_originator + .contains(&ValidatorIndex(NODE_UNDER_TEST)) + || topology_originator .validator_indices_y .contains(&ValidatorIndex(NODE_UNDER_TEST)); diff --git a/pezkuwi/node/subsystem-bench/src/lib/approval/mock_chain_selection.rs b/pezkuwi/node/subsystem-bench/src/lib/approval/mock_chain_selection.rs index ed667b85..07f5ea1e 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/approval/mock_chain_selection.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/approval/mock_chain_selection.rs @@ -45,7 +45,7 @@ impl MockChainSelection { let msg = ctx.recv().await.expect("Should not fail"); match msg { orchestra::FromOrchestra::Signal(_) => {}, - orchestra::FromOrchestra::Communication { msg } => + orchestra::FromOrchestra::Communication { msg } => { if let ChainSelectionMessage::Approved(hash) = msg { let block_info = self.state.get_info_by_hash(hash); let approved_number = block_info.block_number; @@ -55,11 +55,12 @@ impl MockChainSelection { .last_approved_block .store(approved_number, std::sync::atomic::Ordering::SeqCst); - let approved_in_tick = self.clock.tick_now() - - slot_number_to_tick(SLOT_DURATION_MILLIS, block_info.slot); + let approved_in_tick = self.clock.tick_now() + - slot_number_to_tick(SLOT_DURATION_MILLIS, block_info.slot); gum::info!(target: LOG_TARGET, ?hash, "Chain selection approved after {:} ms", approved_in_tick * TICK_DURATION_MILLIS); - }, + } + }, } } } diff --git a/pezkuwi/node/subsystem-bench/src/lib/approval/mod.rs b/pezkuwi/node/subsystem-bench/src/lib/approval/mod.rs index 4a9f5589..26c529fc 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/approval/mod.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/approval/mod.rs @@ -207,8 +207,8 @@ struct CandidateTestData { impl CandidateTestData { /// If message in this tranche needs to be sent. fn should_send_tranche(&self, tranche: u32) -> bool { - self.sent_assignment <= self.needed_approvals || - tranche <= self.max_tranche + self.num_no_shows + self.sent_assignment <= self.needed_approvals + || tranche <= self.max_tranche + self.num_no_shows } /// Sets max tranche @@ -233,8 +233,8 @@ impl CandidateTestData { /// Tells if a message in this tranche should be a no-show. fn should_no_show(&self, tranche: u32) -> bool { - (self.num_no_shows < self.max_no_shows && self.last_tranche_with_no_show < tranche) || - (tranche == 0 && self.num_no_shows == 0 && self.max_no_shows > 0) + (self.num_no_shows < self.max_no_shows && self.last_tranche_with_no_show < tranche) + || (tranche == 0 && self.num_no_shows == 0 && self.max_no_shows > 0) } } @@ -547,8 +547,8 @@ impl PeerMessageProducer { .blocks .iter() .filter(|block_info| { - block_info.slot <= current_slot && - !initialized_blocks.contains(&block_info.hash) + block_info.slot <= current_slot + && !initialized_blocks.contains(&block_info.hash) }) .cloned() .collect_vec(); @@ -556,8 +556,8 @@ impl PeerMessageProducer { if !TestEnvironment::metric_lower_than( &self.registry, "pezkuwi_teyrchain_imported_candidates_total", - (block_info.total_candidates_before + block_info.candidates.len() as u64 - - 1) as f64, + (block_info.total_candidates_before + block_info.candidates.len() as u64 + - 1) as f64, ) { initialized_blocks.insert(block_info.hash); self.initialize_block(&block_info).await; @@ -670,8 +670,8 @@ impl PeerMessageProducer { } } } - } else if !block_info.approved.load(std::sync::atomic::Ordering::SeqCst) && - self.options.num_no_shows_per_candidate > 0 + } else if !block_info.approved.load(std::sync::atomic::Ordering::SeqCst) + && self.options.num_no_shows_per_candidate > 0 { skipped_messages.push(bundle); } @@ -708,9 +708,9 @@ impl PeerMessageProducer { block_info: &BlockTestData, block_initialized: bool, ) -> bool { - bundle.tranche_to_send() <= tranche_now && - current_slot >= block_info.slot && - block_initialized + bundle.tranche_to_send() <= tranche_now + && current_slot >= block_info.slot + && block_initialized } // Queue message to be sent by validator `sent_by` @@ -1011,8 +1011,8 @@ pub async fn bench_approvals_run( let start_marker = Instant::now(); let real_clock = SystemClock {}; state.delta_tick_from_generated.store( - real_clock.tick_now() - - slot_number_to_tick(SLOT_DURATION_MILLIS, state.generated_state.initial_slot), + real_clock.tick_now() + - slot_number_to_tick(SLOT_DURATION_MILLIS, state.generated_state.initial_slot), std::sync::atomic::Ordering::SeqCst, ); let system_clock = PastSystemClock::new(real_clock, state.delta_tick_from_generated.clone()); @@ -1046,8 +1046,8 @@ pub async fn bench_approvals_run( // Wait for all blocks to be approved before exiting. // This is an invariant of the benchmark, if this does not happen something went terribly wrong. - while state.last_approved_block.load(std::sync::atomic::Ordering::SeqCst) < - env.config().num_blocks as u32 + while state.last_approved_block.load(std::sync::atomic::Ordering::SeqCst) + < env.config().num_blocks as u32 { gum::info!( "Waiting for all blocks to be approved current approved {:} num_sent {:} num_unique {:}", diff --git a/pezkuwi/node/subsystem-bench/src/lib/approval/test_message.rs b/pezkuwi/node/subsystem-bench/src/lib/approval/test_message.rs index 19dd7969..df67f611 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/approval/test_message.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/approval/test_message.rs @@ -96,9 +96,9 @@ impl MessagesBundle { candidates_test_data: &HashMap<(Hash, CandidateIndex), CandidateTestData>, options: &ApprovalsOptions, ) -> bool { - self.needed_for_approval(candidates_test_data) || - (!options.stop_when_approved && - self.min_tranche() <= options.last_considered_tranche) + self.needed_for_approval(candidates_test_data) + || (!options.stop_when_approved + && self.min_tranche() <= options.last_considered_tranche) } /// Tells if the bundle is needed because we need more messages to approve the candidates. @@ -218,8 +218,8 @@ impl TestMessageInfo { assert_eq!(approvals.len(), 1); for approval in approvals { - should_no_show = should_no_show || - approval.candidate_indices.iter_ones().all(|candidate_index| { + should_no_show = should_no_show + || approval.candidate_indices.iter_ones().all(|candidate_index| { let candidate_test_data = candidates_test_data .get_mut(&( approval.block_hash, @@ -265,7 +265,7 @@ impl TestMessageInfo { candidates_test_data: &HashMap<(Hash, CandidateIndex), CandidateTestData>, ) -> bool { match &self.msg { - protocol_v3::ApprovalDistributionMessage::Assignments(assignments) => + protocol_v3::ApprovalDistributionMessage::Assignments(assignments) => { assignments.iter().any(|(assignment, candidate_indices)| { candidate_indices.iter_ones().any(|candidate_index| { candidates_test_data @@ -273,8 +273,9 @@ impl TestMessageInfo { .map(|data| data.should_send_tranche(self.tranche)) .unwrap_or_default() }) - }), - protocol_v3::ApprovalDistributionMessage::Approvals(approvals) => + }) + }, + protocol_v3::ApprovalDistributionMessage::Approvals(approvals) => { approvals.iter().any(|approval| { approval.candidate_indices.iter_ones().any(|candidate_index| { candidates_test_data @@ -282,7 +283,8 @@ impl TestMessageInfo { .map(|data| data.should_send_tranche(self.tranche)) .unwrap_or_default() }) - }), + }) + }, } } diff --git a/pezkuwi/node/subsystem-bench/src/lib/availability/mod.rs b/pezkuwi/node/subsystem-bench/src/lib/availability/mod.rs index 17715569..0c0fae52 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/availability/mod.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/availability/mod.rs @@ -220,13 +220,14 @@ pub fn prepare_test( let (overseer, overseer_handle) = match &mode { TestDataAvailability::Read(options) => { let subsystem = match options.strategy { - Strategy::FullFromBackers => + Strategy::FullFromBackers => { AvailabilityRecoverySubsystem::with_recovery_strategy_kind( collation_req_receiver, &state.req_protocol_names, Metrics::try_register(&dependencies.registry).unwrap(), RecoveryStrategyKind::BackersFirstAlways, - ), + ) + }, Strategy::Chunks => AvailabilityRecoverySubsystem::with_recovery_strategy_kind( collation_req_receiver, &state.req_protocol_names, @@ -436,8 +437,8 @@ pub async fn benchmark_availability_write( .get(index) .expect("all validators have keys"); - if env.network().is_peer_connected(peer) && - env.network().send_request_from_peer(peer, request).is_ok() + if env.network().is_peer_connected(peer) + && env.network().send_request_from_peer(peer, request).is_ok() { Some(pending_response_receiver) } else { diff --git a/pezkuwi/node/subsystem-bench/src/lib/disputes/mod.rs b/pezkuwi/node/subsystem-bench/src/lib/disputes/mod.rs index fca8eaca..9d5dd913 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/disputes/mod.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/disputes/mod.rs @@ -218,8 +218,8 @@ pub async fn benchmark_dispute_coordinator( let candidate_hashes = candidate_receipts.iter().map(|receipt| receipt.hash()).collect::>(); - let requests_expected = candidate_hashes.len() * - (state.config.n_validators * state.config.connectivity / 100 - 1); + let requests_expected = candidate_hashes.len() + * (state.config.n_validators * state.config.connectivity / 100 - 1); loop { let requests_sent = candidate_hashes diff --git a/pezkuwi/node/subsystem-bench/src/lib/mock/approval_voting_parallel.rs b/pezkuwi/node/subsystem-bench/src/lib/mock/approval_voting_parallel.rs index 9247e898..53a33fad 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/mock/approval_voting_parallel.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/mock/approval_voting_parallel.rs @@ -47,10 +47,11 @@ impl MockApprovalVotingParallel { loop { let msg = ctx.recv().await.expect("Overseer never fails us"); match msg { - orchestra::FromOrchestra::Signal(signal) => + orchestra::FromOrchestra::Signal(signal) => { if signal == OverseerSignal::Conclude { return; - }, + } + }, orchestra::FromOrchestra::Communication { msg } => match msg { ApprovalVotingParallelMessage::GetApprovalSignaturesForCandidate(hash, tx) => { gum::debug!(target: LOG_TARGET, "GetApprovalSignaturesForCandidate for candidate {:?}", hash); diff --git a/pezkuwi/node/subsystem-bench/src/lib/mock/av_store.rs b/pezkuwi/node/subsystem-bench/src/lib/mock/av_store.rs index 341760bc..82853174 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/mock/av_store.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/mock/av_store.rs @@ -204,10 +204,11 @@ impl MockAvailabilityStore { let msg = ctx.recv().await.expect("Overseer never fails us"); match msg { - orchestra::FromOrchestra::Signal(signal) => + orchestra::FromOrchestra::Signal(signal) => { if signal == OverseerSignal::Conclude { return; - }, + } + }, orchestra::FromOrchestra::Communication { msg } => match msg { AvailabilityStoreMessage::QueryAvailableData(candidate_hash, tx) => { gum::debug!(target: LOG_TARGET, candidate_hash = ?candidate_hash, "Responding to QueryAvailableData"); diff --git a/pezkuwi/node/subsystem-bench/src/lib/mock/availability_recovery.rs b/pezkuwi/node/subsystem-bench/src/lib/mock/availability_recovery.rs index 518ff06a..9228a0cb 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/mock/availability_recovery.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/mock/availability_recovery.rs @@ -51,10 +51,11 @@ impl MockAvailabilityRecovery { loop { let msg = ctx.recv().await.expect("Overseer never fails us"); match msg { - orchestra::FromOrchestra::Signal(signal) => + orchestra::FromOrchestra::Signal(signal) => { if signal == OverseerSignal::Conclude { return; - }, + } + }, orchestra::FromOrchestra::Communication { msg } => match msg { AvailabilityRecoveryMessage::RecoverAvailableData(receipt, _, _, _, tx) => { gum::debug!(target: LOG_TARGET, "RecoverAvailableData for candidate {:?}", receipt.hash()); diff --git a/pezkuwi/node/subsystem-bench/src/lib/mock/candidate_backing.rs b/pezkuwi/node/subsystem-bench/src/lib/mock/candidate_backing.rs index c7bd18b7..d4ceae2b 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/mock/candidate_backing.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/mock/candidate_backing.rs @@ -73,8 +73,8 @@ impl MockCandidateBacking { .or_insert(1); let statements_received_count = *statements_tracker.get(&candidate_hash).unwrap(); - if statements_received_count == (self.config.minimum_backing_votes - 1) && - is_own_backing_group + if statements_received_count == (self.config.minimum_backing_votes - 1) + && is_own_backing_group { let statement = Statement::Valid(candidate_hash); let context = SigningContext { parent_hash: relay_parent, session_index: 0 }; @@ -142,10 +142,11 @@ impl MockCandidateBacking { loop { let msg = ctx.recv().await.expect("Overseer never fails us"); match msg { - orchestra::FromOrchestra::Signal(signal) => + orchestra::FromOrchestra::Signal(signal) => { if signal == OverseerSignal::Conclude { return; - }, + } + }, orchestra::FromOrchestra::Communication { msg } => { gum::trace!(target: LOG_TARGET, msg=?msg, "recv message"); diff --git a/pezkuwi/node/subsystem-bench/src/lib/mock/candidate_validation.rs b/pezkuwi/node/subsystem-bench/src/lib/mock/candidate_validation.rs index ea7458fd..855c47b6 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/mock/candidate_validation.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/mock/candidate_validation.rs @@ -50,10 +50,11 @@ impl MockCandidateValidation { loop { let msg = ctx.recv().await.expect("Overseer never fails us"); match msg { - orchestra::FromOrchestra::Signal(signal) => + orchestra::FromOrchestra::Signal(signal) => { if signal == OverseerSignal::Conclude { return; - }, + } + }, orchestra::FromOrchestra::Communication { msg } => match msg { CandidateValidationMessage::ValidateFromExhaustive { response_sender, diff --git a/pezkuwi/node/subsystem-bench/src/lib/mock/chain_api.rs b/pezkuwi/node/subsystem-bench/src/lib/mock/chain_api.rs index 62b25c12..2be39acf 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/mock/chain_api.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/mock/chain_api.rs @@ -65,10 +65,11 @@ impl MockChainApi { let msg = ctx.recv().await.expect("Overseer never fails us"); match msg { - orchestra::FromOrchestra::Signal(signal) => + orchestra::FromOrchestra::Signal(signal) => { if signal == OverseerSignal::Conclude { return; - }, + } + }, orchestra::FromOrchestra::Communication { msg } => { gum::debug!(target: LOG_TARGET, msg=?msg, "recv message"); diff --git a/pezkuwi/node/subsystem-bench/src/lib/mock/network_bridge.rs b/pezkuwi/node/subsystem-bench/src/lib/mock/network_bridge.rs index fa2dd5ae..74733b11 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/mock/network_bridge.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/mock/network_bridge.rs @@ -102,10 +102,11 @@ impl MockNetworkBridgeTx { loop { let subsystem_message = ctx.recv().await.expect("Overseer never fails us"); match subsystem_message { - orchestra::FromOrchestra::Signal(signal) => + orchestra::FromOrchestra::Signal(signal) => { if signal == OverseerSignal::Conclude { return; - }, + } + }, orchestra::FromOrchestra::Communication { msg } => match msg { NetworkBridgeTxMessage::SendRequests(requests, _if_disconnected) => { for request in requests { diff --git a/pezkuwi/node/subsystem-bench/src/lib/mock/prospective_teyrchains.rs b/pezkuwi/node/subsystem-bench/src/lib/mock/prospective_teyrchains.rs index debd5c8b..ec2c0542 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/mock/prospective_teyrchains.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/mock/prospective_teyrchains.rs @@ -46,10 +46,11 @@ impl MockProspectiveTeyrchains { loop { let msg = ctx.recv().await.expect("Overseer never fails us"); match msg { - orchestra::FromOrchestra::Signal(signal) => + orchestra::FromOrchestra::Signal(signal) => { if signal == OverseerSignal::Conclude { return; - }, + } + }, orchestra::FromOrchestra::Communication { msg } => match msg { ProspectiveTeyrchainsMessage::GetMinimumRelayParents(_relay_parent, tx) => { tx.send(vec![]).unwrap(); diff --git a/pezkuwi/node/subsystem-bench/src/lib/mock/runtime_api.rs b/pezkuwi/node/subsystem-bench/src/lib/mock/runtime_api.rs index 1928502f..3235902c 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/mock/runtime_api.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/mock/runtime_api.rs @@ -173,10 +173,11 @@ impl MockRuntimeApi { let msg = ctx.recv().await.expect("Overseer never fails us"); match msg { - orchestra::FromOrchestra::Signal(signal) => + orchestra::FromOrchestra::Signal(signal) => { if signal == OverseerSignal::Conclude { return; - }, + } + }, orchestra::FromOrchestra::Communication { msg } => { gum::debug!(target: LOG_TARGET, msg=?msg, "recv message"); @@ -323,10 +324,11 @@ impl MockRuntimeApi { RuntimeApiMessage::Request( _parent, RuntimeApiRequest::ApprovalVotingParams(_, tx), - ) => + ) => { if let Err(err) = tx.send(Ok(ApprovalVotingParams::default())) { gum::error!(target: LOG_TARGET, ?err, "Voting params weren't received"); - }, + } + }, RuntimeApiMessage::Request(_parent, RuntimeApiRequest::ClaimQueue(tx)) => { tx.send(Ok(self.state.claim_queue.clone())).unwrap(); }, diff --git a/pezkuwi/node/subsystem-bench/src/lib/network.rs b/pezkuwi/node/subsystem-bench/src/lib/network.rs index e70bc829..0b5919ff 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/network.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/network.rs @@ -165,10 +165,12 @@ impl NetworkMessage { /// Returns the size of the encoded message or request pub fn size(&self) -> usize { match &self { - NetworkMessage::MessageFromPeer(_, ValidationProtocols::V3(message)) => - message.encoded_size(), - NetworkMessage::MessageFromNode(_peer_id, ValidationProtocols::V3(message)) => - message.encoded_size(), + NetworkMessage::MessageFromPeer(_, ValidationProtocols::V3(message)) => { + message.encoded_size() + }, + NetworkMessage::MessageFromNode(_peer_id, ValidationProtocols::V3(message)) => { + message.encoded_size() + }, NetworkMessage::RequestFromNode(_peer_id, incoming) => incoming.size(), NetworkMessage::RequestFromPeer(request) => request.payload.encoded_size(), } @@ -177,8 +179,8 @@ impl NetworkMessage { /// Returns the destination peer from the message or `None` if it originates from a peer. pub fn peer(&self) -> Option<&AuthorityDiscoveryId> { match &self { - NetworkMessage::MessageFromNode(peer_id, _) | - NetworkMessage::RequestFromNode(peer_id, _) => Some(peer_id), + NetworkMessage::MessageFromNode(peer_id, _) + | NetworkMessage::RequestFromNode(peer_id, _) => Some(peer_id), _ => None, } } @@ -345,8 +347,9 @@ impl NetworkInterface { task_tx_limiter.lock().await.reap(size).await; match peer_message { - NetworkMessage::MessageFromNode(peer, message) => - tx_network.send_message_to_peer(&peer, message), + NetworkMessage::MessageFromNode(peer, message) => { + tx_network.send_message_to_peer(&peer, message) + }, NetworkMessage::RequestFromNode(peer, request) => { // Send request through a proxy so we can account and limit bandwidth // usage for the node. @@ -1057,8 +1060,9 @@ impl RequestExt for Requests { fn into_response_sender(self) -> ResponseSender { match self { Requests::ChunkFetching(outgoing_request) => outgoing_request.pending_response, - Requests::AvailableDataFetchingV1(outgoing_request) => - outgoing_request.pending_response, + Requests::AvailableDataFetchingV1(outgoing_request) => { + outgoing_request.pending_response + }, Requests::DisputeSendingV1(outgoing_request) => outgoing_request.pending_response, _ => unimplemented!("unsupported request type"), } @@ -1067,14 +1071,18 @@ impl RequestExt for Requests { /// Swaps the `ResponseSender` and returns the previous value. fn swap_response_sender(&mut self, new_sender: ResponseSender) -> ResponseSender { match self { - Requests::ChunkFetching(outgoing_request) => - std::mem::replace(&mut outgoing_request.pending_response, new_sender), - Requests::AvailableDataFetchingV1(outgoing_request) => - std::mem::replace(&mut outgoing_request.pending_response, new_sender), - Requests::AttestedCandidateV2(outgoing_request) => - std::mem::replace(&mut outgoing_request.pending_response, new_sender), - Requests::DisputeSendingV1(outgoing_request) => - std::mem::replace(&mut outgoing_request.pending_response, new_sender), + Requests::ChunkFetching(outgoing_request) => { + std::mem::replace(&mut outgoing_request.pending_response, new_sender) + }, + Requests::AvailableDataFetchingV1(outgoing_request) => { + std::mem::replace(&mut outgoing_request.pending_response, new_sender) + }, + Requests::AttestedCandidateV2(outgoing_request) => { + std::mem::replace(&mut outgoing_request.pending_response, new_sender) + }, + Requests::DisputeSendingV1(outgoing_request) => { + std::mem::replace(&mut outgoing_request.pending_response, new_sender) + }, _ => unimplemented!("unsupported request type"), } } @@ -1083,10 +1091,12 @@ impl RequestExt for Requests { fn size(&self) -> usize { match self { Requests::ChunkFetching(outgoing_request) => outgoing_request.payload.encoded_size(), - Requests::AvailableDataFetchingV1(outgoing_request) => - outgoing_request.payload.encoded_size(), - Requests::AttestedCandidateV2(outgoing_request) => - outgoing_request.payload.encoded_size(), + Requests::AvailableDataFetchingV1(outgoing_request) => { + outgoing_request.payload.encoded_size() + }, + Requests::AttestedCandidateV2(outgoing_request) => { + outgoing_request.payload.encoded_size() + }, Requests::DisputeSendingV1(outgoing_request) => outgoing_request.payload.encoded_size(), _ => unimplemented!("received an unexpected request"), } @@ -1122,8 +1132,8 @@ mod tests { // Allow up to `budget/max_refill` error tolerance let lower_bound = budget as u128 * ((end - start).as_millis() / 1000u128); - let upper_bound = budget as u128 * - ((end - start).as_millis() / 1000u128 + rate_limiter.max_refill as u128); + let upper_bound = budget as u128 + * ((end - start).as_millis() / 1000u128 + rate_limiter.max_refill as u128); assert!(total_sent as u128 >= lower_bound); assert!(total_sent as u128 <= upper_bound); } diff --git a/pezkuwi/node/subsystem-bench/src/lib/statement/test_state.rs b/pezkuwi/node/subsystem-bench/src/lib/statement/test_state.rs index 6c9f2e74..0a71d2a2 100644 --- a/pezkuwi/node/subsystem-bench/src/lib/statement/test_state.rs +++ b/pezkuwi/node/subsystem-bench/src/lib/statement/test_state.rs @@ -397,10 +397,12 @@ impl HandleNetworkMessage for TestState { let position_in_group = backing_group.iter().position(|v| *v == validator_index).unwrap(); match statement.unchecked_payload() { - CompactStatement::Seconded(_) => - seconded_in_group.set(position_in_group, true), - CompactStatement::Valid(_) => - validated_in_group.set(position_in_group, true), + CompactStatement::Seconded(_) => { + seconded_in_group.set(position_in_group, true) + }, + CompactStatement::Valid(_) => { + validated_in_group.set(position_in_group, true) + }, } } } diff --git a/pezkuwi/node/subsystem-test-helpers/src/lib.rs b/pezkuwi/node/subsystem-test-helpers/src/lib.rs index 7654f0d0..4881bb78 100644 --- a/pezkuwi/node/subsystem-test-helpers/src/lib.rs +++ b/pezkuwi/node/subsystem-test-helpers/src/lib.rs @@ -80,10 +80,11 @@ impl Sink for SingleItemSink { let mut state = self.0.lock(); match *state { - SinkState::Empty { ref mut read_waker } => + SinkState::Empty { ref mut read_waker } => { if let Some(waker) = read_waker.take() { waker.wake(); - }, + } + }, _ => panic!("start_send called outside of empty sink state ensured by poll_ready"), } diff --git a/pezkuwi/node/subsystem-types/src/lib.rs b/pezkuwi/node/subsystem-types/src/lib.rs index ca3e7e1b..30994b52 100644 --- a/pezkuwi/node/subsystem-types/src/lib.rs +++ b/pezkuwi/node/subsystem-types/src/lib.rs @@ -92,9 +92,9 @@ impl PartialEq for ActiveLeavesUpdate { /// /// Instead, it means equality when `activated` and `deactivated` are considered as sets. fn eq(&self, other: &Self) -> bool { - self.activated.as_ref().map(|a| a.hash) == other.activated.as_ref().map(|a| a.hash) && - self.deactivated.len() == other.deactivated.len() && - self.deactivated.iter().all(|a| other.deactivated.contains(a)) + self.activated.as_ref().map(|a| a.hash) == other.activated.as_ref().map(|a| a.hash) + && self.deactivated.len() == other.deactivated.len() + && self.deactivated.iter().all(|a| other.deactivated.contains(a)) } } diff --git a/pezkuwi/node/subsystem-types/src/messages.rs b/pezkuwi/node/subsystem-types/src/messages.rs index 0b8f88b5..b8d302a7 100644 --- a/pezkuwi/node/subsystem-types/src/messages.rs +++ b/pezkuwi/node/subsystem-types/src/messages.rs @@ -1053,10 +1053,12 @@ impl TryFrom for ApprovalVotingMessage { fn try_from(msg: ApprovalVotingParallelMessage) -> Result { match msg { - ApprovalVotingParallelMessage::ApprovedAncestor(hash, number, tx) => - Ok(ApprovalVotingMessage::ApprovedAncestor(hash, number, tx)), - ApprovalVotingParallelMessage::GetApprovalSignaturesForCandidate(candidate, tx) => - Ok(ApprovalVotingMessage::GetApprovalSignaturesForCandidate(candidate, tx)), + ApprovalVotingParallelMessage::ApprovedAncestor(hash, number, tx) => { + Ok(ApprovalVotingMessage::ApprovedAncestor(hash, number, tx)) + }, + ApprovalVotingParallelMessage::GetApprovalSignaturesForCandidate(candidate, tx) => { + Ok(ApprovalVotingMessage::GetApprovalSignaturesForCandidate(candidate, tx)) + }, _ => Err(()), } } @@ -1067,18 +1069,24 @@ impl TryFrom for ApprovalDistributionMessage { fn try_from(msg: ApprovalVotingParallelMessage) -> Result { match msg { - ApprovalVotingParallelMessage::NewBlocks(blocks) => - Ok(ApprovalDistributionMessage::NewBlocks(blocks)), - ApprovalVotingParallelMessage::DistributeAssignment(assignment, claimed_cores) => - Ok(ApprovalDistributionMessage::DistributeAssignment(assignment, claimed_cores)), - ApprovalVotingParallelMessage::DistributeApproval(vote) => - Ok(ApprovalDistributionMessage::DistributeApproval(vote)), - ApprovalVotingParallelMessage::NetworkBridgeUpdate(msg) => - Ok(ApprovalDistributionMessage::NetworkBridgeUpdate(msg)), - ApprovalVotingParallelMessage::GetApprovalSignatures(candidate_indicies, tx) => - Ok(ApprovalDistributionMessage::GetApprovalSignatures(candidate_indicies, tx)), - ApprovalVotingParallelMessage::ApprovalCheckingLagUpdate(lag) => - Ok(ApprovalDistributionMessage::ApprovalCheckingLagUpdate(lag)), + ApprovalVotingParallelMessage::NewBlocks(blocks) => { + Ok(ApprovalDistributionMessage::NewBlocks(blocks)) + }, + ApprovalVotingParallelMessage::DistributeAssignment(assignment, claimed_cores) => { + Ok(ApprovalDistributionMessage::DistributeAssignment(assignment, claimed_cores)) + }, + ApprovalVotingParallelMessage::DistributeApproval(vote) => { + Ok(ApprovalDistributionMessage::DistributeApproval(vote)) + }, + ApprovalVotingParallelMessage::NetworkBridgeUpdate(msg) => { + Ok(ApprovalDistributionMessage::NetworkBridgeUpdate(msg)) + }, + ApprovalVotingParallelMessage::GetApprovalSignatures(candidate_indicies, tx) => { + Ok(ApprovalDistributionMessage::GetApprovalSignatures(candidate_indicies, tx)) + }, + ApprovalVotingParallelMessage::ApprovalCheckingLagUpdate(lag) => { + Ok(ApprovalDistributionMessage::ApprovalCheckingLagUpdate(lag)) + }, _ => Err(()), } } @@ -1087,18 +1095,24 @@ impl TryFrom for ApprovalDistributionMessage { impl From for ApprovalVotingParallelMessage { fn from(msg: ApprovalDistributionMessage) -> Self { match msg { - ApprovalDistributionMessage::NewBlocks(blocks) => - ApprovalVotingParallelMessage::NewBlocks(blocks), - ApprovalDistributionMessage::DistributeAssignment(cert, bitfield) => - ApprovalVotingParallelMessage::DistributeAssignment(cert, bitfield), - ApprovalDistributionMessage::DistributeApproval(vote) => - ApprovalVotingParallelMessage::DistributeApproval(vote), - ApprovalDistributionMessage::NetworkBridgeUpdate(msg) => - ApprovalVotingParallelMessage::NetworkBridgeUpdate(msg), - ApprovalDistributionMessage::GetApprovalSignatures(candidate_indicies, tx) => - ApprovalVotingParallelMessage::GetApprovalSignatures(candidate_indicies, tx), - ApprovalDistributionMessage::ApprovalCheckingLagUpdate(lag) => - ApprovalVotingParallelMessage::ApprovalCheckingLagUpdate(lag), + ApprovalDistributionMessage::NewBlocks(blocks) => { + ApprovalVotingParallelMessage::NewBlocks(blocks) + }, + ApprovalDistributionMessage::DistributeAssignment(cert, bitfield) => { + ApprovalVotingParallelMessage::DistributeAssignment(cert, bitfield) + }, + ApprovalDistributionMessage::DistributeApproval(vote) => { + ApprovalVotingParallelMessage::DistributeApproval(vote) + }, + ApprovalDistributionMessage::NetworkBridgeUpdate(msg) => { + ApprovalVotingParallelMessage::NetworkBridgeUpdate(msg) + }, + ApprovalDistributionMessage::GetApprovalSignatures(candidate_indicies, tx) => { + ApprovalVotingParallelMessage::GetApprovalSignatures(candidate_indicies, tx) + }, + ApprovalDistributionMessage::ApprovalCheckingLagUpdate(lag) => { + ApprovalVotingParallelMessage::ApprovalCheckingLagUpdate(lag) + }, } } } @@ -1296,28 +1310,33 @@ impl HypotheticalCandidate { /// Get parent head data hash of the hypothetical candidate. pub fn parent_head_data_hash(&self) -> Hash { match *self { - HypotheticalCandidate::Complete { ref persisted_validation_data, .. } => - persisted_validation_data.parent_head.hash(), - HypotheticalCandidate::Incomplete { parent_head_data_hash, .. } => - parent_head_data_hash, + HypotheticalCandidate::Complete { ref persisted_validation_data, .. } => { + persisted_validation_data.parent_head.hash() + }, + HypotheticalCandidate::Incomplete { parent_head_data_hash, .. } => { + parent_head_data_hash + }, } } /// Get candidate's relay parent. pub fn relay_parent(&self) -> Hash { match *self { - HypotheticalCandidate::Complete { ref receipt, .. } => - receipt.descriptor.relay_parent(), - HypotheticalCandidate::Incomplete { candidate_relay_parent, .. } => - candidate_relay_parent, + HypotheticalCandidate::Complete { ref receipt, .. } => { + receipt.descriptor.relay_parent() + }, + HypotheticalCandidate::Incomplete { candidate_relay_parent, .. } => { + candidate_relay_parent + }, } } /// Get the output head data hash, if the candidate is complete. pub fn output_head_data_hash(&self) -> Option { match *self { - HypotheticalCandidate::Complete { ref receipt, .. } => - Some(receipt.descriptor.para_head()), + HypotheticalCandidate::Complete { ref receipt, .. } => { + Some(receipt.descriptor.para_head()) + }, HypotheticalCandidate::Incomplete { .. } => None, } } @@ -1333,8 +1352,9 @@ impl HypotheticalCandidate { /// Get the persisted validation data, if the candidate is complete. pub fn persisted_validation_data(&self) -> Option<&PersistedValidationData> { match *self { - HypotheticalCandidate::Complete { ref persisted_validation_data, .. } => - Some(persisted_validation_data), + HypotheticalCandidate::Complete { ref persisted_validation_data, .. } => { + Some(persisted_validation_data) + }, HypotheticalCandidate::Incomplete { .. } => None, } } @@ -1342,8 +1362,9 @@ impl HypotheticalCandidate { /// Get the validation code hash, if the candidate is complete. pub fn validation_code_hash(&self) -> Option { match *self { - HypotheticalCandidate::Complete { ref receipt, .. } => - Some(receipt.descriptor.validation_code_hash()), + HypotheticalCandidate::Complete { ref receipt, .. } => { + Some(receipt.descriptor.validation_code_hash()) + }, HypotheticalCandidate::Incomplete { .. } => None, } } diff --git a/pezkuwi/node/subsystem-types/src/messages/network_bridge_event.rs b/pezkuwi/node/subsystem-types/src/messages/network_bridge_event.rs index 6fb3e2ad..bb132511 100644 --- a/pezkuwi/node/subsystem-types/src/messages/network_bridge_event.rs +++ b/pezkuwi/node/subsystem-types/src/messages/network_bridge_event.rs @@ -89,24 +89,30 @@ impl NetworkBridgeEvent { T: TryFrom<&'a M, Error = WrongVariant>, { Ok(match *self { - NetworkBridgeEvent::PeerMessage(ref peer, ref msg) => - NetworkBridgeEvent::PeerMessage(*peer, T::try_from(msg)?), + NetworkBridgeEvent::PeerMessage(ref peer, ref msg) => { + NetworkBridgeEvent::PeerMessage(*peer, T::try_from(msg)?) + }, NetworkBridgeEvent::PeerConnected( ref peer, ref role, ref version, ref authority_id, ) => NetworkBridgeEvent::PeerConnected(*peer, *role, *version, authority_id.clone()), - NetworkBridgeEvent::PeerDisconnected(ref peer) => - NetworkBridgeEvent::PeerDisconnected(*peer), - NetworkBridgeEvent::NewGossipTopology(ref topology) => - NetworkBridgeEvent::NewGossipTopology(topology.clone()), - NetworkBridgeEvent::PeerViewChange(ref peer, ref view) => - NetworkBridgeEvent::PeerViewChange(*peer, view.clone()), - NetworkBridgeEvent::OurViewChange(ref view) => - NetworkBridgeEvent::OurViewChange(view.clone()), - NetworkBridgeEvent::UpdatedAuthorityIds(ref peer, ref authority_ids) => - NetworkBridgeEvent::UpdatedAuthorityIds(*peer, authority_ids.clone()), + NetworkBridgeEvent::PeerDisconnected(ref peer) => { + NetworkBridgeEvent::PeerDisconnected(*peer) + }, + NetworkBridgeEvent::NewGossipTopology(ref topology) => { + NetworkBridgeEvent::NewGossipTopology(topology.clone()) + }, + NetworkBridgeEvent::PeerViewChange(ref peer, ref view) => { + NetworkBridgeEvent::PeerViewChange(*peer, view.clone()) + }, + NetworkBridgeEvent::OurViewChange(ref view) => { + NetworkBridgeEvent::OurViewChange(view.clone()) + }, + NetworkBridgeEvent::UpdatedAuthorityIds(ref peer, ref authority_ids) => { + NetworkBridgeEvent::UpdatedAuthorityIds(*peer, authority_ids.clone()) + }, }) } } diff --git a/pezkuwi/node/subsystem-util/src/backing_implicit_view.rs b/pezkuwi/node/subsystem-util/src/backing_implicit_view.rs index 08ce48e3..aa6f32e5 100644 --- a/pezkuwi/node/subsystem-util/src/backing_implicit_view.rs +++ b/pezkuwi/node/subsystem-util/src/backing_implicit_view.rs @@ -413,21 +413,24 @@ impl View { match rx.await { Ok(Ok(Some(header))) => header, - Ok(Ok(None)) => + Ok(Ok(None)) => { return Err(FetchError::BlockHeaderUnavailable( leaf_hash, BlockHeaderUnavailableReason::Unknown, - )), - Ok(Err(e)) => + )) + }, + Ok(Err(e)) => { return Err(FetchError::BlockHeaderUnavailable( leaf_hash, BlockHeaderUnavailableReason::Internal(e), - )), - Err(_) => + )) + }, + Err(_) => { return Err(FetchError::BlockHeaderUnavailable( leaf_hash, BlockHeaderUnavailableReason::SubsystemUnavailable, - )), + )) + }, } }; @@ -467,21 +470,24 @@ impl View { let header = match rx.await { Ok(Ok(Some(header))) => header, - Ok(Ok(None)) => + Ok(Ok(None)) => { return Err(FetchError::BlockHeaderUnavailable( next_ancestor_hash, BlockHeaderUnavailableReason::Unknown, - )), - Ok(Err(e)) => + )) + }, + Ok(Err(e)) => { return Err(FetchError::BlockHeaderUnavailable( next_ancestor_hash, BlockHeaderUnavailableReason::Internal(e), - )), - Err(_) => + )) + }, + Err(_) => { return Err(FetchError::BlockHeaderUnavailable( next_ancestor_hash, BlockHeaderUnavailableReason::SubsystemUnavailable, - )), + )) + }, }; self.block_info_storage.insert( diff --git a/pezkuwi/node/subsystem-util/src/database.rs b/pezkuwi/node/subsystem-util/src/database.rs index b77f30ab..e095cdfc 100644 --- a/pezkuwi/node/subsystem-util/src/database.rs +++ b/pezkuwi/node/subsystem-util/src/database.rs @@ -217,8 +217,9 @@ pub mod paritydb_impl { } return match ops.next() { None => None, - Some(DBOp::Insert { col, key, value }) => - Some((col as u8, key.to_vec(), Some(value))), + Some(DBOp::Insert { col, key, value }) => { + Some((col as u8, key.to_vec(), Some(value))) + }, Some(DBOp::Delete { col, key }) => Some((col as u8, key.to_vec(), None)), Some(DBOp::DeletePrefix { col, prefix }) => { let col = col as u8; diff --git a/pezkuwi/node/subsystem-util/src/inclusion_emulator/mod.rs b/pezkuwi/node/subsystem-util/src/inclusion_emulator/mod.rs index aba30bb4..4c08d185 100644 --- a/pezkuwi/node/subsystem-util/src/inclusion_emulator/mod.rs +++ b/pezkuwi/node/subsystem-util/src/inclusion_emulator/mod.rs @@ -724,8 +724,9 @@ pub fn validate_commitments( if commitments.new_validation_code.is_some() { match constraints.upgrade_restriction { None => {}, - Some(UpgradeRestriction::Present) => - return Err(FragmentValidityError::CodeUpgradeRestricted), + Some(UpgradeRestriction::Present) => { + return Err(FragmentValidityError::CodeUpgradeRestricted) + }, } } diff --git a/pezkuwi/node/test/service/src/lib.rs b/pezkuwi/node/test/service/src/lib.rs index 361a848d..07a7d667 100644 --- a/pezkuwi/node/test/service/src/lib.rs +++ b/pezkuwi/node/test/service/src/lib.rs @@ -103,10 +103,12 @@ pub fn new_full( }; match config.network.network_backend { - pezsc_network::config::NetworkBackendType::Libp2p => - pezkuwi_service::new_full::<_, pezsc_network::NetworkWorker<_, _>>(config, params), - pezsc_network::config::NetworkBackendType::Litep2p => - pezkuwi_service::new_full::<_, pezsc_network::Litep2pNetworkBackend>(config, params), + pezsc_network::config::NetworkBackendType::Libp2p => { + pezkuwi_service::new_full::<_, pezsc_network::NetworkWorker<_, _>>(config, params) + }, + pezsc_network::config::NetworkBackendType::Litep2p => { + pezkuwi_service::new_full::<_, pezsc_network::Litep2pNetworkBackend>(config, params) + }, } } diff --git a/pezkuwi/node/zombienet-backchannel/src/lib.rs b/pezkuwi/node/zombienet-backchannel/src/lib.rs index 94908971..c6ac1201 100644 --- a/pezkuwi/node/zombienet-backchannel/src/lib.rs +++ b/pezkuwi/node/zombienet-backchannel/src/lib.rs @@ -112,11 +112,12 @@ impl ZombienetBackchannel { tokio::spawn(async move { while let Some(Ok(Message::Text(text))) = read.next().await { match serde_json::from_str::(&text) { - Ok(backchannel_item) => + Ok(backchannel_item) => { if tx1.send(backchannel_item).is_err() { gum::error!(target: ZOMBIENET, "Error sending through the channel"); return; - }, + } + }, Err(_) => { gum::error!(target: ZOMBIENET, "Invalid payload received"); }, diff --git a/pezkuwi/pezpallets/validator-pool/src/tests.rs b/pezkuwi/pezpallets/validator-pool/src/tests.rs index 6f69bf7a..9413fd73 100644 --- a/pezkuwi/pezpallets/validator-pool/src/tests.rs +++ b/pezkuwi/pezpallets/validator-pool/src/tests.rs @@ -637,7 +637,9 @@ fn shadow_comparison_recorded() { let comparison = ValidatorPool::shadow_comparison(); assert!(comparison.is_some()); let comp = comparison.unwrap(); - assert!(comp.overlap_count > 0 || !comp.tnpos_only.is_empty() || !comp.npos_only.is_empty()); + assert!( + comp.overlap_count > 0 || !comp.tnpos_only.is_empty() || !comp.npos_only.is_empty() + ); }); } diff --git a/pezkuwi/pezpallets/validator-pool/src/types.rs b/pezkuwi/pezpallets/validator-pool/src/types.rs index d603b0d6..76999a57 100644 --- a/pezkuwi/pezpallets/validator-pool/src/types.rs +++ b/pezkuwi/pezpallets/validator-pool/src/types.rs @@ -102,9 +102,9 @@ where /// Get total validator count pub fn total_count(&self) -> u32 { - self.stake_validators.len() as u32 + - self.parliamentary_validators.len() as u32 + - self.merit_validators.len() as u32 + self.stake_validators.len() as u32 + + self.parliamentary_validators.len() as u32 + + self.merit_validators.len() as u32 } } diff --git a/pezkuwi/primitives/src/v9/executor_params.rs b/pezkuwi/primitives/src/v9/executor_params.rs index 86efbc04..9308bb83 100644 --- a/pezkuwi/primitives/src/v9/executor_params.rs +++ b/pezkuwi/primitives/src/v9/executor_params.rs @@ -447,8 +447,9 @@ fn ensure_prep_hash_changes() { PrecheckingMaxMemory(_) => continue, PvfPrepTimeout(_, _) => continue, PvfExecTimeout(_, _) => continue, - WasmExtBulkMemory => - (ExecutorParams::default(), ExecutorParams::from(&[WasmExtBulkMemory][..])), + WasmExtBulkMemory => { + (ExecutorParams::default(), ExecutorParams::from(&[WasmExtBulkMemory][..])) + }, }; assert_ne!(ep1.prep_hash(), ep2.prep_hash()); diff --git a/pezkuwi/primitives/src/v9/mod.rs b/pezkuwi/primitives/src/v9/mod.rs index aef68e93..289833e1 100644 --- a/pezkuwi/primitives/src/v9/mod.rs +++ b/pezkuwi/primitives/src/v9/mod.rs @@ -820,15 +820,15 @@ impl GroupRotationInfo { /// is 10 and the rotation frequency is 5, this should return 15. pub fn next_rotation_at(&self) -> N { let cycle_once = self.now + self.group_rotation_frequency; - cycle_once - - (cycle_once.saturating_sub(self.session_start_block) % self.group_rotation_frequency) + cycle_once + - (cycle_once.saturating_sub(self.session_start_block) % self.group_rotation_frequency) } /// Returns the block number of the last rotation before or including the current block. If the /// current block is 10 and the rotation frequency is 5, this should return 10. pub fn last_rotation_at(&self) -> N { - self.now - - (self.now.saturating_sub(self.session_start_block) % self.group_rotation_frequency) + self.now + - (self.now.saturating_sub(self.session_start_block) % self.group_rotation_frequency) } } @@ -1067,8 +1067,9 @@ impl ConsensusLog { digest_item: &pezsp_runtime::DigestItem, ) -> Result, codec::Error> { match digest_item { - pezsp_runtime::DigestItem::Consensus(id, encoded) if id == &PEZKUWI_ENGINE_ID => - Ok(Some(Self::decode(&mut &encoded[..])?)), + pezsp_runtime::DigestItem::Consensus(id, encoded) if id == &PEZKUWI_ENGINE_ID => { + Ok(Some(Self::decode(&mut &encoded[..])?)) + }, _ => Ok(None), } } @@ -1104,33 +1105,38 @@ impl DisputeStatement { session: SessionIndex, ) -> Result, ()> { match self { - DisputeStatement::Valid(ValidDisputeStatementKind::Explicit) => + DisputeStatement::Valid(ValidDisputeStatementKind::Explicit) => { Ok(ExplicitDisputeStatement { valid: true, candidate_hash, session } - .signing_payload()), + .signing_payload()) + }, DisputeStatement::Valid(ValidDisputeStatementKind::BackingSeconded( inclusion_parent, )) => Ok(CompactStatement::Seconded(candidate_hash).signing_payload(&SigningContext { session_index: session, parent_hash: *inclusion_parent, })), - DisputeStatement::Valid(ValidDisputeStatementKind::BackingValid(inclusion_parent)) => + DisputeStatement::Valid(ValidDisputeStatementKind::BackingValid(inclusion_parent)) => { Ok(CompactStatement::Valid(candidate_hash).signing_payload(&SigningContext { session_index: session, parent_hash: *inclusion_parent, - })), - DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) => - Ok(ApprovalVote(candidate_hash).signing_payload(session)), + })) + }, + DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) => { + Ok(ApprovalVote(candidate_hash).signing_payload(session)) + }, DisputeStatement::Valid( ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(candidate_hashes), - ) => + ) => { if candidate_hashes.contains(&candidate_hash) { Ok(ApprovalVoteMultipleCandidates(candidate_hashes).signing_payload(session)) } else { Err(()) - }, - DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit) => + } + }, + DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit) => { Ok(ExplicitDisputeStatement { valid: false, candidate_hash, session } - .signing_payload()), + .signing_payload()) + }, } } @@ -1203,11 +1209,11 @@ impl ValidDisputeStatementKind { /// Whether the statement is from the backing phase. pub fn is_backing(&self) -> bool { match self { - ValidDisputeStatementKind::BackingSeconded(_) | - ValidDisputeStatementKind::BackingValid(_) => true, - ValidDisputeStatementKind::Explicit | - ValidDisputeStatementKind::ApprovalChecking | - ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(_) => false, + ValidDisputeStatementKind::BackingSeconded(_) + | ValidDisputeStatementKind::BackingValid(_) => true, + ValidDisputeStatementKind::Explicit + | ValidDisputeStatementKind::ApprovalChecking + | ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(_) => false, } } } @@ -1349,10 +1355,12 @@ impl ValidityAttestation { signing_context: &SigningContext, ) -> Vec { match *self { - ValidityAttestation::Implicit(_) => - (CompactStatement::Seconded(candidate_hash), signing_context).encode(), - ValidityAttestation::Explicit(_) => - (CompactStatement::Valid(candidate_hash), signing_context).encode(), + ValidityAttestation::Implicit(_) => { + (CompactStatement::Seconded(candidate_hash), signing_context).encode() + }, + ValidityAttestation::Explicit(_) => { + (CompactStatement::Valid(candidate_hash), signing_context).encode() + }, } } } @@ -2426,8 +2434,9 @@ impl CommittedCandidateReceiptV2 { } }, CandidateDescriptorVersion::V2 => {}, - CandidateDescriptorVersion::Unknown => - return Err(CommittedCandidateReceiptError::UnknownVersion(self.descriptor.version)), + CandidateDescriptorVersion::Unknown => { + return Err(CommittedCandidateReceiptError::UnknownVersion(self.descriptor.version)) + }, } // Check the core index diff --git a/pezkuwi/runtime/common/src/assigned_slots/mod.rs b/pezkuwi/runtime/common/src/assigned_slots/mod.rs index 0e442fd0..c6708276 100644 --- a/pezkuwi/runtime/common/src/assigned_slots/mod.rs +++ b/pezkuwi/runtime/common/src/assigned_slots/mod.rs @@ -363,8 +363,8 @@ pub mod pezpallet { lease_count: 0, }; - if lease_period_start == SlotLeasePeriodStart::Current && - ActiveTemporarySlotCount::::get() < T::MaxTemporarySlotPerLeasePeriod::get() + if lease_period_start == SlotLeasePeriodStart::Current + && ActiveTemporarySlotCount::::get() < T::MaxTemporarySlotPerLeasePeriod::get() { // Try to allocate slot directly match Self::configure_slot_lease( @@ -520,8 +520,8 @@ impl Pezpallet { }); let mut newly_created_lease = 0u32; - if active_temp_slots < T::MaxTemporarySlotPerLeasePeriod::get() && - !pending_temp_slots.is_empty() + if active_temp_slots < T::MaxTemporarySlotPerLeasePeriod::get() + && !pending_temp_slots.is_empty() { // Sort by lease_count, favoring slots that had no or less turns first // (then by last_lease index, and then Para ID) @@ -625,8 +625,8 @@ impl Pezpallet { err ); } - ::WeightInfo::force_lease() * - (T::MaxTemporarySlotPerLeasePeriod::get() as u64) + ::WeightInfo::force_lease() + * (T::MaxTemporarySlotPerLeasePeriod::get() as u64) } } diff --git a/pezkuwi/runtime/common/src/auctions/mod.rs b/pezkuwi/runtime/common/src/auctions/mod.rs index 0ff77dbb..ea863ea9 100644 --- a/pezkuwi/runtime/common/src/auctions/mod.rs +++ b/pezkuwi/runtime/common/src/auctions/mod.rs @@ -494,8 +494,8 @@ impl Pezpallet { let mut outgoing_winner = Some((bidder.clone(), para, amount)); swap(&mut current_winning[range_index], &mut outgoing_winner); if let Some((who, para, _amount)) = outgoing_winner { - if auction_status.is_starting() && - current_winning + if auction_status.is_starting() + && current_winning .iter() .filter_map(Option::as_ref) .all(|&(ref other, other_para, _)| other != &who || other_para != para) @@ -545,8 +545,8 @@ impl Pezpallet { &mut raw_offset.as_ref(), ) .expect("secure hashes should always be bigger than the block number; qed"); - let offset = (raw_offset_block_number % ending_period) / - T::SampleLength::get().max(One::one()); + let offset = (raw_offset_block_number % ending_period) + / T::SampleLength::get().max(One::one()); let auction_counter = AuctionCounter::::get(); Self::deposit_event(Event::::WinningOffset { @@ -594,9 +594,9 @@ impl Pezpallet { let period_count = LeasePeriodOf::::from(range.len() as u32); match T::Leaser::lease_out(para, &leaser, amount, period_begin, period_count) { - Err(LeaseError::ReserveFailed) | - Err(LeaseError::AlreadyEnded) | - Err(LeaseError::NoLeasePeriod) => { + Err(LeaseError::ReserveFailed) + | Err(LeaseError::AlreadyEnded) + | Err(LeaseError::NoLeasePeriod) => { // Should never happen since we just unreserved this amount (and our offset is // from the present period). But if it does, there's not much we can do. }, diff --git a/pezkuwi/runtime/common/src/claims/mod.rs b/pezkuwi/runtime/common/src/claims/mod.rs index 7531c411..ee61ab2a 100644 --- a/pezkuwi/runtime/common/src/claims/mod.rs +++ b/pezkuwi/runtime/common/src/claims/mod.rs @@ -107,14 +107,16 @@ impl StatementKind { /// Convert this to the (English) statement it represents. fn to_text(self) -> &'static [u8] { match self { - StatementKind::Regular => + StatementKind::Regular => { &b"I hereby agree to the terms of the statement whose SHA-256 multihash is \ Qmc1XYqT6S39WNp2UeiRUrZichUWUPpGEThDE6dAb3f6Ny. (This may be found at the URL: \ - https://statement.polkadot.network/regular.html)"[..], - StatementKind::Saft => + https://statement.polkadot.network/regular.html)"[..] + }, + StatementKind::Saft => { &b"I hereby agree to the terms of the statement whose SHA-256 multihash is \ QmXEkMahfhHJPzT3RjkXiZVFi77ZeVeuxtAjhojGRNYckz. (This may be found at the URL: \ - https://statement.polkadot.network/saft.html)"[..], + https://statement.polkadot.network/saft.html)"[..] + }, } } } diff --git a/pezkuwi/runtime/common/src/impls.rs b/pezkuwi/runtime/common/src/impls.rs index 464af851..f6f6a1d9 100644 --- a/pezkuwi/runtime/common/src/impls.rs +++ b/pezkuwi/runtime/common/src/impls.rs @@ -178,13 +178,15 @@ impl TryConvert asset_id: v4_asset_id.try_into().map_err(|_| asset.clone())?, }) }, - VersionedLocatableAsset::V4 { ref location, ref asset_id } => + VersionedLocatableAsset::V4 { ref location, ref asset_id } => { Ok(xcm_builder::LocatableAssetId { location: location.clone().try_into().map_err(|_| asset.clone())?, asset_id: asset_id.clone().try_into().map_err(|_| asset.clone())?, - }), - VersionedLocatableAsset::V5 { location, asset_id } => - Ok(xcm_builder::LocatableAssetId { location, asset_id }), + }) + }, + VersionedLocatableAsset::V5 { location, asset_id } => { + Ok(xcm_builder::LocatableAssetId { location, asset_id }) + }, } } } diff --git a/pezkuwi/runtime/common/src/integration_tests.rs b/pezkuwi/runtime/common/src/integration_tests.rs index dd499583..a9f7aac1 100644 --- a/pezkuwi/runtime/common/src/integration_tests.rs +++ b/pezkuwi/runtime/common/src/integration_tests.rs @@ -936,8 +936,8 @@ fn basic_swap_works() { // ----------------------------------------- para deposit --- crowdloan let crowdloan_deposit = 100; let para_id_deposit = ::ParaDeposit::get(); - let code_deposit = configuration::ActiveConfig::::get().max_code_size * - ::DataDepositPerByte::get(); + let code_deposit = configuration::ActiveConfig::::get().max_code_size + * ::DataDepositPerByte::get(); // Para 2000 has a genesis head size of 10. assert_eq!( diff --git a/pezkuwi/runtime/common/src/mock.rs b/pezkuwi/runtime/common/src/mock.rs index ccfb0019..c9bdf2c3 100644 --- a/pezkuwi/runtime/common/src/mock.rs +++ b/pezkuwi/runtime/common/src/mock.rs @@ -163,8 +163,9 @@ impl Registrar for TestRegistrar { PARATHREADS.with(|x| { let mut parathreads = x.borrow_mut(); match parathreads.binary_search(&id) { - Ok(_) => - Err(DispatchError::Other("already parathread, so cannot `make_parathread`")), + Ok(_) => { + Err(DispatchError::Other("already parathread, so cannot `make_parathread`")) + }, Err(i) => { parathreads.insert(i, id); Ok(()) diff --git a/pezkuwi/runtime/common/src/paras_registrar/mod.rs b/pezkuwi/runtime/common/src/paras_registrar/mod.rs index bbba69bc..2a68d7a0 100644 --- a/pezkuwi/runtime/common/src/paras_registrar/mod.rs +++ b/pezkuwi/runtime/common/src/paras_registrar/mod.rs @@ -341,16 +341,16 @@ pub mod pezpallet { paras::Pezpallet::::lifecycle(other).ok_or(Error::::NotRegistered)?; // identify which is a lease holding teyrchain and which is a parathread (on-demand // teyrchain) - if id_lifecycle == ParaLifecycle::Teyrchain && - other_lifecycle == ParaLifecycle::Parathread + if id_lifecycle == ParaLifecycle::Teyrchain + && other_lifecycle == ParaLifecycle::Parathread { Self::do_thread_and_chain_swap(id, other); - } else if id_lifecycle == ParaLifecycle::Parathread && - other_lifecycle == ParaLifecycle::Teyrchain + } else if id_lifecycle == ParaLifecycle::Parathread + && other_lifecycle == ParaLifecycle::Teyrchain { Self::do_thread_and_chain_swap(other, id); - } else if id_lifecycle == ParaLifecycle::Teyrchain && - other_lifecycle == ParaLifecycle::Teyrchain + } else if id_lifecycle == ParaLifecycle::Teyrchain + && other_lifecycle == ParaLifecycle::Teyrchain { // If both chains are currently teyrchains, there is nothing funny we // need to do for their lifecycle management, just swap the underlying diff --git a/pezkuwi/runtime/common/src/paras_sudo_wrapper.rs b/pezkuwi/runtime/common/src/paras_sudo_wrapper.rs index babd4765..fb365e5c 100644 --- a/pezkuwi/runtime/common/src/paras_sudo_wrapper.rs +++ b/pezkuwi/runtime/common/src/paras_sudo_wrapper.rs @@ -157,8 +157,9 @@ pub mod pezpallet { let config = configuration::ActiveConfig::::get(); dmp::Pezpallet::::queue_downward_message(&config, id, xcm.encode()).map_err(|e| { match e { - dmp::QueueDownwardMessageError::ExceedsMaxMessageSize => - Error::::ExceedsMaxMessageSize.into(), + dmp::QueueDownwardMessageError::ExceedsMaxMessageSize => { + Error::::ExceedsMaxMessageSize.into() + }, dmp::QueueDownwardMessageError::Unroutable => Error::::Unroutable.into(), } }) diff --git a/pezkuwi/runtime/common/src/slots/mod.rs b/pezkuwi/runtime/common/src/slots/mod.rs index 98ee16d5..35f2770a 100644 --- a/pezkuwi/runtime/common/src/slots/mod.rs +++ b/pezkuwi/runtime/common/src/slots/mod.rs @@ -314,10 +314,11 @@ impl Pezpallet { let mut tracker = alloc::collections::btree_map::BTreeMap::new(); Leases::::get(para).into_iter().for_each(|lease| match lease { Some((who, amount)) => match tracker.get(&who) { - Some(prev_amount) => + Some(prev_amount) => { if amount > *prev_amount { tracker.insert(who, amount); - }, + } + }, None => { tracker.insert(who, amount); }, @@ -432,12 +433,13 @@ impl Leaser> for Pezpallet { Leases::::get(para) .into_iter() .map(|lease| match lease { - Some((who, amount)) => + Some((who, amount)) => { if &who == leaser { amount } else { Zero::zero() - }, + } + }, None => Zero::zero(), }) .max() diff --git a/pezkuwi/runtime/common/src/try_runtime.rs b/pezkuwi/runtime/common/src/try_runtime.rs index 70b8bf3d..37c0c2c8 100644 --- a/pezkuwi/runtime/common/src/try_runtime.rs +++ b/pezkuwi/runtime/common/src/try_runtime.rs @@ -83,12 +83,13 @@ where maybe_fast_unstake_event }) .for_each(|e: pezpallet_fast_unstake::Event| match e { - pezpallet_fast_unstake::Event::::Unstaked { result, .. } => + pezpallet_fast_unstake::Event::::Unstaked { result, .. } => { if result.is_ok() { unstaked_ok += 1; } else { unstaked_err += 1 - }, + } + }, pezpallet_fast_unstake::Event::::Slashed { .. } => unstaked_slashed += 1, pezpallet_fast_unstake::Event::::InternalError => unreachable!(), _ => {}, diff --git a/pezkuwi/runtime/pezkuwichain/src/genesis_config_presets.rs b/pezkuwi/runtime/pezkuwichain/src/genesis_config_presets.rs index b4ee954b..70ce71f2 100644 --- a/pezkuwi/runtime/pezkuwichain/src/genesis_config_presets.rs +++ b/pezkuwi/runtime/pezkuwichain/src/genesis_config_presets.rs @@ -65,7 +65,10 @@ pub const HEZ_AIRDROP_ALLOCATION: u128 = 40_000_000 * TYR; // COMPILE-TIME VALIDATION: Ensure allocations sum to 200M genesis supply // =========================================================================== const _: () = assert!( - HEZ_FOUNDER_ALLOCATION + HEZ_PRESALE_ALLOCATION + HEZ_TREASURY_ALLOCATION + HEZ_AIRDROP_ALLOCATION + HEZ_FOUNDER_ALLOCATION + + HEZ_PRESALE_ALLOCATION + + HEZ_TREASURY_ALLOCATION + + HEZ_AIRDROP_ALLOCATION == 200_000_000 * TYR, "HEZ allocations MUST sum to genesis supply (200M)" ); @@ -164,9 +167,9 @@ fn default_teyrchains_host_configuration( allowed_ancestry_len: 0, }, node_features: bitvec::vec::BitVec::from_element( - (1u8 << (FeatureIndex::ElasticScalingMVP as usize)) | - (1u8 << (FeatureIndex::EnableAssignmentsV2 as usize)) | - (1u8 << (FeatureIndex::CandidateReceiptV2 as usize)), + (1u8 << (FeatureIndex::ElasticScalingMVP as usize)) + | (1u8 << (FeatureIndex::EnableAssignmentsV2 as usize)) + | (1u8 << (FeatureIndex::CandidateReceiptV2 as usize)), ), scheduler_params: SchedulerParams { lookahead: 3, @@ -189,8 +192,10 @@ fn default_teyrchains_host_configuration_is_consistent() { #[test] fn hez_allocations_sum_to_200m() { // Runtime validation that allocations sum to 200M - let total = HEZ_FOUNDER_ALLOCATION + HEZ_PRESALE_ALLOCATION + - HEZ_TREASURY_ALLOCATION + HEZ_AIRDROP_ALLOCATION; + let total = HEZ_FOUNDER_ALLOCATION + + HEZ_PRESALE_ALLOCATION + + HEZ_TREASURY_ALLOCATION + + HEZ_AIRDROP_ALLOCATION; assert_eq!(total, 200_000_000 * TYR, "HEZ total supply must equal 200M"); } diff --git a/pezkuwi/runtime/pezkuwichain/src/lib.rs b/pezkuwi/runtime/pezkuwichain/src/lib.rs index d6066c9f..c97159b9 100644 --- a/pezkuwi/runtime/pezkuwichain/src/lib.rs +++ b/pezkuwi/runtime/pezkuwichain/src/lib.rs @@ -1025,11 +1025,11 @@ impl InstanceFilter for ProxyType { }, ProxyType::Auction => matches!( c, - RuntimeCall::Auctions { .. } | - RuntimeCall::Crowdloan { .. } | - RuntimeCall::Registrar { .. } | - RuntimeCall::Multisig(..) | - RuntimeCall::Slots { .. } + RuntimeCall::Auctions { .. } + | RuntimeCall::Crowdloan { .. } + | RuntimeCall::Registrar { .. } + | RuntimeCall::Multisig(..) + | RuntimeCall::Slots { .. } ), ProxyType::OnDemandOrdering => matches!(c, RuntimeCall::OnDemandAssignmentProvider(..)), } diff --git a/pezkuwi/runtime/pezkuwichain/src/weights/xcm/mod.rs b/pezkuwi/runtime/pezkuwichain/src/weights/xcm/mod.rs index 7e5dbd8f..cf039d86 100644 --- a/pezkuwi/runtime/pezkuwichain/src/weights/xcm/mod.rs +++ b/pezkuwi/runtime/pezkuwichain/src/weights/xcm/mod.rs @@ -38,8 +38,9 @@ pub enum AssetTypes { impl From<&Asset> for AssetTypes { fn from(asset: &Asset) -> Self { match asset { - Asset { id: AssetId(Location { parents: 0, interior: Here }), .. } => - AssetTypes::Balances, + Asset { id: AssetId(Location { parents: 0, interior: Here }), .. } => { + AssetTypes::Balances + }, _ => AssetTypes::Unknown, } } @@ -67,8 +68,9 @@ impl WeighAssets for AssetFilter { // We don't support any NFTs on Pezkuwichain, so these two variants will always match // only 1 kind of fungible asset. Self::Wild(AllOf { .. } | AllOfCounted { .. }) => balances_weight, - Self::Wild(AllCounted(count)) => - balances_weight.saturating_mul(MAX_ASSETS.min(*count as u64)), + Self::Wild(AllCounted(count)) => { + balances_weight.saturating_mul(MAX_ASSETS.min(*count as u64)) + }, Self::Wild(All) => balances_weight.saturating_mul(MAX_ASSETS), } } diff --git a/pezkuwi/runtime/teyrchains/src/assigner_coretime/mod.rs b/pezkuwi/runtime/teyrchains/src/assigner_coretime/mod.rs index 90bae14d..39196e15 100644 --- a/pezkuwi/runtime/teyrchains/src/assigner_coretime/mod.rs +++ b/pezkuwi/runtime/teyrchains/src/assigner_coretime/mod.rs @@ -282,8 +282,9 @@ impl AssignmentProvider> for Pezpallet { match a_type { CoreAssignment::Idle => None, - CoreAssignment::Pool => - on_demand::Pezpallet::::pop_assignment_for_core(core_idx), + CoreAssignment::Pool => { + on_demand::Pezpallet::::pop_assignment_for_core(core_idx) + }, CoreAssignment::Task(para_id) => Some(Assignment::Bulk((*para_id).into())), } }) @@ -291,8 +292,9 @@ impl AssignmentProvider> for Pezpallet { fn report_processed(assignment: Assignment) { match assignment { - Assignment::Pool { para_id, core_index } => - on_demand::Pezpallet::::report_processed(para_id, core_index), + Assignment::Pool { para_id, core_index } => { + on_demand::Pezpallet::::report_processed(para_id, core_index) + }, Assignment::Bulk(_) => {}, } } @@ -304,8 +306,9 @@ impl AssignmentProvider> for Pezpallet { /// - `assignment`: The on demand assignment. fn push_back_assignment(assignment: Assignment) { match assignment { - Assignment::Pool { para_id, core_index } => - on_demand::Pezpallet::::push_back_assignment(para_id, core_index), + Assignment::Pool { para_id, core_index } => { + on_demand::Pezpallet::::push_back_assignment(para_id, core_index) + }, Assignment::Bulk(_) => { // Session changes are rough. We just drop assignments that did not make it on a // session boundary. This seems sensible as bulk is region based. Meaning, even if @@ -325,8 +328,9 @@ impl AssignmentProvider> for Pezpallet { fn assignment_duplicated(assignment: &Assignment) { match assignment { - Assignment::Pool { para_id, core_index } => - on_demand::Pezpallet::::assignment_duplicated(*para_id, *core_index), + Assignment::Pool { para_id, core_index } => { + on_demand::Pezpallet::::assignment_duplicated(*para_id, *core_index) + }, Assignment::Bulk(_) => {}, } } diff --git a/pezkuwi/runtime/teyrchains/src/builder.rs b/pezkuwi/runtime/teyrchains/src/builder.rs index a92adb78..14fe0b98 100644 --- a/pezkuwi/runtime/teyrchains/src/builder.rs +++ b/pezkuwi/runtime/teyrchains/src/builder.rs @@ -837,10 +837,10 @@ impl BenchBuilder { .sum::() .saturating_sub(self.elastic_paras.len() as usize); - let used_cores = self.dispute_sessions.len() + - self.backed_and_concluding_paras.len() + - self.backed_in_inherent_paras.len() + - extra_cores; + let used_cores = self.dispute_sessions.len() + + self.backed_and_concluding_paras.len() + + self.backed_in_inherent_paras.len() + + extra_cores; assert!(used_cores <= max_cores); @@ -873,8 +873,8 @@ impl BenchBuilder { (used_cores - extra_cores) as u32, builder.dispute_sessions.as_slice(), ); - let mut disputed_cores = (builder.backed_and_concluding_paras.len() as u32.. - ((used_cores - extra_cores) as u32)) + let mut disputed_cores = (builder.backed_and_concluding_paras.len() as u32 + ..((used_cores - extra_cores) as u32)) .into_iter() .map(|idx| (idx, 0)) .collect::>(); diff --git a/pezkuwi/runtime/teyrchains/src/disputes.rs b/pezkuwi/runtime/teyrchains/src/disputes.rs index ea6789ba..8fed5a4b 100644 --- a/pezkuwi/runtime/teyrchains/src/disputes.rs +++ b/pezkuwi/runtime/teyrchains/src/disputes.rs @@ -158,8 +158,9 @@ where (None, Some(_)) => Ordering::Greater, (Some(_), None) => Ordering::Less, // For local disputes, prioritize those that occur at an earlier height. - (Some(a_height), Some(b_height)) => - a_height.cmp(&b_height).then_with(|| a.candidate_hash.cmp(&b.candidate_hash)), + (Some(a_height), Some(b_height)) => { + a_height.cmp(&b_height).then_with(|| a.candidate_hash.cmp(&b.candidate_hash)) + }, // Prioritize earlier remote disputes using session as rough proxy. (None, None) => { let session_ord = a.session.cmp(&b.session); @@ -682,8 +683,9 @@ impl DisputeStateImporter { // We allow backing statements to be imported after an // explicit "for" vote, but not the other way around. match (kind.is_backing(), self.backers.contains(&validator)) { - (true, true) | (false, false) => - return Err(VoteImportError::DuplicateStatement), + (true, true) | (false, false) => { + return Err(VoteImportError::DuplicateStatement) + }, (false, true) => return Err(VoteImportError::MaliciousBacker), (true, false) => {}, } @@ -789,8 +791,8 @@ impl DisputeStateImporter { .validators_for .iter_ones() .filter(|i| { - self.pre_state.validators_for.get(*i).map_or(false, |b| !*b) || - new_backing_vote(&ValidatorIndex(*i as _)) + self.pre_state.validators_for.get(*i).map_or(false, |b| !*b) + || new_backing_vote(&ValidatorIndex(*i as _)) }) .map(|i| ValidatorIndex(i as _)) .collect() @@ -1040,15 +1042,15 @@ impl Pezpallet { }; // Reject disputes which don't have at least one vote on each side. - if summary.state.validators_for.count_ones() == 0 || - summary.state.validators_against.count_ones() == 0 + if summary.state.validators_for.count_ones() == 0 + || summary.state.validators_against.count_ones() == 0 { return StatementSetFilter::RemoveAll; } // Reject disputes containing less votes than needed for confirmation. - if (summary.state.validators_for.clone() | &summary.state.validators_against).count_ones() <= - byzantine_threshold(summary.state.validators_for.len()) + if (summary.state.validators_for.clone() | &summary.state.validators_against).count_ones() + <= byzantine_threshold(summary.state.validators_for.len()) { return StatementSetFilter::RemoveAll; } @@ -1118,15 +1120,15 @@ impl Pezpallet { // Reject disputes which don't have at least one vote on each side. ensure!( - summary.state.validators_for.count_ones() > 0 && - summary.state.validators_against.count_ones() > 0, + summary.state.validators_for.count_ones() > 0 + && summary.state.validators_against.count_ones() > 0, Error::::SingleSidedDispute, ); // Reject disputes containing less votes than needed for confirmation. ensure!( - (summary.state.validators_for.clone() | &summary.state.validators_against).count_ones() > - byzantine_threshold(summary.state.validators_for.len()), + (summary.state.validators_for.clone() | &summary.state.validators_against).count_ones() + > byzantine_threshold(summary.state.validators_for.len()), Error::::UnconfirmedDispute, ); let backers = summary.backers; @@ -1277,30 +1279,36 @@ fn check_signature( approval_multiple_candidates_enabled: bool, ) -> Result<(), ()> { let payload = match statement { - DisputeStatement::Valid(ValidDisputeStatementKind::Explicit) => - ExplicitDisputeStatement { valid: true, candidate_hash, session }.signing_payload(), - DisputeStatement::Valid(ValidDisputeStatementKind::BackingSeconded(inclusion_parent)) => + DisputeStatement::Valid(ValidDisputeStatementKind::Explicit) => { + ExplicitDisputeStatement { valid: true, candidate_hash, session }.signing_payload() + }, + DisputeStatement::Valid(ValidDisputeStatementKind::BackingSeconded(inclusion_parent)) => { CompactStatement::Seconded(candidate_hash).signing_payload(&SigningContext { session_index: session, parent_hash: *inclusion_parent, - }), - DisputeStatement::Valid(ValidDisputeStatementKind::BackingValid(inclusion_parent)) => + }) + }, + DisputeStatement::Valid(ValidDisputeStatementKind::BackingValid(inclusion_parent)) => { CompactStatement::Valid(candidate_hash).signing_payload(&SigningContext { session_index: session, parent_hash: *inclusion_parent, - }), - DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) => - ApprovalVote(candidate_hash).signing_payload(session), + }) + }, + DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) => { + ApprovalVote(candidate_hash).signing_payload(session) + }, DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates( candidates, - )) => + )) => { if approval_multiple_candidates_enabled && candidates.contains(&candidate_hash) { ApprovalVoteMultipleCandidates(candidates).signing_payload(session) } else { return Err(()); - }, - DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit) => - ExplicitDisputeStatement { valid: false, candidate_hash, session }.signing_payload(), + } + }, + DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit) => { + ExplicitDisputeStatement { valid: false, candidate_hash, session }.signing_payload() + }, }; let start = get_current_time(); diff --git a/pezkuwi/runtime/teyrchains/src/disputes/slashing.rs b/pezkuwi/runtime/teyrchains/src/disputes/slashing.rs index 630f2ae4..aa05a5f4 100644 --- a/pezkuwi/runtime/teyrchains/src/disputes/slashing.rs +++ b/pezkuwi/runtime/teyrchains/src/disputes/slashing.rs @@ -498,8 +498,9 @@ pub mod pezpallet { match pending.keys.entry(dispute_proof.validator_index) { Entry::Vacant(_) => return Err(Error::::InvalidValidatorIndex.into()), // check that `validator_index` matches `validator_id` - Entry::Occupied(e) if e.get() != &dispute_proof.validator_id => - return Err(Error::::ValidatorIndexIdMismatch.into()), + Entry::Occupied(e) if e.get() != &dispute_proof.validator_id => { + return Err(Error::::ValidatorIndexIdMismatch.into()) + }, Entry::Occupied(e) => { e.remove(); // the report is correct }, diff --git a/pezkuwi/runtime/teyrchains/src/disputes/tests.rs b/pezkuwi/runtime/teyrchains/src/disputes/tests.rs index ce47fa71..af277351 100644 --- a/pezkuwi/runtime/teyrchains/src/disputes/tests.rs +++ b/pezkuwi/runtime/teyrchains/src/disputes/tests.rs @@ -166,9 +166,9 @@ fn test_dispute_state_flag_from_state() { start: 0, concluded_at: None, }), - DisputeStateFlags::AGAINST_SUPERMAJORITY | - DisputeStateFlags::CONFIRMED | - DisputeStateFlags::AGAINST_BYZANTINE, + DisputeStateFlags::AGAINST_SUPERMAJORITY + | DisputeStateFlags::CONFIRMED + | DisputeStateFlags::AGAINST_BYZANTINE, ); } @@ -286,9 +286,9 @@ fn test_import_prev_participant_confirmed_slash_for() { assert_eq!(summary.new_participants, bitvec![u8, BitOrderLsb0; 0, 0, 1, 1, 1, 1, 1, 0]); assert_eq!( summary.new_flags, - DisputeStateFlags::CONFIRMED | - DisputeStateFlags::AGAINST_SUPERMAJORITY | - DisputeStateFlags::AGAINST_BYZANTINE, + DisputeStateFlags::CONFIRMED + | DisputeStateFlags::AGAINST_SUPERMAJORITY + | DisputeStateFlags::AGAINST_BYZANTINE, ); } diff --git a/pezkuwi/runtime/teyrchains/src/dmp/tests.rs b/pezkuwi/runtime/teyrchains/src/dmp/tests.rs index 9c7cd910..2da8525c 100644 --- a/pezkuwi/runtime/teyrchains/src/dmp/tests.rs +++ b/pezkuwi/runtime/teyrchains/src/dmp/tests.rs @@ -300,8 +300,8 @@ fn verify_fee_increase_and_decrease() { let big_message = [0; 10240].to_vec(); let msg_len_in_kb = big_message.len().saturating_div(1024) as u32; let result = initial.saturating_mul( - Dmp::EXPONENTIAL_FEE_BASE + - Dmp::MESSAGE_SIZE_FEE_BASE.saturating_mul(FixedU128::from_u32(msg_len_in_kb)), + Dmp::EXPONENTIAL_FEE_BASE + + Dmp::MESSAGE_SIZE_FEE_BASE.saturating_mul(FixedU128::from_u32(msg_len_in_kb)), ); queue_downward_message(a, big_message).unwrap(); assert_eq!(DeliveryFeeFactor::::get(a), result); diff --git a/pezkuwi/runtime/teyrchains/src/hrmp.rs b/pezkuwi/runtime/teyrchains/src/hrmp.rs index 9e650695..655d98d6 100644 --- a/pezkuwi/runtime/teyrchains/src/hrmp.rs +++ b/pezkuwi/runtime/teyrchains/src/hrmp.rs @@ -583,13 +583,13 @@ pub mod pezpallet { T::ChannelManager::ensure_origin(origin)?; ensure!( - HrmpIngressChannelsIndex::::decode_len(para).unwrap_or_default() <= - num_inbound as usize, + HrmpIngressChannelsIndex::::decode_len(para).unwrap_or_default() + <= num_inbound as usize, Error::::WrongWitness ); ensure!( - HrmpEgressChannelsIndex::::decode_len(para).unwrap_or_default() <= - num_outbound as usize, + HrmpEgressChannelsIndex::::decode_len(para).unwrap_or_default() + <= num_outbound as usize, Error::::WrongWitness ); @@ -611,8 +611,8 @@ pub mod pezpallet { T::ChannelManager::ensure_origin(origin)?; ensure!( - HrmpOpenChannelRequestsList::::decode_len().unwrap_or_default() as u32 <= - channels, + HrmpOpenChannelRequestsList::::decode_len().unwrap_or_default() as u32 + <= channels, Error::::WrongWitness ); @@ -635,8 +635,8 @@ pub mod pezpallet { T::ChannelManager::ensure_origin(origin)?; ensure!( - HrmpCloseChannelRequestsList::::decode_len().unwrap_or_default() as u32 <= - channels, + HrmpCloseChannelRequestsList::::decode_len().unwrap_or_default() as u32 + <= channels, Error::::WrongWitness ); @@ -661,8 +661,8 @@ pub mod pezpallet { ) -> DispatchResult { let origin = ensure_teyrchain(::RuntimeOrigin::from(origin))?; ensure!( - HrmpOpenChannelRequestsList::::decode_len().unwrap_or_default() as u32 <= - open_requests, + HrmpOpenChannelRequestsList::::decode_len().unwrap_or_default() as u32 + <= open_requests, Error::::WrongWitness ); Self::cancel_open_request(origin, channel_id.clone())?; @@ -795,8 +795,8 @@ pub mod pezpallet { let current_recipient_deposit = channel.recipient_deposit; // nothing to update - if current_sender_deposit == new_sender_deposit && - current_recipient_deposit == new_recipient_deposit + if current_sender_deposit == new_sender_deposit + && current_recipient_deposit == new_recipient_deposit { return Ok(()); } @@ -1081,8 +1081,8 @@ impl Pezpallet { let recipient_deposit = if system_channel { 0 } else { config.hrmp_recipient_deposit }; if request.confirmed { - if paras::Pezpallet::::is_valid_para(channel_id.sender) && - paras::Pezpallet::::is_valid_para(channel_id.recipient) + if paras::Pezpallet::::is_valid_para(channel_id.sender) + && paras::Pezpallet::::is_valid_para(channel_id.recipient) { HrmpChannels::::insert( &channel_id, @@ -1256,8 +1256,9 @@ impl Pezpallet { // the messages must be sorted in ascending order and there must be no two messages // sent to the same recipient. Thus we can check that every recipient is strictly // greater than the previous one. - Some(last_recipient) if out_msg.recipient <= last_recipient => - return Err(OutboundHrmpAcceptanceErr::NotSorted { idx }), + Some(last_recipient) if out_msg.recipient <= last_recipient => { + return Err(OutboundHrmpAcceptanceErr::NotSorted { idx }) + }, _ => last_recipient = Some(out_msg.recipient), } diff --git a/pezkuwi/runtime/teyrchains/src/hrmp/tests.rs b/pezkuwi/runtime/teyrchains/src/hrmp/tests.rs index f744146a..369580d0 100644 --- a/pezkuwi/runtime/teyrchains/src/hrmp/tests.rs +++ b/pezkuwi/runtime/teyrchains/src/hrmp/tests.rs @@ -154,8 +154,8 @@ fn open_channel_works() { run_to_block(5, Some(vec![4, 5])); Hrmp::hrmp_init_open_channel(para_a_origin.into(), para_b, 2, 8).unwrap(); Hrmp::assert_storage_consistency_exhaustive(); - assert!(System::events().iter().any(|record| record.event == - MockEvent::Hrmp(Event::OpenChannelRequested { + assert!(System::events().iter().any(|record| record.event + == MockEvent::Hrmp(Event::OpenChannelRequested { sender: para_a, recipient: para_b, proposed_max_capacity: 2, @@ -164,8 +164,8 @@ fn open_channel_works() { Hrmp::hrmp_accept_open_channel(para_b_origin.into(), para_a).unwrap(); Hrmp::assert_storage_consistency_exhaustive(); - assert!(System::events().iter().any(|record| record.event == - MockEvent::Hrmp(Event::OpenChannelAccepted { sender: para_a, recipient: para_b }))); + assert!(System::events().iter().any(|record| record.event + == MockEvent::Hrmp(Event::OpenChannelAccepted { sender: para_a, recipient: para_b }))); // Advance to a block 6, but without session change. That means that the channel has // not been created yet. @@ -198,15 +198,15 @@ fn force_open_channel_works() { Hrmp::force_open_hrmp_channel(RuntimeOrigin::root(), para_a, para_b, 2, 8).unwrap(); Hrmp::force_open_hrmp_channel(RuntimeOrigin::root(), para_b, para_a, 2, 8).unwrap(); Hrmp::assert_storage_consistency_exhaustive(); - assert!(System::events().iter().any(|record| record.event == - MockEvent::Hrmp(Event::HrmpChannelForceOpened { + assert!(System::events().iter().any(|record| record.event + == MockEvent::Hrmp(Event::HrmpChannelForceOpened { sender: para_a, recipient: para_b, proposed_max_capacity: 2, proposed_max_message_size: 8 }))); - assert!(System::events().iter().any(|record| record.event == - MockEvent::Hrmp(Event::HrmpChannelForceOpened { + assert!(System::events().iter().any(|record| record.event + == MockEvent::Hrmp(Event::HrmpChannelForceOpened { sender: para_b, recipient: para_a, proposed_max_capacity: 2, @@ -252,15 +252,15 @@ fn force_open_channel_without_free_balance_works() { Hrmp::force_open_hrmp_channel(RuntimeOrigin::root(), para_a, para_b, 2, 8).unwrap(); Hrmp::force_open_hrmp_channel(RuntimeOrigin::root(), para_b, para_a, 2, 8).unwrap(); Hrmp::assert_storage_consistency_exhaustive(); - assert!(System::events().iter().any(|record| record.event == - MockEvent::Hrmp(Event::HrmpChannelForceOpened { + assert!(System::events().iter().any(|record| record.event + == MockEvent::Hrmp(Event::HrmpChannelForceOpened { sender: para_a, recipient: para_b, proposed_max_capacity: 2, proposed_max_message_size: 8 }))); - assert!(System::events().iter().any(|record| record.event == - MockEvent::Hrmp(Event::HrmpChannelForceOpened { + assert!(System::events().iter().any(|record| record.event + == MockEvent::Hrmp(Event::HrmpChannelForceOpened { sender: para_b, recipient: para_a, proposed_max_capacity: 2, @@ -296,8 +296,8 @@ fn force_open_channel_works_with_existing_request() { run_to_block(3, Some(vec![2, 3])); Hrmp::hrmp_init_open_channel(para_a_origin.into(), para_b, 2, 8).unwrap(); Hrmp::assert_storage_consistency_exhaustive(); - assert!(System::events().iter().any(|record| record.event == - MockEvent::Hrmp(Event::OpenChannelRequested { + assert!(System::events().iter().any(|record| record.event + == MockEvent::Hrmp(Event::OpenChannelRequested { sender: para_a, recipient: para_b, proposed_max_capacity: 2, @@ -315,8 +315,8 @@ fn force_open_channel_works_with_existing_request() { // now force open it. Hrmp::force_open_hrmp_channel(RuntimeOrigin::root(), para_a, para_b, 2, 8).unwrap(); Hrmp::assert_storage_consistency_exhaustive(); - assert!(System::events().iter().any(|record| record.event == - MockEvent::Hrmp(Event::HrmpChannelForceOpened { + assert!(System::events().iter().any(|record| record.event + == MockEvent::Hrmp(Event::HrmpChannelForceOpened { sender: para_a, recipient: para_b, proposed_max_capacity: 2, @@ -348,8 +348,8 @@ fn open_system_channel_works() { run_to_block(5, Some(vec![4, 5])); Hrmp::establish_system_channel(RuntimeOrigin::signed(1), para_a, para_b).unwrap(); Hrmp::assert_storage_consistency_exhaustive(); - assert!(System::events().iter().any(|record| record.event == - MockEvent::Hrmp(Event::HrmpSystemChannelOpened { + assert!(System::events().iter().any(|record| record.event + == MockEvent::Hrmp(Event::HrmpSystemChannelOpened { sender: para_a, recipient: para_b, proposed_max_capacity: 2, @@ -484,8 +484,8 @@ fn close_channel_works() { run_to_block(8, Some(vec![8])); assert!(!channel_exists(para_a, para_b)); Hrmp::assert_storage_consistency_exhaustive(); - assert!(System::events().iter().any(|record| record.event == - MockEvent::Hrmp(Event::ChannelClosed { + assert!(System::events().iter().any(|record| record.event + == MockEvent::Hrmp(Event::ChannelClosed { by_teyrchain: para_b, channel_id: channel_id.clone() }))); @@ -1040,16 +1040,16 @@ fn establish_channel_with_system_works() { run_to_block(5, Some(vec![4, 5])); Hrmp::establish_channel_with_system(para_a_origin.into(), para_b).unwrap(); Hrmp::assert_storage_consistency_exhaustive(); - assert!(System::events().iter().any(|record| record.event == - MockEvent::Hrmp(Event::HrmpSystemChannelOpened { + assert!(System::events().iter().any(|record| record.event + == MockEvent::Hrmp(Event::HrmpSystemChannelOpened { sender: para_a, recipient: para_b, proposed_max_capacity: 1, proposed_max_message_size: 4 }))); - assert!(System::events().iter().any(|record| record.event == - MockEvent::Hrmp(Event::HrmpSystemChannelOpened { + assert!(System::events().iter().any(|record| record.event + == MockEvent::Hrmp(Event::HrmpSystemChannelOpened { sender: para_b, recipient: para_a, proposed_max_capacity: 1, diff --git a/pezkuwi/runtime/teyrchains/src/inclusion/mod.rs b/pezkuwi/runtime/teyrchains/src/inclusion/mod.rs index 08c860f8..a3686558 100644 --- a/pezkuwi/runtime/teyrchains/src/inclusion/mod.rs +++ b/pezkuwi/runtime/teyrchains/src/inclusion/mod.rs @@ -792,8 +792,8 @@ impl Pezpallet { match maybe_amount_validated { Ok(amount_validated) => ensure!( - amount_validated >= - effective_minimum_backing_votes(group_vals.len(), minimum_backing_votes), + amount_validated + >= effective_minimum_backing_votes(group_vals.len(), minimum_backing_votes), Error::::InsufficientBacking, ), Err(()) => { @@ -1274,8 +1274,8 @@ impl CandidateCheckContext { ); ensure!( - backed_candidate_receipt.descriptor.para_head() == - backed_candidate_receipt.commitments.head_data.hash(), + backed_candidate_receipt.descriptor.para_head() + == backed_candidate_receipt.commitments.head_data.hash(), Error::::ParaHeadMismatch, ); diff --git a/pezkuwi/runtime/teyrchains/src/inclusion/tests.rs b/pezkuwi/runtime/teyrchains/src/inclusion/tests.rs index 5cb76e39..aa567db4 100644 --- a/pezkuwi/runtime/teyrchains/src/inclusion/tests.rs +++ b/pezkuwi/runtime/teyrchains/src/inclusion/tests.rs @@ -151,8 +151,8 @@ pub(crate) fn back_candidate( |i| Some(validators[group[i].0 as usize].public().into()), ) .ok() - .unwrap_or(0) >= - threshold; + .unwrap_or(0) + >= threshold; match kind { BackingKind::Unanimous | BackingKind::Threshold => assert!(successfully_backed), @@ -207,8 +207,8 @@ pub(crate) fn run_to_block( } pub(crate) fn expected_bits() -> usize { - paras::Teyrchains::::get().len() + - configuration::ActiveConfig::::get().scheduler_params.num_cores as usize + paras::Teyrchains::::get().len() + + configuration::ActiveConfig::::get().scheduler_params.num_cores as usize } fn default_bitfield() -> AvailabilityBitfield { diff --git a/pezkuwi/runtime/teyrchains/src/initializer.rs b/pezkuwi/runtime/teyrchains/src/initializer.rs index 612b275d..b6edf41f 100644 --- a/pezkuwi/runtime/teyrchains/src/initializer.rs +++ b/pezkuwi/runtime/teyrchains/src/initializer.rs @@ -173,16 +173,16 @@ pub mod pezpallet { // - DMP // - UMP // - HRMP - let total_weight = configuration::Pezpallet::::initializer_initialize(now) + - shared::Pezpallet::::initializer_initialize(now) + - paras::Pezpallet::::initializer_initialize(now) + - scheduler::Pezpallet::::initializer_initialize(now) + - inclusion::Pezpallet::::initializer_initialize(now) + - session_info::Pezpallet::::initializer_initialize(now) + - T::DisputesHandler::initializer_initialize(now) + - T::SlashingHandler::initializer_initialize(now) + - dmp::Pezpallet::::initializer_initialize(now) + - hrmp::Pezpallet::::initializer_initialize(now); + let total_weight = configuration::Pezpallet::::initializer_initialize(now) + + shared::Pezpallet::::initializer_initialize(now) + + paras::Pezpallet::::initializer_initialize(now) + + scheduler::Pezpallet::::initializer_initialize(now) + + inclusion::Pezpallet::::initializer_initialize(now) + + session_info::Pezpallet::::initializer_initialize(now) + + T::DisputesHandler::initializer_initialize(now) + + T::SlashingHandler::initializer_initialize(now) + + dmp::Pezpallet::::initializer_initialize(now) + + hrmp::Pezpallet::::initializer_initialize(now); HasInitialized::::set(Some(())); diff --git a/pezkuwi/runtime/teyrchains/src/on_demand/mod.rs b/pezkuwi/runtime/teyrchains/src/on_demand/mod.rs index 39ca1d79..6f1e7a02 100644 --- a/pezkuwi/runtime/teyrchains/src/on_demand/mod.rs +++ b/pezkuwi/runtime/teyrchains/src/on_demand/mod.rs @@ -615,8 +615,8 @@ where // (queue_size / queue_capacity) - target_queue_utilisation let queue_util_ratio = FixedU128::from_rational(queue_size.into(), queue_capacity.into()); let positive = queue_util_ratio >= target_queue_utilisation.into(); - let queue_util_diff = queue_util_ratio.max(target_queue_utilisation.into()) - - queue_util_ratio.min(target_queue_utilisation.into()); + let queue_util_diff = queue_util_ratio.max(target_queue_utilisation.into()) + - queue_util_ratio.min(target_queue_utilisation.into()); // variability * queue_util_diff let var_times_qud = queue_util_diff.saturating_mul(variability.into()); @@ -667,8 +667,9 @@ where match affinity { None => FreeEntries::::mutate(|entries| entries.push(order)), - Some(affinity) => - AffinityEntries::::mutate(affinity.core_index, |entries| entries.push(order)), + Some(affinity) => { + AffinityEntries::::mutate(affinity.core_index, |entries| entries.push(order)) + }, } } @@ -729,13 +730,14 @@ where /// `CoreIndex`. fn increase_affinity(para_id: ParaId, core_index: CoreIndex) { ParaIdAffinity::::mutate(para_id, |maybe_affinity| match maybe_affinity { - Some(affinity) => + Some(affinity) => { if affinity.core_index == core_index { *maybe_affinity = Some(CoreAffinityCount { core_index, count: affinity.count.saturating_add(1), }); - }, + } + }, None => { *maybe_affinity = Some(CoreAffinityCount { core_index, count: 1 }); }, diff --git a/pezkuwi/runtime/teyrchains/src/paras/mod.rs b/pezkuwi/runtime/teyrchains/src/paras/mod.rs index 374eacf4..5fcac78d 100644 --- a/pezkuwi/runtime/teyrchains/src/paras/mod.rs +++ b/pezkuwi/runtime/teyrchains/src/paras/mod.rs @@ -221,9 +221,9 @@ impl ParaLifecycle { pub fn is_teyrchain(&self) -> bool { matches!( self, - ParaLifecycle::Teyrchain | - ParaLifecycle::DowngradingTeyrchain | - ParaLifecycle::OffboardingTeyrchain + ParaLifecycle::Teyrchain + | ParaLifecycle::DowngradingTeyrchain + | ParaLifecycle::OffboardingTeyrchain ) } @@ -233,9 +233,9 @@ impl ParaLifecycle { pub fn is_parathread(&self) -> bool { matches!( self, - ParaLifecycle::Parathread | - ParaLifecycle::UpgradingParathread | - ParaLifecycle::OffboardingParathread + ParaLifecycle::Parathread + | ParaLifecycle::UpgradingParathread + | ParaLifecycle::OffboardingParathread ) } @@ -1385,8 +1385,9 @@ pub mod pezpallet { let validators = shared::ActiveValidatorKeys::::get(); let validator_public = match validators.get(validator_index) { Some(pk) => pk, - None => - return InvalidTransaction::Custom(INVALID_TX_BAD_VALIDATOR_IDX).into(), + None => { + return InvalidTransaction::Custom(INVALID_TX_BAD_VALIDATOR_IDX).into() + }, }; let signing_payload = stmt.signing_payload(); @@ -1401,10 +1402,12 @@ pub mod pezpallet { match active_vote.has_vote(validator_index) { Some(false) => (), - Some(true) => - return InvalidTransaction::Custom(INVALID_TX_DOUBLE_VOTE).into(), - None => - return InvalidTransaction::Custom(INVALID_TX_BAD_VALIDATOR_IDX).into(), + Some(true) => { + return InvalidTransaction::Custom(INVALID_TX_DOUBLE_VOTE).into() + }, + None => { + return InvalidTransaction::Custom(INVALID_TX_BAD_VALIDATOR_IDX).into() + }, } ValidTransaction::with_tag_prefix("PvfPreCheckingVote") @@ -1419,7 +1422,7 @@ pub mod pezpallet { .propagate(true) .build() }, - Call::apply_authorized_force_set_current_code { para, new_code } => + Call::apply_authorized_force_set_current_code { para, new_code } => { match Self::validate_code_is_authorized(new_code, para) { Ok(authorized_code) => { let now = pezframe_system::Pezpallet::::block_number(); @@ -1432,9 +1435,11 @@ pub mod pezpallet { .propagate(true) .build() }, - Err(_) => - return InvalidTransaction::Custom(INVALID_TX_UNAUTHORIZED_CODE).into(), - }, + Err(_) => { + return InvalidTransaction::Custom(INVALID_TX_UNAUTHORIZED_CODE).into() + }, + } + }, _ => InvalidTransaction::Call.into(), } } @@ -1500,10 +1505,10 @@ impl Pezpallet { /// Called by the initializer to initialize the paras pezpallet. pub(crate) fn initializer_initialize(now: BlockNumberFor) -> Weight { - Self::prune_old_code(now) + - Self::process_scheduled_upgrade_changes(now) + - Self::process_future_code_upgrades_at(now) + - Self::prune_expired_authorizations(now) + Self::prune_old_code(now) + + Self::process_scheduled_upgrade_changes(now) + + Self::process_future_code_upgrades_at(now) + + Self::prune_expired_authorizations(now) } /// Called by the initializer to finalize the paras pezpallet. @@ -1582,8 +1587,8 @@ impl Pezpallet { ParaLifecycles::::insert(¶, ParaLifecycle::Parathread); }, // Offboard a lease holding or on-demand teyrchain from the system - Some(ParaLifecycle::OffboardingTeyrchain) | - Some(ParaLifecycle::OffboardingParathread) => { + Some(ParaLifecycle::OffboardingTeyrchain) + | Some(ParaLifecycle::OffboardingParathread) => { teyrchains.remove(para); Heads::::remove(¶); @@ -1913,8 +1918,8 @@ impl Pezpallet { // // we cannot onboard at the current session, so it must be at least one // session ahead. - let onboard_at: SessionIndex = shared::CurrentSessionIndex::::get() + - cmp::max(shared::SESSION_DELAY.saturating_sub(sessions_observed), 1); + let onboard_at: SessionIndex = shared::CurrentSessionIndex::::get() + + cmp::max(shared::SESSION_DELAY.saturating_sub(sessions_observed), 1); ActionsQueue::::mutate(onboard_at, |v| { if let Err(i) = v.binary_search(&id) { diff --git a/pezkuwi/runtime/teyrchains/src/paras/tests.rs b/pezkuwi/runtime/teyrchains/src/paras/tests.rs index 30f0eeb2..30ccc76d 100644 --- a/pezkuwi/runtime/teyrchains/src/paras/tests.rs +++ b/pezkuwi/runtime/teyrchains/src/paras/tests.rs @@ -2117,8 +2117,8 @@ fn remove_upgrade_cooldown_works() { assert_ok!(Call::::remove_upgrade_cooldown { para: para_id } .dispatch_bypass_filter(RuntimeOrigin::signed(1))); - let expected_issuance = issuance - - Pezpallet::::calculate_remove_upgrade_cooldown_cost(next_possible_upgrade_at); + let expected_issuance = issuance + - Pezpallet::::calculate_remove_upgrade_cooldown_cost(next_possible_upgrade_at); // Check that we burned the funds assert_eq!(expected_issuance, Balances::total_issuance()); diff --git a/pezkuwi/runtime/teyrchains/src/paras_inherent/mod.rs b/pezkuwi/runtime/teyrchains/src/paras_inherent/mod.rs index 3337c035..fb5e6066 100644 --- a/pezkuwi/runtime/teyrchains/src/paras_inherent/mod.rs +++ b/pezkuwi/runtime/teyrchains/src/paras_inherent/mod.rs @@ -913,8 +913,8 @@ pub(crate) fn sanitize_bitfields( continue; } - if unchecked_bitfield.unchecked_payload().0.clone() & disputed_bitfield.0.clone() != - all_zeros + if unchecked_bitfield.unchecked_payload().0.clone() & disputed_bitfield.0.clone() + != all_zeros { log::trace!( target: LOG_TARGET, @@ -1345,8 +1345,8 @@ fn filter_backed_statements_from_disabled_validators< // By filtering votes we might render the candidate invalid and cause a failure in // [`process_candidates`]. To avoid this we have to perform a sanity check here. If there // are not enough backing votes after filtering we will remove the whole candidate. - if bc.validity_votes().len() < - effective_minimum_backing_votes(validator_group.len(), minimum_backing_votes) + if bc.validity_votes().len() + < effective_minimum_backing_votes(validator_group.len(), minimum_backing_votes) { log::debug!( target: LOG_TARGET, diff --git a/pezkuwi/runtime/teyrchains/src/paras_inherent/tests.rs b/pezkuwi/runtime/teyrchains/src/paras_inherent/tests.rs index ff3b71f6..dc0a0206 100644 --- a/pezkuwi/runtime/teyrchains/src/paras_inherent/tests.rs +++ b/pezkuwi/runtime/teyrchains/src/paras_inherent/tests.rs @@ -1188,9 +1188,9 @@ mod enter { let backed_candidates_weight = backed_candidates_weight::(&inherent_data.backed_candidates); - let sum = multi_dispute_statement_sets_weight + - signed_bitfields_weight + - backed_candidates_weight; + let sum = multi_dispute_statement_sets_weight + + signed_bitfields_weight + + backed_candidates_weight; println!( "disputes({})={} + bitfields({})={} + candidates({})={} -> {}", diff --git a/pezkuwi/runtime/teyrchains/src/runtime_api_impl/v13.rs b/pezkuwi/runtime/teyrchains/src/runtime_api_impl/v13.rs index a1a26552..0e8a2418 100644 --- a/pezkuwi/runtime/teyrchains/src/runtime_api_impl/v13.rs +++ b/pezkuwi/runtime/teyrchains/src/runtime_api_impl/v13.rs @@ -148,13 +148,14 @@ where build() }, OccupiedCoreAssumption::TimedOut => build(), - OccupiedCoreAssumption::Free => + OccupiedCoreAssumption::Free => { if !>::candidates_pending_availability(para_id).is_empty() { None } else { build() - }, + } + }, } } @@ -296,12 +297,15 @@ where .filter_map(|record| extract_event(record.event)) .filter_map(|event| { Some(match event { - RawEvent::::CandidateBacked(c, h, core, group) => - CandidateEvent::CandidateBacked(c, h, core, group), - RawEvent::::CandidateIncluded(c, h, core, group) => - CandidateEvent::CandidateIncluded(c, h, core, group), - RawEvent::::CandidateTimedOut(c, h, core) => - CandidateEvent::CandidateTimedOut(c, h, core), + RawEvent::::CandidateBacked(c, h, core, group) => { + CandidateEvent::CandidateBacked(c, h, core, group) + }, + RawEvent::::CandidateIncluded(c, h, core, group) => { + CandidateEvent::CandidateIncluded(c, h, core, group) + }, + RawEvent::::CandidateTimedOut(c, h, core) => { + CandidateEvent::CandidateTimedOut(c, h, core) + }, // Not needed for candidate events. RawEvent::::UpwardMessagesReceived { .. } => return None, RawEvent::::__Ignore(_, _) => unreachable!("__Ignore cannot be used"), @@ -432,8 +436,8 @@ pub fn backing_constraints( // Use the right storage depending on version to ensure #64 doesn't cause issues with this // migration. - let min_relay_parent_number = if shared::Pezpallet::::on_chain_storage_version() == - StorageVersion::new(0) + let min_relay_parent_number = if shared::Pezpallet::::on_chain_storage_version() + == StorageVersion::new(0) { shared::migration::v0::AllowedRelayParents::::get().hypothetical_earliest_block_number( now, @@ -577,8 +581,8 @@ pub fn candidates_pending_availability( /// Implementation for `validation_code_bomb_limit` function from the runtime API pub fn validation_code_bomb_limit() -> u32 { - configuration::ActiveConfig::::get().max_code_size * - configuration::MAX_VALIDATION_CODE_COMPRESSION_RATIO + configuration::ActiveConfig::::get().max_code_size + * configuration::MAX_VALIDATION_CODE_COMPRESSION_RATIO } /// Implementation for `scheduling_lookahead` function from the runtime API diff --git a/pezkuwi/runtime/teyrchains/src/scheduler/migration.rs b/pezkuwi/runtime/teyrchains/src/scheduler/migration.rs index d203c261..ef809d09 100644 --- a/pezkuwi/runtime/teyrchains/src/scheduler/migration.rs +++ b/pezkuwi/runtime/teyrchains/src/scheduler/migration.rs @@ -191,11 +191,12 @@ mod v1 { for (core_index, core) in availability_cores.into_iter().enumerate() { let new_core = if let Some(core) = core { match core { - v0::CoreOccupied::Teyrchain => + v0::CoreOccupied::Teyrchain => { v1::CoreOccupied::Paras(v1::ParasEntry::new( V0Assignment { para_id: teyrchains[core_index] }, now, - )), + )) + }, v0::CoreOccupied::Parathread(entry) => v1::CoreOccupied::Paras( v1::ParasEntry::new(V0Assignment { para_id: entry.claim.0 }, now), ), @@ -223,8 +224,8 @@ mod v1 { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, pezsp_runtime::DispatchError> { - let n: u32 = v0::Scheduled::::get().len() as u32 + - v0::AvailabilityCores::::get().iter().filter(|c| c.is_some()).count() as u32; + let n: u32 = v0::Scheduled::::get().len() as u32 + + v0::AvailabilityCores::::get().iter().filter(|c| c.is_some()).count() as u32; log::info!( target: crate::scheduler::LOG_TARGET, @@ -250,8 +251,8 @@ mod v1 { .count(); ensure!( - Pezpallet::::claim_queue_len() as u32 + availability_cores_waiting as u32 == - expected_len, + Pezpallet::::claim_queue_len() as u32 + availability_cores_waiting as u32 + == expected_len, "ClaimQueue and AvailabilityCores should have the correct length", ); diff --git a/pezkuwi/runtime/teyrchains/src/ump_tests.rs b/pezkuwi/runtime/teyrchains/src/ump_tests.rs index 8743c427..7b895a32 100644 --- a/pezkuwi/runtime/teyrchains/src/ump_tests.rs +++ b/pezkuwi/runtime/teyrchains/src/ump_tests.rs @@ -214,8 +214,8 @@ mod check_upward_messages { 5 ); assert!( - configuration::ActiveConfig::::get().max_upward_queue_size < - crate::inclusion::MaxUmpMessageLenOf::::get(), + configuration::ActiveConfig::::get().max_upward_queue_size + < crate::inclusion::MaxUmpMessageLenOf::::get(), "Test will not work" ); diff --git a/pezkuwi/runtime/zagros/src/genesis_config_presets.rs b/pezkuwi/runtime/zagros/src/genesis_config_presets.rs index 4e356862..5b7436ba 100644 --- a/pezkuwi/runtime/zagros/src/genesis_config_presets.rs +++ b/pezkuwi/runtime/zagros/src/genesis_config_presets.rs @@ -131,9 +131,9 @@ fn default_teyrchains_host_configuration( allowed_ancestry_len: 0, }, node_features: bitvec::vec::BitVec::from_element( - (1u8 << (FeatureIndex::ElasticScalingMVP as usize)) | - (1u8 << (FeatureIndex::EnableAssignmentsV2 as usize)) | - (1u8 << (FeatureIndex::CandidateReceiptV2 as usize)), + (1u8 << (FeatureIndex::ElasticScalingMVP as usize)) + | (1u8 << (FeatureIndex::EnableAssignmentsV2 as usize)) + | (1u8 << (FeatureIndex::CandidateReceiptV2 as usize)), ), scheduler_params: SchedulerParams { lookahead: 3, diff --git a/pezkuwi/runtime/zagros/src/lib.rs b/pezkuwi/runtime/zagros/src/lib.rs index 07023cda..6f9376d0 100644 --- a/pezkuwi/runtime/zagros/src/lib.rs +++ b/pezkuwi/runtime/zagros/src/lib.rs @@ -1321,12 +1321,12 @@ impl InstanceFilter for ProxyType { ProxyType::Staking => { matches!( c, - RuntimeCall::Staking(..) | - RuntimeCall::Session(..) | - RuntimeCall::Utility(..) | - RuntimeCall::FastUnstake(..) | - RuntimeCall::VoterList(..) | - RuntimeCall::NominationPools(..) + RuntimeCall::Staking(..) + | RuntimeCall::Session(..) + | RuntimeCall::Utility(..) + | RuntimeCall::FastUnstake(..) + | RuntimeCall::VoterList(..) + | RuntimeCall::NominationPools(..) ) }, ProxyType::NominationPools => { @@ -1342,33 +1342,33 @@ impl InstanceFilter for ProxyType { ProxyType::Governance => matches!( c, // OpenGov calls - RuntimeCall::ConvictionVoting(..) | - RuntimeCall::Referenda(..) | - RuntimeCall::Whitelist(..) + RuntimeCall::ConvictionVoting(..) + | RuntimeCall::Referenda(..) + | RuntimeCall::Whitelist(..) ), ProxyType::IdentityJudgement => matches!( c, - RuntimeCall::Identity(pezpallet_identity::Call::provide_judgement { .. }) | - RuntimeCall::Utility(..) + RuntimeCall::Identity(pezpallet_identity::Call::provide_judgement { .. }) + | RuntimeCall::Utility(..) ), ProxyType::CancelProxy => { matches!(c, RuntimeCall::Proxy(pezpallet_proxy::Call::reject_announcement { .. })) }, ProxyType::Auction => matches!( c, - RuntimeCall::Auctions(..) | - RuntimeCall::Crowdloan(..) | - RuntimeCall::Registrar(..) | - RuntimeCall::Slots(..) + RuntimeCall::Auctions(..) + | RuntimeCall::Crowdloan(..) + | RuntimeCall::Registrar(..) + | RuntimeCall::Slots(..) ), ProxyType::ParaRegistration => matches!( c, - RuntimeCall::Registrar(paras_registrar::Call::reserve { .. }) | - RuntimeCall::Registrar(paras_registrar::Call::register { .. }) | - RuntimeCall::Utility(pezpallet_utility::Call::batch { .. }) | - RuntimeCall::Utility(pezpallet_utility::Call::batch_all { .. }) | - RuntimeCall::Utility(pezpallet_utility::Call::force_batch { .. }) | - RuntimeCall::Proxy(pezpallet_proxy::Call::remove_proxy { .. }) + RuntimeCall::Registrar(paras_registrar::Call::reserve { .. }) + | RuntimeCall::Registrar(paras_registrar::Call::register { .. }) + | RuntimeCall::Utility(pezpallet_utility::Call::batch { .. }) + | RuntimeCall::Utility(pezpallet_utility::Call::batch_all { .. }) + | RuntimeCall::Utility(pezpallet_utility::Call::force_batch { .. }) + | RuntimeCall::Proxy(pezpallet_proxy::Call::remove_proxy { .. }) ), } } diff --git a/pezkuwi/runtime/zagros/src/weights/xcm/mod.rs b/pezkuwi/runtime/zagros/src/weights/xcm/mod.rs index ea3ed54d..c37cd3ab 100644 --- a/pezkuwi/runtime/zagros/src/weights/xcm/mod.rs +++ b/pezkuwi/runtime/zagros/src/weights/xcm/mod.rs @@ -41,8 +41,9 @@ pub enum AssetTypes { impl From<&Asset> for AssetTypes { fn from(asset: &Asset) -> Self { match asset { - Asset { id: AssetId(Location { parents: 0, interior: Here }), .. } => - AssetTypes::Balances, + Asset { id: AssetId(Location { parents: 0, interior: Here }), .. } => { + AssetTypes::Balances + }, _ => AssetTypes::Unknown, } } @@ -70,8 +71,9 @@ impl WeighAssets for AssetFilter { // We don't support any NFTs on Zagros, so these two variants will always match // only 1 kind of fungible asset. Self::Wild(AllOf { .. } | AllOfCounted { .. }) => balances_weight, - Self::Wild(AllCounted(count)) => - balances_weight.saturating_mul(MAX_ASSETS.min(*count as u64)), + Self::Wild(AllCounted(count)) => { + balances_weight.saturating_mul(MAX_ASSETS.min(*count as u64)) + }, Self::Wild(All) => balances_weight.saturating_mul(MAX_ASSETS), } } diff --git a/pezkuwi/statement-table/src/generic.rs b/pezkuwi/statement-table/src/generic.rs index 70f6f720..119f3aba 100644 --- a/pezkuwi/statement-table/src/generic.rs +++ b/pezkuwi/statement-table/src/generic.rs @@ -109,8 +109,9 @@ impl ValidityDoubleVote - ((Statement::Seconded(c), s1), (Statement::Valid(d), s2)), + Self::IssuedAndValidity((c, s1), (d, s2)) => { + ((Statement::Seconded(c), s1), (Statement::Valid(d), s2)) + }, } } } @@ -238,8 +239,9 @@ impl CandidateData { .iter() .map(|(a, v)| match *v { ValidityVote::Valid(ref s) => (a.clone(), ValidityAttestation::Explicit(s.clone())), - ValidityVote::Issued(ref s) => - (a.clone(), ValidityAttestation::Implicit(s.clone())), + ValidityVote::Issued(ref s) => { + (a.clone(), ValidityAttestation::Implicit(s.clone())) + }, }) .collect(); @@ -325,10 +327,12 @@ impl Table { ) -> Option> { let SignedStatement { statement, signature, sender: signer } = statement; let res = match statement { - Statement::Seconded(candidate) => - self.import_candidate(context, signer.clone(), candidate, signature, group_id), - Statement::Valid(digest) => - self.validity_vote(context, signer.clone(), digest, ValidityVote::Valid(signature)), + Statement::Seconded(candidate) => { + self.import_candidate(context, signer.clone(), candidate, signature, group_id) + }, + Statement::Valid(digest) => { + self.validity_vote(context, signer.clone(), digest, ValidityVote::Valid(signature)) + }, }; match res { @@ -451,20 +455,23 @@ impl Table { return if occ.get() != &vote { Err(match (occ.get().clone(), vote) { // valid vote conflicting with candidate statement - (ValidityVote::Issued(iss), ValidityVote::Valid(good)) | - (ValidityVote::Valid(good), ValidityVote::Issued(iss)) => + (ValidityVote::Issued(iss), ValidityVote::Valid(good)) + | (ValidityVote::Valid(good), ValidityVote::Issued(iss)) => { make_vdv(ValidityDoubleVote::IssuedAndValidity( (votes.candidate.clone(), iss), (digest, good), - )), + )) + }, // two signatures on same candidate - (ValidityVote::Issued(a), ValidityVote::Issued(b)) => - make_ds(DoubleSign::Seconded(votes.candidate.clone(), a, b)), + (ValidityVote::Issued(a), ValidityVote::Issued(b)) => { + make_ds(DoubleSign::Seconded(votes.candidate.clone(), a, b)) + }, // two signatures on same validity vote - (ValidityVote::Valid(a), ValidityVote::Valid(b)) => - make_ds(DoubleSign::Validity(digest, a, b)), + (ValidityVote::Valid(a), ValidityVote::Valid(b)) => { + make_ds(DoubleSign::Validity(digest, a, b)) + }, }) } else { Ok(None) diff --git a/pezkuwi/tests/benchmark_block.rs b/pezkuwi/tests/benchmark_block.rs index 57949e54..f7b295e2 100644 --- a/pezkuwi/tests/benchmark_block.rs +++ b/pezkuwi/tests/benchmark_block.rs @@ -15,7 +15,6 @@ // along with Pezkuwi. If not, see . #![allow(deprecated)] - // Unix only since it uses signals. #![cfg(unix)] diff --git a/pezkuwi/teyrchain/test-teyrchains/adder/collator/src/cli.rs b/pezkuwi/teyrchain/test-teyrchains/adder/collator/src/cli.rs index fcb9c9d0..329ab5d3 100644 --- a/pezkuwi/teyrchain/test-teyrchains/adder/collator/src/cli.rs +++ b/pezkuwi/teyrchain/test-teyrchains/adder/collator/src/cli.rs @@ -106,10 +106,12 @@ impl BizinikiwiCli for Cli { ) -> std::result::Result, String> { let id = if id.is_empty() { "pezkuwichain" } else { id }; Ok(match id { - "pezkuwichain-staging" => - Box::new(pezkuwi_service::chain_spec::pezkuwichain_staging_testnet_config()?), - "pezkuwichain-local" => - Box::new(pezkuwi_service::chain_spec::pezkuwichain_local_testnet_config()?), + "pezkuwichain-staging" => { + Box::new(pezkuwi_service::chain_spec::pezkuwichain_staging_testnet_config()?) + }, + "pezkuwichain-local" => { + Box::new(pezkuwi_service::chain_spec::pezkuwichain_local_testnet_config()?) + }, "pezkuwichain" => Box::new(pezkuwi_service::chain_spec::pezkuwichain_config()?), path => { let path = std::path::PathBuf::from(path); diff --git a/pezkuwi/teyrchain/test-teyrchains/undying/collator/src/cli.rs b/pezkuwi/teyrchain/test-teyrchains/undying/collator/src/cli.rs index 4fc243f0..b2beab91 100644 --- a/pezkuwi/teyrchain/test-teyrchains/undying/collator/src/cli.rs +++ b/pezkuwi/teyrchain/test-teyrchains/undying/collator/src/cli.rs @@ -145,10 +145,12 @@ impl BizinikiwiCli for Cli { ) -> std::result::Result, String> { let id = if id.is_empty() { "pezkuwichain" } else { id }; Ok(match id { - "pezkuwichain-staging" => - Box::new(pezkuwi_service::chain_spec::pezkuwichain_staging_testnet_config()?), - "pezkuwichain-local" => - Box::new(pezkuwi_service::chain_spec::pezkuwichain_local_testnet_config()?), + "pezkuwichain-staging" => { + Box::new(pezkuwi_service::chain_spec::pezkuwichain_staging_testnet_config()?) + }, + "pezkuwichain-local" => { + Box::new(pezkuwi_service::chain_spec::pezkuwichain_local_testnet_config()?) + }, "pezkuwichain" => Box::new(pezkuwi_service::chain_spec::pezkuwichain_config()?), path => { let path = std::path::PathBuf::from(path); diff --git a/pezkuwi/xcm/pezpallet-xcm-benchmarks/src/mock.rs b/pezkuwi/xcm/pezpallet-xcm-benchmarks/src/mock.rs index 0da47228..b712fdb9 100644 --- a/pezkuwi/xcm/pezpallet-xcm-benchmarks/src/mock.rs +++ b/pezkuwi/xcm/pezpallet-xcm-benchmarks/src/mock.rs @@ -50,8 +50,9 @@ pub struct AccountIdConverter; impl xcm_executor::traits::ConvertLocation for AccountIdConverter { fn convert_location(ml: &Location) -> Option { match ml.unpack() { - (0, [Junction::AccountId32 { id, .. }]) => - Some(::decode(&mut &*id.to_vec()).unwrap()), + (0, [Junction::AccountId32 { id, .. }]) => { + Some(::decode(&mut &*id.to_vec()).unwrap()) + }, _ => None, } } diff --git a/pezkuwi/xcm/pezpallet-xcm/precompiles/src/lib.rs b/pezkuwi/xcm/pezpallet-xcm/precompiles/src/lib.rs index 65a33776..ad5b91d6 100644 --- a/pezkuwi/xcm/pezpallet-xcm/precompiles/src/lib.rs +++ b/pezkuwi/xcm/pezpallet-xcm/precompiles/src/lib.rs @@ -82,8 +82,9 @@ where }; match input { - IXcmCalls::send(_) | IXcmCalls::execute(_) if env.is_read_only() => - Err(Error::Error(pezpallet_revive::Error::::StateChangeDenied.into())), + IXcmCalls::send(_) | IXcmCalls::execute(_) if env.is_read_only() => { + Err(Error::Error(pezpallet_revive::Error::::StateChangeDenied.into())) + }, IXcmCalls::send(IXcm::sendCall { destination, message }) => { let _ = env.charge(::WeightInfo::send())?; diff --git a/pezkuwi/xcm/pezpallet-xcm/src/benchmarking.rs b/pezkuwi/xcm/pezpallet-xcm/src/benchmarking.rs index 12b94e26..6a492369 100644 --- a/pezkuwi/xcm/pezpallet-xcm/src/benchmarking.rs +++ b/pezkuwi/xcm/pezpallet-xcm/src/benchmarking.rs @@ -671,8 +671,9 @@ mod benchmarks { // remove `network` from inner `AccountId32` for easier matching of automatic AccountId -> // Location conversions. let origin_location: VersionedLocation = match origin_location.unpack() { - (0, [AccountId32 { network: _, id }]) => - Location::new(0, [AccountId32 { network: None, id: *id }]).into(), + (0, [AccountId32 { network: _, id }]) => { + Location::new(0, [AccountId32 { network: None, id: *id }]).into() + }, _ => { tracing::error!( target: "xcm::benchmarking::pezpallet_xcm::remove_authorized_alias", diff --git a/pezkuwi/xcm/pezpallet-xcm/src/lib.rs b/pezkuwi/xcm/pezpallet-xcm/src/lib.rs index 1857dbfe..762b53ce 100644 --- a/pezkuwi/xcm/pezpallet-xcm/src/lib.rs +++ b/pezkuwi/xcm/pezpallet-xcm/src/lib.rs @@ -1075,8 +1075,9 @@ pub mod pezpallet { timeout, maybe_match_querier: Some(Location::here().into()), }, - VersionNotifier { origin, is_active } => - QueryStatus::VersionNotifier { origin, is_active }, + VersionNotifier { origin, is_active } => { + QueryStatus::VersionNotifier { origin, is_active } + }, Ready { response, at } => QueryStatus::Ready { response, at }, } } @@ -1714,16 +1715,17 @@ pub mod pezpallet { ensure!(origin_location != new_aliaser, Error::::BadLocation); // remove `network` from inner `AccountId32` for easier matching let origin_location = match origin_location.unpack() { - (0, [AccountId32 { network: _, id }]) => - Location::new(0, [AccountId32 { network: None, id: *id }]), + (0, [AccountId32 { network: _, id }]) => { + Location::new(0, [AccountId32 { network: None, id: *id }]) + }, _ => return Err(Error::::InvalidOrigin.into()), }; tracing::debug!(target: "xcm::pezpallet_xcm::add_authorized_alias", ?origin_location, ?new_aliaser, ?expires); ensure!(origin_location != new_aliaser, Error::::BadLocation); if let Some(expiry) = expires { ensure!( - expiry > - pezframe_system::Pezpallet::::current_block_number() + expiry + > pezframe_system::Pezpallet::::current_block_number() .saturated_into::(), Error::::ExpiresInPast ); @@ -1797,8 +1799,9 @@ pub mod pezpallet { ensure!(origin_location != to_remove, Error::::BadLocation); // remove `network` from inner `AccountId32` for easier matching let origin_location = match origin_location.unpack() { - (0, [AccountId32 { network: _, id }]) => - Location::new(0, [AccountId32 { network: None, id: *id }]), + (0, [AccountId32 { network: _, id }]) => { + Location::new(0, [AccountId32 { network: None, id: *id }]) + }, _ => return Err(Error::::InvalidOrigin.into()), }; tracing::debug!(target: "xcm::pezpallet_xcm::remove_authorized_alias", ?origin_location, ?to_remove); @@ -1847,8 +1850,9 @@ pub mod pezpallet { let origin_location: Location = T::ExecuteXcmOrigin::ensure_origin(origin)?; // remove `network` from inner `AccountId32` for easier matching let origin_location = match origin_location.unpack() { - (0, [AccountId32 { network: _, id }]) => - Location::new(0, [AccountId32 { network: None, id: *id }]), + (0, [AccountId32 { network: _, id }]) => { + Location::new(0, [AccountId32 { network: None, id: *id }]) + }, _ => return Err(Error::::InvalidOrigin.into()), }; tracing::debug!(target: "xcm::pezpallet_xcm::remove_all_authorized_aliases", ?origin_location); @@ -2236,8 +2240,9 @@ impl Pezpallet { fees, weight_limit, )?, - TransferType::RemoteReserve(_) => - return Err(Error::::InvalidAssetUnsupportedReserve.into()), + TransferType::RemoteReserve(_) => { + return Err(Error::::InvalidAssetUnsupportedReserve.into()) + }, }; FeesHandling::Separate { local_xcm, remote_xcm } }; @@ -3460,13 +3465,13 @@ impl Pezpallet { Ok(Self::authorized_aliasers(target)?.into_iter().any(|aliaser| { // `aliasers` and `origin` have already been transformed to `desired_version`, we // can just directly compare them. - aliaser.location == origin && - aliaser + aliaser.location == origin + && aliaser .expiry .map(|expiry| { pezframe_system::Pezpallet::::current_block_number() - .saturated_into::() < - expiry + .saturated_into::() + < expiry }) .unwrap_or(true) })) @@ -3631,8 +3636,8 @@ impl Pezpallet { // check `RemoteLockedFungibles` ensure!( !RemoteLockedFungibles::::iter() - .any(|(key, data)| key.needs_migration(minimal_allowed_xcm_version) || - data.needs_migration(minimal_allowed_xcm_version)), + .any(|(key, data)| key.needs_migration(minimal_allowed_xcm_version) + || data.needs_migration(minimal_allowed_xcm_version)), TryRuntimeError::Other( "`RemoteLockedFungibles` data should be migrated to the higher xcm version!" ) @@ -3966,11 +3971,12 @@ impl ClaimAssets for Pezpallet { ) -> bool { let mut versioned = VersionedAssets::from(assets.clone()); match ticket.unpack() { - (0, [GeneralIndex(i)]) => + (0, [GeneralIndex(i)]) => { versioned = match versioned.into_version(*i as u32) { Ok(v) => v, Err(()) => return false, - }, + } + }, (0, []) => (), _ => return false, }; @@ -3996,15 +4002,17 @@ impl OnResponse for Pezpallet { querier: Option<&Location>, ) -> bool { match Queries::::get(query_id) { - Some(QueryStatus::Pending { responder, maybe_match_querier, .. }) => - Location::try_from(responder).map_or(false, |r| origin == &r) && - maybe_match_querier.map_or(true, |match_querier| { + Some(QueryStatus::Pending { responder, maybe_match_querier, .. }) => { + Location::try_from(responder).map_or(false, |r| origin == &r) + && maybe_match_querier.map_or(true, |match_querier| { Location::try_from(match_querier).map_or(false, |match_querier| { querier.map_or(false, |q| q == &match_querier) }) - }), - Some(QueryStatus::VersionNotifier { origin: r, .. }) => - Location::try_from(r).map_or(false, |r| origin == &r), + }) + }, + Some(QueryStatus::VersionNotifier { origin: r, .. }) => { + Location::try_from(r).map_or(false, |r| origin == &r) + }, _ => false, } } @@ -4285,12 +4293,13 @@ where fn try_origin(outer: O) -> Result { match outer.caller().try_into() { - Ok(Origin::Xcm(ref location)) => + Ok(Origin::Xcm(ref location)) => { if let Ok(location) = location.clone().try_into() { if F::contains(&location) { return Ok(location); } - }, + } + }, _ => (), } diff --git a/pezkuwi/xcm/pezpallet-xcm/src/migration.rs b/pezkuwi/xcm/pezpallet-xcm/src/migration.rs index e6a506b6..2f226435 100644 --- a/pezkuwi/xcm/pezpallet-xcm/src/migration.rs +++ b/pezkuwi/xcm/pezpallet-xcm/src/migration.rs @@ -80,16 +80,19 @@ pub mod data { fn needs_migration(&self, minimal_allowed_xcm_version: XcmVersion) -> bool { match &self { - QueryStatus::Pending { responder, maybe_match_querier, .. } => - responder.identify_version() < minimal_allowed_xcm_version || - maybe_match_querier + QueryStatus::Pending { responder, maybe_match_querier, .. } => { + responder.identify_version() < minimal_allowed_xcm_version + || maybe_match_querier .as_ref() .map(|v| v.identify_version() < minimal_allowed_xcm_version) - .unwrap_or(false), - QueryStatus::VersionNotifier { origin, .. } => - origin.identify_version() < minimal_allowed_xcm_version, - QueryStatus::Ready { response, .. } => - response.identify_version() < minimal_allowed_xcm_version, + .unwrap_or(false) + }, + QueryStatus::VersionNotifier { origin, .. } => { + origin.identify_version() < minimal_allowed_xcm_version + }, + QueryStatus::Ready { response, .. } => { + response.identify_version() < minimal_allowed_xcm_version + }, } } @@ -131,8 +134,8 @@ pub mod data { type MigratedData = Self; fn needs_migration(&self, minimal_allowed_xcm_version: XcmVersion) -> bool { - self.0 < minimal_allowed_xcm_version || - self.2.identify_version() < minimal_allowed_xcm_version + self.0 < minimal_allowed_xcm_version + || self.2.identify_version() < minimal_allowed_xcm_version } fn try_migrate(self, to_xcm_version: XcmVersion) -> Result, ()> { @@ -152,8 +155,8 @@ pub mod data { type MigratedData = Self; fn needs_migration(&self, minimal_allowed_xcm_version: XcmVersion) -> bool { - self.owner.identify_version() < minimal_allowed_xcm_version || - self.locker.identify_version() < minimal_allowed_xcm_version + self.owner.identify_version() < minimal_allowed_xcm_version + || self.locker.identify_version() < minimal_allowed_xcm_version } fn try_migrate(self, to_xcm_version: XcmVersion) -> Result, ()> { @@ -177,8 +180,9 @@ pub mod data { type MigratedData = (VersionedLocation, AuthorizedAliasesEntry, M>); fn needs_migration(&self, required_version: XcmVersion) -> bool { - self.0.identify_version() != required_version || - self.1 + self.0.identify_version() != required_version + || self + .1 .aliasers .iter() .any(|alias| alias.location.identify_version() != required_version) diff --git a/pezkuwi/xcm/pezpallet-xcm/src/transfer_assets_validation.rs b/pezkuwi/xcm/pezpallet-xcm/src/transfer_assets_validation.rs index 9497c778..1da69cec 100644 --- a/pezkuwi/xcm/pezpallet-xcm/src/transfer_assets_validation.rs +++ b/pezkuwi/xcm/pezpallet-xcm/src/transfer_assets_validation.rs @@ -77,9 +77,9 @@ impl Pezpallet { // is being attempted. let is_reserve_transfer = matches!( transfer_type, - TransferType::LocalReserve | - TransferType::DestinationReserve | - TransferType::RemoteReserve(_) + TransferType::LocalReserve + | TransferType::DestinationReserve + | TransferType::RemoteReserve(_) ); if !is_reserve_transfer { @@ -122,9 +122,9 @@ impl Pezpallet { NetworkId::Pezkuwi | NetworkId::Kusama => true, NetworkId::ByGenesis(genesis_hash) => { // Check if this is Zagros by genesis hash - *genesis_hash == xcm::v5::ZAGROS_GENESIS_HASH || - *genesis_hash == PASEO_GENESIS_HASH || - *genesis_hash == xcm::v5::PEZKUWICHAIN_GENESIS_HASH // Used in tests. + *genesis_hash == xcm::v5::ZAGROS_GENESIS_HASH + || *genesis_hash == PASEO_GENESIS_HASH + || *genesis_hash == xcm::v5::PEZKUWICHAIN_GENESIS_HASH // Used in tests. }, _ => false, }; @@ -144,9 +144,9 @@ impl Pezpallet { NetworkId::Pezkuwi | NetworkId::Kusama => true, NetworkId::ByGenesis(genesis_hash) => { // Check if this is Zagros by genesis hash - *genesis_hash == xcm::v5::ZAGROS_GENESIS_HASH || - *genesis_hash == PASEO_GENESIS_HASH || - *genesis_hash == xcm::v5::PEZKUWICHAIN_GENESIS_HASH // Used in tests. + *genesis_hash == xcm::v5::ZAGROS_GENESIS_HASH + || *genesis_hash == PASEO_GENESIS_HASH + || *genesis_hash == xcm::v5::PEZKUWICHAIN_GENESIS_HASH // Used in tests. }, _ => false, }; diff --git a/pezkuwi/xcm/procedural/src/builder_pattern.rs b/pezkuwi/xcm/procedural/src/builder_pattern.rs index 79fdc483..1397d1b2 100644 --- a/pezkuwi/xcm/procedural/src/builder_pattern.rs +++ b/pezkuwi/xcm/procedural/src/builder_pattern.rs @@ -261,7 +261,7 @@ fn convert_variant_to_method( let method_name = syn::Ident::new(method_name_string, variant_name.span()); let docs = get_doc_comments(variant); let method = match &variant.fields { - Fields::Unit => + Fields::Unit => { if let Some(return_type) = maybe_return_type { quote! { pub fn #method_name(self) -> #return_type { @@ -280,7 +280,8 @@ fn convert_variant_to_method( self } } - }, + } + }, Fields::Unnamed(fields) => { let arg_names: Vec<_> = fields .unnamed diff --git a/pezkuwi/xcm/src/v3/junction.rs b/pezkuwi/xcm/src/v3/junction.rs index 51ff64ba..c2f9c1cb 100644 --- a/pezkuwi/xcm/src/v3/junction.rs +++ b/pezkuwi/xcm/src/v3/junction.rs @@ -320,8 +320,9 @@ impl<'a> TryFrom<&'a Junction> for BoundedSlice<'a, u8, ConstU32<32>> { type Error = (); fn try_from(key: &'a Junction) -> Result { match key { - Junction::GeneralKey { length, data } => - BoundedSlice::try_from(&data[..data.len().min(*length as usize)]).map_err(|_| ()), + Junction::GeneralKey { length, data } => { + BoundedSlice::try_from(&data[..data.len().min(*length as usize)]).map_err(|_| ()) + }, _ => Err(()), } } @@ -352,12 +353,15 @@ impl TryFrom for Junction { use NewJunction::*; Ok(match value { Teyrchain(id) => Self::Teyrchain(id), - AccountId32 { network: maybe_network, id } => - Self::AccountId32 { network: maybe_network.map(|network| network.into()), id }, - AccountIndex64 { network: maybe_network, index } => - Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index }, - AccountKey20 { network: maybe_network, key } => - Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key }, + AccountId32 { network: maybe_network, id } => { + Self::AccountId32 { network: maybe_network.map(|network| network.into()), id } + }, + AccountIndex64 { network: maybe_network, index } => { + Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index } + }, + AccountKey20 { network: maybe_network, key } => { + Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key } + }, PalletInstance(index) => Self::PalletInstance(index), GeneralIndex(id) => Self::GeneralIndex(id), GeneralKey { length, data } => Self::GeneralKey { length, data }, @@ -395,9 +399,9 @@ impl Junction { pub fn remove_network_id(&mut self) { use Junction::*; match self { - AccountId32 { ref mut network, .. } | - AccountIndex64 { ref mut network, .. } | - AccountKey20 { ref mut network, .. } => *network = None, + AccountId32 { ref mut network, .. } + | AccountIndex64 { ref mut network, .. } + | AccountKey20 { ref mut network, .. } => *network = None, _ => {}, } } diff --git a/pezkuwi/xcm/src/v3/mod.rs b/pezkuwi/xcm/src/v3/mod.rs index e3574b3b..7131cf7d 100644 --- a/pezkuwi/xcm/src/v3/mod.rs +++ b/pezkuwi/xcm/src/v3/mod.rs @@ -328,8 +328,9 @@ impl TryFrom for Response { Ok(match new { Null => Self::Null, Assets(assets) => Self::Assets(assets.try_into()?), - ExecutionResult(result) => - Self::ExecutionResult(result.map(|(num, old_error)| (num, old_error.into()))), + ExecutionResult(result) => { + Self::ExecutionResult(result.map(|(num, old_error)| (num, old_error.into()))) + }, Version(version) => Self::Version(version), PalletsInfo(pezpallet_info) => { let inner = pezpallet_info @@ -340,8 +341,9 @@ impl TryFrom for Response { BoundedVec::::try_from(inner).map_err(|_| ())?, ) }, - DispatchResult(maybe_error) => - Self::DispatchResult(maybe_error.try_into().map_err(|_| ())?), + DispatchResult(maybe_error) => { + Self::DispatchResult(maybe_error.try_into().map_err(|_| ())?) + }, }) } } @@ -1150,24 +1152,30 @@ impl Instruction { WithdrawAsset(assets) => WithdrawAsset(assets), ReserveAssetDeposited(assets) => ReserveAssetDeposited(assets), ReceiveTeleportedAsset(assets) => ReceiveTeleportedAsset(assets), - QueryResponse { query_id, response, max_weight, querier } => - QueryResponse { query_id, response, max_weight, querier }, + QueryResponse { query_id, response, max_weight, querier } => { + QueryResponse { query_id, response, max_weight, querier } + }, TransferAsset { assets, beneficiary } => TransferAsset { assets, beneficiary }, - TransferReserveAsset { assets, dest, xcm } => - TransferReserveAsset { assets, dest, xcm }, - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, + TransferReserveAsset { assets, dest, xcm } => { + TransferReserveAsset { assets, dest, xcm } + }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => { + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } + }, HrmpChannelAccepted { recipient } => HrmpChannelAccepted { recipient }, - HrmpChannelClosing { initiator, sender, recipient } => - HrmpChannelClosing { initiator, sender, recipient }, - Transact { origin_kind, require_weight_at_most, call } => - Transact { origin_kind, require_weight_at_most, call: call.into() }, + HrmpChannelClosing { initiator, sender, recipient } => { + HrmpChannelClosing { initiator, sender, recipient } + }, + Transact { origin_kind, require_weight_at_most, call } => { + Transact { origin_kind, require_weight_at_most, call: call.into() } + }, ReportError(response_info) => ReportError(response_info), DepositAsset { assets, beneficiary } => DepositAsset { assets, beneficiary }, DepositReserveAsset { assets, dest, xcm } => DepositReserveAsset { assets, dest, xcm }, ExchangeAsset { give, want, maximal } => ExchangeAsset { give, want, maximal }, - InitiateReserveWithdraw { assets, reserve, xcm } => - InitiateReserveWithdraw { assets, reserve, xcm }, + InitiateReserveWithdraw { assets, reserve, xcm } => { + InitiateReserveWithdraw { assets, reserve, xcm } + }, InitiateTeleport { assets, dest, xcm } => InitiateTeleport { assets, dest, xcm }, ReportHolding { response_info, assets } => ReportHolding { response_info, assets }, BuyExecution { fees, weight_limit } => BuyExecution { fees, weight_limit }, @@ -1179,23 +1187,27 @@ impl Instruction { ClearError => ClearError, ClaimAsset { assets, ticket } => ClaimAsset { assets, ticket }, Trap(code) => Trap(code), - SubscribeVersion { query_id, max_response_weight } => - SubscribeVersion { query_id, max_response_weight }, + SubscribeVersion { query_id, max_response_weight } => { + SubscribeVersion { query_id, max_response_weight } + }, UnsubscribeVersion => UnsubscribeVersion, BurnAsset(assets) => BurnAsset(assets), ExpectAsset(assets) => ExpectAsset(assets), ExpectOrigin(origin) => ExpectOrigin(origin), ExpectError(error) => ExpectError(error), ExpectTransactStatus(transact_status) => ExpectTransactStatus(transact_status), - QueryPallet { module_name, response_info } => - QueryPallet { module_name, response_info }, - ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => - ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, + QueryPallet { module_name, response_info } => { + QueryPallet { module_name, response_info } + }, + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => { + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } + }, ReportTransactStatus(response_info) => ReportTransactStatus(response_info), ClearTransactStatus => ClearTransactStatus, UniversalOrigin(j) => UniversalOrigin(j), - ExportMessage { network, destination, xcm } => - ExportMessage { network, destination, xcm }, + ExportMessage { network, destination, xcm } => { + ExportMessage { network, destination, xcm } + }, LockAsset { asset, unlocker } => LockAsset { asset, unlocker }, UnlockAsset { asset, target } => UnlockAsset { asset, target }, NoteUnlockable { asset, owner } => NoteUnlockable { asset, owner }, @@ -1204,8 +1216,9 @@ impl Instruction { SetTopic(topic) => SetTopic(topic), ClearTopic => ClearTopic, AliasOrigin(location) => AliasOrigin(location), - UnpaidExecution { weight_limit, check_origin } => - UnpaidExecution { weight_limit, check_origin }, + UnpaidExecution { weight_limit, check_origin } => { + UnpaidExecution { weight_limit, check_origin } + }, } } } @@ -1218,27 +1231,34 @@ impl> GetWeight for Instruction { WithdrawAsset(assets) => W::withdraw_asset(assets), ReserveAssetDeposited(assets) => W::reserve_asset_deposited(assets), ReceiveTeleportedAsset(assets) => W::receive_teleported_asset(assets), - QueryResponse { query_id, response, max_weight, querier } => - W::query_response(query_id, response, max_weight, querier), + QueryResponse { query_id, response, max_weight, querier } => { + W::query_response(query_id, response, max_weight, querier) + }, TransferAsset { assets, beneficiary } => W::transfer_asset(assets, beneficiary), - TransferReserveAsset { assets, dest, xcm } => - W::transfer_reserve_asset(&assets, dest, xcm), - Transact { origin_kind, require_weight_at_most, call } => - W::transact(origin_kind, require_weight_at_most, call), - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => - W::hrmp_new_channel_open_request(sender, max_message_size, max_capacity), + TransferReserveAsset { assets, dest, xcm } => { + W::transfer_reserve_asset(&assets, dest, xcm) + }, + Transact { origin_kind, require_weight_at_most, call } => { + W::transact(origin_kind, require_weight_at_most, call) + }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => { + W::hrmp_new_channel_open_request(sender, max_message_size, max_capacity) + }, HrmpChannelAccepted { recipient } => W::hrmp_channel_accepted(recipient), - HrmpChannelClosing { initiator, sender, recipient } => - W::hrmp_channel_closing(initiator, sender, recipient), + HrmpChannelClosing { initiator, sender, recipient } => { + W::hrmp_channel_closing(initiator, sender, recipient) + }, ClearOrigin => W::clear_origin(), DescendOrigin(who) => W::descend_origin(who), ReportError(response_info) => W::report_error(&response_info), DepositAsset { assets, beneficiary } => W::deposit_asset(assets, beneficiary), - DepositReserveAsset { assets, dest, xcm } => - W::deposit_reserve_asset(assets, dest, xcm), + DepositReserveAsset { assets, dest, xcm } => { + W::deposit_reserve_asset(assets, dest, xcm) + }, ExchangeAsset { give, want, maximal } => W::exchange_asset(give, want, maximal), - InitiateReserveWithdraw { assets, reserve, xcm } => - W::initiate_reserve_withdraw(assets, reserve, xcm), + InitiateReserveWithdraw { assets, reserve, xcm } => { + W::initiate_reserve_withdraw(assets, reserve, xcm) + }, InitiateTeleport { assets, dest, xcm } => W::initiate_teleport(assets, dest, xcm), ReportHolding { response_info, assets } => W::report_holding(&response_info, &assets), BuyExecution { fees, weight_limit } => W::buy_execution(fees, weight_limit), @@ -1248,23 +1268,27 @@ impl> GetWeight for Instruction { ClearError => W::clear_error(), ClaimAsset { assets, ticket } => W::claim_asset(assets, ticket), Trap(code) => W::trap(code), - SubscribeVersion { query_id, max_response_weight } => - W::subscribe_version(query_id, max_response_weight), + SubscribeVersion { query_id, max_response_weight } => { + W::subscribe_version(query_id, max_response_weight) + }, UnsubscribeVersion => W::unsubscribe_version(), BurnAsset(assets) => W::burn_asset(assets), ExpectAsset(assets) => W::expect_asset(assets), ExpectOrigin(origin) => W::expect_origin(origin), ExpectError(error) => W::expect_error(error), ExpectTransactStatus(transact_status) => W::expect_transact_status(transact_status), - QueryPallet { module_name, response_info } => - W::query_pallet(module_name, response_info), - ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => - W::expect_pallet(index, name, module_name, crate_major, min_crate_minor), + QueryPallet { module_name, response_info } => { + W::query_pallet(module_name, response_info) + }, + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => { + W::expect_pallet(index, name, module_name, crate_major, min_crate_minor) + }, ReportTransactStatus(response_info) => W::report_transact_status(response_info), ClearTransactStatus => W::clear_transact_status(), UniversalOrigin(j) => W::universal_origin(j), - ExportMessage { network, destination, xcm } => - W::export_message(network, destination, xcm), + ExportMessage { network, destination, xcm } => { + W::export_message(network, destination, xcm) + }, LockAsset { asset, unlocker } => W::lock_asset(asset, unlocker), UnlockAsset { asset, target } => W::unlock_asset(asset, target), NoteUnlockable { asset, owner } => W::note_unlockable(asset, owner), @@ -1273,8 +1297,9 @@ impl> GetWeight for Instruction { SetTopic(topic) => W::set_topic(topic), ClearTopic => W::clear_topic(), AliasOrigin(location) => W::alias_origin(location), - UnpaidExecution { weight_limit, check_origin } => - W::unpaid_execution(weight_limit, check_origin), + UnpaidExecution { weight_limit, check_origin } => { + W::unpaid_execution(weight_limit, check_origin) + }, } } } @@ -1306,20 +1331,22 @@ impl TryFrom> for Instruction { WithdrawAsset(assets) => Self::WithdrawAsset(assets.try_into()?), ReserveAssetDeposited(assets) => Self::ReserveAssetDeposited(assets.try_into()?), ReceiveTeleportedAsset(assets) => Self::ReceiveTeleportedAsset(assets.try_into()?), - QueryResponse { query_id, response, max_weight, querier: Some(querier) } => + QueryResponse { query_id, response, max_weight, querier: Some(querier) } => { Self::QueryResponse { query_id, querier: querier.try_into()?, response: response.try_into()?, max_weight, - }, - QueryResponse { query_id, response, max_weight, querier: None } => + } + }, + QueryResponse { query_id, response, max_weight, querier: None } => { Self::QueryResponse { query_id, querier: None, response: response.try_into()?, max_weight, - }, + } + }, TransferAsset { assets, beneficiary } => Self::TransferAsset { assets: assets.try_into()?, beneficiary: beneficiary.try_into()?, @@ -1329,13 +1356,16 @@ impl TryFrom> for Instruction { dest: dest.try_into()?, xcm: xcm.try_into()?, }, - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => - Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => { + Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } + }, HrmpChannelAccepted { recipient } => Self::HrmpChannelAccepted { recipient }, - HrmpChannelClosing { initiator, sender, recipient } => - Self::HrmpChannelClosing { initiator, sender, recipient }, - Transact { origin_kind, require_weight_at_most, call } => - Self::Transact { origin_kind, require_weight_at_most, call: call.into() }, + HrmpChannelClosing { initiator, sender, recipient } => { + Self::HrmpChannelClosing { initiator, sender, recipient } + }, + Transact { origin_kind, require_weight_at_most, call } => { + Self::Transact { origin_kind, require_weight_at_most, call: call.into() } + }, ReportError(response_info) => Self::ReportError(QueryResponseInfo { query_id: response_info.query_id, destination: response_info.destination.try_into().map_err(|_| ())?, @@ -1396,21 +1426,26 @@ impl TryFrom> for Instruction { Self::ClaimAsset { assets, ticket } }, Trap(code) => Self::Trap(code), - SubscribeVersion { query_id, max_response_weight } => - Self::SubscribeVersion { query_id, max_response_weight }, + SubscribeVersion { query_id, max_response_weight } => { + Self::SubscribeVersion { query_id, max_response_weight } + }, UnsubscribeVersion => Self::UnsubscribeVersion, BurnAsset(assets) => Self::BurnAsset(assets.try_into()?), ExpectAsset(assets) => Self::ExpectAsset(assets.try_into()?), - ExpectOrigin(maybe_origin) => - Self::ExpectOrigin(maybe_origin.map(|origin| origin.try_into()).transpose()?), + ExpectOrigin(maybe_origin) => { + Self::ExpectOrigin(maybe_origin.map(|origin| origin.try_into()).transpose()?) + }, ExpectError(maybe_error) => Self::ExpectError(maybe_error), ExpectTransactStatus(maybe_error_code) => Self::ExpectTransactStatus(maybe_error_code), - QueryPallet { module_name, response_info } => - Self::QueryPallet { module_name, response_info: response_info.try_into()? }, - ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => - Self::ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, - ReportTransactStatus(response_info) => - Self::ReportTransactStatus(response_info.try_into()?), + QueryPallet { module_name, response_info } => { + Self::QueryPallet { module_name, response_info: response_info.try_into()? } + }, + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => { + Self::ExpectPallet { index, name, module_name, crate_major, min_crate_minor } + }, + ReportTransactStatus(response_info) => { + Self::ReportTransactStatus(response_info.try_into()?) + }, ClearTransactStatus => Self::ClearTransactStatus, UniversalOrigin(junction) => Self::UniversalOrigin(junction.try_into()?), ExportMessage { network, destination, xcm } => Self::ExportMessage { @@ -1418,14 +1453,18 @@ impl TryFrom> for Instruction { destination: destination.try_into()?, xcm: xcm.try_into()?, }, - LockAsset { asset, unlocker } => - Self::LockAsset { asset: asset.try_into()?, unlocker: unlocker.try_into()? }, - UnlockAsset { asset, target } => - Self::UnlockAsset { asset: asset.try_into()?, target: target.try_into()? }, - NoteUnlockable { asset, owner } => - Self::NoteUnlockable { asset: asset.try_into()?, owner: owner.try_into()? }, - RequestUnlock { asset, locker } => - Self::RequestUnlock { asset: asset.try_into()?, locker: locker.try_into()? }, + LockAsset { asset, unlocker } => { + Self::LockAsset { asset: asset.try_into()?, unlocker: unlocker.try_into()? } + }, + UnlockAsset { asset, target } => { + Self::UnlockAsset { asset: asset.try_into()?, target: target.try_into()? } + }, + NoteUnlockable { asset, owner } => { + Self::NoteUnlockable { asset: asset.try_into()?, owner: owner.try_into()? } + }, + RequestUnlock { asset, locker } => { + Self::RequestUnlock { asset: asset.try_into()?, locker: locker.try_into()? } + }, SetFeesMode { jit_withdraw } => Self::SetFeesMode { jit_withdraw }, SetTopic(topic) => Self::SetTopic(topic), ClearTopic => Self::ClearTopic, diff --git a/pezkuwi/xcm/src/v3/multiasset.rs b/pezkuwi/xcm/src/v3/multiasset.rs index 52308986..8d2227b2 100644 --- a/pezkuwi/xcm/src/v3/multiasset.rs +++ b/pezkuwi/xcm/src/v3/multiasset.rs @@ -284,8 +284,9 @@ impl Decode for Fungibility { match UncheckedFungibility::decode(input)? { UncheckedFungibility::Fungible(a) if a != 0 => Ok(Self::Fungible(a)), UncheckedFungibility::NonFungible(i) => Ok(Self::NonFungible(i)), - UncheckedFungibility::Fungible(_) => - Err("Fungible asset of zero amount is not allowed".into()), + UncheckedFungibility::Fungible(_) => { + Err("Fungible asset of zero amount is not allowed".into()) + }, } } } @@ -628,8 +629,9 @@ impl From> for MultiAssets { ( MultiAsset { fun: Fungibility::NonFungible(a_instance), id: a_id }, MultiAsset { fun: Fungibility::NonFungible(b_instance), id: b_id }, - ) if a_id == b_id && a_instance == b_instance => - MultiAsset { fun: Fungibility::NonFungible(a_instance), id: a_id }, + ) if a_id == b_id && a_instance == b_instance => { + MultiAsset { fun: Fungibility::NonFungible(a_instance), id: a_id } + }, (to_push, to_remember) => { res.push(to_push); to_remember @@ -710,7 +712,9 @@ impl MultiAssets { }, (Fungibility::NonFungible(inst1), Fungibility::NonFungible(inst2)) if inst1 == inst2 => - return, + { + return + }, _ => (), } } @@ -818,8 +822,9 @@ impl TryFrom for WildMultiAsset { use NewWildMultiAsset::*; Ok(match new { AllOf { id, fun } => Self::AllOf { id: id.try_into()?, fun: fun.try_into()? }, - AllOfCounted { id, fun, count } => - Self::AllOfCounted { id: id.try_into()?, fun: fun.try_into()?, count }, + AllOfCounted { id, fun, count } => { + Self::AllOfCounted { id: id.try_into()?, fun: fun.try_into()?, count } + }, All => Self::All, AllCounted(count) => Self::AllCounted(count), }) @@ -832,8 +837,9 @@ impl WildMultiAsset { use WildMultiAsset::*; match self { AllOfCounted { count: 0, .. } | AllCounted(0) => false, - AllOf { fun, id } | AllOfCounted { id, fun, .. } => - inner.fun.is_kind(*fun) && &inner.id == id, + AllOf { fun, id } | AllOfCounted { id, fun, .. } => { + inner.fun.is_kind(*fun) && &inner.id == id + }, All | AllCounted(_) => true, } } @@ -856,8 +862,9 @@ impl WildMultiAsset { ) -> Result<(), ()> { use WildMultiAsset::*; match self { - AllOf { ref mut id, .. } | AllOfCounted { ref mut id, .. } => - id.reanchor(target, context), + AllOf { ref mut id, .. } | AllOfCounted { ref mut id, .. } => { + id.reanchor(target, context) + }, All | AllCounted(_) => Ok(()), } } diff --git a/pezkuwi/xcm/src/v3/traits.rs b/pezkuwi/xcm/src/v3/traits.rs index 8c60adf1..670363ee 100644 --- a/pezkuwi/xcm/src/v3/traits.rs +++ b/pezkuwi/xcm/src/v3/traits.rs @@ -224,8 +224,9 @@ impl TryFrom for Error { impl From for Error { fn from(e: SendError) -> Self { match e { - SendError::NotApplicable | SendError::Unroutable | SendError::MissingArgument => - Error::Unroutable, + SendError::NotApplicable | SendError::Unroutable | SendError::MissingArgument => { + Error::Unroutable + }, SendError::Transport(s) => Error::Transport(s), SendError::DestinationUnsupported => Error::DestinationUnsupported, SendError::ExceedsMaxMessageSize => Error::ExceedsMaxMessageSize, diff --git a/pezkuwi/xcm/src/v4/asset.rs b/pezkuwi/xcm/src/v4/asset.rs index b30173e2..cc94f815 100644 --- a/pezkuwi/xcm/src/v4/asset.rs +++ b/pezkuwi/xcm/src/v4/asset.rs @@ -313,8 +313,9 @@ impl Decode for Fungibility { match UncheckedFungibility::decode(input)? { UncheckedFungibility::Fungible(a) if a != 0 => Ok(Self::Fungible(a)), UncheckedFungibility::NonFungible(i) => Ok(Self::NonFungible(i)), - UncheckedFungibility::Fungible(_) => - Err("Fungible asset of zero amount is not allowed".into()), + UncheckedFungibility::Fungible(_) => { + Err("Fungible asset of zero amount is not allowed".into()) + }, } } } @@ -677,8 +678,9 @@ impl From> for Assets { ( Asset { fun: Fungibility::NonFungible(a_instance), id: a_id }, Asset { fun: Fungibility::NonFungible(b_instance), id: b_id }, - ) if a_id == b_id && a_instance == b_instance => - Asset { fun: Fungibility::NonFungible(a_instance), id: a_id }, + ) if a_id == b_id && a_instance == b_instance => { + Asset { fun: Fungibility::NonFungible(a_instance), id: a_id } + }, (to_push, to_remember) => { res.push(to_push); to_remember @@ -758,7 +760,9 @@ impl Assets { }, (Fungibility::NonFungible(inst1), Fungibility::NonFungible(inst2)) if inst1 == inst2 => - return, + { + return + }, _ => (), } } @@ -868,8 +872,9 @@ impl TryFrom for WildAsset { Ok(match old { AllOf { id, fun } => Self::AllOf { id: id.try_into()?, fun: fun.try_into()? }, All => Self::All, - AllOfCounted { id, fun, count } => - Self::AllOfCounted { id: id.try_into()?, fun: fun.try_into()?, count }, + AllOfCounted { id, fun, count } => { + Self::AllOfCounted { id: id.try_into()?, fun: fun.try_into()?, count } + }, AllCounted(count) => Self::AllCounted(count), }) } @@ -881,8 +886,9 @@ impl TryFrom for WildAsset { use NewWildAsset::*; Ok(match new { AllOf { id, fun } => Self::AllOf { id: id.try_into()?, fun: fun.try_into()? }, - AllOfCounted { id, fun, count } => - Self::AllOfCounted { id: id.try_into()?, fun: fun.try_into()?, count }, + AllOfCounted { id, fun, count } => { + Self::AllOfCounted { id: id.try_into()?, fun: fun.try_into()?, count } + }, All => Self::All, AllCounted(count) => Self::AllCounted(count), }) @@ -895,8 +901,9 @@ impl WildAsset { use WildAsset::*; match self { AllOfCounted { count: 0, .. } | AllCounted(0) => false, - AllOf { fun, id } | AllOfCounted { id, fun, .. } => - inner.fun.is_kind(*fun) && &inner.id == id, + AllOf { fun, id } | AllOfCounted { id, fun, .. } => { + inner.fun.is_kind(*fun) && &inner.id == id + }, All | AllCounted(_) => true, } } @@ -915,8 +922,9 @@ impl WildAsset { pub fn reanchor(&mut self, target: &Location, context: &InteriorLocation) -> Result<(), ()> { use WildAsset::*; match self { - AllOf { ref mut id, .. } | AllOfCounted { ref mut id, .. } => - id.reanchor(target, context), + AllOf { ref mut id, .. } | AllOfCounted { ref mut id, .. } => { + id.reanchor(target, context) + }, All | AllCounted(_) => Ok(()), } } diff --git a/pezkuwi/xcm/src/v4/junction.rs b/pezkuwi/xcm/src/v4/junction.rs index 9b9431e5..f344e476 100644 --- a/pezkuwi/xcm/src/v4/junction.rs +++ b/pezkuwi/xcm/src/v4/junction.rs @@ -230,8 +230,9 @@ impl<'a> TryFrom<&'a Junction> for BoundedSlice<'a, u8, ConstU32<32>> { type Error = (); fn try_from(key: &'a Junction) -> Result { match key { - Junction::GeneralKey { length, data } => - BoundedSlice::try_from(&data[..data.len().min(*length as usize)]).map_err(|_| ()), + Junction::GeneralKey { length, data } => { + BoundedSlice::try_from(&data[..data.len().min(*length as usize)]).map_err(|_| ()) + }, _ => Err(()), } } @@ -261,12 +262,15 @@ impl TryFrom for Junction { use OldJunction::*; Ok(match value { Teyrchain(id) => Self::Teyrchain(id), - AccountId32 { network: maybe_network, id } => - Self::AccountId32 { network: maybe_network.map(|network| network.into()), id }, - AccountIndex64 { network: maybe_network, index } => - Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index }, - AccountKey20 { network: maybe_network, key } => - Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key }, + AccountId32 { network: maybe_network, id } => { + Self::AccountId32 { network: maybe_network.map(|network| network.into()), id } + }, + AccountIndex64 { network: maybe_network, index } => { + Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index } + }, + AccountKey20 { network: maybe_network, key } => { + Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key } + }, PalletInstance(index) => Self::PalletInstance(index), GeneralIndex(id) => Self::GeneralIndex(id), GeneralKey { length, data } => Self::GeneralKey { length, data }, @@ -284,12 +288,15 @@ impl TryFrom for Junction { use NewJunction::*; Ok(match value { Teyrchain(id) => Self::Teyrchain(id), - AccountId32 { network: maybe_network, id } => - Self::AccountId32 { network: maybe_network.map(|network| network.into()), id }, - AccountIndex64 { network: maybe_network, index } => - Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index }, - AccountKey20 { network: maybe_network, key } => - Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key }, + AccountId32 { network: maybe_network, id } => { + Self::AccountId32 { network: maybe_network.map(|network| network.into()), id } + }, + AccountIndex64 { network: maybe_network, index } => { + Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index } + }, + AccountKey20 { network: maybe_network, key } => { + Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key } + }, PalletInstance(index) => Self::PalletInstance(index), GeneralIndex(id) => Self::GeneralIndex(id), GeneralKey { length, data } => Self::GeneralKey { length, data }, @@ -327,9 +334,9 @@ impl Junction { pub fn remove_network_id(&mut self) { use Junction::*; match self { - AccountId32 { ref mut network, .. } | - AccountIndex64 { ref mut network, .. } | - AccountKey20 { ref mut network, .. } => *network = None, + AccountId32 { ref mut network, .. } + | AccountIndex64 { ref mut network, .. } + | AccountKey20 { ref mut network, .. } => *network = None, _ => {}, } } diff --git a/pezkuwi/xcm/src/v4/mod.rs b/pezkuwi/xcm/src/v4/mod.rs index 84290f61..fa783d2a 100644 --- a/pezkuwi/xcm/src/v4/mod.rs +++ b/pezkuwi/xcm/src/v4/mod.rs @@ -313,8 +313,9 @@ impl TryFrom for Response { Ok(match old { Null => Self::Null, Assets(assets) => Self::Assets(assets.try_into()?), - ExecutionResult(result) => - Self::ExecutionResult(result.map(|(num, old_error)| (num, old_error.into()))), + ExecutionResult(result) => { + Self::ExecutionResult(result.map(|(num, old_error)| (num, old_error.into()))) + }, Version(version) => Self::Version(version), PalletsInfo(pezpallet_info) => { let inner = pezpallet_info @@ -354,8 +355,9 @@ impl TryFrom for Response { BoundedVec::::try_from(inner).map_err(|_| ())?, ) }, - DispatchResult(maybe_error) => - Self::DispatchResult(maybe_error.try_into().map_err(|_| ())?), + DispatchResult(maybe_error) => { + Self::DispatchResult(maybe_error.try_into().map_err(|_| ())?) + }, }) } } @@ -1111,24 +1113,30 @@ impl Instruction { WithdrawAsset(assets) => WithdrawAsset(assets), ReserveAssetDeposited(assets) => ReserveAssetDeposited(assets), ReceiveTeleportedAsset(assets) => ReceiveTeleportedAsset(assets), - QueryResponse { query_id, response, max_weight, querier } => - QueryResponse { query_id, response, max_weight, querier }, + QueryResponse { query_id, response, max_weight, querier } => { + QueryResponse { query_id, response, max_weight, querier } + }, TransferAsset { assets, beneficiary } => TransferAsset { assets, beneficiary }, - TransferReserveAsset { assets, dest, xcm } => - TransferReserveAsset { assets, dest, xcm }, - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, + TransferReserveAsset { assets, dest, xcm } => { + TransferReserveAsset { assets, dest, xcm } + }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => { + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } + }, HrmpChannelAccepted { recipient } => HrmpChannelAccepted { recipient }, - HrmpChannelClosing { initiator, sender, recipient } => - HrmpChannelClosing { initiator, sender, recipient }, - Transact { origin_kind, require_weight_at_most, call } => - Transact { origin_kind, require_weight_at_most, call: call.into() }, + HrmpChannelClosing { initiator, sender, recipient } => { + HrmpChannelClosing { initiator, sender, recipient } + }, + Transact { origin_kind, require_weight_at_most, call } => { + Transact { origin_kind, require_weight_at_most, call: call.into() } + }, ReportError(response_info) => ReportError(response_info), DepositAsset { assets, beneficiary } => DepositAsset { assets, beneficiary }, DepositReserveAsset { assets, dest, xcm } => DepositReserveAsset { assets, dest, xcm }, ExchangeAsset { give, want, maximal } => ExchangeAsset { give, want, maximal }, - InitiateReserveWithdraw { assets, reserve, xcm } => - InitiateReserveWithdraw { assets, reserve, xcm }, + InitiateReserveWithdraw { assets, reserve, xcm } => { + InitiateReserveWithdraw { assets, reserve, xcm } + }, InitiateTeleport { assets, dest, xcm } => InitiateTeleport { assets, dest, xcm }, ReportHolding { response_info, assets } => ReportHolding { response_info, assets }, BuyExecution { fees, weight_limit } => BuyExecution { fees, weight_limit }, @@ -1140,23 +1148,27 @@ impl Instruction { ClearError => ClearError, ClaimAsset { assets, ticket } => ClaimAsset { assets, ticket }, Trap(code) => Trap(code), - SubscribeVersion { query_id, max_response_weight } => - SubscribeVersion { query_id, max_response_weight }, + SubscribeVersion { query_id, max_response_weight } => { + SubscribeVersion { query_id, max_response_weight } + }, UnsubscribeVersion => UnsubscribeVersion, BurnAsset(assets) => BurnAsset(assets), ExpectAsset(assets) => ExpectAsset(assets), ExpectOrigin(origin) => ExpectOrigin(origin), ExpectError(error) => ExpectError(error), ExpectTransactStatus(transact_status) => ExpectTransactStatus(transact_status), - QueryPallet { module_name, response_info } => - QueryPallet { module_name, response_info }, - ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => - ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, + QueryPallet { module_name, response_info } => { + QueryPallet { module_name, response_info } + }, + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => { + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } + }, ReportTransactStatus(response_info) => ReportTransactStatus(response_info), ClearTransactStatus => ClearTransactStatus, UniversalOrigin(j) => UniversalOrigin(j), - ExportMessage { network, destination, xcm } => - ExportMessage { network, destination, xcm }, + ExportMessage { network, destination, xcm } => { + ExportMessage { network, destination, xcm } + }, LockAsset { asset, unlocker } => LockAsset { asset, unlocker }, UnlockAsset { asset, target } => UnlockAsset { asset, target }, NoteUnlockable { asset, owner } => NoteUnlockable { asset, owner }, @@ -1165,8 +1177,9 @@ impl Instruction { SetTopic(topic) => SetTopic(topic), ClearTopic => ClearTopic, AliasOrigin(location) => AliasOrigin(location), - UnpaidExecution { weight_limit, check_origin } => - UnpaidExecution { weight_limit, check_origin }, + UnpaidExecution { weight_limit, check_origin } => { + UnpaidExecution { weight_limit, check_origin } + }, } } } @@ -1179,27 +1192,34 @@ impl> GetWeight for Instruction { WithdrawAsset(assets) => W::withdraw_asset(assets), ReserveAssetDeposited(assets) => W::reserve_asset_deposited(assets), ReceiveTeleportedAsset(assets) => W::receive_teleported_asset(assets), - QueryResponse { query_id, response, max_weight, querier } => - W::query_response(query_id, response, max_weight, querier), + QueryResponse { query_id, response, max_weight, querier } => { + W::query_response(query_id, response, max_weight, querier) + }, TransferAsset { assets, beneficiary } => W::transfer_asset(assets, beneficiary), - TransferReserveAsset { assets, dest, xcm } => - W::transfer_reserve_asset(&assets, dest, xcm), - Transact { origin_kind, require_weight_at_most, call } => - W::transact(origin_kind, require_weight_at_most, call), - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => - W::hrmp_new_channel_open_request(sender, max_message_size, max_capacity), + TransferReserveAsset { assets, dest, xcm } => { + W::transfer_reserve_asset(&assets, dest, xcm) + }, + Transact { origin_kind, require_weight_at_most, call } => { + W::transact(origin_kind, require_weight_at_most, call) + }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => { + W::hrmp_new_channel_open_request(sender, max_message_size, max_capacity) + }, HrmpChannelAccepted { recipient } => W::hrmp_channel_accepted(recipient), - HrmpChannelClosing { initiator, sender, recipient } => - W::hrmp_channel_closing(initiator, sender, recipient), + HrmpChannelClosing { initiator, sender, recipient } => { + W::hrmp_channel_closing(initiator, sender, recipient) + }, ClearOrigin => W::clear_origin(), DescendOrigin(who) => W::descend_origin(who), ReportError(response_info) => W::report_error(&response_info), DepositAsset { assets, beneficiary } => W::deposit_asset(assets, beneficiary), - DepositReserveAsset { assets, dest, xcm } => - W::deposit_reserve_asset(assets, dest, xcm), + DepositReserveAsset { assets, dest, xcm } => { + W::deposit_reserve_asset(assets, dest, xcm) + }, ExchangeAsset { give, want, maximal } => W::exchange_asset(give, want, maximal), - InitiateReserveWithdraw { assets, reserve, xcm } => - W::initiate_reserve_withdraw(assets, reserve, xcm), + InitiateReserveWithdraw { assets, reserve, xcm } => { + W::initiate_reserve_withdraw(assets, reserve, xcm) + }, InitiateTeleport { assets, dest, xcm } => W::initiate_teleport(assets, dest, xcm), ReportHolding { response_info, assets } => W::report_holding(&response_info, &assets), BuyExecution { fees, weight_limit } => W::buy_execution(fees, weight_limit), @@ -1209,23 +1229,27 @@ impl> GetWeight for Instruction { ClearError => W::clear_error(), ClaimAsset { assets, ticket } => W::claim_asset(assets, ticket), Trap(code) => W::trap(code), - SubscribeVersion { query_id, max_response_weight } => - W::subscribe_version(query_id, max_response_weight), + SubscribeVersion { query_id, max_response_weight } => { + W::subscribe_version(query_id, max_response_weight) + }, UnsubscribeVersion => W::unsubscribe_version(), BurnAsset(assets) => W::burn_asset(assets), ExpectAsset(assets) => W::expect_asset(assets), ExpectOrigin(origin) => W::expect_origin(origin), ExpectError(error) => W::expect_error(error), ExpectTransactStatus(transact_status) => W::expect_transact_status(transact_status), - QueryPallet { module_name, response_info } => - W::query_pallet(module_name, response_info), - ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => - W::expect_pallet(index, name, module_name, crate_major, min_crate_minor), + QueryPallet { module_name, response_info } => { + W::query_pallet(module_name, response_info) + }, + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => { + W::expect_pallet(index, name, module_name, crate_major, min_crate_minor) + }, ReportTransactStatus(response_info) => W::report_transact_status(response_info), ClearTransactStatus => W::clear_transact_status(), UniversalOrigin(j) => W::universal_origin(j), - ExportMessage { network, destination, xcm } => - W::export_message(network, destination, xcm), + ExportMessage { network, destination, xcm } => { + W::export_message(network, destination, xcm) + }, LockAsset { asset, unlocker } => W::lock_asset(asset, unlocker), UnlockAsset { asset, target } => W::unlock_asset(asset, target), NoteUnlockable { asset, owner } => W::note_unlockable(asset, owner), @@ -1234,8 +1258,9 @@ impl> GetWeight for Instruction { SetTopic(topic) => W::set_topic(topic), ClearTopic => W::clear_topic(), AliasOrigin(location) => W::alias_origin(location), - UnpaidExecution { weight_limit, check_origin } => - W::unpaid_execution(weight_limit, check_origin), + UnpaidExecution { weight_limit, check_origin } => { + W::unpaid_execution(weight_limit, check_origin) + }, } } } @@ -1275,20 +1300,22 @@ impl TryFrom> for Instructi WithdrawAsset(assets) => Self::WithdrawAsset(assets.try_into()?), ReserveAssetDeposited(assets) => Self::ReserveAssetDeposited(assets.try_into()?), ReceiveTeleportedAsset(assets) => Self::ReceiveTeleportedAsset(assets.try_into()?), - QueryResponse { query_id, response, max_weight, querier: Some(querier) } => + QueryResponse { query_id, response, max_weight, querier: Some(querier) } => { Self::QueryResponse { query_id, querier: querier.try_into()?, response: response.try_into()?, max_weight, - }, - QueryResponse { query_id, response, max_weight, querier: None } => + } + }, + QueryResponse { query_id, response, max_weight, querier: None } => { Self::QueryResponse { query_id, querier: None, response: response.try_into()?, max_weight, - }, + } + }, TransferAsset { assets, beneficiary } => Self::TransferAsset { assets: assets.try_into()?, beneficiary: beneficiary.try_into()?, @@ -1298,11 +1325,13 @@ impl TryFrom> for Instructi dest: dest.try_into()?, xcm: xcm.try_into()?, }, - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => - Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => { + Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } + }, HrmpChannelAccepted { recipient } => Self::HrmpChannelAccepted { recipient }, - HrmpChannelClosing { initiator, sender, recipient } => - Self::HrmpChannelClosing { initiator, sender, recipient }, + HrmpChannelClosing { initiator, sender, recipient } => { + Self::HrmpChannelClosing { initiator, sender, recipient } + }, Transact { origin_kind, mut call, fallback_max_weight } => { // We first try to decode the call, if we can't, we use the fallback weight, // if there's no fallback, we just return `Weight::MAX`. @@ -1381,13 +1410,15 @@ impl TryFrom> for Instructi Self::ClaimAsset { assets, ticket } }, Trap(code) => Self::Trap(code), - SubscribeVersion { query_id, max_response_weight } => - Self::SubscribeVersion { query_id, max_response_weight }, + SubscribeVersion { query_id, max_response_weight } => { + Self::SubscribeVersion { query_id, max_response_weight } + }, UnsubscribeVersion => Self::UnsubscribeVersion, BurnAsset(assets) => Self::BurnAsset(assets.try_into()?), ExpectAsset(assets) => Self::ExpectAsset(assets.try_into()?), - ExpectOrigin(maybe_origin) => - Self::ExpectOrigin(maybe_origin.map(|origin| origin.try_into()).transpose()?), + ExpectOrigin(maybe_origin) => { + Self::ExpectOrigin(maybe_origin.map(|origin| origin.try_into()).transpose()?) + }, ExpectError(maybe_error) => Self::ExpectError( maybe_error .map(|(num, new_error)| (num, new_error.try_into())) @@ -1395,12 +1426,15 @@ impl TryFrom> for Instructi .transpose()?, ), ExpectTransactStatus(maybe_error_code) => Self::ExpectTransactStatus(maybe_error_code), - QueryPallet { module_name, response_info } => - Self::QueryPallet { module_name, response_info: response_info.try_into()? }, - ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => - Self::ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, - ReportTransactStatus(response_info) => - Self::ReportTransactStatus(response_info.try_into()?), + QueryPallet { module_name, response_info } => { + Self::QueryPallet { module_name, response_info: response_info.try_into()? } + }, + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => { + Self::ExpectPallet { index, name, module_name, crate_major, min_crate_minor } + }, + ReportTransactStatus(response_info) => { + Self::ReportTransactStatus(response_info.try_into()?) + }, ClearTransactStatus => Self::ClearTransactStatus, UniversalOrigin(junction) => Self::UniversalOrigin(junction.try_into()?), ExportMessage { network, destination, xcm } => Self::ExportMessage { @@ -1408,14 +1442,18 @@ impl TryFrom> for Instructi destination: destination.try_into()?, xcm: xcm.try_into()?, }, - LockAsset { asset, unlocker } => - Self::LockAsset { asset: asset.try_into()?, unlocker: unlocker.try_into()? }, - UnlockAsset { asset, target } => - Self::UnlockAsset { asset: asset.try_into()?, target: target.try_into()? }, - NoteUnlockable { asset, owner } => - Self::NoteUnlockable { asset: asset.try_into()?, owner: owner.try_into()? }, - RequestUnlock { asset, locker } => - Self::RequestUnlock { asset: asset.try_into()?, locker: locker.try_into()? }, + LockAsset { asset, unlocker } => { + Self::LockAsset { asset: asset.try_into()?, unlocker: unlocker.try_into()? } + }, + UnlockAsset { asset, target } => { + Self::UnlockAsset { asset: asset.try_into()?, target: target.try_into()? } + }, + NoteUnlockable { asset, owner } => { + Self::NoteUnlockable { asset: asset.try_into()?, owner: owner.try_into()? } + }, + RequestUnlock { asset, locker } => { + Self::RequestUnlock { asset: asset.try_into()?, locker: locker.try_into()? } + }, SetFeesMode { jit_withdraw } => Self::SetFeesMode { jit_withdraw }, SetTopic(topic) => Self::SetTopic(topic), ClearTopic => Self::ClearTopic, @@ -1424,10 +1462,10 @@ impl TryFrom> for Instructi weight_limit, check_origin: check_origin.map(|origin| origin.try_into()).transpose()?, }, - InitiateTransfer { .. } | - PayFees { .. } | - SetHints { .. } | - ExecuteWithOrigin { .. } => { + InitiateTransfer { .. } + | PayFees { .. } + | SetHints { .. } + | ExecuteWithOrigin { .. } => { tracing::debug!(target: "xcm::versions::v5tov4", ?new_instruction, "not supported by v4"); return Err(()); }, @@ -1444,20 +1482,22 @@ impl TryFrom> for Instruction { WithdrawAsset(assets) => Self::WithdrawAsset(assets.try_into()?), ReserveAssetDeposited(assets) => Self::ReserveAssetDeposited(assets.try_into()?), ReceiveTeleportedAsset(assets) => Self::ReceiveTeleportedAsset(assets.try_into()?), - QueryResponse { query_id, response, max_weight, querier: Some(querier) } => + QueryResponse { query_id, response, max_weight, querier: Some(querier) } => { Self::QueryResponse { query_id, querier: querier.try_into()?, response: response.try_into()?, max_weight, - }, - QueryResponse { query_id, response, max_weight, querier: None } => + } + }, + QueryResponse { query_id, response, max_weight, querier: None } => { Self::QueryResponse { query_id, querier: None, response: response.try_into()?, max_weight, - }, + } + }, TransferAsset { assets, beneficiary } => Self::TransferAsset { assets: assets.try_into()?, beneficiary: beneficiary.try_into()?, @@ -1467,13 +1507,16 @@ impl TryFrom> for Instruction { dest: dest.try_into()?, xcm: xcm.try_into()?, }, - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => - Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => { + Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } + }, HrmpChannelAccepted { recipient } => Self::HrmpChannelAccepted { recipient }, - HrmpChannelClosing { initiator, sender, recipient } => - Self::HrmpChannelClosing { initiator, sender, recipient }, - Transact { origin_kind, require_weight_at_most, call } => - Self::Transact { origin_kind, require_weight_at_most, call: call.into() }, + HrmpChannelClosing { initiator, sender, recipient } => { + Self::HrmpChannelClosing { initiator, sender, recipient } + }, + Transact { origin_kind, require_weight_at_most, call } => { + Self::Transact { origin_kind, require_weight_at_most, call: call.into() } + }, ReportError(response_info) => Self::ReportError(QueryResponseInfo { query_id: response_info.query_id, destination: response_info.destination.try_into().map_err(|_| ())?, @@ -1532,8 +1575,9 @@ impl TryFrom> for Instruction { Self::ClaimAsset { assets, ticket } }, Trap(code) => Self::Trap(code), - SubscribeVersion { query_id, max_response_weight } => - Self::SubscribeVersion { query_id, max_response_weight }, + SubscribeVersion { query_id, max_response_weight } => { + Self::SubscribeVersion { query_id, max_response_weight } + }, UnsubscribeVersion => Self::UnsubscribeVersion, BurnAsset(assets) => Self::BurnAsset(assets.try_into()?), ExpectAsset(assets) => Self::ExpectAsset(assets.try_into()?), @@ -1548,13 +1592,16 @@ impl TryFrom> for Instruction { module_name, response_info: response_info.try_into().map_err(|_| ())?, }, - ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => - Self::ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, - ReportTransactStatus(response_info) => - Self::ReportTransactStatus(response_info.try_into().map_err(|_| ())?), + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => { + Self::ExpectPallet { index, name, module_name, crate_major, min_crate_minor } + }, + ReportTransactStatus(response_info) => { + Self::ReportTransactStatus(response_info.try_into().map_err(|_| ())?) + }, ClearTransactStatus => Self::ClearTransactStatus, - UniversalOrigin(junction) => - Self::UniversalOrigin(junction.try_into().map_err(|_| ())?), + UniversalOrigin(junction) => { + Self::UniversalOrigin(junction.try_into().map_err(|_| ())?) + }, ExportMessage { network, destination, xcm } => Self::ExportMessage { network: network.into(), destination: destination.try_into().map_err(|_| ())?, diff --git a/pezkuwi/xcm/src/v5/asset.rs b/pezkuwi/xcm/src/v5/asset.rs index 84c97707..ddf972e1 100644 --- a/pezkuwi/xcm/src/v5/asset.rs +++ b/pezkuwi/xcm/src/v5/asset.rs @@ -280,8 +280,9 @@ impl Decode for Fungibility { match UncheckedFungibility::decode(input)? { UncheckedFungibility::Fungible(a) if a != 0 => Ok(Self::Fungible(a)), UncheckedFungibility::NonFungible(i) => Ok(Self::NonFungible(i)), - UncheckedFungibility::Fungible(_) => - Err("Fungible asset of zero amount is not allowed".into()), + UncheckedFungibility::Fungible(_) => { + Err("Fungible asset of zero amount is not allowed".into()) + }, } } } @@ -603,8 +604,9 @@ impl From> for Assets { ( Asset { fun: Fungibility::NonFungible(a_instance), id: a_id }, Asset { fun: Fungibility::NonFungible(b_instance), id: b_id }, - ) if a_id == b_id && a_instance == b_instance => - Asset { fun: Fungibility::NonFungible(a_instance), id: a_id }, + ) if a_id == b_id && a_instance == b_instance => { + Asset { fun: Fungibility::NonFungible(a_instance), id: a_id } + }, (to_push, to_remember) => { res.push(to_push); to_remember @@ -684,7 +686,9 @@ impl Assets { }, (Fungibility::NonFungible(inst1), Fungibility::NonFungible(inst2)) if inst1 == inst2 => - return, + { + return + }, _ => (), } } @@ -794,8 +798,9 @@ impl TryFrom for WildAsset { Ok(match old { AllOf { id, fun } => Self::AllOf { id: id.try_into()?, fun: fun.try_into()? }, All => Self::All, - AllOfCounted { id, fun, count } => - Self::AllOfCounted { id: id.try_into()?, fun: fun.try_into()?, count }, + AllOfCounted { id, fun, count } => { + Self::AllOfCounted { id: id.try_into()?, fun: fun.try_into()?, count } + }, AllCounted(count) => Self::AllCounted(count), }) } @@ -807,8 +812,9 @@ impl WildAsset { use WildAsset::*; match self { AllOfCounted { count: 0, .. } | AllCounted(0) => false, - AllOf { fun, id } | AllOfCounted { id, fun, .. } => - inner.fun.is_kind(*fun) && &inner.id == id, + AllOf { fun, id } | AllOfCounted { id, fun, .. } => { + inner.fun.is_kind(*fun) && &inner.id == id + }, All | AllCounted(_) => true, } } @@ -827,8 +833,9 @@ impl WildAsset { pub fn reanchor(&mut self, target: &Location, context: &InteriorLocation) -> Result<(), ()> { use WildAsset::*; match self { - AllOf { ref mut id, .. } | AllOfCounted { ref mut id, .. } => - id.reanchor(target, context), + AllOf { ref mut id, .. } | AllOfCounted { ref mut id, .. } => { + id.reanchor(target, context) + }, All | AllCounted(_) => Ok(()), } } diff --git a/pezkuwi/xcm/src/v5/junction.rs b/pezkuwi/xcm/src/v5/junction.rs index 465181c7..804105e3 100644 --- a/pezkuwi/xcm/src/v5/junction.rs +++ b/pezkuwi/xcm/src/v5/junction.rs @@ -217,8 +217,9 @@ impl<'a> TryFrom<&'a Junction> for BoundedSlice<'a, u8, ConstU32<32>> { type Error = (); fn try_from(key: &'a Junction) -> Result { match key { - Junction::GeneralKey { length, data } => - BoundedSlice::try_from(&data[..data.len().min(*length as usize)]).map_err(|_| ()), + Junction::GeneralKey { length, data } => { + BoundedSlice::try_from(&data[..data.len().min(*length as usize)]).map_err(|_| ()) + }, _ => Err(()), } } @@ -248,12 +249,15 @@ impl TryFrom for Junction { use OldJunction::*; Ok(match value { Teyrchain(id) => Self::Teyrchain(id), - AccountId32 { network: maybe_network, id } => - Self::AccountId32 { network: maybe_network.map(|network| network.into()), id }, - AccountIndex64 { network: maybe_network, index } => - Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index }, - AccountKey20 { network: maybe_network, key } => - Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key }, + AccountId32 { network: maybe_network, id } => { + Self::AccountId32 { network: maybe_network.map(|network| network.into()), id } + }, + AccountIndex64 { network: maybe_network, index } => { + Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index } + }, + AccountKey20 { network: maybe_network, key } => { + Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key } + }, PalletInstance(index) => Self::PalletInstance(index), GeneralIndex(id) => Self::GeneralIndex(id), GeneralKey { length, data } => Self::GeneralKey { length, data }, @@ -291,9 +295,9 @@ impl Junction { pub fn remove_network_id(&mut self) { use Junction::*; match self { - AccountId32 { ref mut network, .. } | - AccountIndex64 { ref mut network, .. } | - AccountKey20 { ref mut network, .. } => *network = None, + AccountId32 { ref mut network, .. } + | AccountIndex64 { ref mut network, .. } + | AccountKey20 { ref mut network, .. } => *network = None, _ => {}, } } diff --git a/pezkuwi/xcm/src/v5/mod.rs b/pezkuwi/xcm/src/v5/mod.rs index d8025371..cde65d93 100644 --- a/pezkuwi/xcm/src/v5/mod.rs +++ b/pezkuwi/xcm/src/v5/mod.rs @@ -1179,24 +1179,30 @@ impl Instruction { WithdrawAsset(assets) => WithdrawAsset(assets), ReserveAssetDeposited(assets) => ReserveAssetDeposited(assets), ReceiveTeleportedAsset(assets) => ReceiveTeleportedAsset(assets), - QueryResponse { query_id, response, max_weight, querier } => - QueryResponse { query_id, response, max_weight, querier }, + QueryResponse { query_id, response, max_weight, querier } => { + QueryResponse { query_id, response, max_weight, querier } + }, TransferAsset { assets, beneficiary } => TransferAsset { assets, beneficiary }, - TransferReserveAsset { assets, dest, xcm } => - TransferReserveAsset { assets, dest, xcm }, - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, + TransferReserveAsset { assets, dest, xcm } => { + TransferReserveAsset { assets, dest, xcm } + }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => { + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } + }, HrmpChannelAccepted { recipient } => HrmpChannelAccepted { recipient }, - HrmpChannelClosing { initiator, sender, recipient } => - HrmpChannelClosing { initiator, sender, recipient }, - Transact { origin_kind, call, fallback_max_weight } => - Transact { origin_kind, call: call.into(), fallback_max_weight }, + HrmpChannelClosing { initiator, sender, recipient } => { + HrmpChannelClosing { initiator, sender, recipient } + }, + Transact { origin_kind, call, fallback_max_weight } => { + Transact { origin_kind, call: call.into(), fallback_max_weight } + }, ReportError(response_info) => ReportError(response_info), DepositAsset { assets, beneficiary } => DepositAsset { assets, beneficiary }, DepositReserveAsset { assets, dest, xcm } => DepositReserveAsset { assets, dest, xcm }, ExchangeAsset { give, want, maximal } => ExchangeAsset { give, want, maximal }, - InitiateReserveWithdraw { assets, reserve, xcm } => - InitiateReserveWithdraw { assets, reserve, xcm }, + InitiateReserveWithdraw { assets, reserve, xcm } => { + InitiateReserveWithdraw { assets, reserve, xcm } + }, InitiateTeleport { assets, dest, xcm } => InitiateTeleport { assets, dest, xcm }, ReportHolding { response_info, assets } => ReportHolding { response_info, assets }, BuyExecution { fees, weight_limit } => BuyExecution { fees, weight_limit }, @@ -1209,23 +1215,27 @@ impl Instruction { SetHints { hints } => SetHints { hints }, ClaimAsset { assets, ticket } => ClaimAsset { assets, ticket }, Trap(code) => Trap(code), - SubscribeVersion { query_id, max_response_weight } => - SubscribeVersion { query_id, max_response_weight }, + SubscribeVersion { query_id, max_response_weight } => { + SubscribeVersion { query_id, max_response_weight } + }, UnsubscribeVersion => UnsubscribeVersion, BurnAsset(assets) => BurnAsset(assets), ExpectAsset(assets) => ExpectAsset(assets), ExpectOrigin(origin) => ExpectOrigin(origin), ExpectError(error) => ExpectError(error), ExpectTransactStatus(transact_status) => ExpectTransactStatus(transact_status), - QueryPallet { module_name, response_info } => - QueryPallet { module_name, response_info }, - ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => - ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, + QueryPallet { module_name, response_info } => { + QueryPallet { module_name, response_info } + }, + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => { + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } + }, ReportTransactStatus(response_info) => ReportTransactStatus(response_info), ClearTransactStatus => ClearTransactStatus, UniversalOrigin(j) => UniversalOrigin(j), - ExportMessage { network, destination, xcm } => - ExportMessage { network, destination, xcm }, + ExportMessage { network, destination, xcm } => { + ExportMessage { network, destination, xcm } + }, LockAsset { asset, unlocker } => LockAsset { asset, unlocker }, UnlockAsset { asset, target } => UnlockAsset { asset, target }, NoteUnlockable { asset, owner } => NoteUnlockable { asset, owner }, @@ -1234,13 +1244,16 @@ impl Instruction { SetTopic(topic) => SetTopic(topic), ClearTopic => ClearTopic, AliasOrigin(location) => AliasOrigin(location), - UnpaidExecution { weight_limit, check_origin } => - UnpaidExecution { weight_limit, check_origin }, + UnpaidExecution { weight_limit, check_origin } => { + UnpaidExecution { weight_limit, check_origin } + }, PayFees { asset } => PayFees { asset }, - InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm } => - InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm }, - ExecuteWithOrigin { descendant_origin, xcm } => - ExecuteWithOrigin { descendant_origin, xcm: xcm.into() }, + InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm } => { + InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm } + }, + ExecuteWithOrigin { descendant_origin, xcm } => { + ExecuteWithOrigin { descendant_origin, xcm: xcm.into() } + }, } } } @@ -1253,27 +1266,34 @@ impl> GetWeight for Instruction { WithdrawAsset(assets) => W::withdraw_asset(assets), ReserveAssetDeposited(assets) => W::reserve_asset_deposited(assets), ReceiveTeleportedAsset(assets) => W::receive_teleported_asset(assets), - QueryResponse { query_id, response, max_weight, querier } => - W::query_response(query_id, response, max_weight, querier), + QueryResponse { query_id, response, max_weight, querier } => { + W::query_response(query_id, response, max_weight, querier) + }, TransferAsset { assets, beneficiary } => W::transfer_asset(assets, beneficiary), - TransferReserveAsset { assets, dest, xcm } => - W::transfer_reserve_asset(&assets, dest, xcm), - Transact { origin_kind, fallback_max_weight, call } => - W::transact(origin_kind, fallback_max_weight, call), - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => - W::hrmp_new_channel_open_request(sender, max_message_size, max_capacity), + TransferReserveAsset { assets, dest, xcm } => { + W::transfer_reserve_asset(&assets, dest, xcm) + }, + Transact { origin_kind, fallback_max_weight, call } => { + W::transact(origin_kind, fallback_max_weight, call) + }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => { + W::hrmp_new_channel_open_request(sender, max_message_size, max_capacity) + }, HrmpChannelAccepted { recipient } => W::hrmp_channel_accepted(recipient), - HrmpChannelClosing { initiator, sender, recipient } => - W::hrmp_channel_closing(initiator, sender, recipient), + HrmpChannelClosing { initiator, sender, recipient } => { + W::hrmp_channel_closing(initiator, sender, recipient) + }, ClearOrigin => W::clear_origin(), DescendOrigin(who) => W::descend_origin(who), ReportError(response_info) => W::report_error(&response_info), DepositAsset { assets, beneficiary } => W::deposit_asset(assets, beneficiary), - DepositReserveAsset { assets, dest, xcm } => - W::deposit_reserve_asset(assets, dest, xcm), + DepositReserveAsset { assets, dest, xcm } => { + W::deposit_reserve_asset(assets, dest, xcm) + }, ExchangeAsset { give, want, maximal } => W::exchange_asset(give, want, maximal), - InitiateReserveWithdraw { assets, reserve, xcm } => - W::initiate_reserve_withdraw(assets, reserve, xcm), + InitiateReserveWithdraw { assets, reserve, xcm } => { + W::initiate_reserve_withdraw(assets, reserve, xcm) + }, InitiateTeleport { assets, dest, xcm } => W::initiate_teleport(assets, dest, xcm), ReportHolding { response_info, assets } => W::report_holding(&response_info, &assets), BuyExecution { fees, weight_limit } => W::buy_execution(fees, weight_limit), @@ -1284,23 +1304,27 @@ impl> GetWeight for Instruction { SetHints { hints } => W::set_hints(hints), ClaimAsset { assets, ticket } => W::claim_asset(assets, ticket), Trap(code) => W::trap(code), - SubscribeVersion { query_id, max_response_weight } => - W::subscribe_version(query_id, max_response_weight), + SubscribeVersion { query_id, max_response_weight } => { + W::subscribe_version(query_id, max_response_weight) + }, UnsubscribeVersion => W::unsubscribe_version(), BurnAsset(assets) => W::burn_asset(assets), ExpectAsset(assets) => W::expect_asset(assets), ExpectOrigin(origin) => W::expect_origin(origin), ExpectError(error) => W::expect_error(error), ExpectTransactStatus(transact_status) => W::expect_transact_status(transact_status), - QueryPallet { module_name, response_info } => - W::query_pallet(module_name, response_info), - ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => - W::expect_pallet(index, name, module_name, crate_major, min_crate_minor), + QueryPallet { module_name, response_info } => { + W::query_pallet(module_name, response_info) + }, + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => { + W::expect_pallet(index, name, module_name, crate_major, min_crate_minor) + }, ReportTransactStatus(response_info) => W::report_transact_status(response_info), ClearTransactStatus => W::clear_transact_status(), UniversalOrigin(j) => W::universal_origin(j), - ExportMessage { network, destination, xcm } => - W::export_message(network, destination, xcm), + ExportMessage { network, destination, xcm } => { + W::export_message(network, destination, xcm) + }, LockAsset { asset, unlocker } => W::lock_asset(asset, unlocker), UnlockAsset { asset, target } => W::unlock_asset(asset, target), NoteUnlockable { asset, owner } => W::note_unlockable(asset, owner), @@ -1309,13 +1333,16 @@ impl> GetWeight for Instruction { SetTopic(topic) => W::set_topic(topic), ClearTopic => W::clear_topic(), AliasOrigin(location) => W::alias_origin(location), - UnpaidExecution { weight_limit, check_origin } => - W::unpaid_execution(weight_limit, check_origin), + UnpaidExecution { weight_limit, check_origin } => { + W::unpaid_execution(weight_limit, check_origin) + }, PayFees { asset } => W::pay_fees(asset), - InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm } => - W::initiate_transfer(destination, remote_fees, preserve_origin, assets, remote_xcm), - ExecuteWithOrigin { descendant_origin, xcm } => - W::execute_with_origin(descendant_origin, xcm), + InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm } => { + W::initiate_transfer(destination, remote_fees, preserve_origin, assets, remote_xcm) + }, + ExecuteWithOrigin { descendant_origin, xcm } => { + W::execute_with_origin(descendant_origin, xcm) + }, } } } @@ -1347,20 +1374,22 @@ impl TryFrom> for Instruction { WithdrawAsset(assets) => Self::WithdrawAsset(assets.try_into()?), ReserveAssetDeposited(assets) => Self::ReserveAssetDeposited(assets.try_into()?), ReceiveTeleportedAsset(assets) => Self::ReceiveTeleportedAsset(assets.try_into()?), - QueryResponse { query_id, response, max_weight, querier: Some(querier) } => + QueryResponse { query_id, response, max_weight, querier: Some(querier) } => { Self::QueryResponse { query_id, querier: querier.try_into()?, response: response.try_into()?, max_weight, - }, - QueryResponse { query_id, response, max_weight, querier: None } => + } + }, + QueryResponse { query_id, response, max_weight, querier: None } => { Self::QueryResponse { query_id, querier: None, response: response.try_into()?, max_weight, - }, + } + }, TransferAsset { assets, beneficiary } => Self::TransferAsset { assets: assets.try_into()?, beneficiary: beneficiary.try_into()?, @@ -1370,11 +1399,13 @@ impl TryFrom> for Instruction { dest: dest.try_into()?, xcm: xcm.try_into()?, }, - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => - Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => { + Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } + }, HrmpChannelAccepted { recipient } => Self::HrmpChannelAccepted { recipient }, - HrmpChannelClosing { initiator, sender, recipient } => - Self::HrmpChannelClosing { initiator, sender, recipient }, + HrmpChannelClosing { initiator, sender, recipient } => { + Self::HrmpChannelClosing { initiator, sender, recipient } + }, Transact { origin_kind, require_weight_at_most, call } => Self::Transact { origin_kind, call: call.into(), @@ -1438,8 +1469,9 @@ impl TryFrom> for Instruction { Self::ClaimAsset { assets, ticket } }, Trap(code) => Self::Trap(code), - SubscribeVersion { query_id, max_response_weight } => - Self::SubscribeVersion { query_id, max_response_weight }, + SubscribeVersion { query_id, max_response_weight } => { + Self::SubscribeVersion { query_id, max_response_weight } + }, UnsubscribeVersion => Self::UnsubscribeVersion, BurnAsset(assets) => Self::BurnAsset(assets.try_into()?), ExpectAsset(assets) => Self::ExpectAsset(assets.try_into()?), @@ -1458,13 +1490,16 @@ impl TryFrom> for Instruction { module_name, response_info: response_info.try_into().map_err(|_| ())?, }, - ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => - Self::ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, - ReportTransactStatus(response_info) => - Self::ReportTransactStatus(response_info.try_into().map_err(|_| ())?), + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => { + Self::ExpectPallet { index, name, module_name, crate_major, min_crate_minor } + }, + ReportTransactStatus(response_info) => { + Self::ReportTransactStatus(response_info.try_into().map_err(|_| ())?) + }, ClearTransactStatus => Self::ClearTransactStatus, - UniversalOrigin(junction) => - Self::UniversalOrigin(junction.try_into().map_err(|_| ())?), + UniversalOrigin(junction) => { + Self::UniversalOrigin(junction.try_into().map_err(|_| ())?) + }, ExportMessage { network, destination, xcm } => Self::ExportMessage { network: network.into(), destination: destination.try_into().map_err(|_| ())?, diff --git a/pezkuwi/xcm/src/v5/traits.rs b/pezkuwi/xcm/src/v5/traits.rs index a11700b0..6e2799ec 100644 --- a/pezkuwi/xcm/src/v5/traits.rs +++ b/pezkuwi/xcm/src/v5/traits.rs @@ -230,8 +230,9 @@ impl TryFrom for Error { impl From for Error { fn from(e: SendError) -> Self { match e { - SendError::NotApplicable | SendError::Unroutable | SendError::MissingArgument => - Error::Unroutable, + SendError::NotApplicable | SendError::Unroutable | SendError::MissingArgument => { + Error::Unroutable + }, SendError::Transport(s) => Error::Transport(s), SendError::DestinationUnsupported => Error::DestinationUnsupported, SendError::ExceedsMaxMessageSize => Error::ExceedsMaxMessageSize, diff --git a/pezkuwi/xcm/xcm-builder/src/asset_conversion.rs b/pezkuwi/xcm/xcm-builder/src/asset_conversion.rs index 9a5d70e7..e81bcc30 100644 --- a/pezkuwi/xcm/xcm-builder/src/asset_conversion.rs +++ b/pezkuwi/xcm/xcm-builder/src/asset_conversion.rs @@ -41,8 +41,8 @@ impl< let prefix = Prefix::get(); let latest_prefix: Location = prefix.try_into().ok()?; let latest_id: Location = (*id).clone().try_into().ok()?; - if latest_prefix.parent_count() != latest_id.parent_count() || - latest_prefix + if latest_prefix.parent_count() != latest_id.parent_count() + || latest_prefix .interior() .iter() .enumerate() @@ -149,8 +149,9 @@ impl< { fn matches_nonfungibles(a: &Asset) -> result::Result<(ClassId, InstanceId), MatchError> { let (instance, class) = match (&a.fun, &a.id) { - (NonFungible(ref instance), AssetId(ref class)) if MatchClassId::contains(class) => - (instance, class), + (NonFungible(ref instance), AssetId(ref class)) if MatchClassId::contains(class) => { + (instance, class) + }, _ => return Err(MatchError::AssetNotHandled), }; let what = ConvertClassId::convert(class).ok_or(MatchError::AssetIdConversionFailed)?; diff --git a/pezkuwi/xcm/xcm-builder/src/asset_exchange/single_asset_adapter/mock.rs b/pezkuwi/xcm/xcm-builder/src/asset_exchange/single_asset_adapter/mock.rs index 5c45dc60..f80ef774 100644 --- a/pezkuwi/xcm/xcm-builder/src/asset_exchange/single_asset_adapter/mock.rs +++ b/pezkuwi/xcm/xcm-builder/src/asset_exchange/single_asset_adapter/mock.rs @@ -188,7 +188,9 @@ impl MaybeEquivalence> for LocationToAssetId { match location.unpack() { (0, [PalletInstance(instance), GeneralIndex(index)]) if *instance == pezpallet_instance => - Some(NativeOrWithId::WithId(*index as u32)), + { + Some(NativeOrWithId::WithId(*index as u32)) + }, (0, []) => Some(NativeOrWithId::Native), _ => None, } @@ -197,8 +199,9 @@ impl MaybeEquivalence> for LocationToAssetId { fn convert_back(asset_id: &NativeOrWithId) -> Option { let pezpallet_instance = TrustBackedAssetsPalletIndex::get(); Some(match asset_id { - NativeOrWithId::WithId(id) => - Location::new(0, [PalletInstance(pezpallet_instance), GeneralIndex((*id).into())]), + NativeOrWithId::WithId(id) => { + Location::new(0, [PalletInstance(pezpallet_instance), GeneralIndex((*id).into())]) + }, NativeOrWithId::Native => Location::new(0, []), }) } @@ -282,8 +285,9 @@ where { fn try_convert(o: RuntimeOrigin) -> Result { o.try_with_caller(|caller| match caller.try_into() { - Ok(pezframe_system::RawOrigin::Signed(who)) => - Ok(Junction::AccountIndex64 { network: Network::get(), index: who.into() }.into()), + Ok(pezframe_system::RawOrigin::Signed(who)) => { + Ok(Junction::AccountIndex64 { network: Network::get(), index: who.into() }.into()) + }, Ok(other) => Err(other.into()), Err(other) => Err(other), }) diff --git a/pezkuwi/xcm/xcm-builder/src/barriers.rs b/pezkuwi/xcm/xcm-builder/src/barriers.rs index ce423e74..4e4c6f5c 100644 --- a/pezkuwi/xcm/xcm-builder/src/barriers.rs +++ b/pezkuwi/xcm/xcm-builder/src/barriers.rs @@ -88,21 +88,22 @@ impl> ShouldExecute for AllowTopLevelPaidExecutionFrom instructions[..end] .matcher() .match_next_inst(|inst| match inst { - WithdrawAsset(ref assets) | - ReceiveTeleportedAsset(ref assets) | - ReserveAssetDeposited(ref assets) | - ClaimAsset { ref assets, .. } => + WithdrawAsset(ref assets) + | ReceiveTeleportedAsset(ref assets) + | ReserveAssetDeposited(ref assets) + | ClaimAsset { ref assets, .. } => { if assets.len() <= MAX_ASSETS_FOR_BUY_EXECUTION { Ok(()) } else { Err(ProcessMessageError::BadFormat) - }, + } + }, _ => Err(ProcessMessageError::BadFormat), })? .skip_inst_while(|inst| { - matches!(inst, ClearOrigin | AliasOrigin(..)) || - matches!(inst, DescendOrigin(child) if child != &Here) || - matches!(inst, SetHints { .. }) + matches!(inst, ClearOrigin | AliasOrigin(..)) + || matches!(inst, DescendOrigin(child) if child != &Here) + || matches!(inst, SetHints { .. }) })? .match_next_inst(|inst| match inst { BuyExecution { weight_limit: Limited(ref mut weight), .. } @@ -343,12 +344,12 @@ impl, Aliasers: ContainsPair> ShouldEx // We skip set hints and all types of asset transfer instructions. .match_next_inst_while( |inst| { - processed.get() < instructions_to_process && - matches!( + processed.get() < instructions_to_process + && matches!( inst, - ReceiveTeleportedAsset(_) | - ReserveAssetDeposited(_) | WithdrawAsset(_) | - SetHints { .. } + ReceiveTeleportedAsset(_) + | ReserveAssetDeposited(_) + | WithdrawAsset(_) | SetHints { .. } ) }, |_| { @@ -367,12 +368,13 @@ impl, Aliasers: ContainsPair> ShouldEx // to know the origin to know if it's allowed unpaid execution. return Err(ProcessMessageError::Unsupported); }, - AliasOrigin(target) => + AliasOrigin(target) => { if Aliasers::contains(&actual_origin, &target) { actual_origin = target.clone(); } else { return Err(ProcessMessageError::Unsupported); - }, + } + }, DescendOrigin(child) if child != &Here => { let Ok(_) = actual_origin.append_with(child.clone()) else { return Err(ProcessMessageError::Unsupported); @@ -454,7 +456,9 @@ impl ShouldExecute for AllowKnownQueryResponses - Ok(()), + { + Ok(()) + }, _ => Err(ProcessMessageError::BadFormat), })?; Ok(()) @@ -514,9 +518,9 @@ impl ShouldExecute for AllowHrmpNotificationsFromRelayChain { .matcher() .assert_remaining_insts(1)? .match_next_inst(|inst| match inst { - HrmpNewChannelOpenRequest { .. } | - HrmpChannelAccepted { .. } | - HrmpChannelClosing { .. } => Ok(()), + HrmpNewChannelOpenRequest { .. } + | HrmpChannelAccepted { .. } + | HrmpChannelClosing { .. } => Ok(()), _ => Err(ProcessMessageError::BadFormat), })?; Ok(()) @@ -561,9 +565,9 @@ impl DenyExecution for DenyReserveTransferToRelayChain { InitiateReserveWithdraw { reserve: Location { parents: 1, interior: Here }, .. - } | - DepositReserveAsset { dest: Location { parents: 1, interior: Here }, .. } | - TransferReserveAsset { dest: Location { parents: 1, interior: Here }, .. } => { + } + | DepositReserveAsset { dest: Location { parents: 1, interior: Here }, .. } + | TransferReserveAsset { dest: Location { parents: 1, interior: Here }, .. } => { Err(ProcessMessageError::Unsupported) // Deny }, @@ -665,9 +669,9 @@ impl DenyExecution for DenyRecursively { instructions.matcher().match_next_inst_while( |_| true, |inst| match inst { - SetAppendix(nested_xcm) | - SetErrorHandler(nested_xcm) | - ExecuteWithOrigin { xcm: nested_xcm, .. } => Self::deny_recursively::( + SetAppendix(nested_xcm) + | SetErrorHandler(nested_xcm) + | ExecuteWithOrigin { xcm: nested_xcm, .. } => Self::deny_recursively::( origin, nested_xcm, max_weight, properties, ), _ => Ok(ControlFlow::Continue(())), diff --git a/pezkuwi/xcm/xcm-builder/src/currency_adapter.rs b/pezkuwi/xcm/xcm-builder/src/currency_adapter.rs index d7e68e3a..03e9b61b 100644 --- a/pezkuwi/xcm/xcm-builder/src/currency_adapter.rs +++ b/pezkuwi/xcm/xcm-builder/src/currency_adapter.rs @@ -151,10 +151,12 @@ impl< let amount: Currency::Balance = Matcher::matches_fungible(what).ok_or(Error::AssetNotHandled)?; match CheckedAccount::get() { - Some((checked_account, MintLocation::Local)) => - Self::can_reduce_checked(checked_account, amount), - Some((checked_account, MintLocation::NonLocal)) => - Self::can_accrue_checked(checked_account, amount), + Some((checked_account, MintLocation::Local)) => { + Self::can_reduce_checked(checked_account, amount) + }, + Some((checked_account, MintLocation::NonLocal)) => { + Self::can_accrue_checked(checked_account, amount) + }, None => Ok(()), } } @@ -163,10 +165,12 @@ impl< tracing::trace!(target: "xcm::currency_adapter", ?origin, ?what, "check_in origin"); if let Some(amount) = Matcher::matches_fungible(what) { match CheckedAccount::get() { - Some((checked_account, MintLocation::Local)) => - Self::reduce_checked(checked_account, amount), - Some((checked_account, MintLocation::NonLocal)) => - Self::accrue_checked(checked_account, amount), + Some((checked_account, MintLocation::Local)) => { + Self::reduce_checked(checked_account, amount) + }, + Some((checked_account, MintLocation::NonLocal)) => { + Self::accrue_checked(checked_account, amount) + }, None => (), } } @@ -176,10 +180,12 @@ impl< tracing::trace!(target: "xcm::currency_adapter", ?dest, ?what, "can_check_out"); let amount = Matcher::matches_fungible(what).ok_or(Error::AssetNotHandled)?; match CheckedAccount::get() { - Some((checked_account, MintLocation::Local)) => - Self::can_accrue_checked(checked_account, amount), - Some((checked_account, MintLocation::NonLocal)) => - Self::can_reduce_checked(checked_account, amount), + Some((checked_account, MintLocation::Local)) => { + Self::can_accrue_checked(checked_account, amount) + }, + Some((checked_account, MintLocation::NonLocal)) => { + Self::can_reduce_checked(checked_account, amount) + }, None => Ok(()), } } @@ -188,10 +194,12 @@ impl< tracing::trace!(target: "xcm::currency_adapter", ?dest, ?what, "check_out"); if let Some(amount) = Matcher::matches_fungible(what) { match CheckedAccount::get() { - Some((checked_account, MintLocation::Local)) => - Self::accrue_checked(checked_account, amount), - Some((checked_account, MintLocation::NonLocal)) => - Self::reduce_checked(checked_account, amount), + Some((checked_account, MintLocation::Local)) => { + Self::accrue_checked(checked_account, amount) + }, + Some((checked_account, MintLocation::NonLocal)) => { + Self::reduce_checked(checked_account, amount) + }, None => (), } } diff --git a/pezkuwi/xcm/xcm-builder/src/fungible_adapter.rs b/pezkuwi/xcm/xcm-builder/src/fungible_adapter.rs index 526cdee5..2e4c2a7b 100644 --- a/pezkuwi/xcm/xcm-builder/src/fungible_adapter.rs +++ b/pezkuwi/xcm/xcm-builder/src/fungible_adapter.rs @@ -140,10 +140,12 @@ impl< // Check we handle this asset let amount = Matcher::matches_fungible(what).ok_or(MatchError::AssetNotHandled)?; match CheckingAccount::get() { - Some((checking_account, MintLocation::Local)) => - Self::can_reduce_checked(checking_account, amount), - Some((checking_account, MintLocation::NonLocal)) => - Self::can_accrue_checked(checking_account, amount), + Some((checking_account, MintLocation::Local)) => { + Self::can_reduce_checked(checking_account, amount) + }, + Some((checking_account, MintLocation::NonLocal)) => { + Self::can_accrue_checked(checking_account, amount) + }, None => Ok(()), } } @@ -156,10 +158,12 @@ impl< ); if let Some(amount) = Matcher::matches_fungible(what) { match CheckingAccount::get() { - Some((checking_account, MintLocation::Local)) => - Self::reduce_checked(checking_account, amount), - Some((checking_account, MintLocation::NonLocal)) => - Self::accrue_checked(checking_account, amount), + Some((checking_account, MintLocation::Local)) => { + Self::reduce_checked(checking_account, amount) + }, + Some((checking_account, MintLocation::NonLocal)) => { + Self::accrue_checked(checking_account, amount) + }, None => (), } } @@ -174,10 +178,12 @@ impl< ); let amount = Matcher::matches_fungible(what).ok_or(MatchError::AssetNotHandled)?; match CheckingAccount::get() { - Some((checking_account, MintLocation::Local)) => - Self::can_accrue_checked(checking_account, amount), - Some((checking_account, MintLocation::NonLocal)) => - Self::can_reduce_checked(checking_account, amount), + Some((checking_account, MintLocation::Local)) => { + Self::can_accrue_checked(checking_account, amount) + }, + Some((checking_account, MintLocation::NonLocal)) => { + Self::can_reduce_checked(checking_account, amount) + }, None => Ok(()), } } @@ -191,10 +197,12 @@ impl< ); if let Some(amount) = Matcher::matches_fungible(what) { match CheckingAccount::get() { - Some((checking_account, MintLocation::Local)) => - Self::accrue_checked(checking_account, amount), - Some((checking_account, MintLocation::NonLocal)) => - Self::reduce_checked(checking_account, amount), + Some((checking_account, MintLocation::Local)) => { + Self::accrue_checked(checking_account, amount) + }, + Some((checking_account, MintLocation::NonLocal)) => { + Self::reduce_checked(checking_account, amount) + }, None => (), } } diff --git a/pezkuwi/xcm/xcm-builder/src/location_conversion.rs b/pezkuwi/xcm/xcm-builder/src/location_conversion.rs index e55f68fd..ea44d25a 100644 --- a/pezkuwi/xcm/xcm-builder/src/location_conversion.rs +++ b/pezkuwi/xcm/xcm-builder/src/location_conversion.rs @@ -58,8 +58,9 @@ pub struct DescribePalletTerminal; impl DescribeLocation for DescribePalletTerminal { fn describe_location(l: &Location) -> Option> { match l.unpack() { - (0, [PalletInstance(i)]) => - Some((b"Pezpallet", Compact::::from(*i as u32)).encode()), + (0, [PalletInstance(i)]) => { + Some((b"Pezpallet", Compact::::from(*i as u32)).encode()) + }, _ => return None, } } @@ -92,8 +93,9 @@ pub struct DescribeTreasuryVoiceTerminal; impl DescribeLocation for DescribeTreasuryVoiceTerminal { fn describe_location(location: &Location) -> Option> { match location.unpack() { - (0, [Plurality { id: BodyId::Treasury, part: BodyPart::Voice }]) => - Some((b"Treasury", b"Voice").encode()), + (0, [Plurality { id: BodyId::Treasury, part: BodyPart::Voice }]) => { + Some((b"Treasury", b"Voice").encode()) + }, _ => None, } } @@ -161,24 +163,29 @@ impl DescribeLocation for LegacyDescribeForeignChainAccount { fn describe_location(location: &Location) -> Option> { Some(match location.unpack() { // Used on the relay chain for sending paras that use 32 byte accounts - (0, [Teyrchain(para_id), AccountId32 { id, .. }]) => - LegacyDescribeForeignChainAccount::from_para_32(para_id, id, 0), + (0, [Teyrchain(para_id), AccountId32 { id, .. }]) => { + LegacyDescribeForeignChainAccount::from_para_32(para_id, id, 0) + }, // Used on the relay chain for sending paras that use 20 byte accounts - (0, [Teyrchain(para_id), AccountKey20 { key, .. }]) => - LegacyDescribeForeignChainAccount::from_para_20(para_id, key, 0), + (0, [Teyrchain(para_id), AccountKey20 { key, .. }]) => { + LegacyDescribeForeignChainAccount::from_para_20(para_id, key, 0) + }, // Used on para-chain for sending paras that use 32 byte accounts - (1, [Teyrchain(para_id), AccountId32 { id, .. }]) => - LegacyDescribeForeignChainAccount::from_para_32(para_id, id, 1), + (1, [Teyrchain(para_id), AccountId32 { id, .. }]) => { + LegacyDescribeForeignChainAccount::from_para_32(para_id, id, 1) + }, // Used on para-chain for sending paras that use 20 byte accounts - (1, [Teyrchain(para_id), AccountKey20 { key, .. }]) => - LegacyDescribeForeignChainAccount::from_para_20(para_id, key, 1), + (1, [Teyrchain(para_id), AccountKey20 { key, .. }]) => { + LegacyDescribeForeignChainAccount::from_para_20(para_id, key, 1) + }, // Used on para-chain for sending from the relay chain - (1, [AccountId32 { id, .. }]) => - LegacyDescribeForeignChainAccount::from_relay_32(id, 1), + (1, [AccountId32 { id, .. }]) => { + LegacyDescribeForeignChainAccount::from_relay_32(id, 1) + }, // No other conversions provided _ => return None, @@ -343,8 +350,9 @@ impl, AccountId: From<[u8; 32]> + Into<[u8; 32]> { fn convert_location(location: &Location) -> Option { match location.unpack() { - (0, [Plurality { id: BodyId::Treasury, part: BodyPart::Voice }]) => - Some((TreasuryAccount::get().into() as [u8; 32]).into()), + (0, [Plurality { id: BodyId::Treasury, part: BodyPart::Voice }]) => { + Some((TreasuryAccount::get().into() as [u8; 32]).into()) + }, _ => None, } } @@ -447,8 +455,9 @@ impl, AccountId: From<[u8; 32]> + Clone let (remote_network, remote_location) = devolved; match remote_location.as_slice() { - [Teyrchain(remote_network_para_id)] => - Some(AccountId::from(Self::from_params(&remote_network, &remote_network_para_id))), + [Teyrchain(remote_network_para_id)] => { + Some(AccountId::from(Self::from_params(&remote_network, &remote_network_para_id))) + }, _ => None, } } @@ -492,16 +501,18 @@ impl, AccountId: From<[u8; 32]> + Clone // equivalent to `EthereumLocationsConverterFor` [] => (b"ethereum-chain", chain_id).using_encoded(blake2_256).into(), // equivalent to `EthereumLocationsConverterFor` - [AccountKey20 { network: _, key }] => - (b"ethereum-chain", chain_id, *key).using_encoded(blake2_256).into(), + [AccountKey20 { network: _, key }] => { + (b"ethereum-chain", chain_id, *key).using_encoded(blake2_256).into() + }, // extends `EthereumLocationsConverterFor` tail => (b"ethereum-chain", chain_id, tail).using_encoded(blake2_256).into(), } } else { match remote_location.as_slice() { // equivalent to `GlobalConsensusTeyrchainConvertsFor` - [Teyrchain(para_id)] => - (b"glblcnsnss/prchn_", remote_network, para_id).using_encoded(blake2_256).into(), + [Teyrchain(para_id)] => { + (b"glblcnsnss/prchn_", remote_network, para_id).using_encoded(blake2_256).into() + }, // converts everything else based on hash of encoded location tail tail => (b"glblcnsnss", remote_network, tail).using_encoded(blake2_256).into(), } diff --git a/pezkuwi/xcm/xcm-builder/src/matches_location.rs b/pezkuwi/xcm/xcm-builder/src/matches_location.rs index 696f3569..75982422 100644 --- a/pezkuwi/xcm/xcm-builder/src/matches_location.rs +++ b/pezkuwi/xcm/xcm-builder/src/matches_location.rs @@ -32,7 +32,8 @@ impl, L: TryInto + Clone> Contains for StartsWith { } else { return false; }; - let latest_t = if let Ok(location) = T::get().try_into() { location } else { return false }; + let latest_t = + if let Ok(location) = T::get().try_into() { location } else { return false }; latest_location.starts_with(&latest_t) } } diff --git a/pezkuwi/xcm/xcm-builder/src/nonfungible_adapter.rs b/pezkuwi/xcm/xcm-builder/src/nonfungible_adapter.rs index 06fce7c6..0421b747 100644 --- a/pezkuwi/xcm/xcm-builder/src/nonfungible_adapter.rs +++ b/pezkuwi/xcm/xcm-builder/src/nonfungible_adapter.rs @@ -142,8 +142,9 @@ where let instance = Matcher::matches_nonfungible(what).ok_or(MatchError::AssetNotHandled)?; match CheckingAccount::get() { // We track this asset's teleports to ensure no more come in than have gone out. - Some((checking_account, MintLocation::Local)) => - Self::can_reduce_checked(checking_account, instance), + Some((checking_account, MintLocation::Local)) => { + Self::can_reduce_checked(checking_account, instance) + }, // We track this asset's teleports to ensure no more go out than have come in. Some((_, MintLocation::NonLocal)) => Self::can_accrue_checked(instance), _ => Ok(()), @@ -163,8 +164,9 @@ where // We track this asset's teleports to ensure no more come in than have gone out. Some((_, MintLocation::Local)) => Self::reduce_checked(instance), // We track this asset's teleports to ensure no more go out than have come in. - Some((checking_account, MintLocation::NonLocal)) => - Self::accrue_checked(checking_account, instance), + Some((checking_account, MintLocation::NonLocal)) => { + Self::accrue_checked(checking_account, instance) + }, _ => (), } } @@ -184,8 +186,9 @@ where // We track this asset's teleports to ensure no more come in than have gone out. Some((_, MintLocation::Local)) => Self::can_accrue_checked(instance), // We track this asset's teleports to ensure no more go out than have come in. - Some((checking_account, MintLocation::NonLocal)) => - Self::can_reduce_checked(checking_account, instance), + Some((checking_account, MintLocation::NonLocal)) => { + Self::can_reduce_checked(checking_account, instance) + }, _ => Ok(()), } } @@ -201,8 +204,9 @@ where if let Some(instance) = Matcher::matches_nonfungible(what) { match CheckingAccount::get() { // We track this asset's teleports to ensure no more come in than have gone out. - Some((checking_account, MintLocation::Local)) => - Self::accrue_checked(checking_account, instance), + Some((checking_account, MintLocation::Local)) => { + Self::accrue_checked(checking_account, instance) + }, // We track this asset's teleports to ensure no more go out than have come in. Some((_, MintLocation::NonLocal)) => Self::reduce_checked(instance), _ => (), diff --git a/pezkuwi/xcm/xcm-builder/src/origin_aliases.rs b/pezkuwi/xcm/xcm-builder/src/origin_aliases.rs index 8f27d3c6..18a7521d 100644 --- a/pezkuwi/xcm/xcm-builder/src/origin_aliases.rs +++ b/pezkuwi/xcm/xcm-builder/src/origin_aliases.rs @@ -32,8 +32,8 @@ impl> ContainsPair if let (prefix, Some(account_id @ AccountId32 { .. })) = origin.clone().split_last_interior() { - return Prefix::contains(&prefix) && - *target == Location { parents: 0, interior: [account_id].into() }; + return Prefix::contains(&prefix) + && *target == Location { parents: 0, interior: [account_id].into() }; } false } @@ -60,9 +60,9 @@ where fn contains(origin: &Location, target: &Location) -> bool { // check that `origin` is a root location match origin.unpack() { - (1, [Teyrchain(_)]) | - (2, [GlobalConsensus(_)]) | - (2, [GlobalConsensus(_), Teyrchain(_)]) => (), + (1, [Teyrchain(_)]) + | (2, [GlobalConsensus(_)]) + | (2, [GlobalConsensus(_), Teyrchain(_)]) => (), _ => return false, }; // check that `origin` matches `Origin` and `target` matches `Filter` diff --git a/pezkuwi/xcm/xcm-builder/src/origin_conversion.rs b/pezkuwi/xcm/xcm-builder/src/origin_conversion.rs index fa1eea86..7f37fb2c 100644 --- a/pezkuwi/xcm/xcm-builder/src/origin_conversion.rs +++ b/pezkuwi/xcm/xcm-builder/src/origin_conversion.rs @@ -84,7 +84,9 @@ impl, RuntimeOrigin: OriginTrait> ConvertOrigin - Ok(RuntimeOrigin::root()), + { + Ok(RuntimeOrigin::root()) + }, _ => Err(origin), } } @@ -109,7 +111,9 @@ impl, RuntimeOrigin: OriginTrait> ConvertOrigin - Ok(RuntimeOrigin::root()), + { + Ok(RuntimeOrigin::root()) + }, _ => Err(origin), } } @@ -128,8 +132,9 @@ impl, RuntimeOrigin: From> ConvertOr let origin = origin.into(); tracing::trace!(target: "xcm::origin_conversion", ?origin, ?kind, "ChildTeyrchainAsNative"); match (kind, origin.unpack()) { - (OriginKind::Native, (0, [Junction::Teyrchain(id)])) => - Ok(RuntimeOrigin::from(TeyrchainOrigin::from(*id))), + (OriginKind::Native, (0, [Junction::Teyrchain(id)])) => { + Ok(RuntimeOrigin::from(TeyrchainOrigin::from(*id))) + }, _ => Err(origin), } } @@ -152,8 +157,9 @@ impl, RuntimeOrigin: From> ConvertOr "SiblingTeyrchainAsNative", ); match (kind, origin.unpack()) { - (OriginKind::Native, (1, [Junction::Teyrchain(id)])) => - Ok(RuntimeOrigin::from(TeyrchainOrigin::from(*id))), + (OriginKind::Native, (1, [Junction::Teyrchain(id)])) => { + Ok(RuntimeOrigin::from(TeyrchainOrigin::from(*id))) + }, _ => Err(origin), } } @@ -199,7 +205,9 @@ where match (kind, origin.unpack()) { (OriginKind::Native, (0, [Junction::AccountId32 { id, network }])) if matches!(network, None) || *network == Network::get() => - Ok(RuntimeOrigin::signed((*id).into())), + { + Ok(RuntimeOrigin::signed((*id).into())) + }, _ => Err(origin), } } @@ -226,7 +234,9 @@ where match (kind, origin.unpack()) { (OriginKind::Native, (0, [Junction::AccountKey20 { key, network }])) if (matches!(network, None) || *network == Network::get()) => - Ok(RuntimeOrigin::signed((*key).into())), + { + Ok(RuntimeOrigin::signed((*key).into())) + }, _ => Err(origin), } } @@ -279,8 +289,9 @@ where { fn try_convert(o: RuntimeOrigin) -> Result { o.try_with_caller(|caller| match caller.try_into() { - Ok(SystemRawOrigin::Signed(who)) => - Ok(Junction::AccountId32 { network: Network::get(), id: who.into() }.into()), + Ok(SystemRawOrigin::Signed(who)) => { + Ok(Junction::AccountId32 { network: Network::get(), id: who.into() }.into()) + }, Ok(other) => Err(other.into()), Err(other) => Err(other), }) @@ -353,8 +364,9 @@ impl, RuntimeOrigin: OriginTra "LocationAsSuperuser", ); match (kind, &origin) { - (OriginKind::Superuser, loc) if WhitelistedSuperuserLocations::contains(loc) => - Ok(RuntimeOrigin::root()), + (OriginKind::Superuser, loc) if WhitelistedSuperuserLocations::contains(loc) => { + Ok(RuntimeOrigin::root()) + }, _ => Err(origin), } } diff --git a/pezkuwi/xcm/xcm-builder/src/tests/barriers.rs b/pezkuwi/xcm/xcm-builder/src/tests/barriers.rs index 25f21a79..3415eb0b 100644 --- a/pezkuwi/xcm/xcm-builder/src/tests/barriers.rs +++ b/pezkuwi/xcm/xcm-builder/src/tests/barriers.rs @@ -930,12 +930,13 @@ fn deny_then_try_works() { instructions.matcher().match_next_inst_while( |_| true, |inst| match inst { - ClearOrigin { .. } => + ClearOrigin { .. } => { if origin.clone() == Here.into_location() { Err(ProcessMessageError::BadFormat) } else { Ok(ControlFlow::Continue(())) - }, + } + }, _ => Ok(ControlFlow::Continue(())), }, )?; diff --git a/pezkuwi/xcm/xcm-builder/src/tests/mock.rs b/pezkuwi/xcm/xcm-builder/src/tests/mock.rs index afa9b8b9..e2add84b 100644 --- a/pezkuwi/xcm/xcm-builder/src/tests/mock.rs +++ b/pezkuwi/xcm/xcm-builder/src/tests/mock.rs @@ -80,19 +80,19 @@ impl Dispatchable for TestCall { fn dispatch(self, origin: Self::RuntimeOrigin) -> DispatchResultWithPostInfo { let mut post_info = PostDispatchInfo::default(); let maybe_actual = match self { - TestCall::OnlyRoot(_, maybe_actual) | - TestCall::OnlySigned(_, maybe_actual, _) | - TestCall::OnlyTeyrchain(_, maybe_actual, _) | - TestCall::Any(_, maybe_actual) => maybe_actual, + TestCall::OnlyRoot(_, maybe_actual) + | TestCall::OnlySigned(_, maybe_actual, _) + | TestCall::OnlyTeyrchain(_, maybe_actual, _) + | TestCall::Any(_, maybe_actual) => maybe_actual, }; post_info.actual_weight = maybe_actual; if match (&origin, &self) { (TestOrigin::Teyrchain(i), TestCall::OnlyTeyrchain(_, _, Some(j))) => i == j, (TestOrigin::Signed(i), TestCall::OnlySigned(_, _, Some(j))) => i == j, - (TestOrigin::Root, TestCall::OnlyRoot(..)) | - (TestOrigin::Teyrchain(_), TestCall::OnlyTeyrchain(_, _, None)) | - (TestOrigin::Signed(_), TestCall::OnlySigned(_, _, None)) | - (_, TestCall::Any(..)) => true, + (TestOrigin::Root, TestCall::OnlyRoot(..)) + | (TestOrigin::Teyrchain(_), TestCall::OnlyTeyrchain(_, _, None)) + | (TestOrigin::Signed(_), TestCall::OnlySigned(_, _, None)) + | (_, TestCall::Any(..)) => true, _ => false, } { Ok(post_info) @@ -105,10 +105,10 @@ impl Dispatchable for TestCall { impl GetDispatchInfo for TestCall { fn get_dispatch_info(&self) -> DispatchInfo { let call_weight = *match self { - TestCall::OnlyRoot(estimate, ..) | - TestCall::OnlyTeyrchain(estimate, ..) | - TestCall::OnlySigned(estimate, ..) | - TestCall::Any(estimate, ..) => estimate, + TestCall::OnlyRoot(estimate, ..) + | TestCall::OnlyTeyrchain(estimate, ..) + | TestCall::OnlySigned(estimate, ..) + | TestCall::Any(estimate, ..) => estimate, }; DispatchInfo { call_weight, ..Default::default() } } @@ -617,12 +617,15 @@ pub struct TestTicket(LockTraceItem); impl Enact for TestTicket { fn enact(self) -> Result<(), LockError> { match &self.0 { - LockTraceItem::Lock { unlocker, asset, owner } => - allow_unlock(unlocker.clone(), asset.clone(), owner.clone()), - LockTraceItem::Unlock { unlocker, asset, owner } => - disallow_unlock(unlocker.clone(), asset.clone(), owner.clone()), - LockTraceItem::Reduce { locker, asset, owner } => - disallow_request_unlock(locker.clone(), asset.clone(), owner.clone()), + LockTraceItem::Lock { unlocker, asset, owner } => { + allow_unlock(unlocker.clone(), asset.clone(), owner.clone()) + }, + LockTraceItem::Unlock { unlocker, asset, owner } => { + disallow_unlock(unlocker.clone(), asset.clone(), owner.clone()) + }, + LockTraceItem::Reduce { locker, asset, owner } => { + disallow_request_unlock(locker.clone(), asset.clone(), owner.clone()) + }, _ => {}, } LOCK_TRACE.with(move |l| l.borrow_mut().push(self.0)); diff --git a/pezkuwi/xcm/xcm-builder/src/tests/pay/mock.rs b/pezkuwi/xcm/xcm-builder/src/tests/pay/mock.rs index 9efea479..1ac066dd 100644 --- a/pezkuwi/xcm/xcm-builder/src/tests/pay/mock.rs +++ b/pezkuwi/xcm/xcm-builder/src/tests/pay/mock.rs @@ -163,8 +163,9 @@ impl MaybeEquivalence match value.unpack() { (0, []) => Some(0 as AssetIdForAssets), (1, []) => Some(1 as AssetIdForAssets), - (0, [PalletInstance(1), GeneralIndex(index)]) if ![0, 1].contains(index) => - Some(*index as AssetIdForAssets), + (0, [PalletInstance(1), GeneralIndex(index)]) if ![0, 1].contains(index) => { + Some(*index as AssetIdForAssets) + }, _ => None, } } @@ -173,8 +174,9 @@ impl MaybeEquivalence match value { 0u128 => Some(Location { parents: 1, interior: Here }), 1u128 => Some(Location { parents: 0, interior: Here }), - para_id @ 1..=1000 => - Some(Location { parents: 1, interior: [Teyrchain(*para_id as u32)].into() }), + para_id @ 1..=1000 => { + Some(Location { parents: 1, interior: [Teyrchain(*para_id as u32)].into() }) + }, _ => None, } } @@ -262,8 +264,9 @@ pub struct TreasuryToAccount; impl ConvertLocation for TreasuryToAccount { fn convert_location(location: &Location) -> Option { match location.unpack() { - (1, [Teyrchain(42), Plurality { id: BodyId::Treasury, part: BodyPart::Voice }]) => - Some(TreasuryAccountId::get()), // Hardcoded test treasury account id + (1, [Teyrchain(42), Plurality { id: BodyId::Treasury, part: BodyPart::Voice }]) => { + Some(TreasuryAccountId::get()) + }, // Hardcoded test treasury account id _ => None, } } diff --git a/pezkuwi/xcm/xcm-builder/src/universal_exports.rs b/pezkuwi/xcm/xcm-builder/src/universal_exports.rs index 2f511299..5c238ce2 100644 --- a/pezkuwi/xcm/xcm-builder/src/universal_exports.rs +++ b/pezkuwi/xcm/xcm-builder/src/universal_exports.rs @@ -229,8 +229,9 @@ impl>> ExporterFor for NetworkExportTable T::get() .into_iter() .find(|item| { - &item.remote_network == network && - item.remote_location_filter + &item.remote_network == network + && item + .remote_location_filter .as_ref() .map(|filters| filters.iter().any(|filter| filter == remote_location)) .unwrap_or(true) diff --git a/pezkuwi/xcm/xcm-builder/src/weight.rs b/pezkuwi/xcm/xcm-builder/src/weight.rs index f8887b3d..8ecec922 100644 --- a/pezkuwi/xcm/xcm-builder/src/weight.rs +++ b/pezkuwi/xcm/xcm-builder/src/weight.rs @@ -103,14 +103,16 @@ impl, C: Decode + GetDispatchInfo, M> FixedWeightBounds weight_limit: Weight, ) -> Result { let instruction_weight = match instruction { - Transact { ref mut call, .. } => + Transact { ref mut call, .. } => { call.ensure_decoded() .map_err(|_| XcmError::FailedToDecode)? .get_dispatch_info() - .call_weight, - SetErrorHandler(xcm) | SetAppendix(xcm) | ExecuteWithOrigin { xcm, .. } => + .call_weight + }, + SetErrorHandler(xcm) | SetAppendix(xcm) | ExecuteWithOrigin { xcm, .. } => { Self::weight_with_limit(xcm, instructions_left, weight_limit) - .map_err(|outcome_error| outcome_error.error)?, + .map_err(|outcome_error| outcome_error.error)? + }, _ => Weight::zero(), }; let total_weight = T::get().checked_add(&instruction_weight).ok_or(XcmError::Overflow)?; @@ -197,14 +199,16 @@ where weight_limit: Weight, ) -> Result { let instruction_weight = match instruction { - Transact { ref mut call, .. } => + Transact { ref mut call, .. } => { call.ensure_decoded() .map_err(|_| XcmError::FailedToDecode)? .get_dispatch_info() - .call_weight, - SetErrorHandler(xcm) | SetAppendix(xcm) => + .call_weight + }, + SetErrorHandler(xcm) | SetAppendix(xcm) => { Self::weight_with_limit(xcm, instructions_left, weight_limit) - .map_err(|outcome_error| outcome_error.error)?, + .map_err(|outcome_error| outcome_error.error)? + }, _ => Weight::zero(), }; let total_weight = instruction @@ -254,9 +258,9 @@ impl, R: TakeRevenue> WeightTrader for FixedRateOf ?id, ?weight, ?payment, ?context, "FixedRateOfFungible::buy_weight", ); - let amount = (units_per_second * (weight.ref_time() as u128) / - (WEIGHT_REF_TIME_PER_SECOND as u128)) + - (units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128)); + let amount = (units_per_second * (weight.ref_time() as u128) + / (WEIGHT_REF_TIME_PER_SECOND as u128)) + + (units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128)); if amount == 0 { return Ok(payment); } @@ -273,9 +277,9 @@ impl, R: TakeRevenue> WeightTrader for FixedRateOf let (id, units_per_second, units_per_mb) = T::get(); tracing::trace!(target: "xcm::weight", ?id, ?weight, ?context, "FixedRateOfFungible::refund_weight"); let weight = weight.min(self.0); - let amount = (units_per_second * (weight.ref_time() as u128) / - (WEIGHT_REF_TIME_PER_SECOND as u128)) + - (units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128)); + let amount = (units_per_second * (weight.ref_time() as u128) + / (WEIGHT_REF_TIME_PER_SECOND as u128)) + + (units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128)); self.0 -= weight; self.1 = self.1.saturating_sub(amount); if amount > 0 { diff --git a/pezkuwi/xcm/xcm-executor/src/assets.rs b/pezkuwi/xcm/xcm-executor/src/assets.rs index 15b0d92d..b5018cd0 100644 --- a/pezkuwi/xcm/xcm-executor/src/assets.rs +++ b/pezkuwi/xcm/xcm-executor/src/assets.rs @@ -238,10 +238,12 @@ impl AssetsInHolding { /// Returns `true` if `asset` is contained within `self`. pub fn contains_asset(&self, asset: &Asset) -> bool { match asset { - Asset { fun: Fungible(amount), id } => - self.fungible.get(id).map_or(false, |a| a >= amount), - Asset { fun: NonFungible(instance), id } => - self.non_fungible.contains(&(id.clone(), *instance)), + Asset { fun: Fungible(amount), id } => { + self.fungible.get(id).map_or(false, |a| a >= amount) + }, + Asset { fun: NonFungible(instance), id } => { + self.non_fungible.contains(&(id.clone(), *instance)) + }, } } @@ -255,8 +257,8 @@ impl AssetsInHolding { assets .fungible .iter() - .all(|(k, v)| self.fungible.get(k).map_or(false, |a| a >= v)) && - self.non_fungible.is_superset(&assets.non_fungible) + .all(|(k, v)| self.fungible.get(k).map_or(false, |a| a >= v)) + && self.non_fungible.is_superset(&assets.non_fungible) } /// Returns an error unless all `assets` are contained in `self`. In the case of an error, the @@ -303,8 +305,9 @@ impl AssetsInHolding { match mask { AssetFilter::Wild(All) | AssetFilter::Wild(AllCounted(_)) => match maybe_limit { None => return Ok(self.swapped(AssetsInHolding::new())), - Some(limit) if self.len() <= limit => - return Ok(self.swapped(AssetsInHolding::new())), + Some(limit) if self.len() <= limit => { + return Ok(self.swapped(AssetsInHolding::new())) + }, Some(0) => return Ok(AssetsInHolding::new()), Some(limit) => { let fungible = mem::replace(&mut self.fungible, Default::default()); @@ -325,15 +328,16 @@ impl AssetsInHolding { }); }, }, - AssetFilter::Wild(AllOfCounted { fun: WildFungible, id, .. }) | - AssetFilter::Wild(AllOf { fun: WildFungible, id }) => + AssetFilter::Wild(AllOfCounted { fun: WildFungible, id, .. }) + | AssetFilter::Wild(AllOf { fun: WildFungible, id }) => { if maybe_limit.map_or(true, |l| l >= 1) { if let Some((id, amount)) = self.fungible.remove_entry(&id) { taken.fungible.insert(id, amount); } - }, - AssetFilter::Wild(AllOfCounted { fun: WildNonFungible, id, .. }) | - AssetFilter::Wild(AllOf { fun: WildNonFungible, id }) => { + } + }, + AssetFilter::Wild(AllOfCounted { fun: WildNonFungible, id, .. }) + | AssetFilter::Wild(AllOf { fun: WildNonFungible, id }) => { let non_fungible = mem::replace(&mut self.non_fungible, Default::default()); non_fungible.into_iter().for_each(|(c, instance)| { if c == id && maybe_limit.map_or(true, |l| taken.len() < l) { @@ -417,12 +421,13 @@ impl AssetsInHolding { } Ok(self) }, - NonFungible(instance) => + NonFungible(instance) => { if self.non_fungible.remove(&(asset.id, instance)) { Ok(self) } else { Err(self) - }, + } + }, } } @@ -469,14 +474,14 @@ impl AssetsInHolding { } } }, - AssetFilter::Wild(AllOfCounted { fun: WildFungible, id, .. }) | - AssetFilter::Wild(AllOf { fun: WildFungible, id }) => { + AssetFilter::Wild(AllOfCounted { fun: WildFungible, id, .. }) + | AssetFilter::Wild(AllOf { fun: WildFungible, id }) => { if let Some(&amount) = self.fungible.get(&id) { masked.fungible.insert(id.clone(), amount); } }, - AssetFilter::Wild(AllOfCounted { fun: WildNonFungible, id, .. }) | - AssetFilter::Wild(AllOf { fun: WildNonFungible, id }) => { + AssetFilter::Wild(AllOfCounted { fun: WildNonFungible, id, .. }) + | AssetFilter::Wild(AllOf { fun: WildNonFungible, id }) => { for (c, instance) in self.non_fungible.iter() { if c == id { masked.non_fungible.insert((c.clone(), *instance)); @@ -486,7 +491,7 @@ impl AssetsInHolding { } } }, - AssetFilter::Definite(assets) => + AssetFilter::Definite(assets) => { for asset in assets.inner().iter() { match asset { Asset { fun: Fungible(amount), id } => { @@ -501,7 +506,8 @@ impl AssetsInHolding { } }, } - }, + } + }, } masked } diff --git a/pezkuwi/xcm/xcm-executor/src/lib.rs b/pezkuwi/xcm/xcm-executor/src/lib.rs index 4ac98929..fdc0f64e 100644 --- a/pezkuwi/xcm/xcm-executor/src/lib.rs +++ b/pezkuwi/xcm/xcm-executor/src/lib.rs @@ -540,8 +540,8 @@ impl XcmExecutor { ); if current_surplus.any_gt(Weight::zero()) { if let Some(w) = self.trader.refund_weight(current_surplus, &self.context) { - if !self.holding.contains_asset(&(w.id.clone(), 1).into()) && - self.ensure_can_subsume_assets(1).is_err() + if !self.holding.contains_asset(&(w.id.clone(), 1).into()) + && self.ensure_can_subsume_assets(1).is_err() { let _ = self .trader @@ -890,10 +890,11 @@ impl XcmExecutor { }); } }, - Err(ref mut error) => + Err(ref mut error) => { if let Ok(x) = Config::Weigher::instr_weight(&mut instr) { error.weight.saturating_accrue(x) - }, + } + }, } } result diff --git a/pezkuwi/xcm/xcm-executor/src/traits/asset_lock.rs b/pezkuwi/xcm/xcm-executor/src/traits/asset_lock.rs index 302bf4fa..ed045b82 100644 --- a/pezkuwi/xcm/xcm-executor/src/traits/asset_lock.rs +++ b/pezkuwi/xcm/xcm-executor/src/traits/asset_lock.rs @@ -40,9 +40,8 @@ impl From for XcmError { match e { NotApplicable => XcmError::AssetNotFound, BadOrigin => XcmError::BadOrigin, - WouldClobber | NotLocked | NotEnoughLocked | Unimplemented | NotTrusted | - BadOwner | UnknownAsset | AssetNotOwned | NoResources | UnexpectedState | InUse => - XcmError::LockError, + WouldClobber | NotLocked | NotEnoughLocked | Unimplemented | NotTrusted | BadOwner + | UnknownAsset | AssetNotOwned | NoResources | UnexpectedState | InUse => XcmError::LockError, } } } diff --git a/pezkuwi/xcm/xcm-executor/src/traits/asset_transfer.rs b/pezkuwi/xcm/xcm-executor/src/traits/asset_transfer.rs index 3a31166f..85fbe25d 100644 --- a/pezkuwi/xcm/xcm-executor/src/traits/asset_transfer.rs +++ b/pezkuwi/xcm/xcm-executor/src/traits/asset_transfer.rs @@ -66,8 +66,8 @@ pub trait XcmAssetTransfers { // try to determine reserve location based on asset id/location let asset_location = asset.id.0.chain_location(); - if asset_location == Location::here() || - Self::IsTeleporter::contains(asset, &asset_location) + if asset_location == Location::here() + || Self::IsTeleporter::contains(asset, &asset_location) { // if the asset is local, then it's a local reserve // it's also a local reserve if the asset's location is not `here` but it's a location diff --git a/pezkuwi/xcm/xcm-executor/src/traits/token_matching.rs b/pezkuwi/xcm/xcm-executor/src/traits/token_matching.rs index 0ff30007..aa0e4b5f 100644 --- a/pezkuwi/xcm/xcm-executor/src/traits/token_matching.rs +++ b/pezkuwi/xcm/xcm-executor/src/traits/token_matching.rs @@ -68,8 +68,9 @@ impl From for XcmError { match e { Error::AssetNotHandled => XcmError::AssetNotFound, Error::AccountIdConversionFailed => FailedToTransactAsset("AccountIdConversionFailed"), - Error::AmountToBalanceConversionFailed => - FailedToTransactAsset("AmountToBalanceConversionFailed"), + Error::AmountToBalanceConversionFailed => { + FailedToTransactAsset("AmountToBalanceConversionFailed") + }, Error::AssetIdConversionFailed => FailedToTransactAsset("AssetIdConversionFailed"), Error::InstanceConversionFailed => FailedToTransactAsset("InstanceConversionFailed"), } diff --git a/pezkuwi/xcm/xcm-pez-simulator/fuzzer/src/fuzz.rs b/pezkuwi/xcm/xcm-pez-simulator/fuzzer/src/fuzz.rs index 6f2d389b..eb611450 100644 --- a/pezkuwi/xcm/xcm-pez-simulator/fuzzer/src/fuzz.rs +++ b/pezkuwi/xcm/xcm-pez-simulator/fuzzer/src/fuzz.rs @@ -159,13 +159,13 @@ pub type TeyrchainPalletXcm = pezpallet_xcm::Pezpallet; // We check XCM messages recursively for blocklisted messages fn recursively_matches_blocklisted_messages(message: &Instruction<()>) -> bool { match message { - DepositReserveAsset { xcm, .. } | - ExportMessage { xcm, .. } | - InitiateReserveWithdraw { xcm, .. } | - InitiateTeleport { xcm, .. } | - TransferReserveAsset { xcm, .. } | - SetErrorHandler(xcm) | - SetAppendix(xcm) => xcm.iter().any(recursively_matches_blocklisted_messages), + DepositReserveAsset { xcm, .. } + | ExportMessage { xcm, .. } + | InitiateReserveWithdraw { xcm, .. } + | InitiateTeleport { xcm, .. } + | TransferReserveAsset { xcm, .. } + | SetErrorHandler(xcm) + | SetAppendix(xcm) => xcm.iter().any(recursively_matches_blocklisted_messages), // The blocklisted message is the Transact instruction. m => matches!(m, Transact { .. }), } diff --git a/pezkuwi/xcm/xcm-pez-simulator/fuzzer/src/teyrchain.rs b/pezkuwi/xcm/xcm-pez-simulator/fuzzer/src/teyrchain.rs index 5e576a9e..c5d533d2 100644 --- a/pezkuwi/xcm/xcm-pez-simulator/fuzzer/src/teyrchain.rs +++ b/pezkuwi/xcm/xcm-pez-simulator/fuzzer/src/teyrchain.rs @@ -238,8 +238,9 @@ pub mod mock_msg_queue { max_weight, Weight::zero(), ) { - Outcome::Error(InstructionError { error, .. }) => - (Err(error), Event::Fail(Some(hash), error)), + Outcome::Error(InstructionError { error, .. }) => { + (Err(error), Event::Fail(Some(hash), error)) + }, Outcome::Complete { used } => (Ok(used), Event::Success(Some(hash))), // As far as the caller is concerned, this was dispatched without error, so // we just report the weight used. diff --git a/pezkuwi/xcm/xcm-pez-simulator/src/mock_message_queue.rs b/pezkuwi/xcm/xcm-pez-simulator/src/mock_message_queue.rs index 048d4820..93cc2aec 100644 --- a/pezkuwi/xcm/xcm-pez-simulator/src/mock_message_queue.rs +++ b/pezkuwi/xcm/xcm-pez-simulator/src/mock_message_queue.rs @@ -108,10 +108,12 @@ pub mod pezpallet { max_weight, Weight::zero(), ) { - Outcome::Error(InstructionError { error, .. }) => - (Err(error), Event::Fail { message_id: Some(hash), error }), - Outcome::Complete { used } => - (Ok(used), Event::Success { message_id: Some(hash) }), + Outcome::Error(InstructionError { error, .. }) => { + (Err(error), Event::Fail { message_id: Some(hash), error }) + }, + Outcome::Complete { used } => { + (Ok(used), Event::Success { message_id: Some(hash) }) + }, // As far as the caller is concerned, this was dispatched without error, so // we just report the weight used. Outcome::Incomplete { @@ -167,8 +169,9 @@ pub mod pezpallet { Self::deposit_event(Event::InvalidFormat { message_id: id }); }, Ok(versioned) => match Xcm::try_from(versioned) { - Err(()) => - Self::deposit_event(Event::UnsupportedVersion { message_id: id }), + Err(()) => { + Self::deposit_event(Event::UnsupportedVersion { message_id: id }) + }, Ok(x) => { let outcome = T::XcmExecutor::prepare_and_execute( Parent, diff --git a/pezkuwi/xcm/xcm-runtime-pezapis/tests/mock.rs b/pezkuwi/xcm/xcm-runtime-pezapis/tests/mock.rs index b6a05159..be1facfb 100644 --- a/pezkuwi/xcm/xcm-runtime-pezapis/tests/mock.rs +++ b/pezkuwi/xcm/xcm-runtime-pezapis/tests/mock.rs @@ -186,8 +186,8 @@ type Weigher = FixedWeightBounds; pub struct NativeTokenToAssetHub; impl ContainsPair for NativeTokenToAssetHub { fn contains(asset: &Asset, origin: &Location) -> bool { - matches!(asset.id.0.unpack(), (0, [])) && - matches!(origin.unpack(), (1, [Teyrchain(ASSET_HUB_PARA_ID)])) + matches!(asset.id.0.unpack(), (0, [])) + && matches!(origin.unpack(), (1, [Teyrchain(ASSET_HUB_PARA_ID)])) } } @@ -428,8 +428,9 @@ where { fn try_convert(origin: RuntimeOrigin) -> Result { origin.try_with_caller(|caller| match caller.try_into() { - Ok(SystemRawOrigin::Signed(who)) => - Ok(Junction::AccountIndex64 { network: None, index: who.into() }.into()), + Ok(SystemRawOrigin::Signed(who)) => { + Ok(Junction::AccountIndex64 { network: None, index: who.into() }.into()) + }, Ok(other) => Err(other.into()), Err(other) => Err(other), }) diff --git a/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/basic_3cores.rs b/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/basic_3cores.rs index 373f97b8..32cdc28e 100644 --- a/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/basic_3cores.rs +++ b/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/basic_3cores.rs @@ -43,7 +43,9 @@ async fn basic_3cores_test() -> Result<(), anyhow::Error> { // type. .with_validator(|node| node.with_name("validator-0")); - (1..4).fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))) + (1..4).fold(r, |acc, i| { + acc.with_validator(|node| node.with_name(&format!("validator-{i}"))) + }) }) .with_teyrchain(|p| { p.with_id(2000) diff --git a/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/doesnt_break_teyrchains.rs b/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/doesnt_break_teyrchains.rs index ec561270..b3f45fba 100644 --- a/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/doesnt_break_teyrchains.rs +++ b/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/doesnt_break_teyrchains.rs @@ -47,7 +47,9 @@ async fn doesnt_break_teyrchains_test() -> Result<(), anyhow::Error> { // type. .with_validator(|node| node.with_name("validator-0")); - (1..4).fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))) + (1..4).fold(r, |acc, i| { + acc.with_validator(|node| node.with_name(&format!("validator-{i}"))) + }) }) .with_teyrchain(|p| { // Use pezkuwichain-teyrchain default, which has 6 second slot time. Also, don't use diff --git a/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/slot_based_12cores.rs b/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/slot_based_12cores.rs index 4d08c6ad..99e85391 100644 --- a/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/slot_based_12cores.rs +++ b/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/slot_based_12cores.rs @@ -53,8 +53,9 @@ async fn slot_based_12cores_test() -> Result<(), anyhow::Error> { // type. .with_validator(|node| node.with_name("validator-0")); - (1..12) - .fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))) + (1..12).fold(r, |acc, i| { + acc.with_validator(|node| node.with_name(&format!("validator-{i}"))) + }) }) .with_teyrchain(|p| { p.with_id(2300) diff --git a/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/slot_based_3cores.rs b/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/slot_based_3cores.rs index e52a04d5..5fb903fe 100644 --- a/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/slot_based_3cores.rs +++ b/pezkuwi/zombienet-sdk-tests/tests/elastic_scaling/slot_based_3cores.rs @@ -50,8 +50,9 @@ async fn slot_based_3cores_test() -> Result<(), anyhow::Error> { // type. .with_validator(|node| node.with_name("validator-0")); - (1..12) - .fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))) + (1..12).fold(r, |acc, i| { + acc.with_validator(|node| node.with_name(&format!("validator-{i}"))) + }) }) .with_teyrchain(|p| { // Para 2100 uses the old elastic scaling mvp, which doesn't send the new UMP signal diff --git a/pezkuwi/zombienet-sdk-tests/tests/functional/approval_voting_coalescing.rs b/pezkuwi/zombienet-sdk-tests/tests/functional/approval_voting_coalescing.rs index 056b5c6a..d41e67dd 100644 --- a/pezkuwi/zombienet-sdk-tests/tests/functional/approval_voting_coalescing.rs +++ b/pezkuwi/zombienet-sdk-tests/tests/functional/approval_voting_coalescing.rs @@ -41,7 +41,8 @@ async fn approval_voting_coalescing_test() -> Result<(), anyhow::Error> { })) .with_validator(|node| node.with_name("validator-0")); - (1..12).fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))) + (1..12) + .fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))) }); for para_id in 2000..2008 { diff --git a/pezkuwi/zombienet-sdk-tests/tests/functional/approved_peer_mixed_validators.rs b/pezkuwi/zombienet-sdk-tests/tests/functional/approved_peer_mixed_validators.rs index 0e5bbfaf..2d67a0fe 100644 --- a/pezkuwi/zombienet-sdk-tests/tests/functional/approved_peer_mixed_validators.rs +++ b/pezkuwi/zombienet-sdk-tests/tests/functional/approved_peer_mixed_validators.rs @@ -46,8 +46,9 @@ async fn approved_peer_mixed_validators_test() -> Result<(), anyhow::Error> { })) .with_validator(|node| node.with_name("validator-0")); - let r = (1..7) - .fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))); + let r = (1..7).fold(r, |acc, i| { + acc.with_validator(|node| node.with_name(&format!("validator-{i}"))) + }); (7..10).fold(r, |acc, i| { acc.with_validator(|node| { diff --git a/pezkuwi/zombienet-sdk-tests/tests/functional/async_backing_6_seconds_rate.rs b/pezkuwi/zombienet-sdk-tests/tests/functional/async_backing_6_seconds_rate.rs index 1a37a9dd..330e362a 100644 --- a/pezkuwi/zombienet-sdk-tests/tests/functional/async_backing_6_seconds_rate.rs +++ b/pezkuwi/zombienet-sdk-tests/tests/functional/async_backing_6_seconds_rate.rs @@ -39,8 +39,9 @@ async fn async_backing_6_seconds_rate_test() -> Result<(), anyhow::Error> { })) .with_validator(|node| node.with_name("validator-0")); - (1..12) - .fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))) + (1..12).fold(r, |acc, i| { + acc.with_validator(|node| node.with_name(&format!("validator-{i}"))) + }) }) .with_teyrchain(|p| { p.with_id(2000) diff --git a/pezkuwi/zombienet-sdk-tests/tests/functional/duplicate_collations.rs b/pezkuwi/zombienet-sdk-tests/tests/functional/duplicate_collations.rs index 1bd3e073..8e3044a6 100644 --- a/pezkuwi/zombienet-sdk-tests/tests/functional/duplicate_collations.rs +++ b/pezkuwi/zombienet-sdk-tests/tests/functional/duplicate_collations.rs @@ -50,8 +50,9 @@ async fn duplicate_collations_test() -> Result<(), anyhow::Error> { // type. .with_validator(|node| node.with_name("validator-0")); - (1..VALIDATOR_COUNT) - .fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))) + (1..VALIDATOR_COUNT).fold(r, |acc, i| { + acc.with_validator(|node| node.with_name(&format!("validator-{i}"))) + }) }) .with_teyrchain(|p| { p.with_id(2000) diff --git a/pezkuwi/zombienet-sdk-tests/tests/functional/shared_core_idle_teyrchain.rs b/pezkuwi/zombienet-sdk-tests/tests/functional/shared_core_idle_teyrchain.rs index d8961378..0a69670d 100644 --- a/pezkuwi/zombienet-sdk-tests/tests/functional/shared_core_idle_teyrchain.rs +++ b/pezkuwi/zombienet-sdk-tests/tests/functional/shared_core_idle_teyrchain.rs @@ -42,7 +42,9 @@ async fn shared_core_idle_teyrchain_test() -> Result<(), anyhow::Error> { })) .with_validator(|node| node.with_name("validator-0")); - (1..4).fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))) + (1..4).fold(r, |acc, i| { + acc.with_validator(|node| node.with_name(&format!("validator-{i}"))) + }) }) .with_teyrchain(|p| { p.with_id(2000) diff --git a/pezkuwi/zombienet-sdk-tests/tests/functional/sync_backing.rs b/pezkuwi/zombienet-sdk-tests/tests/functional/sync_backing.rs index 6ddaebe4..18d6774d 100644 --- a/pezkuwi/zombienet-sdk-tests/tests/functional/sync_backing.rs +++ b/pezkuwi/zombienet-sdk-tests/tests/functional/sync_backing.rs @@ -39,7 +39,9 @@ async fn sync_backing_test() -> Result<(), anyhow::Error> { })) .with_validator(|node| node.with_name("validator-0")); - (1..5).fold(r, |acc, i| acc.with_validator(|node| node.with_name(&format!("validator-{i}")))) + (1..5).fold(r, |acc, i| { + acc.with_validator(|node| node.with_name(&format!("validator-{i}"))) + }) }) .with_teyrchain(|p| { p.with_id(2500) diff --git a/pezkuwi/zombienet-sdk-tests/tests/smoke/coretime_revenue.rs b/pezkuwi/zombienet-sdk-tests/tests/smoke/coretime_revenue.rs index b77fb7a5..f4f85941 100644 --- a/pezkuwi/zombienet-sdk-tests/tests/smoke/coretime_revenue.rs +++ b/pezkuwi/zombienet-sdk-tests/tests/smoke/coretime_revenue.rs @@ -11,9 +11,7 @@ use anyhow::anyhow; -#[pezkuwi_subxt::subxt( - runtime_metadata_path = "metadata-files/coretime-pezkuwichain-local.scale" -)] +#[pezkuwi_subxt::subxt(runtime_metadata_path = "metadata-files/coretime-pezkuwichain-local.scale")] mod coretime_pezkuwichain {} #[pezkuwi_subxt::subxt(runtime_metadata_path = "metadata-files/pezkuwichain-local.scale")] @@ -105,10 +103,8 @@ macro_rules! trace_event { }; } -async fn para_watcher( - api: OnlineClient, - events: EventOf, -) where +async fn para_watcher(api: OnlineClient, events: EventOf) +where ::Number: Display, { let mut blocks_sub = api.blocks().subscribe_finalized().await.unwrap(); @@ -135,10 +131,8 @@ async fn para_watcher( } } -async fn relay_watcher( - api: OnlineClient, - events: EventOf, -) where +async fn relay_watcher(api: OnlineClient, events: EventOf) +where ::Number: Display, { let mut blocks_sub = api.blocks().subscribe_finalized().await.unwrap(); @@ -177,9 +171,9 @@ async fn wait_for_event< loop { let mut events = events.write().await; if let Some(entry) = events.iter().find(|&e| { - e.1.pezpallet_name() == pezpallet && - e.1.variant_name() == variant && - predicate(&e.1.as_event::().unwrap().unwrap()) + e.1.pezpallet_name() == pezpallet + && e.1.variant_name() == variant + && predicate(&e.1.as_event::().unwrap().unwrap()) }) { let entry = entry.clone(); events.retain(|e| e.0 > entry.0); @@ -190,10 +184,8 @@ async fn wait_for_event< } } -async fn ti_watcher( - api: OnlineClient, - prefix: &'static str, -) where +async fn ti_watcher(api: OnlineClient, prefix: &'static str) +where ::Number: Display, { let mut blocks_sub = api.blocks().subscribe_finalized().await.unwrap(); diff --git a/pezkuwi/zombienet-sdk-tests/tests/teyrchains/weights.rs b/pezkuwi/zombienet-sdk-tests/tests/teyrchains/weights.rs index 10f97679..2ebd4a16 100644 --- a/pezkuwi/zombienet-sdk-tests/tests/teyrchains/weights.rs +++ b/pezkuwi/zombienet-sdk-tests/tests/teyrchains/weights.rs @@ -1,9 +1,7 @@ // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 -#[pezkuwi_subxt::subxt( - runtime_metadata_path = "metadata-files/asset-hub-zagros-local.scale" -)] +#[pezkuwi_subxt::subxt(runtime_metadata_path = "metadata-files/asset-hub-zagros-local.scale")] mod ahw {} use ahw::runtime_types::{ @@ -14,14 +12,14 @@ use anyhow::anyhow; use asset_hub_zagros_runtime::Runtime as AHWRuntime; use ethabi::Token; use futures::{stream::FuturesUnordered, StreamExt}; -use pezpallet_revive::AddressMapper; -use pezsp_core::{H160, H256}; -use rand::Rng; -use std::str::FromStr; use pezkuwi_subxt::{ config::pezkuwi::PezkuwiExtrinsicParamsBuilder, tx::SubmittableTransaction, OnlineClient, PezkuwiConfig, }; +use pezpallet_revive::AddressMapper; +use pezsp_core::{H160, H256}; +use rand::Rng; +use std::str::FromStr; use zombienet_sdk::{ subxt_signer::{ sr25519::{dev, Keypair}, @@ -30,7 +28,6 @@ use zombienet_sdk::{ LocalFileSystem, Network, NetworkConfigBuilder, NetworkNode, }; - const KEYS_COUNT: usize = 6000; const CHUNK_SIZE: usize = 3000; const CALL_CHUNK_SIZE: usize = 3000; @@ -214,7 +211,7 @@ fn create_keys(n: usize) -> Vec { fn tx_params( nonce: u64, -) -> as pezkuwi_subxt::config::ExtrinsicParams>::Params { +) -> as pezkuwi_subxt::config::ExtrinsicParams>::Params{ PezkuwiExtrinsicParamsBuilder::::new().nonce(nonce).build() } @@ -356,9 +353,7 @@ async fn call_contract( let finalized_blocks = submit_txs(txs).await?; for block in finalized_blocks { let storage_at = client.storage().at(block); - let weight = storage_at - .fetch(&ahw::storage().system().block_weight(), ()) - .await?; + let weight = storage_at.fetch(&ahw::storage().system().block_weight(), ()).await?; log::info!("Weight of block {block:?}: {weight:?}"); } @@ -379,15 +374,21 @@ async fn submit_txs( Ok(st) => match st { pezkuwi_subxt::tx::TxStatus::Validated => log::trace!("VALIDATED"), pezkuwi_subxt::tx::TxStatus::Broadcasted => log::trace!("BROADCASTED"), - pezkuwi_subxt::tx::TxStatus::NoLongerInBestBlock => log::warn!("NO LONGER IN BEST BLOCK"), + pezkuwi_subxt::tx::TxStatus::NoLongerInBestBlock => { + log::warn!("NO LONGER IN BEST BLOCK") + }, pezkuwi_subxt::tx::TxStatus::InBestBlock(_) => log::trace!("IN BEST BLOCK"), pezkuwi_subxt::tx::TxStatus::InFinalizedBlock(block) => { log::trace!("IN FINALIZED BLOCK"); finalized_blocks.insert(block.block_hash()); }, pezkuwi_subxt::tx::TxStatus::Error { message } => log::warn!("ERROR: {message}"), - pezkuwi_subxt::tx::TxStatus::Invalid { message } => log::trace!("INVALID: {message}"), - pezkuwi_subxt::tx::TxStatus::Dropped { message } => log::trace!("DROPPED: {message}"), + pezkuwi_subxt::tx::TxStatus::Invalid { message } => { + log::trace!("INVALID: {message}") + }, + pezkuwi_subxt::tx::TxStatus::Dropped { message } => { + log::trace!("DROPPED: {message}") + }, }, Err(e) => { println!("Error status {e:?}"); diff --git a/templates/minimal/node/src/command.rs b/templates/minimal/node/src/command.rs index 0d03a269..bfa9aab0 100644 --- a/templates/minimal/node/src/command.rs +++ b/templates/minimal/node/src/command.rs @@ -50,8 +50,9 @@ impl BizinikiwiCli for Cli { fn load_spec(&self, id: &str) -> Result, String> { Ok(match id { "dev" => Box::new(chain_spec::development_chain_spec()?), - 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))?) + }, }) } } diff --git a/templates/solochain/node/src/command.rs b/templates/solochain/node/src/command.rs index 54fe8c31..72c9c910 100644 --- a/templates/solochain/node/src/command.rs +++ b/templates/solochain/node/src/command.rs @@ -39,8 +39,9 @@ impl BizinikiwiCli for Cli { Ok(match id { "dev" => Box::new(chain_spec::development_chain_spec()?), "" | "local" => Box::new(chain_spec::local_chain_spec()?), - 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))?) + }, }) } } @@ -172,8 +173,9 @@ pub fn run() -> pezsc_cli::Result<()> { cmd.run(client, inherent_benchmark_data()?, Vec::new(), &ext_factory) }, - BenchmarkCmd::Machine(cmd) => - cmd.run(&config, BIZINIKIWI_REFERENCE_HARDWARE.clone()), + BenchmarkCmd::Machine(cmd) => { + cmd.run(&config, BIZINIKIWI_REFERENCE_HARDWARE.clone()) + }, } }) }, diff --git a/templates/teyrchain/node/src/command.rs b/templates/teyrchain/node/src/command.rs index c142eadd..877f50fe 100644 --- a/templates/teyrchain/node/src/command.rs +++ b/templates/teyrchain/node/src/command.rs @@ -192,14 +192,15 @@ pub fn run() -> Result<()> { let runner = cli.create_runner(cmd)?; // Switch on the concrete benchmark sub-command- match cmd { - BenchmarkCmd::Pezpallet(cmd) => + BenchmarkCmd::Pezpallet(cmd) => { if cfg!(feature = "runtime-benchmarks") { runner.sync_run(|config| cmd.run_with_spec::, ReclaimHostFunctions>(Some(config.chain_spec))) } else { Err("Benchmarking wasn't enabled when building the node. \ You can enable it with `--features runtime-benchmarks`." .into()) - }, + } + }, BenchmarkCmd::Block(cmd) => runner.sync_run(|config| { let partials = new_partial(&config)?; cmd.run(partials.client) diff --git a/vendor/ss58-registry/build.rs b/vendor/ss58-registry/build.rs index e3ad5906..73077577 100644 --- a/vendor/ss58-registry/build.rs +++ b/vendor/ss58-registry/build.rs @@ -35,7 +35,7 @@ fn is_valid_rust_identifier(id: &str) -> Result<(), String> { if ch.is_xid_start() { for ch in id.chars().skip(1) { if !ch.is_xid_continue() { - return Err(format!("Invalid char `{ch}` in `{id}`")) + return Err(format!("Invalid char `{ch}` in `{id}`")); } } Ok(()) @@ -65,16 +65,16 @@ impl Registry { )); } if account_type.network.is_empty() { - return Err("network is mandatory.".into()) + return Err("network is mandatory.".into()); } if let Err(err) = is_valid_rust_identifier(&account_type.name()) { - return Err(format!("network not valid: {err} for {account_type:#?}")) + return Err(format!("network not valid: {err} for {account_type:#?}")); } if account_type.decimals.len() != account_type.symbols.len() { return Err(format!( "decimals must be specified for each symbol: {account_type:?}" - )) + )); } for (name, decimals) in account_type.symbols.iter().zip(&account_type.decimals) { use Entry::*; @@ -87,7 +87,7 @@ impl Registry { name, e.get().networks.join(", "), network, - )) + )); } e.get_mut().networks.push(network); }, diff --git a/vendor/ss58-registry/rustfmt.toml b/vendor/ss58-registry/rustfmt.toml index 441913f6..8d7860b1 100644 --- a/vendor/ss58-registry/rustfmt.toml +++ b/vendor/ss58-registry/rustfmt.toml @@ -1,23 +1,19 @@ +# SS58 Registry - Stable Rustfmt Configuration +# Only stable features for compatibility + # Basic hard_tabs = true max_width = 100 use_small_heuristics = "Max" + # Imports -imports_granularity = "Crate" reorder_imports = true + # Consistency newline_style = "Unix" -# Format comments -comment_width = 100 -wrap_comments = true + # Misc chain_width = 80 -spaces_around_ranges = false -binop_separator = "Back" -reorder_impl_items = false match_arm_leading_pipes = "Preserve" -match_arm_blocks = false match_block_trailing_comma = true -trailing_comma = "Vertical" -trailing_semicolon = false use_field_init_shorthand = true