From 949f6b1d1007aa50c7e054c8d7ede47e1f9a4a1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Zemanovi=C4=8D?= Date: Fri, 21 Jun 2024 15:52:34 +0100 Subject: [PATCH] fix everything that was depending on rm'd namada crate --- Cargo.lock | 19 +- Cargo.toml | 1 + Makefile | 8 +- crates/apps/src/bin/namada-node/cli.rs | 8 +- crates/apps/src/bin/namada-relayer/main.rs | 2 +- crates/apps_lib/Cargo.toml | 11 +- crates/apps_lib/src/cli.rs | 34 +- crates/apps_lib/src/cli/api.rs | 8 +- crates/apps_lib/src/cli/client.rs | 2 +- crates/apps_lib/src/cli/context.rs | 19 +- crates/apps_lib/src/cli/relayer.rs | 2 +- crates/apps_lib/src/cli/utils.rs | 8 +- crates/apps_lib/src/cli/wallet.rs | 11 +- crates/apps_lib/src/client/rpc.rs | 140 +++--- crates/apps_lib/src/client/tx.rs | 58 +-- crates/apps_lib/src/client/utils.rs | 14 +- .../src/config/ethereum_bridge/ledger.rs | 2 +- crates/apps_lib/src/config/genesis.rs | 45 +- crates/apps_lib/src/config/genesis/chain.rs | 58 ++- .../apps_lib/src/config/genesis/templates.rs | 27 +- .../src/config/genesis/transactions.rs | 42 +- crates/apps_lib/src/config/genesis/utils.rs | 6 +- crates/apps_lib/src/config/global.rs | 2 +- crates/apps_lib/src/config/mod.rs | 10 +- crates/apps_lib/src/lib.rs | 7 +- crates/apps_lib/src/tendermint_node.rs | 2 +- crates/apps_lib/src/wallet/defaults.rs | 17 +- crates/apps_lib/src/wallet/mod.rs | 6 +- crates/apps_lib/src/wallet/pre_genesis.rs | 2 +- crates/apps_lib/src/wallet/store.rs | 4 +- crates/apps_lib/src/wasm_loader/mod.rs | 2 +- crates/benches/Cargo.toml | 7 +- crates/benches/README.md | 2 +- crates/benches/host_env.rs | 25 +- crates/benches/native_vps.rs | 455 +++++++++--------- crates/benches/process_wrapper.rs | 28 +- crates/core/Cargo.toml | 11 +- crates/core/src/lib.rs | 2 - crates/core/src/wasm_cache.rs | 25 - crates/encoding_spec/Cargo.toml | 5 + crates/encoding_spec/src/main.rs | 16 +- .../ethereum_bridge/src/vp/bridge_pool_vp.rs | 52 +- .../ethereum_bridge/src/vp/eth_bridge_vp.rs | 35 +- crates/ethereum_bridge/src/vp/mod.rs | 6 +- crates/ethereum_bridge/src/vp/nut_vp.rs | 26 +- crates/governance/src/vp/mod.rs | 46 +- crates/governance/src/vp/pgf.rs | 27 +- crates/ibc/src/vp/mod.rs | 59 ++- crates/node/Cargo.toml | 7 +- crates/node/src/abortable.rs | 2 +- crates/node/src/bench_utils.rs | 164 ++++--- crates/node/src/broadcaster.rs | 4 +- crates/node/src/dry_run_tx.rs | 112 ++--- crates/node/src/ethereum_oracle/control.rs | 2 +- crates/node/src/ethereum_oracle/events.rs | 16 +- crates/node/src/ethereum_oracle/mod.rs | 25 +- .../test_tools/events_endpoint.rs | 2 +- .../src/ethereum_oracle/test_tools/mod.rs | 8 +- crates/node/src/lib.rs | 21 +- crates/node/src/protocol.rs | 239 +++++---- crates/node/src/shell/block_alloc.rs | 7 +- crates/node/src/shell/finalize_block.rs | 451 ++++++++--------- crates/node/src/shell/governance.rs | 50 +- crates/node/src/shell/init_chain.rs | 51 +- crates/node/src/shell/mod.rs | 173 ++++--- crates/node/src/shell/prepare_proposal.rs | 92 ++-- crates/node/src/shell/process_proposal.rs | 59 ++- crates/node/src/shell/queries.rs | 47 +- crates/node/src/shell/stats.rs | 2 +- crates/node/src/shell/testing/client.rs | 2 +- crates/node/src/shell/testing/node.rs | 127 ++--- crates/node/src/shell/testing/utils.rs | 2 +- crates/node/src/shell/utils.rs | 4 +- crates/node/src/shell/vote_extensions.rs | 18 +- .../shell/vote_extensions/bridge_pool_vext.rs | 38 +- .../src/shell/vote_extensions/eth_events.rs | 31 +- .../shell/vote_extensions/val_set_update.rs | 23 +- crates/node/src/shims/abcipp_shim.rs | 12 +- crates/node/src/shims/abcipp_shim_types.rs | 8 +- crates/node/src/storage/mod.rs | 53 +- crates/node/src/storage/rocksdb.rs | 42 +- crates/node/src/tendermint_node.rs | 6 +- crates/parameters/src/vp.rs | 34 +- crates/proof_of_stake/src/lib.rs | 4 +- crates/proof_of_stake/src/vp.rs | 36 +- crates/sdk/Cargo.toml | 39 +- crates/sdk/src/lib.rs | 12 +- crates/sdk/src/masp.rs | 33 +- crates/sdk/src/migrations.rs | 25 +- crates/sdk/src/queries/mod.rs | 1 - crates/sdk/src/queries/router.rs | 5 +- crates/sdk/src/queries/shell.rs | 1 - crates/sdk/src/queries/vp/pos.rs | 1 - crates/sdk/src/queries/vp/token.rs | 1 - crates/shielded_token/Cargo.toml | 1 - crates/shielded_token/src/lib.rs | 1 - crates/shielded_token/src/vp.rs | 42 +- crates/state/src/lib.rs | 1 - crates/state/src/wl_state.rs | 23 + crates/state/src/write_log.rs | 2 +- crates/tests/Cargo.toml | 12 +- crates/tests/src/e2e/eth_bridge_tests.rs | 18 +- .../tests/src/e2e/eth_bridge_tests/helpers.rs | 8 +- crates/tests/src/e2e/helpers.rs | 12 +- crates/tests/src/e2e/ibc_tests.rs | 96 ++-- crates/tests/src/e2e/ledger_tests.rs | 8 +- .../tests/src/e2e/multitoken_tests/helpers.rs | 2 +- crates/tests/src/e2e/setup.rs | 2 +- crates/tests/src/integration/ledger_tests.rs | 15 +- crates/tests/src/integration/masp.rs | 10 +- crates/tests/src/integration/setup.rs | 4 +- crates/tests/src/lib.rs | 6 +- crates/tests/src/native_vp/eth_bridge_pool.rs | 33 +- crates/tests/src/native_vp/mod.rs | 53 +- crates/tests/src/native_vp/pos.rs | 47 +- crates/tests/src/storage.rs | 2 +- .../src/storage_api/collections/lazy_map.rs | 4 +- .../src/storage_api/collections/lazy_set.rs | 4 +- .../src/storage_api/collections/lazy_vec.rs | 4 +- .../collections/nested_lazy_map.rs | 4 +- crates/tests/src/vm_host_env/ibc.rs | 138 +++--- crates/tests/src/vm_host_env/mod.rs | 30 +- crates/tests/src/vm_host_env/tx.rs | 50 +- crates/tests/src/vm_host_env/vp.rs | 59 +-- crates/token/Cargo.toml | 1 + crates/token/src/lib.rs | 1 - crates/trans_token/src/vp.rs | 43 +- crates/tx_prelude/Cargo.toml | 1 + crates/tx_prelude/src/ibc.rs | 2 +- crates/tx_prelude/src/lib.rs | 5 +- crates/tx_prelude/src/proof_of_stake.rs | 2 +- crates/vm/Cargo.toml | 3 +- crates/vm/src/host_env.rs | 56 ++- crates/vm/src/lib.rs | 26 + .../vm/src/wasm/compilation_cache/common.rs | 8 +- crates/vm/src/wasm/host_env.rs | 7 +- crates/vm/src/wasm/memory.rs | 2 +- crates/vm/src/wasm/run.rs | 8 +- crates/vp/src/native_vp.rs | 24 +- examples/Cargo.toml | 2 +- wasm/Cargo.lock | 280 +++++------ wasm/tx_bond/src/lib.rs | 22 +- .../tx_change_validator_commission/src/lib.rs | 14 +- wasm/tx_redelegate/src/lib.rs | 22 +- wasm/tx_unbond/src/lib.rs | 22 +- wasm/tx_withdraw/src/lib.rs | 14 +- wasm/vp_implicit/src/lib.rs | 16 +- wasm/vp_user/src/lib.rs | 14 +- wasm_for_tests/Cargo.lock | 140 +++--- wasm_for_tests/tx_fail/Cargo.toml | 4 +- .../tx_infinite_guest_gas/Cargo.toml | 4 +- .../tx_infinite_host_gas/Cargo.toml | 4 +- wasm_for_tests/tx_invalid_data/Cargo.toml | 4 +- wasm_for_tests/tx_memory_limit/Cargo.toml | 4 +- wasm_for_tests/tx_no_op/Cargo.toml | 4 +- wasm_for_tests/tx_proposal_code/Cargo.toml | 4 +- .../Cargo.toml | 4 +- .../tx_proposal_masp_reward/Cargo.toml | 4 +- wasm_for_tests/tx_read_storage_key/Cargo.toml | 4 +- wasm_for_tests/tx_write/Cargo.toml | 4 +- wasm_for_tests/vp_always_false/Cargo.toml | 4 +- wasm_for_tests/vp_always_true/Cargo.toml | 4 +- wasm_for_tests/vp_eval/Cargo.toml | 4 +- .../vp_infinite_guest_gas/Cargo.toml | 4 +- .../vp_infinite_host_gas/Cargo.toml | 4 +- wasm_for_tests/vp_memory_limit/Cargo.toml | 4 +- wasm_for_tests/vp_read_storage_key/Cargo.toml | 4 +- 167 files changed, 2510 insertions(+), 2484 deletions(-) delete mode 100644 crates/core/src/wasm_cache.rs diff --git a/Cargo.lock b/Cargo.lock index 11f21ae33cd..e3fa843a1d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4728,10 +4728,12 @@ dependencies = [ "ledger-transport-hid", "linkme", "masp_primitives", + "namada_core", "namada_macros", "namada_migrations", "namada_sdk", "namada_test_utils", + "namada_vm", "pretty_assertions", "proptest", "prost 0.12.3", @@ -4771,6 +4773,8 @@ dependencies = [ "masp_proofs", "namada_apps_lib", "namada_node", + "namada_vm", + "namada_vp", "prost 0.12.3", "rand 0.8.5", "rand_core 0.6.4", @@ -4804,6 +4808,7 @@ dependencies = [ "ethabi", "ethbridge-structs", "eyre", + "futures", "ibc", "ics23", "impl-num-traits", @@ -4835,10 +4840,12 @@ dependencies = [ "test-log", "thiserror", "tiny-keccak", + "tokio", "toml 0.5.11", "tracing", "tracing-subscriber", "uint", + "wasmtimer", "zeroize", ] @@ -5095,8 +5102,12 @@ dependencies = [ "masp_proofs", "namada_apps_lib", "namada_migrations", + "namada_replay_protection", "namada_sdk", "namada_test_utils", + "namada_vm", + "namada_vote_ext", + "namada_vp", "num-rational", "num-traits 0.2.17", "num256", @@ -5225,7 +5236,9 @@ dependencies = [ "namada_test_utils", "namada_token", "namada_tx", + "namada_vm", "namada_vote_ext", + "namada_vp", "num-traits 0.2.17", "num256", "orion", @@ -5251,7 +5264,6 @@ dependencies = [ "tokio", "toml 0.5.11", "tracing", - "wasmtimer", "zeroize", ] @@ -5367,8 +5379,11 @@ dependencies = [ "namada_node", "namada_sdk", "namada_test_utils", + "namada_tx_env", "namada_tx_prelude", + "namada_vm", "namada_vm_env", + "namada_vp", "namada_vp_prelude", "once_cell", "pretty_assertions", @@ -5473,6 +5488,7 @@ dependencies = [ "namada_account", "namada_core", "namada_events", + "namada_gas", "namada_governance", "namada_ibc", "namada_macros", @@ -5498,7 +5514,6 @@ dependencies = [ "namada_events", "namada_gas", "namada_parameters", - "namada_sdk", "namada_state", "namada_test_utils", "namada_token", diff --git a/Cargo.toml b/Cargo.toml index 3998044c7fc..95ecf72d8b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -193,6 +193,7 @@ wasmer = "4.3.1" wasmer-cache = "4.3.1" wasmer-compiler-singlepass = "4.3.1" wasmer-vm = "4.3.1" +wasmtimer = "0.2.0" winapi = "0.3.9" yansi = "0.5.1" zeroize = { version = "1.5.5", features = ["zeroize_derive"] } diff --git a/Makefile b/Makefile index a80daf604fc..aca1ce0f8b8 100644 --- a/Makefile +++ b/Makefile @@ -100,14 +100,14 @@ check: check-mainnet: $(cargo) check --workspace --features "mainnet" -# Check that every crate can be built with default features and that namada crate -# can be built for wasm +# Check that every crate can be built with default features and that SDK crate +# can be built for wasm and with all features enabled check-crates: rustup target add --toolchain $(nightly) wasm32-unknown-unknown $(foreach p,$(crates), echo "Checking $(p)" && cargo +$(nightly) check -Z unstable-options --tests -p $(p) && ) \ make -C $(wasms) check && \ make -C $(wasms_for_tests) check && \ - cargo check --package namada --target wasm32-unknown-unknown --no-default-features --features "namada-sdk" && \ + cargo check --package namada_sdk --target wasm32-unknown-unknown --no-default-features && \ cargo check --package namada_sdk --all-features clippy-wasm = $(cargo) +$(nightly) clippy --manifest-path $(wasm)/Cargo.toml --all-targets -- -D warnings @@ -155,7 +155,6 @@ test-coverage: # Run integration tests separately because they require `integration` # feature (and without coverage) $(cargo) +$(nightly) llvm-cov --output-path lcov.info \ - --features namada/testing \ --lcov \ -- --skip e2e --skip pos_state_machine_test --skip integration \ -Z unstable-options --report-time && \ @@ -204,7 +203,6 @@ test-unit-with-eth-bridge: test-unit-with-coverage: $(cargo) +$(nightly) llvm-cov --output-path lcov.info \ - --features namada/testing \ --lcov \ -- --skip e2e --skip pos_state_machine_test --skip integration \ -Z unstable-options --report-time diff --git a/crates/apps/src/bin/namada-node/cli.rs b/crates/apps/src/bin/namada-node/cli.rs index bca121ac6be..45c87d2fc2c 100644 --- a/crates/apps/src/bin/namada-node/cli.rs +++ b/crates/apps/src/bin/namada-node/cli.rs @@ -1,14 +1,14 @@ //! Namada node CLI. use eyre::{Context, Result}; -use namada::core::time::{DateTimeUtc, Utc}; -use namada::sdk::migrations::ScheduledMigration; use namada_apps_lib::cli::cmds::TestGenesis; use namada_apps_lib::cli::{self, cmds}; use namada_apps_lib::config::{Action, ActionAtHeight, ValidatorLocalConfig}; -use namada_node as node; #[cfg(not(feature = "migrations"))] -use namada_sdk::display_line; +use namada_apps_lib::display_line; +use namada_apps_lib::migrations::ScheduledMigration; +use namada_apps_lib::time::{DateTimeUtc, Utc}; +use namada_node as node; pub fn main() -> Result<()> { let (cmd, mut ctx) = cli::namada_node_cli()?; diff --git a/crates/apps/src/bin/namada-relayer/main.rs b/crates/apps/src/bin/namada-relayer/main.rs index 115b63296de..0208add846f 100644 --- a/crates/apps/src/bin/namada-relayer/main.rs +++ b/crates/apps/src/bin/namada-relayer/main.rs @@ -1,6 +1,6 @@ use color_eyre::eyre::Result; -use namada::tendermint_rpc::HttpClient; use namada_apps_lib::cli::api::{CliApi, CliIo}; +use namada_apps_lib::tendermint_rpc::HttpClient; use namada_apps_lib::{cli, logging}; use tracing_subscriber::filter::LevelFilter; diff --git a/crates/apps_lib/Cargo.toml b/crates/apps_lib/Cargo.toml index c839e51ee91..11b9686c4d2 100644 --- a/crates/apps_lib/Cargo.toml +++ b/crates/apps_lib/Cargo.toml @@ -18,8 +18,8 @@ mainnet = [ "namada_sdk/mainnet", ] # for integration tests and test utilities -testing = ["namada_test_utils", "lazy_static"] -benches = ["namada_test_utils", "lazy_static"] +testing = ["namada_test_utils", "lazy_static", "namada_sdk/testing"] +benches = ["namada_test_utils", "lazy_static", "namada_sdk/benches"] integration = [] migrations = [ "namada_migrations", @@ -31,10 +31,12 @@ namada-eth-bridge = [ ] [dependencies] +namada_core = {path = "../core"} namada_macros = {path = "../macros"} namada_migrations = {path = "../migrations", optional = true} -namada_sdk = {path = "../sdk", default-features = false, features = ["download-params", "std", "rand"]} +namada_sdk = {path = "../sdk", features = ["download-params", "multicore"]} namada_test_utils = {path = "../test_utils", optional = true} +namada_vm = {path = "../vm"} async-trait.workspace = true base64.workspace = true @@ -67,7 +69,7 @@ sha2.workspace = true tar.workspace = true tempfile.workspace = true tendermint-config.workspace = true -tendermint-rpc.workspace = true +tendermint-rpc = { workspace = true, features = ["http-client"] } textwrap-macros = "0.3.0" thiserror.workspace = true tokio = {workspace = true, features = ["full"]} @@ -79,6 +81,7 @@ tracing.workspace = true zeroize.workspace = true [dev-dependencies] +namada_sdk = {path = "../sdk", features = ["testing"]} namada_test_utils = {path = "../test_utils"} assert_matches.workspace = true diff --git a/crates/apps_lib/src/cli.rs b/crates/apps_lib/src/cli.rs index eadf78063ab..83cf3d45779 100644 --- a/crates/apps_lib/src/cli.rs +++ b/crates/apps_lib/src/cli.rs @@ -15,7 +15,7 @@ pub mod wallet; use clap::{ArgGroup, ArgMatches, ColorChoice}; use color_eyre::eyre::Result; -use namada::io::StdIo; +use namada_sdk::io::StdIo; use utils::*; pub use utils::{safe_exit, Cmd}; @@ -3076,23 +3076,21 @@ pub mod args { use std::str::FromStr; use data_encoding::HEXUPPER; - use namada::core::address::{Address, EstablishedAddress}; - use namada::core::chain::{ChainId, ChainIdPrefix}; - use namada::core::collections::HashMap; - use namada::core::dec::Dec; - use namada::core::ethereum_events::EthAddress; - use namada::core::keccak::KeccakHash; - use namada::core::key::*; - use namada::core::masp::PaymentAddress; - use namada::core::storage::{self, BlockHeight, Epoch}; - use namada::core::time::DateTimeUtc; - use namada::core::token; - use namada::core::token::NATIVE_MAX_DECIMAL_PLACES; - use namada::hash::Hash; - use namada::ibc::core::host::types::identifiers::{ChannelId, PortId}; - use namada::masp::MaspEpoch; - use namada::tx::data::GasLimit; + use namada_sdk::address::{Address, EstablishedAddress}; pub use namada_sdk::args::*; + use namada_sdk::chain::{ChainId, ChainIdPrefix}; + use namada_sdk::collections::HashMap; + use namada_sdk::dec::Dec; + use namada_sdk::ethereum_events::EthAddress; + use namada_sdk::hash::Hash; + use namada_sdk::ibc::core::host::types::identifiers::{ChannelId, PortId}; + use namada_sdk::keccak::KeccakHash; + use namada_sdk::key::*; + use namada_sdk::masp::{MaspEpoch, PaymentAddress}; + use namada_sdk::storage::{self, BlockHeight, Epoch}; + use namada_sdk::time::DateTimeUtc; + use namada_sdk::token::NATIVE_MAX_DECIMAL_PLACES; + use namada_sdk::tx::data::GasLimit; pub use namada_sdk::tx::{ TX_BECOME_VALIDATOR_WASM, TX_BOND_WASM, TX_BRIDGE_POOL_WASM, TX_CHANGE_COMMISSION_WASM, TX_CHANGE_CONSENSUS_KEY_WASM, @@ -3105,7 +3103,7 @@ pub mod args { TX_UPDATE_ACCOUNT_WASM, TX_UPDATE_STEWARD_COMMISSION, TX_VOTE_PROPOSAL, TX_WITHDRAW_WASM, VP_USER_WASM, }; - use namada_sdk::DEFAULT_GAS_LIMIT; + use namada_sdk::{token, DEFAULT_GAS_LIMIT}; use super::context::*; use super::utils::*; diff --git a/crates/apps_lib/src/cli/api.rs b/crates/apps_lib/src/cli/api.rs index 2dd8d9c9c83..b41520a94f0 100644 --- a/crates/apps_lib/src/cli/api.rs +++ b/crates/apps_lib/src/cli/api.rs @@ -1,10 +1,10 @@ -use namada::io::Io; -use namada::tendermint_rpc::HttpClient; use namada_sdk::error::Error; +use namada_sdk::io::Io; use namada_sdk::queries::Client; use namada_sdk::rpc::wait_until_node_is_synched; -use tendermint_rpc::client::CompatMode; -use tendermint_rpc::Url as TendermintUrl; + +use crate::facade::tendermint_rpc::client::CompatMode; +use crate::facade::tendermint_rpc::{HttpClient, Url as TendermintUrl}; /// Trait for clients that can be used with the CLI. #[async_trait::async_trait(?Send)] diff --git a/crates/apps_lib/src/cli/client.rs b/crates/apps_lib/src/cli/client.rs index 79103a9f3d1..99702a65421 100644 --- a/crates/apps_lib/src/cli/client.rs +++ b/crates/apps_lib/src/cli/client.rs @@ -2,7 +2,7 @@ use std::io::Read; use color_eyre::eyre::Result; use masp_primitives::zip32::ExtendedFullViewingKey; -use namada::io::Io; +use namada_sdk::io::Io; use namada_sdk::{display_line, Namada, NamadaImpl}; use crate::cli; diff --git a/crates/apps_lib/src/cli/context.rs b/crates/apps_lib/src/cli/context.rs index db94b7ad9a1..2d3ba7b0d1f 100644 --- a/crates/apps_lib/src/cli/context.rs +++ b/crates/apps_lib/src/cli/context.rs @@ -6,16 +6,15 @@ use std::path::{Path, PathBuf}; use std::str::FromStr; use color_eyre::eyre::Result; -use namada::core::address::{Address, InternalAddress}; -use namada::core::chain::ChainId; -use namada::core::ethereum_events::EthAddress; -use namada::core::key::*; -use namada::core::masp::*; -use namada::ibc::{is_ibc_denom, is_nft_trace}; -use namada::io::Io; -use namada::ledger::ibc::storage::ibc_token; +use namada_sdk::address::{Address, InternalAddress}; +use namada_sdk::chain::ChainId; +use namada_sdk::ethereum_events::EthAddress; +use namada_sdk::ibc::storage::ibc_token; +use namada_sdk::ibc::{is_ibc_denom, is_nft_trace}; +use namada_sdk::io::Io; +use namada_sdk::key::*; use namada_sdk::masp::fs::FsShieldedUtils; -use namada_sdk::masp::ShieldedContext; +use namada_sdk::masp::{ShieldedContext, *}; use namada_sdk::wallet::Wallet; use namada_sdk::{Namada, NamadaImpl}; @@ -226,7 +225,7 @@ impl Context { /// Make an implementation of Namada from this object and parameters. pub fn to_sdk(self, client: C, io: IO) -> impl Namada where - C: namada::ledger::queries::Client + Sync, + C: namada_sdk::queries::Client + Sync, IO: Io, { let chain_ctx = self.take_chain_or_exit(); diff --git a/crates/apps_lib/src/cli/relayer.rs b/crates/apps_lib/src/cli/relayer.rs index 96995deed7d..fc84673a361 100644 --- a/crates/apps_lib/src/cli/relayer.rs +++ b/crates/apps_lib/src/cli/relayer.rs @@ -1,5 +1,5 @@ use color_eyre::eyre::Result; -use namada::io::Io; +use namada_sdk::io::Io; use crate::cli; use crate::cli::api::{CliApi, CliClient}; diff --git a/crates/apps_lib/src/cli/utils.rs b/crates/apps_lib/src/cli/utils.rs index 3c5280e2aaa..c33e4cf1554 100644 --- a/crates/apps_lib/src/cli/utils.rs +++ b/crates/apps_lib/src/cli/utils.rs @@ -8,10 +8,10 @@ use std::sync::Arc; use clap::{ArgAction, ArgMatches}; use color_eyre::eyre::Result; use data_encoding::HEXLOWER_PERMISSIVE; -use namada::eth_bridge::ethers::core::k256::elliptic_curve::SecretKey as Secp256k1Sk; -use namada::eth_bridge::ethers::middleware::SignerMiddleware; -use namada::eth_bridge::ethers::providers::{Http, Middleware, Provider}; -use namada::eth_bridge::ethers::signers::{Signer, Wallet}; +use namada_sdk::eth_bridge::ethers::core::k256::elliptic_curve::SecretKey as Secp256k1Sk; +use namada_sdk::eth_bridge::ethers::middleware::SignerMiddleware; +use namada_sdk::eth_bridge::ethers::providers::{Http, Middleware, Provider}; +use namada_sdk::eth_bridge::ethers::signers::{Signer, Wallet}; use super::args; use super::context::Context; diff --git a/crates/apps_lib/src/cli/wallet.rs b/crates/apps_lib/src/cli/wallet.rs index 4eeab319f6c..546b3a8dacb 100644 --- a/crates/apps_lib/src/cli/wallet.rs +++ b/crates/apps_lib/src/cli/wallet.rs @@ -12,11 +12,12 @@ use ledger_namada_rs::{BIP44Path, NamadaApp}; use ledger_transport_hid::hidapi::HidApi; use ledger_transport_hid::TransportNativeHID; use masp_primitives::zip32::ExtendedFullViewingKey; -use namada::core::address::{Address, DecodeError}; -use namada::core::key::*; -use namada::core::masp::{ExtendedSpendingKey, MaspValue, PaymentAddress}; -use namada::io::Io; -use namada_sdk::masp::find_valid_diversifier; +use namada_sdk::address::{Address, DecodeError}; +use namada_sdk::io::Io; +use namada_sdk::key::*; +use namada_sdk::masp::{ + find_valid_diversifier, ExtendedSpendingKey, MaspValue, PaymentAddress, +}; use namada_sdk::wallet::{ DecryptionError, DerivationPath, DerivationPathError, FindKeyError, Wallet, }; diff --git a/crates/apps_lib/src/client/rpc.rs b/crates/apps_lib/src/client/rpc.rs index 941fa834444..3267d20bd0c 100644 --- a/crates/apps_lib/src/client/rpc.rs +++ b/crates/apps_lib/src/client/rpc.rs @@ -10,44 +10,42 @@ use masp_primitives::merkle_tree::MerklePath; use masp_primitives::sapling::Node; use masp_primitives::transaction::components::I128Sum; use masp_primitives::zip32::ExtendedFullViewingKey; -use namada::core::address::{Address, InternalAddress, MASP}; -use namada::core::collections::{HashMap, HashSet}; -use namada::core::hash::Hash; -use namada::core::key::*; -use namada::core::masp::BalanceOwner; -use namada::core::storage::{BlockHeight, BlockResults, Epoch}; -use namada::core::token::MaspDigitPos; -use namada::governance::parameters::GovernanceParameters; -use namada::governance::pgf::parameters::PgfParameters; -use namada::governance::pgf::storage::steward::StewardDetail; -use namada::governance::storage::keys as governance_storage; -use namada::governance::storage::proposal::{ +use namada_sdk::address::{Address, InternalAddress, MASP}; +use namada_sdk::collections::{HashMap, HashSet}; +use namada_sdk::control_flow::time::{Duration, Instant}; +use namada_sdk::events::Event; +use namada_sdk::governance::parameters::GovernanceParameters; +use namada_sdk::governance::pgf::parameters::PgfParameters; +use namada_sdk::governance::pgf::storage::steward::StewardDetail; +use namada_sdk::governance::storage::keys as governance_storage; +use namada_sdk::governance::storage::proposal::{ StoragePgfFunding, StorageProposal, }; -use namada::governance::utils::{ProposalVotes, VotePower}; -use namada::governance::ProposalVote; -use namada::io::Io; -use namada::ledger::events::Event; -use namada::ledger::parameters::{storage as param_storage, EpochDuration}; -use namada::ledger::pos::types::{CommissionPair, Slash}; -use namada::ledger::pos::PosParams; -use namada::ledger::queries::RPC; -use namada::masp::MaspEpoch; -use namada::proof_of_stake::types::{ - ValidatorState, ValidatorStateInfo, WeightedValidator, +use namada_sdk::governance::utils::{ProposalVotes, VotePower}; +use namada_sdk::governance::ProposalVote; +use namada_sdk::hash::Hash; +use namada_sdk::io::Io; +use namada_sdk::key::*; +use namada_sdk::masp::{BalanceOwner, MaspEpoch, MaspTokenRewardData}; +use namada_sdk::parameters::{storage as param_storage, EpochDuration}; +use namada_sdk::proof_of_stake::types::{ + CommissionPair, Slash, ValidatorMetaData, ValidatorState, + ValidatorStateInfo, WeightedValidator, }; -use namada::{state as storage, token}; -use namada_sdk::control_flow::time::{Duration, Instant}; -use namada_sdk::masp::MaspTokenRewardData; -use namada_sdk::proof_of_stake::types::ValidatorMetaData; -use namada_sdk::queries::Client; +use namada_sdk::proof_of_stake::PosParams; +use namada_sdk::queries::{Client, RPC}; use namada_sdk::rpc::{ self, enriched_bonds_and_unbonds, query_epoch, TxResponse, }; +use namada_sdk::storage::{BlockHeight, BlockResults, Epoch}; use namada_sdk::tendermint_rpc::endpoint::status; +use namada_sdk::token::MaspDigitPos; use namada_sdk::tx::display_batch_resp; use namada_sdk::wallet::AddressVpType; -use namada_sdk::{display, display_line, edisplay_line, error, Namada}; +use namada_sdk::{ + display, display_line, edisplay_line, error, state as storage, token, + Namada, +}; use crate::cli::{self, args}; use crate::facade::tendermint::merkle::proof::ProofOps; @@ -145,7 +143,7 @@ pub async fn query_block(context: &impl Namada) { } /// Query the results of the last committed block -pub async fn query_results( +pub async fn query_results( client: &C, _args: args::Query, ) -> Vec { @@ -338,7 +336,7 @@ pub async fn query_proposal(context: &impl Namada, args: args::QueryProposal) { } /// Query proposal by Id -pub async fn query_proposal_by_id( +pub async fn query_proposal_by_id( client: &C, proposal_id: u64, ) -> Result, error::Error> { @@ -782,7 +780,7 @@ pub async fn query_protocol_parameters( ); } -pub async fn query_bond( +pub async fn query_bond( client: &C, source: &Address, validator: &Address, @@ -794,7 +792,7 @@ pub async fn query_bond( } pub async fn query_unbond_with_slashing< - C: namada::ledger::queries::Client + Sync, + C: namada_sdk::queries::Client + Sync, >( client: &C, source: &Address, @@ -808,7 +806,7 @@ pub async fn query_unbond_with_slashing< ) } -pub async fn query_pos_parameters( +pub async fn query_pos_parameters( client: &C, ) -> PosParams { unwrap_client_response::( @@ -816,7 +814,7 @@ pub async fn query_pos_parameters( ) } -pub async fn query_consensus_keys( +pub async fn query_consensus_keys( client: &C, ) -> BTreeSet { unwrap_client_response::>( @@ -824,19 +822,19 @@ pub async fn query_consensus_keys( ) } -pub async fn query_pgf_stewards( +pub async fn query_pgf_stewards( client: &C, ) -> Vec { unwrap_client_response::(RPC.vp().pgf().stewards(client).await) } -pub async fn query_pgf_fundings( +pub async fn query_pgf_fundings( client: &C, ) -> Vec { unwrap_client_response::(RPC.vp().pgf().funding(client).await) } -pub async fn query_pgf_parameters( +pub async fn query_pgf_parameters( client: &C, ) -> PgfParameters { unwrap_client_response::(RPC.vp().pgf().parameters(client).await) @@ -884,7 +882,7 @@ pub async fn query_and_print_unbonds( } pub async fn query_withdrawable_tokens< - C: namada::ledger::queries::Client + Sync, + C: namada_sdk::queries::Client + Sync, >( client: &C, bond_source: &Address, @@ -1140,9 +1138,7 @@ pub async fn query_bonded_stake( /// Query and return validator's commission rate and max commission rate change /// per epoch -pub async fn query_commission_rate< - C: namada::ledger::queries::Client + Sync, ->( +pub async fn query_commission_rate( client: &C, validator: &Address, epoch: Option, @@ -1156,7 +1152,7 @@ pub async fn query_commission_rate< } /// Query and return validator's metadata -pub async fn query_metadata( +pub async fn query_metadata( client: &C, validator: &Address, ) -> Option { @@ -1166,9 +1162,7 @@ pub async fn query_metadata( } /// Query and return validator's state -pub async fn query_validator_state< - C: namada::ledger::queries::Client + Sync, ->( +pub async fn query_validator_state( client: &C, validator: &Address, epoch: Option, @@ -1182,7 +1176,7 @@ pub async fn query_validator_state< } /// Query and return the available reward tokens corresponding to the bond -pub async fn query_rewards( +pub async fn query_rewards( client: &C, source: &Option
, validator: &Address, @@ -1642,7 +1636,7 @@ pub async fn query_find_validator( } /// Get account's public key stored in its storage sub-space -pub async fn get_public_key( +pub async fn get_public_key( client: &C, address: &Address, index: u8, @@ -1651,7 +1645,7 @@ pub async fn get_public_key( } /// Check if the given address has any bonds. -pub async fn is_validator( +pub async fn is_validator( client: &C, address: &Address, ) -> bool { @@ -1661,7 +1655,7 @@ pub async fn is_validator( } /// Check if a given address is a known delegator -pub async fn is_delegator( +pub async fn is_delegator( client: &C, address: &Address, ) -> bool { @@ -1670,7 +1664,7 @@ pub async fn is_delegator( .unwrap() } -pub async fn is_delegator_at( +pub async fn is_delegator_at( client: &C, address: &Address, epoch: Epoch, @@ -1681,7 +1675,7 @@ pub async fn is_delegator_at( } /// Check if the given address has any bonds. -pub async fn has_bonds( +pub async fn has_bonds( client: &C, address: &Address, ) -> bool { @@ -1691,7 +1685,7 @@ pub async fn has_bonds( /// Check if the address exists on chain. Established address exists if it has a /// stored validity predicate. Implicit and internal addresses always return /// true. -pub async fn known_address( +pub async fn known_address( client: &C, address: &Address, ) -> bool { @@ -1766,7 +1760,7 @@ pub async fn query_conversions( } /// Query a conversion. -pub async fn query_conversion( +pub async fn query_conversion( client: &C, asset_type: AssetType, ) -> Option<( @@ -1816,7 +1810,7 @@ pub async fn query_wasm_code_hash( } /// Query a storage value and decode it with [`BorshDeserialize`]. -pub async fn query_storage_value( +pub async fn query_storage_value( client: &C, key: &storage::Key, ) -> Result @@ -1828,7 +1822,7 @@ where /// Query a storage value and the proof without decoding. pub async fn query_storage_value_bytes< - C: namada::ledger::queries::Client + Sync, + C: namada_sdk::queries::Client + Sync, >( client: &C, key: &storage::Key, @@ -1854,9 +1848,7 @@ where } /// Query to check if the given storage key exists. -pub async fn query_has_storage_key< - C: namada::ledger::queries::Client + Sync, ->( +pub async fn query_has_storage_key( client: &C, key: &storage::Key, ) -> bool { @@ -1867,13 +1859,11 @@ pub async fn query_has_storage_key< /// Call the corresponding `tx_event_query` RPC method, to fetch /// the current status of a transaction. -pub async fn query_tx_events( +pub async fn query_tx_events( client: &C, tx_event_query: namada_sdk::rpc::TxEventQuery<'_>, -) -> std::result::Result< - Option, - ::Error, -> { +) -> std::result::Result, ::Error> +{ namada_sdk::rpc::query_tx_events(client, tx_event_query).await } @@ -1923,7 +1913,7 @@ pub async fn epoch_sleep(context: &impl Namada, _args: args::Query) { } } -pub async fn get_bond_amount_at( +pub async fn get_bond_amount_at( client: &C, delegator: &Address, validator: &Address, @@ -1938,7 +1928,7 @@ pub async fn get_bond_amount_at( Some(total_active) } -pub async fn get_all_validators( +pub async fn get_all_validators( client: &C, epoch: Epoch, ) -> HashSet
{ @@ -1947,9 +1937,7 @@ pub async fn get_all_validators( .unwrap() } -pub async fn get_total_staked_tokens< - C: namada::ledger::queries::Client + Sync, ->( +pub async fn get_total_staked_tokens( client: &C, epoch: Epoch, ) -> token::Amount { @@ -1962,7 +1950,7 @@ pub async fn get_total_staked_tokens< /// sum of validator's self-bonds and delegations to their address. /// Returns `None` when the given address is not a validator address. For a /// validator with `0` stake, this returns `Ok(token::Amount::zero())`. -async fn get_validator_stake( +async fn get_validator_stake( client: &C, epoch: Epoch, validator: &Address, @@ -1976,7 +1964,7 @@ async fn get_validator_stake( } pub async fn get_delegation_validators< - C: namada::ledger::queries::Client + Sync, + C: namada_sdk::queries::Client + Sync, >( client: &C, address: &Address, @@ -1988,7 +1976,7 @@ pub async fn get_delegation_validators< } pub async fn get_delegations_of_delegator_at< - C: namada::ledger::queries::Client + Sync, + C: namada_sdk::queries::Client + Sync, >( client: &C, address: &Address, @@ -2000,7 +1988,7 @@ pub async fn get_delegations_of_delegator_at< } pub async fn query_governance_parameters< - C: namada::ledger::queries::Client + Sync, + C: namada_sdk::queries::Client + Sync, >( client: &C, ) -> GovernanceParameters { @@ -2008,7 +1996,7 @@ pub async fn query_governance_parameters< } /// A helper to unwrap client's response. Will shut down process on error. -fn unwrap_client_response( +fn unwrap_client_response( response: Result, ) -> T { response.unwrap_or_else(|err| { @@ -2017,9 +2005,7 @@ fn unwrap_client_response( }) } -pub async fn compute_proposal_votes< - C: namada::ledger::queries::Client + Sync, ->( +pub async fn compute_proposal_votes( client: &C, proposal_id: u64, epoch: Epoch, diff --git a/crates/apps_lib/src/client/tx.rs b/crates/apps_lib/src/client/tx.rs index 80e6e52e092..ce85cb95807 100644 --- a/crates/apps_lib/src/client/tx.rs +++ b/crates/apps_lib/src/client/tx.rs @@ -5,17 +5,17 @@ use borsh_ext::BorshSerializeExt; use ledger_namada_rs::{BIP44Path, NamadaApp}; use ledger_transport_hid::hidapi::HidApi; use ledger_transport_hid::TransportNativeHID; -use namada::core::address::{Address, ImplicitAddress}; -use namada::core::collections::HashSet; -use namada::core::key::*; -use namada::governance::cli::onchain::{ +use namada_sdk::address::{Address, ImplicitAddress}; +use namada_sdk::args::TxBecomeValidator; +use namada_sdk::collections::HashSet; +use namada_sdk::governance::cli::onchain::{ DefaultProposal, PgfFundingProposal, PgfStewardProposal, }; -use namada::io::Io; -use namada::state::EPOCH_SWITCH_BLOCKS_DELAY; -use namada::tx::{CompressedAuthorization, Section, Signer, Tx}; -use namada_sdk::args::TxBecomeValidator; +use namada_sdk::io::Io; +use namada_sdk::key::*; use namada_sdk::rpc::{InnerTxResult, TxBroadcastData, TxResponse}; +use namada_sdk::state::EPOCH_SWITCH_BLOCKS_DELAY; +use namada_sdk::tx::{CompressedAuthorization, Section, Signer, Tx}; use namada_sdk::wallet::alias::{validator_address, validator_consensus_key}; use namada_sdk::wallet::{Wallet, WalletIo}; use namada_sdk::{display_line, edisplay_line, error, signing, tx, Namada}; @@ -246,7 +246,7 @@ pub async fn submit_custom( args: args::TxCustom, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { submit_reveal_aux(namada, args.tx.clone(), &args.owner).await?; @@ -268,7 +268,7 @@ pub async fn submit_update_account( args: args::TxUpdateAccount, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let (mut tx, signing_data) = args.build(namada).await?; @@ -288,7 +288,7 @@ pub async fn submit_init_account( args: args::TxInitAccount, ) -> Result, error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let (mut tx, signing_data) = tx::build_init_account(namada, &args).await?; @@ -364,7 +364,7 @@ pub async fn submit_change_consensus_key( // To avoid wallet deadlocks in following operations drop(wallet); - let args = namada::sdk::args::ConsensusKeyChange { + let args = args::ConsensusKeyChange { validator: validator.clone(), consensus_key: Some(new_key.clone()), ..args @@ -833,7 +833,7 @@ pub async fn submit_ibc_transfer( args: args::TxIbcTransfer, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { submit_reveal_aux( namada, @@ -861,7 +861,7 @@ pub async fn submit_init_proposal( args: args::InitProposal, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let current_epoch = rpc::query_and_print_epoch(namada).await; let governance_parameters = @@ -961,7 +961,7 @@ pub async fn submit_vote_proposal( args: args::VoteProposal, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let (mut tx_builder, signing_data) = args.build(namada).await?; @@ -985,7 +985,7 @@ pub async fn sign_tx( }: args::SignTx, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let tx = if let Ok(transaction) = Tx::deserialize(tx_data.as_ref()) { transaction @@ -1062,7 +1062,7 @@ pub async fn submit_reveal_pk( args: args::RevealPk, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { submit_reveal_aux(namada, args.tx, &(&args.public_key).into()).await?; @@ -1074,7 +1074,7 @@ pub async fn submit_bond( args: args::Bond, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let default_address = args.source.clone().unwrap_or(args.validator.clone()); submit_reveal_aux(namada, args.tx.clone(), &default_address).await?; @@ -1097,7 +1097,7 @@ pub async fn submit_unbond( args: args::Unbond, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let (mut tx, signing_data, latest_withdrawal_pre) = args.build(namada).await?; @@ -1123,7 +1123,7 @@ pub async fn submit_withdraw( args: args::Withdraw, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let (mut tx, signing_data) = args.build(namada).await?; @@ -1143,7 +1143,7 @@ pub async fn submit_claim_rewards( args: args::ClaimRewards, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let (mut tx, signing_data) = args.build(namada).await?; @@ -1163,7 +1163,7 @@ pub async fn submit_redelegate( args: args::Redelegate, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let (mut tx, signing_data) = args.build(namada).await?; @@ -1183,7 +1183,7 @@ pub async fn submit_validator_commission_change( args: args::CommissionRateChange, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let (mut tx, signing_data) = args.build(namada).await?; @@ -1203,7 +1203,7 @@ pub async fn submit_validator_metadata_change( args: args::MetaDataChange, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let (mut tx, signing_data) = args.build(namada).await?; @@ -1223,7 +1223,7 @@ pub async fn submit_unjail_validator( args: args::TxUnjailValidator, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let (mut tx, signing_data) = args.build(namada).await?; @@ -1243,7 +1243,7 @@ pub async fn submit_deactivate_validator( args: args::TxDeactivateValidator, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let (mut tx, signing_data) = args.build(namada).await?; @@ -1263,7 +1263,7 @@ pub async fn submit_reactivate_validator( args: args::TxReactivateValidator, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let (mut tx, signing_data) = args.build(namada).await?; @@ -1283,7 +1283,7 @@ pub async fn submit_update_steward_commission( args: args::UpdateStewardCommission, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let (mut tx, signing_data) = args.build(namada).await?; @@ -1303,7 +1303,7 @@ pub async fn submit_resign_steward( args: args::ResignSteward, ) -> Result<(), error::Error> where - ::Error: std::fmt::Display, + ::Error: std::fmt::Display, { let (mut tx, signing_data) = args.build(namada).await?; diff --git a/crates/apps_lib/src/client/utils.rs b/crates/apps_lib/src/client/utils.rs index d7c112dc855..274532ef9f8 100644 --- a/crates/apps_lib/src/client/utils.rs +++ b/crates/apps_lib/src/client/utils.rs @@ -9,14 +9,14 @@ use flate2::read::GzDecoder; use flate2::write::GzEncoder; use flate2::Compression; use itertools::Either; -use namada::core::chain::ChainId; -use namada::core::dec::Dec; -use namada::core::key::*; -use namada::core::string_encoding::StringEncoded; -use namada::core::token; -use namada::core::uint::Uint; -use namada::vm::validate_untrusted_wasm; +use namada_sdk::chain::ChainId; +use namada_sdk::dec::Dec; +use namada_sdk::key::*; +use namada_sdk::string_encoding::StringEncoded; +use namada_sdk::token; +use namada_sdk::uint::Uint; use namada_sdk::wallet::{alias, Wallet}; +use namada_vm::validate_untrusted_wasm; use prost::bytes::Bytes; use serde_json::json; use sha2::{Digest, Sha256}; diff --git a/crates/apps_lib/src/config/ethereum_bridge/ledger.rs b/crates/apps_lib/src/config/ethereum_bridge/ledger.rs index c1117c44b51..ccde2830822 100644 --- a/crates/apps_lib/src/config/ethereum_bridge/ledger.rs +++ b/crates/apps_lib/src/config/ethereum_bridge/ledger.rs @@ -1,6 +1,6 @@ //! Runtime configuration for a validator node. #[allow(unused_imports)] -use namada::core::ethereum_events::EthereumEvent; +use namada_sdk::ethereum_events::EthereumEvent; use serde::{Deserialize, Serialize}; /// Default [Ethereum JSON-RPC](https://ethereum.org/en/developers/docs/apis/json-rpc/) endpoint used by the oracle diff --git a/crates/apps_lib/src/config/genesis.rs b/crates/apps_lib/src/config/genesis.rs index d6e5d970468..e45888c475a 100644 --- a/crates/apps_lib/src/config/genesis.rs +++ b/crates/apps_lib/src/config/genesis.rs @@ -12,23 +12,22 @@ use std::str::FromStr; use borsh::{BorshDeserialize, BorshSerialize}; use derivative::Derivative; -use namada::core::address::{Address, EstablishedAddress}; -use namada::core::chain::ProposalBytes; -use namada::core::collections::HashMap; -use namada::core::key::*; -use namada::core::storage; -use namada::core::string_encoding::StringEncoded; -use namada::core::time::{DateTimeUtc, DurationSecs}; -use namada::core::token::Denomination; -use namada::governance::parameters::GovernanceParameters; -use namada::governance::pgf::parameters::PgfParameters; -use namada::ledger::eth_bridge::EthereumBridgeParams; -use namada::ledger::parameters::EpochDuration; -use namada::ledger::pos::{Dec, GenesisValidator, OwnedPosParams}; -use namada::token; use namada_macros::BorshDeserializer; #[cfg(feature = "migrations")] use namada_migrations::*; +use namada_sdk::address::{Address, EstablishedAddress}; +use namada_sdk::chain::ProposalBytes; +use namada_sdk::collections::HashMap; +use namada_sdk::eth_bridge::EthereumBridgeParams; +use namada_sdk::governance::parameters::GovernanceParameters; +use namada_sdk::governance::pgf::parameters::PgfParameters; +use namada_sdk::key::*; +use namada_sdk::parameters::EpochDuration; +use namada_sdk::proof_of_stake::{Dec, GenesisValidator, OwnedPosParams}; +use namada_sdk::string_encoding::StringEncoded; +use namada_sdk::time::{DateTimeUtc, DurationSecs}; +use namada_sdk::token::Denomination; +use namada_sdk::{storage, token}; use serde::{Deserialize, Serialize}; #[derive( @@ -336,13 +335,13 @@ pub fn make_dev_genesis( use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::time::Duration; - use namada::core::address::testing::wnam; - use namada::core::chain::ChainIdPrefix; - use namada::core::ethereum_events::EthAddress; - use namada::core::key::*; - use namada::ledger::eth_bridge::{Contracts, UpgradeableContract}; - use namada::ledger::pos::types::ValidatorMetaData; - use namada::tx::standalone_signature; + use namada_sdk::address::testing::wnam; + use namada_sdk::chain::ChainIdPrefix; + use namada_sdk::eth_bridge::{Contracts, UpgradeableContract}; + use namada_sdk::ethereum_events::EthAddress; + use namada_sdk::key::*; + use namada_sdk::proof_of_stake::types::ValidatorMetaData; + use namada_sdk::tx::standalone_signature; use namada_sdk::wallet::alias::Alias; use crate::config::genesis::chain::{ @@ -581,8 +580,8 @@ pub fn make_dev_genesis( #[cfg(test)] pub mod tests { use borsh_ext::BorshSerializeExt; - use namada::core::address::testing::gen_established_address; - use namada::core::key::*; + use namada_sdk::address::testing::gen_established_address; + use namada_sdk::key::*; use rand::prelude::ThreadRng; use rand::thread_rng; diff --git a/crates/apps_lib/src/config/genesis/chain.rs b/crates/apps_lib/src/config/genesis/chain.rs index 690d67909f0..d7bd8a5a2e9 100644 --- a/crates/apps_lib/src/config/genesis/chain.rs +++ b/crates/apps_lib/src/config/genesis/chain.rs @@ -4,19 +4,21 @@ use std::str::FromStr; use borsh::{BorshDeserialize, BorshSerialize}; use borsh_ext::BorshSerializeExt; -use namada::address::InternalAddress; -use namada::core::address::{ - Address, EstablishedAddress, EstablishedAddressGen, -}; -use namada::core::chain::{ChainId, ChainIdPrefix}; -use namada::core::hash::Hash; -use namada::core::key::{common, RefTo}; -use namada::core::time::{DateTimeUtc, DurationNanos, Rfc3339String}; -use namada::core::token::Amount; -use namada::ledger::parameters::EpochDuration; use namada_macros::BorshDeserializer; #[cfg(feature = "migrations")] use namada_migrations::*; +use namada_sdk::address::{ + Address, EstablishedAddress, EstablishedAddressGen, InternalAddress, +}; +use namada_sdk::chain::{ChainId, ChainIdPrefix}; +use namada_sdk::eth_bridge::EthereumBridgeParams; +use namada_sdk::governance::pgf::parameters::PgfParameters; +use namada_sdk::hash::Hash; +use namada_sdk::ibc::parameters::IbcParameters; +use namada_sdk::key::{common, RefTo}; +use namada_sdk::parameters::EpochDuration; +use namada_sdk::time::{DateTimeUtc, DurationNanos, Rfc3339String}; +use namada_sdk::token::Amount; use namada_sdk::wallet::store::AddressVpType; use namada_sdk::wallet::{pre_genesis, Wallet}; use serde::{Deserialize, Serialize}; @@ -293,7 +295,7 @@ impl Finalized { pub fn get_chain_parameters( &self, wasm_dir: impl AsRef, - ) -> namada::ledger::parameters::Parameters { + ) -> namada_sdk::parameters::Parameters { let templates::ChainParams { min_num_of_blocks, max_expected_time_per_block, @@ -330,16 +332,16 @@ impl Finalized { let min_duration: i64 = 60 * 60 * 24 * 365 / epy_i64; let epoch_duration = EpochDuration { min_num_of_blocks, - min_duration: namada::core::time::Duration::seconds(min_duration) + min_duration: namada_sdk::time::Duration::seconds(min_duration) .into(), }; let max_expected_time_per_block = - namada::core::time::Duration::seconds(max_expected_time_per_block) + namada_sdk::time::Duration::seconds(max_expected_time_per_block) .into(); let vp_allowlist = vp_allowlist.unwrap_or_default(); let tx_allowlist = tx_allowlist.unwrap_or_default(); - namada::ledger::parameters::Parameters { + namada_sdk::parameters::Parameters { max_tx_bytes, epoch_duration, max_expected_time_per_block, @@ -367,7 +369,7 @@ impl Finalized { pub fn get_pos_params( &self, - ) -> namada::proof_of_stake::parameters::PosParams { + ) -> namada_sdk::proof_of_stake::parameters::PosParams { let templates::PosParams { max_validator_slots, pipeline_len, @@ -387,8 +389,8 @@ impl Finalized { rewards_gain_d, } = self.parameters.pos_params.clone(); - namada::proof_of_stake::parameters::PosParams { - owned: namada::proof_of_stake::parameters::OwnedPosParams { + namada_sdk::proof_of_stake::parameters::PosParams { + owned: namada_sdk::proof_of_stake::parameters::OwnedPosParams { max_validator_slots, pipeline_len, unbonding_len, @@ -412,7 +414,7 @@ impl Finalized { pub fn get_gov_params( &self, - ) -> namada::governance::parameters::GovernanceParameters { + ) -> namada_sdk::governance::parameters::GovernanceParameters { let templates::GovernanceParams { min_proposal_fund, max_proposal_code_size, @@ -422,7 +424,7 @@ impl Finalized { min_proposal_grace_epochs, max_proposal_latency, } = self.parameters.gov_params.clone(); - namada::governance::parameters::GovernanceParameters { + namada_sdk::governance::parameters::GovernanceParameters { min_proposal_fund: Amount::native_whole(min_proposal_fund), max_proposal_code_size, max_proposal_period, @@ -433,15 +435,11 @@ impl Finalized { } } - pub fn get_pgf_params( - &self, - ) -> namada::governance::pgf::parameters::PgfParameters { + pub fn get_pgf_params(&self) -> PgfParameters { self.parameters.pgf_params.clone() } - pub fn get_eth_bridge_params( - &self, - ) -> Option { + pub fn get_eth_bridge_params(&self) -> Option { if let Some(templates::EthBridgeParams { eth_start_height, min_confirmations, @@ -449,7 +447,7 @@ impl Finalized { erc20_whitelist, }) = self.parameters.eth_bridge_params.clone() { - Some(namada::ledger::eth_bridge::EthereumBridgeParams { + Some(EthereumBridgeParams { eth_start_height, min_confirmations, erc20_whitelist, @@ -460,12 +458,12 @@ impl Finalized { } } - pub fn get_ibc_params(&self) -> namada::ibc::parameters::IbcParameters { + pub fn get_ibc_params(&self) -> IbcParameters { let templates::IbcParams { default_mint_limit, default_per_epoch_throughput_limit, } = self.parameters.ibc_params.clone(); - namada::ibc::parameters::IbcParameters { + IbcParameters { default_mint_limit, default_per_epoch_throughput_limit, } @@ -738,7 +736,7 @@ pub struct FinalizedParameters { pub parameters: templates::ChainParams, pub pos_params: templates::PosParams, pub gov_params: templates::GovernanceParams, - pub pgf_params: namada::governance::pgf::parameters::PgfParameters, + pub pgf_params: PgfParameters, pub eth_bridge_params: Option, pub ibc_params: templates::IbcParams, } @@ -754,7 +752,7 @@ impl FinalizedParameters { ibc_params, }: templates::Parameters, ) -> Self { - use namada::governance::pgf::parameters::PgfParameters; + use PgfParameters; let finalized_pgf_params = PgfParameters { stewards: pgf_params.stewards, pgf_inflation_rate: pgf_params.pgf_inflation_rate, diff --git a/crates/apps_lib/src/config/genesis/templates.rs b/crates/apps_lib/src/config/genesis/templates.rs index db5ac13772e..26f51c02c17 100644 --- a/crates/apps_lib/src/config/genesis/templates.rs +++ b/crates/apps_lib/src/config/genesis/templates.rs @@ -5,20 +5,19 @@ use std::marker::PhantomData; use std::path::Path; use borsh::{BorshDeserialize, BorshSerialize}; -use namada::core::address::Address; -use namada::core::chain::ProposalBytes; -use namada::core::dec::Dec; -use namada::core::ethereum_structs; -use namada::core::token::{ - Amount, DenominatedAmount, Denomination, NATIVE_MAX_DECIMAL_PLACES, -}; -use namada::eth_bridge::storage::parameters::{ - Contracts, Erc20WhitelistEntry, MinimumConfirmations, -}; -use namada::token; use namada_macros::BorshDeserializer; #[cfg(feature = "migrations")] use namada_migrations::*; +use namada_sdk::address::Address; +use namada_sdk::chain::ProposalBytes; +use namada_sdk::dec::Dec; +use namada_sdk::eth_bridge::storage::parameters::{ + Contracts, Erc20WhitelistEntry, MinimumConfirmations, +}; +use namada_sdk::token::{ + Amount, DenominatedAmount, Denomination, NATIVE_MAX_DECIMAL_PLACES, +}; +use namada_sdk::{ethereum_structs, token}; use serde::{Deserialize, Serialize}; use super::transactions::{self, Transactions}; @@ -991,9 +990,9 @@ mod tests { use std::fs; use std::path::PathBuf; - use namada::core::key; - use namada::core::key::RefTo; - use namada::core::string_encoding::StringEncoded; + use namada_sdk::key; + use namada_sdk::key::RefTo; + use namada_sdk::string_encoding::StringEncoded; use tempfile::tempdir; use super::*; diff --git a/crates/apps_lib/src/config/genesis/transactions.rs b/crates/apps_lib/src/config/genesis/transactions.rs index b7015a9032a..83dbcc6a6a7 100644 --- a/crates/apps_lib/src/config/genesis/transactions.rs +++ b/crates/apps_lib/src/config/genesis/transactions.rs @@ -10,31 +10,29 @@ use itertools::{Either, Itertools}; use ledger_namada_rs::NamadaApp; use ledger_transport_hid::hidapi::HidApi; use ledger_transport_hid::TransportNativeHID; -use namada::account::AccountPublicKeysMap; -use namada::core::address::{Address, EstablishedAddress}; -use namada::core::chain::ChainId; -use namada::core::collections::HashSet; -use namada::core::dec::Dec; -use namada::core::key::{ - common, ed25519, RefTo, SerializeWithBorsh, SigScheme, -}; -use namada::core::string_encoding::StringEncoded; -use namada::core::time::DateTimeUtc; -use namada::core::token; -use namada::core::token::{DenominatedAmount, NATIVE_MAX_DECIMAL_PLACES}; -use namada::ledger::pos::common::PublicKey; -use namada::ledger::pos::types::ValidatorMetaData; -use namada::proof_of_stake::parameters::MAX_VALIDATOR_METADATA_LEN; -use namada::tx::data::{pos, Fee, TxType}; -use namada::tx::{ - verify_standalone_sig, Code, Commitment, Data, Section, SignatureIndex, Tx, -}; use namada_macros::BorshDeserializer; #[cfg(feature = "migrations")] use namada_migrations::*; +use namada_sdk::account::AccountPublicKeysMap; +use namada_sdk::address::{Address, EstablishedAddress}; use namada_sdk::args::Tx as TxArgs; +use namada_sdk::chain::ChainId; +use namada_sdk::collections::HashSet; +use namada_sdk::dec::Dec; +use namada_sdk::key::common::PublicKey; +use namada_sdk::key::{common, ed25519, RefTo, SerializeWithBorsh, SigScheme}; +use namada_sdk::proof_of_stake::parameters::MAX_VALIDATOR_METADATA_LEN; +use namada_sdk::proof_of_stake::types::ValidatorMetaData; use namada_sdk::signing::{sign_tx, SigningTxData}; -use namada_sdk::tx::{TX_BECOME_VALIDATOR_WASM, TX_BOND_WASM}; +use namada_sdk::string_encoding::StringEncoded; +use namada_sdk::time::DateTimeUtc; +use namada_sdk::token; +use namada_sdk::token::{DenominatedAmount, NATIVE_MAX_DECIMAL_PLACES}; +use namada_sdk::tx::data::{pos, Fee, TxType}; +use namada_sdk::tx::{ + verify_standalone_sig, Code, Commitment, Data, Section, SignatureIndex, Tx, + TX_BECOME_VALIDATOR_WASM, TX_BOND_WASM, +}; use namada_sdk::wallet::alias::Alias; use namada_sdk::wallet::pre_genesis::ValidatorWallet; use namada_sdk::wallet::Wallet; @@ -364,7 +362,7 @@ pub async fn sign_validator_account_tx( tx_data: &T, keypair: &common::SecretKey, ) -> StringEncoded { - StringEncoded::new(namada::tx::standalone_signature::< + StringEncoded::new(namada_sdk::tx::standalone_signature::< T, SerializeWithBorsh, >(keypair, tx_data)) @@ -548,7 +546,7 @@ impl Transactions { stakes.into_values().any(|stake| { let tendermint_voting_power = - namada::ledger::pos::into_tm_voting_power( + namada_sdk::proof_of_stake::types::into_tm_voting_power( votes_per_token, stake, ); diff --git a/crates/apps_lib/src/config/genesis/utils.rs b/crates/apps_lib/src/config/genesis/utils.rs index ea1acd9cbd6..ee8d6bcadda 100644 --- a/crates/apps_lib/src/config/genesis/utils.rs +++ b/crates/apps_lib/src/config/genesis/utils.rs @@ -3,9 +3,9 @@ use std::path::Path; use eyre::Context; use ledger_namada_rs::NamadaApp; use ledger_transport_hid::TransportNativeHID; -use namada::core::collections::HashSet; -use namada::core::key::common; -use namada::tx::Tx; +use namada_sdk::collections::HashSet; +use namada_sdk::key::common; +use namada_sdk::tx::Tx; use namada_sdk::wallet::Wallet; use namada_sdk::{error, signing}; use serde::de::DeserializeOwned; diff --git a/crates/apps_lib/src/config/global.rs b/crates/apps_lib/src/config/global.rs index ef1d5ecf5d7..c9656c722f7 100644 --- a/crates/apps_lib/src/config/global.rs +++ b/crates/apps_lib/src/config/global.rs @@ -4,7 +4,7 @@ use std::fs::{create_dir_all, File}; use std::io::Write; use std::path::{Path, PathBuf}; -use namada::core::chain::ChainId; +use namada_sdk::chain::ChainId; use serde::{Deserialize, Serialize}; use thiserror::Error; diff --git a/crates/apps_lib/src/config/mod.rs b/crates/apps_lib/src/config/mod.rs index c6484d10b00..687c335a94f 100644 --- a/crates/apps_lib/src/config/mod.rs +++ b/crates/apps_lib/src/config/mod.rs @@ -10,10 +10,10 @@ use std::io::Write; use std::path::{Path, PathBuf}; use directories::ProjectDirs; -use namada::core::chain::ChainId; -use namada::core::collections::HashMap; -use namada::core::storage::BlockHeight; -use namada::core::time::Rfc3339String; +use namada_sdk::chain::ChainId; +use namada_sdk::collections::HashMap; +use namada_sdk::storage::BlockHeight; +use namada_sdk::time::Rfc3339String; use serde::{Deserialize, Serialize}; use thiserror::Error; @@ -45,7 +45,7 @@ pub struct Config { #[derive(Debug, Serialize, Deserialize)] pub struct ValidatorLocalConfig { pub accepted_gas_tokens: - HashMap, + HashMap, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] diff --git a/crates/apps_lib/src/lib.rs b/crates/apps_lib/src/lib.rs index 58cdcbf701c..29a18fd78b0 100644 --- a/crates/apps_lib/src/lib.rs +++ b/crates/apps_lib/src/lib.rs @@ -21,14 +21,15 @@ pub mod logging; pub mod tendermint_node; pub mod wallet; pub mod wasm_loader; - // This is here only to include the std's docs in our docs. // Taken from . #[doc(inline)] pub use std; +pub use namada_sdk::*; + pub mod facade { // TODO(namada#3248): only re-export v037 `tendermint-rs` - pub use namada::{tendermint, tendermint_proto, tendermint_rpc}; - pub use tendermint_config; + pub use namada_core::{tendermint, tendermint_proto}; + pub use {tendermint_config, tendermint_rpc}; } diff --git a/crates/apps_lib/src/tendermint_node.rs b/crates/apps_lib/src/tendermint_node.rs index 17b6d4a9ecb..1fc100e0276 100644 --- a/crates/apps_lib/src/tendermint_node.rs +++ b/crates/apps_lib/src/tendermint_node.rs @@ -1,7 +1,7 @@ use std::path::{Path, PathBuf}; use borsh_ext::BorshSerializeExt; -use namada::core::key::*; +use namada_sdk::key::*; use serde_json::json; use sha2::{Digest, Sha256}; use thiserror::Error; diff --git a/crates/apps_lib/src/wallet/defaults.rs b/crates/apps_lib/src/wallet/defaults.rs index 2393b28c6b7..7ea0c136d9e 100644 --- a/crates/apps_lib/src/wallet/defaults.rs +++ b/crates/apps_lib/src/wallet/defaults.rs @@ -11,16 +11,17 @@ pub use dev::{ #[cfg(any(test, feature = "testing", feature = "benches"))] mod dev { use lazy_static::lazy_static; - use namada::core::address::testing::{ + use namada_sdk::address::testing::{ apfel, btc, dot, eth, kartoffel, nam, schnitzel, }; - use namada::core::address::Address; - use namada::core::collections::HashMap; - use namada::core::key::*; - use namada::ledger::{governance, pgf, pos}; + use namada_sdk::address::Address; + use namada_sdk::collections::HashMap; + use namada_sdk::governance::pgf; + use namada_sdk::key::*; use namada_sdk::wallet::alias::Alias; use namada_sdk::wallet::pre_genesis::ValidatorWallet; use namada_sdk::wallet::Wallet; + use namada_sdk::{governance, proof_of_stake}; use crate::wallet::CliWalletUtils; @@ -68,8 +69,8 @@ mod dev { /// The default addresses with their aliases. pub fn addresses() -> HashMap { let mut addresses: HashMap = vec![ - ("pos".into(), pos::ADDRESS), - ("pos_slash_pool".into(), pos::SLASH_POOL_ADDRESS), + ("pos".into(), proof_of_stake::ADDRESS), + ("pos_slash_pool".into(), proof_of_stake::SLASH_POOL_ADDRESS), ("governance".into(), governance::ADDRESS), ("governance".into(), pgf::ADDRESS), ("validator".into(), validator_address()), @@ -78,7 +79,7 @@ mod dev { ("christel".into(), christel_address()), ("daewon".into(), daewon_address()), ("ester".into(), ester_address()), - ("masp".into(), namada::core::address::MASP), + ("masp".into(), namada_sdk::address::MASP), ] .into_iter() .collect(); diff --git a/crates/apps_lib/src/wallet/mod.rs b/crates/apps_lib/src/wallet/mod.rs index 70cb3c78691..c95bdebf0db 100644 --- a/crates/apps_lib/src/wallet/mod.rs +++ b/crates/apps_lib/src/wallet/mod.rs @@ -6,8 +6,8 @@ use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::{env, fs}; -use namada::bip39::{Language, Mnemonic}; -use namada::core::key::*; +use namada_sdk::bip39::{Language, Mnemonic}; +use namada_sdk::key::*; pub use namada_sdk::wallet::alias::Alias; use namada_sdk::wallet::fs::FsWalletStorage; use namada_sdk::wallet::store::Store; @@ -286,7 +286,7 @@ pub fn read_and_confirm_encryption_password( #[cfg(test)] mod tests { - use namada::bip39::MnemonicType; + use namada_sdk::bip39::MnemonicType; use namada_sdk::wallet::WalletIo; use super::CliWalletUtils; diff --git a/crates/apps_lib/src/wallet/pre_genesis.rs b/crates/apps_lib/src/wallet/pre_genesis.rs index a39a8358f65..d383688831c 100644 --- a/crates/apps_lib/src/wallet/pre_genesis.rs +++ b/crates/apps_lib/src/wallet/pre_genesis.rs @@ -3,7 +3,7 @@ use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use fd_lock::RwLock; -use namada::core::key::SchemeType; +use namada_sdk::key::SchemeType; use namada_sdk::wallet::pre_genesis::{ ReadError, ValidatorStore, ValidatorWallet, }; diff --git a/crates/apps_lib/src/wallet/store.rs b/crates/apps_lib/src/wallet/store.rs index 20021765a58..15cce41b6f5 100644 --- a/crates/apps_lib/src/wallet/store.rs +++ b/crates/apps_lib/src/wallet/store.rs @@ -1,6 +1,6 @@ use std::path::{Path, PathBuf}; -use namada::core::key::*; +use namada_sdk::key::*; use namada_sdk::wallet::{ gen_secret_key, LoadStoreError, Store, ValidatorKeys, }; @@ -59,7 +59,7 @@ pub fn gen_validator_keys( #[cfg(test)] mod test_wallet { - use namada::core::address::Address; + use namada_sdk::address::Address; use super::*; diff --git a/crates/apps_lib/src/wasm_loader/mod.rs b/crates/apps_lib/src/wasm_loader/mod.rs index 30cb874be7d..f9f9be70f4c 100644 --- a/crates/apps_lib/src/wasm_loader/mod.rs +++ b/crates/apps_lib/src/wasm_loader/mod.rs @@ -6,7 +6,7 @@ use std::path::Path; use data_encoding::HEXLOWER; use eyre::{eyre, WrapErr}; use futures::future::join_all; -use namada::core::collections::HashMap; +use namada_sdk::collections::HashMap; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use thiserror::Error; diff --git a/crates/benches/Cargo.toml b/crates/benches/Cargo.toml index 947db3698be..0cf8131cf55 100644 --- a/crates/benches/Cargo.toml +++ b/crates/benches/Cargo.toml @@ -41,10 +41,13 @@ namada-eth-bridge = [ # NOTE: this crate MUST NOT import any dependency with testing features to prevent benchmarking non-production code [dev-dependencies] -namada_apps_lib = { path = "../apps_lib" } +namada_apps_lib = { path = "../apps_lib", features = ["benches"] } namada_node = { path = "../node", features = ["benches"] } +namada_vm = { path = "../vm", features = ["wasm-runtime"] } +namada_vp = { path = "../vp" } + masp_primitives.workspace = true -masp_proofs = { workspace = true, features = ["benchmarks"] } +masp_proofs = { workspace = true, features = ["benchmarks", "multicore"] } borsh.workspace = true borsh-ext.workspace = true criterion = { version = "0.5", features = ["html_reports"] } diff --git a/crates/benches/README.md b/crates/benches/README.md index 2bdf837424f..d98268b9d6e 100644 --- a/crates/benches/README.md +++ b/crates/benches/README.md @@ -6,7 +6,7 @@ Measurements are taken on the elapsed wall-time. The benchmarks only focus on successful transactions and vps: in case of failure, the bench function shall panic to avoid timing incomplete execution paths. -In addition, this crate also contains benchmarks for `WrapperTx` (`namada::core::transaction::wrapper::WrapperTx`) validation and `host_env` (`namada::vm::host_env`) exposed functions that define the gas constants of `gas` (`namada::core::ledger::gas`). +In addition, this crate also contains benchmarks for `WrapperTx` (`namada_apps_lib::tx::wrapper::WrapperTx`) validation and `host_env` (`namada_vm::host_env`) exposed functions that define the gas constants of `gas` (`namada_apps_lib::gas`). For more realistic results these benchmarks should be run on all the combination of supported OS/architecture. diff --git a/crates/benches/host_env.rs b/crates/benches/host_env.rs index 1eee5611631..c5b8e1e2f9b 100644 --- a/crates/benches/host_env.rs +++ b/crates/benches/host_env.rs @@ -1,18 +1,17 @@ use criterion::{criterion_group, criterion_main, Criterion}; -use namada::core::account::AccountPublicKeysMap; -use namada::core::address; -use namada::core::collections::{HashMap, HashSet}; -use namada::ledger::storage::DB; -use namada::token::{Amount, TransparentTransfer}; -use namada::tx::Authorization; -use namada::vm::wasm::TxCache; +use namada_apps_lib::account::AccountPublicKeysMap; +use namada_apps_lib::collections::{HashMap, HashSet}; +use namada_apps_lib::storage::DB; +use namada_apps_lib::token::{Amount, TransparentTransfer}; +use namada_apps_lib::tx::Authorization; use namada_apps_lib::wallet::defaults; -use namada_apps_lib::wasm_loader; +use namada_apps_lib::{address, storage, wasm_loader}; use namada_node::bench_utils::{ BenchShell, TX_INIT_PROPOSAL_WASM, TX_REVEAL_PK_WASM, TX_TRANSPARENT_TRANSFER_WASM, TX_UPDATE_ACCOUNT_WASM, VP_USER_WASM, WASM_DIR, }; +use namada_vm::wasm::TxCache; // Benchmarks the validation of a single signature on a single `Section` of a // transaction @@ -128,7 +127,7 @@ fn untrusted_wasm_validation(c: &mut Criterion) { let len = wasm_code.len() as u64; group.throughput(criterion::Throughput::Bytes(len)); group.bench_function(format!("Tx: {tx}, size: {len}"), |b| { - b.iter(|| namada::vm::validate_untrusted_wasm(&wasm_code).unwrap()) + b.iter(|| namada_vm::validate_untrusted_wasm(&wasm_code).unwrap()) }); } group.finish(); @@ -181,7 +180,7 @@ fn write_log_read(c: &mut Criterion) { let mut shell = BenchShell::default(); for (key, value_len) in generate_random_keys_sized() { - let key = namada::core::storage::Key::parse(key).unwrap(); + let key = storage::Key::parse(key).unwrap(); // Extract the throughput, together with the wall-time, so that we can // than invert it to calculate the desired metric (time/byte) // NOTE: criterion states that the throughput is measured on the @@ -212,7 +211,7 @@ fn storage_read(c: &mut Criterion) { let mut shell = BenchShell::default(); for (key, value_len) in generate_random_keys_sized() { - let key = namada::core::storage::Key::parse(key).unwrap(); + let key = storage::Key::parse(key).unwrap(); // Extract the throughput, together with the wall-time, so that we can // than invert it to calculate the desired metric (time/byte) // NOTE: criterion states that the throughput is measured on the @@ -246,7 +245,7 @@ fn write_log_write(c: &mut Criterion) { let mut shell = BenchShell::default(); for (key, value_len) in generate_random_keys_sized() { - let key = namada::core::storage::Key::parse(key).unwrap(); + let key = storage::Key::parse(key).unwrap(); // Extract the throughput, together with the wall-time, so that we can // than invert it to calculate the desired metric (time/byte) // NOTE: criterion states that the throughput is measured on the @@ -281,7 +280,7 @@ fn storage_write(c: &mut Criterion) { let mut shell = BenchShell::default(); for (key, value_len) in generate_random_keys_sized() { - let key = namada::core::storage::Key::parse(key).unwrap(); + let key = storage::Key::parse(key).unwrap(); // Extract the throughput, together with the wall-time, so that we can // than invert it to calculate the desired metric (time/byte) // NOTE: criterion states that the throughput is measured on the diff --git a/crates/benches/native_vps.rs b/crates/benches/native_vps.rs index 298c37fcf55..98b2e3c781a 100644 --- a/crates/benches/native_vps.rs +++ b/crates/benches/native_vps.rs @@ -12,52 +12,47 @@ use masp_primitives::transaction::txid::TxIdDigester; use masp_primitives::transaction::TransactionData; use masp_proofs::group::GroupEncoding; use masp_proofs::sapling::BatchValidator; -use namada::core::address::{self, Address, InternalAddress}; -use namada::core::collections::HashMap; -use namada::core::eth_bridge_pool::{GasFee, PendingTransfer}; -use namada::core::masp::{TransferSource, TransferTarget}; -use namada::eth_bridge::storage::eth_bridge_queries::is_bridge_comptime_enabled; -use namada::eth_bridge::storage::whitelist; -use namada::governance::pgf::storage::steward::StewardDetail; -use namada::governance::storage::proposal::ProposalType; -use namada::governance::storage::vote::ProposalVote; -use namada::governance::{InitProposalData, VoteProposalData}; -use namada::ibc::core::channel::types::channel::Order; -use namada::ibc::core::channel::types::msgs::MsgChannelOpenInit; -use namada::ibc::core::channel::types::Version as ChannelVersion; -use namada::ibc::core::commitment_types::commitment::CommitmentPrefix; -use namada::ibc::core::connection::types::msgs::MsgConnectionOpenInit; -use namada::ibc::core::connection::types::version::Version; -use namada::ibc::core::connection::types::Counterparty; -use namada::ibc::core::host::types::identifiers::{ +use namada_apps_lib::address::{self, Address, InternalAddress}; +use namada_apps_lib::collections::HashMap; +use namada_apps_lib::eth_bridge::read_native_erc20_address; +use namada_apps_lib::eth_bridge::storage::eth_bridge_queries::is_bridge_comptime_enabled; +use namada_apps_lib::eth_bridge::storage::whitelist; +use namada_apps_lib::eth_bridge_pool::{GasFee, PendingTransfer}; +use namada_apps_lib::gas::{TxGasMeter, VpGasMeter}; +use namada_apps_lib::governance::pgf::storage::steward::StewardDetail; +use namada_apps_lib::governance::storage::proposal::ProposalType; +use namada_apps_lib::governance::storage::vote::ProposalVote; +use namada_apps_lib::governance::{InitProposalData, VoteProposalData}; +use namada_apps_lib::ibc::core::channel::types::channel::Order; +use namada_apps_lib::ibc::core::channel::types::msgs::MsgChannelOpenInit; +use namada_apps_lib::ibc::core::channel::types::Version as ChannelVersion; +use namada_apps_lib::ibc::core::commitment_types::commitment::CommitmentPrefix; +use namada_apps_lib::ibc::core::connection::types::msgs::MsgConnectionOpenInit; +use namada_apps_lib::ibc::core::connection::types::version::Version; +use namada_apps_lib::ibc::core::connection::types::Counterparty; +use namada_apps_lib::ibc::core::host::types::identifiers::{ ClientId, ConnectionId, PortId, }; -use namada::ibc::primitives::ToProto; -use namada::ibc::{IbcActions, NftTransferModule, TransferModule}; -use namada::ledger::eth_bridge::read_native_erc20_address; -use namada::ledger::gas::{TxGasMeter, VpGasMeter}; -use namada::ledger::governance::GovernanceVp; -use namada::ledger::native_vp::ethereum_bridge::bridge_pool_vp::BridgePoolVp; -use namada::ledger::native_vp::ethereum_bridge::nut::NonUsableTokens; -use namada::ledger::native_vp::ethereum_bridge::vp::EthBridge; -use namada::ledger::native_vp::ibc::context::PseudoExecutionContext; -use namada::ledger::native_vp::ibc::Ibc; -use namada::ledger::native_vp::masp::MaspVp; -use namada::ledger::native_vp::multitoken::MultitokenVp; -use namada::ledger::native_vp::parameters::ParametersVp; -use namada::ledger::native_vp::{Ctx, NativeVp}; -use namada::ledger::pgf::PgfVp; -use namada::ledger::pos::PosVP; -use namada::proof_of_stake; -use namada::proof_of_stake::KeySeg; -use namada::sdk::masp::{partial_deauthorize, preload_verifying_keys, PVKs}; -use namada::sdk::masp_primitives::merkle_tree::CommitmentTree; -use namada::sdk::masp_primitives::transaction::Transaction; -use namada::sdk::masp_proofs::sapling::SaplingVerificationContextInner; -use namada::state::{Epoch, StorageRead, StorageWrite, TxIndex}; -use namada::token::{Amount, TransparentTransfer}; -use namada::tx::{BatchedTx, Code, Section, Tx}; +use namada_apps_lib::ibc::primitives::ToProto; +use namada_apps_lib::ibc::vp::context::PseudoExecutionContext; +use namada_apps_lib::ibc::{IbcActions, NftTransferModule, TransferModule}; +use namada_apps_lib::masp::{ + partial_deauthorize, preload_verifying_keys, PVKs, TransferSource, + TransferTarget, +}; +use namada_apps_lib::masp_primitives::merkle_tree::CommitmentTree; +use namada_apps_lib::masp_primitives::transaction::Transaction; +use namada_apps_lib::masp_proofs::sapling::SaplingVerificationContextInner; +use namada_apps_lib::proof_of_stake::KeySeg; +use namada_apps_lib::state::{Epoch, StorageRead, StorageWrite, TxIndex}; +use namada_apps_lib::token::{Amount, TransparentTransfer}; +use namada_apps_lib::tx::{BatchedTx, Code, Section, Tx}; +use namada_apps_lib::validation::{ + EthBridgeNutVp, EthBridgePoolVp, EthBridgeVp, GovernanceVp, IbcVp, MaspVp, + MultitokenVp, ParametersVp, PgfVp, PosVp, +}; use namada_apps_lib::wallet::defaults; +use namada_apps_lib::{governance, proof_of_stake, storage, token}; use namada_node::bench_utils::{ generate_foreign_key_tx, BenchShell, BenchShieldedCtx, ALBERT_PAYMENT_ADDRESS, ALBERT_SPENDING_KEY, BERTHA_PAYMENT_ADDRESS, @@ -65,6 +60,7 @@ use namada_node::bench_utils::{ TX_TRANSPARENT_TRANSFER_WASM, TX_UPDATE_STEWARD_COMMISSION, TX_VOTE_PROPOSAL_WASM, }; +use namada_vp::native_vp::{Ctx, NativeVp}; use rand_core::OsRng; fn governance(c: &mut Criterion) { @@ -145,9 +141,9 @@ fn governance(c: &mut Criterion) { } "complete_proposal" => { let max_code_size_key = - namada::governance::storage::keys::get_max_proposal_code_size_key(); + governance::storage::keys::get_max_proposal_code_size_key(); let max_proposal_content_key = - namada::governance::storage::keys::get_max_proposal_content_key(); + governance::storage::keys::get_max_proposal_content_key(); let max_code_size: u64 = shell .state .read(&max_code_size_key) @@ -212,19 +208,17 @@ fn governance(c: &mut Criterion) { let gas_meter = RefCell::new(VpGasMeter::new_from_tx_meter( &TxGasMeter::new_from_sub_limit(u64::MAX.into()), )); - let governance = GovernanceVp { - ctx: Ctx::new( - &Address::Internal(InternalAddress::Governance), - &shell.state, - &signed_tx.tx, - &signed_tx.cmt, - &TxIndex(0), - &gas_meter, - &keys_changed, - &verifiers, - shell.vp_wasm_cache.clone(), - ), - }; + let governance = GovernanceVp::new(Ctx::new( + &Address::Internal(InternalAddress::Governance), + &shell.state, + &signed_tx.tx, + &signed_tx.cmt, + &TxIndex(0), + &gas_meter, + &keys_changed, + &verifiers, + shell.vp_wasm_cache.clone(), + )); group.bench_function(bench_name, |b| { b.iter(|| { @@ -323,11 +317,10 @@ fn prepare_ibc_tx_and_ctx(bench_name: &str) -> (BenchShieldedCtx, BatchedTx) { match bench_name { "open_connection" => { let mut shielded_ctx = BenchShieldedCtx::default(); - let _ = shielded_ctx.shell.init_ibc_client_state( - namada::core::storage::Key::from( + let _ = + shielded_ctx.shell.init_ibc_client_state(storage::Key::from( Address::Internal(InternalAddress::Ibc).to_db_key(), - ), - ); + )); let msg = MsgConnectionOpenInit { client_id_on_a: ClientId::new("07-tendermint", 1).unwrap(), counterparty: Counterparty::new( @@ -436,19 +429,17 @@ fn ibc(c: &mut Criterion) { let gas_meter = RefCell::new(VpGasMeter::new_from_tx_meter( &TxGasMeter::new_from_sub_limit(u64::MAX.into()), )); - let ibc = Ibc { - ctx: Ctx::new( - &Address::Internal(InternalAddress::Ibc), - &shielded_ctx.shell.state, - &signed_tx.tx, - &signed_tx.cmt, - &TxIndex(0), - &gas_meter, - &keys_changed, - &verifiers, - shielded_ctx.shell.vp_wasm_cache.clone(), - ), - }; + let ibc = IbcVp::new(Ctx::new( + &Address::Internal(InternalAddress::Ibc), + &shielded_ctx.shell.state, + &signed_tx.tx, + &signed_tx.cmt, + &TxIndex(0), + &gas_meter, + &keys_changed, + &verifiers, + shielded_ctx.shell.vp_wasm_cache.clone(), + )); group.bench_function(bench_name, |b| { b.iter(|| { @@ -501,19 +492,17 @@ fn vp_multitoken(c: &mut Criterion) { let gas_meter = RefCell::new(VpGasMeter::new_from_tx_meter( &TxGasMeter::new_from_sub_limit(u64::MAX.into()), )); - let multitoken = MultitokenVp { - ctx: Ctx::new( - &Address::Internal(InternalAddress::Multitoken), - &shell.state, - &signed_tx.tx, - &signed_tx.cmt, - &TxIndex(0), - &gas_meter, - &keys_changed, - &verifiers, - shell.vp_wasm_cache.clone(), - ), - }; + let multitoken = MultitokenVp::new(Ctx::new( + &Address::Internal(InternalAddress::Multitoken), + &shell.state, + &signed_tx.tx, + &signed_tx.cmt, + &TxIndex(0), + &gas_meter, + &keys_changed, + &verifiers, + shell.vp_wasm_cache.clone(), + )); group.bench_function(bench_name, |b| { b.iter(|| { @@ -566,12 +555,11 @@ fn setup_storage_for_masp_verification( shielded_ctx.shell.commit_masp_tx(shield_tx.tx); // Update the anchor in storage - let tree_key = namada::token::storage_key::masp_commitment_tree_key(); + let tree_key = token::storage_key::masp_commitment_tree_key(); let updated_tree: CommitmentTree = shielded_ctx.shell.state.read(&tree_key).unwrap().unwrap(); - let anchor_key = namada::token::storage_key::masp_commitment_anchor_key( - updated_tree.root(), - ); + let anchor_key = + token::storage_key::masp_commitment_anchor_key(updated_tree.root()); shielded_ctx.shell.state.write(&anchor_key, ()).unwrap(); shielded_ctx.shell.commit_block(); @@ -614,19 +602,17 @@ fn masp(c: &mut Criterion) { let gas_meter = RefCell::new(VpGasMeter::new_from_tx_meter( &TxGasMeter::new_from_sub_limit(u64::MAX.into()), )); - let masp = MaspVp { - ctx: Ctx::new( - &Address::Internal(InternalAddress::Masp), - &shielded_ctx.shell.state, - &signed_tx.tx, - &signed_tx.cmt, - &TxIndex(0), - &gas_meter, - &keys_changed, - &verifiers, - shielded_ctx.shell.vp_wasm_cache.clone(), - ), - }; + let masp = MaspVp::new(Ctx::new( + &Address::Internal(InternalAddress::Masp), + &shielded_ctx.shell.state, + &signed_tx.tx, + &signed_tx.cmt, + &TxIndex(0), + &gas_meter, + &keys_changed, + &verifiers, + shielded_ctx.shell.vp_wasm_cache.clone(), + )); b.iter(|| { assert!( @@ -1178,7 +1164,7 @@ fn pgf(c: &mut Criterion) { "steward_inflation_rate", ] { let mut shell = BenchShell::default(); - namada::governance::pgf::storage::keys::stewards_handle() + namada_apps_lib::governance::pgf::storage::keys::stewards_handle() .insert( &mut shell.state, defaults::albert_address(), @@ -1198,13 +1184,14 @@ fn pgf(c: &mut Criterion) { vec![&defaults::albert_keypair()], ), "steward_inflation_rate" => { - let data = namada::tx::data::pgf::UpdateStewardCommission { - steward: defaults::albert_address(), - commission: HashMap::from([( - defaults::albert_address(), - namada::core::dec::Dec::zero(), - )]), - }; + let data = + namada_apps_lib::tx::data::pgf::UpdateStewardCommission { + steward: defaults::albert_address(), + commission: HashMap::from([( + defaults::albert_address(), + namada_apps_lib::dec::Dec::zero(), + )]), + }; shell.generate_tx( TX_UPDATE_STEWARD_COMMISSION, data, @@ -1227,19 +1214,17 @@ fn pgf(c: &mut Criterion) { let gas_meter = RefCell::new(VpGasMeter::new_from_tx_meter( &TxGasMeter::new_from_sub_limit(u64::MAX.into()), )); - let pgf = PgfVp { - ctx: Ctx::new( - &Address::Internal(InternalAddress::Pgf), - &shell.state, - &signed_tx.tx, - &signed_tx.cmt, - &TxIndex(0), - &gas_meter, - &keys_changed, - &verifiers, - shell.vp_wasm_cache.clone(), - ), - }; + let pgf = PgfVp::new(Ctx::new( + &Address::Internal(InternalAddress::Pgf), + &shell.state, + &signed_tx.tx, + &signed_tx.cmt, + &TxIndex(0), + &gas_meter, + &keys_changed, + &verifiers, + shell.vp_wasm_cache.clone(), + )); group.bench_function(bench_name, |b| { b.iter(|| { @@ -1268,11 +1253,11 @@ fn eth_bridge_nut(c: &mut Criterion) { let signed_tx = { let data = PendingTransfer { - transfer: namada::core::eth_bridge_pool::TransferToEthereum { + transfer: namada_apps_lib::eth_bridge_pool::TransferToEthereum { kind: - namada::core::eth_bridge_pool::TransferToEthereumKind::Erc20, + namada_apps_lib::eth_bridge_pool::TransferToEthereumKind::Erc20, asset: native_erc20_addres, - recipient: namada::core::ethereum_events::EthAddress([1u8; 20]), + recipient: namada_apps_lib::ethereum_events::EthAddress([1u8; 20]), sender: defaults::albert_address(), amount: Amount::from(1), }, @@ -1304,19 +1289,17 @@ fn eth_bridge_nut(c: &mut Criterion) { let gas_meter = RefCell::new(VpGasMeter::new_from_tx_meter( &TxGasMeter::new_from_sub_limit(u64::MAX.into()), )); - let nut = NonUsableTokens { - ctx: Ctx::new( - &vp_address, - &shell.state, - &signed_tx.tx, - &signed_tx.cmt, - &TxIndex(0), - &gas_meter, - &keys_changed, - &verifiers, - shell.vp_wasm_cache.clone(), - ), - }; + let nut = EthBridgeNutVp::new(Ctx::new( + &vp_address, + &shell.state, + &signed_tx.tx, + &signed_tx.cmt, + &TxIndex(0), + &gas_meter, + &keys_changed, + &verifiers, + shell.vp_wasm_cache.clone(), + )); c.bench_function("vp_eth_bridge_nut", |b| { b.iter(|| { @@ -1342,11 +1325,11 @@ fn eth_bridge(c: &mut Criterion) { let signed_tx = { let data = PendingTransfer { - transfer: namada::core::eth_bridge_pool::TransferToEthereum { + transfer: namada_apps_lib::eth_bridge_pool::TransferToEthereum { kind: - namada::core::eth_bridge_pool::TransferToEthereumKind::Erc20, + namada_apps_lib::eth_bridge_pool::TransferToEthereumKind::Erc20, asset: native_erc20_addres, - recipient: namada::core::ethereum_events::EthAddress([1u8; 20]), + recipient: namada_apps_lib::ethereum_events::EthAddress([1u8; 20]), sender: defaults::albert_address(), amount: Amount::from(1), }, @@ -1377,19 +1360,17 @@ fn eth_bridge(c: &mut Criterion) { let gas_meter = RefCell::new(VpGasMeter::new_from_tx_meter( &TxGasMeter::new_from_sub_limit(u64::MAX.into()), )); - let eth_bridge = EthBridge { - ctx: Ctx::new( - &vp_address, - &shell.state, - &signed_tx.tx, - &signed_tx.cmt, - &TxIndex(0), - &gas_meter, - &keys_changed, - &verifiers, - shell.vp_wasm_cache.clone(), - ), - }; + let eth_bridge = EthBridgeVp::new(Ctx::new( + &vp_address, + &shell.state, + &signed_tx.tx, + &signed_tx.cmt, + &TxIndex(0), + &gas_meter, + &keys_changed, + &verifiers, + shell.vp_wasm_cache.clone(), + )); c.bench_function("vp_eth_bridge", |b| { b.iter(|| { @@ -1441,11 +1422,11 @@ fn eth_bridge_pool(c: &mut Criterion) { let signed_tx = { let data = PendingTransfer { - transfer: namada::core::eth_bridge_pool::TransferToEthereum { + transfer: namada_apps_lib::eth_bridge_pool::TransferToEthereum { kind: - namada::core::eth_bridge_pool::TransferToEthereumKind::Erc20, + namada_apps_lib::eth_bridge_pool::TransferToEthereumKind::Erc20, asset: native_erc20_addres, - recipient: namada::core::ethereum_events::EthAddress([1u8; 20]), + recipient: namada_apps_lib::ethereum_events::EthAddress([1u8; 20]), sender: defaults::albert_address(), amount: Amount::from(1), }, @@ -1476,19 +1457,17 @@ fn eth_bridge_pool(c: &mut Criterion) { let gas_meter = RefCell::new(VpGasMeter::new_from_tx_meter( &TxGasMeter::new_from_sub_limit(u64::MAX.into()), )); - let bridge_pool = BridgePoolVp { - ctx: Ctx::new( - &vp_address, - &shell.state, - &signed_tx.tx, - &signed_tx.cmt, - &TxIndex(0), - &gas_meter, - &keys_changed, - &verifiers, - shell.vp_wasm_cache.clone(), - ), - }; + let bridge_pool = EthBridgePoolVp::new(Ctx::new( + &vp_address, + &shell.state, + &signed_tx.tx, + &signed_tx.cmt, + &TxIndex(0), + &gas_meter, + &keys_changed, + &verifiers, + shell.vp_wasm_cache.clone(), + )); c.bench_function("vp_eth_bridge_pool", |b| { b.iter(|| { @@ -1521,15 +1500,18 @@ fn parameters(c: &mut Criterion) { "parameter_change" => { // Simulate governance proposal to modify a parameter let min_proposal_fund_key = - namada::governance::storage::keys::get_min_proposal_fund_key(); + namada_apps_lib::governance::storage::keys::get_min_proposal_fund_key(); shell.state.write(&min_proposal_fund_key, 1_000).unwrap(); - let proposal_key = namada::governance::storage::keys::get_proposal_execution_key(0); + let proposal_key = namada_apps_lib::governance::storage::keys::get_proposal_execution_key(0); shell.state.write(&proposal_key, 0).unwrap(); // Return a dummy tx for validation - let mut tx = Tx::from_type(namada::tx::data::TxType::Raw); - tx.set_data(namada::tx::Data::new(borsh::to_vec(&0).unwrap())); + let mut tx = + Tx::from_type(namada_apps_lib::tx::data::TxType::Raw); + tx.set_data(namada_apps_lib::tx::Data::new( + borsh::to_vec(&0).unwrap(), + )); let verifiers_from_tx = BTreeSet::default(); let cmt = tx.first_commitments().unwrap().clone(); let batched_tx = tx.batch_tx(cmt); @@ -1547,19 +1529,17 @@ fn parameters(c: &mut Criterion) { let gas_meter = RefCell::new(VpGasMeter::new_from_tx_meter( &TxGasMeter::new_from_sub_limit(u64::MAX.into()), )); - let parameters = ParametersVp { - ctx: Ctx::new( - &vp_address, - &shell.state, - &signed_tx.tx, - &signed_tx.cmt, - &TxIndex(0), - &gas_meter, - &keys_changed, - &verifiers, - shell.vp_wasm_cache.clone(), - ), - }; + let parameters = ParametersVp::new(Ctx::new( + &vp_address, + &shell.state, + &signed_tx.tx, + &signed_tx.cmt, + &TxIndex(0), + &gas_meter, + &keys_changed, + &verifiers, + shell.vp_wasm_cache.clone(), + )); group.bench_function(bench_name, |b| { b.iter(|| { @@ -1595,15 +1575,18 @@ fn pos(c: &mut Criterion) { "parameter_change" => { // Simulate governance proposal to modify a parameter let min_proposal_fund_key = - namada::governance::storage::keys::get_min_proposal_fund_key(); + namada_apps_lib::governance::storage::keys::get_min_proposal_fund_key(); shell.state.write(&min_proposal_fund_key, 1_000).unwrap(); - let proposal_key = namada::governance::storage::keys::get_proposal_execution_key(0); + let proposal_key = namada_apps_lib::governance::storage::keys::get_proposal_execution_key(0); shell.state.write(&proposal_key, 0).unwrap(); // Return a dummy tx for validation - let mut tx = Tx::from_type(namada::tx::data::TxType::Raw); - tx.set_data(namada::tx::Data::new(borsh::to_vec(&0).unwrap())); + let mut tx = + Tx::from_type(namada_apps_lib::tx::data::TxType::Raw); + tx.set_data(namada_apps_lib::tx::Data::new( + borsh::to_vec(&0).unwrap(), + )); let verifiers_from_tx = BTreeSet::default(); let cmt = tx.first_commitments().unwrap().clone(); let batched_tx = tx.batch_tx(cmt); @@ -1621,19 +1604,17 @@ fn pos(c: &mut Criterion) { let gas_meter = RefCell::new(VpGasMeter::new_from_tx_meter( &TxGasMeter::new_from_sub_limit(u64::MAX.into()), )); - let pos = PosVP { - ctx: Ctx::new( - &vp_address, - &shell.state, - &signed_tx.tx, - &signed_tx.cmt, - &TxIndex(0), - &gas_meter, - &keys_changed, - &verifiers, - shell.vp_wasm_cache.clone(), - ), - }; + let pos = PosVp::new(Ctx::new( + &vp_address, + &shell.state, + &signed_tx.tx, + &signed_tx.cmt, + &TxIndex(0), + &gas_meter, + &keys_changed, + &verifiers, + shell.vp_wasm_cache.clone(), + )); group.bench_function(bench_name, |b| { b.iter(|| { @@ -1675,24 +1656,25 @@ fn ibc_vp_validate_action(c: &mut Criterion) { let gas_meter = RefCell::new(VpGasMeter::new_from_tx_meter( &TxGasMeter::new_from_sub_limit(u64::MAX.into()), )); - let ibc = Ibc { - ctx: Ctx::new( - &Address::Internal(InternalAddress::Ibc), - &shielded_ctx.shell.state, - &signed_tx.tx, - &signed_tx.cmt, - &TxIndex(0), - &gas_meter, - &keys_changed, - &verifiers, - shielded_ctx.shell.vp_wasm_cache.clone(), - ), - }; + let ibc = IbcVp::new(Ctx::new( + &Address::Internal(InternalAddress::Ibc), + &shielded_ctx.shell.state, + &signed_tx.tx, + &signed_tx.cmt, + &TxIndex(0), + &gas_meter, + &keys_changed, + &verifiers, + shielded_ctx.shell.vp_wasm_cache.clone(), + )); // Use an empty verifiers set placeholder for validation, this is only // needed in actual txs to addresses whose VPs should be triggered let verifiers = Rc::new(RefCell::new(BTreeSet::
::new())); - let exec_ctx = PseudoExecutionContext::new(ibc.ctx.pre()); + let exec_ctx = + PseudoExecutionContext::<'_, '_, _, _, _, token::Store<_>>::new( + ibc.ctx.pre(), + ); let ctx = Rc::new(RefCell::new(exec_ctx)); let mut actions = IbcActions::new(ctx.clone(), verifiers.clone()); actions.set_validation_params(ibc.validation_params().unwrap()); @@ -1733,24 +1715,25 @@ fn ibc_vp_execute_action(c: &mut Criterion) { let gas_meter = RefCell::new(VpGasMeter::new_from_tx_meter( &TxGasMeter::new_from_sub_limit(u64::MAX.into()), )); - let ibc = Ibc { - ctx: Ctx::new( - &Address::Internal(InternalAddress::Ibc), - &shielded_ctx.shell.state, - &signed_tx.tx, - &signed_tx.cmt, - &TxIndex(0), - &gas_meter, - &keys_changed, - &verifiers, - shielded_ctx.shell.vp_wasm_cache.clone(), - ), - }; + let ibc = IbcVp::new(Ctx::new( + &Address::Internal(InternalAddress::Ibc), + &shielded_ctx.shell.state, + &signed_tx.tx, + &signed_tx.cmt, + &TxIndex(0), + &gas_meter, + &keys_changed, + &verifiers, + shielded_ctx.shell.vp_wasm_cache.clone(), + )); // Use an empty verifiers set placeholder for validation, this is only // needed in actual txs to addresses whose VPs should be triggered let verifiers = Rc::new(RefCell::new(BTreeSet::
::new())); - let exec_ctx = PseudoExecutionContext::new(ibc.ctx.pre()); + let exec_ctx = + PseudoExecutionContext::<'_, '_, _, _, _, token::Store<_>>::new( + ibc.ctx.pre(), + ); let ctx = Rc::new(RefCell::new(exec_ctx)); let mut actions = IbcActions::new(ctx.clone(), verifiers.clone()); diff --git a/crates/benches/process_wrapper.rs b/crates/benches/process_wrapper.rs index 9510ee31250..517118e0aba 100644 --- a/crates/benches/process_wrapper.rs +++ b/crates/benches/process_wrapper.rs @@ -1,11 +1,11 @@ use criterion::{criterion_group, criterion_main, Criterion}; -use namada::core::address; -use namada::core::key::RefTo; -use namada::core::storage::BlockHeight; -use namada::core::time::DateTimeUtc; -use namada::token::{Amount, DenominatedAmount, TransparentTransfer}; -use namada::tx::data::{Fee, WrapperTx}; -use namada::tx::Authorization; +use namada_apps_lib::address; +use namada_apps_lib::key::RefTo; +use namada_apps_lib::storage::BlockHeight; +use namada_apps_lib::time::DateTimeUtc; +use namada_apps_lib::token::{Amount, DenominatedAmount, TransparentTransfer}; +use namada_apps_lib::tx::data::{Fee, WrapperTx}; +use namada_apps_lib::tx::Authorization; use namada_apps_lib::wallet::defaults; use namada_node::bench_utils::{BenchShell, TX_TRANSPARENT_TRANSFER_WASM}; use namada_node::shell::process_proposal::ValidationMeta; @@ -32,7 +32,7 @@ fn process_tx(c: &mut Criterion) { batched_tx .tx - .update_header(namada::tx::data::TxType::Wrapper(Box::new( + .update_header(namada_apps_lib::tx::data::TxType::Wrapper(Box::new( WrapperTx::new( Fee { token: address::testing::nam(), @@ -44,11 +44,13 @@ fn process_tx(c: &mut Criterion) { ))); batched_tx .tx - .add_section(namada::tx::Section::Authorization(Authorization::new( - batched_tx.tx.sechashes(), - [(0, defaults::albert_keypair())].into_iter().collect(), - None, - ))); + .add_section(namada_apps_lib::tx::Section::Authorization( + Authorization::new( + batched_tx.tx.sechashes(), + [(0, defaults::albert_keypair())].into_iter().collect(), + None, + ), + )); let wrapper = batched_tx.tx.to_bytes(); #[allow(clippy::disallowed_methods)] diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 95d5ee59ad7..067911fc5b5 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -29,7 +29,7 @@ migrations = [ "linkme", ] benches = ["proptest"] -control_flow = ["futures", "tokio"] +control_flow = ["futures", "tokio", "wasmtimer"] [dependencies] namada_macros = {path = "../macros"} @@ -72,10 +72,16 @@ tendermint = {workspace = true} tendermint-proto = {workspace = true} thiserror.workspace = true tiny-keccak = {version = "2.0.2", features = ["keccak"]} -tokio = { workspace = true, optional = true, features = ["full"]} tracing.workspace = true uint = "0.9.5" zeroize.workspace = true +wasmtimer = { workspace = true, optional = true } + +[target.'cfg(not(target_family = "wasm"))'.dependencies] +tokio = { workspace = true, optional = true, features = ["full"] } + +[target.'cfg(target_family = "wasm")'.dependencies] +tokio = { workspace = true, optional = true, default-features = false, features = ["sync"] } [dev-dependencies] assert_matches.workspace = true @@ -88,3 +94,4 @@ test-log.workspace = true tokio = { workspace = true, features = ["full"] } toml.workspace = true tracing-subscriber.workspace = true +wasmtimer.workspace = true diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 5a33d6c932d..200b6971cff 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -24,9 +24,7 @@ pub mod control_flow; pub mod governance; pub mod hints; pub mod proof_of_stake; -mod wasm_cache; -pub use wasm_cache::{WasmCacheAccess, WasmCacheRoAccess, WasmCacheRwAccess}; // TODO(namada#3248): only re-export v037 `tendermint-rs` pub use {masp_primitives, tendermint, tendermint_proto}; /// Borsh binary encoding (re-exported) from official crate with custom ext. diff --git a/crates/core/src/wasm_cache.rs b/crates/core/src/wasm_cache.rs deleted file mode 100644 index 1d47cf5680d..00000000000 --- a/crates/core/src/wasm_cache.rs +++ /dev/null @@ -1,25 +0,0 @@ -/// WASM Cache access level, used to limit dry-ran transactions to read-only -/// cache access. -pub trait WasmCacheAccess: Clone + std::fmt::Debug + Default { - /// Is access read/write? - fn is_read_write() -> bool; -} - -/// Regular read/write caches access -#[derive(Debug, Clone, Default)] -pub struct WasmCacheRwAccess; -impl WasmCacheAccess for WasmCacheRwAccess { - fn is_read_write() -> bool { - true - } -} - -/// Restricted read-only access for dry-ran transactions -#[derive(Debug, Clone, Default)] -pub struct WasmCacheRoAccess; - -impl WasmCacheAccess for WasmCacheRoAccess { - fn is_read_write() -> bool { - false - } -} diff --git a/crates/encoding_spec/Cargo.toml b/crates/encoding_spec/Cargo.toml index ddc59eb0e6a..d2999e19827 100644 --- a/crates/encoding_spec/Cargo.toml +++ b/crates/encoding_spec/Cargo.toml @@ -16,6 +16,11 @@ version.workspace = true default = [] [dependencies] +namada_account = { path = "../account" } +namada_core = { path = "../core" } +namada_token = { path = "../token" } +namada_tx = { path = "../tx" } + borsh.workspace = true itertools.workspace = true lazy_static.workspace = true diff --git a/crates/encoding_spec/src/main.rs b/crates/encoding_spec/src/main.rs index efb5c0c79ca..6a29718fabe 100644 --- a/crates/encoding_spec/src/main.rs +++ b/crates/encoding_spec/src/main.rs @@ -23,13 +23,13 @@ use borsh::{schema, schema_container_of}; use itertools::Itertools; use lazy_static::lazy_static; use madato::types::TableRow; -use namada::core::address::Address; -use namada::core::collections::HashSet; -use namada::core::key::ed25519::{PublicKey, Signature}; -use namada::core::storage::{self, Epoch}; -use namada::ledger::parameters::Parameters; -use namada::tx::data::{pos, TxType, WrapperTx}; -use namada::{account, token}; +use namada_core::address::Address; +use namada_core::collections::HashSet; +use namada_core::key::ed25519::{PublicKey, Signature}; +use namada_core::parameters::Parameters; +use namada_core::storage::{self, Epoch}; +use namada_tx::data::{pos, TxType, WrapperTx}; +use {namada_account as account, namada_token as token}; /// This generator will write output into this `docs` file. const OUTPUT_PATH: &str = @@ -100,7 +100,7 @@ fn main() -> Result<(), Box> { // PoS // TODO add after - // TODO imported from `use namada::ledger::pos::Bonds;` + // TODO imported from `use namada_sdk::proof_of_stake::Bonds;` // let pos_bonds_schema = schema_container_of::(); // Merge type definitions diff --git a/crates/ethereum_bridge/src/vp/bridge_pool_vp.rs b/crates/ethereum_bridge/src/vp/bridge_pool_vp.rs index a75789da03b..a31b0cf61c1 100644 --- a/crates/ethereum_bridge/src/vp/bridge_pool_vp.rs +++ b/crates/ethereum_bridge/src/vp/bridge_pool_vp.rs @@ -75,13 +75,21 @@ where pub token_keys: PhantomData, } -impl<'a, S, CA, EVAL, TokenKeys> BridgePool<'a, S, CA, EVAL, TokenKeys> +impl<'ctx, S, CA, EVAL, TokenKeys> BridgePool<'ctx, S, CA, EVAL, TokenKeys> where S: 'static + StateRead, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, CA: 'static + Clone, TokenKeys: token::Keys, { + /// Instantiate bridge pool VP + pub fn new(ctx: Ctx<'ctx, S, CA, EVAL>) -> Self { + Self { + ctx, + token_keys: PhantomData, + } + } + /// Get the change in the balance of an account /// associated with an address fn account_balance_delta( @@ -393,13 +401,13 @@ where /// Helper struct for handling the different escrow /// checking scenarios. -struct EscrowDelta<'a, KIND> { - token: Cow<'a, Address>, - payer_account: &'a Address, - escrow_account: &'a Address, +struct EscrowDelta<'ctx, KIND> { + token: Cow<'ctx, Address>, + payer_account: &'ctx Address, + escrow_account: &'ctx Address, expected_debit: Amount, expected_credit: Amount, - transferred_amount: &'a Amount, + transferred_amount: &'ctx Amount, _kind: PhantomData<*const KIND>, } @@ -477,9 +485,9 @@ impl EscrowDelta<'_, KIND> { /// /// 1. Check that gas fees were escrowed. /// 2. Check that the Nam to back wNam was escrowed. -struct EscrowCheck<'a> { - gas_check: EscrowDelta<'a, GasCheck>, - token_check: EscrowDelta<'a, TokenCheck>, +struct EscrowCheck<'ctx> { + gas_check: EscrowDelta<'ctx, GasCheck>, + token_check: EscrowDelta<'ctx, TokenCheck>, } impl EscrowCheck<'_> { @@ -515,18 +523,18 @@ fn sum_gas_and_token_amounts( }) } -impl<'a, S, CA, EVAL, TokenKeys> NativeVp<'a> - for BridgePool<'a, S, CA, EVAL, TokenKeys> +impl<'view, 'ctx: 'view, S, CA, EVAL, TokenKeys> NativeVp<'view> + for BridgePool<'ctx, S, CA, EVAL, TokenKeys> where S: 'static + StateRead, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, CA: 'static + Clone, TokenKeys: token::Keys, { type Error = Error; fn validate_tx( - &self, + &'view self, batched_tx: &BatchedTxRef<'_>, keys_changed: &BTreeSet, _verifiers: &BTreeSet
, @@ -682,7 +690,6 @@ mod test_bridge_pool_vp { use namada_core::borsh::BorshSerializeExt; use namada_core::eth_bridge_pool::{GasFee, TransferToEthereum}; use namada_core::hash::Hash; - use namada_core::WasmCacheRwAccess; use namada_gas::{TxGasMeter, VpGasMeter}; use namada_state::testing::TestState; use namada_state::write_log::WriteLog; @@ -692,6 +699,7 @@ mod test_bridge_pool_vp { use namada_tx::Tx; use namada_vm::wasm::run::VpEvalWasm; use namada_vm::wasm::VpCache; + use namada_vm::WasmCacheRwAccess; use super::*; use crate::storage::bridge_pool::get_signed_root_key; @@ -957,13 +965,13 @@ mod test_bridge_pool_vp { } /// Setup a ctx for running native vps - fn setup_ctx<'a>( - tx: &'a Tx, - state: &'a TestState, - gas_meter: &'a RefCell, - keys_changed: &'a BTreeSet, - verifiers: &'a BTreeSet
, - ) -> Ctx<'a, TestState, VpCache, Eval> { + fn setup_ctx<'ctx>( + tx: &'ctx Tx, + state: &'ctx TestState, + gas_meter: &'ctx RefCell, + keys_changed: &'ctx BTreeSet, + verifiers: &'ctx BTreeSet
, + ) -> Ctx<'ctx, TestState, VpCache, Eval> { let batched_tx = tx.batch_ref_first_tx(); Ctx::new( &BRIDGE_POOL_ADDRESS, diff --git a/crates/ethereum_bridge/src/vp/eth_bridge_vp.rs b/crates/ethereum_bridge/src/vp/eth_bridge_vp.rs index a6452144552..fb3f98e1832 100644 --- a/crates/ethereum_bridge/src/vp/eth_bridge_vp.rs +++ b/crates/ethereum_bridge/src/vp/eth_bridge_vp.rs @@ -39,6 +39,14 @@ where EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, TokenKeys: token::Keys, { + /// Instantiate eth bridge VP + pub fn new(ctx: Ctx<'ctx, S, CA, EVAL>) -> Self { + Self { + ctx, + token_keys: PhantomData, + } + } + /// If the Ethereum bridge's escrow key was written to, we check /// that the NAM balance increased and that the Bridge pool VP has /// been triggered. @@ -77,12 +85,12 @@ where } } -impl<'a, S, CA, EVAL, TokenKeys> NativeVp<'a> - for EthBridge<'a, S, CA, EVAL, TokenKeys> +impl<'view, 'ctx: 'view, S, CA, EVAL, TokenKeys> NativeVp<'view> + for EthBridge<'ctx, S, CA, EVAL, TokenKeys> where S: 'static + StateRead, CA: 'static + Clone, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, TokenKeys: token::Keys, { type Error = Error; @@ -98,7 +106,7 @@ where /// changes to the `eth_msgs/...` keys. For those cases, we reject here as /// no wasm transactions should be able to modify those keys. fn validate_tx( - &self, + &'view self, _: &BatchedTxRef<'_>, keys_changed: &BTreeSet, verifiers: &BTreeSet
, @@ -183,8 +191,8 @@ mod tests { use namada_core::address::testing::{established_address_1, nam, wnam}; use namada_core::borsh::BorshSerializeExt; + use namada_core::ethereum_events; use namada_core::ethereum_events::EthAddress; - use namada_core::{ethereum_events, WasmCacheRwAccess}; use namada_gas::{TxGasMeter, VpGasMeter}; use namada_state::testing::TestState; use namada_state::{StorageWrite, TxIndex}; @@ -193,6 +201,7 @@ mod tests { use namada_tx::{Tx, TxCommitments}; use namada_vm::wasm::run::VpEvalWasm; use namada_vm::wasm::VpCache; + use namada_vm::WasmCacheRwAccess; use rand::Rng; use super::*; @@ -260,14 +269,14 @@ mod tests { } /// Setup a ctx for running native vps - fn setup_ctx<'a>( - tx: &'a Tx, - cmt: &'a TxCommitments, - state: &'a TestState, - gas_meter: &'a RefCell, - keys_changed: &'a BTreeSet, - verifiers: &'a BTreeSet
, - ) -> Ctx<'a, TestState, VpCache, Eval> { + fn setup_ctx<'ctx>( + tx: &'ctx Tx, + cmt: &'ctx TxCommitments, + state: &'ctx TestState, + gas_meter: &'ctx RefCell, + keys_changed: &'ctx BTreeSet, + verifiers: &'ctx BTreeSet
, + ) -> Ctx<'ctx, TestState, VpCache, Eval> { Ctx::new( &crate::ADDRESS, state, diff --git a/crates/ethereum_bridge/src/vp/mod.rs b/crates/ethereum_bridge/src/vp/mod.rs index e16646f73ef..2771996bd84 100644 --- a/crates/ethereum_bridge/src/vp/mod.rs +++ b/crates/ethereum_bridge/src/vp/mod.rs @@ -6,6 +6,6 @@ mod bridge_pool_vp; mod eth_bridge_vp; mod nut_vp; -pub use bridge_pool_vp::BridgePool; -pub use eth_bridge_vp::EthBridge; -pub use nut_vp::NonUsableTokens; +pub use bridge_pool_vp::{BridgePool, Error as BridgePoolError}; +pub use eth_bridge_vp::{Error as EthBridgeError, EthBridge}; +pub use nut_vp::{Error as NutError, NonUsableTokens}; diff --git a/crates/ethereum_bridge/src/vp/nut_vp.rs b/crates/ethereum_bridge/src/vp/nut_vp.rs index 94368921db4..316d3b4cf31 100644 --- a/crates/ethereum_bridge/src/vp/nut_vp.rs +++ b/crates/ethereum_bridge/src/vp/nut_vp.rs @@ -32,18 +32,18 @@ where pub token_keys: PhantomData, } -impl<'a, S, CA, EVAL, TokenKeys> NativeVp<'a> - for NonUsableTokens<'a, S, CA, EVAL, TokenKeys> +impl<'view, 'ctx: 'view, S, CA, EVAL, TokenKeys> NativeVp<'view> + for NonUsableTokens<'ctx, S, CA, EVAL, TokenKeys> where S: 'static + StateRead, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, CA: 'static + Clone, TokenKeys: token::Keys, { type Error = Error; fn validate_tx( - &self, + &'view self, _: &BatchedTxRef<'_>, keys_changed: &BTreeSet, verifiers: &BTreeSet
, @@ -127,6 +127,22 @@ where } } +impl<'ctx, S, CA, EVAL, TokenKeys> NonUsableTokens<'ctx, S, CA, EVAL, TokenKeys> +where + S: 'static + StateRead, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, + CA: 'static + Clone, + TokenKeys: token::Keys, +{ + /// Instantiate NUT VP + pub fn new(ctx: Ctx<'ctx, S, CA, EVAL>) -> Self { + Self { + ctx, + token_keys: PhantomData, + } + } +} + #[cfg(test)] mod test_nuts { use std::cell::RefCell; @@ -136,7 +152,6 @@ mod test_nuts { use namada_core::borsh::BorshSerializeExt; use namada_core::ethereum_events::testing::DAI_ERC20_ETH_ADDRESS; use namada_core::storage::TxIndex; - use namada_core::WasmCacheRwAccess; use namada_gas::{TxGasMeter, VpGasMeter}; use namada_state::testing::TestState; use namada_state::StorageWrite; @@ -145,6 +160,7 @@ mod test_nuts { use namada_tx::Tx; use namada_vm::wasm::run::VpEvalWasm; use namada_vm::wasm::VpCache; + use namada_vm::WasmCacheRwAccess; use proptest::prelude::*; use super::*; diff --git a/crates/governance/src/vp/mod.rs b/crates/governance/src/vp/mod.rs index 06b37c56a56..9108b5fba33 100644 --- a/crates/governance/src/vp/mod.rs +++ b/crates/governance/src/vp/mod.rs @@ -48,29 +48,27 @@ pub enum Error { } /// Governance VP -pub struct GovernanceVp<'a, S, CA: 'a, EVAL, PoS, TokenKeys> +pub struct GovernanceVp<'ctx, S, CA, EVAL, PoS, TokenKeys> where - S: 'static + StateRead, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, - PoS: proof_of_stake::Read>, - TokenKeys: token::Keys, + S: StateRead, + EVAL: VpEvaluator<'ctx, S, CA, EVAL>, { /// Context to interact with the host structures. - pub ctx: Ctx<'a, S, CA, EVAL>, + pub ctx: Ctx<'ctx, S, CA, EVAL>, /// Read PoS storage pub pos: PhantomData, /// Token keys pub token_keys: PhantomData, } -impl<'a, S, CA, EVAL, PoS, TokenKeys> NativeVp<'a> - for GovernanceVp<'a, S, CA, EVAL, PoS, TokenKeys> +impl<'view, 'ctx: 'view, S, CA, EVAL, PoS, TokenKeys> NativeVp<'view> + for GovernanceVp<'ctx, S, CA, EVAL, PoS, TokenKeys> where S: StateRead, - EVAL: VpEvaluator<'a, S, CA, EVAL>, CA: 'static + Clone, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, PoS: proof_of_stake::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = namada_state::StorageError, >, TokenKeys: token::Keys, @@ -78,7 +76,7 @@ where type Error = Error; fn validate_tx( - &'a self, + &'view self, tx_data: &BatchedTxRef<'_>, keys_changed: &BTreeSet, verifiers: &BTreeSet
, @@ -217,20 +215,20 @@ where } } -impl<'a, S, CA, EVAL, PoS, TokenKeys> - GovernanceVp<'a, S, CA, EVAL, PoS, TokenKeys> +impl<'view, 'ctx: 'view, S, CA, EVAL, PoS, TokenKeys> + GovernanceVp<'ctx, S, CA, EVAL, PoS, TokenKeys> where S: StateRead, - EVAL: VpEvaluator<'a, S, CA, EVAL>, CA: 'static + Clone, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, PoS: proof_of_stake::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = namada_state::StorageError, >, TokenKeys: token::Keys, { /// Instantiate a Governance VP - pub fn new(ctx: Ctx<'a, S, CA, EVAL>) -> Self { + pub fn new(ctx: Ctx<'ctx, S, CA, EVAL>) -> Self { Self { ctx, pos: PhantomData, @@ -276,7 +274,7 @@ where } fn is_valid_vote_key( - &'a self, + &'view self, proposal_id: u64, key: &storage::Key, verifiers: &BTreeSet
, @@ -1118,7 +1116,7 @@ where /// Check if a vote is from a validator pub fn is_validator( - &'a self, + &'view self, verifiers: &BTreeSet
, voter: &Address, validator: &Address, @@ -1176,7 +1174,7 @@ where /// Check if a vote is from a delegator pub fn is_delegator( - &'a self, + &'view self, epoch: Epoch, verifiers: &BTreeSet
, address: &Address, @@ -1278,7 +1276,7 @@ mod test { use namada_core::key::RefTo; use namada_core::storage::testing::get_dummy_header; use namada_core::time::DateTimeUtc; - use namada_core::{token, WasmCacheRwAccess}; + use namada_core::token; use namada_gas::{TxGasMeter, VpGasMeter}; use namada_parameters::Parameters; use namada_proof_of_stake::bond_tokens; @@ -1293,9 +1291,9 @@ mod test { use namada_tx::action::{Action, GovAction, Write}; use namada_tx::data::TxType; use namada_tx::{Authorization, Code, Data, Section, Tx}; - use namada_vm::wasm; use namada_vm::wasm::run::VpEvalWasm; use namada_vm::wasm::VpCache; + use namada_vm::{wasm, WasmCacheRwAccess}; use namada_vp::native_vp::{Ctx, CtxPreStorageRead, NativeVp}; use crate::storage::keys::{ @@ -1308,13 +1306,13 @@ mod test { type CA = WasmCacheRwAccess; type Eval = VpEvalWasm<::D, ::H, CA>; - type GovernanceVp<'a, S> = super::GovernanceVp< - 'a, + type GovernanceVp<'ctx, S> = super::GovernanceVp< + 'ctx, S, VpCache, Eval, namada_proof_of_stake::Store< - CtxPreStorageRead<'a, 'a, S, VpCache, Eval>, + CtxPreStorageRead<'ctx, 'ctx, S, VpCache, Eval>, >, namada_token::Store<()>, >; diff --git a/crates/governance/src/vp/pgf.rs b/crates/governance/src/vp/pgf.rs index 9ab436c24eb..600a9c69056 100644 --- a/crates/governance/src/vp/pgf.rs +++ b/crates/governance/src/vp/pgf.rs @@ -32,25 +32,25 @@ pub enum Error { } /// Pgf VP -pub struct PgfVp<'a, S, CA, EVAL> +pub struct PgfVp<'ctx, S, CA, EVAL> where S: 'static + StateRead, - EVAL: VpEvaluator<'a, S, CA, EVAL>, + EVAL: VpEvaluator<'ctx, S, CA, EVAL>, { /// Context to interact with the host structures. - pub ctx: Ctx<'a, S, CA, EVAL>, + pub ctx: Ctx<'ctx, S, CA, EVAL>, } -impl<'a, S, CA, EVAL> NativeVp<'a> for PgfVp<'a, S, CA, EVAL> +impl<'view, 'ctx, S, CA, EVAL> NativeVp<'view> for PgfVp<'ctx, S, CA, EVAL> where S: 'static + StateRead, CA: 'static + Clone, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, { type Error = Error; fn validate_tx( - &'a self, + &'view self, batched_tx: &BatchedTxRef<'_>, keys_changed: &BTreeSet, verifiers: &BTreeSet
, @@ -207,15 +207,20 @@ where } } -impl<'a, S, CA, EVAL> PgfVp<'a, S, CA, EVAL> +impl<'view, 'ctx, S, CA, EVAL> PgfVp<'ctx, S, CA, EVAL> where S: 'static + StateRead, CA: 'static + Clone, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, { + /// Instantiate PGF VP + pub fn new(ctx: Ctx<'ctx, S, CA, EVAL>) -> Self { + Self { ctx } + } + /// Validate a governance parameter pub fn is_valid_parameter_change( - &'a self, + &'view self, batched_tx: &BatchedTxRef<'_>, ) -> Result<()> { batched_tx.tx.data(batched_tx.cmt).map_or_else( @@ -242,8 +247,8 @@ where #[allow(clippy::upper_case_acronyms)] #[derive(Debug)] -enum KeyType<'a> { - Stewards(&'a Address), +enum KeyType<'ctx> { + Stewards(&'ctx Address), Fundings, PgfInflationRate, StewardInflationRate, diff --git a/crates/ibc/src/vp/mod.rs b/crates/ibc/src/vp/mod.rs index ad4b22cb1e8..9c0aaf42f99 100644 --- a/crates/ibc/src/vp/mod.rs +++ b/crates/ibc/src/vp/mod.rs @@ -66,13 +66,13 @@ pub enum Error { pub type VpResult = std::result::Result; /// IBC VP -pub struct Ibc<'a, S, CA, EVAL, Params, Gov, Token, PoS> +pub struct Ibc<'ctx, S, CA, EVAL, Params, Gov, Token, PoS> where S: 'static + StateRead, - EVAL: VpEvaluator<'a, S, CA, EVAL>, + EVAL: VpEvaluator<'ctx, S, CA, EVAL>, { /// Context to interact with the host structures. - pub ctx: Ctx<'a, S, CA, EVAL>, + pub ctx: Ctx<'ctx, S, CA, EVAL>, /// Parameters type pub params: PhantomData, /// Governance type @@ -83,35 +83,35 @@ where pub pos: PhantomData, } -impl<'a, S, CA, EVAL, Params, Gov, Token, PoS> NativeVp<'a> - for Ibc<'a, S, CA, EVAL, Params, Gov, Token, PoS> +impl<'view, 'ctx: 'view, S, CA, EVAL, Params, Gov, Token, PoS> NativeVp<'view> + for Ibc<'ctx, S, CA, EVAL, Params, Gov, Token, PoS> where S: 'static + StateRead, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL> + Debug, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL> + Debug, CA: 'static + Clone + Debug, Gov: governance::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, Params: parameters::Keys + parameters::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, Token: token::Keys + token::Write< - PseudoExecutionStorage<'a, 'a, S, CA, EVAL>, + PseudoExecutionStorage<'view, 'ctx, S, CA, EVAL>, Err = StorageError, > + Debug, PoS: proof_of_stake::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, { type Error = Error; fn validate_tx( - &'a self, + &'view self, batched_tx: &BatchedTxRef<'_>, keys_changed: &BTreeSet, _verifiers: &BTreeSet
, @@ -149,29 +149,29 @@ where } } -impl<'a, S, CA, EVAL, Params, Gov, Token, PoS> - Ibc<'a, S, CA, EVAL, Params, Gov, Token, PoS> +impl<'view, 'ctx: 'view, S, CA, EVAL, Params, Gov, Token, PoS> + Ibc<'ctx, S, CA, EVAL, Params, Gov, Token, PoS> where S: 'static + StateRead, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL> + Debug, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL> + Debug, CA: 'static + Clone + Debug, Params: parameters::Keys + parameters::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, Token: token::Keys + token::Write< - PseudoExecutionStorage<'a, 'a, S, CA, EVAL>, + PseudoExecutionStorage<'view, 'ctx, S, CA, EVAL>, Err = StorageError, > + Debug, PoS: proof_of_stake::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, { /// Instantiate IBC VP - pub fn new(ctx: Ctx<'a, S, CA, EVAL>) -> Self { + pub fn new(ctx: Ctx<'ctx, S, CA, EVAL>) -> Self { Self { ctx, params: PhantomData, @@ -182,7 +182,7 @@ where } fn validate_state( - &'a self, + &'view self, tx_data: &[u8], keys_changed: &BTreeSet, ) -> VpResult<()> { @@ -243,7 +243,7 @@ where Ok(()) } - fn validate_with_msg(&'a self, tx_data: &[u8]) -> VpResult<()> { + fn validate_with_msg(&'view self, tx_data: &[u8]) -> VpResult<()> { let validation_ctx = VpValidationContext::new(self.ctx.pre()); let ctx = Rc::new(RefCell::new(validation_ctx)); // Use an empty verifiers set placeholder for validation, this is only @@ -265,7 +265,7 @@ where } /// Retrieve the validation params - pub fn validation_params(&'a self) -> VpResult { + pub fn validation_params(&'view self) -> VpResult { use std::str::FromStr; let chain_id = self.ctx.get_chain_id().map_err(Error::NativeVpError)?; let proof_specs = @@ -433,7 +433,6 @@ mod tests { use namada_core::storage::{BlockHeight, Epoch, TxIndex}; use namada_core::tendermint::time::Time as TmTime; use namada_core::time::DurationSecs; - use namada_core::WasmCacheRwAccess; use namada_gas::{TxGasMeter, VpGasMeter}; use namada_governance::parameters::GovernanceParameters; use namada_parameters::storage::{ @@ -447,9 +446,9 @@ mod tests { use namada_token::NATIVE_MAX_DECIMAL_PLACES; use namada_tx::data::TxType; use namada_tx::{Authorization, Code, Data, Section, Tx}; - use namada_vm::wasm; use namada_vm::wasm::run::VpEvalWasm; use namada_vm::wasm::VpCache; + use namada_vm::{wasm, WasmCacheRwAccess}; use prost::Message; use sha2::Digest; @@ -542,23 +541,23 @@ mod tests { ::H, CA, >; - type Ctx<'a> = super::Ctx<'a, TestState, VpCache, Eval>; - type Ibc<'a> = super::Ibc< - 'a, + type Ctx<'ctx> = super::Ctx<'ctx, TestState, VpCache, Eval>; + type Ibc<'ctx> = super::Ibc< + 'ctx, TestState, VpCache, Eval, namada_parameters::Store< - CtxPreStorageRead<'a, 'a, TestState, VpCache, Eval>, + CtxPreStorageRead<'ctx, 'ctx, TestState, VpCache, Eval>, >, namada_governance::Store< - CtxPreStorageRead<'a, 'a, TestState, VpCache, Eval>, + CtxPreStorageRead<'ctx, 'ctx, TestState, VpCache, Eval>, >, namada_token::Store< - PseudoExecutionStorage<'a, 'a, TestState, VpCache, Eval>, + PseudoExecutionStorage<'ctx, 'ctx, TestState, VpCache, Eval>, >, namada_proof_of_stake::Store< - CtxPreStorageRead<'a, 'a, TestState, VpCache, Eval>, + CtxPreStorageRead<'ctx, 'ctx, TestState, VpCache, Eval>, >, >; diff --git a/crates/node/Cargo.toml b/crates/node/Cargo.toml index 782b0c50631..897d53c5a1b 100644 --- a/crates/node/Cargo.toml +++ b/crates/node/Cargo.toml @@ -44,8 +44,12 @@ namada-eth-bridge = [ [dependencies] namada_apps_lib = {path = "../apps_lib"} namada_migrations = {path = "../migrations", optional = true} -namada_sdk = {path = "../sdk", default-features = false, features = ["download-params", "std", "rand"]} +namada_replay_protection = {path = "../replay_protection"} +namada_sdk = {path = "../sdk", features = ["wasm-runtime"]} namada_test_utils = {path = "../test_utils", optional = true} +namada_vm = {path = "../vm"} +namada_vote_ext = { path = "../vote_ext" } +namada_vp = {path = "../vp"} arse-merkle-tree = { workspace = true, features = ["blake2b"] } async-trait.workspace = true @@ -96,6 +100,7 @@ warp = "0.3.2" [dev-dependencies] namada_apps_lib = {path = "../apps_lib", features = ["testing"]} namada_test_utils = {path = "../test_utils"} +namada_vm = {path = "../vm", features = ["testing"]} assert_matches.workspace = true clap.workspace = true diff --git a/crates/node/src/abortable.rs b/crates/node/src/abortable.rs index 8c8a5165826..c078d5d26da 100644 --- a/crates/node/src/abortable.rs +++ b/crates/node/src/abortable.rs @@ -1,7 +1,7 @@ use std::future::Future; use std::pin::Pin; -use namada::control_flow::{install_shutdown_signal, ShutdownSignal}; +use namada_sdk::control_flow::{install_shutdown_signal, ShutdownSignal}; use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; use tokio::task::JoinHandle; diff --git a/crates/node/src/bench_utils.rs b/crates/node/src/bench_utils.rs index ef800367150..8438d6a124d 100644 --- a/crates/node/src/bench_utils.rs +++ b/crates/node/src/bench_utils.rs @@ -17,85 +17,81 @@ use borsh_ext::BorshSerializeExt; use masp_primitives::transaction::Transaction; use masp_primitives::zip32::ExtendedFullViewingKey; use masp_proofs::prover::LocalTxProver; -use namada::address::MASP; -use namada::core::address::{self, Address, InternalAddress}; -use namada::core::chain::ChainId; -use namada::core::key::common::SecretKey; -use namada::core::masp::{ - ExtendedViewingKey, PaymentAddress, TransferSource, TransferTarget, +use namada_apps_lib::cli; +use namada_apps_lib::cli::context::FromContext; +use namada_apps_lib::cli::Context; +use namada_apps_lib::wallet::{defaults, CliWalletUtils}; +use namada_sdk::address::{self, Address, InternalAddress, MASP}; +use namada_sdk::chain::ChainId; +use namada_sdk::events::extend::{ + ComposeEvent, MaspTxBatchRefs, MaspTxBlockIndex, }; -use namada::core::storage::{BlockHeight, Epoch, Key, KeySeg, TxIndex}; -use namada::core::time::DateTimeUtc; -use namada::events::extend::{ComposeEvent, MaspTxBatchRefs, MaspTxBlockIndex}; -use namada::events::Event; -use namada::governance::storage::proposal::ProposalType; -use namada::governance::InitProposalData; -use namada::ibc::apps::transfer::types::msgs::transfer::MsgTransfer as IbcMsgTransfer; -use namada::ibc::apps::transfer::types::packet::PacketData; -use namada::ibc::apps::transfer::types::PrefixedCoin; -use namada::ibc::clients::tendermint::client_state::ClientState; -use namada::ibc::clients::tendermint::consensus_state::ConsensusState; -use namada::ibc::clients::tendermint::types::{ +use namada_sdk::events::Event; +use namada_sdk::gas::TxGasMeter; +use namada_sdk::governance::storage::proposal::ProposalType; +use namada_sdk::governance::InitProposalData; +use namada_sdk::ibc::apps::transfer::types::msgs::transfer::MsgTransfer as IbcMsgTransfer; +use namada_sdk::ibc::apps::transfer::types::packet::PacketData; +use namada_sdk::ibc::apps::transfer::types::PrefixedCoin; +use namada_sdk::ibc::clients::tendermint::client_state::ClientState; +use namada_sdk::ibc::clients::tendermint::consensus_state::ConsensusState; +use namada_sdk::ibc::clients::tendermint::types::{ AllowUpdate, ClientState as ClientStateType, ConsensusState as ConsensusStateType, TrustThreshold, }; -use namada::ibc::core::channel::types::channel::{ +use namada_sdk::ibc::core::channel::types::channel::{ ChannelEnd, Counterparty as ChannelCounterparty, Order, State, }; -use namada::ibc::core::channel::types::timeout::TimeoutHeight; -use namada::ibc::core::channel::types::Version as ChannelVersion; -use namada::ibc::core::client::types::Height as IbcHeight; -use namada::ibc::core::commitment_types::commitment::{ +use namada_sdk::ibc::core::channel::types::timeout::TimeoutHeight; +use namada_sdk::ibc::core::channel::types::Version as ChannelVersion; +use namada_sdk::ibc::core::client::types::Height as IbcHeight; +use namada_sdk::ibc::core::commitment_types::commitment::{ CommitmentPrefix, CommitmentRoot, }; -use namada::ibc::core::commitment_types::specs::ProofSpecs; -use namada::ibc::core::connection::types::version::Version; -use namada::ibc::core::connection::types::{ +use namada_sdk::ibc::core::commitment_types::specs::ProofSpecs; +use namada_sdk::ibc::core::connection::types::version::Version; +use namada_sdk::ibc::core::connection::types::{ ConnectionEnd, Counterparty, State as ConnectionState, }; -use namada::ibc::core::host::types::identifiers::{ +use namada_sdk::ibc::core::host::types::identifiers::{ ChainId as IbcChainId, ChannelId as NamadaChannelId, ChannelId, ClientId, ConnectionId, ConnectionId as NamadaConnectionId, PortId as NamadaPortId, PortId, }; -use namada::ibc::core::host::types::path::{ +use namada_sdk::ibc::core::host::types::path::{ ClientConsensusStatePath, ClientStatePath, Path as IbcPath, }; -use namada::ibc::primitives::proto::{Any, Protobuf}; -use namada::ibc::primitives::Timestamp as IbcTimestamp; -use namada::ibc::storage::{mint_limit_key, port_key, throughput_limit_key}; -use namada::ibc::MsgTransfer; -use namada::io::StdIo; -use namada::ledger::dry_run_tx; -use namada::ledger::gas::TxGasMeter; -use namada::ledger::ibc::storage::{channel_key, connection_key}; -use namada::ledger::native_vp::ibc::get_dummy_header; -use namada::ledger::queries::{ +use namada_sdk::ibc::primitives::proto::{Any, Protobuf}; +use namada_sdk::ibc::primitives::Timestamp as IbcTimestamp; +use namada_sdk::ibc::storage::{ + channel_key, connection_key, mint_limit_key, port_key, throughput_limit_key, +}; +use namada_sdk::ibc::MsgTransfer; +use namada_sdk::io::StdIo; +use namada_sdk::key::common::SecretKey; +use namada_sdk::masp::{ + self, ContextSyncStatus, ExtendedViewingKey, MaspTxRefs, PaymentAddress, + ShieldedContext, ShieldedUtils, TransferSource, TransferTarget, +}; +use namada_sdk::queries::{ Client, EncodedResponseQuery, RequestCtx, RequestQuery, Router, RPC, }; -use namada::masp::MaspTxRefs; -use namada::state::StorageRead; -use namada::token::{ +use namada_sdk::state::StorageRead; +use namada_sdk::storage::testing::get_dummy_header; +use namada_sdk::storage::{BlockHeight, Epoch, Key, KeySeg, TxIndex}; +use namada_sdk::time::DateTimeUtc; +use namada_sdk::token::{ Amount, DenominatedAmount, ShieldedTransfer, ShieldingTransfer, UnshieldingTransfer, }; -use namada::tx::data::pos::Bond; -use namada::tx::data::{ +use namada_sdk::tx::data::pos::Bond; +use namada_sdk::tx::data::{ BatchResults, BatchedTxResult, Fee, TxResult, VpsResult, }; -use namada::tx::event::{new_tx_event, Batch}; -use namada::tx::{ +use namada_sdk::tx::event::{new_tx_event, Batch}; +use namada_sdk::tx::{ Authorization, BatchedTx, BatchedTxRef, Code, Data, Section, Tx, }; -use namada::vm::wasm::run; -use namada::{proof_of_stake, tendermint}; -use namada_apps_lib::cli; -use namada_apps_lib::cli::context::FromContext; -use namada_apps_lib::cli::Context; -use namada_apps_lib::wallet::{defaults, CliWalletUtils}; -use namada_sdk::masp::{ - self, ContextSyncStatus, ShieldedContext, ShieldedUtils, -}; pub use namada_sdk::tx::{ TX_BECOME_VALIDATOR_WASM, TX_BOND_WASM, TX_BRIDGE_POOL_WASM, TX_CHANGE_COMMISSION_WASM as TX_CHANGE_VALIDATOR_COMMISSION_WASM, @@ -111,19 +107,20 @@ pub use namada_sdk::tx::{ TX_VOTE_PROPOSAL as TX_VOTE_PROPOSAL_WASM, TX_WITHDRAW_WASM, VP_USER_WASM, }; use namada_sdk::wallet::Wallet; -use namada_sdk::{Namada, NamadaImpl}; +use namada_sdk::{parameters, proof_of_stake, tendermint, Namada, NamadaImpl}; use namada_test_utils::tx_data::TxWriteData; +use namada_vm::wasm::run; use rand_core::OsRng; use sha2::{Digest, Sha256}; use tempfile::TempDir; -use crate::config; use crate::config::global::GlobalConfig; use crate::config::TendermintMode; use crate::facade::tendermint::v0_37::abci::request::InitChain; use crate::facade::tendermint_proto::google::protobuf::Timestamp; use crate::facade::tendermint_rpc; use crate::shell::Shell; +use crate::{config, dry_run_tx}; pub const WASM_DIR: &str = "../../wasm"; @@ -306,7 +303,7 @@ impl BenchShell { extra_sections: Option>, signers: Vec<&SecretKey>, ) -> BatchedTx { - let mut tx = Tx::from_type(namada::tx::data::TxType::Raw); + let mut tx = Tx::from_type(namada_sdk::tx::data::TxType::Raw); // NOTE: here we use the code hash to avoid including the cost for the // wasm validation. The wasm codes (both txs and vps) are always @@ -351,7 +348,7 @@ impl BenchShell { data: Vec, ) -> BatchedTx { // This function avoid serializaing the tx data with Borsh - let mut tx = Tx::from_type(namada::tx::data::TxType::Raw); + let mut tx = Tx::from_type(namada_sdk::tx::data::TxType::Raw); let code_hash = self .read_storage_key(&Key::wasm_hash(wasm_code_path)) .unwrap(); @@ -382,7 +379,7 @@ impl BenchShell { let timeout_height = TimeoutHeight::At(IbcHeight::new(0, 100).unwrap()); #[allow(clippy::disallowed_methods)] - let now: namada::tendermint::Time = + let now: namada_sdk::tendermint::Time = DateTimeUtc::now().try_into().unwrap(); let now: IbcTimestamp = now.into(); let timeout_timestamp = @@ -445,8 +442,15 @@ impl BenchShell { ) .unwrap(); - if self.state.is_masp_new_epoch(true).unwrap() { - namada::token::conversion::update_allowed_conversions( + let masp_epoch_multiplier = + parameters::read_masp_epoch_multiplier_parameter(&self.state) + .unwrap(); + if self + .state + .is_masp_new_epoch(true, masp_epoch_multiplier) + .unwrap() + { + namada_sdk::token::conversion::update_allowed_conversions( &mut self.state, ) .unwrap(); @@ -489,7 +493,7 @@ impl BenchShell { // Set consensus state #[allow(clippy::disallowed_methods)] - let now: namada::tendermint::Time = + let now: namada_sdk::tendermint::Time = DateTimeUtc::now().try_into().unwrap(); let consensus_key = addr_key.join(&Key::from( IbcPath::ClientConsensusState(ClientConsensusStatePath { @@ -615,7 +619,7 @@ impl BenchShell { // Commit a masp transaction and cache the tx and the changed keys for // client queries pub fn commit_masp_tx(&mut self, mut masp_tx: Tx) { - use namada::core::key::RefTo; + use namada_sdk::key::RefTo; masp_tx.add_wrapper( Fee { amount_per_gas_unit: DenominatedAmount::native(0.into()), @@ -634,7 +638,7 @@ pub fn generate_foreign_key_tx(signer: &SecretKey) -> BatchedTx { let wasm_code = std::fs::read("../../wasm_for_tests/tx_write.wasm").unwrap(); - let mut tx = Tx::from_type(namada::tx::data::TxType::Raw); + let mut tx = Tx::from_type(namada_sdk::tx::data::TxType::Raw); tx.set_code(Code::new(wasm_code, None)); tx.set_data(Data::new( TxWriteData { @@ -798,17 +802,21 @@ impl Client for BenchShell { prove, }; - let ctx = RequestCtx { - state: &self.state, - event_log: self.event_log(), - vp_wasm_cache: self.vp_wasm_cache.read_only(), - tx_wasm_cache: self.tx_wasm_cache.read_only(), - storage_read_past_height_limit: None, - }; - if request.path == RPC.shell().dry_run_tx_path() { - dry_run_tx(ctx, &request) + dry_run_tx( + unsafe { self.state.read_only().with_static_temp_write_log() }, + self.vp_wasm_cache.read_only(), + self.tx_wasm_cache.read_only(), + &request, + ) } else { + let ctx = RequestCtx { + state: &self.state, + event_log: self.event_log(), + vp_wasm_cache: self.vp_wasm_cache.read_only(), + tx_wasm_cache: self.tx_wasm_cache.read_only(), + storage_read_past_height_limit: None, + }; RPC.handle(ctx, &request) } .map_err(|_| std::io::Error::from(std::io::ErrorKind::NotFound)) @@ -895,7 +903,7 @@ impl Client for BenchShell { tendermint_rpc::Error, > where - H: Into + Send, + H: Into + Send, { // NOTE: atm this is only needed to query block results at a specific // height for masp transactions @@ -945,7 +953,7 @@ impl Client for BenchShell { .unwrap(), ]))) .into(); - namada::tendermint::abci::Event::from(event) + namada_sdk::tendermint::abci::Event::from(event) }) .collect(), ) @@ -961,7 +969,7 @@ impl Client for BenchShell { end_block_events, validator_updates: vec![], consensus_param_updates: None, - app_hash: namada::tendermint::hash::AppHash::default(), + app_hash: namada_sdk::tendermint::hash::AppHash::default(), }) } } @@ -1103,7 +1111,7 @@ impl BenchShieldedCtx { .expect("MASP must have shielded part"); let mut hasher = Sha256::new(); - let shielded_section_hash = namada::core::hash::Hash( + let shielded_section_hash = namada_sdk::hash::Hash( Section::MaspTx(shielded.clone()) .hash(&mut hasher) .finalize_reset() @@ -1188,7 +1196,7 @@ impl BenchShieldedCtx { let timeout_height = TimeoutHeight::At(IbcHeight::new(0, 100).unwrap()); #[allow(clippy::disallowed_methods)] - let now: namada::tendermint::Time = + let now: namada_sdk::tendermint::Time = DateTimeUtc::now().try_into().unwrap(); let now: IbcTimestamp = now.into(); let timeout_timestamp = diff --git a/crates/node/src/broadcaster.rs b/crates/node/src/broadcaster.rs index 8a081f19373..6f0fc652c5a 100644 --- a/crates/node/src/broadcaster.rs +++ b/crates/node/src/broadcaster.rs @@ -1,8 +1,8 @@ use std::net::SocketAddr; use std::ops::ControlFlow; -use namada::control_flow::time; -use namada::time::{DateTimeUtc, Utc}; +use namada_sdk::control_flow::time; +use namada_sdk::time::{DateTimeUtc, Utc}; use tokio::sync::mpsc::UnboundedReceiver; use crate::facade::tendermint_rpc::client::CompatMode; diff --git a/crates/node/src/dry_run_tx.rs b/crates/node/src/dry_run_tx.rs index 0871ed56f42..301ddb814c7 100644 --- a/crates/node/src/dry_run_tx.rs +++ b/crates/node/src/dry_run_tx.rs @@ -2,34 +2,33 @@ use std::cell::RefCell; -use namada_gas::Gas; -use namada_sdk::queries::{EncodedResponseQuery, RequestCtx, RequestQuery}; -use namada_state::{DBIter, ResultExt, StorageHasher, DB}; -use namada_tx::data::{GasLimit, TxResult}; +use namada_sdk::borsh::BorshSerializeExt; +use namada_sdk::gas::{Gas, GasMetering, TxGasMeter}; +use namada_sdk::parameters; +use namada_sdk::queries::{EncodedResponseQuery, RequestQuery}; +use namada_sdk::state::{ + DBIter, ResultExt, StorageHasher, StorageResult, TxIndex, DB, +}; +use namada_sdk::tx::data::{GasLimit, TxResult, TxType}; +use namada_sdk::tx::Tx; +use namada_vm::wasm::{TxCache, VpCache}; +use namada_vm::WasmCacheAccess; -use super::protocol; -use crate::vm::wasm::{TxCache, VpCache}; -use crate::vm::WasmCacheAccess; +use crate::protocol; +use crate::protocol::ShellParams; /// Dry run a transaction -pub fn dry_run_tx<'a, D, H, CA>( - mut ctx: RequestCtx<'a, D, H, VpCache, TxCache>, +pub fn dry_run_tx( + mut state: namada_sdk::state::TempWlState<'static, D, H>, + mut vp_wasm_cache: VpCache, + mut tx_wasm_cache: TxCache, request: &RequestQuery, -) -> namada_state::StorageResult +) -> StorageResult where D: 'static + DB + for<'iter> DBIter<'iter> + Sync, H: 'static + StorageHasher + Sync, CA: 'static + WasmCacheAccess + Sync, { - use borsh_ext::BorshSerializeExt; - use namada_gas::{GasMetering, TxGasMeter}; - use namada_tx::data::TxType; - use namada_tx::Tx; - - use crate::ledger::protocol::ShellParams; - use crate::storage::TxIndex; - - let mut temp_state = ctx.state.with_temp_write_log(); let tx = Tx::try_from(&request.data[..]).into_storage_result()?; tx.validate_tx().into_storage_result()?; @@ -44,20 +43,19 @@ where &wrapper, &request.data, &tx_gas_meter, - &mut temp_state, + &mut state, None, ) .into_storage_result()?; - temp_state.write_log_mut().commit_tx(); + state.write_log_mut().commit_tx(); let available_gas = tx_gas_meter.borrow().get_available_gas(); (tx_result, TxGasMeter::new_from_sub_limit(available_gas)) } _ => { // If dry run only the inner tx, use the max block gas as // the gas limit - let max_block_gas = - namada_parameters::get_max_block_gas(ctx.state)?; + let max_block_gas = parameters::get_max_block_gas(&state)?; let gas_limit = Gas::try_from(GasLimit::from(max_block_gas)) .into_storage_result()?; (TxResult::default(), TxGasMeter::new(gas_limit)) @@ -72,17 +70,17 @@ where &TxIndex(0), ShellParams::new( &tx_gas_meter, - &mut temp_state, - &mut ctx.vp_wasm_cache, - &mut ctx.tx_wasm_cache, + &mut state, + &mut vp_wasm_cache, + &mut tx_wasm_cache, ), ); let is_accepted = matches!(&batched_tx_result, Ok(result) if result.is_accepted()); if is_accepted { - temp_state.write_log_mut().commit_tx_to_batch(); + state.write_log_mut().commit_tx_to_batch(); } else { - temp_state.write_log_mut().drop_tx(); + state.write_log_mut().drop_tx(); } tx_result .batch_results @@ -97,7 +95,7 @@ where data, proof: None, info: Default::default(), - height: ctx.state.in_mem().get_last_block_height(), + height: state.in_mem().get_last_block_height(), }) } @@ -105,25 +103,24 @@ where mod test { use borsh::BorshDeserialize; use borsh_ext::BorshSerializeExt; - use namada_core::address; - use namada_core::hash::Hash; - use namada_core::storage::{BlockHeight, Key}; + use namada_sdk::events::log::EventLog; + use namada_sdk::hash::Hash; use namada_sdk::queries::{ - EncodedResponseQuery, RequestCtx, RequestQuery, Router, RPC, + Client, EncodedResponseQuery, RequestCtx, RequestQuery, Router, RPC, }; + use namada_sdk::state::testing::TestState; + use namada_sdk::state::StorageWrite; + use namada_sdk::storage::{BlockHeight, Key}; use namada_sdk::tendermint_rpc::{Error as RpcError, Response}; - use namada_state::testing::TestState; - use namada_state::StorageWrite; + use namada_sdk::tx::data::TxType; + use namada_sdk::tx::{Code, Data, Tx}; + use namada_sdk::{address, token}; use namada_test_utils::TestWasms; - use namada_tx::data::TxType; - use namada_tx::{Code, Data, Tx}; + use namada_vm::wasm::{TxCache, VpCache}; + use namada_vm::{wasm, WasmCacheRoAccess}; use tempfile::TempDir; - use crate::ledger::events::log::EventLog; - use crate::ledger::queries::Client; - use crate::token; - use crate::vm::wasm::{TxCache, VpCache}; - use crate::vm::{wasm, WasmCacheRoAccess}; + use super::*; /// A test client that has direct access to the storage pub struct TestClient @@ -160,7 +157,7 @@ mod test { // Initialize mock gas limit let max_block_gas_key = - namada_parameters::storage::get_max_block_gas_key(); + namada_sdk::parameters::storage::get_max_block_gas_key(); state .db_write(&max_block_gas_key, 20_000_000_u64.serialize_to_vec()) .expect( @@ -183,8 +180,7 @@ mod test { } } - #[cfg_attr(feature = "async-send", async_trait::async_trait)] - #[cfg_attr(not(feature = "async-send"), async_trait::async_trait(?Send))] + #[async_trait::async_trait(?Send)] impl Client for TestClient where RPC: Router + Sync, @@ -208,19 +204,26 @@ mod test { height: height.try_into().unwrap(), prove, }; - let ctx = RequestCtx { - state: &self.state, - event_log: &self.event_log, - vp_wasm_cache: self.vp_wasm_cache.clone(), - tx_wasm_cache: self.tx_wasm_cache.clone(), - storage_read_past_height_limit: None, - }; // TODO(namada#3240): this is a hack to propagate errors to the // caller, we should really permit error types other // than [`std::io::Error`] if request.path == RPC.shell().dry_run_tx_path() { - super::dry_run_tx(ctx, &request) + dry_run_tx( + unsafe { + self.state.read_only().with_static_temp_write_log() + }, + self.vp_wasm_cache.clone(), + self.tx_wasm_cache.clone(), + &request, + ) } else { + let ctx = RequestCtx { + state: self.state.read_only(), + event_log: &self.event_log, + vp_wasm_cache: self.vp_wasm_cache.clone(), + tx_wasm_cache: self.tx_wasm_cache.clone(), + storage_read_past_height_limit: None, + }; self.rpc.handle(ctx, &request) } .map_err(|err| { @@ -237,8 +240,7 @@ mod test { } #[tokio::test] - async fn test_shell_queries_router_with_client() - -> namada_state::StorageResult<()> { + async fn test_shell_queries_router_with_client() -> StorageResult<()> { // Initialize the `TestClient` let mut client = TestClient::new(RPC); // store the wasm code diff --git a/crates/node/src/ethereum_oracle/control.rs b/crates/node/src/ethereum_oracle/control.rs index ca9d3e6dc45..62a59692f50 100644 --- a/crates/node/src/ethereum_oracle/control.rs +++ b/crates/node/src/ethereum_oracle/control.rs @@ -1,6 +1,6 @@ //! The oracle is controlled by sending commands over a channel. -use namada::eth_bridge::oracle::config::Config; +use namada_sdk::eth_bridge::oracle::config::Config; use tokio::sync::mpsc; use tokio::sync::mpsc::error::TrySendError; diff --git a/crates/node/src/ethereum_oracle/events.rs b/crates/node/src/ethereum_oracle/events.rs index 64e94a17570..a081c106e23 100644 --- a/crates/node/src/ethereum_oracle/events.rs +++ b/crates/node/src/ethereum_oracle/events.rs @@ -8,14 +8,14 @@ pub mod eth_events { ValidatorSetUpdateFilter, }; use ethbridge_events::{DynEventCodec, Events as RawEvents}; - use namada::core::address::Address; - use namada::core::ethereum_events::{ + use namada_sdk::address::Address; + use namada_sdk::ethereum_events::{ EthAddress, EthereumEvent, TransferToEthereum, TransferToNamada, Uint, }; - use namada::core::ethereum_structs; - use namada::core::hash::Hash; - use namada::core::keccak::KeccakHash; - use namada::core::token::Amount; + use namada_sdk::ethereum_structs; + use namada_sdk::hash::Hash; + use namada_sdk::keccak::KeccakHash; + use namada_sdk::token::Amount; use num256::Uint256; use thiserror::Error; @@ -181,7 +181,7 @@ pub mod eth_events { impl Parse for ethabi::Uint { fn parse_amount(self) -> Result { let uint = { - use namada::core::uint::Uint as NamadaUint; + use namada_sdk::uint::Uint as NamadaUint; let mut num_buf = [0; 32]; self.to_little_endian(&mut num_buf); NamadaUint::from_little_endian(&num_buf) @@ -303,7 +303,7 @@ pub mod eth_events { TRANSFER_TO_CHAIN_CODEC, TRANSFER_TO_ERC_CODEC, VALIDATOR_SET_UPDATE_CODEC, }; - use namada::eth_bridge::ethers::contract::EthEvent; + use namada_sdk::eth_bridge::ethers::contract::EthEvent; use super::*; use crate::ethereum_oracle::test_tools::event_log::GetLog; diff --git a/crates/node/src/ethereum_oracle/mod.rs b/crates/node/src/ethereum_oracle/mod.rs index ed454eb0023..5e6564a4ffc 100644 --- a/crates/node/src/ethereum_oracle/mod.rs +++ b/crates/node/src/ethereum_oracle/mod.rs @@ -8,13 +8,12 @@ use async_trait::async_trait; use ethabi::Address; use ethbridge_events::{event_codecs, EventKind}; use itertools::Either; -use namada::control_flow::time::{Constant, Duration, Instant, Sleep}; -use namada::core::ethereum_events::EthereumEvent; -use namada::core::{ethereum_structs, hints}; -use namada::eth_bridge::ethers; -use namada::eth_bridge::ethers::providers::{Http, Middleware, Provider}; -use namada::eth_bridge::oracle::config::Config; -use namada_sdk::eth_bridge::{eth_syncing_status_timeout, SyncStatus}; +use namada_sdk::control_flow::time::{Constant, Duration, Instant, Sleep}; +use namada_sdk::eth_bridge::ethers::providers::{Http, Middleware, Provider}; +use namada_sdk::eth_bridge::oracle::config::Config; +use namada_sdk::eth_bridge::{eth_syncing_status_timeout, ethers, SyncStatus}; +use namada_sdk::ethereum_events::EthereumEvent; +use namada_sdk::{ethereum_structs, hints}; use num256::Uint256; use thiserror::Error; use tokio::sync::mpsc::error::TryRecvError; @@ -602,7 +601,7 @@ fn process_queue( pub mod last_processed_block { //! Functionality to do with publishing which blocks we have processed. - use namada::core::ethereum_structs; + use namada_sdk::ethereum_structs; use tokio::sync::watch; pub type Sender = watch::Sender>; @@ -621,11 +620,11 @@ mod test_oracle { use std::num::NonZeroU64; use ethbridge_bridge_events::{TransferToChainFilter, TransferToErcFilter}; - use namada::core::address::testing::gen_established_address; - use namada::core::ethereum_events::{EthAddress, TransferToEthereum}; - use namada::core::hash::Hash; - use namada::eth_bridge::ethers::types::H160; - use namada::eth_bridge::structs::Erc20Transfer; + use namada_sdk::address::testing::gen_established_address; + use namada_sdk::eth_bridge::ethers::types::H160; + use namada_sdk::eth_bridge::structs::Erc20Transfer; + use namada_sdk::ethereum_events::{EthAddress, TransferToEthereum}; + use namada_sdk::hash::Hash; use tokio::sync::oneshot::channel; use tokio::time::timeout; diff --git a/crates/node/src/ethereum_oracle/test_tools/events_endpoint.rs b/crates/node/src/ethereum_oracle/test_tools/events_endpoint.rs index 23f77d93019..5b6e9325815 100644 --- a/crates/node/src/ethereum_oracle/test_tools/events_endpoint.rs +++ b/crates/node/src/ethereum_oracle/test_tools/events_endpoint.rs @@ -1,7 +1,7 @@ use std::net::SocketAddr; use borsh::BorshDeserialize; -use namada::core::ethereum_events::EthereumEvent; +use namada_sdk::ethereum_events::EthereumEvent; use tokio::sync::mpsc::Sender as BoundedSender; use tokio::sync::oneshot::{Receiver, Sender}; use warp::reply::WithStatus; diff --git a/crates/node/src/ethereum_oracle/test_tools/mod.rs b/crates/node/src/ethereum_oracle/test_tools/mod.rs index 46425c4362a..99678972947 100644 --- a/crates/node/src/ethereum_oracle/test_tools/mod.rs +++ b/crates/node/src/ethereum_oracle/test_tools/mod.rs @@ -8,8 +8,8 @@ pub mod event_log { use ethbridge_bridge_events::{ TransferToChainFilter, TransferToErcFilter, ValidatorSetUpdateFilter, }; - use namada::eth_bridge::ethers::abi::AbiEncode; - use namada::eth_bridge::ethers::contract::EthEvent; + use namada_sdk::eth_bridge::ethers::abi::AbiEncode; + use namada_sdk::eth_bridge::ethers::contract::EthEvent; /// Get an [`ethabi::RawLog`] from a given Ethereum event. pub trait GetLog { @@ -67,8 +67,8 @@ pub mod mock_web3_client { use async_trait::async_trait; use ethabi::Address; use ethbridge_events::EventCodec; - use namada::control_flow::time::{Duration, Instant}; - use namada::core::ethereum_structs::BlockHeight; + use namada_sdk::control_flow::time::{Duration, Instant}; + use namada_sdk::ethereum_structs::BlockHeight; use num256::Uint256; use tokio::sync::mpsc::{ unbounded_channel, UnboundedReceiver, UnboundedSender, diff --git a/crates/node/src/lib.rs b/crates/node/src/lib.rs index 1c489f1111e..966dbb650d4 100644 --- a/crates/node/src/lib.rs +++ b/crates/node/src/lib.rs @@ -19,6 +19,7 @@ pub mod bench_utils; mod broadcaster; mod dry_run_tx; pub mod ethereum_oracle; +pub mod protocol; pub mod shell; pub mod shims; pub mod storage; @@ -34,19 +35,17 @@ use byte_unit::Byte; use data_encoding::HEXUPPER; pub use dry_run_tx::dry_run_tx; use futures::future::TryFutureExt; -use namada::core::storage::BlockHeight; -use namada::core::time::DateTimeUtc; -use namada::eth_bridge::ethers::providers::{Http, Provider}; -use namada::state::DB; -use namada::storage::DbColFam; -use namada::tendermint::abci::request::CheckTxKind; use namada_apps_lib::cli::args; use namada_apps_lib::config::utils::{ convert_tm_addr_to_socket_addr, num_of_threads, }; use namada_apps_lib::{config, wasm_loader}; +use namada_sdk::eth_bridge::ethers::providers::{Http, Provider}; use namada_sdk::migrations::ScheduledMigration; -use namada_sdk::state::StateRead; +use namada_sdk::state::{StateRead, DB}; +use namada_sdk::storage::{BlockHeight, DbColFam}; +use namada_sdk::tendermint::abci::request::CheckTxKind; +use namada_sdk::time::DateTimeUtc; use once_cell::unsync::Lazy; use sysinfo::{RefreshKind, System, SystemExt}; use tokio::sync::mpsc; @@ -266,7 +265,7 @@ pub fn dump_db( #[cfg(feature = "migrations")] pub fn query_db( config: config::Ledger, - key: &namada::core::storage::Key, + key: &namada_sdk::storage::Key, type_hash: &[u8; 32], cf: &DbColFam, ) { @@ -373,7 +372,7 @@ async fn run_aux( }; tracing::info!("Loading MASP verifying keys."); - let _ = namada::token::validation::preload_verifying_keys(); + let _ = namada_sdk::token::validation::preload_verifying_keys(); tracing::info!("Done loading MASP verifying keys."); // Start ABCI server and broadcaster (the latter only if we are a validator @@ -872,8 +871,8 @@ pub fn test_genesis_files( genesis: config::genesis::chain::Finalized, wasm_dir: PathBuf, ) { - use namada::core::hash::Sha256Hasher; - use namada::state::mockdb::MockDB; + use namada_sdk::hash::Sha256Hasher; + use namada_sdk::state::mockdb::MockDB; // Channels for validators to send protocol txs to be broadcast to the // broadcaster service diff --git a/crates/node/src/protocol.rs b/crates/node/src/protocol.rs index b19098e18d7..ab3214c460a 100644 --- a/crates/node/src/protocol.rs +++ b/crates/node/src/protocol.rs @@ -5,45 +5,41 @@ use std::fmt::Debug; use borsh_ext::BorshSerializeExt; use eyre::{eyre, WrapErr}; -use namada_core::booleans::BoolResultUnitExt; -use namada_core::hash::Hash; -use namada_events::extend::{ +use namada_sdk::address::{Address, InternalAddress}; +use namada_sdk::booleans::BoolResultUnitExt; +use namada_sdk::events::extend::{ ComposeEvent, Height as HeightAttr, TxHash as TxHashAttr, }; -use namada_events::EventLevel; -use namada_gas::TxGasMeter; -use namada_state::StorageWrite; -use namada_token::event::{TokenEvent, TokenOperation, UserAccount}; -use namada_tx::data::protocol::{ProtocolTx, ProtocolTxType}; -use namada_tx::data::{ +use namada_sdk::events::EventLevel; +use namada_sdk::gas::{GasMetering, TxGasMeter, VpGasMeter}; +use namada_sdk::hash::Hash; +use namada_sdk::state::{ + DBIter, State, StorageHasher, StorageRead, StorageWrite, WlState, DB, +}; +use namada_sdk::storage::TxIndex; +use namada_sdk::token::event::{TokenEvent, TokenOperation, UserAccount}; +use namada_sdk::token::Amount; +use namada_sdk::tx::data::protocol::{ProtocolTx, ProtocolTxType}; +use namada_sdk::tx::data::{ BatchResults, BatchedTxResult, ExtendedTxResult, TxResult, VpStatusFlags, VpsResult, WrapperTx, }; -use namada_tx::{BatchedTxRef, Tx}; +use namada_sdk::tx::{BatchedTxRef, Tx}; +use namada_sdk::validation::{ + EthBridgeNutVp, EthBridgePoolVp, EthBridgeVp, GovernanceVp, IbcVp, MaspVp, + MultitokenVp, NativeVpCtx, ParametersVp, PgfVp, PosVp, +}; +use namada_sdk::{ + eth_bridge, governance, ibc, parameters, proof_of_stake, state, storage, + token, tx, +}; +use namada_vm::wasm::{TxCache, VpCache}; +use namada_vm::{self, wasm, WasmCacheAccess}; use namada_vote_ext::EthereumTxData; +use namada_vp::native_vp::NativeVp; use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; use thiserror::Error; -use crate::address::{Address, InternalAddress}; -use crate::ledger::gas::{GasMetering, VpGasMeter}; -use crate::ledger::governance::GovernanceVp; -use crate::ledger::native_vp::ethereum_bridge::bridge_pool_vp::BridgePoolVp; -use crate::ledger::native_vp::ethereum_bridge::nut::NonUsableTokens; -use crate::ledger::native_vp::ethereum_bridge::vp::EthBridge; -use crate::ledger::native_vp::ibc::Ibc; -use crate::ledger::native_vp::masp::MaspVp; -use crate::ledger::native_vp::multitoken::MultitokenVp; -use crate::ledger::native_vp::parameters::{self, ParametersVp}; -use crate::ledger::native_vp::{self, NativeVp}; -use crate::ledger::pgf::PgfVp; -use crate::ledger::pos::{self, PosVP}; -use crate::state::{DBIter, State, StorageHasher, StorageRead, WlState, DB}; -use crate::storage; -use crate::storage::TxIndex; -use crate::token::Amount; -use crate::vm::wasm::{TxCache, VpCache}; -use crate::vm::{self, wasm, WasmCacheAccess}; - #[allow(missing_docs)] #[derive(Error, Debug)] pub enum Error { @@ -52,13 +48,13 @@ pub enum Error { #[error("Missing tx section: {0}")] MissingSection(String), #[error("State error: {0}")] - StateError(namada_state::Error), + StateError(state::Error), #[error("Storage error: {0}")] - StorageError(namada_state::StorageError), + StorageError(state::StorageError), #[error("Wrapper tx runner error: {0}")] WrapperRunnerError(String), #[error("Transaction runner error: {0}")] - TxRunnerError(vm::wasm::run::Error), + TxRunnerError(wasm::run::Error), #[error("{0:?}")] ProtocolTxError(#[from] eyre::Error), #[error("The atomic batch failed at inner transaction {0}")] @@ -74,31 +70,31 @@ pub enum Error { )] ReplayAttempt(Hash), #[error("Error executing VP for addresses: {0:?}")] - VpRunnerError(vm::wasm::run::Error), + VpRunnerError(wasm::run::Error), #[error("The address {0} doesn't exist")] MissingAddress(Address), #[error("IBC native VP: {0}")] - IbcNativeVpError(crate::ledger::native_vp::ibc::Error), + IbcNativeVpError(ibc::vp::Error), #[error("PoS native VP: {0}")] - PosNativeVpError(pos::vp::Error), + PosNativeVpError(proof_of_stake::vp::Error), #[error("PoS native VP panicked")] PosNativeVpRuntime, #[error("Parameters native VP: {0}")] - ParametersNativeVpError(parameters::Error), + ParametersNativeVpError(parameters::vp::Error), #[error("Multitoken native VP: {0}")] - MultitokenNativeVpError(crate::ledger::native_vp::multitoken::Error), + MultitokenNativeVpError(token::vp::MultitokenError), #[error("Governance native VP error: {0}")] - GovernanceNativeVpError(crate::ledger::governance::Error), + GovernanceNativeVpError(governance::vp::Error), #[error("Pgf native VP error: {0}")] - PgfNativeVpError(crate::ledger::pgf::Error), + PgfNativeVpError(governance::vp::pgf::Error), #[error("Ethereum bridge native VP error: {0:?}")] - EthBridgeNativeVpError(native_vp::ethereum_bridge::vp::Error), + EthBridgeNativeVpError(eth_bridge::vp::EthBridgeError), #[error("Ethereum bridge pool native VP error: {0:?}")] - BridgePoolNativeVpError(native_vp::ethereum_bridge::bridge_pool_vp::Error), + BridgePoolNativeVpError(eth_bridge::vp::BridgePoolError), #[error("Non usable tokens native VP error: {0:?}")] - NutNativeVpError(native_vp::ethereum_bridge::nut::Error), + NutNativeVpError(eth_bridge::vp::NutError), #[error("MASP native VP error: {0}")] - MaspNativeVpError(native_vp::masp::Error), + MaspNativeVpError(token::vp::MaspError), #[error("Access to an internal address {0:?} is forbidden")] AccessForbidden(InternalAddress), } @@ -366,7 +362,7 @@ where // If the transaction was a masp one append the // transaction refs for the events if let Some(masp_section_ref) = - namada_tx::action::get_masp_section_ref(state) + tx::action::get_masp_section_ref(state) .map_err(Error::StateError)? { extended_tx_result @@ -400,16 +396,16 @@ where /// - gas accounting // TODO(namada#2597): this must signal to the caller if we need masp fee payment // in the first inner tx of the batch -pub(crate) fn apply_wrapper_tx( +pub(crate) fn apply_wrapper_tx<'a, S, D, H>( tx: &Tx, wrapper: &WrapperTx, tx_bytes: &[u8], tx_gas_meter: &RefCell, - state: &mut S, + state: &'a mut S, block_proposer: Option<&Address>, ) -> Result> where - S: State + Sync, + S: 'a + State + Sync, D: 'static + DB + for<'iter> DBIter<'iter> + Sync, H: 'static + StorageHasher + Sync, { @@ -479,21 +475,17 @@ pub fn transfer_fee( where S: State + StorageRead + StorageWrite, { - let balance = crate::token::read_balance( - state, - &wrapper.fee.token, - &wrapper.fee_payer(), - ) - .unwrap(); + let balance = + token::read_balance(state, &wrapper.fee.token, &wrapper.fee_payer()) + .unwrap(); const FEE_PAYMENT_DESCRIPTOR: std::borrow::Cow<'static, str> = std::borrow::Cow::Borrowed("wrapper-fee-payment"); match wrapper.get_tx_fee() { Ok(fees) => { - let fees = - crate::token::denom_to_amount(fees, &wrapper.fee.token, state) - .map_err(|e| Error::FeeError(e.to_string()))?; + let fees = token::denom_to_amount(fees, &wrapper.fee.token, state) + .map_err(|e| Error::FeeError(e.to_string()))?; let current_block_height = state.in_mem().get_last_block_height().next_height(); @@ -509,7 +501,7 @@ where .map_err(|e| Error::FeeError(e.to_string()))?; let target_post_balance = Some( - namada_token::read_balance( + token::read_balance( state, &wrapper.fee.token, block_proposer, @@ -557,7 +549,7 @@ where .map_err(|e| Error::FeeError(e.to_string()))?; let target_post_balance = Some( - namada_token::read_balance( + token::read_balance( state, &wrapper.fee.token, block_proposer, @@ -577,7 +569,7 @@ where target: UserAccount::Internal( block_proposer.clone(), ), - source_post_balance: namada_core::uint::ZERO, + source_post_balance: namada_sdk::uint::ZERO, target_post_balance, }, } @@ -609,7 +601,7 @@ where /// Transfer `token` from `src` to `dest`. Returns an `Err` if `src` has /// insufficient balance or if the transfer the `dest` would overflow (This can /// only happen if the total supply doesn't fit in `token::Amount`). Contrary to -/// `crate::token::transfer` this function updates the tx write log and +/// `token::transfer` this function updates the tx write log and /// not the block write log. fn token_transfer( state: &mut WLS, @@ -621,16 +613,16 @@ fn token_transfer( where WLS: State + StorageRead, { - let src_key = crate::token::storage_key::balance_key(token, src); - let src_balance = crate::token::read_balance(state, token, src) + let src_key = token::storage_key::balance_key(token, src); + let src_balance = token::read_balance(state, token, src) .expect("Token balance read in protocol must not fail"); match src_balance.checked_sub(amount) { Some(new_src_balance) => { if src == dest { return Ok(()); } - let dest_key = crate::token::storage_key::balance_key(token, dest); - let dest_balance = crate::token::read_balance(state, token, dest) + let dest_key = token::storage_key::balance_key(token, dest); + let dest_balance = token::read_balance(state, token, dest) .expect("Token balance read in protocol must not fail"); match dest_balance.checked_add(amount) { Some(new_dest_balance) => { @@ -661,18 +653,15 @@ pub fn check_fees(state: &S, wrapper: &WrapperTx) -> Result<()> where S: State + StorageRead, { - let balance = crate::token::read_balance( - state, - &wrapper.fee.token, - &wrapper.fee_payer(), - ) - .unwrap(); + let balance = + token::read_balance(state, &wrapper.fee.token, &wrapper.fee_payer()) + .unwrap(); let fees = wrapper .get_tx_fee() .map_err(|e| Error::FeeError(e.to_string()))?; - let fees = crate::token::denom_to_amount(fees, &wrapper.fee.token, state) + let fees = token::denom_to_amount(fees, &wrapper.fee.token, state) .map_err(|e| Error::FeeError(e.to_string()))?; if balance.checked_sub(fees).is_some() { Ok(()) @@ -691,7 +680,7 @@ pub fn apply_wasm_tx<'a, S, D, H, CA>( shell_params: ShellParams<'a, S, D, H, CA>, ) -> Result where - S: State + Sync, + S: 'static + State + Sync, D: 'static + DB + for<'iter> DBIter<'iter> + Sync, H: 'static + StorageHasher + Sync, CA: 'static + WasmCacheAccess + Sync, @@ -748,7 +737,7 @@ where D: 'static + DB + for<'iter> DBIter<'iter> + Sync, H: 'static + StorageHasher + Sync, { - use namada_ethereum_bridge::protocol::transactions; + use namada_sdk::eth_bridge::protocol::transactions; use namada_vote_ext::{ethereum_events, validator_set_update}; let Some(data) = data else { @@ -863,7 +852,7 @@ fn check_vps( }: CheckVps<'_, S, CA>, ) -> Result where - S: State + Sync, + S: 'static + State + Sync, CA: 'static + WasmCacheAccess + Sync, { let (verifiers, keys_changed) = state @@ -900,7 +889,7 @@ fn execute_vps( vp_wasm_cache: &mut VpCache, ) -> Result where - S: State + Sync, + S: 'static + State + Sync, CA: 'static + WasmCacheAccess + Sync, { let vps_result = verifiers @@ -911,7 +900,7 @@ where let tx_accepted = match &addr { Address::Implicit(_) | Address::Established(_) => { let (vp_hash, gas) = state - .validity_predicate(addr) + .validity_predicate::>(addr) .map_err(Error::StateError)?; gas_meter .borrow_mut() @@ -941,7 +930,7 @@ where }) } Address::Internal(internal_addr) => { - let ctx = native_vp::Ctx::new( + let ctx = NativeVpCtx::new( addr, state, batched_tx.tx, @@ -955,7 +944,7 @@ where match internal_addr { InternalAddress::PoS => { - let pos = PosVP { ctx }; + let pos = PosVp::new(ctx); pos.validate_tx( batched_tx, &keys_changed, @@ -964,7 +953,7 @@ where .map_err(Error::PosNativeVpError) } InternalAddress::Ibc => { - let ibc = Ibc { ctx }; + let ibc = IbcVp::new(ctx); ibc.validate_tx( batched_tx, &keys_changed, @@ -973,7 +962,7 @@ where .map_err(Error::IbcNativeVpError) } InternalAddress::Parameters => { - let parameters = ParametersVp { ctx }; + let parameters = ParametersVp::new(ctx); parameters .validate_tx( batched_tx, @@ -986,7 +975,7 @@ where Error::AccessForbidden((*internal_addr).clone()), ), InternalAddress::Governance => { - let governance = GovernanceVp { ctx }; + let governance = GovernanceVp::new(ctx); governance .validate_tx( batched_tx, @@ -995,8 +984,18 @@ where ) .map_err(Error::GovernanceNativeVpError) } + InternalAddress::Pgf => { + let pgf_vp = PgfVp::new(ctx); + pgf_vp + .validate_tx( + batched_tx, + &keys_changed, + &verifiers, + ) + .map_err(Error::PgfNativeVpError) + } InternalAddress::Multitoken => { - let multitoken = MultitokenVp { ctx }; + let multitoken = MultitokenVp::new(ctx); multitoken .validate_tx( batched_tx, @@ -1005,8 +1004,17 @@ where ) .map_err(Error::MultitokenNativeVpError) } + InternalAddress::Masp => { + let masp = MaspVp::new(ctx); + masp.validate_tx( + batched_tx, + &keys_changed, + &verifiers, + ) + .map_err(Error::MaspNativeVpError) + } InternalAddress::EthBridge => { - let bridge = EthBridge { ctx }; + let bridge = EthBridgeVp::new(ctx); bridge .validate_tx( batched_tx, @@ -1016,7 +1024,7 @@ where .map_err(Error::EthBridgeNativeVpError) } InternalAddress::EthBridgePool => { - let bridge_pool = BridgePoolVp { ctx }; + let bridge_pool = EthBridgePoolVp::new(ctx); bridge_pool .validate_tx( batched_tx, @@ -1025,18 +1033,8 @@ where ) .map_err(Error::BridgePoolNativeVpError) } - InternalAddress::Pgf => { - let pgf_vp = PgfVp { ctx }; - pgf_vp - .validate_tx( - batched_tx, - &keys_changed, - &verifiers, - ) - .map_err(Error::PgfNativeVpError) - } InternalAddress::Nut(_) => { - let non_usable_tokens = NonUsableTokens { ctx }; + let non_usable_tokens = EthBridgeNutVp::new(ctx); non_usable_tokens .validate_tx( batched_tx, @@ -1059,15 +1057,6 @@ where ) }) } - InternalAddress::Masp => { - let masp = MaspVp { ctx }; - masp.validate_tx( - batched_tx, - &keys_changed, - &verifiers, - ) - .map_err(Error::MaspNativeVpError) - } InternalAddress::TempStorage => Err( // Temp storage changes must never be committed Error::AccessForbidden((*internal_addr).clone()), @@ -1147,21 +1136,21 @@ fn merge_vp_results( #[cfg(test)] mod tests { use eyre::Result; - use namada_core::collections::HashMap; - use namada_core::ethereum_events::testing::DAI_ERC20_ETH_ADDRESS; - use namada_core::ethereum_events::{EthereumEvent, TransferToNamada}; - use namada_core::keccak::keccak_hash; - use namada_core::storage::BlockHeight; - use namada_core::voting_power::FractionalVotingPower; - use namada_core::{address, key}; - use namada_ethereum_bridge::protocol::transactions::votes::{ + use namada_sdk::collections::HashMap; + use namada_sdk::eth_bridge::protocol::transactions::votes::{ EpochedVotingPower, Votes, }; - use namada_ethereum_bridge::storage::eth_bridge_queries::EthBridgeQueries; - use namada_ethereum_bridge::storage::proof::EthereumProof; - use namada_ethereum_bridge::storage::{vote_tallies, vp}; - use namada_ethereum_bridge::test_utils; - use namada_tx::{SignableEthMessage, Signed}; + use namada_sdk::eth_bridge::storage::eth_bridge_queries::EthBridgeQueries; + use namada_sdk::eth_bridge::storage::proof::EthereumProof; + use namada_sdk::eth_bridge::storage::{vote_tallies, vp}; + use namada_sdk::eth_bridge::test_utils; + use namada_sdk::ethereum_events::testing::DAI_ERC20_ETH_ADDRESS; + use namada_sdk::ethereum_events::{EthereumEvent, TransferToNamada}; + use namada_sdk::keccak::keccak_hash; + use namada_sdk::storage::BlockHeight; + use namada_sdk::tx::{SignableEthMessage, Signed}; + use namada_sdk::voting_power::FractionalVotingPower; + use namada_sdk::{address, key}; use namada_vote_ext::bridge_pool_roots::BridgePoolRootVext; use namada_vote_ext::ethereum_events::EthereumEventsVext; @@ -1306,7 +1295,7 @@ mod tests { let dst_address = Address::Established([0xba; 20].into()); // supply an address with 1000 of said token - namada_token::credit_tokens( + token::credit_tokens( &mut state, &token_address, &src_address, @@ -1321,12 +1310,12 @@ mod tests { // "execute" a dummy tx, by manually performing its state changes let (dummy_tx, changed_keys, verifiers) = { - let mut tx = Tx::from_type(namada_tx::data::TxType::Raw); - tx.set_code(namada_tx::Code::new(vec![], None)); - tx.set_data(namada_tx::Data::new(vec![])); + let mut tx = Tx::from_type(namada_sdk::tx::data::TxType::Raw); + tx.set_code(namada_sdk::tx::Code::new(vec![], None)); + tx.set_data(namada_sdk::tx::Data::new(vec![])); // transfer half of the supply of src to dst - namada_token::transfer( + token::transfer( &mut state, &token_address, &src_address, @@ -1337,11 +1326,11 @@ mod tests { let changed_keys = { let mut set = BTreeSet::new(); - set.insert(namada_token::storage_key::balance_key( + set.insert(token::storage_key::balance_key( &token_address, &src_address, )); - set.insert(namada_token::storage_key::balance_key( + set.insert(token::storage_key::balance_key( &token_address, &dst_address, )); diff --git a/crates/node/src/shell/block_alloc.rs b/crates/node/src/shell/block_alloc.rs index ef723fe1f48..ee09fd3ff75 100644 --- a/crates/node/src/shell/block_alloc.rs +++ b/crates/node/src/shell/block_alloc.rs @@ -41,8 +41,9 @@ pub mod states; use std::marker::PhantomData; -use namada::proof_of_stake::pos_queries::PosQueries; -use namada::state::{self, WlState}; +use namada_sdk::parameters; +use namada_sdk::proof_of_stake::pos_queries::PosQueries; +use namada_sdk::state::{self, WlState}; #[allow(unused_imports)] use crate::facade::tendermint_proto::abci::RequestPrepareProposal; @@ -135,7 +136,7 @@ where fn from(storage: &WlState) -> Self { Self::init( storage.pos_queries().get_max_proposal_bytes().get(), - namada::parameters::get_max_block_gas(storage).unwrap(), + parameters::get_max_block_gas(storage).unwrap(), ) } } diff --git a/crates/node/src/shell/finalize_block.rs b/crates/node/src/shell/finalize_block.rs index 7adbcd17ba5..263a43f0936 100644 --- a/crates/node/src/shell/finalize_block.rs +++ b/crates/node/src/shell/finalize_block.rs @@ -3,35 +3,33 @@ use data_encoding::HEXUPPER; use masp_primitives::merkle_tree::CommitmentTree; use masp_primitives::sapling::Node; -use namada::core::storage::{BlockResults, Epoch, Header}; -use namada::events::Event; -use namada::gas::event::GasUsed; -use namada::governance::pgf::inflation as pgf_inflation; -use namada::hash::Hash; -use namada::ledger::events::extend::{ +use namada_sdk::events::extend::{ ComposeEvent, Height, Info, MaspTxBatchRefs, MaspTxBlockIndex, TxHash, }; -use namada::ledger::events::EmitEvents; -use namada::ledger::gas::GasMetering; -use namada::ledger::ibc; -use namada::ledger::pos::namada_proof_of_stake; -use namada::ledger::protocol::{DispatchArgs, DispatchError}; -use namada::masp::MaspTxRefs; -use namada::proof_of_stake; -use namada::proof_of_stake::storage::{ +use namada_sdk::events::{EmitEvents, Event}; +use namada_sdk::gas::event::GasUsed; +use namada_sdk::gas::GasMetering; +use namada_sdk::governance::pgf::inflation as pgf_inflation; +use namada_sdk::hash::Hash; +use namada_sdk::masp::MaspTxRefs; +use namada_sdk::proof_of_stake::storage::{ find_validator_by_raw_hash, write_last_block_proposer_address, }; -use namada::state::write_log::StorageModification; -use namada::state::{ResultExt, StorageWrite, EPOCH_SWITCH_BLOCKS_DELAY}; -use namada::tx::data::protocol::ProtocolTxType; -use namada::tx::data::VpStatusFlags; -use namada::tx::event::{Batch, Code}; -use namada::tx::new_tx_event; -use namada::vote_ext::ethereum_events::MultiSignedEthEvent; -use namada::vote_ext::ethereum_tx_data_variants; +use namada_sdk::state::write_log::StorageModification; +use namada_sdk::state::{ResultExt, StorageWrite, EPOCH_SWITCH_BLOCKS_DELAY}; +use namada_sdk::storage::{BlockResults, Epoch, Header}; +use namada_sdk::tx::data::protocol::ProtocolTxType; +use namada_sdk::tx::data::VpStatusFlags; +use namada_sdk::tx::event::{Batch, Code}; +use namada_sdk::tx::new_tx_event; +use namada_sdk::{ibc, proof_of_stake}; +use namada_vote_ext::ethereum_events::MultiSignedEthEvent; +use namada_vote_ext::ethereum_tx_data_variants; use super::*; use crate::facade::tendermint::abci::types::VoteInfo; +use crate::facade::tendermint_proto; +use crate::protocol::{DispatchArgs, DispatchError}; use crate::shell::stats::InternalStats; impl Shell @@ -67,7 +65,12 @@ where // Begin the new block and check if a new epoch has begun let (height, new_epoch) = self.update_state(req.header); - let is_masp_new_epoch = self.state.is_masp_new_epoch(new_epoch)?; + let masp_epoch_multiplier = + parameters::read_masp_epoch_multiplier_parameter(&self.state) + .expect("Must have parameters"); + let is_masp_new_epoch = self + .state + .is_masp_new_epoch(new_epoch, masp_epoch_multiplier)?; let (current_epoch, _gas) = self.state.in_mem().get_current_epoch(); let update_for_tendermint = matches!( @@ -236,9 +239,11 @@ where .set_header(header) .expect("Setting a header shouldn't fail"); + let parameters = + parameters::read(&self.state).expect("Must have parameters"); let new_epoch = self .state - .update_epoch(height, header_time) + .update_epoch(height, header_time, ¶meters) .expect("Must be able to update epoch"); (height, new_epoch) } @@ -253,12 +258,11 @@ where // Apply validator set update response.validator_updates = self .get_abci_validator_updates(false, |pk, power| { - let pub_key = - crate::facade::tendermint_proto::v0_37::crypto::PublicKey { - sum: Some(key_to_tendermint(&pk).unwrap()), - }; + let pub_key = tendermint_proto::v0_37::crypto::PublicKey { + sum: Some(key_to_tendermint(&pk).unwrap()), + }; let pub_key = Some(pub_key); - namada::tendermint_proto::v0_37::abci::ValidatorUpdate { + tendermint_proto::v0_37::abci::ValidatorUpdate { pub_key, power, } @@ -298,7 +302,7 @@ where ); // PoS inflation - namada_proof_of_stake::rewards::apply_inflation( + proof_of_stake::rewards::apply_inflation( &mut self.state, last_epoch, num_blocks_in_last_epoch, @@ -307,7 +311,7 @@ where // Pgf inflation pgf_inflation::apply_inflation( self.state.restrict_writes_to_write_log(), - namada::ibc::transfer_over_ibc, + ibc::transfer_over_ibc, )?; // Take events that may be emitted from PGF @@ -348,7 +352,7 @@ where &mut self, response: &mut shim::response::FinalizeBlock, extended_dispatch_result: std::result::Result< - namada::tx::data::ExtendedTxResult, + namada_sdk::tx::data::ExtendedTxResult, DispatchError, >, tx_data: TxData<'_>, @@ -435,7 +439,9 @@ where fn handle_inner_tx_results( &mut self, response: &mut shim::response::FinalizeBlock, - extended_tx_result: namada::tx::data::ExtendedTxResult, + extended_tx_result: namada_sdk::tx::data::ExtendedTxResult< + protocol::Error, + >, tx_data: TxData<'_>, tx_logs: &mut TxLogs<'_>, ) { @@ -498,7 +504,9 @@ where &mut self, response: &mut shim::response::FinalizeBlock, msg: &Error, - extended_tx_result: namada::tx::data::ExtendedTxResult, + extended_tx_result: namada_sdk::tx::data::ExtendedTxResult< + protocol::Error, + >, tx_data: TxData<'_>, tx_logs: &mut TxLogs<'_>, ) { @@ -891,7 +899,7 @@ struct WrapperCache { tx_index: usize, gas_meter: TxGasMeter, event: Event, - tx_result: namada::tx::data::TxResult, + tx_result: namada_sdk::tx::data::TxResult, } struct TxData<'tx> { @@ -964,7 +972,7 @@ impl<'finalize> TempTxLogs { fn check_inner_results( &mut self, - tx_result: &namada::tx::data::TxResult, + tx_result: &namada_sdk::tx::data::TxResult, masp_tx_refs: MaspTxRefs, tx_index: usize, height: BlockHeight, @@ -1059,7 +1067,7 @@ struct ReplayProtectionHashes { fn pos_votes_from_abci( storage: &impl StorageRead, votes: &[VoteInfo], -) -> Vec { +) -> Vec { votes .iter() .filter_map( @@ -1095,7 +1103,7 @@ fn pos_votes_from_abci( // Try to convert voting power to u64 let validator_vp = u64::from(*power); - Some(namada_proof_of_stake::types::VoteInfo { + Some(proof_of_stake::types::VoteInfo { validator_address, validator_vp, }) @@ -1119,63 +1127,66 @@ mod test_finalize_block { use std::num::NonZeroU64; use std::str::FromStr; - use namada::core::collections::{HashMap, HashSet}; - use namada::core::dec::{Dec, POS_DECIMAL_PRECISION}; - use namada::core::ethereum_events::{EthAddress, Uint as ethUint}; - use namada::core::hash::Hash; - use namada::core::keccak::KeccakHash; - use namada::core::key::testing::common_sk_from_simple_seed; - use namada::core::storage::KeySeg; - use namada::core::time::DurationSecs; - use namada::core::uint::Uint; - use namada::eth_bridge::storage::bridge_pool::{ + use namada_replay_protection as replay_protection; + use namada_sdk::address; + use namada_sdk::collections::{HashMap, HashSet}; + use namada_sdk::dec::{Dec, POS_DECIMAL_PRECISION}; + use namada_sdk::eth_bridge::storage::bridge_pool::{ self, get_key_from_hash, get_nonce_key, get_signed_root_key, }; - use namada::eth_bridge::storage::eth_bridge_queries::is_bridge_comptime_enabled; - use namada::eth_bridge::storage::min_confirmations_key; - use namada::ethereum_bridge::storage::wrapped_erc20s; - use namada::governance::storage::keys::get_proposal_execution_key; - use namada::governance::storage::proposal::ProposalType; - use namada::governance::{InitProposalData, VoteProposalData}; - use namada::ledger::gas::VpGasMeter; - use namada::ledger::native_vp::parameters::ParametersVp; - use namada::ledger::native_vp::NativeVp; - use namada::ledger::parameters::EpochDuration; - use namada::proof_of_stake::storage::{ + use namada_sdk::eth_bridge::storage::eth_bridge_queries::is_bridge_comptime_enabled; + use namada_sdk::eth_bridge::storage::vote_tallies::BridgePoolRoot; + use namada_sdk::eth_bridge::storage::{ + min_confirmations_key, wrapped_erc20s, + }; + use namada_sdk::eth_bridge::MinimumConfirmations; + use namada_sdk::ethereum_events::{EthAddress, Uint as ethUint}; + use namada_sdk::events::Event; + use namada_sdk::gas::VpGasMeter; + use namada_sdk::governance::storage::keys::get_proposal_execution_key; + use namada_sdk::governance::storage::proposal::ProposalType; + use namada_sdk::governance::{ + InitProposalData, ProposalVote, VoteProposalData, + }; + use namada_sdk::hash::Hash; + use namada_sdk::keccak::KeccakHash; + use namada_sdk::key::testing::common_sk_from_simple_seed; + use namada_sdk::parameters::EpochDuration; + use namada_sdk::proof_of_stake::storage::{ enqueued_slashes_handle, get_num_consensus_validators, + liveness_missed_votes_handle, liveness_sum_missed_votes_handle, + read_consensus_validator_set_addresses, read_consensus_validator_set_addresses_with_stake, read_total_stake, read_validator_stake, rewards_accumulator_handle, validator_consensus_key_handle, validator_rewards_products_handle, validator_slashes_handle, validator_state_handle, write_pos_params, }; - use namada::proof_of_stake::storage_key::{ + use namada_sdk::proof_of_stake::storage_key::{ is_validator_slashes_key, slashes_prefix, }; - use namada::proof_of_stake::types::{ + use namada_sdk::proof_of_stake::types::{ BondId, SlashType, ValidatorState, WeightedValidator, }; - use namada::proof_of_stake::{unjail_validator, ADDRESS as pos_address}; - use namada::sdk::events::Event; - use namada::tendermint::abci::types::{Misbehavior, MisbehaviorKind}; - use namada::token::{ + use namada_sdk::proof_of_stake::{ + unjail_validator, ADDRESS as pos_address, + }; + use namada_sdk::storage::KeySeg; + use namada_sdk::tendermint::abci::types::{Misbehavior, MisbehaviorKind}; + use namada_sdk::time::DurationSecs; + use namada_sdk::token::{ read_balance, update_balance, Amount, DenominatedAmount, NATIVE_MAX_DECIMAL_PLACES, }; - use namada::tx::data::Fee; - use namada::tx::event::types::APPLIED as APPLIED_TX; - use namada::tx::event::Code as CodeAttr; - use namada::tx::{Authorization, Code, Data}; - use namada::vote_ext::ethereum_events; - use namada::{address, replay_protection}; - use namada_sdk::eth_bridge::storage::vote_tallies::BridgePoolRoot; - use namada_sdk::eth_bridge::MinimumConfirmations; - use namada_sdk::governance::ProposalVote; - use namada_sdk::proof_of_stake::storage::{ - liveness_missed_votes_handle, liveness_sum_missed_votes_handle, - read_consensus_validator_set_addresses, - }; + use namada_sdk::tx::data::Fee; + use namada_sdk::tx::event::types::APPLIED as APPLIED_TX; + use namada_sdk::tx::event::Code as CodeAttr; + use namada_sdk::tx::{Authorization, Code, Data}; + use namada_sdk::uint::Uint; + use namada_sdk::validation::ParametersVp; use namada_test_utils::tx_data::TxWriteData; use namada_test_utils::TestWasms; + use namada_vote_ext::ethereum_events; + use namada_vp::native_vp::NativeVp; use test_log::test; use super::*; @@ -1559,7 +1570,7 @@ mod test_finalize_block { return; } let (mut shell, _, _, _) = setup_at_height(1u64); - namada::eth_bridge::test_utils::commit_bridge_pool_root_at_height( + namada_sdk::eth_bridge::test_utils::commit_bridge_pool_root_at_height( &mut shell.state, &KeccakHash([1; 32]), 1.into(), @@ -1647,7 +1658,7 @@ mod test_finalize_block { } // write transfer to storage let transfer = { - use namada::core::eth_bridge_pool::{ + use namada_sdk::eth_bridge_pool::{ GasFee, PendingTransfer, TransferToEthereum, TransferToEthereumKind, }; @@ -1717,7 +1728,7 @@ mod test_finalize_block { let (mut shell, _broadcaster, _, _eth_control) = setup(); let masp_epoch_multiplier = - namada::ledger::parameters::read_masp_epoch_multiplier_parameter( + namada_sdk::parameters::read_masp_epoch_multiplier_parameter( &shell.state, ) .unwrap(); @@ -1726,10 +1737,20 @@ mod test_finalize_block { for _ in 1..masp_epoch_multiplier { shell.start_new_epoch(None); - assert!(!shell.state.is_masp_new_epoch(true).unwrap()); + assert!( + !shell + .state + .is_masp_new_epoch(true, masp_epoch_multiplier) + .unwrap() + ); } shell.start_new_epoch(None); - assert!(shell.state.is_masp_new_epoch(true).unwrap()); + assert!( + shell + .state + .is_masp_new_epoch(true, masp_epoch_multiplier) + .unwrap() + ); } /// Test that the finalize block handler never commits changes directly to @@ -1743,7 +1764,7 @@ mod test_finalize_block { min_num_of_blocks: 5, min_duration: DurationSecs(0), }; - namada::ledger::parameters::update_epoch_parameter( + namada_sdk::parameters::update_epoch_parameter( &mut shell.state, &epoch_duration, ) @@ -1778,7 +1799,7 @@ mod test_finalize_block { r#type: ProposalType::Default, }; - namada::governance::init_proposal( + namada_sdk::governance::init_proposal( &mut shell.state, &proposal, vec![], @@ -1793,7 +1814,7 @@ mod test_finalize_block { }; // Vote to accept the proposal (there's only one validator, so its // vote decides) - namada::governance::vote_proposal( + namada_sdk::governance::vote_proposal( &mut shell.state, vote, HashSet::new(), @@ -1828,15 +1849,12 @@ mod test_finalize_block { // Keep applying finalize block let validator = shell.mode.get_validator_address().unwrap(); let pos_params = - namada_proof_of_stake::storage::read_pos_params(&shell.state) - .unwrap(); + proof_of_stake::storage::read_pos_params(&shell.state).unwrap(); let consensus_key = - namada_proof_of_stake::storage::validator_consensus_key_handle( - validator, - ) - .get(&shell.state, Epoch::default(), &pos_params) - .unwrap() - .unwrap(); + proof_of_stake::storage::validator_consensus_key_handle(validator) + .get(&shell.state, Epoch::default(), &pos_params) + .unwrap() + .unwrap(); let proposer_address = HEXUPPER .decode(consensus_key.tm_raw_hash().as_bytes()) .unwrap(); @@ -2266,7 +2284,7 @@ mod test_finalize_block { total_rewards += inflation; // Query the available rewards - let query_rewards = namada_proof_of_stake::query_reward_tokens( + let query_rewards = proof_of_stake::query_reward_tokens( &shell.state, None, &validator.address, @@ -2275,7 +2293,7 @@ mod test_finalize_block { .unwrap(); // Claim the rewards from the initial epoch - let reward_1 = namada_proof_of_stake::claim_reward_tokens( + let reward_1 = proof_of_stake::claim_reward_tokens( &mut shell.state, None, &validator.address, @@ -2288,7 +2306,7 @@ mod test_finalize_block { // Query the available rewards again and check that it is 0 now after // the claim - let query_rewards = namada_proof_of_stake::query_reward_tokens( + let query_rewards = proof_of_stake::query_reward_tokens( &shell.state, None, &validator.address, @@ -2304,7 +2322,7 @@ mod test_finalize_block { votes.clone(), None, ); - let att = namada_proof_of_stake::claim_reward_tokens( + let att = proof_of_stake::claim_reward_tokens( &mut shell.state, None, &validator.address, @@ -2320,7 +2338,7 @@ mod test_finalize_block { // Unbond some tokens let unbond_amount = token::Amount::native_whole(50_000); - let unbond_res = namada_proof_of_stake::unbond_tokens( + let unbond_res = proof_of_stake::unbond_tokens( &mut shell.state, None, &validator.address, @@ -2332,7 +2350,7 @@ mod test_finalize_block { assert_eq!(unbond_res.sum, unbond_amount); // Query the available rewards - let query_rewards = namada_proof_of_stake::query_reward_tokens( + let query_rewards = proof_of_stake::query_reward_tokens( &shell.state, None, &validator.address, @@ -2340,7 +2358,7 @@ mod test_finalize_block { ) .unwrap(); - let rew = namada_proof_of_stake::claim_reward_tokens( + let rew = proof_of_stake::claim_reward_tokens( &mut shell.state, None, &validator.address, @@ -2354,13 +2372,13 @@ mod test_finalize_block { // Check the bond amounts for rewards up thru the withdrawable epoch let withdraw_epoch = current_epoch + params.withdrawable_epoch_offset(); let last_claim_epoch = - namada_proof_of_stake::storage::get_last_reward_claim_epoch( + proof_of_stake::storage::get_last_reward_claim_epoch( &shell.state, &validator.address, &validator.address, ) .unwrap(); - let bond_amounts = namada_proof_of_stake::bond_amounts_for_rewards( + let bond_amounts = proof_of_stake::bond_amounts_for_rewards( &shell.state, &bond_id, last_claim_epoch.unwrap_or_default(), @@ -2400,7 +2418,7 @@ mod test_finalize_block { } // Withdraw tokens - let withdraw_amount = namada_proof_of_stake::withdraw_tokens( + let withdraw_amount = proof_of_stake::withdraw_tokens( &mut shell.state, None, &validator.address, @@ -2410,7 +2428,7 @@ mod test_finalize_block { assert_eq!(withdraw_amount, unbond_amount); // Query the available rewards - let query_rewards = namada_proof_of_stake::query_reward_tokens( + let query_rewards = proof_of_stake::query_reward_tokens( &shell.state, None, &validator.address, @@ -2419,7 +2437,7 @@ mod test_finalize_block { .unwrap(); // Claim tokens - let reward_2 = namada_proof_of_stake::claim_reward_tokens( + let reward_2 = proof_of_stake::claim_reward_tokens( &mut shell.state, None, &validator.address, @@ -2441,7 +2459,7 @@ mod test_finalize_block { assert!(token_diff < token_uncertainty); // Query the available rewards to check that they are 0 - let query_rewards = namada_proof_of_stake::query_reward_tokens( + let query_rewards = proof_of_stake::query_reward_tokens( &shell.state, None, &validator.address, @@ -2473,7 +2491,7 @@ mod test_finalize_block { let validator = validator_set.pop_first().unwrap(); let commission_rate = - namada_proof_of_stake::storage::validator_commission_rate_handle( + proof_of_stake::storage::validator_commission_rate_handle( &validator.address, ) .get(&shell.state, Epoch(0), ¶ms) @@ -2514,7 +2532,7 @@ mod test_finalize_block { let delegator = address::testing::gen_implicit_address(); let del_amount = init_stake; let staking_token = shell.state.in_mem().native_token.clone(); - namada::token::credit_tokens( + namada_sdk::token::credit_tokens( &mut shell.state, &staking_token, &delegator, @@ -2522,7 +2540,7 @@ mod test_finalize_block { ) .unwrap(); let mut current_epoch = shell.state.in_mem().block.epoch; - namada_proof_of_stake::bond_tokens( + proof_of_stake::bond_tokens( &mut shell.state, Some(&delegator), &validator.address, @@ -2545,7 +2563,7 @@ mod test_finalize_block { } // Claim the rewards for the validator for the first two epochs - let val_reward_1 = namada_proof_of_stake::claim_reward_tokens( + let val_reward_1 = proof_of_stake::claim_reward_tokens( &mut shell.state, None, &validator.address, @@ -2571,7 +2589,7 @@ mod test_finalize_block { total_rewards += inflation_3; // Claim again for the validator - let val_reward_2 = namada_proof_of_stake::claim_reward_tokens( + let val_reward_2 = proof_of_stake::claim_reward_tokens( &mut shell.state, None, &validator.address, @@ -2580,7 +2598,7 @@ mod test_finalize_block { .unwrap(); // Claim for the delegator - let del_reward_1 = namada_proof_of_stake::claim_reward_tokens( + let del_reward_1 = proof_of_stake::claim_reward_tokens( &mut shell.state, Some(&delegator), &validator.address, @@ -2639,21 +2657,21 @@ mod test_finalize_block { // Give the validators some tokens for txs let staking_token = shell.state.in_mem().native_token.clone(); - namada::token::credit_tokens( + namada_sdk::token::credit_tokens( &mut shell.state, &staking_token, &validator1.address, init_stake, ) .unwrap(); - namada::token::credit_tokens( + namada_sdk::token::credit_tokens( &mut shell.state, &staking_token, &validator2.address, init_stake, ) .unwrap(); - namada::token::credit_tokens( + namada_sdk::token::credit_tokens( &mut shell.state, &staking_token, &validator3.address, @@ -2679,7 +2697,7 @@ mod test_finalize_block { // Check that there's 3 unique consensus keys let consensus_keys = - namada_proof_of_stake::storage::get_consensus_key_set(&shell.state) + proof_of_stake::storage::get_consensus_key_set(&shell.state) .unwrap(); assert_eq!(consensus_keys.len(), 3); // let ck1 = validator_consensus_key_handle(&validator) @@ -2693,7 +2711,7 @@ mod test_finalize_block { // Validator1 bonds 1 NAM let bond_amount = token::Amount::native_whole(1); - namada_proof_of_stake::bond_tokens( + proof_of_stake::bond_tokens( &mut shell.state, None, &validator1.address, @@ -2705,7 +2723,7 @@ mod test_finalize_block { // Validator2 changes consensus key let new_ck2 = common_sk_from_simple_seed(1).ref_to(); - namada_proof_of_stake::change_consensus_key( + proof_of_stake::change_consensus_key( &mut shell.state, &validator2.address, &new_ck2, @@ -2714,7 +2732,7 @@ mod test_finalize_block { .unwrap(); // Validator3 bonds 1 NAM and changes consensus key - namada_proof_of_stake::bond_tokens( + proof_of_stake::bond_tokens( &mut shell.state, None, &validator3.address, @@ -2724,7 +2742,7 @@ mod test_finalize_block { ) .unwrap(); let new_ck3 = common_sk_from_simple_seed(2).ref_to(); - namada_proof_of_stake::change_consensus_key( + proof_of_stake::change_consensus_key( &mut shell.state, &validator3.address, &new_ck3, @@ -2734,7 +2752,7 @@ mod test_finalize_block { // Check that there's 5 unique consensus keys let consensus_keys = - namada_proof_of_stake::storage::get_consensus_key_set(&shell.state) + proof_of_stake::storage::get_consensus_key_set(&shell.state) .unwrap(); assert_eq!(consensus_keys.len(), 5); @@ -2774,7 +2792,7 @@ mod test_finalize_block { // Val 1 changes consensus key let new_ck1 = common_sk_from_simple_seed(3).ref_to(); - namada_proof_of_stake::change_consensus_key( + proof_of_stake::change_consensus_key( &mut shell.state, &validator1.address, &new_ck1, @@ -2783,7 +2801,7 @@ mod test_finalize_block { .unwrap(); // Val 2 is fully unbonded - namada_proof_of_stake::unbond_tokens( + proof_of_stake::unbond_tokens( &mut shell.state, None, &validator2.address, @@ -2794,7 +2812,7 @@ mod test_finalize_block { .unwrap(); // Val 3 is fully unbonded and changes consensus key - namada_proof_of_stake::unbond_tokens( + proof_of_stake::unbond_tokens( &mut shell.state, None, &validator3.address, @@ -2804,7 +2822,7 @@ mod test_finalize_block { ) .unwrap(); let new2_ck3 = common_sk_from_simple_seed(4).ref_to(); - namada_proof_of_stake::change_consensus_key( + proof_of_stake::change_consensus_key( &mut shell.state, &validator1.address, &new2_ck3, @@ -2814,7 +2832,7 @@ mod test_finalize_block { // Check that there's 7 unique consensus keys let consensus_keys = - namada_proof_of_stake::storage::get_consensus_key_set(&shell.state) + proof_of_stake::storage::get_consensus_key_set(&shell.state) .unwrap(); assert_eq!(consensus_keys.len(), 7); @@ -2846,7 +2864,7 @@ mod test_finalize_block { // set, along with consensus key changes // Val2 bonds 1 NAM and changes consensus key - namada_proof_of_stake::bond_tokens( + proof_of_stake::bond_tokens( &mut shell.state, None, &validator2.address, @@ -2856,7 +2874,7 @@ mod test_finalize_block { ) .unwrap(); let new2_ck2 = common_sk_from_simple_seed(5).ref_to(); - namada_proof_of_stake::change_consensus_key( + proof_of_stake::change_consensus_key( &mut shell.state, &validator2.address, &new2_ck2, @@ -2865,7 +2883,7 @@ mod test_finalize_block { .unwrap(); // Val3 bonds 1 NAM - namada_proof_of_stake::bond_tokens( + proof_of_stake::bond_tokens( &mut shell.state, None, &validator3.address, @@ -2877,7 +2895,7 @@ mod test_finalize_block { // Check that there's 8 unique consensus keys let consensus_keys = - namada_proof_of_stake::storage::get_consensus_key_set(&shell.state) + proof_of_stake::storage::get_consensus_key_set(&shell.state) .unwrap(); assert_eq!(consensus_keys.len(), 8); @@ -3005,9 +3023,10 @@ mod test_finalize_block { fn test_masp_anchors_merklized() { let (mut shell, _, _, _) = setup(); - let convert_key = namada::token::storage_key::masp_convert_anchor_key(); + let convert_key = + namada_sdk::token::storage_key::masp_convert_anchor_key(); let commitment_key = - namada::token::storage_key::masp_commitment_anchor_key(0); + namada_sdk::token::storage_key::masp_commitment_anchor_key(0); // merkle tree root before finalize_block let root_pre = shell.shell.state.in_mem().block.tree.root(); @@ -3600,13 +3619,13 @@ mod test_finalize_block { let fee_amount = wrapper.header().wrapper().unwrap().get_tx_fee().unwrap(); - let fee_amount = namada::token::denom_to_amount( + let fee_amount = namada_sdk::token::denom_to_amount( fee_amount, &wrapper.header().wrapper().unwrap().fee.token, &shell.state, ) .unwrap(); - let signer_balance = namada::token::read_balance( + let signer_balance = namada_sdk::token::read_balance( &shell.state, &shell.state.in_mem().native_token, &wrapper.header().wrapper().unwrap().fee_payer(), @@ -3640,7 +3659,7 @@ mod test_finalize_block { .unwrap(); assert!(inner_result.is_err()); - let new_signer_balance = namada::token::read_balance( + let new_signer_balance = namada_sdk::token::read_balance( &shell.state, &shell.state.in_mem().native_token, &wrapper.header().wrapper().unwrap().fee_payer(), @@ -3662,7 +3681,7 @@ mod test_finalize_block { // Credit some tokens for fee payment let initial_balance = token::Amount::native_whole(1); - namada::token::credit_tokens( + namada_sdk::token::credit_tokens( &mut shell.state, &native_token, &Address::from(&keypair.to_public()), @@ -3701,7 +3720,7 @@ mod test_finalize_block { // payer let fee_amount = wrapper.header().wrapper().unwrap().get_tx_fee().unwrap(); - let fee_amount = namada::token::denom_to_amount( + let fee_amount = namada_sdk::token::denom_to_amount( fee_amount, &wrapper.header().wrapper().unwrap().fee.token, &shell.state, @@ -3746,20 +3765,17 @@ mod test_finalize_block { let validator = shell.mode.get_validator_address().unwrap().to_owned(); let pos_params = - namada_proof_of_stake::storage::read_pos_params(&shell.state) - .unwrap(); + proof_of_stake::storage::read_pos_params(&shell.state).unwrap(); let consensus_key = - namada_proof_of_stake::storage::validator_consensus_key_handle( - &validator, - ) - .get(&shell.state, Epoch::default(), &pos_params) - .unwrap() - .unwrap(); + proof_of_stake::storage::validator_consensus_key_handle(&validator) + .get(&shell.state, Epoch::default(), &pos_params) + .unwrap() + .unwrap(); let proposer_address = HEXUPPER .decode(consensus_key.tm_raw_hash().as_bytes()) .unwrap(); - let proposer_balance = namada::token::read_balance( + let proposer_balance = namada_sdk::token::read_balance( &shell.state, &shell.state.in_mem().native_token, &validator, @@ -3791,14 +3807,14 @@ mod test_finalize_block { ))); let fee_amount = wrapper.header().wrapper().unwrap().get_tx_fee().unwrap(); - let fee_amount = namada::token::denom_to_amount( + let fee_amount = namada_sdk::token::denom_to_amount( fee_amount, &wrapper.header().wrapper().unwrap().fee.token, &shell.state, ) .unwrap(); - let signer_balance = namada::token::read_balance( + let signer_balance = namada_sdk::token::read_balance( &shell.state, &shell.state.in_mem().native_token, &wrapper.header().wrapper().unwrap().fee_payer(), @@ -3826,7 +3842,7 @@ mod test_finalize_block { let code = event.read_attribute::().expect("Test failed"); assert_eq!(code, ResultCode::Ok); - let new_proposer_balance = namada::token::read_balance( + let new_proposer_balance = namada_sdk::token::read_balance( &shell.state, &shell.state.in_mem().native_token, &validator, @@ -3837,7 +3853,7 @@ mod test_finalize_block { proposer_balance.checked_add(fee_amount).unwrap() ); - let new_signer_balance = namada::token::read_balance( + let new_signer_balance = namada_sdk::token::read_balance( &shell.state, &shell.state.in_mem().native_token, &wrapper.header().wrapper().unwrap().fee_payer(), @@ -3850,7 +3866,7 @@ mod test_finalize_block { } #[test] - fn test_ledger_slashing() -> namada::state::StorageResult<()> { + fn test_ledger_slashing() -> namada_sdk::state::StorageResult<()> { let num_validators = 7_u64; let (mut shell, _recv, _, _) = setup_with_cfg(SetupCfg { last_height: 0, @@ -4056,13 +4072,15 @@ mod test_finalize_block { } } - let num_slashes = - namada::state::iter_prefix_bytes(&shell.state, &slashes_prefix())? - .filter(|kv_res| { - let (k, _v) = kv_res.as_ref().unwrap(); - is_validator_slashes_key(k).is_some() - }) - .count(); + let num_slashes = namada_sdk::state::iter_prefix_bytes( + &shell.state, + &slashes_prefix(), + )? + .filter(|kv_res| { + let (k, _v) = kv_res.as_ref().unwrap(); + is_validator_slashes_key(k).is_some() + }) + .count(); assert_eq!(num_slashes, 2); assert_eq!( @@ -4218,7 +4236,7 @@ mod test_finalize_block { /// NOTE: must call `get_default_true_votes` before every call to /// `next_block_for_inflation` #[test] - fn test_multiple_misbehaviors() -> namada::state::StorageResult<()> { + fn test_multiple_misbehaviors() -> namada_sdk::state::StorageResult<()> { for num_validators in &[4_u64, 6_u64, 9_u64] { tracing::debug!("\nNUM VALIDATORS = {}", num_validators); test_multiple_misbehaviors_by_num_vals(*num_validators)?; @@ -4238,7 +4256,7 @@ mod test_finalize_block { /// 7) Discover misbehavior in epoch 4 fn test_multiple_misbehaviors_by_num_vals( num_validators: u64, - ) -> namada::state::StorageResult<()> { + ) -> namada_sdk::state::StorageResult<()> { // Setup the network with pipeline_len = 2, unbonding_len = 4 // let num_validators = 8_u64; let (mut shell, _recv, _, _) = setup_with_cfg(SetupCfg { @@ -4256,7 +4274,7 @@ mod test_finalize_block { let slash_pool_balance_init = read_balance( &shell.state, &nam_address, - &namada_proof_of_stake::SLASH_POOL_ADDRESS, + &proof_of_stake::SLASH_POOL_ADDRESS, ) .unwrap(); debug_assert_eq!(slash_pool_balance_init, token::Amount::zero()); @@ -4297,14 +4315,14 @@ mod test_finalize_block { let delegator = address::testing::gen_implicit_address(); let del_1_amount = token::Amount::native_whole(37_231); let staking_token = shell.state.in_mem().native_token.clone(); - namada::token::credit_tokens( + namada_sdk::token::credit_tokens( &mut shell.state, &staking_token, &delegator, token::Amount::native_whole(200_000), ) .unwrap(); - namada_proof_of_stake::bond_tokens( + proof_of_stake::bond_tokens( &mut shell.state, Some(&delegator), &val1.address, @@ -4316,7 +4334,7 @@ mod test_finalize_block { // Self-unbond let self_unbond_1_amount = token::Amount::native_whole(84_654); - namada_proof_of_stake::unbond_tokens( + proof_of_stake::unbond_tokens( &mut shell.state, None, &val1.address, @@ -4326,7 +4344,7 @@ mod test_finalize_block { ) .unwrap(); - let val_stake = namada_proof_of_stake::storage::read_validator_stake( + let val_stake = proof_of_stake::storage::read_validator_stake( &shell.state, ¶ms, &val1.address, @@ -4334,7 +4352,7 @@ mod test_finalize_block { ) .unwrap(); - let total_stake = namada_proof_of_stake::storage::read_total_stake( + let total_stake = proof_of_stake::storage::read_total_stake( &shell.state, ¶ms, current_epoch + params.pipeline_len, @@ -4359,7 +4377,7 @@ mod test_finalize_block { let (current_epoch, _) = advance_epoch(&mut shell, &pkh1, &votes, None); tracing::debug!("\nUnbonding in epoch 2"); let del_unbond_1_amount = token::Amount::native_whole(18_000); - namada_proof_of_stake::unbond_tokens( + proof_of_stake::unbond_tokens( &mut shell.state, Some(&delegator), &val1.address, @@ -4369,14 +4387,14 @@ mod test_finalize_block { ) .unwrap(); - let val_stake = namada_proof_of_stake::storage::read_validator_stake( + let val_stake = proof_of_stake::storage::read_validator_stake( &shell.state, ¶ms, &val1.address, current_epoch + params.pipeline_len, ) .unwrap(); - let total_stake = namada_proof_of_stake::storage::read_total_stake( + let total_stake = proof_of_stake::storage::read_total_stake( &shell.state, ¶ms, current_epoch + params.pipeline_len, @@ -4405,7 +4423,7 @@ mod test_finalize_block { tracing::debug!("\nBonding in epoch 3"); let self_bond_1_amount = token::Amount::native_whole(9_123); - namada_proof_of_stake::bond_tokens( + proof_of_stake::bond_tokens( &mut shell.state, None, &val1.address, @@ -4425,7 +4443,7 @@ mod test_finalize_block { assert_eq!(current_epoch.0, 4_u64); let self_unbond_2_amount = token::Amount::native_whole(15_000); - namada_proof_of_stake::unbond_tokens( + proof_of_stake::unbond_tokens( &mut shell.state, None, &val1.address, @@ -4447,7 +4465,7 @@ mod test_finalize_block { // Delegate let del_2_amount = token::Amount::native_whole(8_144); - namada_proof_of_stake::bond_tokens( + proof_of_stake::bond_tokens( &mut shell.state, Some(&delegator), &val1.address, @@ -4510,18 +4528,16 @@ mod test_finalize_block { assert_eq!(enqueued_slash.r#type, SlashType::DuplicateVote); assert_eq!(enqueued_slash.rate, Dec::zero()); let last_slash = - namada_proof_of_stake::storage::read_validator_last_slash_epoch( + proof_of_stake::storage::read_validator_last_slash_epoch( &shell.state, &val1.address, ) .unwrap(); assert_eq!(last_slash, Some(misbehavior_epoch)); assert!( - namada_proof_of_stake::storage::validator_slashes_handle( - &val1.address - ) - .is_empty(&shell.state) - .unwrap() + proof_of_stake::storage::validator_slashes_handle(&val1.address) + .is_empty(&shell.state) + .unwrap() ); tracing::debug!("Advancing to epoch 7"); @@ -4581,14 +4597,14 @@ mod test_finalize_block { assert_eq!(num_enqueued_8, 2); assert_eq!(num_enqueued_9, 1); let last_slash = - namada_proof_of_stake::storage::read_validator_last_slash_epoch( + proof_of_stake::storage::read_validator_last_slash_epoch( &shell.state, &val1.address, ) .unwrap(); assert_eq!(last_slash, Some(Epoch(4))); assert!( - namada_proof_of_stake::is_validator_frozen( + proof_of_stake::is_validator_frozen( &shell.state, &val1.address, current_epoch, @@ -4597,21 +4613,18 @@ mod test_finalize_block { .unwrap() ); assert!( - namada_proof_of_stake::storage::validator_slashes_handle( - &val1.address - ) - .is_empty(&shell.state) - .unwrap() + proof_of_stake::storage::validator_slashes_handle(&val1.address) + .is_empty(&shell.state) + .unwrap() ); - let pre_stake_10 = - namada_proof_of_stake::storage::read_validator_stake( - &shell.state, - ¶ms, - &val1.address, - Epoch(10), - ) - .unwrap(); + let pre_stake_10 = proof_of_stake::storage::read_validator_stake( + &shell.state, + ¶ms, + &val1.address, + Epoch(10), + ) + .unwrap(); assert_eq!( pre_stake_10, initial_stake + del_1_amount @@ -4638,14 +4651,14 @@ mod test_finalize_block { let (current_epoch, _) = advance_epoch(&mut shell, &pkh1, &votes, None); assert_eq!(current_epoch.0, 9_u64); - let val_stake_3 = namada_proof_of_stake::storage::read_validator_stake( + let val_stake_3 = proof_of_stake::storage::read_validator_stake( &shell.state, ¶ms, &val1.address, Epoch(3), ) .unwrap(); - let val_stake_4 = namada_proof_of_stake::storage::read_validator_stake( + let val_stake_4 = proof_of_stake::storage::read_validator_stake( &shell.state, ¶ms, &val1.address, @@ -4653,13 +4666,13 @@ mod test_finalize_block { ) .unwrap(); - let tot_stake_3 = namada_proof_of_stake::storage::read_total_stake( + let tot_stake_3 = proof_of_stake::storage::read_total_stake( &shell.state, ¶ms, Epoch(3), ) .unwrap(); - let tot_stake_4 = namada_proof_of_stake::storage::read_total_stake( + let tot_stake_4 = proof_of_stake::storage::read_total_stake( &shell.state, ¶ms, Epoch(4), @@ -4685,9 +4698,7 @@ mod test_finalize_block { // There should be 2 slashes processed for the validator, each with rate // equal to the cubic slashing rate let val_slashes = - namada_proof_of_stake::storage::validator_slashes_handle( - &val1.address, - ); + proof_of_stake::storage::validator_slashes_handle(&val1.address); assert_eq!(val_slashes.len(&shell.state).unwrap(), 2u64); let is_rate_good = val_slashes .iter(&shell.state) @@ -4870,7 +4881,7 @@ mod test_finalize_block { assert_eq!(current_epoch.0, 12_u64); tracing::debug!("\nCHECK BOND AND UNBOND DETAILS"); - let details = namada_proof_of_stake::queries::bonds_and_unbonds( + let details = proof_of_stake::queries::bonds_and_unbonds( &shell.state, None, None, @@ -4989,7 +5000,7 @@ mod test_finalize_block { // let slash_pool_balance_pre_withdraw = slash_pool_balance; // Withdraw the delegation unbonds, which total to 18_000. This should // only be affected by the slashes in epoch 3 - let del_withdraw = namada_proof_of_stake::withdraw_tokens( + let del_withdraw = proof_of_stake::withdraw_tokens( &mut shell.state, Some(&delegator), &val1.address, @@ -5022,7 +5033,7 @@ mod test_finalize_block { // println!("\nWITHDRAWING SELF UNBOND"); // Withdraw the self unbonds, which total 154_654 + 15_000 - 9_123. Only // the (15_000 - 9_123) tokens are slashable. - // let self_withdraw = namada_proof_of_stake::withdraw_tokens( + // let self_withdraw = proof_of_stake::withdraw_tokens( // &mut shell.state, // None, // &val1.address, @@ -5058,8 +5069,8 @@ mod test_finalize_block { } #[test] - fn test_jail_validator_for_inactivity() -> namada::state::StorageResult<()> - { + fn test_jail_validator_for_inactivity() + -> namada_sdk::state::StorageResult<()> { let num_validators = 5_u64; let (mut shell, _recv, _, _) = setup_with_cfg(SetupCfg { last_height: 0, @@ -5091,14 +5102,13 @@ mod test_finalize_block { Epoch::default(), ); - let validator_stake = - namada_proof_of_stake::storage::read_validator_stake( - &shell.state, - ¶ms, - &val2, - Epoch::default(), - ) - .unwrap(); + let validator_stake = proof_of_stake::storage::read_validator_stake( + &shell.state, + ¶ms, + &val2, + Epoch::default(), + ) + .unwrap(); let val3 = initial_consensus_set[2].clone(); let val4 = initial_consensus_set[3].clone(); @@ -5140,7 +5150,7 @@ mod test_finalize_block { // Completely unbond one of the validator to test the pruning at the // pipeline epoch let mut current_epoch = shell.state.in_mem().block.epoch; - namada_proof_of_stake::unbond_tokens( + proof_of_stake::unbond_tokens( &mut shell.state, None, &val5, @@ -5343,7 +5353,7 @@ mod test_finalize_block { } // Validator 2 unjail itself - namada_proof_of_stake::unjail_validator( + proof_of_stake::unjail_validator( &mut shell.state, &val2, current_epoch, @@ -5410,8 +5420,7 @@ mod test_finalize_block { misbehaviors: Option>, ) -> (Epoch, token::Amount) { let current_epoch = shell.state.in_mem().block.epoch; - let staking_token = - namada_proof_of_stake::staking_token_address(&shell.state); + let staking_token = proof_of_stake::staking_token_address(&shell.state); // NOTE: assumed that the only change in pos address balance by // advancing to the next epoch is minted inflation - no change occurs @@ -5468,7 +5477,7 @@ mod test_finalize_block { let keys_changed = BTreeSet::from([min_confirmations_key()]); let verifiers = BTreeSet::default(); let batched_tx = tx.batch_ref_first_tx(); - let ctx = namada::ledger::native_vp::Ctx::new( + let ctx = namada_vp::native_vp::Ctx::new( shell.mode.get_validator_address().expect("Test failed"), shell.state.read_only(), batched_tx.tx, @@ -5479,7 +5488,7 @@ mod test_finalize_block { &verifiers, shell.vp_wasm_cache.clone(), ); - let parameters = ParametersVp { ctx }; + let parameters = ParametersVp::new(ctx); assert!( parameters .validate_tx(&batched_tx, &keys_changed, &verifiers) @@ -5490,7 +5499,7 @@ mod test_finalize_block { let mut req = FinalizeBlock::default(); req.header.time = { #[allow(clippy::disallowed_methods)] - namada::core::time::DateTimeUtc::now() + namada_sdk::time::DateTimeUtc::now() }; let current_decision_height = shell.get_current_decision_height(); if let Some(b) = shell.state.in_mem_mut().last_block.as_mut() { diff --git a/crates/node/src/shell/governance.rs b/crates/node/src/shell/governance.rs index 758ec735d8f..aad63d3230c 100644 --- a/crates/node/src/shell/governance.rs +++ b/crates/node/src/shell/governance.rs @@ -1,34 +1,32 @@ -use namada::core::collections::HashMap; -use namada::core::encode; -use namada::core::storage::Epoch; -use namada::governance::event::GovernanceEvent; -use namada::governance::pgf::storage::keys as pgf_storage; -use namada::governance::pgf::storage::steward::StewardDetail; -use namada::governance::pgf::{storage as pgf, ADDRESS}; -use namada::governance::storage::proposal::{ +use namada_sdk::collections::HashMap; +use namada_sdk::events::extend::{ComposeEvent, Height}; +use namada_sdk::events::{EmitEvents, EventLevel}; +use namada_sdk::governance::event::GovernanceEvent; +use namada_sdk::governance::pgf::storage::keys as pgf_storage; +use namada_sdk::governance::pgf::storage::steward::StewardDetail; +use namada_sdk::governance::pgf::{storage as pgf, ADDRESS}; +use namada_sdk::governance::storage::proposal::{ AddRemove, PGFAction, PGFTarget, ProposalType, StoragePgfFunding, }; -use namada::governance::storage::{keys as gov_storage, load_proposals}; -use namada::governance::utils::{ +use namada_sdk::governance::storage::{keys as gov_storage, load_proposals}; +use namada_sdk::governance::utils::{ compute_proposal_result, ProposalVotes, TallyResult, TallyType, VotePower, }; -use namada::governance::{ +use namada_sdk::governance::{ storage as gov_api, ProposalVote, ADDRESS as gov_address, }; -use namada::ibc; -use namada::ledger::events::extend::{ComposeEvent, Height}; -use namada::proof_of_stake::bond_amount; -use namada::proof_of_stake::parameters::PosParams; -use namada::proof_of_stake::storage::{ - read_total_active_stake, validator_state_handle, +use namada_sdk::proof_of_stake::bond_amount; +use namada_sdk::proof_of_stake::parameters::PosParams; +use namada_sdk::proof_of_stake::storage::{ + read_total_active_stake, read_validator_stake, validator_state_handle, }; -use namada::proof_of_stake::types::{BondId, ValidatorState}; -use namada::sdk::events::{EmitEvents, EventLevel}; -use namada::state::StorageWrite; -use namada::token::event::{TokenEvent, TokenOperation, UserAccount}; -use namada::token::read_balance; -use namada::tx::{Code, Data}; -use namada_sdk::proof_of_stake::storage::read_validator_stake; +use namada_sdk::proof_of_stake::types::{BondId, ValidatorState}; +use namada_sdk::state::StorageWrite; +use namada_sdk::storage::Epoch; +use namada_sdk::token::event::{TokenEvent, TokenOperation, UserAccount}; +use namada_sdk::token::read_balance; +use namada_sdk::tx::{Code, Data}; +use namada_sdk::{encode, ibc}; use super::utils::force_read; use super::*; @@ -304,7 +302,7 @@ fn compute_proposal_votes( params: &PosParams, proposal_id: u64, epoch: Epoch, -) -> namada::state::StorageResult +) -> namada_sdk::state::StorageResult where S: StorageRead, { @@ -387,7 +385,7 @@ fn execute_default_proposal( shell: &mut Shell, id: u64, proposal_code: Vec, -) -> namada::state::StorageResult +) -> namada_sdk::state::StorageResult where D: DB + for<'iter> DBIter<'iter> + Sync + 'static, H: StorageHasher + Sync + 'static, diff --git a/crates/node/src/shell/init_chain.rs b/crates/node/src/shell/init_chain.rs index 457004ff2a4..6a10c9b05c7 100644 --- a/crates/node/src/shell/init_chain.rs +++ b/crates/node/src/shell/init_chain.rs @@ -5,19 +5,18 @@ use std::ops::ControlFlow; use masp_primitives::merkle_tree::CommitmentTree; use masp_primitives::sapling::Node; use masp_proofs::bls12_381; -use namada::account::protocol_pk_key; -use namada::core::collections::HashMap; -use namada::core::hash::Hash as CodeHash; -use namada::core::time::{TimeZone, Utc}; -use namada::ledger::parameters::Parameters; -use namada::ledger::{ibc, pos}; -use namada::proof_of_stake::BecomeValidator; -use namada::state::StorageWrite; -use namada::token::storage_key::masp_token_map_key; -use namada::token::{credit_tokens, write_denom}; -use namada::vm::validate_untrusted_wasm; +use namada_sdk::account::protocol_pk_key; +use namada_sdk::collections::HashMap; use namada_sdk::eth_bridge::EthBridgeStatus; -use namada_sdk::proof_of_stake::PosParams; +use namada_sdk::hash::Hash as CodeHash; +use namada_sdk::parameters::Parameters; +use namada_sdk::proof_of_stake::{self, BecomeValidator, PosParams}; +use namada_sdk::state::StorageWrite; +use namada_sdk::time::{TimeZone, Utc}; +use namada_sdk::token::storage_key::masp_token_map_key; +use namada_sdk::token::{credit_tokens, write_denom}; +use namada_sdk::{eth_bridge, ibc}; +use namada_vm::validate_untrusted_wasm; use super::*; use crate::config::genesis::chain::{ @@ -184,7 +183,7 @@ where let convert_anchor_key = token::storage_key::masp_convert_anchor_key(); self.state.write( &convert_anchor_key, - namada::core::hash::Hash( + namada_sdk::hash::Hash( bls12_381::Scalar::from( self.state.in_mem().conversion_state.tree.root(), ) @@ -246,7 +245,7 @@ where } else { self.state .write( - &namada::eth_bridge::storage::active_key(), + ð_bridge::storage::active_key(), EthBridgeStatus::Disabled, ) .unwrap(); @@ -265,7 +264,7 @@ where // PoS system depends on epoch being initialized let pos_params = genesis.get_pos_params(); let (current_epoch, _gas) = self.state.in_mem().get_current_epoch(); - pos::namada_proof_of_stake::init_genesis( + proof_of_stake::init_genesis( &mut self.state, &pos_params, current_epoch, @@ -291,13 +290,13 @@ where ); self.apply_genesis_txs_bonds(&genesis); - pos::namada_proof_of_stake::compute_and_store_total_consensus_stake( + proof_of_stake::compute_and_store_total_consensus_stake( &mut self.state, current_epoch, ) .expect("Could not compute total consensus stake at genesis"); // This has to be done after `apply_genesis_txs_validator_account` - pos::namada_proof_of_stake::copy_genesis_validator_sets( + proof_of_stake::copy_genesis_validator_sets( &mut self.state, &pos_params, current_epoch, @@ -315,7 +314,7 @@ where genesis: &genesis::chain::Finalized, vp_cache: &mut HashMap>, ) -> ControlFlow<(), Vec> { - use namada::core::collections::hash_map::Entry; + use namada_sdk::collections::hash_map::Entry; let Some(vp_filename) = self .validate( genesis @@ -469,7 +468,7 @@ where } = token; // associate a token with its denomination. write_denom(&mut self.state, address, *denom).unwrap(); - namada::token::write_params( + namada_sdk::token::write_params( masp_params, &mut self.state, address, @@ -514,7 +513,7 @@ where for (owner, balance) in balances { if let genesis::GenesisAddress::PublicKey(pk) = owner { - namada::account::init_account_storage( + namada_sdk::account::init_account_storage( &mut self.state, &owner.address(), std::slice::from_ref(&pk.raw), @@ -569,7 +568,7 @@ where let public_keys: Vec<_> = public_keys.iter().map(|pk| pk.raw.clone()).collect(); - namada::account::init_account_storage( + namada_sdk::account::init_account_storage( &mut self.state, address, &public_keys, @@ -587,7 +586,7 @@ where genesis: &genesis::chain::Finalized, vp_cache: &mut HashMap>, params: &PosParams, - current_epoch: namada::core::storage::Epoch, + current_epoch: namada_sdk::storage::Epoch, ) -> ControlFlow<()> { if let Some(txs) = genesis.transactions.validator_account.as_ref() { for FinalizedValidatorAccountTx { @@ -628,7 +627,7 @@ where .write(&protocol_pk_key(address), &protocol_key.pk.raw) .expect("Unable to set genesis user protocol public key"); - if let Err(err) = pos::namada_proof_of_stake::become_validator( + if let Err(err) = proof_of_stake::become_validator( &mut self.state, BecomeValidator { params, @@ -676,7 +675,7 @@ where amount, ); - if let Err(err) = pos::namada_proof_of_stake::bond_tokens( + if let Err(err) = proof_of_stake::bond_tokens( &mut self.state, Some(&source.address()), validator, @@ -969,8 +968,8 @@ impl Policy { mod test { use std::str::FromStr; - use namada::core::string_encoding::StringEncoded; use namada_apps_lib::wallet::defaults; + use namada_sdk::string_encoding::StringEncoded; use namada_sdk::wallet::alias::Alias; use super::*; @@ -1166,7 +1165,7 @@ mod test { let pos_params = genesis.get_pos_params(); let (current_epoch, _gas) = initializer.state.in_mem().get_current_epoch(); - pos::namada_proof_of_stake::init_genesis( + proof_of_stake::init_genesis( &mut initializer.state, &pos_params, current_epoch, diff --git a/crates/node/src/shell/mod.rs b/crates/node/src/shell/mod.rs index 2ace0f620a7..d7e15a1389f 100644 --- a/crates/node/src/shell/mod.rs +++ b/crates/node/src/shell/mod.rs @@ -10,10 +10,11 @@ mod finalize_block; mod governance; mod init_chain; pub use init_chain::InitChainValidation; -use namada::vm::wasm::run::check_tx_allowed; use namada_sdk::state::StateRead; +use namada_vm::wasm::run::check_tx_allowed; pub mod prepare_proposal; -use namada::state::State; +use namada_sdk::ibc; +use namada_sdk::state::State; pub mod process_proposal; pub(super) mod queries; mod stats; @@ -31,42 +32,40 @@ use std::rc::Rc; use borsh::BorshDeserialize; use borsh_ext::BorshSerializeExt; -use namada::core::address::Address; -use namada::core::chain::ChainId; -use namada::core::ethereum_events::EthereumEvent; -use namada::core::hints; -use namada::core::key::*; -use namada::core::storage::{BlockHeight, Key, TxIndex}; -use namada::core::time::DateTimeUtc; -use namada::ethereum_bridge::protocol::validation::bridge_pool_roots::validate_bp_roots_vext; -use namada::ethereum_bridge::protocol::validation::ethereum_events::validate_eth_events_vext; -use namada::ethereum_bridge::protocol::validation::validator_set_update::validate_valset_upd_vext; -use namada::ledger::events::log::EventLog; -use namada::ledger::gas::{Gas, TxGasMeter}; -use namada::ledger::pos::namada_proof_of_stake::types::{ +use namada_apps_lib::wallet::{self, ValidatorData, ValidatorKeys}; +use namada_sdk::address::Address; +use namada_sdk::chain::ChainId; +use namada_sdk::eth_bridge::protocol::validation::bridge_pool_roots::validate_bp_roots_vext; +use namada_sdk::eth_bridge::protocol::validation::ethereum_events::validate_eth_events_vext; +use namada_sdk::eth_bridge::protocol::validation::validator_set_update::validate_valset_upd_vext; +use namada_sdk::eth_bridge::{EthBridgeQueries, EthereumOracleConfig}; +use namada_sdk::ethereum_events::EthereumEvent; +use namada_sdk::events::log::EventLog; +use namada_sdk::gas::{Gas, TxGasMeter}; +use namada_sdk::key::*; +use namada_sdk::migrations::ScheduledMigration; +use namada_sdk::parameters::validate_tx_bytes; +use namada_sdk::proof_of_stake::storage::read_pos_params; +use namada_sdk::proof_of_stake::types::{ ConsensusValidator, ValidatorSetUpdate, }; -use namada::ledger::protocol::ShellParams; -use namada::ledger::{parameters, protocol}; -use namada::parameters::validate_tx_bytes; -use namada::proof_of_stake::storage::read_pos_params; -use namada::state::tx_queue::ExpiredTx; -use namada::state::{ +use namada_sdk::state::tx_queue::ExpiredTx; +use namada_sdk::state::{ DBIter, FullAccessState, Sha256Hasher, StorageHasher, StorageRead, TempWlState, WlState, DB, EPOCH_SWITCH_BLOCKS_DELAY, }; -use namada::token; -pub use namada::tx::data::ResultCode; -use namada::tx::data::{TxType, WrapperTx}; -use namada::tx::{Section, Tx}; -use namada::vm::wasm::{TxCache, VpCache}; -use namada::vm::{WasmCacheAccess, WasmCacheRwAccess}; -use namada::vote_ext::EthereumTxData; -use namada_apps_lib::wallet::{self, ValidatorData, ValidatorKeys}; -use namada_sdk::eth_bridge::{EthBridgeQueries, EthereumOracleConfig}; -use namada_sdk::migrations; -use namada_sdk::migrations::ScheduledMigration; +use namada_sdk::storage::{BlockHeight, Key, TxIndex}; use namada_sdk::tendermint::AppHash; +use namada_sdk::time::DateTimeUtc; +pub use namada_sdk::tx::data::ResultCode; +use namada_sdk::tx::data::{TxType, WrapperTx}; +use namada_sdk::tx::{Section, Tx}; +use namada_sdk::{ + eth_bridge, hints, migrations, parameters, proof_of_stake, token, +}; +use namada_vm::wasm::{TxCache, VpCache}; +use namada_vm::{WasmCacheAccess, WasmCacheRwAccess}; +use namada_vote_ext::EthereumTxData; use thiserror::Error; use tokio::sync::mpsc::{Receiver, UnboundedSender}; @@ -75,9 +74,10 @@ use crate::config::{self, genesis, TendermintMode, ValidatorLocalConfig}; use crate::facade::tendermint::v0_37::abci::{request, response}; use crate::facade::tendermint::{self, validator}; use crate::facade::tendermint_proto::v0_37::crypto::public_key; +use crate::protocol::ShellParams; use crate::shims::abcipp_shim_types::shim; use crate::shims::abcipp_shim_types::shim::response::TxResult; -use crate::{storage, tendermint_node}; +use crate::{protocol, storage, tendermint_node}; fn key_to_tendermint( pk: &common::PublicKey, @@ -99,7 +99,7 @@ pub enum Error { #[error("chain ID mismatch: {0}")] ChainId(String), #[error("Error decoding a transaction from bytes: {0}")] - TxDecoding(namada::tx::DecodeError), + TxDecoding(namada_sdk::tx::DecodeError), #[error("Error trying to apply a transaction: {0}")] TxApply(protocol::Error), #[error("{0}")] @@ -117,7 +117,7 @@ pub enum Error { #[error("Error loading wasm: {0}")] LoadingWasm(String), #[error("Error reading from or writing to storage: {0}")] - Storage(#[from] namada::state::StorageError), + Storage(#[from] namada_sdk::state::StorageError), #[error("Transaction replay attempt: {0}")] ReplayAttempt(String), } @@ -158,7 +158,7 @@ pub fn rollback(config: config::Ledger) -> Result<()> { tracing::info!("Rollback Namada state"); db.rollback(tendermint_block_height) - .map_err(|e| Error::Storage(namada::state::StorageError::new(e))) + .map_err(|e| Error::Storage(namada_sdk::state::StorageError::new(e))) } #[derive(Debug)] @@ -365,8 +365,8 @@ pub fn is_key_diff_storable(key: &namada_sdk::storage::Key) -> bool { && *key != token::storage_key::masp_token_map_key() && *key != token::storage_key::masp_assets_hash_key() && !token::storage_key::is_masp_commitment_anchor_key(key) - || namada::ibc::storage::is_ibc_counter_key(key) - || namada::proof_of_stake::storage_key::is_delegation_targets_key(key)) + || ibc::storage::is_ibc_counter_key(key) + || proof_of_stake::storage_key::is_delegation_targets_key(key)) } /// Channels for communicating with an Ethereum oracle. @@ -425,7 +425,7 @@ where any(test, feature = "testing", feature = "benches"), not(feature = "integration"), ))] - let native_token = namada::address::testing::nam(); + let native_token = namada_sdk::address::testing::nam(); // ... Otherwise, look it up from the genesis file #[cfg(not(all( any(test, feature = "testing", feature = "benches"), @@ -772,7 +772,7 @@ where .expect("Validators should have protocol keys"); let signed_tx = EthereumTxData::EthEventsVext( - namada::vote_ext::ethereum_events::SignedVext(vote_extension), + namada_vote_ext::ethereum_events::SignedVext(vote_extension), ) .sign(protocol_key, self.chain_id.clone()) .to_bytes(); @@ -807,7 +807,7 @@ where // initialized yet. let has_key = self .state - .has_key(&namada::eth_bridge::storage::active_key()) + .has_key(ð_bridge::storage::active_key()) .expect( "We should always be able to check whether a key exists \ in storage or not", @@ -827,9 +827,7 @@ where return; }; let active = if !self.state.ethbridge_queries().is_bridge_active() { - if !changed_keys - .contains(&namada::eth_bridge::storage::active_key()) - { + if !changed_keys.contains(ð_bridge::storage::active_key()) { tracing::debug!( "Not starting oracle as the Ethereum bridge is \ disabled" @@ -856,7 +854,7 @@ where "Found Ethereum height from which the Ethereum oracle should \ be updated" ); - let config = namada::eth_bridge::oracle::config::Config { + let config = eth_bridge::oracle::config::Config { min_confirmations: config.min_confirmations.into(), bridge_contract: config.contracts.bridge.address, start_block, @@ -895,8 +893,8 @@ where tx_bytes: &[u8], r#_type: MempoolTxType, ) -> response::CheckTx { - use namada::tx::data::protocol::ProtocolTxType; - use namada::vote_ext::ethereum_tx_data_variants; + use namada_sdk::tx::data::protocol::ProtocolTxType; + use namada_vote_ext::ethereum_tx_data_variants; let mut response = response::CheckTx::default(); @@ -1090,7 +1088,7 @@ where // Max block gas let block_gas_limit: Gas = Gas::from_whole_units( - namada::parameters::get_max_block_gas(&self.state).unwrap(), + parameters::get_max_block_gas(&self.state).unwrap(), ) .expect("Gas limit from parameter must not overflow"); if gas_meter.tx_gas_limit > block_gas_limit { @@ -1185,21 +1183,18 @@ where // because we're using domain types in InitChain, but FinalizeBlock is // shimmed with a different old type. The joy... mut validator_conv: F, - ) -> namada::state::StorageResult> + ) -> namada_sdk::state::StorageResult> where F: FnMut(common::PublicKey, i64) -> V, { - use namada::ledger::pos::namada_proof_of_stake; - let (current_epoch, _gas) = self.state.in_mem().get_current_epoch(); - let pos_params = - namada_proof_of_stake::storage::read_pos_params(&self.state) - .expect("Could not find the PoS parameters"); + let pos_params = proof_of_stake::storage::read_pos_params(&self.state) + .expect("Could not find the PoS parameters"); let validator_set_update_fn = if is_genesis { - namada_proof_of_stake::genesis_validator_set_tendermint + proof_of_stake::genesis_validator_set_tendermint } else { - namada_proof_of_stake::validator_set_update::validator_set_update_comet + proof_of_stake::validator_set_update::validator_set_update_comet }; validator_set_update_fn( @@ -1289,15 +1284,13 @@ where H: StorageHasher + Sync + 'static, CA: 'static + WasmCacheAccess + Sync, { - let minimum_gas_price = namada::ledger::parameters::read_gas_cost( - shell_params.state, - &wrapper.fee.token, - ) - .expect("Must be able to read gas cost parameter") - .ok_or(Error::TxApply(protocol::Error::FeeError(format!( - "The provided {} token is not allowed for fee payment", - wrapper.fee.token - ))))?; + let minimum_gas_price = + parameters::read_gas_cost(shell_params.state, &wrapper.fee.token) + .expect("Must be able to read gas cost parameter") + .ok_or(Error::TxApply(protocol::Error::FeeError(format!( + "The provided {} token is not allowed for fee payment", + wrapper.fee.token + ))))?; fee_data_check(wrapper, minimum_gas_price, shell_params)?; protocol::check_fees(shell_params.state, wrapper).map_err(Error::TxApply) @@ -1349,17 +1342,17 @@ mod test_utils { use std::ops::{Deref, DerefMut}; use data_encoding::HEXUPPER; - use namada::core::ethereum_events::Uint; - use namada::core::hash::Hash; - use namada::core::keccak::KeccakHash; - use namada::core::key::*; - use namada::core::storage::{Epoch, Header}; - use namada::ledger::events::Event; - use namada::proof_of_stake::parameters::PosParams; - use namada::proof_of_stake::storage::validator_consensus_key_handle; - use namada::state::mockdb::MockDB; - use namada::state::{LastBlock, StorageWrite}; - use namada::tendermint::abci::types::VoteInfo; + use namada_sdk::ethereum_events::Uint; + use namada_sdk::events::Event; + use namada_sdk::hash::Hash; + use namada_sdk::keccak::KeccakHash; + use namada_sdk::key::*; + use namada_sdk::proof_of_stake::parameters::PosParams; + use namada_sdk::proof_of_stake::storage::validator_consensus_key_handle; + use namada_sdk::state::mockdb::MockDB; + use namada_sdk::state::{LastBlock, StorageWrite}; + use namada_sdk::storage::{Epoch, Header}; + use namada_sdk::tendermint::abci::types::VoteInfo; use tempfile::tempdir; use tokio::sync::mpsc::{Sender, UnboundedReceiver}; @@ -1452,7 +1445,7 @@ mod test_utils { /// Get the default bridge pool vext bytes to be signed. pub fn get_bp_bytes_to_sign() -> KeccakHash { - use namada::core::keccak::{Hasher, Keccak}; + use namada_sdk::keccak::{Hasher, Keccak}; let root = [0; 32]; let nonce = Uint::from(0).to_bytes(); @@ -1828,8 +1821,8 @@ mod test_utils { /// Set the Ethereum bridge to be inactive pub(super) fn deactivate_bridge(shell: &mut TestShell) { - use namada::eth_bridge::storage::active_key; - use namada::eth_bridge::storage::eth_bridge_queries::EthBridgeStatus; + use eth_bridge::storage::active_key; + use eth_bridge::storage::eth_bridge_queries::EthBridgeStatus; shell .state .write(&active_key(), EthBridgeStatus::Disabled) @@ -1881,17 +1874,17 @@ mod test_utils { #[cfg(test)] mod shell_tests { - use namada::core::storage::Epoch; - use namada::eth_bridge::storage::eth_bridge_queries::is_bridge_comptime_enabled; - use namada::token::read_denom; - use namada::tx::data::protocol::{ProtocolTx, ProtocolTxType}; - use namada::tx::data::Fee; - use namada::tx::{Authorization, Code, Data, Signed}; - use namada::vote_ext::{ + use eth_bridge::storage::eth_bridge_queries::is_bridge_comptime_enabled; + use namada_sdk::address; + use namada_sdk::storage::Epoch; + use namada_sdk::token::read_denom; + use namada_sdk::tx::data::protocol::{ProtocolTx, ProtocolTxType}; + use namada_sdk::tx::data::Fee; + use namada_sdk::tx::{Authorization, Code, Data, Signed}; + use namada_vote_ext::{ bridge_pool_roots, ethereum_events, ethereum_tx_data_variants, }; - use namada::{address, replay_protection}; - use wallet; + use {namada_replay_protection as replay_protection, wallet}; use super::*; use crate::shell::token::DenominatedAmount; @@ -1996,7 +1989,7 @@ mod shell_tests { /// not validated by `CheckTx`. #[test] fn test_outdated_nonce_mempool_validate() { - use namada::core::storage::InnerEthEventsQueue; + use namada_sdk::storage::InnerEthEventsQueue; const LAST_HEIGHT: BlockHeight = BlockHeight(3); @@ -2351,7 +2344,7 @@ mod shell_tests { ))); // Write wrapper hash to storage - let mut batch = namada::state::testing::TestState::batch(); + let mut batch = namada_sdk::state::testing::TestState::batch(); let wrapper_hash = wrapper.header_hash(); let wrapper_hash_key = replay_protection::current_key(&wrapper_hash); shell diff --git a/crates/node/src/shell/prepare_proposal.rs b/crates/node/src/shell/prepare_proposal.rs index 6cc2f22392e..90385af24a6 100644 --- a/crates/node/src/shell/prepare_proposal.rs +++ b/crates/node/src/shell/prepare_proposal.rs @@ -2,18 +2,17 @@ use std::cell::RefCell; -use namada::core::address::Address; -use namada::core::key::tm_raw_hash_to_string; -use namada::gas::{Gas, TxGasMeter}; -use namada::hash::Hash; -use namada::ledger::protocol::{self, ShellParams}; -use namada::proof_of_stake::storage::find_validator_by_raw_hash; -use namada::state::{DBIter, StorageHasher, TempWlState, DB}; -use namada::token::{Amount, DenominatedAmount}; -use namada::tx::data::{TxType, WrapperTx}; -use namada::tx::Tx; -use namada::vm::wasm::{TxCache, VpCache}; -use namada::vm::WasmCacheAccess; +use namada_sdk::address::Address; +use namada_sdk::gas::{Gas, TxGasMeter}; +use namada_sdk::hash::Hash; +use namada_sdk::key::tm_raw_hash_to_string; +use namada_sdk::proof_of_stake::storage::find_validator_by_raw_hash; +use namada_sdk::state::{DBIter, StorageHasher, TempWlState, DB}; +use namada_sdk::token::{Amount, DenominatedAmount}; +use namada_sdk::tx::data::{TxType, WrapperTx}; +use namada_sdk::tx::Tx; +use namada_vm::wasm::{TxCache, VpCache}; +use namada_vm::WasmCacheAccess; use super::super::*; use super::block_alloc::states::{ @@ -24,6 +23,7 @@ use super::block_alloc::{AllocFailure, BlockAllocator, BlockResources}; use crate::config::ValidatorLocalConfig; use crate::facade::tendermint_proto::google::protobuf::Timestamp; use crate::facade::tendermint_proto::v0_37::abci::RequestPrepareProposal; +use crate::protocol::{self, ShellParams}; use crate::shell::ShellMode; use crate::shims::abcipp_shim_types::shim::{response, TxBytes}; @@ -356,7 +356,7 @@ where H: StorageHasher + Sync + 'static, { let consensus_min_gas_price = - namada::ledger::parameters::read_gas_cost(temp_state, fee_token) + namada_sdk::parameters::read_gas_cost(temp_state, fee_token) .expect("Must be able to read gas cost parameter") .ok_or_else(|| { Error::TxApply(protocol::Error::FeeError(format!( @@ -406,25 +406,23 @@ where mod test_prepare_proposal { use std::collections::BTreeSet; - use namada::core::address; - use namada::core::ethereum_events::EthereumEvent; - use namada::core::key::RefTo; - use namada::core::storage::{BlockHeight, InnerEthEventsQueue}; - use namada::ledger::pos::PosQueries; - use namada::proof_of_stake::storage::{ + use namada_apps_lib::wallet; + use namada_replay_protection as replay_protection; + use namada_sdk::ethereum_events::EthereumEvent; + use namada_sdk::key::RefTo; + use namada_sdk::proof_of_stake::storage::{ consensus_validator_set_handle, read_consensus_validator_set_addresses_with_stake, }; - use namada::proof_of_stake::types::WeightedValidator; - use namada::proof_of_stake::Epoch; - use namada::state::collections::lazy_map::{NestedSubKey, SubKey}; - use namada::token::read_denom; - use namada::tx::data::Fee; - use namada::tx::{Authorization, Code, Data, Section, Signed}; - use namada::vote_ext::{ethereum_events, ethereum_tx_data_variants}; - use namada::{replay_protection, token}; - use namada_apps_lib::wallet; - use namada_sdk::storage::StorageWrite; + use namada_sdk::proof_of_stake::types::WeightedValidator; + use namada_sdk::proof_of_stake::{Epoch, PosQueries}; + use namada_sdk::state::collections::lazy_map::{NestedSubKey, SubKey}; + use namada_sdk::storage::{BlockHeight, InnerEthEventsQueue, StorageWrite}; + use namada_sdk::token::read_denom; + use namada_sdk::tx::data::Fee; + use namada_sdk::tx::{Authorization, Code, Data, Section, Signed}; + use namada_sdk::{address, token}; + use namada_vote_ext::{ethereum_events, ethereum_tx_data_variants}; use super::*; use crate::shell::test_utils::{ @@ -595,7 +593,7 @@ mod test_prepare_proposal { /// behaves as expected, considering <= 2/3 voting power. #[test] fn test_prepare_proposal_vext_insufficient_voting_power() { - use namada::tendermint::abci::types::{Validator, VoteInfo}; + use namada_sdk::tendermint::abci::types::{Validator, VoteInfo}; const FIRST_HEIGHT: BlockHeight = BlockHeight(1); const LAST_HEIGHT: BlockHeight = BlockHeight(FIRST_HEIGHT.0 + 11); @@ -941,7 +939,7 @@ mod test_prepare_proposal { #[allow(clippy::disallowed_methods)] let time = DateTimeUtc::now(); let block_time = - namada::core::tendermint_proto::google::protobuf::Timestamp { + namada_sdk::tendermint_proto::google::protobuf::Timestamp { seconds: time.0.timestamp(), nanos: time.0.timestamp_subsec_nanos() as i32, }; @@ -963,7 +961,7 @@ mod test_prepare_proposal { let (shell, _recv, _, _) = test_utils::setup(); let block_gas_limit = - namada::parameters::get_max_block_gas(&shell.state).unwrap(); + namada_sdk::parameters::get_max_block_gas(&shell.state).unwrap(); let keypair = gen_keypair(); let wrapper = WrapperTx::new( @@ -1043,9 +1041,9 @@ mod test_prepare_proposal { if let ShellMode::Validator { local_config, .. } = &mut shell.mode { // Remove the allowed btc *local_config = Some(ValidatorLocalConfig { - accepted_gas_tokens: namada::core::collections::HashMap::from( - [(namada::core::address::testing::nam(), Amount::from(1))], - ), + accepted_gas_tokens: namada_sdk::collections::HashMap::from([ + (namada_sdk::address::testing::nam(), Amount::from(1)), + ]), }); } @@ -1144,12 +1142,9 @@ mod test_prepare_proposal { if let ShellMode::Validator { local_config, .. } = &mut shell.mode { // Remove btc and increase minimum for nam *local_config = Some(ValidatorLocalConfig { - accepted_gas_tokens: namada::core::collections::HashMap::from( - [( - namada::core::address::testing::nam(), - Amount::from(100), - )], - ), + accepted_gas_tokens: namada_sdk::collections::HashMap::from([ + (namada_sdk::address::testing::nam(), Amount::from(100)), + ]), }); } @@ -1421,19 +1416,18 @@ mod test_prepare_proposal { let temp_state = shell.state.with_temp_write_log(); let validator_min_gas_price = Amount::zero(); - let consensus_min_gas_price = - namada::ledger::parameters::read_gas_cost( - &temp_state, - &shell.state.in_mem().native_token, - ) - .expect("Must be able to read gas cost parameter") - .expect("NAM should be an allowed gas token"); + let consensus_min_gas_price = namada_sdk::parameters::read_gas_cost( + &temp_state, + &shell.state.in_mem().native_token, + ) + .expect("Must be able to read gas cost parameter") + .expect("NAM should be an allowed gas token"); assert!(validator_min_gas_price < consensus_min_gas_price); let config = ValidatorLocalConfig { accepted_gas_tokens: { - let mut m = namada::core::collections::HashMap::new(); + let mut m = namada_sdk::collections::HashMap::new(); m.insert( shell.state.in_mem().native_token.clone(), validator_min_gas_price, diff --git a/crates/node/src/shell/process_proposal.rs b/crates/node/src/shell/process_proposal.rs index f226097c116..70c7be34504 100644 --- a/crates/node/src/shell/process_proposal.rs +++ b/crates/node/src/shell/process_proposal.rs @@ -2,11 +2,12 @@ //! and [`RevertProposal`] ABCI++ methods for the Shell use data_encoding::HEXUPPER; -use namada::hash::Hash; -use namada::ledger::pos::PosQueries; -use namada::proof_of_stake::storage::find_validator_by_raw_hash; -use namada::tx::data::protocol::ProtocolTxType; -use namada::vote_ext::ethereum_tx_data_variants; +use namada_sdk::hash::Hash; +use namada_sdk::parameters; +use namada_sdk::proof_of_stake::storage::find_validator_by_raw_hash; +use namada_sdk::proof_of_stake::PosQueries; +use namada_sdk::tx::data::protocol::ProtocolTxType; +use namada_vote_ext::ethereum_tx_data_variants; use super::block_alloc::{BlockGas, BlockSpace}; use super::*; @@ -33,8 +34,7 @@ where fn from(state: &WlState) -> Self { let max_proposal_bytes = state.pos_queries().get_max_proposal_bytes().get(); - let max_block_gas = - namada::parameters::get_max_block_gas(state).unwrap(); + let max_block_gas = parameters::get_max_block_gas(state).unwrap(); let user_gas = TxBin::init(max_block_gas); let txs_bin = TxBin::init(max_proposal_bytes); @@ -527,15 +527,13 @@ where H: StorageHasher + Sync + 'static, CA: 'static + WasmCacheAccess + Sync, { - let minimum_gas_price = namada::ledger::parameters::read_gas_cost( - shell_params.state, - &wrapper.fee.token, - ) - .expect("Must be able to read gas cost parameter") - .ok_or(Error::TxApply(protocol::Error::FeeError(format!( - "The provided {} token is not allowed for fee payment", - wrapper.fee.token - ))))?; + let minimum_gas_price = + parameters::read_gas_cost(shell_params.state, &wrapper.fee.token) + .expect("Must be able to read gas cost parameter") + .ok_or(Error::TxApply(protocol::Error::FeeError(format!( + "The provided {} token is not allowed for fee payment", + wrapper.fee.token + ))))?; fee_data_check(wrapper, minimum_gas_price, shell_params)?; @@ -554,19 +552,20 @@ where // process proposals #[cfg(test)] mod test_process_proposal { - use namada::core::key::*; - use namada::eth_bridge::storage::eth_bridge_queries::{ + use namada_apps_lib::wallet; + use namada_replay_protection as replay_protection; + use namada_sdk::address; + use namada_sdk::eth_bridge::storage::eth_bridge_queries::{ is_bridge_comptime_enabled, EthBridgeQueries, }; - use namada::state::StorageWrite; - use namada::token::{read_denom, Amount, DenominatedAmount}; - use namada::tx::data::Fee; - use namada::tx::{Authorization, Code, Data, Signed}; - use namada::vote_ext::{ + use namada_sdk::key::*; + use namada_sdk::state::StorageWrite; + use namada_sdk::token::{read_denom, Amount, DenominatedAmount}; + use namada_sdk::tx::data::Fee; + use namada_sdk::tx::{Authorization, Code, Data, Signed}; + use namada_vote_ext::{ bridge_pool_roots, ethereum_events, validator_set_update, }; - use namada::{address, replay_protection}; - use namada_apps_lib::wallet; use super::*; use crate::shell::test_utils::{ @@ -1164,7 +1163,7 @@ mod test_process_proposal { ))); // Write wrapper hash to storage - let mut batch = namada::state::testing::TestState::batch(); + let mut batch = namada_sdk::state::testing::TestState::batch(); let wrapper_unsigned_hash = wrapper.header_hash(); let hash_key = replay_protection::current_key(&wrapper_unsigned_hash); shell @@ -1284,7 +1283,7 @@ mod test_process_proposal { ))); // Write inner hash to storage - let mut batch = namada::state::testing::TestState::batch(); + let mut batch = namada_sdk::state::testing::TestState::batch(); let hash_key = replay_protection::current_key(&wrapper.raw_header_hash()); shell @@ -1477,7 +1476,7 @@ mod test_process_proposal { let (shell, _recv, _, _) = test_utils::setup(); let block_gas_limit = - namada::parameters::get_max_block_gas(&shell.state).unwrap(); + parameters::get_max_block_gas(&shell.state).unwrap(); let keypair = super::test_utils::gen_keypair(); let mut wrapper = @@ -1731,7 +1730,7 @@ mod test_process_proposal { /// Test max tx bytes parameter in ProcessProposal #[test] fn test_max_tx_bytes_process_proposal() { - use namada::ledger::parameters::storage::get_max_tx_bytes_key; + use parameters::storage::get_max_tx_bytes_key; let (shell, _recv, _, _) = test_utils::setup_at_height(3u64); let max_tx_bytes: u32 = { @@ -1798,7 +1797,7 @@ mod test_process_proposal { /// not validated by `ProcessProposal`. #[test] fn test_outdated_nonce_process_proposal() { - use namada::core::storage::InnerEthEventsQueue; + use namada_sdk::storage::InnerEthEventsQueue; const LAST_HEIGHT: BlockHeight = BlockHeight(3); diff --git a/crates/node/src/shell/queries.rs b/crates/node/src/shell/queries.rs index a1490b4a082..0b1061283c9 100644 --- a/crates/node/src/shell/queries.rs +++ b/crates/node/src/shell/queries.rs @@ -1,9 +1,9 @@ //! Shell methods for querying state -use namada::ledger::dry_run_tx; -use namada::ledger::queries::{RequestCtx, ResponseQuery, RPC}; +use namada_sdk::queries::{RequestCtx, ResponseQuery, RPC}; use super::*; +use crate::dry_run_tx; impl Shell where @@ -15,19 +15,24 @@ where /// the default if `path` is not a supported string. /// INVARIANT: This method must be stateless. pub fn query(&self, query: request::Query) -> response::Query { - let ctx = RequestCtx { - state: self.state.read_only(), - event_log: self.event_log(), - vp_wasm_cache: self.vp_wasm_cache.read_only(), - tx_wasm_cache: self.tx_wasm_cache.read_only(), - storage_read_past_height_limit: self.storage_read_past_height_limit, - }; - // Invoke the root RPC handler - returns borsh-encoded data on success let result = if query.path == RPC.shell().dry_run_tx_path() { - dry_run_tx(ctx, &query) + dry_run_tx( + unsafe { self.state.read_only().with_static_temp_write_log() }, + self.vp_wasm_cache.read_only(), + self.tx_wasm_cache.read_only(), + &query, + ) } else { - namada::ledger::queries::handle_path(ctx, &query) + let ctx = RequestCtx { + state: self.state.read_only(), + event_log: self.event_log(), + vp_wasm_cache: self.vp_wasm_cache.read_only(), + tx_wasm_cache: self.tx_wasm_cache.read_only(), + storage_read_past_height_limit: self + .storage_read_past_height_limit, + }; + namada_sdk::queries::handle_path(ctx, &query) }; match result { Ok(ResponseQuery { @@ -64,19 +69,19 @@ where } } -// NOTE: we are testing `namada::ledger::queries_ext`, +// NOTE: we are testing `namada_sdk::queries_ext`, // which is not possible from `namada` since we do not have // access to the `Shell` there #[allow(clippy::cast_possible_truncation)] #[cfg(test)] mod test_queries { - use namada::core::storage::Epoch; - use namada::eth_bridge::storage::eth_bridge_queries::is_bridge_comptime_enabled; - use namada::ledger::pos::PosQueries; - use namada::proof_of_stake::storage::read_consensus_validator_set_addresses_with_stake; - use namada::proof_of_stake::types::WeightedValidator; - use namada::tendermint::abci::types::VoteInfo; + use namada_sdk::eth_bridge::storage::eth_bridge_queries::is_bridge_comptime_enabled; use namada_sdk::eth_bridge::SendValsetUpd; + use namada_sdk::proof_of_stake::storage::read_consensus_validator_set_addresses_with_stake; + use namada_sdk::proof_of_stake::types::WeightedValidator; + use namada_sdk::proof_of_stake::PosQueries; + use namada_sdk::storage::Epoch; + use namada_sdk::tendermint::abci::types::VoteInfo; use super::*; use crate::shell::test_utils::get_pkh_from_address; @@ -155,11 +160,11 @@ mod test_queries { Epoch::default(), ); let votes = vec![VoteInfo { - validator: namada::tendermint::abci::types::Validator { + validator: namada_sdk::tendermint::abci::types::Validator { address: pkh1.clone().into(), power: (u128::try_from(val1.bonded_stake).expect("Test failed") as u64).try_into().unwrap(), }, - sig_info: namada::tendermint::abci::types::BlockSignatureInfo::LegacySigned, + sig_info: namada_sdk::tendermint::abci::types::BlockSignatureInfo::LegacySigned, }]; let req = FinalizeBlock { proposer_address: pkh1.to_vec(), diff --git a/crates/node/src/shell/stats.rs b/crates/node/src/shell/stats.rs index 7bd198c6d69..4b088ee68bc 100644 --- a/crates/node/src/shell/stats.rs +++ b/crates/node/src/shell/stats.rs @@ -2,7 +2,7 @@ use std::fmt::Display; -use namada::core::collections::HashMap; +use namada_sdk::collections::HashMap; #[derive(Debug, Default, Clone)] pub struct InternalStats { diff --git a/crates/node/src/shell/testing/client.rs b/crates/node/src/shell/testing/client.rs index 037c390bd4b..f9921211ad5 100644 --- a/crates/node/src/shell/testing/client.rs +++ b/crates/node/src/shell/testing/client.rs @@ -1,12 +1,12 @@ use clap::Command as App; use eyre::Report; -use namada::io::Io; use namada_apps_lib::cli::api::{CliApi, CliClient}; use namada_apps_lib::cli::args::Global; use namada_apps_lib::cli::{ args, cmds, Cmd, Context, NamadaClient, NamadaRelayer, }; use namada_sdk::error::Error as SdkError; +use namada_sdk::io::Io; use super::node::MockNode; use crate::shell::testing::utils::{Bin, TestingIo}; diff --git a/crates/node/src/shell/testing/node.rs b/crates/node/src/shell/testing/node.rs index d01a750edb6..dc0db109467 100644 --- a/crates/node/src/shell/testing/node.rs +++ b/crates/node/src/shell/testing/node.rs @@ -9,38 +9,36 @@ use color_eyre::eyre::{Report, Result}; use data_encoding::HEXUPPER; use itertools::Either; use lazy_static::lazy_static; -use namada::address::Address; -use namada::control_flow::time::Duration; -use namada::core::collections::HashMap; -use namada::core::ethereum_events::EthereumEvent; -use namada::core::ethereum_structs; -use namada::core::hash::Hash; -use namada::core::key::tm_consensus_key_raw_hash; -use namada::core::storage::{BlockHeight, Epoch, Header}; -use namada::core::time::DateTimeUtc; -use namada::eth_bridge::oracle::config::Config as OracleConfig; -use namada::ledger::dry_run_tx; -use namada::ledger::events::log::dumb_queries; -use namada::ledger::queries::{ - EncodedResponseQuery, RequestCtx, RequestQuery, Router, RPC, -}; -use namada::proof_of_stake::pos_queries::PosQueries; -use namada::proof_of_stake::storage::{ +use namada_sdk::address::Address; +use namada_sdk::collections::HashMap; +use namada_sdk::control_flow::time::Duration; +use namada_sdk::eth_bridge::oracle::config::Config as OracleConfig; +use namada_sdk::ethereum_events::EthereumEvent; +use namada_sdk::ethereum_structs; +use namada_sdk::events::extend::Height as HeightAttr; +use namada_sdk::events::log::dumb_queries; +use namada_sdk::events::Event; +use namada_sdk::hash::Hash; +use namada_sdk::key::tm_consensus_key_raw_hash; +use namada_sdk::proof_of_stake::pos_queries::PosQueries; +use namada_sdk::proof_of_stake::storage::{ read_consensus_validator_set_addresses_with_stake, validator_consensus_key_handle, }; -use namada::proof_of_stake::types::WeightedValidator; -use namada::sdk::events::extend::Height as HeightAttr; -use namada::sdk::events::Event; -use namada::state::{ +use namada_sdk::proof_of_stake::types::WeightedValidator; +use namada_sdk::queries::{ + Client, EncodedResponseQuery, RequestCtx, RequestQuery, Router, RPC, +}; +use namada_sdk::state::{ LastBlock, Sha256Hasher, StorageRead, EPOCH_SWITCH_BLOCKS_DELAY, }; -use namada::tendermint::abci::response::Info; -use namada::tendermint::abci::types::VoteInfo; -use namada::tx::event::Code as CodeAttr; -use namada_sdk::queries::Client; +use namada_sdk::storage::{BlockHeight, Epoch, Header}; +use namada_sdk::tendermint::abci::response::Info; +use namada_sdk::tendermint::abci::types::VoteInfo; use namada_sdk::tendermint_proto::google::protobuf::Timestamp; +use namada_sdk::time::DateTimeUtc; use namada_sdk::tx::data::ResultCode; +use namada_sdk::tx::event::Code as CodeAttr; use regex::Regex; use tokio::sync::mpsc; @@ -63,7 +61,7 @@ use crate::shims::abcipp_shim_types::shim::request::{ FinalizeBlock, ProcessedTx, }; use crate::shims::abcipp_shim_types::shim::response::TxResult; -use crate::storage; +use crate::{dry_run_tx, storage}; /// Mock Ethereum oracle used for testing purposes. struct MockEthOracle { @@ -382,7 +380,7 @@ impl MockNode { pub fn next_masp_epoch(&mut self) -> Epoch { let masp_epoch_multiplier = - namada::parameters::read_masp_epoch_multiplier_parameter( + namada_sdk::parameters::read_masp_epoch_multiplier_parameter( &self.shell.lock().unwrap().state, ) .unwrap(); @@ -734,16 +732,23 @@ impl<'a> Client for &'a MockNode { prove, }; let borrowed = self.shell.lock().unwrap(); - let ctx = RequestCtx { - state: &borrowed.state, - event_log: borrowed.event_log(), - vp_wasm_cache: borrowed.vp_wasm_cache.read_only(), - tx_wasm_cache: borrowed.tx_wasm_cache.read_only(), - storage_read_past_height_limit: None, - }; if request.path == RPC.shell().dry_run_tx_path() { - dry_run_tx(ctx, &request) + dry_run_tx( + unsafe { + borrowed.state.read_only().with_static_temp_write_log() + }, + borrowed.vp_wasm_cache.read_only(), + borrowed.tx_wasm_cache.read_only(), + &request, + ) } else { + let ctx = RequestCtx { + state: &borrowed.state, + event_log: borrowed.event_log(), + vp_wasm_cache: borrowed.vp_wasm_cache.read_only(), + tx_wasm_cache: borrowed.tx_wasm_cache.read_only(), + storage_read_past_height_limit: None, + }; rpc.handle(ctx, &request) } .map_err(Report::new) @@ -811,10 +816,10 @@ impl<'a> Client for &'a MockNode { /// `/block_search`: search for blocks by BeginBlock and EndBlock events. async fn block_search( &self, - query: namada::tendermint_rpc::query::Query, + query: namada_sdk::tendermint_rpc::query::Query, _page: u32, _per_page: u8, - _order: namada::tendermint_rpc::Order, + _order: namada_sdk::tendermint_rpc::Order, ) -> Result { self.drive_mock_services_bg().await; @@ -834,10 +839,12 @@ impl<'a> Client for &'a MockNode { .map(block_search_response) .collect::>(); - Ok(namada::tendermint_rpc::endpoint::block_search::Response { - total_count: blocks.len() as u32, - blocks, - }) + Ok( + namada_sdk::tendermint_rpc::endpoint::block_search::Response { + total_count: blocks.len() as u32, + blocks, + }, + ) } /// `/block_results`: get ABCI results for a block at a particular height. @@ -846,7 +853,7 @@ impl<'a> Client for &'a MockNode { height: H, ) -> Result where - H: Into + Send, + H: Into + Send, { self.drive_mock_services_bg().await; let height = height.into(); @@ -870,7 +877,9 @@ impl<'a> Client for &'a MockNode { None } }) - .map(|event| namada::tendermint::abci::Event::from(event.clone())) + .map(|event| { + namada_sdk::tendermint::abci::Event::from(event.clone()) + }) .collect(); let has_events = !events.is_empty(); Ok(tendermint_rpc::endpoint::block_results::Response { @@ -881,7 +890,7 @@ impl<'a> Client for &'a MockNode { end_block_events: has_events.then_some(events), validator_updates: vec![], consensus_param_updates: None, - app_hash: namada::tendermint::hash::AppHash::default(), + app_hash: namada_sdk::tendermint::hash::AppHash::default(), }) } @@ -911,11 +920,11 @@ impl<'a> Client for &'a MockNode { /// `/tx_search`: search for transactions with their results. async fn tx_search( &self, - _query: namada::tendermint_rpc::query::Query, + _query: namada_sdk::tendermint_rpc::query::Query, _prove: bool, _page: u32, _per_page: u8, - _order: namada::tendermint_rpc::Order, + _order: namada_sdk::tendermint_rpc::Order, ) -> Result { // In the past, some cli commands for masp called this. However, these // commands are not currently supported, so we do not need to fill @@ -935,7 +944,7 @@ impl<'a> Client for &'a MockNode { /// Parse a Tendermint query. fn parse_tm_query( - query: namada::tendermint_rpc::query::Query, + query: namada_sdk::tendermint_rpc::query::Query, ) -> dumb_queries::QueryMatcher { const QUERY_PARSING_REGEX_STR: &str = r"^tm\.event='NewBlock' AND applied\.hash='([^']+)'$"; @@ -994,15 +1003,17 @@ where #[inline] fn block_search_response( encoded_event: EncodedEvent, -) -> namada::tendermint_rpc::endpoint::block::Response { - namada::tendermint_rpc::endpoint::block::Response { +) -> namada_sdk::tendermint_rpc::endpoint::block::Response { + namada_sdk::tendermint_rpc::endpoint::block::Response { block_id: Default::default(), - block: namada::tendermint_proto::types::Block { - header: Some(namada::tendermint_proto::types::Header { - version: Some(namada::tendermint_proto::version::Consensus { - block: 0, - app: 0, - }), + block: namada_sdk::tendermint_proto::types::Block { + header: Some(namada_sdk::tendermint_proto::types::Header { + version: Some( + namada_sdk::tendermint_proto::version::Consensus { + block: 0, + app: 0, + }, + ), chain_id: String::new(), // NB: this is the only field that matters to us, // everything else is junk @@ -1021,13 +1032,13 @@ fn block_search_response( }), data: Default::default(), evidence: Default::default(), - last_commit: Some(namada::tendermint_proto::types::Commit { + last_commit: Some(namada_sdk::tendermint_proto::types::Commit { height: encoded_event.0 as i64, round: 0, - block_id: Some(namada::tendermint_proto::types::BlockId { + block_id: Some(namada_sdk::tendermint_proto::types::BlockId { hash: vec![0u8; 32], part_set_header: Some( - namada::tendermint_proto::types::PartSetHeader { + namada_sdk::tendermint_proto::types::PartSetHeader { total: 1, hash: vec![1; 32], }, diff --git a/crates/node/src/shell/testing/utils.rs b/crates/node/src/shell/testing/utils.rs index 52485b9d24f..e64114c59a1 100644 --- a/crates/node/src/shell/testing/utils.rs +++ b/crates/node/src/shell/testing/utils.rs @@ -5,7 +5,7 @@ use std::pin::Pin; use std::task::{Context, Poll}; use lazy_static::lazy_static; -use namada::io::{prompt_aux, read_aux, Io}; +use namada_sdk::io::{prompt_aux, read_aux, Io}; use tempfile::tempdir; use tokio::io::{AsyncRead, ReadBuf}; diff --git a/crates/node/src/shell/utils.rs b/crates/node/src/shell/utils.rs index e34009956d7..f34773efa35 100644 --- a/crates/node/src/shell/utils.rs +++ b/crates/node/src/shell/utils.rs @@ -1,6 +1,6 @@ use borsh::BorshDeserialize; -use namada::core::storage::Key; -use namada::state::{self, StorageRead}; +use namada_sdk::state::{self, StorageRead}; +use namada_sdk::storage::Key; pub(super) fn force_read( storage: &S, diff --git a/crates/node/src/shell/vote_extensions.rs b/crates/node/src/shell/vote_extensions.rs index 705c6ade0af..6114ba9b7ab 100644 --- a/crates/node/src/shell/vote_extensions.rs +++ b/crates/node/src/shell/vote_extensions.rs @@ -5,12 +5,12 @@ pub mod eth_events; pub mod val_set_update; use drain_filter_polyfill::DrainFilter; -use namada::ethereum_bridge::protocol::transactions::bridge_pool_roots::sign_bridge_pool_root; -use namada::ethereum_bridge::protocol::transactions::ethereum_events::sign_ethereum_events; -use namada::ethereum_bridge::protocol::transactions::validator_set_update::sign_validator_set_update; -pub use namada::ethereum_bridge::protocol::validation::VoteExtensionError; -use namada::tx::Signed; -use namada::vote_ext::{ +use namada_sdk::eth_bridge::protocol::transactions::bridge_pool_roots::sign_bridge_pool_root; +use namada_sdk::eth_bridge::protocol::transactions::ethereum_events::sign_ethereum_events; +use namada_sdk::eth_bridge::protocol::transactions::validator_set_update::sign_validator_set_update; +pub use namada_sdk::eth_bridge::protocol::validation::VoteExtensionError; +use namada_sdk::tx::Signed; +use namada_vote_ext::{ bridge_pool_roots, ethereum_events, validator_set_update, VoteExtension, }; @@ -34,7 +34,7 @@ where ethereum_events: self.extend_vote_with_ethereum_events(), bridge_pool_root: self .extend_vote_with_bp_roots() - .map(namada::vote_ext::bridge_pool_roots::SignedVext), + .map(bridge_pool_roots::SignedVext), validator_set_update: self.extend_vote_with_valset_update(), } } @@ -176,9 +176,7 @@ pub fn iter_protocol_txs( } = ext; [ ethereum_events.map(|e| { - EthereumTxData::EthEventsVext( - namada::vote_ext::ethereum_events::SignedVext(e), - ) + EthereumTxData::EthEventsVext(ethereum_events::SignedVext(e)) }), bridge_pool_root.map(EthereumTxData::BridgePoolVext), validator_set_update.map(EthereumTxData::ValSetUpdateVext), diff --git a/crates/node/src/shell/vote_extensions/bridge_pool_vext.rs b/crates/node/src/shell/vote_extensions/bridge_pool_vext.rs index 59ced933743..a3b4bc52e68 100644 --- a/crates/node/src/shell/vote_extensions/bridge_pool_vext.rs +++ b/crates/node/src/shell/vote_extensions/bridge_pool_vext.rs @@ -54,29 +54,31 @@ where #[allow(clippy::cast_possible_truncation)] #[cfg(test)] mod test_bp_vote_extensions { - use namada::core::ethereum_events::Uint; - use namada::core::keccak::{keccak_hash, KeccakHash}; - use namada::core::key::*; - use namada::core::storage::BlockHeight; - use namada::core::token; - use namada::eth_bridge::storage::eth_bridge_queries::is_bridge_comptime_enabled; - use namada::ethereum_bridge::protocol::validation::bridge_pool_roots::validate_bp_roots_vext; - use namada::ethereum_bridge::storage::bridge_pool::get_key_from_hash; - use namada::ethereum_bridge::storage::eth_bridge_queries::EthBridgeQueries; - use namada::ledger::pos::PosQueries; - use namada::proof_of_stake::storage::{ + use namada_apps_lib::wallet::defaults::{bertha_address, bertha_keypair}; + use namada_sdk::eth_bridge::protocol::validation::bridge_pool_roots::validate_bp_roots_vext; + use namada_sdk::eth_bridge::storage::bridge_pool::get_key_from_hash; + use namada_sdk::eth_bridge::storage::eth_bridge_queries::{ + is_bridge_comptime_enabled, EthBridgeQueries, + }; + use namada_sdk::ethereum_events::Uint; + use namada_sdk::keccak::{keccak_hash, KeccakHash}; + use namada_sdk::key::*; + use namada_sdk::proof_of_stake::storage::{ consensus_validator_set_handle, read_consensus_validator_set_addresses_with_stake, }; - use namada::proof_of_stake::types::{ + use namada_sdk::proof_of_stake::types::{ Position as ValidatorPosition, WeightedValidator, }; - use namada::proof_of_stake::{become_validator, BecomeValidator, Epoch}; - use namada::state::StorageWrite; - use namada::tendermint::abci::types::VoteInfo; - use namada::tx::Signed; - use namada::vote_ext::bridge_pool_roots; - use namada_apps_lib::wallet::defaults::{bertha_address, bertha_keypair}; + use namada_sdk::proof_of_stake::{ + become_validator, BecomeValidator, Epoch, PosQueries, + }; + use namada_sdk::state::StorageWrite; + use namada_sdk::storage::BlockHeight; + use namada_sdk::tendermint::abci::types::VoteInfo; + use namada_sdk::token; + use namada_sdk::tx::Signed; + use namada_vote_ext::bridge_pool_roots; use crate::shell::test_utils::*; use crate::shims::abcipp_shim_types::shim::request::FinalizeBlock; diff --git a/crates/node/src/shell/vote_extensions/eth_events.rs b/crates/node/src/shell/vote_extensions/eth_events.rs index 6e39450389b..1c24ff50c60 100644 --- a/crates/node/src/shell/vote_extensions/eth_events.rs +++ b/crates/node/src/shell/vote_extensions/eth_events.rs @@ -2,8 +2,8 @@ use std::collections::BTreeMap; -use namada::vote_ext::ethereum_events::MultiSignedEthEvent; use namada_sdk::collections::HashMap; +use namada_vote_ext::ethereum_events::MultiSignedEthEvent; use super::*; @@ -137,26 +137,25 @@ where #[allow(clippy::cast_possible_truncation)] #[cfg(test)] mod test_vote_extensions { - use namada::core::address::testing::gen_established_address; - use namada::core::ethereum_events::{ + use namada_sdk::address::testing::gen_established_address; + use namada_sdk::eth_bridge::storage::bridge_pool; + use namada_sdk::eth_bridge::storage::eth_bridge_queries::is_bridge_comptime_enabled; + use namada_sdk::eth_bridge::EthBridgeQueries; + use namada_sdk::ethereum_events::{ EthAddress, EthereumEvent, TransferToEthereum, Uint, }; - use namada::core::hash::Hash; - use namada::core::key::*; - use namada::core::storage::{Epoch, InnerEthEventsQueue}; - use namada::eth_bridge::storage::bridge_pool; - use namada::eth_bridge::storage::eth_bridge_queries::is_bridge_comptime_enabled; - use namada::ledger::eth_bridge::EthBridgeQueries; - use namada::ledger::pos::PosQueries; - use namada::proof_of_stake::storage::{ + use namada_sdk::hash::Hash; + use namada_sdk::key::*; + use namada_sdk::proof_of_stake::storage::{ consensus_validator_set_handle, read_consensus_validator_set_addresses_with_stake, }; - use namada::proof_of_stake::types::WeightedValidator; - use namada::state::collections::lazy_map::{NestedSubKey, SubKey}; - use namada::tendermint::abci::types::VoteInfo; - use namada::vote_ext::ethereum_events; - use namada_sdk::storage::StorageWrite; + use namada_sdk::proof_of_stake::types::WeightedValidator; + use namada_sdk::proof_of_stake::PosQueries; + use namada_sdk::state::collections::lazy_map::{NestedSubKey, SubKey}; + use namada_sdk::storage::{Epoch, InnerEthEventsQueue, StorageWrite}; + use namada_sdk::tendermint::abci::types::VoteInfo; + use namada_vote_ext::ethereum_events; use super::validate_eth_events_vext; use crate::shell::test_utils::*; diff --git a/crates/node/src/shell/vote_extensions/val_set_update.rs b/crates/node/src/shell/vote_extensions/val_set_update.rs index ed87a89896f..1ddc923affb 100644 --- a/crates/node/src/shell/vote_extensions/val_set_update.rs +++ b/crates/node/src/shell/vote_extensions/val_set_update.rs @@ -1,7 +1,7 @@ //! Extend Tendermint votes with validator set updates, to be relayed to //! Namada's Ethereum bridge smart contracts. -use namada::core::collections::HashMap; +use namada_sdk::collections::HashMap; use super::*; @@ -110,20 +110,19 @@ where #[allow(clippy::cast_possible_truncation)] #[cfg(test)] mod test_vote_extensions { - use namada::core::key::RefTo; - use namada::eth_bridge::storage::eth_bridge_queries::is_bridge_comptime_enabled; - use namada::ledger::pos::PosQueries; - use namada::proof_of_stake::storage::{ + use namada_apps_lib::wallet; + use namada_sdk::eth_bridge::storage::eth_bridge_queries::is_bridge_comptime_enabled; + use namada_sdk::eth_bridge::EthBridgeQueries; + use namada_sdk::key::RefTo; + use namada_sdk::proof_of_stake::storage::{ consensus_validator_set_handle, read_consensus_validator_set_addresses_with_stake, }; - use namada::proof_of_stake::types::WeightedValidator; - use namada::proof_of_stake::Epoch; - use namada::state::collections::lazy_map::{NestedSubKey, SubKey}; - use namada::tendermint::abci::types::VoteInfo; - use namada::vote_ext::validator_set_update; - use namada_apps_lib::wallet; - use namada_sdk::eth_bridge::EthBridgeQueries; + use namada_sdk::proof_of_stake::types::WeightedValidator; + use namada_sdk::proof_of_stake::{Epoch, PosQueries}; + use namada_sdk::state::collections::lazy_map::{NestedSubKey, SubKey}; + use namada_sdk::tendermint::abci::types::VoteInfo; + use namada_vote_ext::validator_set_update; use super::validate_valset_upd_vext; use crate::shell::test_utils::{self, get_pkh_from_address}; diff --git a/crates/node/src/shims/abcipp_shim.rs b/crates/node/src/shims/abcipp_shim.rs index 1ba7b2c50f0..4d4f9d31883 100644 --- a/crates/node/src/shims/abcipp_shim.rs +++ b/crates/node/src/shims/abcipp_shim.rs @@ -4,13 +4,13 @@ use std::pin::Pin; use std::task::{Context, Poll}; use futures::future::FutureExt; -use namada::core::hash::Hash; -use namada::core::key::tm_raw_hash_to_string; -use namada::core::storage::BlockHeight; -use namada::proof_of_stake::storage::find_validator_by_raw_hash; -use namada::time::{DateTimeUtc, Utc}; -use namada::tx::data::hash_tx; +use namada_sdk::hash::Hash; +use namada_sdk::key::tm_raw_hash_to_string; use namada_sdk::migrations::ScheduledMigration; +use namada_sdk::proof_of_stake::storage::find_validator_by_raw_hash; +use namada_sdk::storage::BlockHeight; +use namada_sdk::time::{DateTimeUtc, Utc}; +use namada_sdk::tx::data::hash_tx; use tokio::sync::broadcast; use tokio::sync::mpsc::UnboundedSender; use tower::Service; diff --git a/crates/node/src/shims/abcipp_shim_types.rs b/crates/node/src/shims/abcipp_shim_types.rs index 6decadeb6ba..7add51fffde 100644 --- a/crates/node/src/shims/abcipp_shim_types.rs +++ b/crates/node/src/shims/abcipp_shim_types.rs @@ -150,9 +150,9 @@ pub mod shim { /// Custom types for request payloads pub mod request { - use namada::core::hash::Hash; - use namada::core::storage::Header; - use namada::core::time::DateTimeUtc; + use namada_sdk::hash::Hash; + use namada_sdk::storage::Header; + use namada_sdk::time::DateTimeUtc; use super::VoteInfo; use crate::facade::tendermint::abci::types::Misbehavior; @@ -202,7 +202,7 @@ pub mod shim { /// Custom types for response payloads pub mod response { - use namada::ledger::events::Event; + use namada_sdk::events::Event; pub use crate::facade::tendermint::v0_37::abci::response::{ PrepareProposal, ProcessProposal, diff --git a/crates/node/src/storage/mod.rs b/crates/node/src/storage/mod.rs index f86c40b2c43..dbbb57b772f 100644 --- a/crates/node/src/storage/mod.rs +++ b/crates/node/src/storage/mod.rs @@ -9,8 +9,7 @@ use arse_merkle_tree::blake2b::Blake2bHasher; use arse_merkle_tree::traits::Hasher; use arse_merkle_tree::H256; use blake2b_rs::{Blake2b, Blake2bBuilder}; -use namada::state::StorageHasher; -use namada_sdk::state::FullAccessState; +use namada_sdk::state::{FullAccessState, StorageHasher}; pub use rocksdb::RocksDBUpdateVisitor; #[derive(Default)] @@ -56,25 +55,25 @@ fn new_blake2b() -> Blake2b { mod tests { use borsh::BorshDeserialize; use itertools::Itertools; - use namada::core::chain::ChainId; - use namada::core::collections::HashMap; - use namada::core::ethereum_events::Uint; - use namada::core::hash::Hash; - use namada::core::keccak::KeccakHash; - use namada::core::storage::{BlockHeight, Key, KeySeg}; - use namada::core::time::DurationSecs; - use namada::core::{address, storage}; - use namada::eth_bridge::storage::proof::BridgePoolRootProof; - use namada::ibc::storage::is_ibc_key; - use namada::ledger::eth_bridge::storage::bridge_pool; - use namada::ledger::gas::STORAGE_ACCESS_GAS_PER_BYTE; - use namada::ledger::ibc::storage::{client_counter_key, ibc_key}; - use namada::ledger::parameters::{EpochDuration, Parameters}; - use namada::state::{self, StorageRead, StorageWrite, StoreType, DB}; - use namada::token::conversion::update_allowed_conversions; - use namada::{decode, encode, parameters}; + use namada_sdk::chain::ChainId; + use namada_sdk::collections::HashMap; + use namada_sdk::eth_bridge::storage::bridge_pool; + use namada_sdk::eth_bridge::storage::proof::BridgePoolRootProof; + use namada_sdk::ethereum_events::Uint; + use namada_sdk::gas::STORAGE_ACCESS_GAS_PER_BYTE; + use namada_sdk::hash::Hash; + use namada_sdk::ibc::storage::{client_counter_key, ibc_key, is_ibc_key}; + use namada_sdk::keccak::KeccakHash; + use namada_sdk::parameters::Parameters; use namada_sdk::state::merkle_tree::NO_DIFF_KEY_PREFIX; - use namada_sdk::state::StateRead; + use namada_sdk::state::{ + self, StateRead, StorageRead, StorageWrite, StoreType, DB, + }; + use namada_sdk::storage::{BlockHeight, Key, KeySeg}; + use namada_sdk::token::conversion::update_allowed_conversions; + use namada_sdk::{ + address, decode, encode, parameters, storage, validation, + }; use proptest::collection::vec; use proptest::prelude::*; use proptest::test_runner::Config; @@ -269,8 +268,9 @@ mod tests { let key = Key::validity_predicate(&addr); // not exist - let (vp, gas) = - state.validity_predicate(&addr).expect("VP load failed"); + let (vp, gas) = state + .validity_predicate::(&addr) + .expect("VP load failed"); assert_eq!(vp, None); assert_eq!(gas, (key.len() as u64) * STORAGE_ACCESS_GAS_PER_BYTE); @@ -279,8 +279,9 @@ mod tests { state.db_write(&key, vp1).expect("write failed"); // check - let (vp_code_hash, gas) = - state.validity_predicate(&addr).expect("VP load failed"); + let (vp_code_hash, gas) = state + .validity_predicate::(&addr) + .expect("VP load failed"); assert_eq!(vp_code_hash.expect("no VP"), vp1); assert_eq!( gas, @@ -318,7 +319,7 @@ mod tests { /// value, if any. fn test_read_with_height_aux( blocks_write_value: Vec, - ) -> namada::state::Result<()> { + ) -> namada_sdk::state::Result<()> { let db_path = TempDir::new().expect("Unable to create a temporary DB directory"); let mut state = PersistentState::open( @@ -412,7 +413,7 @@ mod tests { /// Test the restore of the merkle tree fn test_get_merkle_tree_aux( blocks_write_type: Vec, - ) -> namada::state::Result<()> { + ) -> namada_sdk::state::Result<()> { let db_path = TempDir::new().expect("Unable to create a temporary DB directory"); let mut state = PersistentState::open( diff --git a/crates/node/src/storage/rocksdb.rs b/crates/node/src/storage/rocksdb.rs index 36a527fa181..76bc8d908fb 100644 --- a/crates/node/src/storage/rocksdb.rs +++ b/crates/node/src/storage/rocksdb.rs @@ -53,26 +53,25 @@ use std::sync::Mutex; use borsh::{BorshDeserialize, BorshSerialize}; use data_encoding::HEXLOWER; use itertools::Either; -use namada::core::collections::HashSet; -use namada::core::storage::{BlockHeight, Epoch, Header, Key, KeySeg}; -use namada::core::{decode, encode, ethereum_events}; -use namada::eth_bridge::storage::proof::BridgePoolRootProof; -use namada::ledger::eth_bridge::storage::bridge_pool; -use namada::replay_protection; -use namada::state::merkle_tree::{ +use namada_replay_protection as replay_protection; +use namada_sdk::arith::checked; +use namada_sdk::collections::HashSet; +use namada_sdk::eth_bridge::storage::bridge_pool; +use namada_sdk::eth_bridge::storage::proof::BridgePoolRootProof; +use namada_sdk::migrations::{DBUpdateVisitor, DbUpdateType}; +use namada_sdk::state::merkle_tree::{ tree_key_prefix_with_epoch, tree_key_prefix_with_height, }; -use namada::state::{ +use namada_sdk::state::{ BlockStateRead, BlockStateWrite, DBIter, DBWriteBatch, DbError as Error, DbResult as Result, MerkleTreeStoresRead, PatternIterator, PrefixIterator, StoreType, DB, }; -use namada::storage::{ - DbColFam, BLOCK_CF, DIFFS_CF, REPLAY_PROTECTION_CF, ROLLBACK_CF, STATE_CF, - SUBSPACE_CF, +use namada_sdk::storage::{ + BlockHeight, DbColFam, Epoch, Header, Key, KeySeg, BLOCK_CF, DIFFS_CF, + REPLAY_PROTECTION_CF, ROLLBACK_CF, STATE_CF, SUBSPACE_CF, }; -use namada_sdk::arith::checked; -use namada_sdk::migrations::{DBUpdateVisitor, DbUpdateType}; +use namada_sdk::{decode, encode, ethereum_events}; use rayon::prelude::*; use regex::Regex; use rocksdb::{ @@ -1003,7 +1002,7 @@ impl DB for RocksDB { fn has_replay_protection_entry( &self, - hash: &namada::core::hash::Hash, + hash: &namada_sdk::hash::Hash, ) -> Result { let replay_protection_cf = self.get_column_family(REPLAY_PROTECTION_CF)?; @@ -1299,7 +1298,7 @@ impl DB for RocksDB { stripped_prefix.as_ref(), None, ) { - let hash = namada::core::hash::Hash::from_str(hash_str) + let hash = namada_sdk::hash::Hash::from_str(hash_str) .expect("Failed hash conversion"); let current_key = replay_protection::current_key(&hash); let key = replay_protection::key(&hash); @@ -1819,14 +1818,13 @@ mod imp { #[allow(clippy::arithmetic_side_effects)] #[cfg(test)] mod test { - use namada::address::EstablishedAddressGen; - use namada::core::hash::Hash; - use namada::core::storage::Epochs; - use namada::ledger::storage::ConversionState; - use namada::state::{MerkleTree, Sha256Hasher}; - use namada::storage::{BlockResults, EthEventsQueue}; - use namada::time::DateTimeUtc; + use namada_sdk::address::EstablishedAddressGen; + use namada_sdk::hash::Hash; + use namada_sdk::state::{MerkleTree, Sha256Hasher}; + use namada_sdk::storage::conversion_state::ConversionState; use namada_sdk::storage::types::CommitOnlyData; + use namada_sdk::storage::{BlockResults, Epochs, EthEventsQueue}; + use namada_sdk::time::DateTimeUtc; use tempfile::tempdir; use test_log::test; diff --git a/crates/node/src/tendermint_node.rs b/crates/node/src/tendermint_node.rs index b0a4164ba8b..04c6e420bfe 100644 --- a/crates/node/src/tendermint_node.rs +++ b/crates/node/src/tendermint_node.rs @@ -3,12 +3,12 @@ use std::path::{Path, PathBuf}; use std::process::Stdio; use std::str::FromStr; -use namada::core::chain::{ChainId, ProposalBytes}; -use namada::core::storage::BlockHeight; -use namada::core::time::DateTimeUtc; use namada_apps_lib::cli::namada_version; use namada_apps_lib::config; pub use namada_apps_lib::tendermint_node::*; +use namada_sdk::chain::{ChainId, ProposalBytes}; +use namada_sdk::storage::BlockHeight; +use namada_sdk::time::DateTimeUtc; use thiserror::Error; use tokio::fs::{File, OpenOptions}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; diff --git a/crates/parameters/src/vp.rs b/crates/parameters/src/vp.rs index 4b7c76af7d2..ae948fab08a 100644 --- a/crates/parameters/src/vp.rs +++ b/crates/parameters/src/vp.rs @@ -27,31 +27,32 @@ pub enum Error { pub type Result = std::result::Result; /// Parameters VP -pub struct ParametersVp<'a, S, CA, EVAL, Gov> +pub struct ParametersVp<'ctx, S, CA, EVAL, Gov> where S: 'static + StateRead, - EVAL: VpEvaluator<'a, S, CA, EVAL>, + EVAL: VpEvaluator<'ctx, S, CA, EVAL>, { /// Context to interact with the host structures. - pub ctx: Ctx<'a, S, CA, EVAL>, + pub ctx: Ctx<'ctx, S, CA, EVAL>, /// Governance type pub gov: PhantomData, } -impl<'a, S, CA, EVAL, Gov> NativeVp<'a> for ParametersVp<'a, S, CA, EVAL, Gov> +impl<'view, 'ctx: 'view, S, CA, EVAL, Gov> NativeVp<'view> + for ParametersVp<'ctx, S, CA, EVAL, Gov> where S: 'static + StateRead, CA: 'static + Clone, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, Gov: governance::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, { type Error = Error; fn validate_tx( - &'a self, + &'view self, batched_tx: &BatchedTxRef<'_>, keys_changed: &BTreeSet, _verifiers: &BTreeSet
, @@ -86,6 +87,25 @@ where } } +impl<'ctx, S, CA, EVAL, Gov> ParametersVp<'ctx, S, CA, EVAL, Gov> +where + S: 'static + StateRead, + CA: 'static + Clone, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, + Gov: governance::Read< + CtxPreStorageRead<'ctx, 'ctx, S, CA, EVAL>, + Err = StorageError, + >, +{ + /// Instantiate parameters VP + pub fn new(ctx: Ctx<'ctx, S, CA, EVAL>) -> Self { + Self { + ctx, + gov: PhantomData, + } + } +} + #[allow(clippy::upper_case_acronyms)] enum KeyType { #[allow(clippy::upper_case_acronyms)] diff --git a/crates/proof_of_stake/src/lib.rs b/crates/proof_of_stake/src/lib.rs index 7cb1b3c43c3..65ca763515c 100644 --- a/crates/proof_of_stake/src/lib.rs +++ b/crates/proof_of_stake/src/lib.rs @@ -44,7 +44,7 @@ pub use error::*; use namada_core::address::{Address, InternalAddress}; use namada_core::arith::checked; use namada_core::collections::HashSet; -use namada_core::dec::Dec; +pub use namada_core::dec::Dec; use namada_core::key::common; use namada_core::storage::BlockHeight; pub use namada_core::storage::{Epoch, Key, KeySeg}; @@ -54,7 +54,9 @@ use namada_storage::collections::lazy_map::{self, Collectable, LazyMap}; use namada_storage::{OptionExt, StorageRead, StorageWrite}; pub use namada_trans_token as token; pub use parameters::{OwnedPosParams, PosParams}; +pub use pos_queries::PosQueries; use storage::write_validator_name; +pub use types::GenesisValidator; use types::{into_tm_voting_power, DelegationEpochs}; use crate::queries::{find_bonds, has_bonds}; diff --git a/crates/proof_of_stake/src/vp.rs b/crates/proof_of_stake/src/vp.rs index 9bc67f27d00..3289e1716e5 100644 --- a/crates/proof_of_stake/src/vp.rs +++ b/crates/proof_of_stake/src/vp.rs @@ -37,31 +37,32 @@ pub enum Error { pub type Result = std::result::Result; /// Proof-of-Stake validity predicate -pub struct PosVP<'a, S, CA, EVAL, Gov> +pub struct PosVp<'ctx, S, CA, EVAL, Gov> where - S: 'static + StateRead, - EVAL: VpEvaluator<'a, S, CA, EVAL>, + S: StateRead, + EVAL: VpEvaluator<'ctx, S, CA, EVAL>, { /// Context to interact with the host structures. - pub ctx: Ctx<'a, S, CA, EVAL>, + pub ctx: Ctx<'ctx, S, CA, EVAL>, /// Governance type pub gov: PhantomData, } -impl<'a, S, CA, EVAL, Gov> NativeVp<'a> for PosVP<'a, S, CA, EVAL, Gov> +impl<'view, 'ctx: 'view, S, CA, EVAL, Gov> NativeVp<'view> + for PosVp<'ctx, S, CA, EVAL, Gov> where - S: 'static + StateRead, + S: StateRead, CA: 'static + Clone, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, Gov: governance::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, { type Error = Error; fn validate_tx( - &'a self, + &'view self, batched_tx: &BatchedTxRef<'_>, keys_changed: &BTreeSet, verifiers: &BTreeSet
, @@ -316,14 +317,14 @@ where } } -impl<'a, S, CA, EVAL, Gov> PosVP<'a, S, CA, EVAL, Gov> +impl<'ctx, S, CA, EVAL, Gov> PosVp<'ctx, S, CA, EVAL, Gov> where - S: 'static + StateRead, + S: StateRead, CA: 'static + Clone, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, { /// Instantiate a `PosVP`. - pub fn new(ctx: Ctx<'a, S, CA, EVAL>) -> Self { + pub fn new(ctx: Ctx<'ctx, S, CA, EVAL>) -> Self { Self { ctx, gov: PhantomData, @@ -332,10 +333,11 @@ where /// Return `Ok` if the changed parameters are valid fn is_valid_parameter_change(&self) -> Result<()> { - let validation_errors = read_pos_params(&self.ctx.post()) - .map_err(Error::NativeVpError)? - .owned - .validate(); + let validation_errors: Vec = + read_pos_params(&self.ctx.post()) + .map_err(Error::NativeVpError)? + .owned + .validate(); validation_errors.is_empty().ok_or_else(|| { let validation_errors_str = itertools::join(validation_errors, ", "); diff --git a/crates/sdk/Cargo.toml b/crates/sdk/Cargo.toml index d1632ffe97a..b7b9d2225d9 100644 --- a/crates/sdk/Cargo.toml +++ b/crates/sdk/Cargo.toml @@ -15,26 +15,14 @@ version.workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [features] -default = ["tendermint-rpc", "std", "rand", "migrations"] - +default = ["std"] mainnet = ["namada_core/mainnet", "namada_events/mainnet"] - -multicore = ["masp_proofs/multicore"] - -namada-sdk = ["tendermint-rpc", "masp_primitives/transparent-inputs"] - +multicore = ["masp_proofs/multicore", "namada_token/multicore"] std = ["fd-lock", "download-params"] -rand = ["dep:rand", "rand_core", "namada_core/rand"] - -# tendermint-rpc support -tendermint-rpc = ["async-client", "dep:tendermint-rpc"] - -# Enable queries support for an async client -async-client = ["async-trait"] - async-send = [] - namada-eth-bridge = ["namada_ethereum_bridge/namada-eth-bridge"] +benches = ["namada_core/benches", "namada_core/testing", "namada_state/benches"] +wasm-runtime = ["namada_vm/wasm-runtime"] # for integration tests and test utilities testing = [ @@ -44,11 +32,11 @@ testing = [ "namada_ethereum_bridge/testing", "namada_governance/testing", "namada_ibc/testing", + "namada_parameters/testing", "namada_proof_of_stake/testing", "namada_storage/testing", "namada_token/testing", "namada_tx/testing", - "async-client", "proptest", "jubjub", ] @@ -72,7 +60,7 @@ migrations = [ [dependencies] namada_account = { path = "../account" } -namada_core = { path = "../core" } +namada_core = { path = "../core", features = ["control_flow", "rand"] } namada_ethereum_bridge = { path = "../ethereum_bridge", default-features = false } namada_events = { path = "../events" } namada_gas = { path = "../gas" } @@ -86,9 +74,11 @@ namada_state = { path = "../state" } namada_storage = { path = "../storage" } namada_token = { path = "../token" } namada_tx = { path = "../tx" } +namada_vm = { path = "../vm", default-features = false } namada_vote_ext = { path = "../vote_ext" } +namada_vp = { path = "../vp" } -async-trait = { workspace = true, optional = true } +async-trait.workspace = true bimap.workspace = true borsh.workspace = true borsh-ext.workspace = true @@ -115,8 +105,8 @@ paste.workspace = true patricia_tree.workspace = true proptest = { workspace = true, optional = true } prost.workspace = true -rand = { workspace = true, optional = true } -rand_core = { workspace = true, optional = true } +rand.workspace = true +rand_core.workspace = true regex.workspace = true ripemd.workspace = true serde.workspace = true @@ -124,7 +114,7 @@ serde_json.workspace = true sha2.workspace = true slip10_ed25519.workspace = true smooth-operator.workspace = true -tendermint-rpc = { workspace = true, optional = true } +tendermint-rpc.workspace = true thiserror.workspace = true tiny-bip39.workspace = true tiny-hderive.workspace = true @@ -137,7 +127,6 @@ tokio = { workspace = true, features = ["full"] } [target.'cfg(target_family = "wasm")'.dependencies] tokio = { workspace = true, default-features = false, features = ["sync"] } -wasmtimer = "0.2.0" [dev-dependencies] namada_account = { path = "../account", features = ["testing"]} @@ -159,7 +148,9 @@ namada_storage = { path = "../storage", features = ["testing"] } namada_test_utils = { path = "../test_utils" } namada_token = { path = "../token", features = ["testing"] } namada_tx = { path = "../tx", features = ["testing"]} -namada_vote_ext = {path = "../vote_ext"} +namada_vm = { path = "../vm" } +namada_vote_ext = { path = "../vote_ext" } +namada_vp = { path = "../vp" } assert_matches.workspace = true base58.workspace = true diff --git a/crates/sdk/src/lib.rs b/crates/sdk/src/lib.rs index 1ebc5676dc8..bf0c0023ed7 100644 --- a/crates/sdk/src/lib.rs +++ b/crates/sdk/src/lib.rs @@ -15,13 +15,12 @@ extern crate alloc; pub use namada_core::*; -#[cfg(feature = "tendermint-rpc")] -pub use tendermint_rpc; pub use { bip39, masp_primitives, masp_proofs, namada_account as account, - namada_gas as gas, namada_governance as governance, - namada_proof_of_stake as proof_of_stake, namada_state as state, - namada_storage as storage, namada_token as token, zeroize, + namada_gas as gas, namada_governance as governance, namada_ibc as ibc, + namada_parameters as parameters, namada_proof_of_stake as proof_of_stake, + namada_state as state, namada_storage as storage, namada_token as token, + tendermint_rpc, zeroize, }; pub mod eth_bridge; @@ -33,13 +32,14 @@ pub mod masp; pub mod signing; #[allow(clippy::result_large_err)] pub mod tx; -#[cfg(any(test, feature = "testing", feature = "validation"))] +#[cfg(feature = "wasm-runtime")] pub mod validation; pub mod error; pub mod events; pub(crate) mod internal_macros; pub mod io; +#[cfg(feature = "migrations")] pub mod migrations; pub mod queries; pub mod wallet; diff --git a/crates/sdk/src/masp.rs b/crates/sdk/src/masp.rs index fb84c0a7373..1f02cf3b805 100644 --- a/crates/sdk/src/masp.rs +++ b/crates/sdk/src/masp.rs @@ -33,16 +33,14 @@ use masp_primitives::transaction::fees::fixed::FeeRule; use masp_primitives::transaction::{ Authorization, Authorized, Transaction, TransparentAddress, }; -use masp_primitives::zip32::{ExtendedFullViewingKey, ExtendedSpendingKey}; +use masp_primitives::zip32::{ + ExtendedFullViewingKey, ExtendedSpendingKey as MaspExtendedSpendingKey, +}; use masp_proofs::prover::LocalTxProver; use namada_core::address::Address; use namada_core::collections::{HashMap, HashSet}; use namada_core::dec::Dec; -pub use namada_core::masp::{ - encode_asset_type, AssetData, BalanceOwner, ExtendedViewingKey, - PaymentAddress, TransferSource, TransferTarget, -}; -use namada_core::masp::{MaspEpoch, MaspTxRefs}; +pub use namada_core::masp::*; use namada_core::storage::{BlockHeight, TxIndex}; use namada_core::time::{DateTimeUtc, DurationSecs}; use namada_core::uint::Uint; @@ -53,7 +51,6 @@ use namada_events::extend::{ use namada_macros::BorshDeserializer; #[cfg(feature = "migrations")] use namada_migrations::*; -#[cfg(feature = "validation")] pub use namada_token::validation::{ partial_deauthorize, preload_verifying_keys, PVKs, CONVERT_NAME, ENV_VAR_MASP_PARAMS_DIR, OUTPUT_NAME, SPEND_NAME, @@ -128,20 +125,20 @@ struct WalletMap; impl masp_primitives::transaction::components::sapling::builder::MapBuilder< P1, - ExtendedSpendingKey, + MaspExtendedSpendingKey, (), ExtendedFullViewingKey, > for WalletMap { fn map_params(&self, _s: P1) {} - fn map_key(&self, s: ExtendedSpendingKey) -> ExtendedFullViewingKey { + fn map_key(&self, s: MaspExtendedSpendingKey) -> ExtendedFullViewingKey { (&s).into() } } impl - MapBuilder + MapBuilder for WalletMap { fn map_notifier(&self, _s: N1) {} @@ -172,7 +169,7 @@ pub trait ShieldedUtils: } /// Make a ViewingKey that can view notes encrypted by given ExtendedSpendingKey -pub fn to_viewing_key(esk: &ExtendedSpendingKey) -> FullViewingKey { +pub fn to_viewing_key(esk: &MaspExtendedSpendingKey) -> FullViewingKey { ExtendedFullViewingKey::from(esk).fvk } @@ -417,7 +414,7 @@ impl ShieldedContext { // NOTE: do not remove this argument, it will be used once the indexer // is ready _batch_size: u64, - sks: &[ExtendedSpendingKey], + sks: &[MaspExtendedSpendingKey], fvks: &[ViewingKey], ) -> Result<(), Error> { // add new viewing keys @@ -1271,7 +1268,7 @@ impl ShieldedContext { #[allow(unused_mut)] let mut rng = StdRng::from_rng(OsRng).unwrap(); #[cfg(feature = "testing")] - let mut rng = if let Ok(seed) = env::var(ENV_VAR_MASP_TEST_SEED) + let mut rng = if let Ok(seed) = std::env::var(ENV_VAR_MASP_TEST_SEED) .map_err(|e| Error::Other(e.to_string())) .and_then(|seed| { let exp_str = @@ -2183,7 +2180,7 @@ pub mod testing { ) -> (Option, masp_primitives::sapling::PaymentAddress, AssetType, u64, MemoBytes) { let mut spending_key_seed = [0; 32]; rng.fill_bytes(&mut spending_key_seed); - let spending_key = masp_primitives::zip32::ExtendedSpendingKey::master(spending_key_seed.as_ref()); + let spending_key = MaspExtendedSpendingKey::master(spending_key_seed.as_ref()); let viewing_key = ExtendedFullViewingKey::from(&spending_key).fvk.vk; let (div, _g_d) = find_valid_diversifier(&mut rng); @@ -2206,10 +2203,10 @@ pub mod testing { mut rng in arb_rng().prop_map(TestCsprng), bparams_rng in arb_rng().prop_map(TestCsprng), prover_rng in arb_rng().prop_map(TestCsprng), - ) -> (ExtendedSpendingKey, Diversifier, Note, Node) { + ) -> (MaspExtendedSpendingKey, Diversifier, Note, Node) { let mut spending_key_seed = [0; 32]; rng.fill_bytes(&mut spending_key_seed); - let spending_key = masp_primitives::zip32::ExtendedSpendingKey::master(spending_key_seed.as_ref()); + let spending_key = MaspExtendedSpendingKey::master(spending_key_seed.as_ref()); let viewing_key = ExtendedFullViewingKey::from(&spending_key).fvk.vk; let (div, _g_d) = find_valid_diversifier(&mut rng); @@ -2301,7 +2298,7 @@ pub mod testing { ).unwrap(), *value, )).collect::>() - ) -> Vec<(ExtendedSpendingKey, Diversifier, Note, Node)> { + ) -> Vec<(MaspExtendedSpendingKey, Diversifier, Note, Node)> { spend_description } } @@ -2608,7 +2605,7 @@ pub mod testing { } } -#[cfg(all(feature = "std", feature = "validation"))] +#[cfg(feature = "std")] /// Implementation of MASP functionality depending on a standard filesystem pub mod fs { use std::env; diff --git a/crates/sdk/src/migrations.rs b/crates/sdk/src/migrations.rs index df284242389..b66a111f4ef 100644 --- a/crates/sdk/src/migrations.rs +++ b/crates/sdk/src/migrations.rs @@ -1,10 +1,6 @@ #![allow(missing_docs)] -#[cfg(not(feature = "migrations"))] -use core::fmt::Formatter; -#[cfg(feature = "migrations")] use core::fmt::{Display, Formatter}; -#[cfg(feature = "migrations")] use core::str::FromStr; use std::marker::PhantomData; use std::path::{Path, PathBuf}; @@ -15,20 +11,13 @@ use data_encoding::HEXUPPER; use eyre::eyre; use namada_core::hash::Hash; use namada_core::storage::{BlockHeight, Key}; -#[cfg(feature = "migrations")] -use namada_macros::derive_borshdeserializer; -#[cfg(feature = "migrations")] -use namada_macros::typehash; -#[cfg(feature = "migrations")] -use namada_migrations::TypeHash; -#[cfg(feature = "migrations")] -use namada_migrations::*; +use namada_macros::{derive_borshdeserializer, typehash}; +use namada_migrations::{TypeHash, *}; use namada_storage::{DbColFam, DbMigration, DB}; use regex::Regex; use serde::de::{DeserializeOwned, Error, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -#[cfg(feature = "migrations")] /// The maximum number of character printed per value. const PRINTLN_CUTOFF: usize = 300; @@ -58,7 +47,6 @@ pub struct UpdateValue { bytes: UpdateBytes, } -#[cfg(feature = "migrations")] impl UpdateValue { /// Using a type that is a thin wrapper around bytes but with a custom /// serialization when we don't want to use Borsh necessarily @@ -119,7 +107,6 @@ impl UpdateValue { } } -#[cfg(feature = "migrations")] impl From for UpdateValue { fn from(value: T) -> Self { Self { @@ -196,7 +183,6 @@ pub enum DbUpdateType { impl DbMigration for DbUpdateType {} -#[cfg(feature = "migrations")] impl DbUpdateType { /// Get the key or pattern being modified as string pub fn pattern(&self) -> String { @@ -432,7 +418,6 @@ impl IntoIterator for DbChanges { self.changes.into_iter() } } -#[cfg(feature = "migrations")] impl Display for DbUpdateType { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { match self { @@ -484,7 +469,6 @@ pub enum UpdateStatus { Add(Vec<(String, String)>), } -#[cfg(feature = "migrations")] impl Display for UpdateStatus { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { match self { @@ -543,18 +527,14 @@ pub fn commit( } } -#[cfg(feature = "migrations")] derive_borshdeserializer!(Vec::); -#[cfg(feature = "migrations")] derive_borshdeserializer!(Vec::); -#[cfg(feature = "migrations")] derive_borshdeserializer!(u64); #[derive(BorshSerialize, BorshDeserialize)] #[repr(transparent)] pub struct SerializeWrapper(T); -#[cfg(feature = "migrations")] impl TypeHash for SerializeWrapper< std::collections::BTreeMap, @@ -564,7 +544,6 @@ impl TypeHash typehash!(SerializeWrapper>); } -#[cfg(feature = "migrations")] #[distributed_slice(REGISTER_DESERIALIZERS)] static BTREEMAP_STRING_ADDRESS: fn() = || { use std::collections::BTreeMap; diff --git a/crates/sdk/src/queries/mod.rs b/crates/sdk/src/queries/mod.rs index eb6232cf71b..16f5138f8d7 100644 --- a/crates/sdk/src/queries/mod.rs +++ b/crates/sdk/src/queries/mod.rs @@ -209,7 +209,6 @@ use crate::tendermint::block::Height; /// A client with async request dispatcher method, which can be used to invoke /// type-safe methods from a root [`Router`], generated /// via `router!` macro. -#[cfg(any(test, feature = "async-client"))] #[cfg_attr(feature = "async-send", async_trait::async_trait)] #[cfg_attr(not(feature = "async-send"), async_trait::async_trait(?Send))] pub trait Client { diff --git a/crates/sdk/src/queries/router.rs b/crates/sdk/src/queries/router.rs index ec2e5fe3d80..43e109849b0 100644 --- a/crates/sdk/src/queries/router.rs +++ b/crates/sdk/src/queries/router.rs @@ -398,7 +398,6 @@ macro_rules! pattern_and_handler_to_method { #[allow(dead_code)] #[allow(clippy::too_many_arguments)] - #[cfg(any(test, feature = "async-client"))] #[doc = "Request value with optional data (used for e.g. \ `dry_run_tx`), optionally specified height (supported for \ `storage_value`) and optional proof (supported for \ @@ -451,7 +450,6 @@ macro_rules! pattern_and_handler_to_method { #[allow(dead_code)] #[allow(clippy::too_many_arguments)] - #[cfg(any(test, feature = "async-client"))] #[doc = "Request value with optional data (used for e.g. \ `dry_run_tx`), optionally specified height (supported for \ `storage_value`) and optional proof (supported for \ @@ -507,7 +505,6 @@ macro_rules! pattern_and_handler_to_method { #[allow(dead_code)] #[allow(clippy::too_many_arguments)] - #[cfg(any(test, feature = "async-client"))] #[doc = "Request a simple borsh-encoded value from `" $handle "`, \ without any additional request data, specified block height or \ proof."] @@ -729,7 +726,7 @@ macro_rules! router_type { /// Compile time tree patterns router with type-safe dynamic parameter parsing, /// automatic routing, type-safe path constructors and optional client query -/// methods (enabled with `feature = "async-client"`). +/// methods. /// /// The `router!` macro implements greedy matching algorithm. /// diff --git a/crates/sdk/src/queries/shell.rs b/crates/sdk/src/queries/shell.rs index 071939bdd2f..e112ad938f0 100644 --- a/crates/sdk/src/queries/shell.rs +++ b/crates/sdk/src/queries/shell.rs @@ -23,7 +23,6 @@ use namada_ibc::event::IbcEventType; use namada_state::{DBIter, LastBlock, StateRead, StorageHasher, DB}; use namada_storage::{ResultExt, StorageRead}; use namada_token::storage_key::masp_token_map_key; -#[cfg(any(test, feature = "async-client"))] use namada_tx::data::TxResult; use self::eth_bridge::{EthBridge, ETH_BRIDGE}; diff --git a/crates/sdk/src/queries/vp/pos.rs b/crates/sdk/src/queries/vp/pos.rs index 96db66e559c..7b868455632 100644 --- a/crates/sdk/src/queries/vp/pos.rs +++ b/crates/sdk/src/queries/vp/pos.rs @@ -679,7 +679,6 @@ where } /// Client-only methods for the router type are composed from router functions. -#[cfg(any(test, feature = "async-client"))] pub mod client_only_methods { use super::*; use crate::queries::{Client, RPC}; diff --git a/crates/sdk/src/queries/vp/token.rs b/crates/sdk/src/queries/vp/token.rs index 18e994ebc93..aa749d147d6 100644 --- a/crates/sdk/src/queries/vp/token.rs +++ b/crates/sdk/src/queries/vp/token.rs @@ -44,7 +44,6 @@ where } } -#[cfg(any(test, feature = "async-client"))] pub mod client_only_methods { use borsh::BorshDeserialize; use namada_core::address::Address; diff --git a/crates/shielded_token/Cargo.toml b/crates/shielded_token/Cargo.toml index 470eecf480a..a361bfaa9c7 100644 --- a/crates/shielded_token/Cargo.toml +++ b/crates/shielded_token/Cargo.toml @@ -17,7 +17,6 @@ default = [] multicore = ["dep:rayon"] testing = [ "multicore", - "validation", "namada_core/testing", "masp_primitives/test-dependencies", ] diff --git a/crates/shielded_token/src/lib.rs b/crates/shielded_token/src/lib.rs index 386dfa503fb..3a1450d9a6a 100644 --- a/crates/shielded_token/src/lib.rs +++ b/crates/shielded_token/src/lib.rs @@ -22,7 +22,6 @@ mod storage; pub mod storage_key; pub mod utils; pub mod validation; -#[cfg(any(test, feature = "validation", feature = "testing"))] pub mod vp; use std::str::FromStr; diff --git a/crates/shielded_token/src/vp.rs b/crates/shielded_token/src/vp.rs index 9a64855e605..a05e6ebd4f0 100644 --- a/crates/shielded_token/src/vp.rs +++ b/crates/shielded_token/src/vp.rs @@ -57,13 +57,13 @@ pub enum Error { pub type Result = std::result::Result; /// MASP VP -pub struct MaspVp<'a, S, CA, EVAL, Params, Gov> +pub struct MaspVp<'ctx, S, CA, EVAL, Params, Gov> where S: 'static + StateRead, - EVAL: VpEvaluator<'a, S, CA, EVAL>, + EVAL: VpEvaluator<'ctx, S, CA, EVAL>, { /// Context to interact with the host structures. - pub ctx: Ctx<'a, S, CA, EVAL>, + pub ctx: Ctx<'ctx, S, CA, EVAL>, /// Governance type pub gov: PhantomData, /// Parameters type @@ -83,23 +83,33 @@ struct ChangedBalances { post: BTreeMap>, } -impl<'a, S, CA, EVAL, Params, Gov> MaspVp<'a, S, CA, EVAL, Params, Gov> +impl<'view, 'ctx: 'view, S, CA, EVAL, Params, Gov> + MaspVp<'ctx, S, CA, EVAL, Params, Gov> where S: 'static + StateRead, CA: 'static + Clone, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, Params: parameters::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, Gov: governance::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, { + /// Instantiate MASP VP + pub fn new(ctx: Ctx<'ctx, S, CA, EVAL>) -> Self { + Self { + ctx, + params: PhantomData, + gov: PhantomData, + } + } + /// Return if the parameter change was done via a governance proposal pub fn is_valid_parameter_change( - &'a self, + &'view self, tx: &BatchedTxRef<'_>, ) -> Result<()> { tx.tx.data(tx.cmt).map_or_else( @@ -259,7 +269,7 @@ where // Check that the convert descriptions anchors of a transaction are valid fn valid_convert_descriptions_anchor( - &'a self, + &'view self, transaction: &Transaction, ) -> Result<()> { if let Some(bundle) = transaction.sapling_bundle() { @@ -358,7 +368,7 @@ where // Check that MASP Transaction and state changes are valid fn is_valid_masp_transfer( - &'a self, + &'view self, tx_data: &BatchedTxRef<'_>, keys_changed: &BTreeSet, ) -> Result<()> { @@ -843,25 +853,25 @@ fn verify_sapling_balancing_value( } } -impl<'a, S, CA, EVAL, Params, Gov> NativeVp<'a> - for MaspVp<'a, S, CA, EVAL, Params, Gov> +impl<'view, 'ctx: 'view, S, CA, EVAL, Params, Gov> NativeVp<'view> + for MaspVp<'ctx, S, CA, EVAL, Params, Gov> where S: 'static + StateRead, CA: 'static + Clone, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, Params: parameters::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, Gov: governance::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, { type Error = Error; fn validate_tx( - &'a self, + &'view self, tx_data: &BatchedTxRef<'_>, keys_changed: &BTreeSet, _verifiers: &BTreeSet
, diff --git a/crates/state/src/lib.rs b/crates/state/src/lib.rs index 05ddc023e66..57c265794fa 100644 --- a/crates/state/src/lib.rs +++ b/crates/state/src/lib.rs @@ -142,7 +142,6 @@ pub trait StateRead: StorageRead + Debug { fn validity_predicate( &self, addr: &Address, - _: &Params, ) -> Result<(Option, u64)> { let key = if let Address::Implicit(_) = addr { Params::implicit_vp_key() diff --git a/crates/state/src/wl_state.rs b/crates/state/src/wl_state.rs index 0fc1172e584..d4e3ccbad6f 100644 --- a/crates/state/src/wl_state.rs +++ b/crates/state/src/wl_state.rs @@ -651,6 +651,29 @@ where } } + /// Borrow in-memory state and DB handle with a mutable temporary write-log. + /// + /// # Safety + /// + /// The lifetime of borrows is unsafely extended to `'static` to allow usage + /// in node's `dry_run_tx`, which needs a static lifetime to be able to call + /// protocol's API that is generic over the state with a bound `S: 'static + + /// State` with a mutable reference to this struct. + /// Because the lifetime of `S` is invariant w.r.t. `&mut S` + /// () we are faking a + /// static lifetime of `S` for `TempWlState`. This should be safe as neither + /// `db` nor `in_mem` are actually mutable, only the `write_log` which is + /// owned by this struct. + pub unsafe fn with_static_temp_write_log( + &self, + ) -> TempWlState<'static, D, H> { + TempWlState { + write_log: WriteLog::default(), + db: &*(&self.db as *const _), + in_mem: &*(&self.in_mem as *const _), + } + } + /// Commit the current transaction's write log to the block. Starts a new /// transaction write log. pub fn commit_tx(&mut self) { diff --git a/crates/state/src/write_log.rs b/crates/state/src/write_log.rs index 3ab2e22ab97..ce7157e8420 100644 --- a/crates/state/src/write_log.rs +++ b/crates/state/src/write_log.rs @@ -1024,7 +1024,7 @@ mod tests { state.commit_block().expect("commit failed"); let (vp_code_hash, _gas) = state - .validity_predicate(&addr1, &namada_parameters::Key) + .validity_predicate::>(&addr1) .expect("vp read failed"); assert_eq!(vp_code_hash, Some(vp1)); let (value, _) = state.db_read(&key1).expect("read failed"); diff --git a/crates/tests/Cargo.toml b/crates/tests/Cargo.toml index 9ee35885f21..717ccd06d9a 100644 --- a/crates/tests/Cargo.toml +++ b/crates/tests/Cargo.toml @@ -13,7 +13,7 @@ repository.workspace = true version.workspace = true [features] -default = ["migrations"] +default = [] mainnet = [ "namada_sdk/mainnet", ] @@ -29,10 +29,14 @@ namada-eth-bridge = [ [dependencies] namada_core = {path = "../core", features = ["testing"]} -namada_sdk = {path = "../sdk", default-features = false, features = ["tendermint-rpc", "download-params", "std", "rand"]} +namada_sdk = {path = "../sdk", features = ["download-params", "testing"]} namada_test_utils = {path = "../test_utils"} +namada_tx_env = {path = "../tx_env"} namada_tx_prelude = {path = "../tx_prelude"} +namada_vp = {path = "../vp"} namada_vp_prelude = {path = "../vp_prelude"} +namada_vm = {path = "../vm", features = ["testing"]} + concat-idents.workspace = true derivative.workspace = true hyper = {version = "0.14.20", features = ["full"]} @@ -52,7 +56,11 @@ tokio = {workspace = true, features = ["full"]} [dev-dependencies] namada_apps_lib = {path = "../apps_lib", features = ["testing"]} namada_node = { path = "../node", features = ["testing"] } +namada_sdk = {path = "../sdk", default-features = false, features = [ + "download-params", "testing", "migrations" +]} namada_vm_env = {path = "../vm_env"} + assert_cmd.workspace = true assert_matches.workspace = true borsh.workspace = true diff --git a/crates/tests/src/e2e/eth_bridge_tests.rs b/crates/tests/src/e2e/eth_bridge_tests.rs index 582a2ca0945..c8d92937272 100644 --- a/crates/tests/src/e2e/eth_bridge_tests.rs +++ b/crates/tests/src/e2e/eth_bridge_tests.rs @@ -7,15 +7,10 @@ use std::str::FromStr; use borsh::{BorshDeserialize, BorshSerialize}; use color_eyre::eyre::{eyre, Result}; use expectrl::ControlCode; -use namada::control_flow::time::{Constant, Sleep}; -use namada::core::address::wnam; -use namada::core::ethereum_events::testing::DAI_ERC20_ETH_ADDRESS; -use namada::core::ethereum_events::EthAddress; -use namada::core::storage::{self, Epoch}; -use namada::core::{address, token}; -use namada::eth_bridge::oracle; -use namada::eth_bridge::storage::vote_tallies; -use namada::ledger::eth_bridge::{ +use namada_sdk::control_flow::time::{Constant, Sleep}; +use namada_sdk::eth_bridge::oracle; +use namada_sdk::eth_bridge::storage::vote_tallies; +use namada_sdk::eth_bridge::{ ContractVersion, Contracts, EthereumBridgeParams, MinimumConfirmations, UpgradeableContract, }; @@ -25,6 +20,11 @@ use namada_core::ethereum_events::{ EthereumEvent, TransferToEthereum, TransferToNamada, }; use namada_core::token::Amount; +use namada_sdk::address::wnam; +use namada_sdk::ethereum_events::testing::DAI_ERC20_ETH_ADDRESS; +use namada_sdk::ethereum_events::EthAddress; +use namada_sdk::storage::{self, Epoch}; +use namada_sdk::{address, token}; use namada_test_utils::tx_data::TxWriteData; use namada_test_utils::TestWasms; use tokio::time::{Duration, Instant}; diff --git a/crates/tests/src/e2e/eth_bridge_tests/helpers.rs b/crates/tests/src/e2e/eth_bridge_tests/helpers.rs index 40f9b68bf9d..b77944cb15d 100644 --- a/crates/tests/src/e2e/eth_bridge_tests/helpers.rs +++ b/crates/tests/src/e2e/eth_bridge_tests/helpers.rs @@ -7,15 +7,15 @@ use data_encoding::HEXLOWER; use eyre::{eyre, Context, Result}; use hyper::client::HttpConnector; use hyper::{Body, Client, Method, Request, StatusCode}; -use namada::core::address::{wnam, Address}; -use namada::core::ethereum_events::{ +use namada_sdk::address::{wnam, Address}; +use namada_sdk::ethereum_events::{ EthAddress, EthereumEvent, TransferToNamada, Uint, }; -use namada::ledger::eth_bridge::{ +use namada_sdk::eth_bridge::{ wrapped_erc20s, ContractVersion, Contracts, EthereumBridgeParams, MinimumConfirmations, UpgradeableContract, }; -use namada::token; +use namada_sdk::token; use namada_apps_lib::config::ethereum_bridge; use crate::e2e::helpers::{ diff --git a/crates/tests/src/e2e/helpers.rs b/crates/tests/src/e2e/helpers.rs index e5723d580ae..ddd0f1dfa54 100644 --- a/crates/tests/src/e2e/helpers.rs +++ b/crates/tests/src/e2e/helpers.rs @@ -15,18 +15,18 @@ use color_eyre::owo_colors::OwoColorize; use data_encoding::HEXLOWER; use escargot::CargoBuild; use eyre::eyre; -use namada::core::address::Address; -use namada::core::key::*; -use namada::core::storage::Epoch; -use namada::ledger::queries::{Rpc, RPC}; -use namada::tendermint_rpc::HttpClient; -use namada::token; use namada_apps_lib::cli::context::ENV_VAR_CHAIN_ID; use namada_apps_lib::config::genesis::chain::DeriveEstablishedAddress; use namada_apps_lib::config::genesis::templates; use namada_apps_lib::config::utils::convert_tm_addr_to_socket_addr; use namada_apps_lib::config::{Config, TendermintMode}; use namada_core::token::NATIVE_MAX_DECIMAL_PLACES; +use namada_sdk::address::Address; +use namada_sdk::key::*; +use namada_sdk::queries::{Rpc, RPC}; +use namada_sdk::storage::Epoch; +use namada_sdk::tendermint_rpc::HttpClient; +use namada_sdk::token; use namada_sdk::wallet::fs::FsWalletUtils; use namada_sdk::wallet::Wallet; use toml::Value; diff --git a/crates/tests/src/e2e/ibc_tests.rs b/crates/tests/src/e2e/ibc_tests.rs index c1781b62955..912cc4c82ac 100644 --- a/crates/tests/src/e2e/ibc_tests.rs +++ b/crates/tests/src/e2e/ibc_tests.rs @@ -16,71 +16,71 @@ use std::path::{Path, PathBuf}; use color_eyre::eyre::Result; use eyre::eyre; -use namada::core::address::{Address, InternalAddress}; -use namada::core::key::PublicKey; -use namada::core::storage::{BlockHeight, Epoch, Key}; -use namada::core::token::Amount; -use namada::governance::cli::onchain::PgfFunding; -use namada::governance::storage::proposal::{PGFIbcTarget, PGFTarget}; -use namada::ibc::apps::transfer::types::VERSION as ICS20_VERSION; -use namada::ibc::clients::tendermint::client_state::ClientState as TmClientState; -use namada::ibc::clients::tendermint::consensus_state::ConsensusState as TmConsensusState; -use namada::ibc::clients::tendermint::types::{ +use namada_apps_lib::cli::context::ENV_VAR_CHAIN_ID; +use namada_apps_lib::client::rpc::{ + query_pos_parameters, query_storage_value, query_storage_value_bytes, +}; +use namada_apps_lib::client::utils::id_from_pk; +use namada_apps_lib::config::genesis::{chain, templates}; +use namada_apps_lib::config::utils::set_port; +use namada_apps_lib::config::{ethereum_bridge, TendermintMode}; +use namada_apps_lib::facade::tendermint::block::Header as TmHeader; +use namada_apps_lib::facade::tendermint::merkle::proof::ProofOps as TmProof; +use namada_apps_lib::facade::tendermint_rpc::{Client, HttpClient, Url}; +use namada_core::string_encoding::StringEncoded; +use namada_sdk::address::{Address, InternalAddress}; +use namada_sdk::events::extend::ReadFromEventAttributes; +use namada_sdk::governance::cli::onchain::PgfFunding; +use namada_sdk::governance::pgf::ADDRESS as PGF_ADDRESS; +use namada_sdk::governance::storage::proposal::{PGFIbcTarget, PGFTarget}; +use namada_sdk::ibc::apps::transfer::types::VERSION as ICS20_VERSION; +use namada_sdk::ibc::clients::tendermint::client_state::ClientState as TmClientState; +use namada_sdk::ibc::clients::tendermint::consensus_state::ConsensusState as TmConsensusState; +use namada_sdk::ibc::clients::tendermint::types::{ AllowUpdate, ClientState as TmClientStateType, Header as IbcTmHeader, TrustThreshold, }; -use namada::ibc::core::channel::types::channel::Order as ChanOrder; -use namada::ibc::core::channel::types::msgs::{ +use namada_sdk::ibc::core::channel::types::channel::Order as ChanOrder; +use namada_sdk::ibc::core::channel::types::msgs::{ MsgAcknowledgement, MsgChannelOpenAck, MsgChannelOpenConfirm, MsgChannelOpenInit, MsgChannelOpenTry, MsgRecvPacket as IbcMsgRecvPacket, MsgTimeout as IbcMsgTimeout, }; -use namada::ibc::core::channel::types::packet::Packet; -use namada::ibc::core::channel::types::Version as ChanVersion; -use namada::ibc::core::client::context::client_state::ClientStateCommon; -use namada::ibc::core::client::types::msgs::{ +use namada_sdk::ibc::core::channel::types::packet::Packet; +use namada_sdk::ibc::core::channel::types::Version as ChanVersion; +use namada_sdk::ibc::core::client::context::client_state::ClientStateCommon; +use namada_sdk::ibc::core::client::types::msgs::{ MsgCreateClient, MsgUpdateClient, }; -use namada::ibc::core::client::types::Height; -use namada::ibc::core::commitment_types::commitment::{ +use namada_sdk::ibc::core::client::types::Height; +use namada_sdk::ibc::core::commitment_types::commitment::{ CommitmentPrefix, CommitmentProofBytes, }; -use namada::ibc::core::commitment_types::merkle::MerkleProof; -use namada::ibc::core::connection::types::msgs::{ +use namada_sdk::ibc::core::commitment_types::merkle::MerkleProof; +use namada_sdk::ibc::core::connection::types::msgs::{ MsgConnectionOpenAck, MsgConnectionOpenConfirm, MsgConnectionOpenInit, MsgConnectionOpenTry, }; -use namada::ibc::core::connection::types::version::Version as ConnVersion; -use namada::ibc::core::connection::types::Counterparty as ConnCounterparty; -use namada::ibc::core::host::types::identifiers::{ +use namada_sdk::ibc::core::connection::types::version::Version as ConnVersion; +use namada_sdk::ibc::core::connection::types::Counterparty as ConnCounterparty; +use namada_sdk::ibc::core::host::types::identifiers::{ ChainId, ChannelId, ClientId, ConnectionId, PortId, }; -use namada::ibc::event as ibc_events; -use namada::ibc::event::IbcEventType; -use namada::ibc::primitives::proto::Any; -use namada::ibc::primitives::{Signer, ToProto}; -use namada::ledger::ibc::storage::*; -use namada::ledger::parameters::{storage as param_storage, EpochDuration}; -use namada::ledger::pgf::ADDRESS as PGF_ADDRESS; -use namada::ledger::queries::RPC; -use namada::ledger::storage::ics23_specs::ibc_proof_specs; -use namada::sdk::events::extend::ReadFromEventAttributes; -use namada::state::Sha256Hasher; -use namada::tendermint::abci::Event as AbciEvent; -use namada::tendermint::block::Height as TmHeight; -use namada_apps_lib::cli::context::ENV_VAR_CHAIN_ID; -use namada_apps_lib::client::rpc::{ - query_pos_parameters, query_storage_value, query_storage_value_bytes, -}; -use namada_apps_lib::client::utils::id_from_pk; -use namada_apps_lib::config::genesis::{chain, templates}; -use namada_apps_lib::config::utils::set_port; -use namada_apps_lib::config::{ethereum_bridge, TendermintMode}; -use namada_apps_lib::facade::tendermint::block::Header as TmHeader; -use namada_apps_lib::facade::tendermint::merkle::proof::ProofOps as TmProof; -use namada_apps_lib::facade::tendermint_rpc::{Client, HttpClient, Url}; -use namada_core::string_encoding::StringEncoded; +use namada_sdk::ibc::event as ibc_events; +use namada_sdk::ibc::event::IbcEventType; +use namada_sdk::ibc::primitives::proto::Any; +use namada_sdk::ibc::primitives::{Signer, ToProto}; +use namada_sdk::ibc::storage::*; +use namada_sdk::key::PublicKey; use namada_sdk::masp::fs::FsShieldedUtils; +use namada_sdk::parameters::{storage as param_storage, EpochDuration}; +use namada_sdk::queries::RPC; +use namada_sdk::state::ics23_specs::ibc_proof_specs; +use namada_sdk::state::Sha256Hasher; +use namada_sdk::storage::{BlockHeight, Epoch, Key}; +use namada_sdk::tendermint::abci::Event as AbciEvent; +use namada_sdk::tendermint::block::Height as TmHeight; +use namada_sdk::token::Amount; use namada_test_utils::TestWasms; use prost::Message; use setup::constants::*; diff --git a/crates/tests/src/e2e/ledger_tests.rs b/crates/tests/src/e2e/ledger_tests.rs index 792d700029d..ab22429d27a 100644 --- a/crates/tests/src/e2e/ledger_tests.rs +++ b/crates/tests/src/e2e/ledger_tests.rs @@ -19,15 +19,15 @@ use std::time::{Duration, Instant}; use color_eyre::eyre::Result; use color_eyre::owo_colors::OwoColorize; -use namada::core::address::Address; -use namada::core::storage::Epoch; -use namada::token; use namada_apps_lib::cli::context::ENV_VAR_CHAIN_ID; use namada_apps_lib::config::ethereum_bridge; use namada_apps_lib::config::utils::convert_tm_addr_to_socket_addr; use namada_apps_lib::facade::tendermint_config::net::Address as TendermintAddress; use namada_core::chain::ChainId; use namada_core::token::NATIVE_MAX_DECIMAL_PLACES; +use namada_sdk::address::Address; +use namada_sdk::storage::Epoch; +use namada_sdk::token; use namada_test_utils::TestWasms; use serde::Serialize; use serde_json::json; @@ -1066,9 +1066,9 @@ fn double_signing_gets_slashed() -> Result<()> { use std::net::SocketAddr; use std::str::FromStr; - use namada::core::key::{self, ed25519, SigScheme}; use namada_apps_lib::client; use namada_apps_lib::config::Config; + use namada_sdk::key::{self, ed25519, SigScheme}; let mut pipeline_len = 0; let mut unbonding_len = 0; diff --git a/crates/tests/src/e2e/multitoken_tests/helpers.rs b/crates/tests/src/e2e/multitoken_tests/helpers.rs index 948fc750da4..ba6ecbf0ef8 100644 --- a/crates/tests/src/e2e/multitoken_tests/helpers.rs +++ b/crates/tests/src/e2e/multitoken_tests/helpers.rs @@ -41,7 +41,7 @@ pub fn init_multitoken_vp(test: &Test, rpc_addr: &str) -> Result { ARBITRARY_SIGNER, "--public-key", // Value obtained from - // `namada::core::key::ed25519::tests::gen_keypair` + // `namada_sdk::key::ed25519::tests::gen_keypair` "001be519a321e29020fa3cbfbfd01bd5e92db134305609270b71dace25b5a21168", "--code-path", &multitoken_vp_wasm_path, diff --git a/crates/tests/src/e2e/setup.rs b/crates/tests/src/e2e/setup.rs index 287ff9fa8d0..78d88bcba8b 100644 --- a/crates/tests/src/e2e/setup.rs +++ b/crates/tests/src/e2e/setup.rs @@ -18,7 +18,6 @@ use expectrl::stream::log::LogStream; use expectrl::{ControlCode, Eof, WaitStatus}; use eyre::eyre; use itertools::{Either, Itertools}; -use namada::core::chain::ChainId; use namada_apps_lib::cli::context::ENV_VAR_CHAIN_ID; use namada_apps_lib::client::utils::{ self, validator_pre_genesis_dir, validator_pre_genesis_txs_file, @@ -34,6 +33,7 @@ use namada_core::collections::HashMap; use namada_core::key::{RefTo, SchemeType}; use namada_core::string_encoding::StringEncoded; use namada_core::token::NATIVE_MAX_DECIMAL_PLACES; +use namada_sdk::chain::ChainId; use namada_sdk::wallet::alias::Alias; use namada_tx_prelude::token; use once_cell::sync::Lazy; diff --git a/crates/tests/src/integration/ledger_tests.rs b/crates/tests/src/integration/ledger_tests.rs index 214ab32a1d6..d0b41ad20b4 100644 --- a/crates/tests/src/integration/ledger_tests.rs +++ b/crates/tests/src/integration/ledger_tests.rs @@ -6,9 +6,6 @@ use borsh::BorshDeserialize; use borsh_ext::BorshSerializeExt; use color_eyre::eyre::Result; use data_encoding::HEXLOWER; -use namada::account::AccountPublicKeysMap; -use namada::core::collections::HashMap; -use namada::token::{self, Amount, DenominatedAmount}; use namada_apps_lib::wallet::defaults::{self, albert_keypair}; use namada_core::dec::Dec; use namada_core::hash::Hash; @@ -17,8 +14,11 @@ use namada_core::token::NATIVE_MAX_DECIMAL_PLACES; use namada_node::shell::testing::client::run; use namada_node::shell::testing::node::NodeResults; use namada_node::shell::testing::utils::{Bin, CapturedOutput}; +use namada_sdk::account::AccountPublicKeysMap; +use namada_sdk::collections::HashMap; use namada_sdk::migrations; use namada_sdk::queries::RPC; +use namada_sdk::token::{self, Amount, DenominatedAmount}; use namada_sdk::tx::{TX_TRANSPARENT_TRANSFER_WASM, VP_USER_WASM}; use namada_test_utils::TestWasms; use test_log::test; @@ -154,7 +154,7 @@ fn ledger_txs_and_queries() -> Result<()> { vec![ "init-account", "--public-keys", - // Value obtained from `namada::core::key::ed25519::tests::gen_keypair` + // Value obtained from `namada_sdk::key::ed25519::tests::gen_keypair` "tpknam1qpqfzxu3gt05jx2mvg82f4anf90psqerkwqhjey4zlqv0qfgwuvkzt5jhkp", "--threshold", "1", @@ -952,7 +952,8 @@ fn proposal_submission() -> Result<()> { let init_account = vec![ "init-account", "--public-keys", - // Value obtained from `namada::core::key::ed25519::tests::gen_keypair` + // Value obtained from + // `namada_sdk::key::ed25519::tests::gen_keypair` "tpknam1qpqfzxu3gt05jx2mvg82f4anf90psqerkwqhjey4zlqv0qfgwuvkzt5jhkp", "--threshold", "1", @@ -1699,9 +1700,9 @@ fn enforce_fee_payment() -> Result<()> { let mut txs = vec![]; for bytes in txs_bytes { - let mut tx = namada::tx::Tx::deserialize(&bytes).unwrap(); + let mut tx = namada_sdk::tx::Tx::deserialize(&bytes).unwrap(); tx.add_wrapper( - namada::tx::data::wrapper::Fee { + namada_sdk::tx::data::wrapper::Fee { amount_per_gas_unit: DenominatedAmount::native( Amount::native_whole(1), ), diff --git a/crates/tests/src/integration/masp.rs b/crates/tests/src/integration/masp.rs index 5f7f6dfd1b2..866511438b8 100644 --- a/crates/tests/src/integration/masp.rs +++ b/crates/tests/src/integration/masp.rs @@ -3,9 +3,6 @@ use std::str::FromStr; use color_eyre::eyre::Result; use color_eyre::owo_colors::OwoColorize; -use namada::state::{StorageRead, StorageWrite}; -use namada::token::storage_key::masp_token_map_key; -use namada::token::{self, DenominatedAmount}; use namada_apps_lib::wallet::defaults::christel_keypair; use namada_core::dec::Dec; use namada_core::masp::TokenMap; @@ -13,6 +10,9 @@ use namada_node::shell::testing::client::run; use namada_node::shell::testing::node::NodeResults; use namada_node::shell::testing::utils::{Bin, CapturedOutput}; use namada_sdk::masp::fs::FsShieldedUtils; +use namada_sdk::state::{StorageRead, StorageWrite}; +use namada_sdk::token::storage_key::masp_token_map_key; +use namada_sdk::token::{self, DenominatedAmount}; use test_log::test; use super::setup; @@ -1497,9 +1497,9 @@ fn multiple_unfetched_txs_same_block() -> Result<()> { .clone(); let mut txs = vec![]; for bytes in txs_bytes { - let mut tx = namada::tx::Tx::deserialize(&bytes).unwrap(); + let mut tx = namada_sdk::tx::Tx::deserialize(&bytes).unwrap(); tx.add_wrapper( - namada::tx::data::wrapper::Fee { + namada_sdk::tx::data::wrapper::Fee { amount_per_gas_unit: DenominatedAmount::native(1.into()), token: native_token.clone(), }, diff --git a/crates/tests/src/integration/setup.rs b/crates/tests/src/integration/setup.rs index 441273e71e4..fd89fb7b960 100644 --- a/crates/tests/src/integration/setup.rs +++ b/crates/tests/src/integration/setup.rs @@ -5,8 +5,6 @@ use std::str::FromStr; use std::sync::{Arc, Mutex}; use color_eyre::eyre::{eyre, Result}; -use namada::core::dec::Dec; -use namada::token; use namada_apps_lib::cli::args; use namada_apps_lib::client::utils::PRE_GENESIS_DIR; use namada_apps_lib::config; @@ -25,6 +23,8 @@ use namada_node::shell::testing::node::{ }; use namada_node::shell::testing::utils::TestDir; use namada_node::shell::Shell; +use namada_sdk::dec::Dec; +use namada_sdk::token; use namada_sdk::wallet::alias::Alias; use crate::e2e::setup::{copy_wasm_to_chain_dir, SINGLE_NODE_NET_GENESIS}; diff --git a/crates/tests/src/lib.rs b/crates/tests/src/lib.rs index ca55eba2075..e4717b8c125 100644 --- a/crates/tests/src/lib.rs +++ b/crates/tests/src/lib.rs @@ -5,10 +5,8 @@ #![deny(rustdoc::broken_intra_doc_links)] #![deny(rustdoc::private_intra_doc_links)] -pub use namada; - mod vm_host_env; -pub use vm_host_env::{ibc, tx, vp}; +pub use vm_host_env::{tx, vp}; #[cfg(test)] mod e2e; #[cfg(test)] @@ -26,3 +24,5 @@ pub mod strings; pub mod log { pub use test_log::test; } + +pub use namada_sdk::*; diff --git a/crates/tests/src/native_vp/eth_bridge_pool.rs b/crates/tests/src/native_vp/eth_bridge_pool.rs index aefc436f16a..686fadc0c6e 100644 --- a/crates/tests/src/native_vp/eth_bridge_pool.rs +++ b/crates/tests/src/native_vp/eth_bridge_pool.rs @@ -5,25 +5,24 @@ mod test_bridge_pool_vp { use borsh::BorshDeserialize; use borsh_ext::BorshSerializeExt; - use namada::core::address::testing::{nam, wnam}; - use namada::core::chain::ChainId; - use namada::core::eth_bridge_pool::{ - GasFee, PendingTransfer, TransferToEthereum, TransferToEthereumKind, - }; - use namada::core::ethereum_events::EthAddress; - use namada::core::key::{common, ed25519, SecretKey}; - use namada::core::token::Amount; - use namada::eth_bridge::storage::bridge_pool::BRIDGE_POOL_ADDRESS; - use namada::gas::VpGasMeter; - use namada::ledger::native_vp::ethereum_bridge::bridge_pool_vp::BridgePoolVp; - use namada::tx::Tx; use namada_apps_lib::wallet::defaults::{albert_address, bertha_address}; use namada_apps_lib::wasm_loader; + use namada_sdk::address::testing::{nam, wnam}; + use namada_sdk::chain::ChainId; + use namada_sdk::eth_bridge::storage::bridge_pool::BRIDGE_POOL_ADDRESS; use namada_sdk::eth_bridge::{ wrapped_erc20s, Contracts, Erc20WhitelistEntry, EthereumBridgeParams, UpgradeableContract, }; - use namada_sdk::tx::TX_BRIDGE_POOL_WASM as ADD_TRANSFER_WASM; + use namada_sdk::eth_bridge_pool::{ + GasFee, PendingTransfer, TransferToEthereum, TransferToEthereumKind, + }; + use namada_sdk::ethereum_events::EthAddress; + use namada_sdk::gas::VpGasMeter; + use namada_sdk::key::{common, ed25519, SecretKey}; + use namada_sdk::token::Amount; + use namada_sdk::tx::{Tx, TX_BRIDGE_POOL_WASM as ADD_TRANSFER_WASM}; + use namada_sdk::validation::EthBridgePoolVp; use namada_tx_prelude::BatchedTx; use crate::native_vp::TestNativeVpEnv; @@ -38,7 +37,7 @@ mod test_bridge_pool_vp { /// A signing keypair for good old Bertha. fn bertha_keypair() -> common::SecretKey { // generated from - // [`namada::core::key::ed25519::gen_keypair`] + // [`namada_sdk::key::ed25519::gen_keypair`] let bytes = [ 240, 3, 224, 69, 201, 148, 60, 53, 112, 79, 80, 107, 101, 127, 186, 6, 176, 162, 113, 224, 62, 8, 183, 187, 124, 234, 244, 251, 92, 36, @@ -118,9 +117,9 @@ mod test_bridge_pool_vp { &tx_env.gas_meter.borrow(), )); let vp_env = TestNativeVpEnv::from_tx_env(tx_env, BRIDGE_POOL_ADDRESS); - vp_env - .validate_tx(&gas_meter, |ctx| BridgePoolVp { ctx }) - .is_ok() + + let vp = vp_env.init_vp(&gas_meter, EthBridgePoolVp::new); + vp_env.validate_tx(&vp).is_ok() } fn validate_tx(tx: BatchedTx) { diff --git a/crates/tests/src/native_vp/mod.rs b/crates/tests/src/native_vp/mod.rs index d5867e7d038..f3c659f2ce9 100644 --- a/crates/tests/src/native_vp/mod.rs +++ b/crates/tests/src/native_vp/mod.rs @@ -4,16 +4,28 @@ pub mod pos; use std::cell::RefCell; use std::collections::BTreeSet; -use namada::core::address::Address; -use namada::core::storage; -use namada::ledger::gas::VpGasMeter; -use namada::ledger::native_vp::{Ctx, NativeVp}; -use namada::state::testing::TestState; -use namada::vm::WasmCacheRwAccess; +use namada_sdk::address::Address; +use namada_sdk::gas::VpGasMeter; +use namada_sdk::state::testing::TestState; +use namada_sdk::state::StateRead; +use namada_sdk::storage; +use namada_vm::wasm::run::VpEvalWasm; +use namada_vm::wasm::VpCache; +use namada_vm::WasmCacheRwAccess; +use namada_vp::native_vp::{Ctx, NativeVp}; use crate::tx::TestTxEnv; -type NativeVpCtx<'a> = Ctx<'a, TestState, WasmCacheRwAccess>; +type NativeVpCtx<'a> = Ctx< + 'a, + TestState, + VpCache, + VpEvalWasm< + ::D, + ::H, + WasmCacheRwAccess, + >, +>; #[derive(Debug)] pub struct TestNativeVpEnv { @@ -41,15 +53,15 @@ impl TestNativeVpEnv { impl TestNativeVpEnv { /// Run some transaction code `apply_tx` and validate it with a native VP - pub fn validate_tx<'a, T>( - &'a self, - gas_meter: &'a RefCell, - init_native_vp: impl Fn(NativeVpCtx<'a>) -> T, - ) -> Result<(), ::Error> + pub fn init_vp<'view, 'ctx: 'view, T>( + &'ctx self, + gas_meter: &'ctx RefCell, + init_native_vp: impl Fn(NativeVpCtx<'ctx>) -> T, + ) -> T where - T: NativeVp, + T: NativeVp<'view>, { - let ctx = Ctx::new( + let ctx = NativeVpCtx::new( &self.address, &self.tx_env.state, &self.tx_env.batched_tx.tx, @@ -60,9 +72,18 @@ impl TestNativeVpEnv { &self.verifiers, self.tx_env.vp_wasm_cache.clone(), ); - let native_vp = init_native_vp(ctx); + init_native_vp(ctx) + } - native_vp.validate_tx( + /// Run some transaction code `apply_tx` and validate it with a native VP + pub fn validate_tx<'view, 'ctx: 'view, T>( + &'ctx self, + vp: &'view T, + ) -> Result<(), >::Error> + where + T: 'view + NativeVp<'view>, + { + vp.validate_tx( &self.tx_env.batched_tx.to_ref(), &self.keys_changed, &self.verifiers, diff --git a/crates/tests/src/native_vp/pos.rs b/crates/tests/src/native_vp/pos.rs index e0d970f11ad..9734e4c2b0f 100644 --- a/crates/tests/src/native_vp/pos.rs +++ b/crates/tests/src/native_vp/pos.rs @@ -95,10 +95,10 @@ //! - add slashes //! - add rewards -use namada::core::storage::Epoch; -use namada::proof_of_stake::parameters::{OwnedPosParams, PosParams}; -use namada::proof_of_stake::test_utils::test_init_genesis as init_genesis; -use namada::proof_of_stake::types::GenesisValidator; +use namada_sdk::proof_of_stake::parameters::{OwnedPosParams, PosParams}; +use namada_sdk::proof_of_stake::test_utils::test_init_genesis as init_genesis; +use namada_sdk::proof_of_stake::types::GenesisValidator; +use namada_sdk::storage::Epoch; use crate::tx::tx_host_env; @@ -149,11 +149,10 @@ mod tests { use std::cell::RefCell; - use namada::core::address; - use namada::core::key::common::PublicKey; - use namada::gas::VpGasMeter; - use namada::ledger::pos::PosVP; - use namada::token; + use namada_sdk::gas::VpGasMeter; + use namada_sdk::key::common::PublicKey; + use namada_sdk::validation::PosVp; + use namada_sdk::{address, token}; use namada_tx_prelude::proof_of_stake::parameters::testing::arb_pos_params; use namada_tx_prelude::Address; use proptest::prelude::*; @@ -440,7 +439,8 @@ mod tests { &tx_env.gas_meter.borrow(), )); let vp_env = TestNativeVpEnv::from_tx_env(tx_env, address::POS); - let result = vp_env.validate_tx(&gas_meter, PosVP::new); + let vp = vp_env.init_vp(&gas_meter, PosVp::new); + let result = vp_env.validate_tx(&vp); // Put the tx_env back before checking the result tx_host_env::set(vp_env.tx_env); @@ -580,22 +580,21 @@ pub mod testing { use derivative::Derivative; use itertools::Either; - use namada::core::dec::Dec; - use namada::core::key::common::PublicKey; - use namada::core::key::RefTo; - use namada::core::storage::Epoch; - use namada::core::{address, key}; - use namada::ledger::gas::TxGasMeter; - use namada::proof_of_stake::epoched::DynEpochOffset; - use namada::proof_of_stake::parameters::testing::arb_rate; - use namada::proof_of_stake::parameters::PosParams; - use namada::proof_of_stake::storage::{ + use namada_sdk::dec::Dec; + use namada_sdk::gas::TxGasMeter; + use namada_sdk::key::common::PublicKey; + use namada_sdk::key::RefTo; + use namada_sdk::proof_of_stake::epoched::DynEpochOffset; + use namada_sdk::proof_of_stake::parameters::testing::arb_rate; + use namada_sdk::proof_of_stake::parameters::PosParams; + use namada_sdk::proof_of_stake::storage::{ get_num_consensus_validators, read_pos_params, unbond_handle, }; - use namada::proof_of_stake::types::{BondId, ValidatorState}; - use namada::proof_of_stake::ADDRESS as POS_ADDRESS; - use namada::token; - use namada::token::{Amount, Change}; + use namada_sdk::proof_of_stake::types::{BondId, ValidatorState}; + use namada_sdk::proof_of_stake::ADDRESS as POS_ADDRESS; + use namada_sdk::storage::Epoch; + use namada_sdk::token::{Amount, Change}; + use namada_sdk::{address, key, token}; use namada_tx_prelude::{Address, StorageRead, StorageWrite}; use proptest::prelude::*; diff --git a/crates/tests/src/storage.rs b/crates/tests/src/storage.rs index 3a5c9a51184..3256105036f 100644 --- a/crates/tests/src/storage.rs +++ b/crates/tests/src/storage.rs @@ -3,7 +3,7 @@ use std::rc::Rc; use derivative::Derivative; -use namada::core::storage; +use namada_sdk::storage; /// A list of changes, which must be applied in the same order to get to the /// current state. diff --git a/crates/tests/src/storage_api/collections/lazy_map.rs b/crates/tests/src/storage_api/collections/lazy_map.rs index 48d5f64511f..ebd813ce611 100644 --- a/crates/tests/src/storage_api/collections/lazy_map.rs +++ b/crates/tests/src/storage_api/collections/lazy_map.rs @@ -3,8 +3,8 @@ mod tests { use std::collections::BTreeMap; use borsh::{BorshDeserialize, BorshSerialize}; - use namada::core::address::{self, Address}; - use namada::core::storage; + use namada_sdk::address::{self, Address}; + use namada_sdk::storage; use namada_tx_prelude::collections::{LazyCollection, LazyMap}; use namada_tx_prelude::storage::KeySeg; use namada_vp_prelude::collection_validation::{self, LazyCollectionExt}; diff --git a/crates/tests/src/storage_api/collections/lazy_set.rs b/crates/tests/src/storage_api/collections/lazy_set.rs index 4ac16671d91..cbb71d94188 100644 --- a/crates/tests/src/storage_api/collections/lazy_set.rs +++ b/crates/tests/src/storage_api/collections/lazy_set.rs @@ -2,8 +2,8 @@ mod tests { use std::collections::BTreeSet; - use namada::core::address::{self, Address}; - use namada::core::storage; + use namada_sdk::address::{self, Address}; + use namada_sdk::storage; use namada_tx_prelude::collections::{LazyCollection, LazySet}; use namada_tx_prelude::storage::KeySeg; use namada_vp_prelude::collection_validation::{self, LazyCollectionExt}; diff --git a/crates/tests/src/storage_api/collections/lazy_vec.rs b/crates/tests/src/storage_api/collections/lazy_vec.rs index a51508dd714..0cf2e67f1bf 100644 --- a/crates/tests/src/storage_api/collections/lazy_vec.rs +++ b/crates/tests/src/storage_api/collections/lazy_vec.rs @@ -2,8 +2,8 @@ mod tests { use borsh::{BorshDeserialize, BorshSerialize}; - use namada::core::address::{self, Address}; - use namada::core::storage; + use namada_sdk::address::{self, Address}; + use namada_sdk::storage; use namada_tx_prelude::collections::{lazy_vec, LazyCollection, LazyVec}; use namada_tx_prelude::storage::KeySeg; use namada_vp_prelude::collection_validation::{self, LazyCollectionExt}; diff --git a/crates/tests/src/storage_api/collections/nested_lazy_map.rs b/crates/tests/src/storage_api/collections/nested_lazy_map.rs index 7658a66223d..25bf507b79e 100644 --- a/crates/tests/src/storage_api/collections/nested_lazy_map.rs +++ b/crates/tests/src/storage_api/collections/nested_lazy_map.rs @@ -3,8 +3,8 @@ mod tests { use std::collections::BTreeMap; use borsh::{BorshDeserialize, BorshSerialize}; - use namada::core::address::{self, Address}; - use namada::core::storage; + use namada_sdk::address::{self, Address}; + use namada_sdk::storage; use namada_tx_prelude::collections::lazy_map::{ NestedMap, NestedSubKey, SubKey, }; diff --git a/crates/tests/src/vm_host_env/ibc.rs b/crates/tests/src/vm_host_env/ibc.rs index 3d5275323ce..5026805ac74 100644 --- a/crates/tests/src/vm_host_env/ibc.rs +++ b/crates/tests/src/vm_host_env/ibc.rs @@ -6,85 +6,81 @@ use ibc_testkit::testapp::ibc::clients::mock::client_state::{ }; use ibc_testkit::testapp::ibc::clients::mock::consensus_state::MockConsensusState; use ibc_testkit::testapp::ibc::clients::mock::header::MockHeader; -use namada::core::address::{self, Address, InternalAddress}; -use namada::core::hash::Hash; -use namada::core::storage::{self, BlockHeight, Epoch, Key, TxIndex}; -use namada::core::time::DurationSecs; -use namada::gas::TxGasMeter; -use namada::governance::parameters::GovernanceParameters; -use namada::ibc::apps::transfer::types::error::TokenTransferError; -use namada::ibc::apps::transfer::types::msgs::transfer::MsgTransfer as IbcMsgTransfer; -use namada::ibc::apps::transfer::types::packet::PacketData; -use namada::ibc::apps::transfer::types::{ +use namada_core::collections::HashMap; +use namada_core::storage::testing::get_dummy_header; +use namada_sdk::address::{self, Address, InternalAddress}; +use namada_sdk::gas::{TxGasMeter, VpGasMeter}; +use namada_sdk::governance::parameters::GovernanceParameters; +use namada_sdk::hash::Hash; +use namada_sdk::ibc::apps::transfer::types::error::TokenTransferError; +use namada_sdk::ibc::apps::transfer::types::msgs::transfer::MsgTransfer as IbcMsgTransfer; +use namada_sdk::ibc::apps::transfer::types::packet::PacketData; +use namada_sdk::ibc::apps::transfer::types::{ ack_success_b64, PrefixedCoin, VERSION, }; -use namada::ibc::core::channel::types::acknowledgement::{ +use namada_sdk::ibc::core::channel::types::acknowledgement::{ AcknowledgementStatus, StatusValue, }; -use namada::ibc::core::channel::types::channel::{ +use namada_sdk::ibc::core::channel::types::channel::{ ChannelEnd, Counterparty as ChanCounterparty, Order, State as ChanState, }; -use namada::ibc::core::channel::types::msgs::{ +use namada_sdk::ibc::core::channel::types::msgs::{ MsgAcknowledgement, MsgChannelCloseConfirm, MsgChannelCloseInit, MsgChannelOpenAck, MsgChannelOpenConfirm, MsgChannelOpenInit, MsgChannelOpenTry, MsgRecvPacket, MsgTimeout, MsgTimeoutOnClose, }; -pub use namada::ibc::core::channel::types::packet::Packet; -use namada::ibc::core::channel::types::timeout::TimeoutHeight; -use namada::ibc::core::channel::types::Version as ChanVersion; -use namada::ibc::core::client::types::msgs::{ - MsgCreateClient, MsgUpdateClient, MsgUpgradeClient, +pub use namada_sdk::ibc::core::channel::types::packet::Packet; +use namada_sdk::ibc::core::channel::types::timeout::TimeoutHeight; +use namada_sdk::ibc::core::channel::types::Version as ChanVersion; +use namada_sdk::ibc::core::client::types::msgs::{ + MsgCreateClient, MsgUpdateClient, }; -use namada::ibc::core::client::types::Height; -use namada::ibc::core::commitment_types::commitment::{ +use namada_sdk::ibc::core::client::types::Height; +use namada_sdk::ibc::core::commitment_types::commitment::{ CommitmentPrefix, CommitmentProofBytes, }; -use namada::ibc::core::connection::types::msgs::{ +use namada_sdk::ibc::core::connection::types::msgs::{ MsgConnectionOpenAck, MsgConnectionOpenConfirm, MsgConnectionOpenInit, MsgConnectionOpenTry, }; -use namada::ibc::core::connection::types::version::Version as ConnVersion; -use namada::ibc::core::connection::types::{ +use namada_sdk::ibc::core::connection::types::version::Version as ConnVersion; +use namada_sdk::ibc::core::connection::types::{ ConnectionEnd, Counterparty as ConnCounterparty, State as ConnState, }; -pub use namada::ibc::core::host::types::identifiers::{ +pub use namada_sdk::ibc::core::host::types::identifiers::{ ChannelId, ClientId, ConnectionId, PortId, Sequence, }; -use namada::ibc::primitives::proto::{Any, Protobuf}; -use namada::ibc::primitives::Timestamp; -use namada::ibc::MsgTransfer; -use namada::ledger::gas::VpGasMeter; -use namada::ledger::ibc::parameters::IbcParameters; -pub use namada::ledger::ibc::storage::{ - ack_key, channel_counter_key, channel_key, client_counter_key, - client_state_key, client_update_height_key, client_update_timestamp_key, - commitment_key, connection_counter_key, connection_key, - consensus_state_key, ibc_token, next_sequence_ack_key, - next_sequence_recv_key, next_sequence_send_key, port_key, receipt_key, +use namada_sdk::ibc::parameters::IbcParameters; +use namada_sdk::ibc::primitives::proto::{Any, Protobuf}; +use namada_sdk::ibc::primitives::Timestamp; +pub use namada_sdk::ibc::storage::{ + channel_key, client_counter_key, client_state_key, + client_update_height_key, client_update_timestamp_key, + connection_counter_key, connection_key, consensus_state_key, ibc_token, + port_key, }; -use namada::ledger::native_vp::ibc::Ibc; -use namada::ledger::native_vp::multitoken::{ - Error as MultitokenVpError, MultitokenVp, -}; -use namada::ledger::native_vp::{Ctx, NativeVp}; -use namada::ledger::parameters::storage::{ +use namada_sdk::ibc::MsgTransfer; +use namada_sdk::parameters::storage::{ get_epoch_duration_storage_key, get_max_expected_time_per_block_key, }; -use namada::ledger::parameters::EpochDuration; -use namada::ledger::tx_env::TxEnv; -use namada::ledger::{ibc, pos}; -use namada::proof_of_stake::OwnedPosParams; -use namada::state::testing::TestState; -use namada::tendermint::time::Time as TmTime; -use namada::token::{self, Amount, DenominatedAmount}; -use namada::tx::BatchedTxRef; -use namada::vm::{wasm, WasmCacheRwAccess}; -use namada_core::collections::HashMap; -use namada_core::storage::testing::get_dummy_header; -use namada_proof_of_stake::test_utils::get_dummy_genesis_validator; +use namada_sdk::parameters::EpochDuration; +use namada_sdk::proof_of_stake::test_utils::get_dummy_genesis_validator; +use namada_sdk::proof_of_stake::OwnedPosParams; +use namada_sdk::state::testing::TestState; use namada_sdk::state::StateRead; +use namada_sdk::storage::{self, BlockHeight, Epoch, Key, TxIndex}; +use namada_sdk::tendermint::time::Time as TmTime; +use namada_sdk::time::DurationSecs; +use namada_sdk::token::vp::MultitokenError; +use namada_sdk::token::{self, Amount, DenominatedAmount}; +use namada_sdk::tx::BatchedTxRef; +use namada_sdk::validation::{IbcVp, MultitokenVp}; +use namada_sdk::{ibc, proof_of_stake}; use namada_test_utils::TestWasms; +use namada_tx_env::TxEnv; use namada_tx_prelude::BorshSerializeExt; +use namada_vm::{wasm, WasmCacheRwAccess}; +use namada_vp::native_vp::{Ctx, NativeVp}; use crate::tx::*; @@ -93,14 +89,14 @@ pub const ANY_DENOMINATION: u8 = 4; const COMMITMENT_PREFIX: &[u8] = b"ibc"; pub struct TestIbcVp<'a> { - pub ibc: Ibc<'a, TestState, WasmCacheRwAccess>, + pub ibc: IbcVp<'a, TestState, WasmCacheRwAccess>, } impl<'a> TestIbcVp<'a> { pub fn validate( &self, batched_tx: &BatchedTxRef, - ) -> std::result::Result<(), namada::ledger::native_vp::ibc::Error> { + ) -> std::result::Result<(), namada_sdk::ibc::vp::Error> { self.ibc.validate_tx( batched_tx, self.ibc.ctx.keys_changed, @@ -117,7 +113,7 @@ impl<'a> TestMultitokenVp<'a> { pub fn validate( &self, batched_tx: &BatchedTxRef, - ) -> std::result::Result<(), MultitokenVpError> { + ) -> std::result::Result<(), MultitokenError> { self.multitoken_vp.validate_tx( batched_tx, self.multitoken_vp.ctx.keys_changed, @@ -130,7 +126,7 @@ impl<'a> TestMultitokenVp<'a> { pub fn validate_ibc_vp_from_tx<'a>( tx_env: &'a TestTxEnv, batched_tx: &'a BatchedTxRef, -) -> std::result::Result<(), namada::ledger::native_vp::ibc::Error> { +) -> std::result::Result<(), namada_sdk::ibc::vp::Error> { let (verifiers, keys_changed) = tx_env .state .write_log() @@ -159,7 +155,7 @@ pub fn validate_ibc_vp_from_tx<'a>( &verifiers, vp_wasm_cache, ); - let ibc = Ibc { ctx }; + let ibc = IbcVp::new(ctx); TestIbcVp { ibc }.validate(batched_tx) } @@ -169,7 +165,7 @@ pub fn validate_multitoken_vp_from_tx<'a>( tx_env: &'a TestTxEnv, batched_tx: &'a BatchedTxRef, target: &Key, -) -> std::result::Result<(), MultitokenVpError> { +) -> std::result::Result<(), MultitokenError> { let (verifiers, keys_changed) = tx_env .state .write_log() @@ -198,7 +194,7 @@ pub fn validate_multitoken_vp_from_tx<'a>( &verifiers, vp_wasm_cache, ); - let multitoken_vp = MultitokenVp { ctx }; + let multitoken_vp = MultitokenVp::new(ctx); TestMultitokenVp { multitoken_vp }.validate(batched_tx) } @@ -210,7 +206,7 @@ pub fn init_storage() -> (Address, Address) { let code_hash = Hash::sha256(&code); tx_host_env::with(|env| { - namada::parameters::init_test_storage(&mut env.state).unwrap(); + namada_sdk::parameters::init_test_storage(&mut env.state).unwrap(); ibc::init_genesis_storage(&mut env.state); let gov_params = GovernanceParameters::default(); gov_params.init_storage(&mut env.state).unwrap(); @@ -219,7 +215,7 @@ pub fn init_storage() -> (Address, Address) { default_per_epoch_throughput_limit: Amount::native_whole(100), }; ibc_params.init_storage(&mut env.state).unwrap(); - pos::test_utils::test_init_genesis( + proof_of_stake::test_utils::test_init_genesis( &mut env.state, OwnedPosParams::default(), vec![get_dummy_genesis_validator()].into_iter(), @@ -273,7 +269,7 @@ pub fn init_storage() -> (Address, Address) { // max_expected_time_per_block let time = DurationSecs::from(Duration::new(60, 0)); let key = get_max_expected_time_per_block_key(); - let bytes = namada::core::encode(&time); + let bytes = namada_sdk::encode(&time); tx_host_env::with(|env| { env.state.db_write(&key, &bytes).unwrap(); }); @@ -431,18 +427,6 @@ pub fn msg_update_client(client_id: ClientId) -> MsgUpdateClient { } } -pub fn msg_upgrade_client(client_id: ClientId) -> MsgUpgradeClient { - let (client_state, consensus_state) = dummy_client(); - MsgUpgradeClient { - client_id, - upgraded_client_state: client_state.into(), - upgraded_consensus_state: consensus_state.into(), - proof_upgrade_client: dummy_proof(), - proof_upgrade_consensus_state: dummy_proof(), - signer: "test".to_string().into(), - } -} - pub fn msg_connection_open_init(client_id: ClientId) -> MsgConnectionOpenInit { let counterparty_client_id = ClientId::new(&client_type().to_string(), 42).unwrap(); @@ -626,10 +610,6 @@ pub fn dummy_channel_counterparty() -> ChanCounterparty { ChanCounterparty::new(port_id, Some(channel_id)) } -pub fn unorder_channel(channel: &mut ChannelEnd) { - channel.ordering = Order::Unordered; -} - pub fn msg_transfer( port_id: PortId, channel_id: ChannelId, diff --git a/crates/tests/src/vm_host_env/mod.rs b/crates/tests/src/vm_host_env/mod.rs index c6e03ae9d99..ea74ab24edc 100644 --- a/crates/tests/src/vm_host_env/mod.rs +++ b/crates/tests/src/vm_host_env/mod.rs @@ -11,6 +11,7 @@ //! //! `RUST_LOG=debug cargo test test_tx_read_write -- --nocapture` +#[cfg(test)] pub mod ibc; pub mod tx; pub mod vp; @@ -23,23 +24,22 @@ mod tests { use borsh_ext::BorshSerializeExt; use itertools::Itertools; - use namada::account::pks_handle; - use namada::core::hash::Hash; - use namada::core::key::*; - use namada::core::storage::{self, BlockHeight, Key, KeySeg}; - use namada::core::time::DateTimeUtc; - use namada::core::{address, key}; - use namada::ibc::context::nft_transfer_mod::testing::DummyNftTransferModule; - use namada::ibc::context::transfer_mod::testing::DummyTransferModule; - use namada::ibc::primitives::ToProto; - use namada::ibc::Error as IbcActionError; - use namada::ledger::ibc::storage as ibc_storage; - use namada::ledger::native_vp::ibc::Error as IbcError; - use namada::ledger::tx_env::TxEnv; - use namada::token::{self, Amount}; - use namada::tx::Tx; use namada_core::storage::testing::get_dummy_header; + use namada_sdk::account::pks_handle; + use namada_sdk::hash::Hash; + use namada_sdk::ibc::context::nft_transfer_mod::testing::DummyNftTransferModule; + use namada_sdk::ibc::context::transfer_mod::testing::DummyTransferModule; + use namada_sdk::ibc::primitives::ToProto; + use namada_sdk::ibc::vp::Error as IbcError; + use namada_sdk::ibc::{storage as ibc_storage, Error as IbcActionError}; + use namada_sdk::key::*; + use namada_sdk::storage::{self, BlockHeight, Key, KeySeg}; + use namada_sdk::time::DateTimeUtc; + use namada_sdk::token::{self, Amount}; + use namada_sdk::tx::Tx; + use namada_sdk::{address, key}; use namada_test_utils::TestWasms; + use namada_tx_env::TxEnv; use namada_tx_prelude::address::InternalAddress; use namada_tx_prelude::chain::ChainId; use namada_tx_prelude::{Address, BatchedTx, StorageRead, StorageWrite}; diff --git a/crates/tests/src/vm_host_env/tx.rs b/crates/tests/src/vm_host_env/tx.rs index 594391024da..40d506be93b 100644 --- a/crates/tests/src/vm_host_env/tx.rs +++ b/crates/tests/src/vm_host_env/tx.rs @@ -2,23 +2,23 @@ use std::borrow::Borrow; use std::cell::RefCell; use std::collections::BTreeSet; -use namada::core::address::Address; -use namada::core::hash::Hash; -use namada::core::storage::{Key, TxIndex}; -use namada::core::time::DurationSecs; -use namada::ledger::gas::TxGasMeter; -use namada::ledger::parameters::{self, EpochDuration}; -use namada::ledger::storage::mockdb::MockDB; -use namada::ledger::storage::testing::TestState; -pub use namada::tx::data::TxType; -use namada::tx::Tx; -use namada::vm::prefix_iter::PrefixIterators; -use namada::vm::wasm::run::Error; -use namada::vm::wasm::{self, TxCache, VpCache}; -use namada::vm::{self, WasmCacheRwAccess}; -use namada::{account, token}; +use namada_sdk::address::Address; +use namada_sdk::gas::TxGasMeter; +use namada_sdk::hash::Hash; +use namada_sdk::parameters::{self, EpochDuration}; +use namada_sdk::state::prefix_iter::PrefixIterators; +use namada_sdk::state::testing::TestState; +use namada_sdk::storage::mockdb::MockDB; +use namada_sdk::storage::{Key, TxIndex}; +use namada_sdk::time::DurationSecs; +pub use namada_sdk::tx::data::TxType; +pub use namada_sdk::tx::*; +use namada_sdk::{account, token}; use namada_tx_prelude::transaction::TxSentinel; -use namada_tx_prelude::{BatchedTx, BorshSerializeExt, Ctx}; +use namada_tx_prelude::{BorshSerializeExt, Ctx}; +use namada_vm::wasm::run::Error; +use namada_vm::wasm::{self, TxCache, VpCache}; +use namada_vm::WasmCacheRwAccess; use namada_vp_prelude::key::common; use tempfile::TempDir; @@ -246,7 +246,7 @@ mod native_tx_host_env { // TODO replace with `std::concat_idents` once stabilized (https://github.com/rust-lang/rust/issues/29599) use concat_idents::concat_idents; - use namada::vm::host_env::*; + use namada_vm::host_env::*; use super::*; @@ -354,7 +354,7 @@ mod native_tx_host_env { batched_tx, }: &mut TestTxEnv| { - let mut tx_env = vm::host_env::testing::tx_env( + let mut tx_env = namada_vm::host_env::testing::tx_env( state, iterators, verifiers, @@ -398,7 +398,7 @@ mod native_tx_host_env { batched_tx }: &mut TestTxEnv| { - let mut tx_env = vm::host_env::testing::tx_env( + let mut tx_env = namada_vm::host_env::testing::tx_env( state, iterators, verifiers, @@ -442,7 +442,7 @@ mod native_tx_host_env { batched_tx, }: &mut TestTxEnv| { - let mut tx_env = vm::host_env::testing::tx_env( + let mut tx_env = namada_vm::host_env::testing::tx_env( state, iterators, verifiers, @@ -533,11 +533,11 @@ mod native_tx_host_env { #[cfg(test)] mod tests { - use namada::core::storage; - use namada::vm::host_env::{self, TxVmEnv}; - use namada::vm::memory::VmMemory; use namada_core::hash::Sha256Hasher; + use namada_sdk::storage; use namada_tx_prelude::StorageWrite; + use namada_vm::host_env::{self, TxVmEnv}; + use namada_vm::memory::VmMemory; use proptest::prelude::*; use test_log::test; @@ -759,7 +759,7 @@ mod tests { batched_tx, } = test_env; - let mut tx_env = vm::host_env::testing::tx_env_with_wasm_memory( + let mut tx_env = host_env::testing::tx_env_with_wasm_memory( state, iterators, verifiers, @@ -790,7 +790,7 @@ mod tests { any::(), any::(), any::(), - namada::core::storage::testing::arb_key(), + namada_sdk::storage::testing::arb_key(), arb_u64(), arb_u64(), any::>(), diff --git a/crates/tests/src/vm_host_env/vp.rs b/crates/tests/src/vm_host_env/vp.rs index 10a7bda496f..61da373650f 100644 --- a/crates/tests/src/vm_host_env/vp.rs +++ b/crates/tests/src/vm_host_env/vp.rs @@ -1,18 +1,17 @@ use std::cell::RefCell; use std::collections::BTreeSet; -use namada::core::address::{self, Address}; -use namada::core::storage::{self, Key, TxIndex}; -use namada::gas::TxGasMeter; -use namada::ledger::gas::VpGasMeter; -use namada::ledger::storage::mockdb::MockDB; -use namada::ledger::storage::testing::TestState; -use namada::tx::data::TxType; -use namada::tx::Tx; -use namada::vm::prefix_iter::PrefixIterators; -use namada::vm::wasm::{self, VpCache}; -use namada::vm::{self, WasmCacheRwAccess}; +use namada_sdk::address::{self, Address}; +use namada_sdk::gas::{TxGasMeter, VpGasMeter}; +use namada_sdk::state::mockdb::MockDB; +use namada_sdk::state::prefix_iter::PrefixIterators; +use namada_sdk::state::testing::TestState; +use namada_sdk::storage::{self, Key, TxIndex}; +use namada_sdk::tx::data::TxType; +use namada_sdk::tx::Tx; use namada_tx_prelude::BatchedTx; +use namada_vm::wasm::{self, VpCache}; +use namada_vm::WasmCacheRwAccess; use namada_vp_prelude::Ctx; use tempfile::TempDir; @@ -57,10 +56,7 @@ pub struct TestVpEnv { impl Default for TestVpEnv { fn default() -> Self { - #[cfg(feature = "wasm-runtime")] - let eval_runner = namada::vm::wasm::run::VpEvalWasm::default(); - #[cfg(not(feature = "wasm-runtime"))] - let eval_runner = native_vp_host_env::VpEval; + let eval_runner = wasm::run::VpEvalWasm::default(); let (vp_wasm_cache, vp_cache_dir) = wasm::compilation_cache::common::testing::cache(); @@ -112,19 +108,16 @@ mod native_vp_host_env { // TODO replace with `std::concat_idents` once stabilized (https://github.com/rust-lang/rust/issues/29599) use concat_idents::concat_idents; - use namada::state::StateRead; - use namada::vm::host_env::*; + use namada_sdk::state::StateRead; + use namada_vm::host_env::*; use super::*; - #[cfg(feature = "wasm-runtime")] - pub type VpEval = namada::vm::wasm::run::VpEvalWasm< + pub type VpEval = namada_vm::wasm::run::VpEvalWasm< ::D, ::H, WasmCacheRwAccess, >; - #[cfg(not(feature = "wasm-runtime"))] - pub struct VpEval; thread_local! { /// A [`TestVpEnv`] that can be used for VP host env functions calls @@ -222,26 +215,6 @@ mod native_vp_host_env { set(vp_env); } - #[cfg(not(feature = "wasm-runtime"))] - impl VpEvaluator for VpEval { - type CA = WasmCacheRwAccess; - type Db = MockDB; - type Eval = VpEval; - type H = Sha256Hasher; - - fn eval( - &self, - _ctx: VpCtx<'static, Self::Db, Self::H, Self::Eval, Self::CA>, - _vp_code_hash: Vec, - _input_data: Vec, - ) -> namada::core::internal::HostEnvResult { - unimplemented!( - "The \"wasm-runtime\" feature must be enabled to test with \ - the `eval` function." - ) - } - } - /// A helper macro to create implementations of the host environment /// functions exported to wasm, which uses the environment from the /// `ENV` variable. @@ -267,7 +240,7 @@ mod native_vp_host_env { vp_cache_dir: _, }: &mut TestVpEnv| { - let mut env = vm::host_env::testing::vp_env( + let mut env = namada_vm::host_env::testing::vp_env( addr, state, iterators, @@ -312,7 +285,7 @@ mod native_vp_host_env { vp_cache_dir: _, }: &mut TestVpEnv| { - let mut env = vm::host_env::testing::vp_env( + let mut env = namada_vm::host_env::testing::vp_env( addr, state, iterators, diff --git a/crates/token/Cargo.toml b/crates/token/Cargo.toml index 175f73b54ad..97ac5f71038 100644 --- a/crates/token/Cargo.toml +++ b/crates/token/Cargo.toml @@ -32,5 +32,6 @@ serde.workspace = true [dev-dependencies] namada_core = { path = "../core", features = ["testing"] } +namada_shielded_token = { path = "../shielded_token", features = ["testing"] } proptest.workspace = true diff --git a/crates/token/src/lib.rs b/crates/token/src/lib.rs index 903c61701fe..289f4f4708c 100644 --- a/crates/token/src/lib.rs +++ b/crates/token/src/lib.rs @@ -25,7 +25,6 @@ pub use namada_shielded_token::*; pub use namada_trans_token::*; /// Validity predicates -#[cfg(any(test, feature = "validation", feature = "testing"))] pub mod vp { pub use namada_shielded_token::vp::{ Error as MaspError, MaspVp, Result as MaspResult, diff --git a/crates/trans_token/src/vp.rs b/crates/trans_token/src/vp.rs index 29b7eebca15..dc232c5c89f 100644 --- a/crates/trans_token/src/vp.rs +++ b/crates/trans_token/src/vp.rs @@ -46,38 +46,38 @@ pub enum Error { pub type Result = std::result::Result; /// Multitoken VP -pub struct MultitokenVp<'a, S, CA, EVAL, Params, Gov> +pub struct MultitokenVp<'ctx, S, CA, EVAL, Params, Gov> where S: 'static + StateRead, - EVAL: VpEvaluator<'a, S, CA, EVAL>, + EVAL: VpEvaluator<'ctx, S, CA, EVAL>, { /// Context to interact with the host structures. - pub ctx: Ctx<'a, S, CA, EVAL>, + pub ctx: Ctx<'ctx, S, CA, EVAL>, /// Parameters type pub params: PhantomData, /// Governance type pub gov: PhantomData, } -impl<'a, S, CA, EVAL, Params, Gov> NativeVp<'a> - for MultitokenVp<'a, S, CA, EVAL, Params, Gov> +impl<'view, 'ctx: 'view, S, CA, EVAL, Params, Gov> NativeVp<'view> + for MultitokenVp<'ctx, S, CA, EVAL, Params, Gov> where S: 'static + StateRead, CA: 'static + Clone, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, Params: parameters::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, Gov: governance::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, { type Error = Error; fn validate_tx( - &'a self, + &'view self, tx_data: &BatchedTxRef<'_>, keys_changed: &BTreeSet, verifiers: &BTreeSet
, @@ -296,22 +296,23 @@ where } } -impl<'a, S, CA, EVAL, Params, Gov> MultitokenVp<'a, S, CA, EVAL, Params, Gov> +impl<'view, 'ctx: 'view, S, CA, EVAL, Params, Gov> + MultitokenVp<'ctx, S, CA, EVAL, Params, Gov> where S: 'static + StateRead, CA: 'static + Clone, - EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, + EVAL: 'static + VpEvaluator<'ctx, S, CA, EVAL>, Params: parameters::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, Gov: governance::Read< - CtxPreStorageRead<'a, 'a, S, CA, EVAL>, + CtxPreStorageRead<'view, 'ctx, S, CA, EVAL>, Err = StorageError, >, { /// Instantiate token VP - pub fn new(ctx: Ctx<'a, S, CA, EVAL>) -> Self { + pub fn new(ctx: Ctx<'ctx, S, CA, EVAL>) -> Self { Self { ctx, params: PhantomData, @@ -356,7 +357,7 @@ where /// Return if the parameter change was done via a governance proposal pub fn is_valid_parameter( - &'a self, + &'view self, batched_tx: &BatchedTxRef<'_>, ) -> Result<()> { batched_tx.tx.data(batched_tx.cmt).map_or_else( @@ -441,7 +442,6 @@ mod tests { }; use namada_core::borsh::BorshSerializeExt; use namada_core::key::testing::keypair_1; - use namada_core::WasmCacheRwAccess; use namada_gas::{TxGasMeter, VpGasMeter}; use namada_ibc::storage::ibc_token; use namada_parameters::storage::get_native_token_transferable_key; @@ -454,6 +454,7 @@ mod tests { use namada_vm::wasm::compilation_cache::common::testing::vp_cache; use namada_vm::wasm::run::VpEvalWasm; use namada_vm::wasm::VpCache; + use namada_vm::WasmCacheRwAccess; use super::*; use crate::storage_key::{balance_key, minted_balance_key}; @@ -466,17 +467,17 @@ mod tests { ::H, CA, >; - type Ctx<'a> = super::Ctx<'a, TestState, VpCache, Eval>; - type MultitokenVp<'a> = super::MultitokenVp< - 'a, + type Ctx<'ctx> = super::Ctx<'ctx, TestState, VpCache, Eval>; + type MultitokenVp<'ctx> = super::MultitokenVp< + 'ctx, TestState, VpCache, Eval, namada_parameters::Store< - CtxPreStorageRead<'a, 'a, TestState, VpCache, Eval>, + CtxPreStorageRead<'ctx, 'ctx, TestState, VpCache, Eval>, >, namada_governance::Store< - CtxPreStorageRead<'a, 'a, TestState, VpCache, Eval>, + CtxPreStorageRead<'ctx, 'ctx, TestState, VpCache, Eval>, >, >; diff --git a/crates/tx_prelude/Cargo.toml b/crates/tx_prelude/Cargo.toml index 83f5423f690..7ee9be6fea5 100644 --- a/crates/tx_prelude/Cargo.toml +++ b/crates/tx_prelude/Cargo.toml @@ -20,6 +20,7 @@ testing = ["namada_core/testing", "namada_token/testing"] namada_account = { path = "../account" } namada_core = { path = "../core" } namada_events = { path = "../events", default-features = false } +namada_gas = { path = "../gas" } namada_governance = { path = "../governance" } namada_ibc = { path = "../ibc" } namada_macros = { path = "../macros" } diff --git a/crates/tx_prelude/src/ibc.rs b/crates/tx_prelude/src/ibc.rs index 6b5b0c5e69a..a53934760e7 100644 --- a/crates/tx_prelude/src/ibc.rs +++ b/crates/tx_prelude/src/ibc.rs @@ -34,7 +34,7 @@ pub fn ibc_actions(ctx: &mut Ctx) -> IbcActions<'_, Ctx> { actions } -impl<'s> IbcStorageContext for Ctx { +impl IbcStorageContext for Ctx { type Storage = Self; fn storage(&self) -> &Self::Storage { diff --git a/crates/tx_prelude/src/lib.rs b/crates/tx_prelude/src/lib.rs index 3b737c81570..80a950c2b98 100644 --- a/crates/tx_prelude/src/lib.rs +++ b/crates/tx_prelude/src/lib.rs @@ -50,7 +50,10 @@ pub use namada_tx::{action, data as transaction, BatchedTx, Section, Tx}; pub use namada_tx_env::TxEnv; use namada_vm_env::tx::*; use namada_vm_env::{read_from_buffer, read_key_val_bytes_from_buffer}; -pub use {namada_governance as governance, namada_parameters as parameters}; +pub use { + namada_gas as gas, namada_governance as governance, + namada_parameters as parameters, +}; /// Log a string. The message will be printed at the `tracing::Level::Info`. pub fn log_string>(msg: T) { diff --git a/crates/tx_prelude/src/proof_of_stake.rs b/crates/tx_prelude/src/proof_of_stake.rs index 97ed43735cb..72b376a1841 100644 --- a/crates/tx_prelude/src/proof_of_stake.rs +++ b/crates/tx_prelude/src/proof_of_stake.rs @@ -12,7 +12,7 @@ use namada_proof_of_stake::{ claim_reward_tokens, deactivate_validator, reactivate_validator, redelegate_tokens, unbond_tokens, unjail_validator, withdraw_tokens, }; -pub use namada_proof_of_stake::{parameters, types}; +pub use namada_proof_of_stake::{parameters, storage, storage_key, types}; use namada_tx::action::{ Action, ClaimRewards, PosAction, Redelegation, Unbond, Withdraw, Write, }; diff --git a/crates/vm/Cargo.toml b/crates/vm/Cargo.toml index a8e94313ab6..04ee114914a 100644 --- a/crates/vm/Cargo.toml +++ b/crates/vm/Cargo.toml @@ -29,11 +29,10 @@ testing = [ ] [dependencies] -namada_core = { path = "../core" } +namada_core = { path = "../core", features = ["control_flow"] } namada_events = { path = "../events", default-features = false } namada_gas = { path = "../gas" } namada_parameters = { path = "../parameters" } -namada_sdk = { path = "../sdk" } namada_state = { path = "../state" } namada_token = { path = "../token" } namada_tx = { path = "../tx" } diff --git a/crates/vm/src/host_env.rs b/crates/vm/src/host_env.rs index 2008a3820b3..2d34bcd07ab 100644 --- a/crates/vm/src/host_env.rs +++ b/crates/vm/src/host_env.rs @@ -12,7 +12,6 @@ use namada_core::borsh::{BorshDeserialize, BorshSerializeExt}; use namada_core::hash::Hash; use namada_core::internal::{HostEnvResult, KeyVal}; use namada_core::storage::{BlockHeight, Key, TxIndex, TX_INDEX_LENGTH}; -use namada_core::WasmCacheAccess; use namada_events::{Event, EventTypeBuilder}; use namada_gas::{ self as gas, GasMetering, TxGasMeter, VpGasMeter, @@ -35,9 +34,12 @@ use namada_tx::{BatchedTx, BatchedTxRef, Tx, TxCommitments}; use namada_vp::vp_host_fns; use thiserror::Error; +#[cfg(feature = "wasm-runtime")] use super::wasm::{TxCache, VpCache}; use crate::memory::VmMemory; -use crate::{HostRef, RoAccess, RoHostRef, RwAccess, RwHostRef}; +use crate::{ + HostRef, RoAccess, RoHostRef, RwAccess, RwHostRef, WasmCacheAccess, +}; /// These runtime errors will abort tx WASM execution immediately #[allow(missing_docs)] @@ -131,9 +133,14 @@ where pub yielded_value: HostRef>>, /// VP WASM compilation cache (this is available in tx context, because /// we're pre-compiling VPs from [`tx_init_account`]) + #[cfg(feature = "wasm-runtime")] pub vp_wasm_cache: HostRef>, /// Tx WASM compilation cache + #[cfg(feature = "wasm-runtime")] pub tx_wasm_cache: HostRef>, + /// To avoid unused parameter without "wasm-runtime" feature + #[cfg(not(feature = "wasm-runtime"))] + pub cache_access: std::marker::PhantomData, } impl TxVmEnv @@ -164,8 +171,8 @@ where verifiers: &mut BTreeSet
, result_buffer: &mut Option>, yielded_value: &mut Option>, - vp_wasm_cache: &mut VpCache, - tx_wasm_cache: &mut TxCache, + #[cfg(feature = "wasm-runtime")] vp_wasm_cache: &mut VpCache, + #[cfg(feature = "wasm-runtime")] tx_wasm_cache: &mut TxCache, ) -> Self { let write_log = unsafe { RwHostRef::new(write_log) }; let in_mem = unsafe { RoHostRef::new(in_mem) }; @@ -179,7 +186,9 @@ where let verifiers = unsafe { RwHostRef::new(verifiers) }; let result_buffer = unsafe { RwHostRef::new(result_buffer) }; let yielded_value = unsafe { RwHostRef::new(yielded_value) }; + #[cfg(feature = "wasm-runtime")] let vp_wasm_cache = unsafe { RwHostRef::new(vp_wasm_cache) }; + #[cfg(feature = "wasm-runtime")] let tx_wasm_cache = unsafe { RwHostRef::new(tx_wasm_cache) }; let ctx = TxCtx { write_log, @@ -194,8 +203,12 @@ where verifiers, result_buffer, yielded_value, + #[cfg(feature = "wasm-runtime")] vp_wasm_cache, + #[cfg(feature = "wasm-runtime")] tx_wasm_cache, + #[cfg(not(feature = "wasm-runtime"))] + cache_access: std::marker::PhantomData, }; Self { memory, ctx } @@ -274,8 +287,12 @@ where verifiers: self.verifiers, result_buffer: self.result_buffer, yielded_value: self.yielded_value, + #[cfg(feature = "wasm-runtime")] vp_wasm_cache: self.vp_wasm_cache, + #[cfg(feature = "wasm-runtime")] tx_wasm_cache: self.tx_wasm_cache, + #[cfg(not(feature = "wasm-runtime"))] + cache_access: std::marker::PhantomData, } } } @@ -333,7 +350,11 @@ where /// calls to `eval`. pub verifiers: HostRef>, /// VP WASM compilation cache + #[cfg(feature = "wasm-runtime")] pub vp_wasm_cache: HostRef>, + /// To avoid unused parameter without "wasm-runtime" feature + #[cfg(not(feature = "wasm-runtime"))] + pub cache_access: std::marker::PhantomData, } /// A Validity predicate runner for calls from the [`vp_eval`] function. @@ -391,7 +412,7 @@ where yielded_value: &mut Option>, keys_changed: &BTreeSet, eval_runner: &EVAL, - vp_wasm_cache: &mut VpCache, + #[cfg(feature = "wasm-runtime")] vp_wasm_cache: &mut VpCache, ) -> Self { let ctx = VpCtx::new( address, @@ -408,6 +429,7 @@ where yielded_value, keys_changed, eval_runner, + #[cfg(feature = "wasm-runtime")] vp_wasm_cache, ); @@ -466,7 +488,7 @@ where yielded_value: &mut Option>, keys_changed: &BTreeSet, eval_runner: &EVAL, - vp_wasm_cache: &mut VpCache, + #[cfg(feature = "wasm-runtime")] vp_wasm_cache: &mut VpCache, ) -> Self { let address = unsafe { RoHostRef::new(address) }; let write_log = unsafe { RoHostRef::new(write_log) }; @@ -482,6 +504,7 @@ where let yielded_value = unsafe { RwHostRef::new(yielded_value) }; let keys_changed = unsafe { RoHostRef::new(keys_changed) }; let eval_runner = unsafe { RoHostRef::new(eval_runner) }; + #[cfg(feature = "wasm-runtime")] let vp_wasm_cache = unsafe { RwHostRef::new(vp_wasm_cache) }; Self { address, @@ -498,7 +521,10 @@ where yielded_value, keys_changed, verifiers, + #[cfg(feature = "wasm-runtime")] vp_wasm_cache, + #[cfg(not(feature = "wasm-runtime"))] + cache_access: std::marker::PhantomData, } } @@ -546,7 +572,10 @@ where yielded_value: self.yielded_value, keys_changed: self.keys_changed, verifiers: self.verifiers, + #[cfg(feature = "wasm-runtime")] vp_wasm_cache: self.vp_wasm_cache, + #[cfg(not(feature = "wasm-runtime"))] + cache_access: std::marker::PhantomData, } } } @@ -2368,8 +2397,8 @@ pub mod testing { tx_index: &TxIndex, result_buffer: &mut Option>, yielded_value: &mut Option>, - vp_wasm_cache: &mut VpCache, - tx_wasm_cache: &mut TxCache, + #[cfg(feature = "wasm-runtime")] vp_wasm_cache: &mut VpCache, + #[cfg(feature = "wasm-runtime")] tx_wasm_cache: &mut TxCache, ) -> TxVmEnv::D, ::H, CA> where S: State, @@ -2390,7 +2419,9 @@ pub mod testing { verifiers, result_buffer, yielded_value, + #[cfg(feature = "wasm-runtime")] vp_wasm_cache, + #[cfg(feature = "wasm-runtime")] tx_wasm_cache, ) } @@ -2408,8 +2439,8 @@ pub mod testing { tx_index: &TxIndex, result_buffer: &mut Option>, yielded_value: &mut Option>, - vp_wasm_cache: &mut VpCache, - tx_wasm_cache: &mut TxCache, + #[cfg(feature = "wasm-runtime")] vp_wasm_cache: &mut VpCache, + #[cfg(feature = "wasm-runtime")] tx_wasm_cache: &mut TxCache, ) -> TxVmEnv::D, ::H, CA> where S: State, @@ -2435,7 +2466,9 @@ pub mod testing { verifiers, result_buffer, yielded_value, + #[cfg(feature = "wasm-runtime")] vp_wasm_cache, + #[cfg(feature = "wasm-runtime")] tx_wasm_cache, ); @@ -2458,7 +2491,7 @@ pub mod testing { yielded_value: &mut Option>, keys_changed: &BTreeSet, eval_runner: &EVAL, - vp_wasm_cache: &mut VpCache, + #[cfg(feature = "wasm-runtime")] vp_wasm_cache: &mut VpCache, ) -> VpVmEnv::D, ::H, EVAL, CA> where S: StateRead, @@ -2481,6 +2514,7 @@ pub mod testing { yielded_value, keys_changed, eval_runner, + #[cfg(feature = "wasm-runtime")] vp_wasm_cache, ) } diff --git a/crates/vm/src/lib.rs b/crates/vm/src/lib.rs index 9489052eaa1..d2866119f25 100644 --- a/crates/vm/src/lib.rs +++ b/crates/vm/src/lib.rs @@ -61,6 +61,32 @@ pub enum WasmValidationError { ForbiddenWasmFeatures(wasmparser::BinaryReaderError), } +/// WASM Cache access level, used to limit dry-ran transactions to read-only +/// cache access. +pub trait WasmCacheAccess: Clone + std::fmt::Debug + Default { + /// Is access read/write? + fn is_read_write() -> bool; +} + +/// Regular read/write caches access +#[derive(Debug, Clone, Default)] +pub struct WasmCacheRwAccess; +impl WasmCacheAccess for WasmCacheRwAccess { + fn is_read_write() -> bool { + true + } +} + +/// Restricted read-only access for dry-ran transactions +#[derive(Debug, Clone, Default)] +pub struct WasmCacheRoAccess; + +impl WasmCacheAccess for WasmCacheRoAccess { + fn is_read_write() -> bool { + false + } +} + /// Read-only access to host data. #[derive(Debug)] pub enum RoAccess {} diff --git a/crates/vm/src/wasm/compilation_cache/common.rs b/crates/vm/src/wasm/compilation_cache/common.rs index dd8b2b0debb..e54491324b8 100644 --- a/crates/vm/src/wasm/compilation_cache/common.rs +++ b/crates/vm/src/wasm/compilation_cache/common.rs @@ -14,14 +14,14 @@ use std::time::Duration; use clru::{CLruCache, CLruCacheConfig, WeightScale}; use namada_core::collections::HashMap; +use namada_core::control_flow::time::{ExponentialBackoff, SleepStrategy}; use namada_core::hash::Hash; -use namada_core::{WasmCacheAccess, WasmCacheRoAccess}; -use namada_sdk::control_flow::time::{ExponentialBackoff, SleepStrategy}; use wasmer::{Module, Store}; use wasmer_cache::{FileSystemCache, Hash as CacheHash}; use crate::wasm::run::untrusted_wasm_store; use crate::wasm::{self, memory}; +use crate::{WasmCacheAccess, WasmCacheRoAccess}; /// Cache handle. Thread-safe. #[derive(Debug, Clone)] @@ -580,11 +580,11 @@ mod universal { /// Testing helpers #[cfg(any(test, feature = "testing"))] pub mod testing { - use namada_core::WasmCacheRwAccess; use tempfile::{tempdir, TempDir}; use super::*; use crate::wasm::{TxCache, VpCache}; + use crate::WasmCacheRwAccess; /// VP Cache with a temp dir for testing pub fn vp_cache() -> (VpCache, TempDir) { @@ -614,12 +614,12 @@ mod test { use assert_matches::assert_matches; use byte_unit::Byte; - use namada_core::WasmCacheRwAccess; use namada_test_utils::TestWasms; use tempfile::{tempdir, TempDir}; use test_log::test; use super::*; + use crate::WasmCacheRwAccess; #[test] fn test_fetch_or_compile_valid_wasm() { diff --git a/crates/vm/src/wasm/host_env.rs b/crates/vm/src/wasm/host_env.rs index fdc4e7089b7..ba36f12d766 100644 --- a/crates/vm/src/wasm/host_env.rs +++ b/crates/vm/src/wasm/host_env.rs @@ -3,13 +3,12 @@ //! Here, we expose the host functions into wasm's //! imports, so they can be called from inside the wasm. -use namada_core::WasmCacheAccess; use namada_state::{DBIter, StorageHasher, DB}; use wasmer::{Function, FunctionEnv, Imports}; -use crate::host_env; use crate::host_env::{TxVmEnv, VpEvaluator, VpVmEnv}; use crate::wasm::memory::WasmMemory; +use crate::{host_env, WasmCacheAccess}; /// Prepare imports (memory and host functions) exposed to the vm guest running /// transaction code @@ -114,12 +113,12 @@ mod wrap_tx { #![allow(missing_docs)] - use namada_core::WasmCacheAccess; use namada_state::{DBIter, StorageHasher, DB}; use wasmer::FunctionEnvMut; use crate::host_env::TxVmEnv; use crate::wasm::memory::WasmMemory; + use crate::WasmCacheAccess; pub(super) fn _0( f: F, @@ -267,12 +266,12 @@ mod wrap_vp { #![allow(missing_docs)] - use namada_core::WasmCacheAccess; use namada_state::{DBIter, StorageHasher, DB}; use wasmer::FunctionEnvMut; use crate::host_env::{VpEvaluator, VpVmEnv}; use crate::wasm::memory::WasmMemory; + use crate::WasmCacheAccess; pub(super) fn _0( f: F, diff --git a/crates/vm/src/wasm/memory.rs b/crates/vm/src/wasm/memory.rs index a32d13031f1..ae4b3defee0 100644 --- a/crates/vm/src/wasm/memory.rs +++ b/crates/vm/src/wasm/memory.rs @@ -6,9 +6,9 @@ use std::ptr::NonNull; use std::rc::Rc; use std::str::Utf8Error; +use namada_core::arith::{self, checked}; use namada_core::borsh::BorshSerializeExt; use namada_gas::MEMORY_ACCESS_GAS_PER_BYTE; -use namada_sdk::arith::{self, checked}; use namada_tx::BatchedTxRef; use thiserror::Error; use wasmer::sys::BaseTunables; diff --git a/crates/vm/src/wasm/run.rs b/crates/vm/src/wasm/run.rs index 4297efc7685..f7dadcb55db 100644 --- a/crates/vm/src/wasm/run.rs +++ b/crates/vm/src/wasm/run.rs @@ -14,7 +14,6 @@ use namada_core::hash::{Error as TxHashError, Hash}; use namada_core::internal::HostEnvResult; use namada_core::storage::{Key, TxIndex}; use namada_core::validity_predicate::VpError; -use namada_core::WasmCacheAccess; use namada_gas::{GasMetering, TxGasMeter, VpGasMeter, WASM_MEMORY_PAGE_GAS}; use namada_state::prefix_iter::PrefixIterators; use namada_state::{DBIter, State, StateRead, StorageHasher, StorageRead, DB}; @@ -33,7 +32,10 @@ use crate::host_env::{TxVmEnv, VpCtx, VpEvaluator, VpVmEnv}; use crate::types::VpInput; use crate::wasm::host_env::{tx_imports, vp_imports}; use crate::wasm::{memory, Cache, CacheName, VpCache}; -use crate::{validate_untrusted_wasm, HostRef, RwAccess, WasmValidationError}; +use crate::{ + validate_untrusted_wasm, HostRef, RwAccess, WasmCacheAccess, + WasmValidationError, +}; const TX_ENTRYPOINT: &str = "_apply_tx"; const VP_ENTRYPOINT: &str = "_validate_tx"; @@ -996,8 +998,8 @@ mod tests { use assert_matches::assert_matches; use itertools::Either; + use namada_core::arith::checked; use namada_core::borsh::BorshSerializeExt; - use namada_sdk::arith::checked; use namada_state::testing::TestState; use namada_state::StorageWrite; use namada_test_utils::TestWasms; diff --git a/crates/vp/src/native_vp.rs b/crates/vp/src/native_vp.rs index dd6dccb1f31..dde8eafb58c 100644 --- a/crates/vp/src/native_vp.rs +++ b/crates/vp/src/native_vp.rs @@ -47,13 +47,13 @@ pub trait NativeVp<'a> { /// A validity predicate's host context. /// -/// This is similar to [`crate::vm::host_env::VpCtx`], but without the VM +/// This is similar to `namada_vm::host_env::VpCtx`, but without the VM /// wrapper types and `eval_runner` field. The references must not be changed /// when [`Ctx`] is mutable. #[derive(Debug)] pub struct Ctx<'a, S, CA, EVAL> where - S: 'static + StateRead, + S: StateRead, EVAL: VpEvaluator<'a, S, CA, EVAL>, { /// The address of the account that owns the VP @@ -82,10 +82,10 @@ where pub eval: PhantomData, } -/// A Validity predicate runner for calls from the [`vp_eval`] function. +/// A Validity predicate runner for calls from the host env `vp_eval` function. pub trait VpEvaluator<'a, S, CA, EVAL> where - S: 'static + StateRead, + S: 'a + StateRead, EVAL: VpEvaluator<'a, S, CA, EVAL>, { /// Evaluate a given validity predicate code with the given input data. @@ -105,7 +105,7 @@ where #[derive(Debug)] pub struct CtxPreStorageRead<'view, 'a, S, CA, EVAL> where - S: 'static + StateRead, + S: StateRead, EVAL: VpEvaluator<'a, S, CA, EVAL>, { /// The inner context @@ -117,7 +117,7 @@ where #[derive(Debug)] pub struct CtxPostStorageRead<'view, 'a, S, CA, EVAL> where - S: 'static + StateRead, + S: StateRead, EVAL: VpEvaluator<'a, S, CA, EVAL>, { /// The inner context @@ -126,7 +126,7 @@ where impl<'a, S, CA, EVAL> Ctx<'a, S, CA, EVAL> where - S: 'static + StateRead, + S: StateRead, EVAL: VpEvaluator<'a, S, CA, EVAL>, CA: 'static + Clone, { @@ -178,7 +178,7 @@ where impl<'view, 'a: 'view, S, CA, EVAL> StorageRead for CtxPreStorageRead<'view, 'a, S, CA, EVAL> where - S: 'static + StateRead, + S: StateRead, EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, CA: 'static + Clone, { @@ -256,7 +256,7 @@ where impl<'view, 'a: 'view, S, CA, EVAL> StorageRead for CtxPostStorageRead<'view, 'a, S, CA, EVAL> where - S: 'static + StateRead, + S: StateRead, EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, CA: 'static + Clone, { @@ -333,7 +333,7 @@ where impl<'view, 'a: 'view, S, CA, EVAL> VpEnv<'view> for Ctx<'a, S, CA, EVAL> where - S: 'static + StateRead, + S: 'a + StateRead, EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, CA: 'static + Clone, { @@ -490,7 +490,7 @@ where impl<'a, S, CA, EVAL> namada_tx::action::Read for Ctx<'a, S, CA, EVAL> where - S: 'static + StateRead, + S: StateRead, EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, CA: 'static + Clone, { @@ -553,7 +553,7 @@ pub trait StorageReader { impl<'a, S, CA, EVAL> StorageReader for &Ctx<'a, S, CA, EVAL> where - S: 'static + StateRead, + S: StateRead, EVAL: 'static + VpEvaluator<'a, S, CA, EVAL>, CA: 'static + Clone, { diff --git a/examples/Cargo.toml b/examples/Cargo.toml index 1720015a94c..9f9c30f10bb 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -35,7 +35,7 @@ namada_macros = {path = "../crates/macros"} namada_migrations = {path = "../crates/migrations"} namada_parameters = { path = "../crates/parameters"} namada_trans_token = {path = "../crates/trans_token", features = ["migrations"]} -namada_sdk = { path = "../crates/sdk", default-features = false, features = ["namada-sdk", "std", "testing", "migrations"] } +namada_sdk = { path = "../crates/sdk", default-features = false, features = ["std", "testing", "migrations"] } namada_shielded_token = { path = "../crates/shielded_token" } borsh.workspace = true diff --git a/wasm/Cargo.lock b/wasm/Cargo.lock index b2c96152ed9..9f5327f7254 100644 --- a/wasm/Cargo.lock +++ b/wasm/Cargo.lock @@ -477,9 +477,9 @@ dependencies = [ [[package]] name = "blake3" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0231f06152bf547e9c2b5194f247cd97aacf6dcd8b15d8e5ec0663f64580da87" +checksum = "30cca6d3674597c30ddf2c587bf8d9d65c9a84d2326d941cc79c9842dfe0ef52" dependencies = [ "arrayref", "arrayvec", @@ -626,9 +626,9 @@ checksum = "c3ac9f8b63eca6fd385229b3675f6cc0dc5c8a5c8a54a59d4f52ffd670d87b0c" [[package]] name = "bytecheck" -version = "0.6.11" +version = "0.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b6372023ac861f6e6dc89c8344a8f398fb42aaba2b5dbc649ca0c0e9dbcb627" +checksum = "23cdc57ce23ac53c931e88a43d06d070a6fd142f2617be5855eb75efc9beb1c2" dependencies = [ "bytecheck_derive", "ptr_meta", @@ -637,9 +637,9 @@ dependencies = [ [[package]] name = "bytecheck_derive" -version = "0.6.11" +version = "0.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7ec4c6f261935ad534c0c22dbef2201b45918860eb1c574b972bd213a76af61" +checksum = "3db406d29fbcd95542e92559bed4d8ad92636d1ca8b3b72ede10b4bcc010e659" dependencies = [ "proc-macro2", "quote", @@ -1086,9 +1086,9 @@ checksum = "393bc73c451830ff8dbb3a07f61843d6cb41a084f9996319917c0b291ed785bb" [[package]] name = "crc32fast" -version = "1.3.2" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" +checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" dependencies = [ "cfg-if", ] @@ -1234,12 +1234,12 @@ dependencies = [ [[package]] name = "darling" -version = "0.20.3" +version = "0.20.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0209d94da627ab5605dcccf08bb18afa5009cfbef48d8a8b7d7bdbc79be25c5e" +checksum = "83b2eb4d90d12bdda5ed17de686c2acb4c57914f8f921b8da7e112b5a36f3fe1" dependencies = [ - "darling_core 0.20.3", - "darling_macro 0.20.3", + "darling_core 0.20.9", + "darling_macro 0.20.9", ] [[package]] @@ -1258,9 +1258,9 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.20.3" +version = "0.20.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "177e3443818124b357d8e76f53be906d60937f0d3a90773a664fa63fa253e621" +checksum = "622687fe0bac72a04e5599029151f5796111b90f1baaa9b544d807a5e31cd120" dependencies = [ "fnv", "ident_case", @@ -1282,11 +1282,11 @@ dependencies = [ [[package]] name = "darling_macro" -version = "0.20.3" +version = "0.20.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" +checksum = "733cabb43482b1a1b53eee8583c2b9e8684d592215ea83efd305dd31bc2f0178" dependencies = [ - "darling_core 0.20.3", + "darling_core 0.20.9", "quote", "syn 2.0.52", ] @@ -1644,7 +1644,7 @@ version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e08b6c6ab82d70f08844964ba10c7babb716de2ecaeab9be5717918a5177d3af" dependencies = [ - "darling 0.20.3", + "darling 0.20.9", "proc-macro2", "quote", "syn 2.0.52", @@ -3427,26 +3427,6 @@ dependencies = [ "redox_syscall", ] -[[package]] -name = "linkme" -version = "0.3.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb2cfee0de9bd869589fb9a015e155946d1be5ff415cb844c2caccc6cc4b5db9" -dependencies = [ - "linkme-impl", -] - -[[package]] -name = "linkme-impl" -version = "0.3.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adf157a4dc5a29b7b464aa8fe7edeff30076e07e13646a1c3874f58477dc99f8" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.52", -] - [[package]] name = "linux-raw-sys" version = "0.4.12" @@ -3484,6 +3464,15 @@ dependencies = [ "libc", ] +[[package]] +name = "mach2" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b955cdeb2a02b9117f121ce63aa52d08ade45de53e48fe6a38b39c10f6f709" +dependencies = [ + "libc", +] + [[package]] name = "masp_note_encryption" version = "1.0.0" @@ -3661,71 +3650,13 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a" -[[package]] -name = "namada" -version = "0.39.0" -dependencies = [ - "async-trait", - "borsh 1.4.0", - "borsh-ext", - "clru", - "ethers", - "eyre", - "itertools 0.12.1", - "linkme", - "masp_primitives", - "masp_proofs", - "namada_account", - "namada_core", - "namada_ethereum_bridge", - "namada_events", - "namada_gas", - "namada_governance", - "namada_ibc", - "namada_migrations", - "namada_parameters", - "namada_proof_of_stake", - "namada_replay_protection", - "namada_sdk", - "namada_state", - "namada_token", - "namada_tx", - "namada_tx_env", - "namada_vote_ext", - "namada_vp_env", - "parity-wasm", - "proptest", - "prost", - "rand 0.8.5", - "rayon", - "ripemd", - "serde_json", - "sha2 0.9.9", - "smooth-operator", - "tempfile", - "thiserror", - "tiny-bip39", - "tokio", - "tracing", - "uint", - "wasm-instrument", - "wasmer", - "wasmer-cache", - "wasmer-compiler-singlepass", - "wasmer-vm", - "wasmparser 0.107.0", - "wasmtimer", -] - [[package]] name = "namada_account" version = "0.39.0" dependencies = [ "borsh 1.4.0", - "linkme", "namada_core", "namada_macros", - "namada_migrations", "namada_storage", "proptest", "serde", @@ -3753,16 +3684,15 @@ dependencies = [ "ethabi", "ethbridge-structs", "eyre", + "futures", "ibc", "ics23", "impl-num-traits", "index-set", "indexmap 2.2.4", "k256", - "linkme", "masp_primitives", "namada_macros", - "namada_migrations", "num-integer", "num-rational", "num-traits 0.2.17", @@ -3782,8 +3712,10 @@ dependencies = [ "tendermint-proto 0.36.0", "thiserror", "tiny-keccak", + "tokio", "tracing", "uint", + "wasmtimer", "zeroize", ] @@ -3796,12 +3728,10 @@ dependencies = [ "eyre", "itertools 0.12.1", "konst", - "linkme", "namada_account", "namada_core", "namada_events", "namada_macros", - "namada_migrations", "namada_parameters", "namada_proof_of_stake", "namada_state", @@ -3821,10 +3751,8 @@ name = "namada_events" version = "0.39.0" dependencies = [ "borsh 1.4.0", - "linkme", "namada_core", "namada_macros", - "namada_migrations", "serde", "serde_json", "thiserror", @@ -3836,11 +3764,9 @@ name = "namada_gas" version = "0.39.0" dependencies = [ "borsh 1.4.0", - "linkme", "namada_core", "namada_events", "namada_macros", - "namada_migrations", "serde", "thiserror", ] @@ -3852,12 +3778,10 @@ dependencies = [ "borsh 1.4.0", "itertools 0.12.1", "konst", - "linkme", "namada_account", "namada_core", "namada_events", "namada_macros", - "namada_migrations", "namada_parameters", "namada_state", "namada_trans_token", @@ -3929,22 +3853,16 @@ dependencies = [ "thiserror", ] -[[package]] -name = "namada_migrations" -version = "0.39.0" -dependencies = [ - "lazy_static", - "linkme", - "namada_macros", -] - [[package]] name = "namada_parameters" version = "0.39.0" dependencies = [ "namada_core", "namada_macros", + "namada_state", "namada_storage", + "namada_tx", + "namada_vp", "thiserror", ] @@ -3953,18 +3871,20 @@ name = "namada_proof_of_stake" version = "0.39.0" dependencies = [ "borsh 1.4.0", + "itertools 0.12.1", "konst", - "linkme", "namada_account", "namada_controller", "namada_core", "namada_events", "namada_governance", "namada_macros", - "namada_migrations", "namada_parameters", + "namada_state", "namada_storage", "namada_trans_token", + "namada_tx", + "namada_vp", "once_cell", "proptest", "serde", @@ -4000,7 +3920,6 @@ dependencies = [ "itertools 0.12.1", "jubjub", "lazy_static", - "linkme", "masp_primitives", "masp_proofs", "namada_account", @@ -4011,14 +3930,15 @@ dependencies = [ "namada_governance", "namada_ibc", "namada_macros", - "namada_migrations", "namada_parameters", "namada_proof_of_stake", "namada_state", "namada_storage", "namada_token", "namada_tx", + "namada_vm", "namada_vote_ext", + "namada_vp", "num-traits 0.2.17", "num256", "orion", @@ -4043,7 +3963,6 @@ dependencies = [ "tokio", "toml 0.5.11", "tracing", - "wasmtimer", "zeroize", ] @@ -4055,16 +3974,23 @@ dependencies = [ "lazy_static", "masp_primitives", "masp_proofs", + "namada_account", "namada_controller", "namada_core", "namada_gas", "namada_parameters", + "namada_state", "namada_storage", "namada_trans_token", + "namada_tx", + "namada_vp", "rand_core 0.6.4", "rayon", + "ripemd", "serde", + "sha2 0.9.9", "smooth-operator", + "thiserror", "tracing", ] @@ -4074,13 +4000,11 @@ version = "0.39.0" dependencies = [ "borsh 1.4.0", "itertools 0.12.1", - "linkme", "namada_core", "namada_events", "namada_gas", "namada_macros", "namada_merkle_tree", - "namada_migrations", "namada_replay_protection", "namada_storage", "namada_tx", @@ -4097,11 +4021,9 @@ version = "0.39.0" dependencies = [ "borsh 1.4.0", "itertools 0.12.1", - "linkme", "namada_core", "namada_macros", "namada_merkle_tree", - "namada_migrations", "namada_replay_protection", "regex", "serde", @@ -4129,11 +4051,13 @@ dependencies = [ "ibc-testkit", "ics23", "itertools 0.12.1", - "namada", "namada_core", "namada_sdk", "namada_test_utils", + "namada_tx_env", "namada_tx_prelude", + "namada_vm", + "namada_vp", "namada_vp_prelude", "proptest", "prost", @@ -4168,7 +4092,12 @@ dependencies = [ "konst", "namada_core", "namada_events", + "namada_state", "namada_storage", + "namada_tx", + "namada_vp", + "thiserror", + "tracing", ] [[package]] @@ -4180,13 +4109,11 @@ dependencies = [ "borsh 1.4.0", "data-encoding", "konst", - "linkme", "masp_primitives", "namada_core", "namada_events", "namada_gas", "namada_macros", - "namada_migrations", "num-derive 0.4.2", "num-traits 0.2.17", "proptest", @@ -4217,6 +4144,7 @@ dependencies = [ "namada_account", "namada_core", "namada_events", + "namada_gas", "namada_governance", "namada_ibc", "namada_macros", @@ -4229,6 +4157,34 @@ dependencies = [ "namada_vm_env", ] +[[package]] +name = "namada_vm" +version = "0.39.0" +dependencies = [ + "borsh 1.4.0", + "clru", + "namada_core", + "namada_events", + "namada_gas", + "namada_parameters", + "namada_state", + "namada_token", + "namada_tx", + "namada_vp", + "parity-wasm", + "rayon", + "smooth-operator", + "tempfile", + "thiserror", + "tracing", + "wasm-instrument", + "wasmer", + "wasmer-cache", + "wasmer-compiler-singlepass", + "wasmer-vm", + "wasmparser 0.107.0", +] + [[package]] name = "namada_vm_env" version = "0.39.0" @@ -4243,10 +4199,8 @@ name = "namada_vote_ext" version = "0.39.0" dependencies = [ "borsh 1.4.0", - "linkme", "namada_core", "namada_macros", - "namada_migrations", "namada_tx", "serde", ] @@ -5212,21 +5166,21 @@ checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" [[package]] name = "region" -version = "3.0.0" +version = "3.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76e189c2369884dce920945e2ddf79b3dff49e071a167dd1817fa9c4c00d512e" +checksum = "e6b6ebd13bc009aef9cd476c1310d49ac354d36e240cf1bd753290f3dc7199a7" dependencies = [ "bitflags 1.3.2", "libc", - "mach", - "winapi", + "mach2", + "windows-sys 0.52.0", ] [[package]] name = "rend" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2571463863a6bd50c32f94402933f03457a3fbaf697a707c5be741e459f08fd" +checksum = "71fe3824f5629716b1589be05dacd749f6aa084c87e00e016714a8cdfccc997c" dependencies = [ "bytecheck", ] @@ -5316,12 +5270,13 @@ dependencies = [ [[package]] name = "rkyv" -version = "0.7.42" +version = "0.7.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0200c8230b013893c0b2d6213d6ec64ed2b9be2e0e016682b7224ff82cff5c58" +checksum = "5cba464629b3394fc4dbc6f940ff8f5b4ff5c7aef40f29166fd4ad12acbc99c0" dependencies = [ "bitvec", "bytecheck", + "bytes", "hashbrown 0.12.3", "indexmap 1.9.3", "ptr_meta", @@ -5334,9 +5289,9 @@ dependencies = [ [[package]] name = "rkyv_derive" -version = "0.7.42" +version = "0.7.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2e06b915b5c230a17d7a736d1e2e63ee753c256a8614ef3f5147b13a4f5541d" +checksum = "a7dddfff8de25e6f62b9d64e6e432bf1c6736c57d20323e15ee10435fbda7c65" dependencies = [ "proc-macro2", "quote", @@ -6151,9 +6106,9 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" [[package]] name = "tar" -version = "0.4.40" +version = "0.4.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b16afcea1f22891c49a00c751c7b63b2233284064f11a200fc624137c51e2ddb" +checksum = "cb797dad5fb5b76fcf519e702f4a589483b5ef06567f160c392832c1f5e44909" dependencies = [ "filetime", "libc", @@ -6162,9 +6117,9 @@ dependencies = [ [[package]] name = "target-lexicon" -version = "0.12.12" +version = "0.12.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c39fd04924ca3a864207c66fc2cd7d22d7c016007f9ce846cbb9326331930a" +checksum = "e1fc403891a21bcfb7c37834ba66a547a8f402146eba7265b5a6d88059c9ff2f" [[package]] name = "tempfile" @@ -6769,7 +6724,6 @@ name = "tx_bond" version = "0.39.0" dependencies = [ "getrandom 0.2.15", - "namada", "namada_test_utils", "namada_tests", "namada_tx_prelude", @@ -6804,7 +6758,6 @@ name = "tx_change_validator_commission" version = "0.39.0" dependencies = [ "getrandom 0.2.15", - "namada", "namada_test_utils", "namada_tests", "namada_tx_prelude", @@ -6884,7 +6837,6 @@ name = "tx_redelegate" version = "0.39.0" dependencies = [ "getrandom 0.2.15", - "namada", "namada_test_utils", "namada_tests", "namada_tx_prelude", @@ -6946,7 +6898,6 @@ name = "tx_unbond" version = "0.39.0" dependencies = [ "getrandom 0.2.15", - "namada", "namada_test_utils", "namada_tests", "namada_tx_prelude", @@ -7008,7 +6959,6 @@ name = "tx_withdraw" version = "0.39.0" dependencies = [ "getrandom 0.2.15", - "namada", "namada_test_utils", "namada_tests", "namada_tx_prelude", @@ -7185,7 +7135,6 @@ name = "vp_implicit" version = "0.39.0" dependencies = [ "getrandom 0.2.15", - "namada", "namada_test_utils", "namada_tests", "namada_tx_prelude", @@ -7202,7 +7151,6 @@ name = "vp_user" version = "0.39.0" dependencies = [ "getrandom 0.2.15", - "namada", "namada_test_utils", "namada_tests", "namada_tx_prelude", @@ -7340,9 +7288,9 @@ dependencies = [ [[package]] name = "wasmer" -version = "4.3.1" +version = "4.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce4a267a570e121c9375136adefa2c48810273907de9c6817bc19db4d6144bc" +checksum = "b1852ee143a2d8143265bfee017c43bf690702d6c2b45a763a2f13e669f5b7ec" dependencies = [ "bytes", "cfg-if", @@ -7369,9 +7317,9 @@ dependencies = [ [[package]] name = "wasmer-cache" -version = "4.3.1" +version = "4.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67a40804bcc2567f112003182fc5edc29584da5199c4a1f5a8d6a6e4b65feff0" +checksum = "092ca4da29a7320b99c9b6660dfbde055f4db0a71c1273860272c213b2f7e019" dependencies = [ "blake3", "hex", @@ -7381,9 +7329,9 @@ dependencies = [ [[package]] name = "wasmer-compiler" -version = "4.3.1" +version = "4.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9c23098e86ef1038155684fe50f0c1079a0e2a2e70f115b789df17e6ba98d20" +checksum = "6b4f157d715f3bb60c2c9d7b9e48299a30e9209f87f4484f79f9cd586b40b6ee" dependencies = [ "backtrace", "bytes", @@ -7409,9 +7357,9 @@ dependencies = [ [[package]] name = "wasmer-compiler-cranelift" -version = "4.3.1" +version = "4.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95287b79973ad5f485215733ef9f0d4bb951a6b7e655585d2bd3d4a4ba1253c9" +checksum = "eb457e66b77ca2188fbbd6c2056ec6e8ccb4bddee73e60ba9d39733d7b2e8068" dependencies = [ "cranelift-codegen", "cranelift-entity", @@ -7428,9 +7376,9 @@ dependencies = [ [[package]] name = "wasmer-compiler-singlepass" -version = "4.3.1" +version = "4.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00d78d59be3ce78ad859e176b88f0d5bec0120ece0684922d7c5da1289e251b1" +checksum = "0a3196b2a87d5c6692021ece7ad1cf7fe43b7f1669c3aba1b8ccfcebe660070c" dependencies = [ "byteorder", "dynasm", @@ -7469,9 +7417,9 @@ dependencies = [ [[package]] name = "wasmer-derive" -version = "4.3.1" +version = "4.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e48f36aeeecb655f15fdd358bdf6e4cec27df181468fa4226084157e8462bd5e" +checksum = "32cd5732ff64370e98986f9753cce13b91cc9d3c4b649e31b0d08d5db69164ea" dependencies = [ "proc-macro-error", "proc-macro2", @@ -7481,9 +7429,9 @@ dependencies = [ [[package]] name = "wasmer-types" -version = "4.3.1" +version = "4.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83cb97b6b20084757a2a8d548dc0d4179c3fe9e2d711740423a1e6aa3f8b9091" +checksum = "c890fd0dbda40df03977b899d1ad7113deba3c225f2cc7b88deb7633044d3e07" dependencies = [ "bytecheck", "enum-iterator", @@ -7502,9 +7450,9 @@ dependencies = [ [[package]] name = "wasmer-vm" -version = "4.3.1" +version = "4.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc1e19d986844b17b927ec8b0c7f3da6a7a2c2cb3b0f8ca5d4cb1a1f71bfb124" +checksum = "5e0dc60ab800cf0bd44e2d35d88422d256d2470b00c72778f91bfb826c42dbd0" dependencies = [ "backtrace", "cc", diff --git a/wasm/tx_bond/src/lib.rs b/wasm/tx_bond/src/lib.rs index f09e127b500..b8a1f605365 100644 --- a/wasm/tx_bond/src/lib.rs +++ b/wasm/tx_bond/src/lib.rs @@ -16,26 +16,29 @@ mod tests { use std::cell::RefCell; use std::collections::BTreeSet; - use namada::core::dec::Dec; - use namada::ledger::gas::VpGasMeter; - use namada::ledger::pos::{OwnedPosParams, PosVP}; - use namada::proof_of_stake::storage::{ - bond_handle, read_consensus_validator_set_addresses_with_stake, - read_total_stake, read_validator_stake, - }; - use namada::proof_of_stake::types::{GenesisValidator, WeightedValidator}; use namada_tests::log::test; use namada_tests::native_vp::pos::init_pos; use namada_tests::native_vp::TestNativeVpEnv; use namada_tests::tx::*; + use namada_tests::validation::PosVp; use namada_tx_prelude::address::testing::{ arb_established_address, arb_non_internal_address, }; use namada_tx_prelude::address::InternalAddress; use namada_tx_prelude::chain::ChainId; + use namada_tx_prelude::dec::Dec; + use namada_tx_prelude::gas::VpGasMeter; use namada_tx_prelude::key::testing::arb_common_keypair; use namada_tx_prelude::key::RefTo; use namada_tx_prelude::proof_of_stake::parameters::testing::arb_pos_params; + use namada_tx_prelude::proof_of_stake::parameters::OwnedPosParams; + use namada_tx_prelude::proof_of_stake::storage::{ + bond_handle, read_consensus_validator_set_addresses_with_stake, + read_total_stake, read_validator_stake, + }; + use namada_tx_prelude::proof_of_stake::types::{ + GenesisValidator, WeightedValidator, + }; use proptest::prelude::*; use super::*; @@ -326,7 +329,8 @@ mod tests { &tx_env.gas_meter.borrow(), )); let vp_env = TestNativeVpEnv::from_tx_env(tx_env, address::POS); - let result = vp_env.validate_tx(&gas_meter, PosVP::new); + let vp = vp_env.init_vp(&gas_meter, PosVp::new); + let result = vp_env.validate_tx(&vp); assert!( result.is_ok(), "PoS Validity predicate must accept this transaction" diff --git a/wasm/tx_change_validator_commission/src/lib.rs b/wasm/tx_change_validator_commission/src/lib.rs index 8b6caa80112..2218f5db610 100644 --- a/wasm/tx_change_validator_commission/src/lib.rs +++ b/wasm/tx_change_validator_commission/src/lib.rs @@ -20,20 +20,21 @@ mod tests { use std::cell::RefCell; use std::cmp; - use namada::core::dec::{Dec, POS_DECIMAL_PRECISION}; - use namada::ledger::gas::VpGasMeter; - use namada::ledger::pos::{OwnedPosParams, PosVP}; - use namada::proof_of_stake::storage::validator_commission_rate_handle; - use namada::proof_of_stake::types::GenesisValidator; use namada_tests::log::test; use namada_tests::native_vp::pos::init_pos; use namada_tests::native_vp::TestNativeVpEnv; use namada_tests::tx::*; + use namada_tests::validation::PosVp; use namada_tx_prelude::address::testing::arb_established_address; use namada_tx_prelude::chain::ChainId; + use namada_tx_prelude::dec::{Dec, POS_DECIMAL_PRECISION}; + use namada_tx_prelude::gas::VpGasMeter; use namada_tx_prelude::key::testing::arb_common_keypair; use namada_tx_prelude::key::RefTo; use namada_tx_prelude::proof_of_stake::parameters::testing::arb_pos_params; + use namada_tx_prelude::proof_of_stake::parameters::OwnedPosParams; + use namada_tx_prelude::proof_of_stake::storage::validator_commission_rate_handle; + use namada_tx_prelude::proof_of_stake::types::GenesisValidator; use proptest::prelude::*; use super::*; @@ -153,7 +154,8 @@ mod tests { &tx_env.gas_meter.borrow(), )); let vp_env = TestNativeVpEnv::from_tx_env(tx_env, address::POS); - let result = vp_env.validate_tx(&gas_meter, PosVP::new); + let vp = vp_env.init_vp(&gas_meter, PosVp::new); + let result = vp_env.validate_tx(&vp); assert!( result.is_ok(), "PoS Validity predicate must accept this transaction" diff --git a/wasm/tx_redelegate/src/lib.rs b/wasm/tx_redelegate/src/lib.rs index efc7aab65ed..3ccbd7520e1 100644 --- a/wasm/tx_redelegate/src/lib.rs +++ b/wasm/tx_redelegate/src/lib.rs @@ -22,23 +22,26 @@ mod tests { use std::cell::RefCell; use std::collections::BTreeSet; - use namada::core::dec::Dec; - use namada::ledger::gas::VpGasMeter; - use namada::ledger::pos::{OwnedPosParams, PosVP}; - use namada::proof_of_stake::storage::{ - bond_handle, read_consensus_validator_set_addresses_with_stake, - read_total_stake, read_validator_stake, unbond_handle, - }; - use namada::proof_of_stake::types::{GenesisValidator, WeightedValidator}; use namada_tests::log::test; use namada_tests::native_vp::pos::init_pos; use namada_tests::native_vp::TestNativeVpEnv; use namada_tests::tx::*; + use namada_tests::validation::PosVp; use namada_tx_prelude::address::InternalAddress; use namada_tx_prelude::chain::ChainId; + use namada_tx_prelude::dec::Dec; + use namada_tx_prelude::gas::VpGasMeter; use namada_tx_prelude::key::testing::arb_common_keypair; use namada_tx_prelude::key::RefTo; use namada_tx_prelude::proof_of_stake::parameters::testing::arb_pos_params; + use namada_tx_prelude::proof_of_stake::parameters::OwnedPosParams; + use namada_tx_prelude::proof_of_stake::storage::{ + bond_handle, read_consensus_validator_set_addresses_with_stake, + read_total_stake, read_validator_stake, unbond_handle, + }; + use namada_tx_prelude::proof_of_stake::types::{ + GenesisValidator, WeightedValidator, + }; use proptest::prelude::*; use super::*; @@ -362,7 +365,8 @@ mod tests { &tx_env.gas_meter.borrow(), )); let vp_env = TestNativeVpEnv::from_tx_env(tx_env, address::POS); - let result = vp_env.validate_tx(&gas_meter, PosVP::new); + let vp = vp_env.init_vp(&gas_meter, PosVp::new); + let result = vp_env.validate_tx(&vp); assert!( result.is_ok(), "PoS Validity predicate must accept this transaction" diff --git a/wasm/tx_unbond/src/lib.rs b/wasm/tx_unbond/src/lib.rs index e22a3ed7a8f..3188c16673b 100644 --- a/wasm/tx_unbond/src/lib.rs +++ b/wasm/tx_unbond/src/lib.rs @@ -22,23 +22,26 @@ mod tests { use std::cell::RefCell; use std::collections::BTreeSet; - use namada::core::dec::Dec; - use namada::ledger::gas::VpGasMeter; - use namada::ledger::pos::{OwnedPosParams, PosVP}; - use namada::proof_of_stake::storage::{ - bond_handle, read_consensus_validator_set_addresses_with_stake, - read_total_stake, read_validator_stake, unbond_handle, - }; - use namada::proof_of_stake::types::{GenesisValidator, WeightedValidator}; use namada_tests::log::test; use namada_tests::native_vp::pos::init_pos; use namada_tests::native_vp::TestNativeVpEnv; use namada_tests::tx::*; + use namada_tests::validation::PosVp; use namada_tx_prelude::address::InternalAddress; use namada_tx_prelude::chain::ChainId; + use namada_tx_prelude::dec::Dec; + use namada_tx_prelude::gas::VpGasMeter; use namada_tx_prelude::key::testing::arb_common_keypair; use namada_tx_prelude::key::RefTo; use namada_tx_prelude::proof_of_stake::parameters::testing::arb_pos_params; + use namada_tx_prelude::proof_of_stake::parameters::OwnedPosParams; + use namada_tx_prelude::proof_of_stake::storage::{ + bond_handle, read_consensus_validator_set_addresses_with_stake, + read_total_stake, read_validator_stake, unbond_handle, + }; + use namada_tx_prelude::proof_of_stake::types::{ + GenesisValidator, WeightedValidator, + }; use proptest::prelude::*; use super::*; @@ -338,7 +341,8 @@ mod tests { &tx_env.gas_meter.borrow(), )); let vp_env = TestNativeVpEnv::from_tx_env(tx_env, address::POS); - let result = vp_env.validate_tx(&gas_meter, PosVP::new); + let vp = vp_env.init_vp(&gas_meter, PosVp::new); + let result = vp_env.validate_tx(&vp); assert!( result.is_ok(), "PoS Validity predicate must accept this transaction" diff --git a/wasm/tx_withdraw/src/lib.rs b/wasm/tx_withdraw/src/lib.rs index a11cc0a63a9..7a0dc5591d1 100644 --- a/wasm/tx_withdraw/src/lib.rs +++ b/wasm/tx_withdraw/src/lib.rs @@ -22,23 +22,24 @@ fn apply_tx(ctx: &mut Ctx, tx_data: BatchedTx) -> TxResult { mod tests { use std::cell::RefCell; - use namada::core::dec::Dec; - use namada::ledger::gas::VpGasMeter; - use namada::ledger::pos::{OwnedPosParams, PosVP}; - use namada::proof_of_stake::storage::unbond_handle; - use namada::proof_of_stake::types::GenesisValidator; use namada_tests::log::test; use namada_tests::native_vp::pos::init_pos; use namada_tests::native_vp::TestNativeVpEnv; use namada_tests::tx::*; + use namada_tests::validation::PosVp; use namada_tx_prelude::address::testing::{ arb_established_address, arb_non_internal_address, }; use namada_tx_prelude::address::InternalAddress; use namada_tx_prelude::chain::ChainId; + use namada_tx_prelude::dec::Dec; + use namada_tx_prelude::gas::VpGasMeter; use namada_tx_prelude::key::testing::arb_common_keypair; use namada_tx_prelude::key::RefTo; use namada_tx_prelude::proof_of_stake::parameters::testing::arb_pos_params; + use namada_tx_prelude::proof_of_stake::parameters::OwnedPosParams; + use namada_tx_prelude::proof_of_stake::storage::unbond_handle; + use namada_tx_prelude::proof_of_stake::types::GenesisValidator; use proptest::prelude::*; use super::*; @@ -226,7 +227,8 @@ mod tests { &tx_env.gas_meter.borrow(), )); let vp_env = TestNativeVpEnv::from_tx_env(tx_env, address::POS); - let result = vp_env.validate_tx(&gas_meter, PosVP::new); + let vp = vp_env.init_vp(&gas_meter, PosVp::new); + let result = vp_env.validate_tx(&vp); assert!( result.is_ok(), "PoS Validity predicate must accept this transaction" diff --git a/wasm/vp_implicit/src/lib.rs b/wasm/vp_implicit/src/lib.rs index db89216cafc..9cc2ce35460 100644 --- a/wasm/vp_implicit/src/lib.rs +++ b/wasm/vp_implicit/src/lib.rs @@ -245,18 +245,20 @@ impl<'a> From<&'a storage::Key> for KeyType<'a> { mod tests { use std::panic; - // Use this as `#[test]` annotation to enable logging - use namada::core::dec::Dec; - use namada::core::storage::Epoch; - use namada::ledger::pos::{GenesisValidator, PosParams}; - use namada::tx::data::TxType; - use namada::tx::{Authorization, Code, Data}; use namada_test_utils::TestWasms; use namada_tests::log::test; use namada_tests::native_vp::pos::init_pos; - use namada_tests::tx::{self, tx_host_env, TestTxEnv}; + use namada_tests::tx::data::TxType; + use namada_tests::tx::{ + self, tx_host_env, Authorization, Code, Data, TestTxEnv, + }; use namada_tests::vp::vp_host_env::storage::Key; use namada_tests::vp::*; + // Use this as `#[test]` annotation to enable logging + use namada_tx_prelude::dec::Dec; + use namada_tx_prelude::proof_of_stake::parameters::PosParams; + use namada_tx_prelude::proof_of_stake::types::GenesisValidator; + use namada_tx_prelude::storage::Epoch; use namada_tx_prelude::{StorageWrite, TxEnv}; use namada_vp_prelude::account::AccountPublicKeysMap; use namada_vp_prelude::key::RefTo; diff --git a/wasm/vp_user/src/lib.rs b/wasm/vp_user/src/lib.rs index 4071c6fdc5a..cd8c567b905 100644 --- a/wasm/vp_user/src/lib.rs +++ b/wasm/vp_user/src/lib.rs @@ -214,18 +214,20 @@ mod tests { use std::panic; use address::testing::arb_non_internal_address; - use namada::core::dec::Dec; - use namada::core::storage::Epoch; - use namada::ledger::pos::{GenesisValidator, PosParams}; - use namada::tx::data::{self, TxType}; - use namada::tx::{Authorization, Code, Data}; use namada_test_utils::TestWasms; // Use this as `#[test]` annotation to enable logging use namada_tests::log::test; use namada_tests::native_vp::pos::init_pos; - use namada_tests::tx::{self, tx_host_env, TestTxEnv}; + use namada_tests::tx::data::{self, TxType}; + use namada_tests::tx::{ + self, tx_host_env, Authorization, Code, Data, TestTxEnv, + }; use namada_tests::vp::vp_host_env::storage::Key; use namada_tests::vp::*; + use namada_tx_prelude::dec::Dec; + use namada_tx_prelude::proof_of_stake::parameters::PosParams; + use namada_tx_prelude::proof_of_stake::types::GenesisValidator; + use namada_tx_prelude::storage::Epoch; use namada_tx_prelude::{StorageWrite, TxEnv}; use namada_vp_prelude::account::AccountPublicKeysMap; use namada_vp_prelude::key::RefTo; diff --git a/wasm_for_tests/Cargo.lock b/wasm_for_tests/Cargo.lock index d9f0f36d93f..33a9526a04f 100644 --- a/wasm_for_tests/Cargo.lock +++ b/wasm_for_tests/Cargo.lock @@ -3742,60 +3742,6 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a" -[[package]] -name = "namada" -version = "0.39.0" -dependencies = [ - "async-trait", - "borsh 1.2.1", - "borsh-ext", - "clru", - "ethers", - "eyre", - "itertools 0.12.1", - "masp_primitives", - "masp_proofs", - "namada_account", - "namada_core", - "namada_ethereum_bridge", - "namada_events", - "namada_gas", - "namada_governance", - "namada_ibc", - "namada_parameters", - "namada_proof_of_stake", - "namada_replay_protection", - "namada_sdk", - "namada_state", - "namada_token", - "namada_tx", - "namada_tx_env", - "namada_vote_ext", - "namada_vp_env", - "parity-wasm", - "proptest", - "prost", - "rand 0.8.5", - "rayon", - "ripemd", - "serde_json", - "sha2 0.9.9", - "smooth-operator", - "tempfile", - "thiserror", - "tiny-bip39", - "tokio", - "tracing", - "uint", - "wasm-instrument", - "wasmer", - "wasmer-cache", - "wasmer-compiler-singlepass", - "wasmer-vm", - "wasmparser 0.107.0", - "wasmtimer", -] - [[package]] name = "namada_account" version = "0.39.0" @@ -3830,6 +3776,7 @@ dependencies = [ "ethabi", "ethbridge-structs", "eyre", + "futures", "ibc", "ics23", "impl-num-traits", @@ -3857,8 +3804,10 @@ dependencies = [ "tendermint-proto 0.36.0", "thiserror", "tiny-keccak", + "tokio", "tracing", "uint", + "wasmtimer", "zeroize", ] @@ -3882,7 +3831,9 @@ dependencies = [ "namada_trans_token", "namada_tx", "namada_vote_ext", + "namada_vp", "serde", + "smooth-operator", "thiserror", "tracing", ] @@ -3919,12 +3870,15 @@ dependencies = [ "borsh 1.2.1", "itertools 0.12.1", "konst", + "namada_account", "namada_core", "namada_events", "namada_macros", "namada_parameters", - "namada_storage", + "namada_state", "namada_trans_token", + "namada_tx", + "namada_vp", "proptest", "serde", "serde_json", @@ -3946,18 +3900,22 @@ dependencies = [ "masp_primitives", "namada_core", "namada_events", + "namada_gas", "namada_governance", "namada_macros", "namada_parameters", "namada_state", "namada_storage", "namada_token", + "namada_tx", + "namada_vp", "primitive-types", "proptest", "prost", "serde", "serde_json", "sha2 0.9.9", + "smooth-operator", "thiserror", "tracing", ] @@ -3993,7 +3951,10 @@ version = "0.39.0" dependencies = [ "namada_core", "namada_macros", + "namada_state", "namada_storage", + "namada_tx", + "namada_vp", "thiserror", ] @@ -4002,6 +3963,7 @@ name = "namada_proof_of_stake" version = "0.39.0" dependencies = [ "borsh 1.2.1", + "itertools 0.12.1", "konst", "namada_account", "namada_controller", @@ -4010,8 +3972,11 @@ dependencies = [ "namada_governance", "namada_macros", "namada_parameters", + "namada_state", "namada_storage", "namada_trans_token", + "namada_tx", + "namada_vp", "once_cell", "proptest", "serde", @@ -4063,7 +4028,9 @@ dependencies = [ "namada_storage", "namada_token", "namada_tx", + "namada_vm", "namada_vote_ext", + "namada_vp", "num-traits 0.2.17", "num256", "orion", @@ -4088,7 +4055,6 @@ dependencies = [ "tokio", "toml 0.5.11", "tracing", - "wasmtimer", "zeroize", ] @@ -4100,16 +4066,23 @@ dependencies = [ "lazy_static", "masp_primitives", "masp_proofs", + "namada_account", "namada_controller", "namada_core", "namada_gas", "namada_parameters", + "namada_state", "namada_storage", "namada_trans_token", + "namada_tx", + "namada_vp", "rand_core 0.6.4", "rayon", + "ripemd", "serde", + "sha2 0.9.9", "smooth-operator", + "thiserror", "tracing", ] @@ -4124,7 +4097,6 @@ dependencies = [ "namada_gas", "namada_macros", "namada_merkle_tree", - "namada_parameters", "namada_replay_protection", "namada_storage", "namada_tx", @@ -4171,11 +4143,13 @@ dependencies = [ "ibc-testkit", "ics23", "itertools 0.12.1", - "namada", "namada_core", "namada_sdk", "namada_test_utils", + "namada_tx_env", "namada_tx_prelude", + "namada_vm", + "namada_vp", "namada_vp_prelude", "proptest", "prost", @@ -4210,7 +4184,12 @@ dependencies = [ "konst", "namada_core", "namada_events", + "namada_state", "namada_storage", + "namada_tx", + "namada_vp", + "thiserror", + "tracing", ] [[package]] @@ -4257,6 +4236,7 @@ dependencies = [ "namada_account", "namada_core", "namada_events", + "namada_gas", "namada_governance", "namada_ibc", "namada_macros", @@ -4269,6 +4249,34 @@ dependencies = [ "namada_vm_env", ] +[[package]] +name = "namada_vm" +version = "0.39.0" +dependencies = [ + "borsh 1.2.1", + "clru", + "namada_core", + "namada_events", + "namada_gas", + "namada_parameters", + "namada_state", + "namada_token", + "namada_tx", + "namada_vp", + "parity-wasm", + "rayon", + "smooth-operator", + "tempfile", + "thiserror", + "tracing", + "wasm-instrument", + "wasmer", + "wasmer-cache", + "wasmer-compiler-singlepass", + "wasmer-vm", + "wasmparser 0.107.0", +] + [[package]] name = "namada_vm_env" version = "0.39.0" @@ -4289,6 +4297,21 @@ dependencies = [ "serde", ] +[[package]] +name = "namada_vp" +version = "0.39.0" +dependencies = [ + "namada_core", + "namada_events", + "namada_gas", + "namada_state", + "namada_tx", + "namada_vp_env", + "smooth-operator", + "thiserror", + "tracing", +] + [[package]] name = "namada_vp_env" version = "0.39.0" @@ -4297,7 +4320,6 @@ dependencies = [ "masp_primitives", "namada_core", "namada_events", - "namada_ibc", "namada_storage", "namada_tx", "smooth-operator", diff --git a/wasm_for_tests/tx_fail/Cargo.toml b/wasm_for_tests/tx_fail/Cargo.toml index 7ad61b13900..474241508d9 100644 --- a/wasm_for_tests/tx_fail/Cargo.toml +++ b/wasm_for_tests/tx_fail/Cargo.toml @@ -14,9 +14,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/tx_infinite_guest_gas/Cargo.toml b/wasm_for_tests/tx_infinite_guest_gas/Cargo.toml index 4ae786610a0..bb96412cd1a 100644 --- a/wasm_for_tests/tx_infinite_guest_gas/Cargo.toml +++ b/wasm_for_tests/tx_infinite_guest_gas/Cargo.toml @@ -14,9 +14,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/tx_infinite_host_gas/Cargo.toml b/wasm_for_tests/tx_infinite_host_gas/Cargo.toml index f6173d018d9..7839da47311 100644 --- a/wasm_for_tests/tx_infinite_host_gas/Cargo.toml +++ b/wasm_for_tests/tx_infinite_host_gas/Cargo.toml @@ -14,9 +14,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/tx_invalid_data/Cargo.toml b/wasm_for_tests/tx_invalid_data/Cargo.toml index 08ede9f0859..dd0d5d75b58 100644 --- a/wasm_for_tests/tx_invalid_data/Cargo.toml +++ b/wasm_for_tests/tx_invalid_data/Cargo.toml @@ -14,9 +14,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/tx_memory_limit/Cargo.toml b/wasm_for_tests/tx_memory_limit/Cargo.toml index c7d95994626..838d9784de6 100644 --- a/wasm_for_tests/tx_memory_limit/Cargo.toml +++ b/wasm_for_tests/tx_memory_limit/Cargo.toml @@ -14,9 +14,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/tx_no_op/Cargo.toml b/wasm_for_tests/tx_no_op/Cargo.toml index 6a7d8411960..13c1d1585e9 100644 --- a/wasm_for_tests/tx_no_op/Cargo.toml +++ b/wasm_for_tests/tx_no_op/Cargo.toml @@ -14,9 +14,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/tx_proposal_code/Cargo.toml b/wasm_for_tests/tx_proposal_code/Cargo.toml index 871734a09df..0fbf2f47150 100644 --- a/wasm_for_tests/tx_proposal_code/Cargo.toml +++ b/wasm_for_tests/tx_proposal_code/Cargo.toml @@ -15,9 +15,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/tx_proposal_ibc_token_inflation/Cargo.toml b/wasm_for_tests/tx_proposal_ibc_token_inflation/Cargo.toml index e5caefcfb0c..4dc32d08cfc 100644 --- a/wasm_for_tests/tx_proposal_ibc_token_inflation/Cargo.toml +++ b/wasm_for_tests/tx_proposal_ibc_token_inflation/Cargo.toml @@ -14,9 +14,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/tx_proposal_masp_reward/Cargo.toml b/wasm_for_tests/tx_proposal_masp_reward/Cargo.toml index 361d8eaeefe..cbe83d4cbe7 100644 --- a/wasm_for_tests/tx_proposal_masp_reward/Cargo.toml +++ b/wasm_for_tests/tx_proposal_masp_reward/Cargo.toml @@ -14,9 +14,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/tx_read_storage_key/Cargo.toml b/wasm_for_tests/tx_read_storage_key/Cargo.toml index 4a4f1aef2ab..2e2ca9b3347 100644 --- a/wasm_for_tests/tx_read_storage_key/Cargo.toml +++ b/wasm_for_tests/tx_read_storage_key/Cargo.toml @@ -14,9 +14,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/tx_write/Cargo.toml b/wasm_for_tests/tx_write/Cargo.toml index 52ef2c7b913..80f03b180c2 100644 --- a/wasm_for_tests/tx_write/Cargo.toml +++ b/wasm_for_tests/tx_write/Cargo.toml @@ -15,9 +15,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/vp_always_false/Cargo.toml b/wasm_for_tests/vp_always_false/Cargo.toml index dfb265329db..44839189160 100644 --- a/wasm_for_tests/vp_always_false/Cargo.toml +++ b/wasm_for_tests/vp_always_false/Cargo.toml @@ -14,9 +14,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/vp_always_true/Cargo.toml b/wasm_for_tests/vp_always_true/Cargo.toml index 9ad6a8621c3..3bc58827e9d 100644 --- a/wasm_for_tests/vp_always_true/Cargo.toml +++ b/wasm_for_tests/vp_always_true/Cargo.toml @@ -14,9 +14,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/vp_eval/Cargo.toml b/wasm_for_tests/vp_eval/Cargo.toml index d6c7d13215e..c8477dd1555 100644 --- a/wasm_for_tests/vp_eval/Cargo.toml +++ b/wasm_for_tests/vp_eval/Cargo.toml @@ -15,9 +15,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/vp_infinite_guest_gas/Cargo.toml b/wasm_for_tests/vp_infinite_guest_gas/Cargo.toml index 3243cae45a5..50ac66ce801 100644 --- a/wasm_for_tests/vp_infinite_guest_gas/Cargo.toml +++ b/wasm_for_tests/vp_infinite_guest_gas/Cargo.toml @@ -14,9 +14,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/vp_infinite_host_gas/Cargo.toml b/wasm_for_tests/vp_infinite_host_gas/Cargo.toml index 5f2ee8d60b6..d13e70a821a 100644 --- a/wasm_for_tests/vp_infinite_host_gas/Cargo.toml +++ b/wasm_for_tests/vp_infinite_host_gas/Cargo.toml @@ -15,9 +15,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/vp_memory_limit/Cargo.toml b/wasm_for_tests/vp_memory_limit/Cargo.toml index 67d8d97e6af..5715cf1d07d 100644 --- a/wasm_for_tests/vp_memory_limit/Cargo.toml +++ b/wasm_for_tests/vp_memory_limit/Cargo.toml @@ -14,9 +14,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]} diff --git a/wasm_for_tests/vp_read_storage_key/Cargo.toml b/wasm_for_tests/vp_read_storage_key/Cargo.toml index 094c40c7b48..b7bd36790fd 100644 --- a/wasm_for_tests/vp_read_storage_key/Cargo.toml +++ b/wasm_for_tests/vp_read_storage_key/Cargo.toml @@ -14,9 +14,7 @@ rlsf.workspace = true getrandom.workspace = true [dev-dependencies] -namada_tests = { path = "../../crates/tests", default-features = false, features = [ - "wasm-runtime", -] } +namada_tests = { path = "../../crates/tests" } proptest = "1.4.0" test-log = {version = "0.2.14", default-features = false, features = ["trace"]}