diff --git a/Cargo.lock b/Cargo.lock index 289a1a9e4..2abbf4fcf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -18,6 +18,7 @@ dependencies = [ "bech32 0.9.1", "constcat", "data-encoding", + "extensions", "serde", "serde_json", "thiserror", @@ -1331,6 +1332,7 @@ checksum = "e8566979429cf69b49a5c740c60791108e86440e8be149bbea4fe54d2c32d6e2" name = "database" version = "0.1.0" dependencies = [ + "extensions", "rocksdb", "sled", "thiserror", @@ -1668,6 +1670,14 @@ dependencies = [ "tracing", ] +[[package]] +name = "extensions" +version = "0.1.0" +dependencies = [ + "itertools 0.13.0", + "vec1", +] + [[package]] name = "eyre" version = "0.6.12" @@ -1925,7 +1935,6 @@ dependencies = [ "axum 0.7.5", "bank", "bip32", - "bytes", "clap", "data-encoding", "distribution", @@ -1969,13 +1978,13 @@ dependencies = [ "derive_more 0.99.18", "dircpy", "dirs", + "extensions", "former", "handlebars", "hex 0.4.3", "http 0.2.12", "human-panic", "ibc-proto 0.33.0", - "itertools 0.13.0", "k256", "key-derive", "keyring", @@ -3013,6 +3022,7 @@ dependencies = [ "derive_more 0.99.18", "gears", "ibc", + "nz", "prost 0.12.6", "schemars", "serde", @@ -3348,6 +3358,7 @@ dependencies = [ "argon2", "bip32", "eth-keystore", + "extensions", "hex 0.4.3", "k256", "pkcs8", @@ -3383,6 +3394,7 @@ name = "kv_store" version = "0.1.0" dependencies = [ "database", + "extensions", "hex 0.4.3", "integer-encoding", "sha2 0.10.8", @@ -5235,6 +5247,7 @@ dependencies = [ "bytes", "chrono", "ed25519-consensus", + "extensions", "handlebars", "ibc-proto 0.33.0", "prost 0.11.9", @@ -5812,6 +5825,7 @@ dependencies = [ "caches", "criterion", "database", + "extensions", "handlebars", "hex 0.4.3", "integer-encoding", diff --git a/Cargo.toml b/Cargo.toml index 87c62f329..7b5ac7e6e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,6 @@ [workspace] members = [ + "extensions", # no local deps "database", "tendermint", @@ -94,6 +95,7 @@ constcat = { version = "0.5.0" } # upgraded std::concat! wh derive_more = "0.99.17" former = "0.16.0" nz = "0.4.1" +itertools = "0.13.0" # log log = { version = "0.4.21" } diff --git a/address/Cargo.toml b/address/Cargo.toml index 3a5dc03a4..8ea36e314 100644 --- a/address/Cargo.toml +++ b/address/Cargo.toml @@ -14,6 +14,7 @@ thiserror = { workspace = true } [dev-dependencies] serde_json = { workspace = true } +extensions = { path = "../extensions" } [lints] workspace = true diff --git a/address/src/lib.rs b/address/src/lib.rs index f877bdbea..51a229175 100644 --- a/address/src/lib.rs +++ b/address/src/lib.rs @@ -259,6 +259,7 @@ pub enum AddressError { mod tests { use bech32::ToBase32; + use extensions::testing::UnwrapTesting; use super::*; @@ -270,12 +271,13 @@ mod tests { input_address.to_base32(), Variant::Bech32, ) - .unwrap(); + .unwrap_test(); + let expected_address = BaseAddress::<0>(input_address); - let address = AccAddress::from_bech32(&encoded).unwrap(); + let address = AccAddress::from_bech32(&encoded); - assert_eq!(expected_address, address); + assert_eq!(Ok(expected_address), address); } #[test] @@ -286,12 +288,16 @@ mod tests { input_address.to_base32(), Variant::Bech32, ) - .unwrap(); + .unwrap_test(); + encoded.pop(); - let err = AccAddress::from_bech32(&encoded).unwrap_err(); + let err = AccAddress::from_bech32(&encoded); - assert_eq!(err, AddressError::Decode(bech32::Error::InvalidChecksum)); + assert_eq!( + err, + Err(AddressError::Decode(bech32::Error::InvalidChecksum)) + ); } #[test] @@ -299,7 +305,7 @@ mod tests { let mut hrp = BECH_32_PREFIX_ACC_ADDR.to_string(); hrp.push_str("atom"); // adding to the BECH_32_PREFIX_ACC_ADDR ensures that hrp is different let encoded = - bech32::encode(&hrp, vec![0x00, 0x01, 0x02].to_base32(), Variant::Bech32).unwrap(); + bech32::encode(&hrp, vec![0x00, 0x01, 0x02].to_base32(), Variant::Bech32).unwrap_test(); let err = AccAddress::from_bech32(&encoded).unwrap_err(); @@ -319,7 +325,7 @@ mod tests { vec![0x00, 0x01, 0x02].to_base32(), Variant::Bech32m, ) - .unwrap(); + .unwrap_test(); let err = AccAddress::from_bech32(&encoded).unwrap_err(); @@ -339,7 +345,7 @@ mod tests { vec![0x00; 300].to_base32(), Variant::Bech32, ) - .unwrap(); + .unwrap_test(); let err = AccAddress::from_bech32(&encoded).unwrap_err(); @@ -354,8 +360,8 @@ mod tests { #[test] fn from_bech32_failure_empty_address() { - let encoded = - bech32::encode(BECH_32_PREFIX_ACC_ADDR, vec![].to_base32(), Variant::Bech32).unwrap(); + let encoded = bech32::encode(BECH_32_PREFIX_ACC_ADDR, vec![].to_base32(), Variant::Bech32) + .unwrap_test(); let err = AccAddress::from_bech32(&encoded).unwrap_err(); @@ -373,7 +379,7 @@ mod tests { fn to_string_success() { let addr = "cosmos1syavy2npfyt9tcncdtsdzf7kny9lh777pahuux".to_string(); - let acc_addr = AccAddress::from_bech32(&addr).unwrap(); + let acc_addr = AccAddress::from_bech32(&addr).unwrap_test(); assert_eq!(addr, acc_addr.to_string()); } @@ -382,7 +388,7 @@ mod tests { fn string_from_self_success() { let addr = "cosmos1syavy2npfyt9tcncdtsdzf7kny9lh777pahuux".to_string(); - let acc_addr = AccAddress::from_bech32(&addr).unwrap(); + let acc_addr = AccAddress::from_bech32(&addr).unwrap_test(); assert_eq!(addr, String::from(acc_addr)); } @@ -390,9 +396,9 @@ mod tests { #[test] fn serialize_works() { let addr = "cosmos1syavy2npfyt9tcncdtsdzf7kny9lh777pahuux".to_string(); - let acc_addr = AccAddress::from_bech32(&addr).unwrap(); + let acc_addr = AccAddress::from_bech32(&addr).unwrap_test(); - let json = serde_json::to_string(&acc_addr).unwrap(); + let json = serde_json::to_string(&acc_addr).unwrap_test(); assert_eq!(json, r#""cosmos1syavy2npfyt9tcncdtsdzf7kny9lh777pahuux""#); } @@ -400,17 +406,17 @@ mod tests { #[test] fn deserialize_works() { let json = r#""cosmos1syavy2npfyt9tcncdtsdzf7kny9lh777pahuux""#; - let addr: AccAddress = serde_json::from_str(json).unwrap(); + let addr = serde_json::from_str::(json).unwrap_test(); assert_eq!( addr, - AccAddress::from_bech32("cosmos1syavy2npfyt9tcncdtsdzf7kny9lh777pahuux").unwrap() + AccAddress::from_bech32("cosmos1syavy2npfyt9tcncdtsdzf7kny9lh777pahuux").unwrap_test() ) } #[test] fn prefix_len_bytes_works() { let addr = vec![0x00, 0x01, 0x02]; - let acc_addr = AccAddress::try_from(addr.as_slice()).unwrap(); + let acc_addr = AccAddress::try_from(addr.as_slice()).unwrap_test(); let prefixed = acc_addr.prefix_len_bytes(); diff --git a/database/Cargo.toml b/database/Cargo.toml index a65d1f41e..1298f9604 100644 --- a/database/Cargo.toml +++ b/database/Cargo.toml @@ -4,6 +4,8 @@ version = "0.1.0" edition = "2021" [dependencies] +extensions = { path = "../extensions" } + thiserror = { workspace = true } rocksdb = { version = "0.22.0", optional = true } sled = {version = "0.34.7", optional = true } diff --git a/database/src/lib.rs b/database/src/lib.rs index 68242d557..54b7b4927 100644 --- a/database/src/lib.rs +++ b/database/src/lib.rs @@ -1,7 +1,6 @@ #![warn(rust_2018_idioms)] pub mod error; -pub mod ext; mod memory; pub mod prefix; #[cfg(feature = "rocksdb")] diff --git a/database/src/rocks.rs b/database/src/rocks.rs index 2eb1267d4..118cb5ce8 100644 --- a/database/src/rocks.rs +++ b/database/src/rocks.rs @@ -70,7 +70,7 @@ mod tests { #[test] fn iterator_works() { - let db = RocksDB::new("tmp/1").unwrap(); + let db = RocksDB::new("tmp/1").expect("hardcoded is valid"); db.put(vec![1], vec![1]); db.put(vec![2], vec![2]); let got_pairs: Vec<(Box<[u8]>, Box<[u8]>)> = db.iterator().collect(); @@ -86,7 +86,7 @@ mod tests { #[test] fn prefix_iterator_works() { - let db = RocksDB::new("tmp/2").unwrap(); + let db = RocksDB::new("tmp/2").expect("hardcoded is valid"); db.put(vec![1, 1], vec![1]); db.put(vec![2, 1], vec![2]); db.put(vec![3, 1], vec![3]); diff --git a/database/src/sled.rs b/database/src/sled.rs index c4742f205..452e8a1ba 100644 --- a/database/src/sled.rs +++ b/database/src/sled.rs @@ -1,4 +1,6 @@ -use crate::{error::DatabaseError, ext::UnwrapCorrupt, DBBuilder, Database, DatabaseBuilder}; +use extensions::corruption::UnwrapCorrupt; + +use crate::{error::DatabaseError, DBBuilder, Database, DatabaseBuilder}; impl DatabaseBuilder for DBBuilder { type Err = DatabaseError; diff --git a/extensions/Cargo.toml b/extensions/Cargo.toml new file mode 100644 index 000000000..c2c2850eb --- /dev/null +++ b/extensions/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "extensions" +version = "0.1.0" +edition = "2021" + +[dependencies] +vec1 = { workspace = true } +itertools = { workspace = true } + +[lints] +workspace = true diff --git a/database/src/ext.rs b/extensions/src/corruption.rs similarity index 100% rename from database/src/ext.rs rename to extensions/src/corruption.rs diff --git a/gears/src/types/store/gas/ext.rs b/extensions/src/gas.rs similarity index 100% rename from gears/src/types/store/gas/ext.rs rename to extensions/src/gas.rs diff --git a/kv_store/src/ext.rs b/extensions/src/infallible.rs similarity index 100% rename from kv_store/src/ext.rs rename to extensions/src/infallible.rs diff --git a/extensions/src/lib.rs b/extensions/src/lib.rs new file mode 100644 index 000000000..5398a9ffe --- /dev/null +++ b/extensions/src/lib.rs @@ -0,0 +1,8 @@ +pub mod lock; +pub mod corruption; +pub mod gas; +pub mod infallible; +pub mod pagination; +pub mod socker_addr; +pub mod testing; +pub mod try_map; diff --git a/extensions/src/lock.rs b/extensions/src/lock.rs new file mode 100644 index 000000000..c5506c232 --- /dev/null +++ b/extensions/src/lock.rs @@ -0,0 +1,22 @@ +use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; + +const POISONED_LOCK_MSG: &str = "poisoned lock"; + +pub trait AcquireRwLock { + type Output; + + fn acquire_read(&self) -> RwLockReadGuard<'_, Self::Output>; + fn acquire_write(&self) -> RwLockWriteGuard<'_, Self::Output>; +} + +impl AcquireRwLock for RwLock { + type Output = T; + + fn acquire_read(&self) -> RwLockReadGuard<'_, Self::Output> { + self.read().expect(POISONED_LOCK_MSG) + } + + fn acquire_write(&self) -> RwLockWriteGuard<'_, Self::Output> { + self.write().expect(POISONED_LOCK_MSG) + } +} diff --git a/gears/src/ext/pagination/key.rs b/extensions/src/pagination/key.rs similarity index 94% rename from gears/src/ext/pagination/key.rs rename to extensions/src/pagination/key.rs index e053e6cb6..777a656ad 100644 --- a/gears/src/ext/pagination/key.rs +++ b/extensions/src/pagination/key.rs @@ -3,8 +3,6 @@ use std::borrow::Cow; use itertools::Itertools; use vec1::Vec1; -use crate::types::{base::coin::UnsignedCoin, store::gas::errors::GasStoreErrors}; - use super::{PaginationResultElement, TwoIterators}; pub type PaginationByKeyResult = PaginationResultElement>; @@ -85,12 +83,6 @@ impl, U: PaginationKey> IteratorPaginateByKey for T { } } -impl PaginationKey for UnsignedCoin { - fn iterator_key(&self) -> Cow<'_, [u8]> { - Cow::Borrowed(self.denom.as_ref()) - } -} - impl PaginationKey for (Cow<'_, Vec>, T) { fn iterator_key(&self) -> Cow<'_, [u8]> { Cow::Borrowed(self.0.as_ref()) @@ -109,18 +101,19 @@ impl PaginationKey for Vec { } } -impl PaginationKey for Result { +impl PaginationKey for Result { fn iterator_key(&self) -> Cow<'_, [u8]> { match self { Ok(var) => var.iterator_key(), - Err(var) => Cow::Borrowed(&var.key), + Err(var) => var.iterator_key(), } } } #[cfg(test)] mod tests { - use crate::ext::UnwrapPagination; + + use crate::pagination::UnwrapPagination; use super::*; use vec1::vec1; diff --git a/gears/src/ext/pagination/mod.rs b/extensions/src/pagination/mod.rs similarity index 87% rename from gears/src/ext/pagination/mod.rs rename to extensions/src/pagination/mod.rs index 2b45fde17..eb28db5f8 100644 --- a/gears/src/ext/pagination/mod.rs +++ b/extensions/src/pagination/mod.rs @@ -1,8 +1,6 @@ mod key; mod offset; -use crate::types::pagination::response::PaginationResponse; - pub use self::key::*; pub use self::offset::*; @@ -134,19 +132,3 @@ impl PaginationResultElement { } } } - -impl From> for PaginationResponse { - fn from( - PaginationResultElement { - total, - next_key: next_element, - }: PaginationResultElement, - ) -> Self { - Self { - next_key: next_element - .map(|this| this.iterator_key().into_owned()) - .unwrap_or_default(), - total: total as u64, - } - } -} diff --git a/gears/src/ext/pagination/offset.rs b/extensions/src/pagination/offset.rs similarity index 99% rename from gears/src/ext/pagination/offset.rs rename to extensions/src/pagination/offset.rs index 89cd3f188..f3ee6df70 100644 --- a/gears/src/ext/pagination/offset.rs +++ b/extensions/src/pagination/offset.rs @@ -81,7 +81,8 @@ impl, U: Clone> IteratorPaginateByOffset for T { #[cfg(test)] mod tests { - use crate::ext::UnwrapPagination; + + use crate::pagination::UnwrapPagination; use super::*; diff --git a/gears/src/ext/socker_addr.rs b/extensions/src/socker_addr.rs similarity index 100% rename from gears/src/ext/socker_addr.rs rename to extensions/src/socker_addr.rs diff --git a/extensions/src/testing.rs b/extensions/src/testing.rs new file mode 100644 index 000000000..f94323935 --- /dev/null +++ b/extensions/src/testing.rs @@ -0,0 +1,25 @@ +use std::fmt::Debug; + +pub const TESTING_MSG: &str = "unwrap value in test"; + +pub trait UnwrapTesting { + type Output; + + fn unwrap_test(self) -> Self::Output; +} + +impl UnwrapTesting for Option { + type Output = T; + + fn unwrap_test(self) -> Self::Output { + self.expect(TESTING_MSG) + } +} + +impl UnwrapTesting for Result { + type Output = T; + + fn unwrap_test(self) -> Self::Output { + self.expect(TESTING_MSG) + } +} diff --git a/gears/src/ext/try_map.rs b/extensions/src/try_map.rs similarity index 100% rename from gears/src/ext/try_map.rs rename to extensions/src/try_map.rs diff --git a/gaia-rs/Cargo.toml b/gaia-rs/Cargo.toml index 5ac9c0015..83dda2cb2 100644 --- a/gaia-rs/Cargo.toml +++ b/gaia-rs/Cargo.toml @@ -24,7 +24,7 @@ staking = { path = "../x/staking" } genutil = { path = "../x/genutil" } #newtypes -bytes = { workspace = true } +# bytes = { workspace = true } # thiserror = { workspace = true } #utils diff --git a/gaia-rs/build.rs b/gaia-rs/build.rs index c5c0c3b4a..d4d984df2 100644 --- a/gaia-rs/build.rs +++ b/gaia-rs/build.rs @@ -1,9 +1,13 @@ use std::process::Command; + fn main() { let output = Command::new("git") .args(["rev-parse", "HEAD"]) .output() - .unwrap(); - let git_hash = String::from_utf8(output.stdout).unwrap(); + .map(|this| this.stdout) + .unwrap_or_default(); + + let git_hash = String::from_utf8_lossy(&output); + println!("cargo:rustc-env=GIT_HASH={}", git_hash); } diff --git a/gaia-rs/src/abci_handler.rs b/gaia-rs/src/abci_handler.rs index 447b7d5d7..f5e196f42 100644 --- a/gaia-rs/src/abci_handler.rs +++ b/gaia-rs/src/abci_handler.rs @@ -23,6 +23,13 @@ impl ModuleInfo for BankModuleInfo { const NAME: &'static str = "bank"; } +#[derive(Debug, Clone)] +struct IbcModuleInfo; + +impl ModuleInfo for IbcModuleInfo { + const NAME: &'static str = "ibc"; +} + #[derive(Debug, Clone)] struct StakingModuleInfo; @@ -58,7 +65,7 @@ pub struct GaiaABCIHandler { GaiaModules, StakingModuleInfo, >, - ibc_abci_handler: ibc_rs::ABCIHandler, + ibc_abci_handler: ibc_rs::ABCIHandler, ante_handler: BaseAnteHandler< bank::Keeper< GaiaStoreKey, diff --git a/gaia-rs/tests/abci/main.rs b/gaia-rs/tests/abci/main.rs index 2c9b70802..ac330c106 100644 --- a/gaia-rs/tests/abci/main.rs +++ b/gaia-rs/tests/abci/main.rs @@ -29,7 +29,8 @@ const USER_1: &str = "unfair live spike near cushion blanket club salad poet cig // This is a helper function to create a user with a specific account number pub fn user(account_number: u64, mnemonic: &str) -> User { - let mnemonic = bip32::Mnemonic::new(mnemonic, bip32::Language::English).unwrap(); + let mnemonic = + bip32::Mnemonic::new(mnemonic, bip32::Language::English).expect("mnemonic is invalid"); let key_pair = KeyPair::from_mnemonic(&mnemonic); User { @@ -56,14 +57,16 @@ fn setup_mock_node( let chain_id = ChainId::default(); let mnemonic = "race draft rival universe maid cheese steel logic crowd fork comic easy truth drift tomorrow eye buddy head time cash swing swift midnight borrow"; - let mnemonic = bip32::Mnemonic::new(mnemonic, bip32::Language::English).unwrap(); + let mnemonic = + bip32::Mnemonic::new(mnemonic, bip32::Language::English).expect("mnemonic is invalid"); let key_pair = KeyPair::from_mnemonic(&mnemonic); let address = key_pair.get_address(); let consensus_key = gears::tendermint::crypto::new_private_key(); let genesis = if let Some(path) = genesis_path { - let genesis_state = fs::read_to_string(path.as_ref()).unwrap(); - serde_json::from_str(&genesis_state).unwrap() + let genesis_state = + fs::read_to_string(path.as_ref()).expect("failed to read genesis state"); + serde_json::from_str(&genesis_state).expect("invalid genesis") } else { let mut genesis = GenesisState::default(); genesis diff --git a/gaia-rs/tests/abci/scenario_2.rs b/gaia-rs/tests/abci/scenario_2.rs index 12eeaf708..4273d4070 100644 --- a/gaia-rs/tests/abci/scenario_2.rs +++ b/gaia-rs/tests/abci/scenario_2.rs @@ -32,7 +32,7 @@ fn scenario_2() { "value": "NJWo4rSXCswNmK0Bttxzb8/1ioFNkRVi6Fio2KzAlCo=" }"#, ) - .unwrap(); + .expect("hardcoded is valid"); let msg = gaia_rs::message::Message::Staking(staking::Message::CreateValidator(CreateValidator { @@ -44,21 +44,21 @@ fn scenario_2() { security_contact: "".to_string(), }, commission: CommissionRates::new( - "0.1".parse().unwrap(), - "1".parse().unwrap(), - "0.1".parse().unwrap(), + "0.1".parse().expect("hardcoded is valid"), + "1".parse().expect("hardcoded is valid"), + "0.1".parse().expect("hardcoded is valid"), ) - .unwrap(), + .expect("hardcoded is valid"), min_self_delegation: Uint256::from(100u32), delegator_address: user_1.address(), validator_address: user_1.address().into(), pubkey: consensus_pub_key, - value: "10000uatom".parse().unwrap(), + value: "10000uatom".parse().expect("hardcoded is valid"), })); let txs = generate_txs([(0, msg)], &user_1, node.chain_id().clone()); - let app_hash = node.step(txs, Timestamp::try_new(0, 0).unwrap()); + let app_hash = node.step(txs, Timestamp::try_new(0, 0).expect("hardcoded is valid")); assert_eq!( hex::encode(app_hash), "6f02c4708c36481eeb65acf704340d906af5737702dbf05fc8bf4dd29a92f16e" @@ -76,7 +76,7 @@ fn scenario_2() { security_contact: Some("".to_string()), details: Some("".to_string()), }, - Some("0.2".parse().unwrap()), + Some("0.2".parse().expect("hardcoded is valid")), Some(Uint256::from(200u32)), user_1.address().into(), ), @@ -84,7 +84,10 @@ fn scenario_2() { let txs = generate_txs([(1, msg)], &user_1, node.chain_id().clone()); - let app_hash = node.step(txs, Timestamp::try_new(60 * 60 * 24, 0).unwrap()); + let app_hash = node.step( + txs, + Timestamp::try_new(60 * 60 * 24, 0).expect("hardcoded is valid"), + ); assert_eq!( hex::encode(app_hash), "68f309714a2273b0f8ad93f318bc5a0dd418bd2bdd1431a6a848ae104c98a39b" @@ -96,13 +99,16 @@ fn scenario_2() { let msg = gaia_rs::message::Message::Staking(staking::Message::Delegate(staking::DelegateMsg { validator_address: user_0.address().into(), - amount: "1000uatom".parse().unwrap(), + amount: "1000uatom".parse().expect("hardcoded is valid"), delegator_address: user_1.address(), })); let txs = generate_txs([(2, msg)], &user_1, node.chain_id().clone()); - let app_hash = node.step(txs, Timestamp::try_new(60 * 60 * 24, 0).unwrap()); + let app_hash = node.step( + txs, + Timestamp::try_new(60 * 60 * 24, 0).expect("hardcoded is valid"), + ); assert_eq!( hex::encode(app_hash), @@ -117,12 +123,15 @@ fn scenario_2() { delegator_address: user_1.address(), src_validator_address: user_0.address().into(), dst_validator_address: user_1.address().into(), - amount: "500uatom".parse().unwrap(), + amount: "500uatom".parse().expect("hardcoded is valid"), })); let txs = generate_txs([(3, msg)], &user_1, node.chain_id().clone()); - let app_hash = node.step(txs, Timestamp::try_new(60 * 60 * 24, 0).unwrap()); + let app_hash = node.step( + txs, + Timestamp::try_new(60 * 60 * 24, 0).expect("hardcoded is valid"), + ); assert_eq!( hex::encode(app_hash), @@ -135,13 +144,16 @@ fn scenario_2() { let msg = gaia_rs::message::Message::Staking(staking::Message::Undelegate(staking::UndelegateMsg { validator_address: user_0.address().into(), - amount: "500uatom".parse().unwrap(), + amount: "500uatom".parse().expect("hardcoded is valid"), delegator_address: user_1.address(), })); let txs = generate_txs([(4, msg)], &user_1, node.chain_id().clone()); - let app_hash = node.step(txs, Timestamp::try_new(60 * 60 * 24, 0).unwrap()); + let app_hash = node.step( + txs, + Timestamp::try_new(60 * 60 * 24, 0).expect("hardcoded is valid"), + ); assert_eq!( hex::encode(app_hash), diff --git a/gaia-rs/tests/staking.rs b/gaia-rs/tests/staking.rs index 265decdb7..bfd965931 100644 --- a/gaia-rs/tests/staking.rs +++ b/gaia-rs/tests/staking.rs @@ -28,7 +28,7 @@ use staking::{ }, tx::{CreateValidatorCli, StakingCommands, StakingTxCli}, }, - CommissionRatesRaw, CommissionRaw, DelegationResponse, Description, Validator, + DelegationResponse, Description, Validator, }; use std::{path::PathBuf, str::FromStr}; use utilities::{acc_address, default_coin, ACC_ADDRESS}; @@ -89,9 +89,9 @@ fn new_validator( website: "".to_string(), security_contact: "".to_string(), details: "".to_string(), - commission_rate: Decimal256::from_atomics(1u64, 1).unwrap(), - commission_max_rate: Decimal256::from_atomics(2u64, 1).unwrap(), - commission_max_change_rate: Decimal256::from_atomics(1u64, 2).unwrap(), + commission_rate: Decimal256::from_atomics(1u64, 1)?, + commission_max_rate: Decimal256::from_atomics(2u64, 1)?, + commission_max_change_rate: Decimal256::from_atomics(1u64, 2)?, min_self_delegation: Uint256::one(), }); let command = GaiaTxCommands::Staking(StakingTxCli { command: tx_cmd }); @@ -273,7 +273,7 @@ fn redelegate() -> anyhow::Result<()> { .events .iter() .find(|e| e.kind == "redelegate") - .unwrap() + .expect("should exists") .attributes .len(), 4 @@ -391,11 +391,12 @@ fn query_validator() -> anyhow::Result<()> { assert_eq!( operator_address, - ValAddress::from_bech32("cosmosvaloper1syavy2npfyt9tcncdtsdzf7kny9lh777yfrfs4").unwrap() + ValAddress::from_bech32("cosmosvaloper1syavy2npfyt9tcncdtsdzf7kny9lh777yfrfs4") + .expect("hardcoded is valid") ); assert_eq!( delegator_shares, - Decimal256::from_atomics(100u64, 0).unwrap() + Decimal256::from_atomics(100u64, 0).expect("hardcoded is valid") ); assert_eq!( description, @@ -404,12 +405,12 @@ fn query_validator() -> anyhow::Result<()> { ..Default::default() } ); - assert_eq!(consensus_pubkey, serde_json::from_str("{\"type\":\"tendermint/PubKeyEd25519\",\"value\":\"+uo5x4+nFiCBt2MuhVwT5XeMfj6ttkjY/JC6WyHb+rE=\"}").unwrap()); + assert_eq!(consensus_pubkey, serde_json::from_str("{\"type\":\"tendermint/PubKeyEd25519\",\"value\":\"+uo5x4+nFiCBt2MuhVwT5XeMfj6ttkjY/JC6WyHb+rE=\"}").expect("hardcoded is valid")); assert!(!jailed); assert_eq!(tokens, Uint256::from(100u64)); assert_eq!( - CommissionRaw::from(commission).commission_rates, - Some(CommissionRatesRaw { + ibc_proto::cosmos::staking::v1beta1::Commission::from(commission).commission_rates, + Some(ibc_proto::cosmos::staking::v1beta1::CommissionRates { rate: 10u64.pow(17).to_string(), max_rate: (2 * 10u64.pow(17)).to_string(), max_change_rate: 10u64.pow(16).to_string(), @@ -449,10 +450,10 @@ fn query_delegation() -> anyhow::Result<()> { delegation: Some(staking::Delegation { delegator_address, validator_address, - shares: Decimal256::from_atomics(110u64, 0).unwrap(), + shares: Decimal256::from_atomics(110u64, 0).expect("hardcoded is valid"), }), balance: Some(UnsignedCoin { - denom: "uatom".try_into().unwrap(), + denom: "uatom".try_into().expect("hardcoded is valid"), amount: Uint256::from(110u64), }), }), diff --git a/gears/Cargo.toml b/gears/Cargo.toml index 8987c117d..f1d73f26c 100644 --- a/gears/Cargo.toml +++ b/gears/Cargo.toml @@ -8,6 +8,7 @@ workspace = true [dependencies] #local +extensions = { path = "../extensions" } address = { path = "../address" } tendermint = { path = "../tendermint" } core-types = { path = "../core-types" } @@ -39,7 +40,6 @@ tracing-subscriber = { workspace = true } sha2 = { workspace = true } regex = { workspace = true } derive_more = { workspace = true } -itertools = "0.13.0" #serialization prost = { workspace = true } diff --git a/gears/src/baseapp/abci.rs b/gears/src/baseapp/abci.rs index 9f724c07b..335824611 100644 --- a/gears/src/baseapp/abci.rs +++ b/gears/src/baseapp/abci.rs @@ -10,6 +10,7 @@ use crate::params::ParamsSubspaceKey; use crate::types::gas::Gas; use bytes::Bytes; use database::Database; +use extensions::lock::AcquireRwLock; use tendermint::{ application::ABCIApplication, types::{ @@ -130,7 +131,7 @@ impl } fn check_tx(&self, RequestCheckTx { tx, r#type }: RequestCheckTx) -> ResponseCheckTx { - let mut state = self.state.write().expect(POISONED_LOCK); + let mut state = self.state.acquire_write(); let CheckTxMode { block_gas_meter, @@ -224,7 +225,7 @@ impl } fn commit(&self) -> ResponseCommit { - let height = self.get_block_header().unwrap().height; + let height = self.get_block_header().height; let hash = self.state.write().expect(POISONED_LOCK).commit(); @@ -281,9 +282,7 @@ impl fn end_block(&self, request: RequestEndBlock) -> ResponseEndBlock { let mut state = self.state.write().expect(POISONED_LOCK); - let header = self - .get_block_header() - .expect("block header is set in begin block"); + let header = self.get_block_header(); let consensus_params = { self.baseapp_params_keeper diff --git a/gears/src/baseapp/mod.rs b/gears/src/baseapp/mod.rs index 7620aead3..f19bddf70 100644 --- a/gears/src/baseapp/mod.rs +++ b/gears/src/baseapp/mod.rs @@ -47,7 +47,7 @@ pub use query::*; pub struct BaseApp { state: Arc>>, abci_handler: H, - block_header: Arc>>, // passed by Tendermint in call to begin_block + block_header: Arc>, // passed by Tendermint in call to begin_block baseapp_params_keeper: BaseAppParamsKeeper, options: NodeOptions, _info_marker: PhantomData, @@ -57,7 +57,11 @@ impl BaseApp { pub fn new(db: DB, params_subspace_key: PSK, abci_handler: H, options: NodeOptions) -> Self { - let mut multi_store = ApplicationMultiBank::new(db); + let multi_store = ApplicationMultiBank::new(db); + let mut multi_store = match multi_store { + Ok(ms) => ms, + Err(err) => panic!("Failed to init MultiStore with err: {err}"), + }; let baseapp_params_keeper = BaseAppParamsKeeper { params_subspace_key, @@ -73,7 +77,7 @@ impl Self { abci_handler, - block_header: Arc::new(RwLock::new(None)), + block_header: Arc::new(RwLock::new(Default::default())), baseapp_params_keeper, state: Arc::new(RwLock::new(ApplicationState::new( Gas::from(max_gas), @@ -84,13 +88,13 @@ impl } } - fn get_block_header(&self) -> Option
{ + fn get_block_header(&self) -> Header { self.block_header.read().expect(POISONED_LOCK).clone() } fn set_block_header(&self, header: Header) { let mut current_header = self.block_header.write().expect(POISONED_LOCK); - *current_header = Some(header); + *current_header = header; } fn run_query(&self, request: &RequestQuery) -> Result { @@ -118,9 +122,7 @@ impl RunTxError::InvalidTransaction(e.to_string()) })?; - let header = self - .get_block_header() - .expect("block header is set in begin block"); //TODO: return error + let header = self.get_block_header(); let height = header.height; let consensus_params = { diff --git a/gears/src/baseapp/params.rs b/gears/src/baseapp/params.rs index b230e4dfd..f0130bd3e 100644 --- a/gears/src/baseapp/params.rs +++ b/gears/src/baseapp/params.rs @@ -1,4 +1,5 @@ use database::Database; +use extensions::corruption::UnwrapCorrupt; use kv_store::StoreKey; use serde::{Deserialize, Serialize}; use serde_with::serde_as; @@ -96,9 +97,12 @@ impl ParamsSerialize for ConsensusParams { impl ParamsDeserialize for ConsensusParams { fn from_raw(fields: HashMap<&'static str, Vec>) -> Self { Self { - block: serde_json::from_slice(fields.get(KEY_BLOCK_PARAMS).unwrap()).unwrap(), - evidence: serde_json::from_slice(fields.get(KEY_EVIDENCE_PARAMS).unwrap()).unwrap(), - validator: serde_json::from_slice(fields.get(KEY_VALIDATOR_PARAMS).unwrap()).unwrap(), + block: serde_json::from_slice(fields.get(KEY_BLOCK_PARAMS).unwrap_or_corrupt()) + .unwrap_or_corrupt(), + evidence: serde_json::from_slice(fields.get(KEY_EVIDENCE_PARAMS).unwrap_or_corrupt()) + .unwrap_or_corrupt(), + validator: serde_json::from_slice(fields.get(KEY_VALIDATOR_PARAMS).unwrap_or_corrupt()) + .unwrap_or_corrupt(), } } } @@ -278,6 +282,7 @@ mod tests { use super::*; use database::MemDB; + use extensions::testing::UnwrapTesting; use key_derive::{ParamsKeys, StoreKeys}; use kv_store::bank::multi::ApplicationMultiBank; use tendermint::types::{ @@ -294,7 +299,7 @@ mod tests { .into(); assert_eq!( - serde_json::to_string(¶ms).unwrap(), + serde_json::to_string(¶ms).expect("hardcoded is valid"), "{\"max_age_num_blocks\":\"0\",\"max_age_duration\":\"10000000030\",\"max_bytes\":\"0\"}" .to_string() ); @@ -315,7 +320,8 @@ mod tests { params_subspace_key: SubspaceKey::Params, }; - let mut multi_store = ApplicationMultiBank::<_, SubspaceKey>::new(MemDB::new()); + let mut multi_store = + ApplicationMultiBank::<_, SubspaceKey>::new(MemDB::new()).unwrap_test(); let before_hash = multi_store.head_commit_hash(); @@ -348,7 +354,8 @@ mod tests { params_subspace_key: SubspaceKey::Params, }; - let mut multi_store = ApplicationMultiBank::<_, SubspaceKey>::new(MemDB::new()); + let mut multi_store = + ApplicationMultiBank::<_, SubspaceKey>::new(MemDB::new()).unwrap_test(); let mut ctx = InitContext::new( &mut multi_store, diff --git a/gears/src/config.rs b/gears/src/config.rs index d44f5bc33..38667484c 100644 --- a/gears/src/config.rs +++ b/gears/src/config.rs @@ -4,12 +4,12 @@ use std::io::Write; use std::net::{Ipv4Addr, SocketAddr}; use std::path::{Path, PathBuf}; +use extensions::socket_addr; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use tendermint::rpc::url::Url; use crate::defaults::{CONFIG_DIR, CONFIG_FILE_NAME, GENESIS_FILE_NAME}; -use crate::socket_addr; use crate::types::base::min_gas::MinGasPrices; pub const DEFAULT_GRPC_LISTEN_ADDR: SocketAddr = socket_addr!(127, 0, 0, 1, 8080); @@ -72,7 +72,7 @@ impl Config { .render("config", &cfg) .expect("Config will always work with the CONFIG_TEMPLATE"); - let app_cfg = toml::to_string(&cfg.app_config).unwrap(); + let app_cfg = toml::to_string(&cfg.app_config)?; file.write_all(config.as_bytes())?; writeln!(file)?; diff --git a/gears/src/crypto/secp256k1.rs b/gears/src/crypto/secp256k1.rs index 884b81920..b2cd58e08 100644 --- a/gears/src/crypto/secp256k1.rs +++ b/gears/src/crypto/secp256k1.rs @@ -137,11 +137,11 @@ mod tests { "key": "Auvdf+T963bciiBe9l15DNMOijdaXCUo6zqSOvH7TXlN" }"#, ) - .unwrap(); + .expect("hardcoded is valid"); } #[test] - fn verify_signature_works() { + fn verify_signature_works() -> Result<(), SigningError> { let key: Secp256k1PubKey = serde_json::from_str( r#"{ "key": "A7Jg0Wg+RHwI7CAkSbCjpfWFROGtYYkUlaBVxCT6UXJ4" @@ -191,6 +191,6 @@ mod tests { 109, 86, 11, 164, 83, 9, 12, 79, ]; - key.verify_signature(message, signature).unwrap(); + key.verify_signature(message, signature) } } diff --git a/gears/src/ext/mod.rs b/gears/src/ext/mod.rs deleted file mode 100644 index 5fc229550..000000000 --- a/gears/src/ext/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -mod pagination; -mod socker_addr; -mod try_map; - -pub use pagination::*; -pub use try_map::*; diff --git a/gears/src/lib.rs b/gears/src/lib.rs index 31187bb34..987fae8c9 100644 --- a/gears/src/lib.rs +++ b/gears/src/lib.rs @@ -8,7 +8,6 @@ pub mod context; pub mod crypto; pub mod defaults; pub mod error; -pub mod ext; pub mod grpc; pub mod params; pub mod rest; @@ -20,6 +19,10 @@ pub mod utils; #[cfg(feature = "xmods")] pub mod x; +pub mod extensions { + pub use extensions::*; +} + pub mod keyring { pub use keyring::*; } diff --git a/gears/src/params/mod.rs b/gears/src/params/mod.rs index f972c9bbd..b7c30b453 100644 --- a/gears/src/params/mod.rs +++ b/gears/src/params/mod.rs @@ -6,6 +6,7 @@ use std::{ }; use database::{prefix::PrefixDB, Database}; +use extensions::corruption::UnwrapCorrupt; use kv_store::StoreKey; use crate::context::{InfallibleContext, InfallibleContextMut}; @@ -94,15 +95,15 @@ impl ParamKind { where ::Err: std::fmt::Debug, { - String::from_utf8(value) - .expect("should be valid utf-8") + let value = String::from_utf8(value).expect("should be valid utf-8"); + + value .strip_suffix('\"') - .unwrap() // TODO - .strip_prefix('\"') - .unwrap() // TODO - .to_owned() + .and_then(|this| this.strip_prefix('\"')) + .map(String::from) + .unwrap_or(value) .parse() - .unwrap() // TODO + .unwrap_or_corrupt() } match self { diff --git a/gears/src/rest/handlers.rs b/gears/src/rest/handlers.rs index 17d2c3e44..b73b4b06b 100644 --- a/gears/src/rest/handlers.rs +++ b/gears/src/rest/handlers.rs @@ -1,6 +1,5 @@ use crate::application::ApplicationInfo; use crate::baseapp::NodeQueryHandler; -use crate::ext::{IteratorPaginateByOffset, PaginationByOffset}; use crate::rest::error::HTTPError; use crate::types::pagination::response::PaginationResponse; use crate::types::request::tx::BroadcastTxRequest; @@ -17,6 +16,7 @@ use axum::extract::{Path, Query as AxumQuery, State}; use axum::Json; use bytes::Bytes; use core_types::Protobuf; +use extensions::pagination::{IteratorPaginateByOffset, PaginationByOffset}; use ibc_proto::cosmos::tx::v1beta1::BroadcastMode; use serde::Deserialize; use tendermint::informal::Hash; diff --git a/gears/src/signing/handler.rs b/gears/src/signing/handler.rs index 2bd257c33..47bf74842 100644 --- a/gears/src/signing/handler.rs +++ b/gears/src/signing/handler.rs @@ -71,6 +71,7 @@ mod tests { use ciborium::Value; use core_types::tx::mode_info::{ModeInfo, SignMode}; use cosmwasm_std::Uint256; + use extensions::testing::UnwrapTesting; use std::{collections::BTreeMap, str::FromStr}; use tendermint::types::chain_id::ChainId; use vec1::vec1; @@ -96,7 +97,7 @@ mod tests { denom: Denom::try_from("uatom".to_owned())?, amount: Uint256::from(2000u32), }]) - .unwrap(), + .unwrap_test(), ), gas_limit: 100000_u64.try_into().expect("this is a valid gas limit"), payer: None, @@ -130,7 +131,7 @@ mod tests { denom: Denom::try_from("uatom".to_string())?, amount: Uint256::from(10000000u32), }]) - .unwrap(), + .unwrap_test(), }], memo: String::new(), timeout_height: 0, @@ -318,7 +319,7 @@ mod tests { denom: Denom::try_from("uatom".to_string())?, amount: Uint256::from(1u8), }]) - .unwrap(), + .unwrap_test(), }], memo: String::new(), timeout_height: 0, @@ -420,7 +421,7 @@ mod tests { denom: Denom::try_from("uatom".to_string())?, amount: Uint256::from(1u8), }]) - .unwrap(), + .unwrap_test(), }], memo: String::new(), timeout_height: 0, diff --git a/gears/src/signing/renderer/primitives/coin.rs b/gears/src/signing/renderer/primitives/coin.rs index d3e7cd9fb..c588f34d8 100644 --- a/gears/src/signing/renderer/primitives/coin.rs +++ b/gears/src/signing/renderer/primitives/coin.rs @@ -119,6 +119,7 @@ mod tests { use crate::types::{base::coin::UnsignedCoin, rendering::screen::Content}; use anyhow::Ok; use cosmwasm_std::Uint256; + use extensions::testing::UnwrapTesting; #[test] fn coin_formatting() -> anyhow::Result<()> { @@ -127,12 +128,12 @@ mod tests { amount: Uint256::from(10000000_u64), }; - let expected_content = Content::try_new("10 ATOM".to_string()).unwrap(); + let expected_content = Content::try_new("10 ATOM".to_string()).unwrap_test(); let actual_content = DefaultPrimitiveRenderer::try_format_with_metadata(coin, &TestMetadataGetter); - assert_eq!(expected_content, actual_content.unwrap()); + assert_eq!(expected_content, actual_content.unwrap_test()); Ok(()) } @@ -144,12 +145,12 @@ mod tests { amount: Uint256::from(1u8), }; - let expected_content = Content::try_new("0.000001 ATOM".to_string()).unwrap(); + let expected_content = Content::try_new("0.000001 ATOM".to_string()).unwrap_test(); let actual_content = DefaultPrimitiveRenderer::try_format_with_metadata(coin, &TestMetadataGetter); - assert_eq!(expected_content, actual_content.unwrap()); + assert_eq!(expected_content, actual_content.unwrap_test()); Ok(()) } @@ -161,12 +162,12 @@ mod tests { amount: Uint256::from(0u8), }; - let expected_content = Content::try_new("0 ATOM".to_string()).unwrap(); + let expected_content = Content::try_new("0 ATOM".to_string()).unwrap_test(); let actual_content = DefaultPrimitiveRenderer::try_format_with_metadata(coin, &TestMetadataGetter); - assert_eq!(expected_content, actual_content.unwrap()); + assert_eq!(expected_content, actual_content.unwrap_test()); Ok(()) } @@ -178,12 +179,12 @@ mod tests { amount: Uint256::from(10_000u16), }; - let expected_content = Content::try_new("10'000 ATOM".to_string()).unwrap(); + let expected_content = Content::try_new("10'000 ATOM".to_string()).unwrap_test(); let actual_content = DefaultPrimitiveRenderer::try_format_with_metadata(coin, &TestMetadataGetter); - assert_eq!(expected_content, actual_content.unwrap()); + assert_eq!(expected_content, actual_content.unwrap_test()); Ok(()) } diff --git a/gears/src/signing/renderer/primitives/decimal256.rs b/gears/src/signing/renderer/primitives/decimal256.rs index 032ce0a11..2a1321790 100644 --- a/gears/src/signing/renderer/primitives/decimal256.rs +++ b/gears/src/signing/renderer/primitives/decimal256.rs @@ -25,6 +25,7 @@ impl PrimitiveValueRenderer for DefaultPrimitiveRenderer { #[cfg(test)] mod tests { use cosmwasm_std::Decimal256; + use extensions::testing::UnwrapTesting; use crate::signing::renderer::value_renderer::{ DefaultPrimitiveRenderer, PrimitiveValueRenderer, @@ -50,9 +51,9 @@ mod tests { ]; for (i, expected) in test_data { - let actual = DefaultPrimitiveRenderer::format(Decimal256::from_str(i).unwrap()); + let actual = DefaultPrimitiveRenderer::format(Decimal256::from_str(i).unwrap_test()); - assert_eq!(Content::try_new(expected).unwrap(), actual); + assert_eq!(Content::try_new(expected).unwrap_test(), actual); } } } diff --git a/gears/src/signing/renderer/primitives/send_coins.rs b/gears/src/signing/renderer/primitives/send_coins.rs index fb5ff79cb..48d4e7ce6 100644 --- a/gears/src/signing/renderer/primitives/send_coins.rs +++ b/gears/src/signing/renderer/primitives/send_coins.rs @@ -36,6 +36,7 @@ impl TryPrimitiveValueRendererWithMetadata for DefaultPrimitiveRe #[cfg(test)] mod tests { use cosmwasm_std::Uint256; + use extensions::testing::UnwrapTesting; use crate::signing::renderer::test_functions::TestMetadataGetter; use crate::signing::renderer::value_renderer::{ @@ -53,14 +54,14 @@ mod tests { amount: Uint256::from(2000u32), }; - let expected_content = Content::try_new("0.002 ATOM".to_string()).unwrap(); + let expected_content = Content::try_new("0.002 ATOM".to_string()).unwrap_test(); let actual_content = DefaultPrimitiveRenderer::try_format_with_metadata( - UnsignedCoins::new(vec![coin]).unwrap(), + UnsignedCoins::new(vec![coin]).unwrap_test(), &TestMetadataGetter, ); - assert_eq!(expected_content, actual_content.unwrap()); + assert_eq!(expected_content, actual_content.unwrap_test()); Ok(()) } @@ -77,14 +78,15 @@ mod tests { amount: Uint256::from(2000u32), }; - let expected_content = Content::try_new("0.002 AAUON, 0.002 ATOM".to_string()).unwrap(); + let expected_content = + Content::try_new("0.002 AAUON, 0.002 ATOM".to_string()).unwrap_test(); let actual_content = DefaultPrimitiveRenderer::try_format_with_metadata( - UnsignedCoins::new(vec![coin1, coin2]).unwrap(), + UnsignedCoins::new(vec![coin1, coin2]).unwrap_test(), &TestMetadataGetter, ); - assert_eq!(expected_content, actual_content.unwrap()); + assert_eq!(expected_content, actual_content.unwrap_test()); Ok(()) } @@ -96,14 +98,14 @@ mod tests { amount: Uint256::from(2047u32), }; - let expected_content = Content::try_new("0.002047 ATOM".to_string()).unwrap(); + let expected_content = Content::try_new("0.002047 ATOM".to_string()).unwrap_test(); let actual_content = DefaultPrimitiveRenderer::try_format_with_metadata( - UnsignedCoins::new(vec![coin]).unwrap(), + UnsignedCoins::new(vec![coin]).unwrap_test(), &TestMetadataGetter, ); - assert_eq!(expected_content, actual_content.unwrap()); + assert_eq!(expected_content, actual_content.unwrap_test()); Ok(()) } @@ -115,14 +117,14 @@ mod tests { amount: Uint256::from(2_123_456u32), }; - let expected_content = Content::try_new("2.123456 ATOM".to_string()).unwrap(); + let expected_content = Content::try_new("2.123456 ATOM".to_string()).unwrap_test(); let actual_content = DefaultPrimitiveRenderer::try_format_with_metadata( - UnsignedCoins::new(vec![coin]).unwrap(), + UnsignedCoins::new(vec![coin]).unwrap_test(), &TestMetadataGetter, ); - assert_eq!(expected_content, actual_content.unwrap()); + assert_eq!(expected_content, actual_content.unwrap_test()); Ok(()) } diff --git a/gears/src/signing/renderer/primitives/uint256.rs b/gears/src/signing/renderer/primitives/uint256.rs index 5196e43d5..e6b39b99a 100644 --- a/gears/src/signing/renderer/primitives/uint256.rs +++ b/gears/src/signing/renderer/primitives/uint256.rs @@ -24,6 +24,7 @@ impl PrimitiveValueRenderer for DefaultPrimitiveRenderer { #[cfg(test)] mod tests { use cosmwasm_std::Uint256; + use extensions::testing::UnwrapTesting; use crate::signing::renderer::value_renderer::{ DefaultPrimitiveRenderer, PrimitiveValueRenderer, @@ -50,7 +51,7 @@ mod tests { for (i, expected) in test_data { let actual = DefaultPrimitiveRenderer::format(Uint256::from(i)); - assert_eq!(Content::try_new(expected).unwrap(), actual); + assert_eq!(Content::try_new(expected).unwrap_test(), actual); } } } diff --git a/gears/src/signing/renderer/tx/tx.rs b/gears/src/signing/renderer/tx/tx.rs index bd1b744b0..cc7243f15 100644 --- a/gears/src/signing/renderer/tx/tx.rs +++ b/gears/src/signing/renderer/tx/tx.rs @@ -247,6 +247,7 @@ mod tests { use crate::types::tx::signer::SignerData; use core_types::tx::mode_info::{ModeInfo, SignMode}; use cosmwasm_std::Uint256; + use extensions::testing::UnwrapTesting; use std::str::FromStr; use tendermint::types::chain_id::ChainId; use vec1::vec1; @@ -291,7 +292,7 @@ mod tests { denom: Denom::try_from("uatom".to_owned())?, amount: Uint256::from(2000u32), }]) - .unwrap(), + .unwrap_test(), ), gas_limit: 100000_u64.try_into().expect("this is a valid gas limit"), payer: None, @@ -325,7 +326,7 @@ mod tests { denom: Denom::try_from("uatom".to_string())?, amount: Uint256::from(10000000u32), }]) - .unwrap(), + .unwrap_test(), }], memo: String::new(), timeout_height: 0, diff --git a/gears/src/signing/std_sign_doc.rs b/gears/src/signing/std_sign_doc.rs index 1c5ca747a..e3983edb7 100644 --- a/gears/src/signing/std_sign_doc.rs +++ b/gears/src/signing/std_sign_doc.rs @@ -86,6 +86,8 @@ impl StdSignDoc { #[cfg(test)] mod test { + use extensions::testing::UnwrapTesting; + use crate::crypto::secp256k1::Secp256k1PubKey; use super::*; @@ -100,9 +102,9 @@ mod test { "key":"AtTjh9XR+GbfnqBXHb1Gcj2a6i3oWlTiqT0SDIDWGYFR" }"#, ) - .unwrap(); + .unwrap_test(); - let bytes = serde_json::to_vec(&std_sign_doc).unwrap(); + let bytes = serde_json::to_vec(&std_sign_doc).unwrap_test(); let exp = vec![ 123, 34, 97, 99, 99, 111, 117, 110, 116, 95, 110, 117, 109, 98, 101, 114, 34, 58, 34, 53, 34, 44, 34, 99, 104, 97, 105, 110, 95, 105, 100, 34, 58, 34, 116, 101, 115, 116, diff --git a/gears/src/types/account.rs b/gears/src/types/account.rs index 1c5a20cbe..4dfa1ba6e 100644 --- a/gears/src/types/account.rs +++ b/gears/src/types/account.rs @@ -223,6 +223,7 @@ impl Protobuf for Account {} mod tests { use core_types::Protobuf; + use extensions::testing::UnwrapTesting; use crate::types::{account::BaseAccount, address::AccAddress}; @@ -230,7 +231,7 @@ mod tests { fn base_account_encode_works() { let account = BaseAccount { address: AccAddress::from_bech32("cosmos1syavy2npfyt9tcncdtsdzf7kny9lh777pahuux") - .unwrap(), + .unwrap_test(), pub_key: None, account_number: 0, sequence: 0, diff --git a/gears/src/types/auth/gas.rs b/gears/src/types/auth/gas.rs index d50229ae2..9e7fa6c97 100644 --- a/gears/src/types/auth/gas.rs +++ b/gears/src/types/auth/gas.rs @@ -173,11 +173,13 @@ pub enum GasError { #[cfg(test)] mod tests { + use extensions::testing::UnwrapTesting; + use super::*; #[test] fn gas_try_from_into_u64() { - let gas = Gas::try_from(100_u64).unwrap(); + let gas = Gas::try_from(100_u64).unwrap_test(); assert_eq!(u64::from(gas), 100); } @@ -192,13 +194,13 @@ mod tests { #[test] fn test_gas_try_from_limit_ok() { let raw_gas: u64 = u63::MAX.into(); - let gas = Gas::try_from(raw_gas).expect("should not error"); + let gas = Gas::try_from(raw_gas).unwrap_test(); assert_eq!(gas, Gas::MAX); } #[test] fn test_gas_from_str() { - let gas = Gas::from_str("100").unwrap(); + let gas = Gas::from_str("100").unwrap_test(); assert_eq!(gas, u63::new(100).into()); } diff --git a/gears/src/types/base/coin/unsigned.rs b/gears/src/types/base/coin/unsigned.rs index e930440d9..d3c5a80d4 100644 --- a/gears/src/types/base/coin/unsigned.rs +++ b/gears/src/types/base/coin/unsigned.rs @@ -1,7 +1,8 @@ use core_types::{errors::CoreError, Protobuf}; use cosmwasm_std::Uint256; +use extensions::pagination::PaginationKey; use serde::{Deserialize, Serialize}; -use std::str::FromStr; +use std::{borrow::Cow, str::FromStr}; use crate::types::{base::errors::CoinError, denom::Denom, errors::DenomError}; @@ -115,3 +116,9 @@ impl From for inner::IntProto { } impl Protobuf for Uint256Proto {} + +impl PaginationKey for UnsignedCoin { + fn iterator_key(&self) -> Cow<'_, [u8]> { + Cow::Borrowed(self.denom.as_ref()) + } +} diff --git a/gears/src/types/base/coins/decimal.rs b/gears/src/types/base/coins/decimal.rs index d969d985d..f9b066afa 100644 --- a/gears/src/types/base/coins/decimal.rs +++ b/gears/src/types/base/coins/decimal.rs @@ -239,6 +239,7 @@ mod tests { use super::*; use crate::types::denom::Denom; use cosmwasm_std::Uint256; + use extensions::testing::UnwrapTesting; use std::{str::FromStr, sync::OnceLock}; static DENOMS: OnceLock<[Denom; 4]> = OnceLock::new(); @@ -262,11 +263,11 @@ mod tests { if v != 0 { coins.push(DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[i].clone(), - amount: Decimal256::from_atomics(v, 0).unwrap(), + amount: Decimal256::from_atomics(v, 0).unwrap_test(), }) } } - DecimalCoins::new(coins).unwrap() + DecimalCoins::new(coins).unwrap_test() } #[test] @@ -298,25 +299,25 @@ mod tests { fn checked_add() -> anyhow::Result<()> { let dec_coins_1 = generate_coins(vec![100, 100, 100]); let dec_coins_2 = generate_coins(vec![50, 50, 0, 50]); - let dec_coins_add = dec_coins_1.checked_add(&dec_coins_2).unwrap(); + let dec_coins_add = dec_coins_1.checked_add(&dec_coins_2).unwrap_test(); assert_eq!( dec_coins_add.into_inner(), vec![ DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), - amount: Decimal256::from_atomics(150u64, 0).unwrap(), + amount: Decimal256::from_atomics(150u64, 0).unwrap_test(), }, DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[1].clone(), - amount: Decimal256::from_atomics(150u64, 0).unwrap(), + amount: Decimal256::from_atomics(150u64, 0).unwrap_test(), }, DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[2].clone(), - amount: Decimal256::from_atomics(100u64, 0).unwrap(), + amount: Decimal256::from_atomics(100u64, 0).unwrap_test(), }, DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[3].clone(), - amount: Decimal256::from_atomics(50u64, 0).unwrap(), + amount: Decimal256::from_atomics(50u64, 0).unwrap_test(), }, ] ); @@ -325,8 +326,8 @@ mod tests { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), amount: Decimal256::new(Uint256::MAX), }]; - let dec_coins_1 = DecimalCoins::new(dec_coins_inner.clone()).unwrap(); - let dec_coins_2 = DecimalCoins::new(dec_coins_inner).unwrap(); + let dec_coins_1 = DecimalCoins::new(dec_coins_inner.clone()).unwrap_test(); + let dec_coins_2 = DecimalCoins::new(dec_coins_inner).unwrap_test(); assert!(dec_coins_1.checked_add(&dec_coins_2).is_err()); @@ -353,15 +354,15 @@ mod tests { &vec![ DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), - amount: Decimal256::from_atomics(50u64, 0).unwrap(), + amount: Decimal256::from_atomics(50u64, 0).unwrap_test(), }, DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[1].clone(), - amount: Decimal256::from_atomics(50u64, 0).unwrap(), + amount: Decimal256::from_atomics(50u64, 0).unwrap_test(), }, DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[2].clone(), - amount: Decimal256::from_atomics(100u64, 0).unwrap(), + amount: Decimal256::from_atomics(100u64, 0).unwrap_test(), }, ] ); @@ -381,12 +382,12 @@ mod tests { DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), // 3.03 - amount: Decimal256::from_atomics(3u64, 0).unwrap(), + amount: Decimal256::from_atomics(3u64, 0).unwrap_test(), }, DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[1].clone(), // 2.73 - amount: Decimal256::from_atomics(2u64, 0).unwrap(), + amount: Decimal256::from_atomics(2u64, 0).unwrap_test(), }, ] ); @@ -395,7 +396,7 @@ mod tests { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), amount: Decimal256::new(Uint256::MAX), }]; - let dec_coins = DecimalCoins::new(dec_coins_inner.clone()).unwrap(); + let dec_coins = DecimalCoins::new(dec_coins_inner.clone()).unwrap_test(); let dec_coins_mul_truncated = dec_coins.checked_mul_dec_truncate(Decimal256::new(Uint256::MAX)); assert!(dec_coins_mul_truncated.is_err()); @@ -415,17 +416,17 @@ mod tests { DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), // > 2.5 - amount: Decimal256::from_atomics(3u64, 0).unwrap(), + amount: Decimal256::from_atomics(3u64, 0).unwrap_test(), }, DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[1].clone(), // == 2.5 - amount: Decimal256::from_atomics(3u64, 0).unwrap(), + amount: Decimal256::from_atomics(3u64, 0).unwrap_test(), }, DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[2].clone(), // < 2.5 - amount: Decimal256::from_atomics(2u64, 0).unwrap(), + amount: Decimal256::from_atomics(2u64, 0).unwrap_test(), }, ] ); @@ -434,7 +435,7 @@ mod tests { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), amount: Decimal256::new(Uint256::MAX), }]; - let dec_coins = DecimalCoins::new(dec_coins_inner.clone()).unwrap(); + let dec_coins = DecimalCoins::new(dec_coins_inner.clone()).unwrap_test(); let dec_coins_mul = dec_coins.checked_mul_dec(Decimal256::new(Uint256::MAX)); assert!(dec_coins_mul.is_err()); @@ -453,12 +454,12 @@ mod tests { DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), // 1.7 - amount: Decimal256::from_atomics(1u64, 0).unwrap(), + amount: Decimal256::from_atomics(1u64, 0).unwrap_test(), }, DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[1].clone(), // 1.2 - amount: Decimal256::from_atomics(1u64, 0).unwrap(), + amount: Decimal256::from_atomics(1u64, 0).unwrap_test(), }, ] ); @@ -482,7 +483,7 @@ mod tests { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), amount: Uint256::from(17u64), },]) - .unwrap() + .unwrap_test() ) ); assert!(change.is_none()); @@ -491,7 +492,7 @@ mod tests { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), amount: Decimal256::from_atomics(5u64, 1).expect("hardcoded value cannot fail"), }]; - let dec_coins = DecimalCoins::new(dec_coins_inner.clone()).unwrap(); + let dec_coins = DecimalCoins::new(dec_coins_inner.clone()).unwrap_test(); let (truncated, change) = dec_coins.truncate_decimal(); assert!(truncated.is_none()); assert_eq!( @@ -499,9 +500,9 @@ mod tests { Some( DecimalCoins::new(vec![DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), - amount: Decimal256::from_atomics(5u64, 1).unwrap(), + amount: Decimal256::from_atomics(5u64, 1).unwrap_test(), },]) - .unwrap() + .unwrap_test() ) ); @@ -509,7 +510,7 @@ mod tests { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), amount: Decimal256::from_atomics(175u64, 1).expect("hardcoded value cannot fail"), }]; - let dec_coins = DecimalCoins::new(dec_coins_inner.clone()).unwrap(); + let dec_coins = DecimalCoins::new(dec_coins_inner.clone()).unwrap_test(); let (truncated, change) = dec_coins.truncate_decimal(); assert_eq!( truncated, @@ -518,7 +519,7 @@ mod tests { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), amount: Uint256::from(17u64), },]) - .unwrap() + .unwrap_test() ) ); assert_eq!( @@ -526,9 +527,9 @@ mod tests { Some( DecimalCoins::new(vec![DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), - amount: Decimal256::from_atomics(5u64, 1).unwrap(), + amount: Decimal256::from_atomics(5u64, 1).unwrap_test(), },]) - .unwrap() + .unwrap_test() ) ); @@ -546,12 +547,12 @@ mod tests { &vec![ DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[0].clone(), - amount: Decimal256::from_atomics(90u64, 0).unwrap(), + amount: Decimal256::from_atomics(90u64, 0).unwrap_test(), }, DecimalCoin { denom: DENOMS.get().expect("cannot fail initialized variable")[2].clone(), // 1.2 - amount: Decimal256::from_atomics(20u64, 0).unwrap(), + amount: Decimal256::from_atomics(20u64, 0).unwrap_test(), }, ] ); diff --git a/gears/src/types/base/coins/unsigned.rs b/gears/src/types/base/coins/unsigned.rs index 27566293d..65149d261 100644 --- a/gears/src/types/base/coins/unsigned.rs +++ b/gears/src/types/base/coins/unsigned.rs @@ -100,6 +100,7 @@ impl UnsignedCoins { mod tests { use cosmwasm_std::Uint256; + use extensions::testing::UnwrapTesting; use std::str::FromStr; use crate::types::base::errors::CoinsError; @@ -109,41 +110,41 @@ mod tests { #[test] fn coin_from_string_successes() { let raw = "32454uatom"; - let coin = raw.parse::().unwrap(); + let coin = raw.parse::().unwrap_test(); assert_eq!( UnsignedCoin { - denom: String::from("uatom").try_into().unwrap(), - amount: "32454".try_into().unwrap() + denom: String::from("uatom").try_into().unwrap_test(), + amount: "32454".try_into().unwrap_test() }, coin ); let raw = "0uatom"; - let coin = raw.parse::().unwrap(); + let coin = raw.parse::().unwrap_test(); assert_eq!( UnsignedCoin { - denom: String::from("uatom").try_into().unwrap(), - amount: "0".try_into().unwrap() + denom: String::from("uatom").try_into().unwrap_test(), + amount: "0".try_into().unwrap_test() }, coin ); let raw = "0001uatom"; - let coin = raw.parse::().unwrap(); + let coin = raw.parse::().unwrap_test(); assert_eq!( UnsignedCoin { - denom: String::from("uatom").try_into().unwrap(), - amount: "1".try_into().unwrap() + denom: String::from("uatom").try_into().unwrap_test(), + amount: "1".try_into().unwrap_test() }, coin ); let raw = "12uatom56"; - let coin = raw.parse::().unwrap(); + let coin = raw.parse::().unwrap_test(); assert_eq!( UnsignedCoin { - denom: String::from("uatom56").try_into().unwrap(), - amount: "12".try_into().unwrap() + denom: String::from("uatom56").try_into().unwrap_test(), + amount: "12".try_into().unwrap_test() }, coin ); @@ -171,15 +172,15 @@ mod tests { fn validate_coins_success() { let coins = vec![ UnsignedCoin { - denom: String::from("atom").try_into().unwrap(), + denom: String::from("atom").try_into().unwrap_test(), amount: Uint256::one(), }, UnsignedCoin { - denom: String::from("atom1").try_into().unwrap(), + denom: String::from("atom1").try_into().unwrap_test(), amount: Uint256::one(), }, ]; - UnsignedCoins::new(coins).unwrap(); + UnsignedCoins::new(coins).unwrap_test(); // ibc denoms let coins = vec![ @@ -188,7 +189,7 @@ mod tests { "ibc/7F1D3FCF4AE79E1554D670D1AD949A9BA4E4A3C76C63093E17E446A46061A7A2", ) .try_into() - .unwrap(), + .unwrap_test(), amount: Uint256::one(), }, UnsignedCoin { @@ -196,24 +197,24 @@ mod tests { "ibc/876563AAAACF739EB061C67CDB5EDF2B7C9FD4AA9D876450CC21210807C2820A", ) .try_into() - .unwrap(), - amount: Uint256::from_str("3").unwrap(), + .unwrap_test(), + amount: Uint256::from_str("3").unwrap_test(), }, ]; - UnsignedCoins::new(coins).unwrap(); + UnsignedCoins::new(coins).unwrap_test(); // prefix lexicographical ordering let coins = vec![ UnsignedCoin { - denom: String::from("big").try_into().unwrap(), + denom: String::from("big").try_into().unwrap_test(), amount: Uint256::one(), }, UnsignedCoin { - denom: String::from("bigger").try_into().unwrap(), - amount: Uint256::from_str("3").unwrap(), + denom: String::from("bigger").try_into().unwrap_test(), + amount: Uint256::from_str("3").unwrap_test(), }, ]; - UnsignedCoins::new(coins).unwrap(); + UnsignedCoins::new(coins).unwrap_test(); } #[test] @@ -225,7 +226,7 @@ mod tests { // not positive let coins = vec![UnsignedCoin { - denom: String::from("truer").try_into().unwrap(), + denom: String::from("truer").try_into().unwrap_test(), amount: Uint256::zero(), }]; let err = UnsignedCoins::new(coins); @@ -234,15 +235,15 @@ mod tests { // not all positive let coins = vec![ UnsignedCoin { - denom: String::from("gas").try_into().unwrap(), + denom: String::from("gas").try_into().unwrap_test(), amount: Uint256::one(), }, UnsignedCoin { - denom: String::from("true").try_into().unwrap(), - amount: Uint256::from_str("3").unwrap(), + denom: String::from("true").try_into().unwrap_test(), + amount: Uint256::from_str("3").unwrap_test(), }, UnsignedCoin { - denom: String::from("truer").try_into().unwrap(), + denom: String::from("truer").try_into().unwrap_test(), amount: Uint256::zero(), }, ]; @@ -252,15 +253,15 @@ mod tests { // duplicate denomination let coins = vec![ UnsignedCoin { - denom: String::from("gas").try_into().unwrap(), + denom: String::from("gas").try_into().unwrap_test(), amount: Uint256::one(), }, UnsignedCoin { - denom: String::from("truer").try_into().unwrap(), - amount: Uint256::from_str("3").unwrap(), + denom: String::from("truer").try_into().unwrap_test(), + amount: Uint256::from_str("3").unwrap_test(), }, UnsignedCoin { - denom: String::from("truer").try_into().unwrap(), + denom: String::from("truer").try_into().unwrap_test(), amount: Uint256::one(), }, ]; @@ -270,16 +271,16 @@ mod tests { // not sorted let coins = vec![ UnsignedCoin { - denom: String::from("tree").try_into().unwrap(), + denom: String::from("tree").try_into().unwrap_test(), amount: Uint256::one(), }, UnsignedCoin { - denom: String::from("gas").try_into().unwrap(), - amount: Uint256::from_str("3").unwrap(), + denom: String::from("gas").try_into().unwrap_test(), + amount: Uint256::from_str("3").unwrap_test(), }, UnsignedCoin { - denom: String::from("mineral").try_into().unwrap(), - amount: Uint256::from_str("3").unwrap(), + denom: String::from("mineral").try_into().unwrap_test(), + amount: Uint256::from_str("3").unwrap_test(), }, ]; let err = UnsignedCoins::new(coins); @@ -288,16 +289,16 @@ mod tests { // not sorted 2 let coins = vec![ UnsignedCoin { - denom: String::from("gas").try_into().unwrap(), + denom: String::from("gas").try_into().unwrap_test(), amount: Uint256::one(), }, UnsignedCoin { - denom: String::from("true").try_into().unwrap(), - amount: Uint256::from_str("3").unwrap(), + denom: String::from("true").try_into().unwrap_test(), + amount: Uint256::from_str("3").unwrap_test(), }, UnsignedCoin { - denom: String::from("mineral").try_into().unwrap(), - amount: Uint256::from_str("3").unwrap(), + denom: String::from("mineral").try_into().unwrap_test(), + amount: Uint256::from_str("3").unwrap_test(), }, ]; let err = UnsignedCoins::new(coins); @@ -307,7 +308,7 @@ mod tests { #[test] fn coins_from_string_successes() { let raw_coins = "100atom,30uatom"; - UnsignedCoins::from_str(raw_coins).unwrap(); + UnsignedCoins::from_str(raw_coins).unwrap_test(); } #[test] diff --git a/gears/src/types/decimal256.rs b/gears/src/types/decimal256.rs index 2dfee87bc..55e431e1d 100644 --- a/gears/src/types/decimal256.rs +++ b/gears/src/types/decimal256.rs @@ -38,23 +38,25 @@ impl CosmosDecimalProtoString for Decimal256 { #[cfg(test)] mod tests { + use extensions::testing::UnwrapTesting; + use super::*; #[test] fn decimal256_from_cosmos_proto_string_works() { assert_eq!( - Decimal256::from_cosmos_proto_string("123000000000000000000").unwrap(), - Decimal256::from_str("123").unwrap(), + Decimal256::from_cosmos_proto_string("123000000000000000000").unwrap_test(), + Decimal256::from_str("123").unwrap_test(), ); assert_eq!( - Decimal256::from_cosmos_proto_string("123456000000000000000").unwrap(), - Decimal256::from_str("123.456").unwrap(), + Decimal256::from_cosmos_proto_string("123456000000000000000").unwrap_test(), + Decimal256::from_str("123.456").unwrap_test(), ); assert_eq!( - Decimal256::from_cosmos_proto_string("123456000000000000001").unwrap(), - Decimal256::from_str("123.456000000000000001").unwrap(), + Decimal256::from_cosmos_proto_string("123456000000000000001").unwrap_test(), + Decimal256::from_str("123.456000000000000001").unwrap_test(), ); } @@ -62,21 +64,21 @@ mod tests { fn decimal256_to_cosmos_proto_string_works() { assert_eq!( Decimal256::from_str("123") - .unwrap() + .unwrap_test() .to_cosmos_proto_string(), "123000000000000000000" ); assert_eq!( Decimal256::from_str("123.456") - .unwrap() + .unwrap_test() .to_cosmos_proto_string(), "123456000000000000000" ); assert_eq!( Decimal256::from_str("123.456000000000000001") - .unwrap() + .unwrap_test() .to_cosmos_proto_string(), "123456000000000000001" ); diff --git a/gears/src/types/denom.rs b/gears/src/types/denom.rs index 644664981..d8411a96f 100644 --- a/gears/src/types/denom.rs +++ b/gears/src/types/denom.rs @@ -91,26 +91,28 @@ impl Display for Denom { #[cfg(test)] mod tests { + use extensions::testing::UnwrapTesting; + use super::*; #[test] fn from_string_successes() { - let res: Denom = "abcd".to_string().try_into().unwrap(); + let res: Denom = "abcd".to_string().try_into().unwrap_test(); assert_eq!(Denom("abcd".into()), res); let res: Denom = "ibc/7F1D3FCF4AE79E1554D670D1AD949A9BA4E4A3C76C63093E17E446A46061A7A2" .to_string() .try_into() - .unwrap(); + .unwrap_test(); assert_eq!( Denom("ibc/7F1D3FCF4AE79E1554D670D1AD949A9BA4E4A3C76C63093E17E446A46061A7A2".into()), res ); - let res: Denom = "at0m".to_string().try_into().unwrap(); + let res: Denom = "at0m".to_string().try_into().unwrap_test(); assert_eq!(Denom("at0m".into()), res); - let res: Denom = "Atom".to_string().try_into().unwrap(); + let res: Denom = "Atom".to_string().try_into().unwrap_test(); assert_eq!(Denom("Atom".into()), res); } @@ -149,16 +151,16 @@ mod tests { #[test] fn to_string_success() { - let denom: Denom = "atom".to_string().try_into().unwrap(); + let denom: Denom = "atom".to_string().try_into().unwrap_test(); assert_eq!("atom", denom.to_string()); } #[test] fn serialize_success() { - let res: Denom = "abcd".to_string().try_into().unwrap(); + let res: Denom = "abcd".to_string().try_into().unwrap_test(); assert_eq!( - serde_json::to_string(&res).unwrap(), + serde_json::to_string(&res).unwrap_test(), r#""abcd""#.to_string() ); } diff --git a/gears/src/types/pagination/request.rs b/gears/src/types/pagination/request.rs index ea5ae0984..58787f7fd 100644 --- a/gears/src/types/pagination/request.rs +++ b/gears/src/types/pagination/request.rs @@ -1,8 +1,7 @@ +use extensions::pagination::{Pagination, PaginationByKey, PaginationByOffset}; use serde::Deserialize; use vec1::Vec1; -use crate::ext::{Pagination, PaginationByKey, PaginationByOffset}; - pub(crate) const QUERY_DEFAULT_LIMIT: u8 = 100; #[derive(Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)] diff --git a/gears/src/types/pagination/response.rs b/gears/src/types/pagination/response.rs index 30b8eaa99..bb5ff30b4 100644 --- a/gears/src/types/pagination/response.rs +++ b/gears/src/types/pagination/response.rs @@ -1,3 +1,4 @@ +use extensions::pagination::{PaginationKey, PaginationResultElement}; use serde::{Deserialize, Serialize}; mod inner { @@ -30,3 +31,19 @@ impl From for inner::PageResponse { Self { next_key, total } } } + +impl From> for PaginationResponse { + fn from( + PaginationResultElement { + total, + next_key: next_element, + }: PaginationResultElement, + ) -> Self { + Self { + next_key: next_element + .map(|this| this.iterator_key().into_owned()) + .unwrap_or_default(), + total: total as u64, + } + } +} diff --git a/gears/src/types/rendering/cbor.rs b/gears/src/types/rendering/cbor.rs index 77ffb880c..fde4f65c4 100644 --- a/gears/src/types/rendering/cbor.rs +++ b/gears/src/types/rendering/cbor.rs @@ -24,6 +24,7 @@ mod tests { value::{CanonicalValue, Integer}, Value, }; + use extensions::testing::UnwrapTesting; use super::Cbor; @@ -62,7 +63,7 @@ mod tests { final_map.insert(canonical_key, 3); let mut bytes = Vec::new(); - ciborium::into_writer(&final_map, &mut bytes).unwrap(); + ciborium::into_writer(&final_map, &mut bytes).unwrap_test(); let hex_bytes = hex::encode(bytes); assert_eq!(hex_bytes, "a20a022003") diff --git a/gears/src/types/response/validators.rs b/gears/src/types/response/validators.rs index c5f2b4c5e..c74e205e1 100644 --- a/gears/src/types/response/validators.rs +++ b/gears/src/types/response/validators.rs @@ -1,6 +1,7 @@ +use crate::crypto::public::PublicKey; use crate::types::pagination::response::PaginationResponse; -use crate::{crypto::public::PublicKey, ext::PaginationKey}; use core_types::any::google::Any; +use extensions::pagination::PaginationKey; use serde::{Deserialize, Serialize}; use tendermint::informal::validator::Info; diff --git a/gears/src/types/store/gas/errors.rs b/gears/src/types/store/gas/errors.rs index 559622fda..63c347283 100644 --- a/gears/src/types/store/gas/errors.rs +++ b/gears/src/types/store/gas/errors.rs @@ -1,6 +1,6 @@ -use crate::types::{auth::gas::GasError, gas::GasMeteringErrors}; +use extensions::{gas::UnwrapGasError, pagination::PaginationKey}; -use super::ext::UnwrapGasError; +use crate::types::{auth::gas::GasError, gas::GasMeteringErrors}; // TODO: this error should have two variants, out of gas and gas overflow #[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)] @@ -28,3 +28,9 @@ impl GasStoreErrors { } impl UnwrapGasError for GasStoreErrors {} + +impl PaginationKey for GasStoreErrors { + fn iterator_key(&self) -> std::borrow::Cow<'_, [u8]> { + std::borrow::Cow::Borrowed(&self.key) + } +} diff --git a/gears/src/types/store/gas/mod.rs b/gears/src/types/store/gas/mod.rs index 30a11a46a..ec3f86277 100644 --- a/gears/src/types/store/gas/mod.rs +++ b/gears/src/types/store/gas/mod.rs @@ -1,6 +1,5 @@ mod constants; pub mod errors; -pub mod ext; pub mod guard; pub mod kv; pub mod prefix; diff --git a/gears/src/utils/node/ctx.rs b/gears/src/utils/node/ctx.rs index 858b0f66f..15d0939fc 100644 --- a/gears/src/utils/node/ctx.rs +++ b/gears/src/utils/node/ctx.rs @@ -1,8 +1,4 @@ -use database::MemDB; -use kv_store::{ - bank::multi::{ApplicationMultiBank, TransactionMultiBank}, - StoreKey, -}; +use kv_store::bank::multi::{ApplicationMultiBank, TransactionMultiBank}; use tendermint::types::proto::header::Header; use crate::{ @@ -14,10 +10,6 @@ use crate::{ }, }; -pub fn build_store() -> ApplicationMultiBank { - ApplicationMultiBank::new(MemDB::new()) -} - pub struct ContextOptions { height: u32, header: Header, diff --git a/gears/src/utils/node/helpers.rs b/gears/src/utils/node/helpers.rs index 364dbe5fb..4027c20e3 100644 --- a/gears/src/utils/node/helpers.rs +++ b/gears/src/utils/node/helpers.rs @@ -2,7 +2,7 @@ use address::AccAddress; use bytes::Bytes; use core_types::Protobuf as _; -use kv_store::ext::UnwrapInfallible; +use extensions::infallible::UnwrapInfallible; use prost::Message; use tendermint::types::chain_id::ChainId; diff --git a/gears/src/utils/node/presets.rs b/gears/src/utils/node/presets.rs index 7fe265be3..8536d9961 100644 --- a/gears/src/utils/node/presets.rs +++ b/gears/src/utils/node/presets.rs @@ -62,7 +62,8 @@ pub fn init_node, GS: Genes let chain_id = ChainId::default(); let mnemonic = "race draft rival universe maid cheese steel logic crowd fork comic easy truth drift tomorrow eye buddy head time cash swing swift midnight borrow"; - let mnemonic = bip32::Mnemonic::new(mnemonic, bip32::Language::English).unwrap(); + let mnemonic = + bip32::Mnemonic::new(mnemonic, bip32::Language::English).expect("Invalid mnemonic"); let key_pair = KeyPair::from_mnemonic(&mnemonic); let address = key_pair.get_address(); let consensus_key = crate::tendermint::crypto::new_private_key(); @@ -71,10 +72,11 @@ pub fn init_node, GS: Genes GenesisSource::File(path) => { println!("Loading genesis state from {:?}", path.as_path()); // print current directory - let current_dir = std::env::current_dir().unwrap(); + let current_dir = std::env::current_dir().expect("failed to get current dir"); println!("The current directory is {}", current_dir.display()); - let genesis_state = std::fs::read_to_string(path.as_path()).unwrap(); - serde_json::from_str(&genesis_state).unwrap() + let genesis_state = + std::fs::read_to_string(path.as_path()).expect("failed to read genesis"); + serde_json::from_str(&genesis_state).expect("failed to deserialize genesis state") } GenesisSource::Genesis(genesis) => genesis, GenesisSource::Default => { diff --git a/gears/src/x/ante.rs b/gears/src/x/ante.rs index c90075f9d..b2274ae54 100644 --- a/gears/src/x/ante.rs +++ b/gears/src/x/ante.rs @@ -518,10 +518,7 @@ impl< _phantom: PhantomData, }; - handler - .sign_bytes_get(&f, signer_data, &tx.tx.body, &tx.tx.auth_info) - .unwrap() - //TODO: remove unwrap + handler.sign_bytes_get(&f, signer_data, &tx.tx.body, &tx.tx.auth_info)? } mode => { return Err(AnteError::Validation(format!( @@ -596,6 +593,7 @@ impl< // use database::MemDB; // use proto_messages::cosmos::auth::v1beta1::{Account, BaseAccount}; // use proto_types::AccAddress; +// use extensions::testing::UnwrapCorrupt; // use crate::store::MultiStore; // use crate::types::tests::get_signed_tx; @@ -614,13 +612,13 @@ impl< // let mut ctx = InitContext::new(&mut store, 0, "unit-testing".into()); // let account = BaseAccount { // address: AccAddress::from_bech32("cosmos1syavy2npfyt9tcncdtsdzf7kny9lh777pahuux") -// .unwrap(), +// .unwrap_test(), // pub_key: None, // account_number: 1, // sequence: 1, // }; // Auth::set_account(&mut ctx.as_any(), Account::Base(account)); -// set_pub_key_ante_handler(&mut ctx.as_any(), &tx).unwrap(); -// sig_verification_handler(&mut ctx.as_any(), &tx).unwrap(); +// set_pub_key_ante_handler(&mut ctx.as_any(), &tx).unwrap_test(); +// sig_verification_handler(&mut ctx.as_any(), &tx).unwrap_test(); // } // } diff --git a/gears/src/x/errors.rs b/gears/src/x/errors.rs index 9d38d4f1c..d7508653a 100644 --- a/gears/src/x/errors.rs +++ b/gears/src/x/errors.rs @@ -6,7 +6,7 @@ use thiserror::Error; use crate::{ application::handlers::node::TxError, - signing::renderer::amino_renderer::RenderError, + signing::{errors::SigningErrors, renderer::amino_renderer::RenderError}, types::{ base::errors::CoinsError, denom::Denom, @@ -104,6 +104,8 @@ pub(crate) enum AnteError { CoinsSend(#[from] BankKeeperError), #[error("legacy amino json encoding failed")] LegacyAminoJson(#[from] RenderError), + #[error("failed get sign bytes from tx: {0}")] + Signing(#[from] SigningErrors), } impl From for TxError { @@ -127,6 +129,7 @@ impl From for TxError { AnteError::CoinsSend(_) => 9, AnteError::Gas(_) => 10, AnteError::LegacyAminoJson(_) => 11, + AnteError::Signing(_) => 12, }; TxError { diff --git a/keyring/Cargo.toml b/keyring/Cargo.toml index 24ca1f6ab..4a0f7f288 100644 --- a/keyring/Cargo.toml +++ b/keyring/Cargo.toml @@ -32,3 +32,4 @@ eth-keystore = { git = "https://github.com/rumos-io/eth-keystore-rs" } [dev-dependencies] serde_json = { workspace = true } +extensions = { path = "../extensions" } \ No newline at end of file diff --git a/keyring/src/key/pair/mod.rs b/keyring/src/key/pair/mod.rs index f382668f2..081f8e304 100644 --- a/keyring/src/key/pair/mod.rs +++ b/keyring/src/key/pair/mod.rs @@ -62,14 +62,15 @@ impl KeyPair { mod tests { use super::*; use bip32::Mnemonic; + use extensions::testing::UnwrapTesting; #[test] fn test_key_pair_serialization() { let mnemonic = "race draft rival universe maid cheese steel logic crowd fork comic easy truth drift tomorrow eye buddy head time cash swing swift midnight borrow"; - let mnemonic = Mnemonic::new(mnemonic, bip32::Language::English).unwrap(); + let mnemonic = Mnemonic::new(mnemonic, bip32::Language::English).unwrap_test(); let key_pair = KeyPair::Secp256k1(Secp256k1KeyPair::from_mnemonic(&mnemonic)); - let serialized = serde_json::to_string(&key_pair).unwrap(); + let serialized = serde_json::to_string(&key_pair).unwrap_test(); assert_eq!( serialized, diff --git a/keyring/src/key/pair/secp256k1_key_pair.rs b/keyring/src/key/pair/secp256k1_key_pair.rs index aa0c40f58..dce97bf39 100644 --- a/keyring/src/key/pair/secp256k1_key_pair.rs +++ b/keyring/src/key/pair/secp256k1_key_pair.rs @@ -135,6 +135,7 @@ impl FromHex for Secp256k1KeyPair { #[cfg(test)] mod tests { + use extensions::testing::UnwrapTesting; use pkcs8::der::zeroize::Zeroizing; use super::*; @@ -144,7 +145,7 @@ mod tests { let expected_pem = "-----BEGIN PRIVATE KEY-----\nMIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQg9v3Q6I45iMwQhpDigYRQ\nhHH0jrooPuth/OhY97epZC+hRANCAAT1BLBR27K+NJ00ploewlmEWRxsH+HKUS7S\nZWkTuFQKKsUHT9nzm6axXiI797T+92b2kfW3JACbcvQ2uTZQWoFE\n-----END PRIVATE KEY-----\n".to_string(); let expected_pem = Zeroizing::new(expected_pem); let mnemonic = "race draft rival universe maid cheese steel logic crowd fork comic easy truth drift tomorrow eye buddy head time cash swing swift midnight borrow"; - let mnemonic = Mnemonic::new(mnemonic, bip32::Language::English).unwrap(); + let mnemonic = Mnemonic::new(mnemonic, bip32::Language::English).unwrap_test(); let key_pair = Secp256k1KeyPair::from_mnemonic(&mnemonic); let pem = key_pair.to_pkcs8_pem(); @@ -155,7 +156,7 @@ mod tests { #[test] fn from_pkcs8_pem_works() { let mnemonic = "race draft rival universe maid cheese steel logic crowd fork comic easy truth drift tomorrow eye buddy head time cash swing swift midnight borrow"; - let mnemonic = Mnemonic::new(mnemonic, bip32::Language::English).unwrap(); + let mnemonic = Mnemonic::new(mnemonic, bip32::Language::English).unwrap_test(); let expected_key_pair = Secp256k1KeyPair::from_mnemonic(&mnemonic); let pem_key_pair = Secp256k1KeyPair::from_pkcs8_pem( @@ -168,7 +169,7 @@ mod tests { #[test] fn encrypted_scenario_works() { let mnemonic = "race draft rival universe maid cheese steel logic crowd fork comic easy truth drift tomorrow eye buddy head time cash swing swift midnight borrow"; - let mnemonic = Mnemonic::new(mnemonic, bip32::Language::English).unwrap(); + let mnemonic = Mnemonic::new(mnemonic, bip32::Language::English).unwrap_test(); let key_pair = Secp256k1KeyPair::from_mnemonic(&mnemonic); let pem = key_pair.to_pkcs8_encrypted_pem("password"); @@ -182,12 +183,12 @@ mod tests { #[test] fn sandpit() { let mnemonic = "race draft rival universe maid cheese steel logic crowd fork comic easy truth drift tomorrow eye buddy head time cash swing swift midnight borrow"; - let mnemonic = Mnemonic::new(mnemonic, bip32::Language::English).unwrap(); + let mnemonic = Mnemonic::new(mnemonic, bip32::Language::English).unwrap_test(); let key_pair = Secp256k1KeyPair::from_mnemonic(&mnemonic); let pem = key_pair.to_pkcs8_encrypted_pem("password"); // write pem string to file - std::fs::write("./tmp/pem.pem", pem.as_bytes()).unwrap(); + std::fs::write("./tmp/pem.pem", pem.as_bytes()).unwrap_test(); } } diff --git a/keyring/src/keyring.rs b/keyring/src/keyring.rs index b6d131704..90f5fef9f 100644 --- a/keyring/src/keyring.rs +++ b/keyring/src/keyring.rs @@ -95,6 +95,8 @@ mod tests { use std::path::PathBuf; + use extensions::testing::UnwrapTesting; + use super::*; #[test] @@ -104,7 +106,7 @@ mod tests { // add key should succeed let mnemonic = "race draft rival universe maid cheese steel logic crowd fork comic easy truth drift tomorrow eye buddy head time cash swing swift midnight borrow"; - let mnemonic = Mnemonic::new(mnemonic, bip32::Language::English).unwrap(); + let mnemonic = Mnemonic::new(mnemonic, bip32::Language::English).unwrap_test(); add_key("bob", &mnemonic, KeyType::Secp256k1, Backend::Test(&path)) .expect("key should be added"); diff --git a/kv_store/Cargo.toml b/kv_store/Cargo.toml index 248dd432a..4ddcf9cba 100644 --- a/kv_store/Cargo.toml +++ b/kv_store/Cargo.toml @@ -23,3 +23,4 @@ strum = { workspace = true } [dev-dependencies] hex = { workspace = true } +extensions = { path = "../extensions" } \ No newline at end of file diff --git a/kv_store/src/bank/multi/application.rs b/kv_store/src/bank/multi/application.rs index 7660dbd49..9e99d8584 100644 --- a/kv_store/src/bank/multi/application.rs +++ b/kv_store/src/bank/multi/application.rs @@ -2,7 +2,9 @@ use std::{collections::HashMap, sync::Arc}; use database::{prefix::PrefixDB, Database}; -use crate::{bank::kv::application::ApplicationKVBank, hash::StoreInfo, StoreKey}; +use crate::{ + bank::kv::application::ApplicationKVBank, error::MultiStoreError, hash::StoreInfo, StoreKey, +}; use super::*; @@ -22,7 +24,7 @@ impl MultiBankBackend for ApplicationStore { } impl MultiBank> { - pub fn new(db: DB) -> Self { + pub fn new(db: DB) -> Result> { let db = Arc::new(db); let mut store_infos = Vec::new(); @@ -36,7 +38,10 @@ impl MultiBank> { None, Some(store.name().to_owned()), ) - .unwrap(); + .map_err(|err| MultiStoreError { + sk: store.clone(), + err, + })?; let store_info = StoreInfo { name: store.name().into(), @@ -49,12 +54,12 @@ impl MultiBank> { store_infos.push(store_info) } - MultiBank { + Ok(MultiBank { head_version, head_commit_hash: crate::hash::hash_store_infos(store_infos), backend: ApplicationStore(stores), _marker: PhantomData, - } + }) } pub fn to_tx_kind(&self) -> TransactionMultiBank { diff --git a/kv_store/src/error.rs b/kv_store/src/error.rs index cfbbf9dcb..2d66ac5a8 100644 --- a/kv_store/src/error.rs +++ b/kv_store/src/error.rs @@ -1,10 +1,30 @@ use thiserror::Error; +use crate::StoreKey; + #[derive(Error, Debug, PartialEq, Eq)] pub enum KVStoreError { #[error(transparent)] Tree(#[from] trees::Error), } +#[derive(Debug, PartialEq, Eq)] + +pub struct MultiStoreError { + pub sk: SK, + pub err: KVStoreError, +} + +impl std::fmt::Display for MultiStoreError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "failed to init for {} with error: {}", + self.sk.name(), + self.err + ) + } +} + pub const KEY_EXISTS_MSG: &str = "a store for every key is guaranteed to exist"; pub const POISONED_LOCK: &str = "poisoned lock"; diff --git a/kv_store/src/hash.rs b/kv_store/src/hash.rs index fa41056b6..1aed7503b 100644 --- a/kv_store/src/hash.rs +++ b/kv_store/src/hash.rs @@ -52,6 +52,8 @@ pub fn hash_store_infos(store_infos: Vec) -> [u8; 32] { #[cfg(test)] mod tests { + use extensions::testing::UnwrapTesting; + use super::*; #[test] @@ -59,9 +61,9 @@ mod tests { let store_infos = vec![StoreInfo { name: "bob".to_string(), hash: hex::decode("45aa73be3d99644509f273acc713717f7c49caacd64226216e6263fdd8a3296c") - .unwrap() + .unwrap_test() .try_into() - .unwrap(), + .unwrap_test(), }]; assert_eq!( hex::encode(hash_store_infos(store_infos)), @@ -74,18 +76,18 @@ mod tests { hash: hex::decode( "45aa73be3d99644509f273acc713717f7c49caacd64226216e6263fdd8a3296c", ) - .unwrap() + .unwrap_test() .try_into() - .unwrap(), + .unwrap_test(), }, StoreInfo { name: "alice".to_string(), hash: hex::decode( "c70e5a44aceeb02764ce49920ddd7c7abe0d2bb28be890764d6912c187144520", ) - .unwrap() + .unwrap_test() .try_into() - .unwrap(), + .unwrap_test(), }, ]; assert_eq!( diff --git a/kv_store/src/lib.rs b/kv_store/src/lib.rs index 1e2fa1149..3d61c57aa 100644 --- a/kv_store/src/lib.rs +++ b/kv_store/src/lib.rs @@ -4,7 +4,6 @@ use strum::IntoEnumIterator; pub mod cache; pub mod error; -pub mod ext; mod hash; pub mod query; diff --git a/tendermint/Cargo.toml b/tendermint/Cargo.toml index b565cbb23..a18c4871e 100644 --- a/tendermint/Cargo.toml +++ b/tendermint/Cargo.toml @@ -47,5 +47,6 @@ async-trait = "0.1.81" [dev-dependencies] +extensions = { path = "../extensions" } [features] diff --git a/tendermint/src/lib.rs b/tendermint/src/lib.rs index 3134f9190..d8900e3f4 100644 --- a/tendermint/src/lib.rs +++ b/tendermint/src/lib.rs @@ -79,7 +79,7 @@ pub fn write_keys_and_genesis( version: None, }, validators: vec![], - app_hash: vec![].try_into().unwrap(), + app_hash: vec![].try_into().expect("infallible"), app_state, }; diff --git a/tendermint/src/types/proto/consensus.rs b/tendermint/src/types/proto/consensus.rs index c7f4a2c1e..910a98f45 100644 --- a/tendermint/src/types/proto/consensus.rs +++ b/tendermint/src/types/proto/consensus.rs @@ -83,7 +83,7 @@ impl TryFrom for ConsensusParams { /// Consensus captures the consensus rules for processing a block in the blockchain, /// including all blockchain data structures and the rules of the application's /// state transition machine. -#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, Debug)] +#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, Debug, Default)] pub struct Consensus { #[serde(with = "crate::types::serializers::from_str")] pub block: u64, diff --git a/tendermint/src/types/proto/header.rs b/tendermint/src/types/proto/header.rs index 73adca006..c9eeeaac5 100644 --- a/tendermint/src/types/proto/header.rs +++ b/tendermint/src/types/proto/header.rs @@ -3,7 +3,7 @@ use crate::types::{chain_id::ChainId, time::timestamp::Timestamp}; use super::{block::BlockId, consensus::Consensus}; /// Header defines the structure of a Tendermint block header. -#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, Debug)] +#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, Debug, Default)] pub struct Header { /// basic block info pub version: Consensus, diff --git a/tendermint/src/types/serializers/timestamp.rs b/tendermint/src/types/serializers/timestamp.rs deleted file mode 100644 index 8acd0bb49..000000000 --- a/tendermint/src/types/serializers/timestamp.rs +++ /dev/null @@ -1,125 +0,0 @@ -//! Serialize/deserialize Timestamp type from and into string: - -use core::fmt; - -use serde::{de::Error as _, ser::Error, Deserialize, Deserializer, Serialize, Serializer}; -use time::{ - format_description::well_known::Rfc3339 as Rfc3339Format, macros::offset, OffsetDateTime, -}; - -use crate::types::time::Timestamp; - -/// Helper struct to serialize and deserialize Timestamp into an RFC3339-compatible string -/// This is required because the serde `with` attribute is only available to fields of a struct but -/// not the whole struct. -#[derive(Debug, Serialize, Deserialize)] -#[serde(transparent)] -pub struct Rfc3339(#[serde(with = "crate::types::serializers::timestamp")] Timestamp); - -impl From for Rfc3339 { - fn from(value: Timestamp) -> Self { - Rfc3339(value) - } -} -impl From for Timestamp { - fn from(value: Rfc3339) -> Self { - value.0 - } -} - -/// Deserialize string into Timestamp -pub fn deserialize<'de, D>(deserializer: D) -> Result -where - D: Deserializer<'de>, -{ - let value_string = String::deserialize(deserializer)?; - let t = OffsetDateTime::parse(&value_string, &Rfc3339Format).map_err(D::Error::custom)?; - let t = t.to_offset(offset!(UTC)); - if !matches!(t.year(), 1..=9999) { - return Err(D::Error::custom("date is out of range")); - } - let seconds = t.unix_timestamp(); - // Safe to convert to i32 because .nanosecond() - // is guaranteed to return a value in 0..1_000_000_000 range. - let nanos = t.nanosecond() as i32; - Ok(Timestamp { seconds, nanos }) -} - -/// Serialize from Timestamp into string -pub fn serialize(value: &Timestamp, serializer: S) -> Result -where - S: Serializer, -{ - if value.nanos < 0 || value.nanos > 999_999_999 { - return Err(S::Error::custom("invalid nanoseconds in time")); - } - let total_nanos = value.seconds as i128 * 1_000_000_000 + value.nanos as i128; - let datetime = OffsetDateTime::from_unix_timestamp_nanos(total_nanos) - .map_err(|_| S::Error::custom("invalid time"))?; - to_rfc3339_nanos(datetime).serialize(serializer) -} - -/// Serialization helper for converting an [`OffsetDateTime`] object to a string. -/// -/// This reproduces the behavior of Go's `time.RFC3339Nano` format, -/// ie. a RFC3339 date-time with left-padded subsecond digits without -/// trailing zeros and no trailing dot. -pub fn to_rfc3339_nanos(t: OffsetDateTime) -> String { - // Can't use OffsetDateTime::format because the feature enabling it - // currently requires std (https://github.com/time-rs/time/issues/400) - - // Preallocate enough string capacity to fit the shortest possible form, - // yyyy-mm-ddThh:mm:ssZ - let mut buf = String::with_capacity(20); - - fmt_as_rfc3339_nanos(t, &mut buf).unwrap(); - - buf -} - -/// Helper for formatting an [`OffsetDateTime`] value. -/// -/// This function can be used to efficiently format date-time values -/// in [`Display`] or [`Debug`] implementations. -/// -/// The format reproduces Go's `time.RFC3339Nano` format, -/// ie. a RFC3339 date-time with left-padded subsecond digits without -/// trailing zeros and no trailing dot. -/// -/// [`Display`]: core::fmt::Display -/// [`Debug`]: core::fmt::Debug -pub fn fmt_as_rfc3339_nanos(t: OffsetDateTime, f: &mut impl fmt::Write) -> fmt::Result { - let t = t.to_offset(offset!(UTC)); - let nanos = t.nanosecond(); - if nanos == 0 { - write!( - f, - "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z", - year = t.year(), - month = t.month() as u8, - day = t.day(), - hour = t.hour(), - minute = t.minute(), - second = t.second(), - ) - } else { - let mut secfrac = nanos; - let mut secfrac_width = 9; - while secfrac % 10 == 0 { - secfrac /= 10; - secfrac_width -= 1; - } - write!( - f, - "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{secfrac:0sfw$}Z", - year = t.year(), - month = t.month() as u8, - day = t.day(), - hour = t.hour(), - minute = t.minute(), - second = t.second(), - secfrac = secfrac, - sfw = secfrac_width, - ) - } -} diff --git a/tendermint/src/types/time/duration.rs b/tendermint/src/types/time/duration.rs index 132f6349d..8d0c779c5 100644 --- a/tendermint/src/types/time/duration.rs +++ b/tendermint/src/types/time/duration.rs @@ -287,11 +287,13 @@ pub mod inner { mod tests { use std::i32; + use extensions::testing::UnwrapTesting; + use super::*; #[test] fn test_try_new() { - let duration = Duration::try_new(1, 0).unwrap(); + let duration = Duration::try_new(1, 0).unwrap_test(); assert_eq!( duration, Duration { @@ -301,11 +303,11 @@ mod tests { ); let duration = - Duration::try_new(DurationSeconds::MIN.into(), Nanoseconds::MIN.into()).unwrap(); + Duration::try_new(DurationSeconds::MIN.into(), Nanoseconds::MIN.into()).unwrap_test(); assert_eq!(duration, Duration::MIN); let duration = - Duration::try_new(DurationSeconds::MAX.into(), Nanoseconds::MAX.into()).unwrap(); + Duration::try_new(DurationSeconds::MAX.into(), Nanoseconds::MAX.into()).unwrap_test(); assert_eq!(duration, Duration::MAX); let dur_error = Duration::try_new(i64::from(DurationSeconds::MIN) - 1, 0).unwrap_err(); @@ -407,7 +409,7 @@ mod tests { #[test] fn test_try_new_from_nanos() { - let duration = Duration::try_new_from_nanos(1_000_000_001).unwrap(); + let duration = Duration::try_new_from_nanos(1_000_000_001).unwrap_test(); assert_eq!( duration, Duration { @@ -416,7 +418,7 @@ mod tests { } ); - let duration = Duration::try_new_from_nanos(-1_000_000_001).unwrap(); + let duration = Duration::try_new_from_nanos(-1_000_000_001).unwrap_test(); assert_eq!( duration, Duration { @@ -425,7 +427,7 @@ mod tests { } ); - let duration = Duration::try_new_from_nanos(1_000_000_000).unwrap(); + let duration = Duration::try_new_from_nanos(1_000_000_000).unwrap_test(); assert_eq!( duration, Duration { @@ -434,7 +436,7 @@ mod tests { } ); - let duration = Duration::try_new_from_nanos(-1_000_000_000).unwrap(); + let duration = Duration::try_new_from_nanos(-1_000_000_000).unwrap_test(); assert_eq!( duration, Duration { @@ -443,7 +445,7 @@ mod tests { } ); - let duration = Duration::try_new_from_nanos(0).unwrap(); + let duration = Duration::try_new_from_nanos(0).unwrap_test(); assert_eq!( duration, Duration { @@ -452,10 +454,10 @@ mod tests { } ); - let duration = Duration::try_new_from_nanos(DurationNanoseconds::MAX.into()).unwrap(); + let duration = Duration::try_new_from_nanos(DurationNanoseconds::MAX.into()).unwrap_test(); assert_eq!(duration, Duration::MAX); - let duration = Duration::try_new_from_nanos(DurationNanoseconds::MIN.into()).unwrap(); + let duration = Duration::try_new_from_nanos(DurationNanoseconds::MIN.into()).unwrap_test(); assert_eq!(duration, Duration::MIN); let dur_error = @@ -469,19 +471,19 @@ mod tests { #[test] fn test_duration_hours() { - let duration = Duration::try_new(3 * SECONDS_PER_HOUR + 1, 0).unwrap(); + let duration = Duration::try_new(3 * SECONDS_PER_HOUR + 1, 0).unwrap_test(); assert_eq!(duration.duration_hours(), DurationHours(3)); - let duration = Duration::try_new(3 * SECONDS_PER_HOUR - 1, 0).unwrap(); + let duration = Duration::try_new(3 * SECONDS_PER_HOUR - 1, 0).unwrap_test(); assert_eq!(duration.duration_hours(), DurationHours(2)); - let duration = Duration::try_new(-3 * SECONDS_PER_HOUR - 1, 0).unwrap(); + let duration = Duration::try_new(-3 * SECONDS_PER_HOUR - 1, 0).unwrap_test(); assert_eq!(duration.duration_hours(), DurationHours(-3)); - let duration = Duration::try_new(-3 * SECONDS_PER_HOUR + 1, 0).unwrap(); + let duration = Duration::try_new(-3 * SECONDS_PER_HOUR + 1, 0).unwrap_test(); assert_eq!(duration.duration_hours(), DurationHours(-2)); - let duration = Duration::try_new(0, 0).unwrap(); + let duration = Duration::try_new(0, 0).unwrap_test(); assert_eq!(duration.duration_hours(), DurationHours(0)); let duration = Duration::MAX; @@ -493,13 +495,13 @@ mod tests { #[test] fn test_duration_seconds() { - let duration = Duration::try_new(3, 1).unwrap(); + let duration = Duration::try_new(3, 1).unwrap_test(); assert_eq!(duration.duration_seconds(), DurationSeconds(3)); - let duration = Duration::try_new(-3, -1).unwrap(); + let duration = Duration::try_new(-3, -1).unwrap_test(); assert_eq!(duration.duration_seconds(), DurationSeconds(-3)); - let duration = Duration::try_new(0, 0).unwrap(); + let duration = Duration::try_new(0, 0).unwrap_test(); assert_eq!(duration.duration_seconds(), DurationSeconds(0)); let duration = Duration::MAX; @@ -511,46 +513,46 @@ mod tests { #[test] fn test_nanoseconds() { - let duration = Duration::try_new(3, 1).unwrap(); + let duration = Duration::try_new(3, 1).unwrap_test(); assert_eq!(duration.nanoseconds(), Nanoseconds(1)); - let duration = Duration::try_new(-3, -1).unwrap(); + let duration = Duration::try_new(-3, -1).unwrap_test(); assert_eq!(duration.nanoseconds(), Nanoseconds(-1)); - let duration = Duration::try_new(0, 0).unwrap(); + let duration = Duration::try_new(0, 0).unwrap_test(); assert_eq!(duration.nanoseconds(), Nanoseconds(0)); - let duration = Duration::try_new(0, 999_999_999).unwrap(); + let duration = Duration::try_new(0, 999_999_999).unwrap_test(); assert_eq!(duration.nanoseconds(), Nanoseconds::MAX); - let duration = Duration::try_new(0, -999_999_999).unwrap(); + let duration = Duration::try_new(0, -999_999_999).unwrap_test(); assert_eq!(duration.nanoseconds(), Nanoseconds::MIN); } #[test] fn test_duration_nanoseconds() { - let duration = Duration::try_new(3, 1).unwrap(); + let duration = Duration::try_new(3, 1).unwrap_test(); assert_eq!( duration.duration_nanoseconds(), DurationNanoseconds(3_000_000_001) ); - let duration = Duration::try_new(-3, -1).unwrap(); + let duration = Duration::try_new(-3, -1).unwrap_test(); assert_eq!( duration.duration_nanoseconds(), DurationNanoseconds(-3_000_000_001) ); - let duration = Duration::try_new(0, 0).unwrap(); + let duration = Duration::try_new(0, 0).unwrap_test(); assert_eq!(duration.duration_nanoseconds(), DurationNanoseconds(0)); - let duration = Duration::try_new(0, 999_999_999).unwrap(); + let duration = Duration::try_new(0, 999_999_999).unwrap_test(); assert_eq!( duration.duration_nanoseconds(), DurationNanoseconds(999_999_999) ); - let duration = Duration::try_new(0, -999_999_999).unwrap(); + let duration = Duration::try_new(0, -999_999_999).unwrap_test(); assert_eq!( duration.duration_nanoseconds(), DurationNanoseconds(-999_999_999) @@ -565,38 +567,38 @@ mod tests { #[test] fn test_serialization() { - let duration = Duration::try_new(3, 1).unwrap(); - let serialized = serde_json::to_string(&duration).unwrap(); + let duration = Duration::try_new(3, 1).unwrap_test(); + let serialized = serde_json::to_string(&duration).unwrap_test(); assert_eq!(serialized, r#""3.000000001s""#); - let deserialized: Duration = serde_json::from_str(&serialized).unwrap(); + let deserialized: Duration = serde_json::from_str(&serialized).unwrap_test(); assert_eq!(deserialized, duration); //-------------------------------------------- - let duration = Duration::try_new(3, 0).unwrap(); - let serialized = serde_json::to_string(&duration).unwrap(); + let duration = Duration::try_new(3, 0).unwrap_test(); + let serialized = serde_json::to_string(&duration).unwrap_test(); assert_eq!(serialized, r#""3s""#); - let deserialized: Duration = serde_json::from_str(&serialized).unwrap(); + let deserialized: Duration = serde_json::from_str(&serialized).unwrap_test(); assert_eq!(deserialized, duration); //-------------------------------------------- - let duration = Duration::try_new(-3, -1).unwrap(); - let serialized = serde_json::to_string(&duration).unwrap(); + let duration = Duration::try_new(-3, -1).unwrap_test(); + let serialized = serde_json::to_string(&duration).unwrap_test(); assert_eq!(serialized, r#""-3.000000001s""#); - let deserialized: Duration = serde_json::from_str(&serialized).unwrap(); + let deserialized: Duration = serde_json::from_str(&serialized).unwrap_test(); assert_eq!(deserialized, duration); //-------------------------------------------- - let duration = Duration::try_new(3, 1000).unwrap(); - let serialized = serde_json::to_string(&duration).unwrap(); + let duration = Duration::try_new(3, 1000).unwrap_test(); + let serialized = serde_json::to_string(&duration).unwrap_test(); assert_eq!(serialized, r#""3.000001s""#); - let deserialized: Duration = serde_json::from_str(&serialized).unwrap(); + let deserialized: Duration = serde_json::from_str(&serialized).unwrap_test(); assert_eq!(deserialized, duration); //-------------------------------------------- diff --git a/tendermint/src/types/time/serializers.rs b/tendermint/src/types/time/serializers.rs index 331216e70..9303838b0 100644 --- a/tendermint/src/types/time/serializers.rs +++ b/tendermint/src/types/time/serializers.rs @@ -75,7 +75,7 @@ pub fn to_rfc3339_nanos(t: OffsetDateTime) -> String { // yyyy-mm-ddThh:mm:ssZ let mut buf = String::with_capacity(20); - fmt_as_rfc3339_nanos(t, &mut buf).unwrap(); + fmt_as_rfc3339_nanos(t, &mut buf).expect("writing to `String` infallible"); buf } diff --git a/tendermint/src/types/time/timestamp.rs b/tendermint/src/types/time/timestamp.rs index fe45e4862..90f3ebcf9 100644 --- a/tendermint/src/types/time/timestamp.rs +++ b/tendermint/src/types/time/timestamp.rs @@ -363,11 +363,13 @@ pub mod inner { #[cfg(test)] mod tests { + use extensions::testing::UnwrapTesting; + use super::*; #[test] fn test_try_new() { - let ts = Timestamp::try_new(0, 0).unwrap(); + let ts = Timestamp::try_new(0, 0).unwrap_test(); assert_eq!(ts, Timestamp::UNIX_EPOCH); let err = Timestamp::try_new(1, 1_000_000_000).unwrap_err(); @@ -385,89 +387,89 @@ mod tests { #[test] fn test_checked_add() { - let ts = Timestamp::try_new(0, 0).unwrap(); - let dur = Duration::try_new(1, 0).unwrap(); - let ts = ts.checked_add(dur).unwrap(); - assert_eq!(ts, Timestamp::try_new(1, 0).unwrap()); - - let ts = Timestamp::try_new(0, 0).unwrap(); - let dur = Duration::try_new(0, -1).unwrap(); - let ts = ts.checked_add(dur).unwrap(); - assert_eq!(ts, Timestamp::try_new(-1, 999_999_999).unwrap()); - - let ts = Timestamp::try_new(0, 999_999_999).unwrap(); - let dur = Duration::try_new(0, 999_999_999).unwrap(); - let ts = ts.checked_add(dur).unwrap(); - assert_eq!(ts, Timestamp::try_new(1, 999_999_998).unwrap()); - - let ts = Timestamp::try_new(253402300799, 999_999_999).unwrap(); - let dur = Duration::try_new(0, 1).unwrap(); + let ts = Timestamp::try_new(0, 0).unwrap_test(); + let dur = Duration::try_new(1, 0).unwrap_test(); + let ts = ts.checked_add(dur).unwrap_test(); + assert_eq!(ts, Timestamp::try_new(1, 0).unwrap_test()); + + let ts = Timestamp::try_new(0, 0).unwrap_test(); + let dur = Duration::try_new(0, -1).unwrap_test(); + let ts = ts.checked_add(dur).unwrap_test(); + assert_eq!(ts, Timestamp::try_new(-1, 999_999_999).unwrap_test()); + + let ts = Timestamp::try_new(0, 999_999_999).unwrap_test(); + let dur = Duration::try_new(0, 999_999_999).unwrap_test(); + let ts = ts.checked_add(dur).unwrap_test(); + assert_eq!(ts, Timestamp::try_new(1, 999_999_998).unwrap_test()); + + let ts = Timestamp::try_new(253402300799, 999_999_999).unwrap_test(); + let dur = Duration::try_new(0, 1).unwrap_test(); let ts = ts.checked_add(dur); assert!(ts.is_none()); } #[test] fn test_timestamp_nanoseconds() { - let ts = Timestamp::try_new(1, 234).unwrap(); + let ts = Timestamp::try_new(1, 234).unwrap_test(); let ts: i128 = ts.timestamp_nanoseconds().into(); assert_eq!(ts, 1_000_000_234); - let ts = Timestamp::try_new(-1, 234).unwrap(); + let ts = Timestamp::try_new(-1, 234).unwrap_test(); let ts: i128 = ts.timestamp_nanoseconds().into(); assert_eq!(ts, -999_999_766); } #[test] fn test_timestamp_seconds() { - let ts = Timestamp::try_new(1, 234).unwrap(); + let ts = Timestamp::try_new(1, 234).unwrap_test(); let ts: i64 = ts.timestamp_seconds().into(); assert_eq!(ts, 1); - let ts = Timestamp::try_new(-1, 234).unwrap(); + let ts = Timestamp::try_new(-1, 234).unwrap_test(); let ts: i64 = ts.timestamp_seconds().into(); assert_eq!(ts, 0); - let ts = Timestamp::try_new(-1, 0).unwrap(); + let ts = Timestamp::try_new(-1, 0).unwrap_test(); let ts: i64 = ts.timestamp_seconds().into(); assert_eq!(ts, -1); } #[test] fn test_checked_sub() { - let ts1 = Timestamp::try_new(1, 0).unwrap(); - let ts2 = Timestamp::try_new(0, 0).unwrap(); - let dur = ts1.checked_sub(&ts2).unwrap(); - assert_eq!(dur, Duration::try_new(1, 0).unwrap()); + let ts1 = Timestamp::try_new(1, 0).unwrap_test(); + let ts2 = Timestamp::try_new(0, 0).unwrap_test(); + let dur = ts1.checked_sub(&ts2).unwrap_test(); + assert_eq!(dur, Duration::try_new(1, 0).unwrap_test()); - let dur = ts2.checked_sub(&ts1).unwrap(); - assert_eq!(dur, Duration::try_new(-1, 0).unwrap()); + let dur = ts2.checked_sub(&ts1).unwrap_test(); + assert_eq!(dur, Duration::try_new(-1, 0).unwrap_test()); - let ts1 = Timestamp::try_new(1, 0).unwrap(); - let ts2 = Timestamp::try_new(0, 1).unwrap(); - let dur = ts1.checked_sub(&ts2).unwrap(); - assert_eq!(dur, Duration::try_new(0, 999_999_999).unwrap()); + let ts1 = Timestamp::try_new(1, 0).unwrap_test(); + let ts2 = Timestamp::try_new(0, 1).unwrap_test(); + let dur = ts1.checked_sub(&ts2).unwrap_test(); + assert_eq!(dur, Duration::try_new(0, 999_999_999).unwrap_test()); - let dur = ts2.checked_sub(&ts1).unwrap(); - assert_eq!(dur, Duration::try_new(0, -999_999_999).unwrap()); + let dur = ts2.checked_sub(&ts1).unwrap_test(); + assert_eq!(dur, Duration::try_new(0, -999_999_999).unwrap_test()); } #[test] fn test_format_string_rounded() { - let ts = Timestamp::try_new(1, 234_000_000).unwrap(); + let ts = Timestamp::try_new(1, 234_000_000).unwrap_test(); assert_eq!(ts.format_string_rounded(), "1970-01-01T00:00:01.000000000"); - let ts = Timestamp::try_new(-1, 234_000_000).unwrap(); + let ts = Timestamp::try_new(-1, 234_000_000).unwrap_test(); assert_eq!(ts.format_string_rounded(), "1969-12-31T23:59:59.000000000"); - let ts = Timestamp::try_new(-1, 734_000_000).unwrap(); + let ts = Timestamp::try_new(-1, 734_000_000).unwrap_test(); assert_eq!(ts.format_string_rounded(), "1970-01-01T00:00:00.000000000"); } #[test] fn test_try_from_formatted_bytes() { let bytes = b"1969-12-31T23:59:59.000000000"; - let ts2 = Timestamp::try_from_formatted_bytes(bytes.as_slice()).unwrap(); - let ts3 = Timestamp::try_new(-1, 0).unwrap(); + let ts2 = Timestamp::try_from_formatted_bytes(bytes.as_slice()).unwrap_test(); + let ts3 = Timestamp::try_new(-1, 0).unwrap_test(); assert_eq!(ts3, ts2); // nanoseconds should be zero @@ -493,11 +495,11 @@ mod tests { #[test] fn test_serialization() { - let ts = Timestamp::try_new(1484443815, 10_000_000).unwrap(); - let serialized = serde_json::to_string(&ts).unwrap(); + let ts = Timestamp::try_new(1484443815, 10_000_000).unwrap_test(); + let serialized = serde_json::to_string(&ts).unwrap_test(); assert_eq!(serialized, r#""2017-01-15T01:30:15.01Z""#); - let deserialized: Timestamp = serde_json::from_str(&serialized).unwrap(); + let deserialized: Timestamp = serde_json::from_str(&serialized).unwrap_test(); assert_eq!(deserialized, ts); } } diff --git a/trees/Cargo.toml b/trees/Cargo.toml index 5dedb351e..ac12a3fe2 100644 --- a/trees/Cargo.toml +++ b/trees/Cargo.toml @@ -6,6 +6,7 @@ version = "0.1.0" [dependencies] #local database = {path = "../database"} +extensions = { path = "../extensions" } #newtypes @@ -29,6 +30,7 @@ rand = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } anyhow = { workspace = true } +extensions = { path = "../extensions" } [[bench]] harness = false diff --git a/trees/benches/iavl_benchmark.rs b/trees/benches/iavl_benchmark.rs index 2b0bba583..207920b8f 100644 --- a/trees/benches/iavl_benchmark.rs +++ b/trees/benches/iavl_benchmark.rs @@ -3,6 +3,8 @@ use bench::*; #[cfg(feature = "bench")] use criterion::{criterion_group, criterion_main, Criterion}; #[cfg(feature = "bench")] +use extensions::testing::UnwrapCorrupt; +#[cfg(feature = "bench")] use pprof::criterion::{Output, PProfProfiler}; #[cfg(feature = "bench")] @@ -72,7 +74,7 @@ mod bench { b.iter(|| { let key: &Vec = keys .get(rand::thread_rng().gen_range(0..params.init_size)) - .unwrap(); + .unwrap_test(); tree.get(black_box(key)); }) }); @@ -90,7 +92,7 @@ mod bench { for i in 0..iters { let key: &Vec = keys .get(rand::thread_rng().gen_range(0..params.init_size)) - .unwrap(); + .unwrap_test(); let data: Vec = rand::thread_rng() .sample_iter(Standard) @@ -135,7 +137,7 @@ mod bench { // 50% insert, 50% update let key = if i % 2 == 0 { keys.get(rand::thread_rng().gen_range(0..params.init_size)) - .unwrap() + .unwrap_test() .clone() } else { rand::thread_rng() @@ -196,7 +198,7 @@ mod bench { /// Attempts to exactly replicate steps in go IAVL, see https://github.com/cosmos/iavl/blob/7f698ba3fa232c54109e5b4ea42562bbecdb1bf8/benchmarks/bench_test.go#L41-L57 fn commit_tree(tree: &mut Tree) { - let (_, _version) = tree.save_version().unwrap(); + let (_, _version) = tree.save_version().unwrap_test(); // TODO: need to implement this once delete_version has been implemented // if version > historySize { @@ -209,11 +211,11 @@ mod bench { fn prepare_tree(params: &Params) -> (Tree, Vec>) { // remove previous test DBs - fs::remove_dir_all(DB_DIR).unwrap(); - fs::create_dir(DB_DIR).unwrap(); + fs::remove_dir_all(DB_DIR).unwrap_test(); + fs::create_dir(DB_DIR).unwrap_test(); - let db = RocksDB::new(DB_DIR).unwrap(); - let mut tree = Tree::new(db, None, params.init_size.try_into().unwrap()).unwrap(); + let db = RocksDB::new(DB_DIR).unwrap_test(); + let mut tree = Tree::new(db, None, params.init_size.try_into().unwrap_test()).unwrap_test(); let mut keys = Vec::with_capacity(params.init_size); for _ in 0..params.init_size { @@ -231,7 +233,7 @@ mod bench { keys.push(key); } - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); (tree, keys) } diff --git a/trees/examples/benchtable.rs b/trees/examples/benchtable.rs index d421356a0..828ae65e9 100644 --- a/trees/examples/benchtable.rs +++ b/trees/examples/benchtable.rs @@ -150,13 +150,14 @@ struct InputBenchResult { /// NOTE: This doesn't belong in the examples directory but I couldn't /// find a better place for it. fn main() { - let file = File::open("benchmark.json").unwrap(); + let file = File::open("benchmark.json").expect("failed to open file"); let reader = BufReader::new(file); let mut full_results = FullResults::default(); for line in reader.lines() { - let bench: Result = serde_json::from_str(&line.unwrap()); + let bench: Result = + serde_json::from_str(&line.expect("failed to read line")); if let Ok(bench) = bench { let time = bench.mean.into(); @@ -240,14 +241,18 @@ fn main() { .render("bench_large", &full_results.large) .expect("OutputResult will always work with the BENCH_TEMPLATE"); - let mut file = std::fs::File::create("benchmark.md").unwrap(); - file.write("# Benchmark\n".as_bytes()).unwrap(); - file.write("## Small".as_bytes()).unwrap(); - file.write_all(small_table.as_bytes()).unwrap(); - file.write("## Medium".as_bytes()).unwrap(); - file.write_all(medium_table.as_bytes()).unwrap(); - file.write("## Large".as_bytes()).unwrap(); - file.write_all(large_table.as_bytes()).unwrap(); + let mut file = std::fs::File::create("benchmark.md").expect("failed to create a new file"); + file.write("# Benchmark\n".as_bytes()) + .expect("failed to write"); + file.write("## Small".as_bytes()).expect("failed to write"); + file.write_all(small_table.as_bytes()) + .expect("failed to write"); + file.write("## Medium".as_bytes()).expect("failed to write"); + file.write_all(medium_table.as_bytes()) + .expect("failed to write"); + file.write("## Large".as_bytes()).expect("failed to write"); + file.write_all(large_table.as_bytes()) + .expect("failed to write"); } #[derive(serde::Serialize, Default)] diff --git a/trees/src/iavl/node_db.rs b/trees/src/iavl/node_db.rs index d7df7dfa8..18649491b 100644 --- a/trees/src/iavl/node_db.rs +++ b/trees/src/iavl/node_db.rs @@ -4,7 +4,8 @@ use std::{ }; use caches::{Cache, DefaultHashBuilder, LRUCache}; -use database::{ext::UnwrapCorrupt, Database}; +use database::Database; +use extensions::corruption::UnwrapCorrupt; use integer_encoding::VarInt; use crate::{merkle::EMPTY_HASH, Error}; @@ -129,6 +130,7 @@ where mod tests { use super::*; use database::MemDB; + use extensions::testing::UnwrapTesting; #[test] fn get_root_key_works() { @@ -157,7 +159,7 @@ mod tests { db.put(NodeDB::::get_root_key(1u32), vec![]); let node_db = NodeDB { db, - cache: Arc::new(Mutex::new(LRUCache::new(2).unwrap())), + cache: Arc::new(Mutex::new(LRUCache::new(2).unwrap_test())), }; let mut expected_versions = BTreeSet::new(); @@ -177,10 +179,10 @@ mod tests { db.put(NodeDB::::get_root_key(1u32), root_hash.into()); let node_db = NodeDB { db, - cache: Arc::new(Mutex::new(LRUCache::new(2).unwrap())), + cache: Arc::new(Mutex::new(LRUCache::new(2).unwrap_test())), }; - let got_root_hash = node_db.get_root_hash(1).unwrap(); + let got_root_hash = node_db.get_root_hash(1).unwrap_test(); assert_eq!(root_hash, got_root_hash); } diff --git a/trees/src/iavl/query_tree.rs b/trees/src/iavl/query_tree.rs index 99ad75489..11d5aa36f 100644 --- a/trees/src/iavl/query_tree.rs +++ b/trees/src/iavl/query_tree.rs @@ -109,22 +109,23 @@ impl QueryTree { mod tests { use super::*; use database::MemDB; + use extensions::testing::UnwrapTesting; #[test] fn new_query_tree_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set(b"alice".to_vec(), b"abc".to_vec()); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); tree.set(b"alice".to_vec(), b"123".to_vec()); - let query_tree = QueryTree::new(&tree, 1).unwrap(); - let result = query_tree.get(b"alice".as_slice()).unwrap(); + let query_tree = QueryTree::new(&tree, 1).unwrap_test(); + let result = query_tree.get(b"alice".as_slice()).unwrap_test(); let expected = b"abc".to_vec(); assert_eq!(expected, result); - let result = tree.get(b"alice".as_slice()).unwrap(); + let result = tree.get(b"alice".as_slice()).unwrap_test(); let expected = b"123".to_vec(); assert_eq!(expected, result); } @@ -132,10 +133,10 @@ mod tests { #[test] fn new_query_tree_works_empty_tree() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); - tree.save_version().unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); + tree.save_version().unwrap_test(); - let query_tree = QueryTree::new(&tree, 1).unwrap(); + let query_tree = QueryTree::new(&tree, 1).unwrap_test(); let result = query_tree.get(b"alice".as_slice()); let expected = None; diff --git a/trees/src/iavl/tree.rs b/trees/src/iavl/tree.rs index 8747d41fa..95babbfbe 100644 --- a/trees/src/iavl/tree.rs +++ b/trees/src/iavl/tree.rs @@ -5,7 +5,8 @@ use std::{ ops::{Bound, RangeBounds}, }; -use database::{ext::UnwrapCorrupt, Database}; +use database::Database; +use extensions::corruption::UnwrapCorrupt; use integer_encoding::VarInt; use nutype::nutype; use sha2::{Digest, Sha256}; @@ -1079,6 +1080,7 @@ mod tests { use super::*; use cmp::max; use database::MemDB; + use extensions::testing::UnwrapTesting; #[test] fn remove_leaf_from_tree() -> anyhow::Result<()> { @@ -1110,7 +1112,7 @@ mod tests { }; let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.root = Some(Box::new(Node::Inner(root))); @@ -1135,7 +1137,7 @@ mod tests { #[test] fn remove_leaf_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set(vec![1], vec![4]); tree.set(vec![2], vec![5]); tree.set(vec![3], vec![6]); @@ -1166,12 +1168,12 @@ mod tests { #[test] fn remove_leaf_after_save_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set(vec![1], vec![4]); tree.set(vec![2], vec![5]); tree.set(vec![3], vec![6]); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); let val = tree.remove(&[2]); @@ -1258,8 +1260,8 @@ mod tests { let mut z = Node::Inner(z); let db = MemDB::new(); - z.right_rotate(0, &NodeDB::new(db, 100.try_into().unwrap())) - .unwrap(); + z.right_rotate(0, &NodeDB::new(db, 100.try_into().unwrap_test())) + .unwrap_test(); let hash = z.hash(); let expected = [ @@ -1341,8 +1343,8 @@ mod tests { let mut z = Node::Inner(z); let db = MemDB::new(); - z.left_rotate(0, &NodeDB::new(db, 100.try_into().unwrap())) - .unwrap(); + z.left_rotate(0, &NodeDB::new(db, 100.try_into().unwrap_test())) + .unwrap_test(); let hash = z.hash(); let expected = [ @@ -1355,7 +1357,7 @@ mod tests { #[test] fn set_equal_leaf_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set(vec![1], vec![2]); tree.set(vec![1], vec![3]); @@ -1370,7 +1372,7 @@ mod tests { #[test] fn set_less_than_leaf_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set(vec![3], vec![2]); tree.set(vec![1], vec![3]); @@ -1385,7 +1387,7 @@ mod tests { #[test] fn set_greater_than_leaf_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set(vec![1], vec![2]); tree.set(vec![3], vec![3]); @@ -1400,7 +1402,7 @@ mod tests { #[test] fn repeated_set_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set(b"alice".to_vec(), b"abc".to_vec()); tree.set(b"bob".to_vec(), b"123".to_vec()); tree.set(b"c".to_vec(), b"1".to_vec()); @@ -1417,19 +1419,19 @@ mod tests { #[test] fn save_version_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set(b"alice".to_vec(), b"abc".to_vec()); tree.set(b"bob".to_vec(), b"123".to_vec()); tree.set(b"c".to_vec(), b"1".to_vec()); tree.set(b"q".to_vec(), b"1".to_vec()); - tree.save_version().unwrap(); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); + tree.save_version().unwrap_test(); tree.set(b"qwerty".to_vec(), b"312".to_vec()); tree.set(b"-32".to_vec(), b"gamma".to_vec()); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); tree.set(b"alice".to_vec(), b"123".to_vec()); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); let expected = [ 37, 155, 233, 229, 243, 173, 29, 241, 235, 234, 85, 10, 36, 129, 53, 79, 77, 11, 29, @@ -1442,7 +1444,7 @@ mod tests { #[test] fn get_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set(b"alice".to_vec(), b"abc".to_vec()); tree.set(b"bob".to_vec(), b"123".to_vec()); tree.set(b"c".to_vec(), b"1".to_vec()); @@ -1458,7 +1460,7 @@ mod tests { #[test] fn scenario_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set(vec![0, 117, 97, 116, 111, 109], vec![51, 52]); tree.set( vec![ @@ -1468,13 +1470,13 @@ mod tests { vec![10, 5, 117, 97, 116, 111, 109, 18, 2, 51, 52], ); - tree.save_version().unwrap(); - tree.save_version().unwrap(); - tree.save_version().unwrap(); - tree.save_version().unwrap(); - tree.save_version().unwrap(); - tree.save_version().unwrap(); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); + tree.save_version().unwrap_test(); + tree.save_version().unwrap_test(); + tree.save_version().unwrap_test(); + tree.save_version().unwrap_test(); + tree.save_version().unwrap_test(); + tree.save_version().unwrap_test(); tree.set( vec![ @@ -1503,7 +1505,7 @@ mod tests { 145, 99, 187, 82, 49, 149, 36, 196, 63, 37, 42, 171, 124, ]; - let (hash, version) = tree.save_version().unwrap(); + let (hash, version) = tree.save_version().unwrap_test(); assert_eq!((expected, 8), (hash, version)); } @@ -1511,7 +1513,7 @@ mod tests { #[test] fn bounded_range_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set(b"1".to_vec(), b"abc1".to_vec()); tree.set(b"2".to_vec(), b"abc2".to_vec()); @@ -1575,7 +1577,7 @@ mod tests { #[test] fn full_range_unique_keys_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set(b"alice".to_vec(), b"abc".to_vec()); tree.set(b"bob".to_vec(), b"123".to_vec()); tree.set(b"c".to_vec(), b"1".to_vec()); @@ -1599,7 +1601,7 @@ mod tests { #[test] fn full_range_duplicate_keys_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set(b"alice".to_vec(), b"abc".to_vec()); tree.set(b"alice".to_vec(), b"abc".to_vec()); let got_pairs: Vec<(Vec, Vec)> = tree.range(..).collect(); @@ -1616,7 +1618,7 @@ mod tests { #[test] fn empty_tree_range_works() { let db = MemDB::new(); - let tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); let got_pairs: Vec<(Vec, Vec)> = tree.range(..).collect(); let expected_pairs: Vec<(Vec, Vec)> = vec![]; @@ -1657,7 +1659,7 @@ mod tests { 129, 85, 55, 190, 253, 226, 35, 230, 65, 214, 244, 35, 69, 39, 223, 90 ] ); - let deserialized_node = Node::deserialize(node_bytes).unwrap(); + let deserialized_node = Node::deserialize(node_bytes).unwrap_test(); assert_eq!(deserialized_node, orig_node); } @@ -1671,7 +1673,7 @@ mod tests { let node_bytes = orig_node.serialize(); assert_eq!(node_bytes, [0, 1, 0, 1, 19, 3, 1, 2, 3]); - let deserialized_node = Node::deserialize(node_bytes).unwrap(); + let deserialized_node = Node::deserialize(node_bytes).unwrap_test(); assert_eq!(deserialized_node, orig_node); } @@ -1679,13 +1681,13 @@ mod tests { #[test] fn bug_scenario_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set(vec![0], vec![8, 244, 162, 237, 1]); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); tree.set(vec![0], vec![8, 133, 164, 237, 1]); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); tree.set(vec![0], vec![8, 133, 164, 237, 1]); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); tree.set(vec![0], vec![8, 135, 164, 237, 1]); tree.set( vec![ @@ -1703,7 +1705,7 @@ mod tests { vec![2, 173, 86, 59, 0, 0, 0, 0, 0, 1], vec![8, 173, 173, 237, 1, 16, 1], ); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); tree.set(vec![0], vec![8, 137, 164, 237, 1]); tree.set( vec![ @@ -1721,7 +1723,7 @@ mod tests { vec![2, 173, 86, 59, 0, 0, 0, 0, 0, 1], vec![8, 173, 173, 237, 1, 16, 1], ); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); tree.set(vec![0], vec![8, 138, 164, 237, 1]); tree.set( vec![ @@ -1739,9 +1741,9 @@ mod tests { vec![2, 174, 86, 59, 0, 0, 0, 0, 0, 1], vec![8, 174, 173, 237, 1, 16, 1], ); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); tree.set(vec![0], vec![8, 140, 164, 237, 1]); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); tree.set(vec![0], vec![8, 142, 164, 237, 1]); tree.set( @@ -1757,14 +1759,17 @@ mod tests { ], ); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); let expected = [ 136, 164, 1, 21, 163, 66, 127, 238, 197, 107, 178, 152, 75, 8, 254, 220, 62, 141, 140, 212, 4, 23, 213, 249, 34, 96, 132, 172, 166, 207, 48, 17, ]; - assert!(is_consistent(tree.root.clone().unwrap(), &tree.node_db)); + assert!(is_consistent( + tree.root.clone().unwrap_test(), + &tree.node_db + )); assert_eq!(expected, tree.root_hash()); } @@ -1772,7 +1777,7 @@ mod tests { #[test] fn bug_scenario_2_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set( vec![ 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 58, @@ -1808,14 +1813,14 @@ mod tests { ], ); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); let expected = [ 161, 141, 64, 164, 190, 244, 170, 230, 150, 211, 45, 54, 92, 136, 170, 253, 7, 176, 179, 212, 27, 116, 84, 160, 78, 92, 155, 245, 98, 143, 221, 105, ]; - let root = tree.root.as_ref().unwrap(); + let root = tree.root.as_ref().unwrap_test(); assert!(is_consistent(root, &tree.node_db)); assert_eq!(expected, tree.root_hash()); @@ -1825,7 +1830,7 @@ mod tests { #[test] fn bug_scenario_3_works() { let db = MemDB::new(); - let mut tree = Tree::new(db, None, 100.try_into().unwrap(), None).unwrap(); + let mut tree = Tree::new(db, None, 100.try_into().unwrap_test(), None).unwrap_test(); tree.set( vec![ 17, 20, 129, 58, 194, 42, 97, 73, 22, 85, 226, 120, 106, 224, 209, 39, 214, 153, @@ -1892,7 +1897,7 @@ mod tests { 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, ], ); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); //hash: [127, 232, 174, 89, 120, 86, 81, 219, 254, 142, 241, 61, 88, 167, 95, 47, 46, 11, 185, 19, 254, 90, 230, 122, 169, 230, 66, 137, 113, 190, 112, 170] tree.set( vec![ @@ -1955,7 +1960,7 @@ mod tests { 35, 35, 0, 0, 0, 0, 0, 0, 0, 0, 20, 95, 250, 64, 175, 205, 68, 27, 247, 205, 195, 84, 17, 223, 86, 125, 125, 81, 47, 40, 54, ]); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); //hash: [71, 62, 145, 220, 39, 77, 189, 142, 99, 132, 1, 149, 176, 46, 111, 122, 197, 109, 135, 202, 48, 4, 205, 181, 32, 126, 194, 131, 1, 107, 179, 202] tree.set( vec![ @@ -1978,7 +1983,7 @@ mod tests { 48, 18, 4, 8, 128, 163, 5, 90, 3, 50, 48, 48, ], ); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); //hash: [108, 218, 96, 64, 252, 252, 121, 101, 78, 92, 148, 82, 4, 236, 90, 170, 208, 15, 54, 39, 224, 114, 255, 233, 4, 228, 101, 43, 221, 201, 9, 69] tree.set( vec![ @@ -2031,7 +2036,7 @@ mod tests { 35, 35, 0, 0, 0, 0, 0, 0, 0, 0, 20, 126, 197, 61, 213, 158, 182, 233, 170, 29, 135, 149, 31, 46, 216, 41, 102, 244, 4, 4, 33, ]); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); //hash: [125, 158, 16, 16, 23, 121, 241, 110, 38, 21, 149, 110, 110, 28, 0, 31, 45, 10, 190, 92, 130, 177, 142, 113, 193, 79, 74, 61, 131, 50, 119, 107] tree.set( vec![ @@ -2192,7 +2197,7 @@ mod tests { 35, 35, 0, 0, 0, 0, 0, 0, 0, 0, 20, 126, 197, 61, 213, 158, 182, 233, 170, 29, 135, 149, 31, 46, 216, 41, 102, 244, 4, 4, 33, ]); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); //hash: [95, 218, 225, 239, 104, 173, 61, 97, 77, 92, 43, 191, 247, 22, 215, 180, 45, 46, 115, 93, 67, 216, 246, 202, 62, 17, 176, 236, 211, 235, 156, 111] tree.set( vec![ @@ -2243,14 +2248,14 @@ mod tests { 149, 31, 46, 216, 41, 102, 244, 4, 4, 33, ]); - tree.save_version().unwrap(); + tree.save_version().unwrap_test(); let expected = [ 51, 242, 234, 184, 99, 85, 249, 34, 67, 50, 97, 105, 141, 61, 225, 136, 3, 110, 208, 136, 19, 245, 48, 65, 1, 140, 5, 82, 49, 108, 187, 67, ]; - let root = tree.root.as_ref().unwrap(); + let root = tree.root.as_ref().unwrap_test(); assert!(is_consistent(root, &tree.node_db)); assert_eq!(expected, tree.root_hash()); } @@ -3024,7 +3029,7 @@ mod tests { ) where N: AsRef, { - let mut f = File::create(filename.as_ref()).unwrap(); + let mut f = File::create(filename.as_ref()).unwrap_test(); fn recursive_draw( root: Option, @@ -3059,7 +3064,7 @@ mod tests { self_size, self_key, ); - f.write_all(buf.as_bytes()).unwrap(); + f.write_all(buf.as_bytes()).unwrap_test(); match root.as_ref() { Node::Inner(node) => { @@ -3103,21 +3108,22 @@ mod tests { ) }; - f.write_all(buf.as_bytes()).unwrap(); + f.write_all(buf.as_bytes()).unwrap_test(); } } } None => { let buf = format!("{} --> none[NONE];\n", parent.expect("for this to not have a parent it must be the root, but then it wouldn't be `None`")); - f.write_all(buf.as_bytes()).unwrap(); + f.write_all(buf.as_bytes()).unwrap_test(); } } } - f.write_all("```mermaid\n graph TD;".as_bytes()).unwrap(); + f.write_all("```mermaid\n graph TD;".as_bytes()) + .unwrap_test(); recursive_draw(Some(root), node_db, None, &mut f, highlight); - f.write_all("```".as_bytes()).unwrap(); + f.write_all("```".as_bytes()).unwrap_test(); } } diff --git a/x/auth/src/genesis.rs b/x/auth/src/genesis.rs index a68f3c9d9..5b85b04ba 100644 --- a/x/auth/src/genesis.rs +++ b/x/auth/src/genesis.rs @@ -67,6 +67,8 @@ impl GenesisState { #[cfg(test)] mod tests { + use gears::extensions::testing::UnwrapTesting; + use super::*; #[test] @@ -74,7 +76,7 @@ mod tests { let mut genesis_state = GenesisState::default(); let address = "cosmos1syavy2npfyt9tcncdtsdzf7kny9lh777pahuux" .parse() - .unwrap(); + .unwrap_test(); genesis_state .add_genesis_account(address) .expect("will succeed because address is not in genesis_state.accounts"); @@ -88,7 +90,7 @@ mod tests { account_number: 0, sequence: 0, }) - if address == &AccAddress::from_bech32("cosmos1syavy2npfyt9tcncdtsdzf7kny9lh777pahuux").unwrap()),); + if address == &AccAddress::from_bech32("cosmos1syavy2npfyt9tcncdtsdzf7kny9lh777pahuux").unwrap_test()),); } #[test] @@ -154,6 +156,6 @@ mod tests { } }"#; - serde_json::from_str::(genesis).unwrap(); + serde_json::from_str::(genesis).unwrap_test(); } } diff --git a/x/auth/src/keeper.rs b/x/auth/src/keeper.rs index 1e042fffd..848461fe3 100644 --- a/x/auth/src/keeper.rs +++ b/x/auth/src/keeper.rs @@ -9,15 +9,16 @@ use gears::context::init::InitContext; use gears::context::query::QueryContext; use gears::context::{QueryableContext, TransactionalContext}; use gears::core::Protobuf as _; -use gears::ext::{IteratorPaginate, Pagination}; +use gears::extensions::corruption::UnwrapCorrupt; +use gears::extensions::gas::GasResultExt; +use gears::extensions::pagination::{IteratorPaginate, Pagination}; use gears::params::ParamsSubspaceKey; -use gears::store::database::{ext::UnwrapCorrupt, Database}; +use gears::store::database::Database; use gears::store::StoreKey; use gears::types::account::{Account, BaseAccount, ModuleAccount}; use gears::types::address::AccAddress; use gears::types::pagination::response::PaginationResponse; use gears::types::store::gas::errors::GasStoreErrors; -use gears::types::store::gas::ext::GasResultExt; use gears::x::keepers::auth::AuthKeeper; use gears::x::module::Module; use prost::Message; diff --git a/x/auth/src/params.rs b/x/auth/src/params.rs index 017c4697a..209bc6891 100644 --- a/x/auth/src/params.rs +++ b/x/auth/src/params.rs @@ -3,6 +3,7 @@ use std::collections::{HashMap, HashSet}; use gears::application::keepers::params::ParamsKeeper; use gears::core::serializers::serialize_number_to_string; +use gears::extensions::corruption::UnwrapCorrupt; use gears::params::{ParamKind, ParamsDeserialize, ParamsSerialize, ParamsSubspaceKey}; use gears::x::keepers::auth::AuthParams; @@ -111,28 +112,36 @@ impl ParamsSerialize for AuthsParams { impl ParamsDeserialize for AuthsParams { fn from_raw(mut fields: HashMap<&'static str, Vec>) -> Self { - // TODO:NOW THIS IS AWFUL + // THIS IS AWFUL Self { max_memo_characters: ParamKind::U64 - .parse_param(fields.remove(KEY_MAX_MEMO_CHARACTERS).unwrap()) + .parse_param(fields.remove(KEY_MAX_MEMO_CHARACTERS).unwrap_or_corrupt()) .unsigned_64() - .unwrap(), + .unwrap_or_corrupt(), tx_sig_limit: ParamKind::U64 - .parse_param(fields.remove(KEY_TX_SIG_LIMIT).unwrap()) + .parse_param(fields.remove(KEY_TX_SIG_LIMIT).unwrap_or_corrupt()) .unsigned_64() - .unwrap(), + .unwrap_or_corrupt(), tx_size_cost_per_byte: ParamKind::U64 - .parse_param(fields.remove(KEY_TX_SIZE_COST_PER_BYTE).unwrap()) + .parse_param(fields.remove(KEY_TX_SIZE_COST_PER_BYTE).unwrap_or_corrupt()) .unsigned_64() - .unwrap(), + .unwrap_or_corrupt(), sig_verify_cost_ed25519: ParamKind::U64 - .parse_param(fields.remove(KEY_SIG_VERIFY_COST_ED25519).unwrap()) + .parse_param( + fields + .remove(KEY_SIG_VERIFY_COST_ED25519) + .unwrap_or_corrupt(), + ) .unsigned_64() - .unwrap(), + .unwrap_or_corrupt(), sig_verify_cost_secp256k1: ParamKind::U64 - .parse_param(fields.remove(KEY_SIG_VERIFY_COST_SECP256K1).unwrap()) + .parse_param( + fields + .remove(KEY_SIG_VERIFY_COST_SECP256K1) + .unwrap_or_corrupt(), + ) .unsigned_64() - .unwrap(), + .unwrap_or_corrupt(), } } } @@ -204,6 +213,7 @@ mod tests { use gears::{ baseapp::ConsensusParams, derive::{ParamsKeys, StoreKeys}, + extensions::testing::UnwrapTesting, store::{bank::multi::ApplicationMultiBank, database::MemDB}, utils::node::build_init_ctx, }; @@ -216,7 +226,8 @@ mod tests { params_subspace_key: SubspaceKey::Auth, }; - let mut multi_store = ApplicationMultiBank::<_, SubspaceKey>::new(MemDB::new()); + let mut multi_store = + ApplicationMultiBank::<_, SubspaceKey>::new(MemDB::new()).unwrap_test(); let before_hash = multi_store.head_commit_hash(); diff --git a/x/bank/src/abci_handler.rs b/x/bank/src/abci_handler.rs index 52218574a..0c31ba4c1 100644 --- a/x/bank/src/abci_handler.rs +++ b/x/bank/src/abci_handler.rs @@ -6,13 +6,13 @@ use gears::baseapp::QueryRequest; use gears::context::{init::InitContext, query::QueryContext, tx::TxContext}; use gears::core::Protobuf; use gears::derive::Query; -use gears::ext::Pagination; +use gears::extensions::gas::GasResultExt; +use gears::extensions::pagination::Pagination; use gears::params::ParamsSubspaceKey; use gears::store::database::Database; use gears::store::StoreKey; use gears::tendermint::types::request::query::RequestQuery; use gears::types::pagination::response::PaginationResponse; -use gears::types::store::gas::ext::GasResultExt; use gears::x::keepers::auth::AuthKeeper; use gears::x::keepers::bank::BankKeeper; use gears::x::module::Module; diff --git a/x/bank/src/client/cli/query.rs b/x/bank/src/client/cli/query.rs index 2f78d8089..0aac25931 100644 --- a/x/bank/src/client/cli/query.rs +++ b/x/bank/src/client/cli/query.rs @@ -8,7 +8,7 @@ use gears::{ cli::pagination::CliPaginationRequest, core::Protobuf, derive::Query, - ext::FallibleMapExt, + extensions::try_map::FallibleMapExt, types::{address::AccAddress, pagination::request::PaginationRequest}, }; use serde::{Deserialize, Serialize}; diff --git a/x/bank/src/keeper.rs b/x/bank/src/keeper.rs index fc69ffb41..e1c0f4e23 100644 --- a/x/bank/src/keeper.rs +++ b/x/bank/src/keeper.rs @@ -6,9 +6,10 @@ use gears::application::keepers::params::ParamsKeeper; use gears::context::{init::InitContext, query::QueryContext}; use gears::context::{QueryableContext, TransactionalContext}; use gears::core::Protobuf; -use gears::ext::{IteratorPaginate, Pagination, PaginationResult}; +use gears::extensions::corruption::UnwrapCorrupt; +use gears::extensions::gas::GasResultExt; +use gears::extensions::pagination::{IteratorPaginate, Pagination, PaginationResult}; use gears::params::ParamsSubspaceKey; -use gears::store::database::ext::UnwrapCorrupt; use gears::store::database::prefix::PrefixDB; use gears::store::database::Database; use gears::store::StoreKey; @@ -19,7 +20,6 @@ use gears::types::base::coins::UnsignedCoins; use gears::types::denom::Denom; use gears::types::msg::send::MsgSend; use gears::types::store::gas::errors::GasStoreErrors; -use gears::types::store::gas::ext::GasResultExt; use gears::types::store::prefix::mutable::PrefixStoreMut; use gears::types::tx::metadata::Metadata; use gears::types::uint::Uint256; @@ -110,7 +110,7 @@ impl< let account = self .auth_keeper .get_account(ctx, &module_acc_addr)? - .unwrap(); // TODO: + .ok_or(AccountNotFound::new(module_acc_addr.to_string()))?; match account.has_permissions("burner") { true => Ok(()), diff --git a/x/bank/src/params.rs b/x/bank/src/params.rs index 2a571ba32..5d6eba7a4 100644 --- a/x/bank/src/params.rs +++ b/x/bank/src/params.rs @@ -1,5 +1,6 @@ use gears::application::keepers::params::ParamsKeeper; use gears::derive::Protobuf; +use gears::extensions::corruption::UnwrapCorrupt; use gears::params::{ParamKind, ParamsDeserialize, ParamsSerialize, ParamsSubspaceKey}; use gears::types::denom::Denom; use serde::{Deserialize, Serialize}; @@ -68,16 +69,16 @@ impl ParamsDeserialize for BankParams { fn from_raw(mut fields: HashMap<&'static str, Vec>) -> Self { Self { default_send_enabled: ParamKind::Bool - .parse_param(fields.remove(KEY_DEFAULT_SEND_ENABLED).unwrap()) + .parse_param(fields.remove(KEY_DEFAULT_SEND_ENABLED).unwrap_or_corrupt()) .boolean() - .unwrap(), + .unwrap_or_corrupt(), send_enabled: serde_json::from_slice( &ParamKind::Bytes - .parse_param(fields.remove(KEY_SEND_ENABLED).unwrap()) + .parse_param(fields.remove(KEY_SEND_ENABLED).unwrap_or_corrupt()) .bytes() - .unwrap(), + .unwrap_or_corrupt(), ) - .unwrap(), + .unwrap_or_corrupt(), } } } diff --git a/x/bank/tests/abci.rs b/x/bank/tests/abci.rs index 649c73799..6293a10a9 100644 --- a/x/bank/tests/abci.rs +++ b/x/bank/tests/abci.rs @@ -4,6 +4,7 @@ use bank::{BankABCIHandler, GenesisState, Keeper, Message}; use gears::{ application::handlers::node::ModuleInfo, derive::{ParamsKeys, StoreKeys}, + extensions::testing::UnwrapTesting, tendermint::types::time::timestamp::Timestamp, types::{ address::AccAddress, @@ -57,7 +58,7 @@ fn test_init_and_sending_tx() { genesis.add_genesis_account( acc_address(), - UnsignedCoins::new(vec![UnsignedCoin::from_str("30uatom").unwrap()]).unwrap(), + UnsignedCoins::new(vec![UnsignedCoin::from_str("30uatom").unwrap_test()]).unwrap_test(), ); let opt: MockOptionsFormer< diff --git a/x/distribution/src/client/cli/query.rs b/x/distribution/src/client/cli/query.rs index 829163b09..b4ad2d373 100644 --- a/x/distribution/src/client/cli/query.rs +++ b/x/distribution/src/client/cli/query.rs @@ -11,7 +11,7 @@ use gears::{ baseapp::Query, cli::pagination::CliPaginationRequest, core::Protobuf, - ext::FallibleMapExt, + extensions::try_map::FallibleMapExt, types::{ address::{AccAddress, ValAddress}, pagination::request::PaginationRequest, diff --git a/x/distribution/src/keeper/allocation.rs b/x/distribution/src/keeper/allocation.rs index 782bbd5f3..58ff8030f 100644 --- a/x/distribution/src/keeper/allocation.rs +++ b/x/distribution/src/keeper/allocation.rs @@ -6,6 +6,7 @@ use crate::{ use gears::{ context::block::BlockContext, error::{MathOperation, NumericError}, + extensions::gas::GasResultExt, tendermint::types::proto::{ event::{Event, EventAttribute}, info::VoteInfo, @@ -103,7 +104,9 @@ impl< EventAttribute { key: "amount".into(), // TODO: stringify coins structs - value: serde_json::to_string(&proposer_reward).unwrap().into(), + value: serde_json::to_string(&proposer_reward) + .expect("serde can't fail") + .into(), index: false, }, EventAttribute { @@ -203,7 +206,9 @@ impl< EventAttribute { key: "amount".into(), // TODO: stringify coins structs - value: serde_json::to_string(&commission).unwrap().into(), + value: serde_json::to_string(&commission) + .expect("serde can't fail") + .into(), index: false, }, EventAttribute { @@ -255,7 +260,9 @@ impl< EventAttribute { key: "amount".into(), // TODO: stringify coins structs - value: serde_json::to_string(&tokens).unwrap().into(), + value: serde_json::to_string(&tokens) + .expect("serde can't fail") + .into(), index: false, }, EventAttribute { diff --git a/x/distribution/src/keeper/delegation.rs b/x/distribution/src/keeper/delegation.rs index 695d55150..c99e1947f 100644 --- a/x/distribution/src/keeper/delegation.rs +++ b/x/distribution/src/keeper/delegation.rs @@ -191,7 +191,9 @@ impl< EventAttribute { key: "amount".into(), // TODO: stringify coins structs - value: serde_json::to_string(&final_rewards).unwrap().into(), + value: serde_json::to_string(&final_rewards) + .expect("serde can't fail") + .into(), index: false, }, EventAttribute { diff --git a/x/distribution/src/keeper/mod.rs b/x/distribution/src/keeper/mod.rs index e4ac41213..ae2b2f170 100644 --- a/x/distribution/src/keeper/mod.rs +++ b/x/distribution/src/keeper/mod.rs @@ -3,6 +3,7 @@ use crate::{ ValidatorAccumulatedCommission, ValidatorOutstandingRewards, }; use anyhow::anyhow; +use gears::extensions::gas::GasResultExt; pub use gears::{ context::init::InitContext, params::ParamsSubspaceKey, @@ -22,7 +23,7 @@ use gears::{ types::{ address::{AccAddress, ConsAddress, ValAddress}, base::coins::{DecimalCoins, UnsignedCoins}, - store::gas::{errors::GasStoreErrors, ext::GasResultExt}, + store::gas::errors::GasStoreErrors, }, x::keepers::staking::DistributionStakingKeeper, }; @@ -303,7 +304,9 @@ impl< attributes: vec![EventAttribute { key: "amount".into(), // TODO: stringify coins structs - value: serde_json::to_string(&commission).unwrap().into(), + value: serde_json::to_string(&commission) + .expect("serde can't fail") + .into(), index: false, }], }); diff --git a/x/distribution/src/keeper/query.rs b/x/distribution/src/keeper/query.rs index cee46d5d3..5ccc8fdf0 100644 --- a/x/distribution/src/keeper/query.rs +++ b/x/distribution/src/keeper/query.rs @@ -11,7 +11,7 @@ use crate::{ use gears::{ baseapp::errors::QueryError, context::query::QueryContext, - ext::{IteratorPaginate, Pagination}, + extensions::pagination::{IteratorPaginate, Pagination}, types::pagination::response::PaginationResponse, x::types::delegation::StakingDelegation, }; diff --git a/x/distribution/src/keeper/store.rs b/x/distribution/src/keeper/store.rs index a310cfcf2..604719848 100644 --- a/x/distribution/src/keeper/store.rs +++ b/x/distribution/src/keeper/store.rs @@ -14,7 +14,7 @@ use crate::{ use gears::{ context::{InfallibleContext, InfallibleContextMut, QueryableContext}, core::Protobuf, - store::database::ext::UnwrapCorrupt, + extensions::corruption::UnwrapCorrupt, types::address::{AccAddress, ValAddress}, }; diff --git a/x/distribution/src/params.rs b/x/distribution/src/params.rs index 99d1c7af9..573b1e26c 100644 --- a/x/distribution/src/params.rs +++ b/x/distribution/src/params.rs @@ -6,6 +6,7 @@ use std::{ use gears::{ context::{InfallibleContext, InfallibleContextMut, QueryableContext, TransactionalContext}, core::Protobuf, + extensions::corruption::UnwrapCorrupt, params::{ gas, infallible_subspace, infallible_subspace_mut, ParamKind, ParamsDeserialize, ParamsSerialize, ParamsSubspaceKey, @@ -122,37 +123,37 @@ impl ParamsDeserialize for DistributionParams { community_tax: Decimal256::from_str( &String::from_utf8( ParamKind::Bytes - .parse_param(fields.remove(KEY_COMMUNITY_TAX).unwrap()) + .parse_param(fields.remove(KEY_COMMUNITY_TAX).unwrap_or_corrupt()) .bytes() - .unwrap(), + .unwrap_or_corrupt(), ) - .unwrap(), + .unwrap_or_corrupt(), ) - .unwrap(), + .unwrap_or_corrupt(), base_proposer_reward: Decimal256::from_str( &String::from_utf8( ParamKind::Bytes - .parse_param(fields.remove(KEY_BASE_PROPOSER_REWARD).unwrap()) + .parse_param(fields.remove(KEY_BASE_PROPOSER_REWARD).unwrap_or_corrupt()) .bytes() - .unwrap(), + .unwrap_or_corrupt(), ) - .unwrap(), + .unwrap_or_corrupt(), ) - .unwrap(), + .unwrap_or_corrupt(), bonus_proposer_reward: Decimal256::from_str( &String::from_utf8( ParamKind::Bytes - .parse_param(fields.remove(KEY_BONUS_PROPOSER_REWARD).unwrap()) + .parse_param(fields.remove(KEY_BONUS_PROPOSER_REWARD).unwrap_or_corrupt()) .bytes() - .unwrap(), + .unwrap_or_corrupt(), ) - .unwrap(), + .unwrap_or_corrupt(), ) - .unwrap(), + .unwrap_or_corrupt(), withdraw_addr_enabled: ParamKind::Bool - .parse_param(fields.remove(KEY_WITHDRAW_ADDR_ENABLED).unwrap()) + .parse_param(fields.remove(KEY_WITHDRAW_ADDR_ENABLED).unwrap_or_corrupt()) .boolean() - .unwrap(), + .unwrap_or_corrupt(), } } } diff --git a/x/distribution/src/types/iter/slash_event.rs b/x/distribution/src/types/iter/slash_event.rs index 9bb0fd828..11c5254e4 100644 --- a/x/distribution/src/types/iter/slash_event.rs +++ b/x/distribution/src/types/iter/slash_event.rs @@ -3,8 +3,9 @@ use std::borrow::Cow; use gears::{ context::QueryableContext, core::Protobuf, + extensions::corruption::UnwrapCorrupt, store::{ - database::{ext::UnwrapCorrupt, prefix::PrefixDB, Database}, + database::{prefix::PrefixDB, Database}, StoreKey, }, types::{ diff --git a/x/evidence/src/keeper/mod.rs b/x/evidence/src/keeper/mod.rs index c371223a6..085fcea8d 100644 --- a/x/evidence/src/keeper/mod.rs +++ b/x/evidence/src/keeper/mod.rs @@ -1,18 +1,18 @@ use crate::{errors::EvidenceAlreadyExistsError, types::Evidence, GenesisState}; +use gears::extensions::gas::GasResultExt; use gears::{ context::{init::InitContext, QueryableContext, TransactionalContext}, core::any::google::Any, - store::{ - database::{ext::UnwrapCorrupt, Database}, - StoreKey, - }, + extensions::corruption::UnwrapCorrupt, + store::{database::Database, StoreKey}, tendermint::informal::Hash, - types::store::gas::{errors::GasStoreErrors, ext::GasResultExt}, + types::store::gas::errors::GasStoreErrors, x::{ keepers::{slashing::EvidenceSlashingKeeper, staking::SlashingStakingKeeper}, module::Module, }, }; + use std::marker::PhantomData; mod infraction; diff --git a/x/evidence/src/keeper/query.rs b/x/evidence/src/keeper/query.rs index e0bb8d18f..53c9545ad 100644 --- a/x/evidence/src/keeper/query.rs +++ b/x/evidence/src/keeper/query.rs @@ -5,7 +5,7 @@ use crate::types::{ }; use gears::{ context::query::QueryContext, - ext::{IteratorPaginate, Pagination, PaginationKey}, + extensions::pagination::{IteratorPaginate, Pagination, PaginationKey}, }; impl< diff --git a/x/genutil/Cargo.toml b/x/genutil/Cargo.toml index 8d36e76ae..9aa2c0057 100644 --- a/x/genutil/Cargo.toml +++ b/x/genutil/Cargo.toml @@ -9,6 +9,7 @@ workspace = true [dependencies] gears = { path = "../../gears", features = ["cli", "xmods"] } staking = { path = "../staking" } +tendermint = { path = "../../tendermint" } # TODO: WHY? Staking should be fine, but why tendermint? # unsorted clap = { workspace = true } @@ -17,5 +18,4 @@ serde = { workspace = true } serde_json = { workspace = true } url = { workspace = true } toml_edit = "0.22.20" # to preserve order, comments and sane look better to use toml_edit crate -tendermint = { path = "../../tendermint" } -# bip32 = { workspace = true } +# bip32 = { workspace = true } \ No newline at end of file diff --git a/x/genutil/src/client/cli/gentx.rs b/x/genutil/src/client/cli/gentx.rs index 4d030f9df..dee0bc393 100644 --- a/x/genutil/src/client/cli/gentx.rs +++ b/x/genutil/src/client/cli/gentx.rs @@ -3,11 +3,9 @@ use std::{net::SocketAddr, path::PathBuf}; use clap::{ArgAction, Args, ValueHint}; use gears::application::ApplicationInfo; +use gears::extensions::socket_addr; use gears::tendermint::types::proto::crypto::PublicKey as TendermintPublicKey; -use gears::{ - socket_addr, - types::{base::coin::UnsignedCoin, decimal256::Decimal256, uint::Uint256}, -}; +use gears::types::{base::coin::UnsignedCoin, decimal256::Decimal256, uint::Uint256}; use crate::gentx::GentxCmd; @@ -37,15 +35,15 @@ pub struct GentxCli { pub details: Option, /// The initial commission rate percentage /* 0.1 */ - #[arg(long, default_value_t = Decimal256::from_atomics(1u64, 1).unwrap())] + #[arg(long, default_value_t = Decimal256::from_atomics(1u64, 1).expect("default is valid"))] pub commission_rate: Decimal256, /// The maximum commission rate percentage /* 0.2 */ - #[arg(long, default_value_t = Decimal256::from_atomics(2u64, 1).unwrap())] + #[arg(long, default_value_t = Decimal256::from_atomics(2u64, 1).expect("default is valid"))] pub commission_max_rate: Decimal256, /// The maximum commission change rate percentage (per day) /* 0.01 */ - #[arg(long, default_value_t = Decimal256::from_atomics(1u64, 2).unwrap())] + #[arg(long, default_value_t = Decimal256::from_atomics(1u64, 2).expect("default is valid"))] pub commission_max_change_rate: Decimal256, /// The minimum self delegation required on the validator #[arg(long, default_value_t = Uint256::zero())] diff --git a/x/gov/src/abci_handler.rs b/x/gov/src/abci_handler.rs index e82db37a2..85f2e7fad 100644 --- a/x/gov/src/abci_handler.rs +++ b/x/gov/src/abci_handler.rs @@ -1,8 +1,10 @@ use std::marker::PhantomData; +use gears::baseapp::QueryResponse; +use gears::extensions::gas::GasResultExt; use gears::{ application::handlers::node::{ABCIHandler, ModuleInfo, TxError}, - baseapp::{errors::QueryError, QueryResponse}, + baseapp::errors::QueryError, context::{ block::BlockContext, init::InitContext, query::QueryContext, tx::TxContext, TransactionalContext, @@ -17,7 +19,7 @@ use gears::{ }, request::{end_block::RequestEndBlock, query::RequestQuery}, }, - types::{store::gas::ext::GasResultExt, tx::raw::TxWithRaw}, + types::tx::raw::TxWithRaw, x::{ keepers::{gov::GovernanceBankKeeper, staking::GovStakingKeeper}, module::Module, diff --git a/x/gov/src/keeper.rs b/x/gov/src/keeper.rs index 8cacec50a..83131d99b 100644 --- a/x/gov/src/keeper.rs +++ b/x/gov/src/keeper.rs @@ -4,6 +4,7 @@ use std::{ ops::{Div, Mul}, }; +use gears::extensions::gas::GasResultExt; use gears::{ application::keepers::params::ParamsKeeper, context::{ @@ -16,7 +17,7 @@ use gears::{ types::{ address::{AccAddress, ValAddress}, decimal256::Decimal256, - store::gas::{errors::GasStoreErrors, ext::GasResultExt}, + store::gas::errors::GasStoreErrors, }, x::{ keepers::{gov::GovernanceBankKeeper, staking::GovStakingKeeper}, diff --git a/x/gov/src/params.rs b/x/gov/src/params.rs index 22d65ca03..ef0b69a83 100644 --- a/x/gov/src/params.rs +++ b/x/gov/src/params.rs @@ -6,6 +6,7 @@ use std::{ use gears::{ application::keepers::params::ParamsKeeper, core::{errors::CoreError, Protobuf}, + error::ProtobufError, params::{ParamsDeserialize, ParamsSerialize, ParamsSubspaceKey}, tendermint::types::time::duration::Duration, types::{ @@ -235,7 +236,7 @@ impl From for inner::TallyParams { impl Protobuf for TallyParams {} impl TryFrom for VotingParams { - type Error = CoreError; + type Error = ProtobufError; fn try_from( inner::VotingParams { voting_period }: inner::VotingParams, @@ -246,7 +247,8 @@ impl TryFrom for VotingParams { "VotingParams: field `voting_period`".to_owned(), ))?; - Duration::try_new(duration.seconds, duration.nanos).unwrap() // TODO:NOW + Duration::try_new(duration.seconds, duration.nanos) + .map_err(|err| anyhow::anyhow!("failed to map duration: {err}"))? }, }) } diff --git a/x/ibc-rs/Cargo.toml b/x/ibc-rs/Cargo.toml index 9c657aaab..6ab088e26 100644 --- a/x/ibc-rs/Cargo.toml +++ b/x/ibc-rs/Cargo.toml @@ -23,6 +23,7 @@ anyhow = { workspace = true } thiserror = { workspace = true } constcat = { workspace = true } derive_more = "0.99.17" # TODO: move to workspace +nz = { workspace = true } #networking axum = { workspace = true } diff --git a/x/ibc-rs/src/abci_handler.rs b/x/ibc-rs/src/abci_handler.rs index 4473f1375..52592b797 100644 --- a/x/ibc-rs/src/abci_handler.rs +++ b/x/ibc-rs/src/abci_handler.rs @@ -1,9 +1,11 @@ +use std::marker::PhantomData; + use crate::{ errors, ics02_client::client::cli::query::client_states::STATES_URL, keeper::Keeper, message::Message, types::genesis::GenesisState, }; use gears::{ - application::handlers::node::TxError, + application::handlers::node::{ModuleInfo, TxError}, baseapp::errors::QueryError, context::{init::InitContext, query::QueryContext, tx::TxContext}, core::errors::CoreError, @@ -18,13 +20,14 @@ use ibc::primitives::proto::Protobuf; use prost::Message as ProstMessage; #[derive(Debug, Clone)] -pub struct ABCIHandler { +pub struct ABCIHandler { //tx_keeper: TxKeeper, // TODO: Should signature for Handler always be &self or allow &mut self? //query_keeper: QueryKeeper, keeper: Keeper, + _marker: PhantomData, } -impl ABCIHandler { +impl ABCIHandler { // pub fn new(tx_keeper: TxKeeper, query_keeper: QueryKeeper) -> Self { // Self { // tx_keeper, @@ -33,7 +36,10 @@ impl ABCIHandler { // } pub fn new(keeper: Keeper) -> Self { - Self { keeper } + Self { + keeper, + _marker: PhantomData, + } } pub fn msg( @@ -53,7 +59,9 @@ impl ABCIHandler { // .tx_keeper // .client_create(ctx, &client_state, consensus_state.into())?; - self.keeper.client_create(ctx, msg); + self.keeper + .client_create(ctx, msg) + .map_err(|e| TxError::new::(e.to_string(), nz::u16!(1)))?; Ok(()) } // Message::ClientUpdate(msg) => { diff --git a/x/ibc-rs/src/ics02_client/params.rs b/x/ibc-rs/src/ics02_client/params.rs index de3cd4d18..9bae3430f 100644 --- a/x/ibc-rs/src/ics02_client/params.rs +++ b/x/ibc-rs/src/ics02_client/params.rs @@ -73,7 +73,7 @@ impl ClientParamsKeeper { ) -> ClientParams { let store = infallible_subspace(ctx, &self.params_subspace_key); - store.params().unwrap() // TODO: Add default + store.params().unwrap_or_default() } pub fn set>( @@ -92,7 +92,7 @@ impl ClientParamsKeeper { ) -> Result { let store = gas::subspace(ctx, &self.params_subspace_key); - Ok(store.params()?.unwrap()) // TODO: Add default + Ok(store.params()?.unwrap_or_default()) } pub fn try_set>( diff --git a/x/ibc-rs/src/ics02_client/types/query.rs b/x/ibc-rs/src/ics02_client/types/query.rs index 8d344003d..963b23463 100644 --- a/x/ibc-rs/src/ics02_client/types/query.rs +++ b/x/ibc-rs/src/ics02_client/types/query.rs @@ -1,4 +1,4 @@ -use gears::core::errors::CoreError; +use gears::{core::errors::CoreError, error::ProtobufError}; use ibc::{ core::{ client::types::proto::v1::IdentifiedClientState as RawIdentifiedClientState, @@ -17,7 +17,7 @@ pub struct QueryClientStatesResponse { } impl TryFrom for QueryClientStatesResponse { - type Error = CoreError; + type Error = ProtobufError; fn try_from(raw: RawQueryClientStatesResponse) -> Result { let client_states: Result, Self::Error> = raw @@ -80,12 +80,19 @@ impl From for RawIdentifiedClientState { } impl TryFrom for IdentifiedClientState { - type Error = CoreError; + type Error = ProtobufError; fn try_from(value: RawIdentifiedClientState) -> Result { Ok(IdentifiedClientState { - client_id: value.client_id.parse().unwrap(), //TODO: unwrap - client_state: value.client_state.unwrap().try_into().unwrap(), //TODO: unwraps + client_id: value + .client_id + .parse() + .map_err(|e| anyhow::anyhow!("invalid client_id: {e}"))?, + client_state: value + .client_state + .ok_or(CoreError::MissingField("client_state".to_owned()))? + .try_into() + .map_err(|e| anyhow::anyhow!("invalid client_state: {e}"))?, }) } } diff --git a/x/ibc-rs/src/ics03_connection/params.rs b/x/ibc-rs/src/ics03_connection/params.rs index d1e49ce37..26a50acd1 100644 --- a/x/ibc-rs/src/ics03_connection/params.rs +++ b/x/ibc-rs/src/ics03_connection/params.rs @@ -4,6 +4,7 @@ use std::collections::HashSet; use gears::context::InfallibleContext; use gears::context::InfallibleContextMut; use gears::core::serializers::serialize_number_to_string; +use gears::extensions::corruption::UnwrapCorrupt; use gears::params::infallible_subspace; use gears::params::infallible_subspace_mut; use gears::params::ParamKind; @@ -57,9 +58,13 @@ impl ParamsDeserialize for ConnectionParams { fn from_raw(mut fields: HashMap<&'static str, Vec>) -> Self { Self { max_expected_time_per_block: ParamKind::U64 - .parse_param(fields.remove(KEY_MAX_EXPECTED_TIME_PER_BLOCK).unwrap()) + .parse_param( + fields + .remove(KEY_MAX_EXPECTED_TIME_PER_BLOCK) + .unwrap_or_corrupt(), + ) .unsigned_64() - .unwrap(), + .unwrap_or_corrupt(), } } } @@ -76,7 +81,7 @@ impl ConnectionParamsKeeper { ) -> ConnectionParams { let store = infallible_subspace(ctx, &self.params_subspace_key); - store.params().unwrap() // TODO: Add default + store.params().unwrap_or_default() } pub fn set>( diff --git a/x/ibc-rs/src/keeper.rs b/x/ibc-rs/src/keeper.rs index cf8b3815f..0c27099ef 100644 --- a/x/ibc-rs/src/keeper.rs +++ b/x/ibc-rs/src/keeper.rs @@ -51,7 +51,7 @@ impl Keeper { &self, ctx: &mut TxContext<'_, DB, SK>, msg: MsgCreateClient, - ) { + ) -> Result<(), ibc::core::handler::types::error::ContextError> { let mut ctx = Context { gears_ctx: ctx, client_keeper: &self.client_keeper, @@ -62,7 +62,7 @@ impl Keeper { let mut router = ClientRouter; - dispatch(&mut ctx, &mut router, msg.into()).unwrap() //TODO: unwrap + dispatch(&mut ctx, &mut router, msg.into()) } pub fn client_states( diff --git a/x/slashing/src/abci_handler.rs b/x/slashing/src/abci_handler.rs index 286f2d9db..e20c584c5 100644 --- a/x/slashing/src/abci_handler.rs +++ b/x/slashing/src/abci_handler.rs @@ -7,7 +7,7 @@ use gears::{ baseapp::{errors::QueryError, QueryResponse}, context::{block::BlockContext, init::InitContext, query::QueryContext, tx::TxContext}, core::Protobuf, - ext::Pagination, + extensions::pagination::Pagination, params::ParamsSubspaceKey, store::{database::Database, StoreKey}, tendermint::types::request::{begin_block::RequestBeginBlock, query::RequestQuery}, diff --git a/x/slashing/src/keeper.rs b/x/slashing/src/keeper.rs index 173f01071..9cfa758f0 100644 --- a/x/slashing/src/keeper.rs +++ b/x/slashing/src/keeper.rs @@ -7,18 +7,19 @@ use crate::{ GenesisState, MsgUnjail, QueryParamsRequest, QueryParamsResponse, QuerySigningInfoRequest, QuerySigningInfoResponse, SlashingParamsKeeper, ValidatorSigningInfo, }; +use gears::extensions::gas::GasResultExt; use gears::{ context::{ block::BlockContext, init::InitContext, query::QueryContext, tx::TxContext, InfallibleContextMut, QueryableContext, TransactionalContext, }, core::Protobuf, - ext::{IteratorPaginate, Pagination, PaginationResult}, - params::ParamsSubspaceKey, - store::{ - database::{ext::UnwrapCorrupt, Database}, - StoreKey, + extensions::{ + corruption::UnwrapCorrupt, + pagination::{IteratorPaginate, Pagination, PaginationResult}, }, + params::ParamsSubspaceKey, + store::{database::Database, StoreKey}, tendermint::types::{ proto::{ crypto::PublicKey, @@ -30,7 +31,7 @@ use gears::{ types::{ address::{AccAddress, ConsAddress, ValAddress}, decimal256::Decimal256, - store::gas::{errors::GasStoreErrors, ext::GasResultExt}, + store::gas::errors::GasStoreErrors, }, x::{ errors::AccountNotFound, @@ -437,7 +438,7 @@ impl, M: let key = addr_pubkey_relation_key(addr); // TODO: add Protobuf for PublicKey - let value = serde_json::to_vec(pub_key).unwrap(); + let value = serde_json::to_vec(pub_key).expect("serde encoding can't fail"); store.set(key, value) } @@ -507,7 +508,7 @@ impl, M: let mut store = ctx.infallible_store_mut(&self.store_key); let key = validator_missed_block_bit_array_key(addr.clone(), index); // TODO: something like that in sdk - let value = serde_json::to_vec(&missed).unwrap(); + let value = serde_json::to_vec(&missed).expect("serde encoding can't fail"); store.set(key, value) } diff --git a/x/slashing/src/params.rs b/x/slashing/src/params.rs index 35e1f3067..bea8ba46f 100644 --- a/x/slashing/src/params.rs +++ b/x/slashing/src/params.rs @@ -2,6 +2,7 @@ use anyhow::anyhow; use gears::{ context::{InfallibleContext, InfallibleContextMut, QueryableContext, TransactionalContext}, core::{serializers::serialize_number_to_string, Protobuf}, + extensions::corruption::UnwrapCorrupt, params::{ gas, infallible_subspace, infallible_subspace_mut, ParamKind, ParamsDeserialize, ParamsSerialize, ParamsSubspaceKey, @@ -161,43 +162,55 @@ impl ParamsDeserialize for SlashingParams { fn from_raw(mut fields: HashMap<&'static str, Vec>) -> Self { Self { signed_blocks_window: ParamKind::I64 - .parse_param(fields.remove(KEY_SIGNED_BLOCKS_WINDOW).unwrap()) + .parse_param(fields.remove(KEY_SIGNED_BLOCKS_WINDOW).unwrap_or_corrupt()) .signed_64() - .unwrap(), + .unwrap_or_corrupt(), min_signed_per_window: Decimal256::from_str( &String::from_utf8( ParamKind::Bytes - .parse_param(fields.remove(KEY_MIN_SIGNED_PER_WINDOW).unwrap()) + .parse_param(fields.remove(KEY_MIN_SIGNED_PER_WINDOW).unwrap_or_corrupt()) .bytes() - .unwrap(), + .unwrap_or_corrupt(), ) - .unwrap(), + .unwrap_or_corrupt(), ) - .unwrap(), + .unwrap_or_corrupt(), downtime_jail_duration: ParamKind::I64 - .parse_param(fields.remove(KEY_DOWNTIME_JAIL_DURATION).unwrap()) + .parse_param( + fields + .remove(KEY_DOWNTIME_JAIL_DURATION) + .unwrap_or_corrupt(), + ) .signed_64() - .unwrap(), + .unwrap_or_corrupt(), slash_fraction_double_sign: Decimal256::from_str( &String::from_utf8( ParamKind::Bytes - .parse_param(fields.remove(KEY_SLASH_FRACTION_DOUBLE_SIGN).unwrap()) + .parse_param( + fields + .remove(KEY_SLASH_FRACTION_DOUBLE_SIGN) + .unwrap_or_corrupt(), + ) .bytes() - .unwrap(), + .unwrap_or_corrupt(), ) - .unwrap(), + .unwrap_or_corrupt(), ) - .unwrap(), + .unwrap_or_corrupt(), slash_fraction_downtime: Decimal256::from_str( &String::from_utf8( ParamKind::Bytes - .parse_param(fields.remove(KEY_SLASH_FRACTION_DOWNTIME).unwrap()) + .parse_param( + fields + .remove(KEY_SLASH_FRACTION_DOWNTIME) + .unwrap_or_corrupt(), + ) .bytes() - .unwrap(), + .unwrap_or_corrupt(), ) - .unwrap(), + .unwrap_or_corrupt(), ) - .unwrap(), + .unwrap_or_corrupt(), } } } @@ -207,14 +220,14 @@ impl Default for SlashingParams { // TODO: check defaults, especially with division Self { signed_blocks_window: 100, - min_signed_per_window: Decimal256::from_atomics(5u64, 1).unwrap(), + min_signed_per_window: Decimal256::from_atomics(5u64, 1).expect("default is valid"), downtime_jail_duration: 60 * 10 * 1_000_000_000, slash_fraction_double_sign: Decimal256::one() - .checked_div(Decimal256::from_atomics(20u64, 0).unwrap()) - .unwrap(), + .checked_div(Decimal256::from_atomics(20u64, 0).expect("default is valid")) + .expect("default is valid"), slash_fraction_downtime: Decimal256::one() - .checked_div(Decimal256::from_atomics(100u64, 0).unwrap()) - .unwrap(), + .checked_div(Decimal256::from_atomics(100u64, 0).expect("default is valid")) + .expect("default is valid"), } } } diff --git a/x/staking/src/abci_handler.rs b/x/staking/src/abci_handler.rs index 025a43747..3c6961b16 100644 --- a/x/staking/src/abci_handler.rs +++ b/x/staking/src/abci_handler.rs @@ -8,13 +8,14 @@ use crate::{ QueryValidatorsRequest, QueryValidatorsResponse, Redelegation, RedelegationEntryResponse, RedelegationResponse, }; +use gears::extensions::gas::GasResultExt; use gears::{ application::handlers::node::{ABCIHandler, ModuleInfo, TxError}, baseapp::{errors::QueryError, QueryRequest, QueryResponse}, context::{block::BlockContext, init::InitContext, query::QueryContext, tx::TxContext}, core::Protobuf, derive::Query, - ext::Pagination, + extensions::pagination::Pagination, params::ParamsSubspaceKey, store::{database::Database, StoreKey}, tendermint::types::{ @@ -23,7 +24,7 @@ use gears::{ begin_block::RequestBeginBlock, end_block::RequestEndBlock, query::RequestQuery, }, }, - types::{pagination::response::PaginationResponse, store::gas::ext::GasResultExt}, + types::pagination::response::PaginationResponse, x::{ keepers::{ auth::AuthKeeper, @@ -32,6 +33,7 @@ use gears::{ module::Module, }, }; + use serde::Serialize; #[derive(Debug, Clone)] diff --git a/x/staking/src/client/cli/query.rs b/x/staking/src/client/cli/query.rs index c7ec2251f..d57194b86 100644 --- a/x/staking/src/client/cli/query.rs +++ b/x/staking/src/client/cli/query.rs @@ -11,7 +11,7 @@ use gears::{ cli::pagination::CliPaginationRequest, core::Protobuf, derive::Query, - ext::FallibleMapExt, + extensions::try_map::FallibleMapExt, types::{ address::{AccAddress, ValAddress}, pagination::request::PaginationRequest, diff --git a/x/staking/src/client/cli/tx.rs b/x/staking/src/client/cli/tx.rs index 8cb63de16..d50ff49dd 100644 --- a/x/staking/src/client/cli/tx.rs +++ b/x/staking/src/client/cli/tx.rs @@ -43,15 +43,15 @@ pub struct CreateValidatorCli { pub details: String, /// The initial commission rate percentage /* 0.1 */ - #[arg(long, default_value_t = Decimal256::from_atomics(1u64, 1).unwrap())] + #[arg(long, default_value_t = Decimal256::from_atomics(1u64, 1).expect("default is valid"))] pub commission_rate: Decimal256, /// The maximum commission rate percentage /* 0.2 */ - #[arg(long, default_value_t = Decimal256::from_atomics(2u64, 1).unwrap())] + #[arg(long, default_value_t = Decimal256::from_atomics(2u64, 1).expect("default is valid"))] pub commission_max_rate: Decimal256, /// The maximum commission change rate percentage (per day) /* 0.01 */ - #[arg(long, default_value_t = Decimal256::from_atomics(1u64, 2).unwrap())] + #[arg(long, default_value_t = Decimal256::from_atomics(1u64, 2).expect("default is valid"))] pub commission_max_change_rate: Decimal256, /// The minimum self delegation required on the validator #[arg(long, default_value_t = Uint256::one())] diff --git a/x/staking/src/keeper/bonded.rs b/x/staking/src/keeper/bonded.rs index 0462ab03b..860cd31dc 100644 --- a/x/staking/src/keeper/bonded.rs +++ b/x/staking/src/keeper/bonded.rs @@ -23,7 +23,7 @@ impl< denom: params.bond_denom().clone(), amount, }]) - .unwrap(); + .expect("shouldn't fail"); self.bank_keeper .send_coins_from_module_to_module::( diff --git a/x/staking/src/keeper/delegation.rs b/x/staking/src/keeper/delegation.rs index a12f6335a..6508fa7c2 100644 --- a/x/staking/src/keeper/delegation.rs +++ b/x/staking/src/keeper/delegation.rs @@ -2,7 +2,7 @@ use super::*; use anyhow::anyhow; use gears::{ core::Protobuf, - store::database::ext::UnwrapCorrupt, + extensions::corruption::UnwrapCorrupt, types::{base::coins::UnsignedCoins, store::gas::errors::GasStoreErrors}, x::types::validator::BondStatus, }; diff --git a/x/staking/src/keeper/historical_info.rs b/x/staking/src/keeper/historical_info.rs index 34d98b244..076e18ee3 100644 --- a/x/staking/src/keeper/historical_info.rs +++ b/x/staking/src/keeper/historical_info.rs @@ -1,7 +1,7 @@ use super::*; use crate::{historical_info_key, HistoricalInfo}; use gears::core::Protobuf; -use gears::{store::database::ext::UnwrapCorrupt, types::store::gas::ext::GasResultExt}; +use gears::extensions::corruption::UnwrapCorrupt; use prost::bytes::Bytes; impl< diff --git a/x/staking/src/keeper/mod.rs b/x/staking/src/keeper/mod.rs index 9ca7f5b94..87f22bf78 100644 --- a/x/staking/src/keeper/mod.rs +++ b/x/staking/src/keeper/mod.rs @@ -5,6 +5,7 @@ use crate::{ StakingParamsKeeper, UnbondingDelegation, Validator, }; use anyhow::anyhow; +use gears::extensions::gas::GasResultExt; use gears::{ application::keepers::params::ParamsKeeper, context::{ @@ -24,7 +25,7 @@ use gears::{ address::{AccAddress, ValAddress}, base::{coin::UnsignedCoin, coins::UnsignedCoins}, decimal256::Decimal256, - store::gas::{errors::GasStoreErrors, ext::GasResultExt}, + store::gas::errors::GasStoreErrors, uint::Uint256, }, x::{ diff --git a/x/staking/src/keeper/query.rs b/x/staking/src/keeper/query.rs index 9b0de0f90..99f05558c 100644 --- a/x/staking/src/keeper/query.rs +++ b/x/staking/src/keeper/query.rs @@ -10,7 +10,7 @@ use gears::{ baseapp::errors::QueryError, context::query::QueryContext, core::Protobuf, - ext::{IteratorPaginate, Pagination, PaginationResult}, + extensions::pagination::{IteratorPaginate, Pagination, PaginationResult}, types::pagination::response::PaginationResponse, }; @@ -48,7 +48,9 @@ impl< } }); - let pagination = query.pagination.map(gears::ext::Pagination::from); + let pagination = query + .pagination + .map(gears::extensions::pagination::Pagination::from); let (validators, p_result) = if query.status == BondStatus::Unspecified { let (p_result, iterator) = iterator.maybe_paginate(pagination); ( @@ -121,9 +123,11 @@ impl< let store = ctx.kv_store(&self.store_key); let store = store.prefix_store(DELEGATION_KEY); let key = query.delegator_addr.prefix_len_bytes(); - let (p_result, iterator) = store - .into_range(..) - .maybe_paginate(query.pagination.map(gears::ext::Pagination::from)); + let (p_result, iterator) = store.into_range(..).maybe_paginate( + query + .pagination + .map(gears::extensions::pagination::Pagination::from), + ); let delegation_responses = iterator .filter_map(|(k, bytes)| { @@ -162,9 +166,11 @@ impl< let store = ctx.kv_store(&self.store_key); let store = store.prefix_store(UNBONDING_DELEGATION_KEY); let key = query.delegator_addr.prefix_len_bytes(); - let (p_result, iterator) = store - .into_range(..) - .maybe_paginate(query.pagination.map(gears::ext::Pagination::from)); + let (p_result, iterator) = store.into_range(..).maybe_paginate( + query + .pagination + .map(gears::extensions::pagination::Pagination::from), + ); let mut unbonding_responses = vec![]; for (k, bytes) in iterator { diff --git a/x/staking/src/keeper/redelegation.rs b/x/staking/src/keeper/redelegation.rs index f7fef6a17..15af78b9e 100644 --- a/x/staking/src/keeper/redelegation.rs +++ b/x/staking/src/keeper/redelegation.rs @@ -3,11 +3,9 @@ use crate::types::keys; use crate::{ length_prefixed_val_del_addrs_key, redelegation_time_key, DvvTriplets, RedelegationEntry, }; +use gears::context::{InfallibleContext, InfallibleContextMut}; use gears::core::Protobuf; -use gears::{ - context::{InfallibleContext, InfallibleContextMut}, - store::database::ext::UnwrapCorrupt, -}; +use gears::extensions::corruption::UnwrapCorrupt; use prost::bytes::Bytes; impl< diff --git a/x/staking/src/keeper/store_iter.rs b/x/staking/src/keeper/store_iter.rs index a2ad36e8f..97a6cea27 100644 --- a/x/staking/src/keeper/store_iter.rs +++ b/x/staking/src/keeper/store_iter.rs @@ -1,6 +1,7 @@ use super::Database; use gears::{ - store::database::{ext::UnwrapCorrupt, prefix::PrefixDB}, + extensions::corruption::UnwrapCorrupt, + store::database::prefix::PrefixDB, types::{ address::ValAddress, store::{gas::errors::GasStoreErrors, kv::Store, range::StoreRange}, diff --git a/x/staking/src/keeper/tx.rs b/x/staking/src/keeper/tx.rs index 9a44bf679..fe39e0bc2 100644 --- a/x/staking/src/keeper/tx.rs +++ b/x/staking/src/keeper/tx.rs @@ -3,7 +3,7 @@ use crate::{ Commission, CreateValidator, DelegateMsg, EditValidator, RedelegateMsg, UndelegateMsg, }; use gears::{ - baseapp::ValidatorParams, context::tx::TxContext, store::database::ext::UnwrapCorrupt, + baseapp::ValidatorParams, context::tx::TxContext, extensions::corruption::UnwrapCorrupt, types::address::ConsAddress, }; diff --git a/x/staking/src/keeper/unbonding.rs b/x/staking/src/keeper/unbonding.rs index e11a301aa..870cc17a9 100644 --- a/x/staking/src/keeper/unbonding.rs +++ b/x/staking/src/keeper/unbonding.rs @@ -7,7 +7,7 @@ use crate::{ use gears::{ context::{InfallibleContext, InfallibleContextMut}, core::Protobuf, - store::database::ext::UnwrapCorrupt, + extensions::corruption::UnwrapCorrupt, tendermint::types::time::timestamp::Timestamp, }; use prost::bytes::Bytes; diff --git a/x/staking/src/keeper/validator.rs b/x/staking/src/keeper/validator.rs index 831e8c527..d8a4a2219 100644 --- a/x/staking/src/keeper/validator.rs +++ b/x/staking/src/keeper/validator.rs @@ -1,6 +1,6 @@ use super::*; use crate::{Commission, CommissionRates, Validator}; -use gears::{core::Protobuf, store::database::ext::UnwrapCorrupt, types::address::ConsAddress}; +use gears::{core::Protobuf, extensions::corruption::UnwrapCorrupt, types::address::ConsAddress}; impl< SK: StoreKey, diff --git a/x/staking/src/keeper/validators_and_total_power.rs b/x/staking/src/keeper/validators_and_total_power.rs index 1584e4a4d..aab7884c7 100644 --- a/x/staking/src/keeper/validators_and_total_power.rs +++ b/x/staking/src/keeper/validators_and_total_power.rs @@ -1,6 +1,6 @@ use super::*; use gears::{ - context::InfallibleContext, core::Protobuf, store::database::ext::UnwrapCorrupt, + context::InfallibleContext, core::Protobuf, extensions::corruption::UnwrapCorrupt, types::base::coin::Uint256Proto, }; use prost::{bytes::Bytes, Message}; diff --git a/x/staking/src/params.rs b/x/staking/src/params.rs index bb98da267..2429ed3fd 100644 --- a/x/staking/src/params.rs +++ b/x/staking/src/params.rs @@ -1,6 +1,7 @@ use anyhow::anyhow; use gears::{ application::keepers::params::ParamsKeeper, + extensions::corruption::UnwrapCorrupt, params::{ParamKind, ParamsDeserialize, ParamsSerialize, ParamsSubspaceKey}, tendermint::types::time::duration::Duration, types::denom::Denom, @@ -164,31 +165,33 @@ impl ParamsSerialize for StakingParams { impl ParamsDeserialize for StakingParams { fn from_raw(mut fields: HashMap<&'static str, Vec>) -> Self { let unbonding_time = ParamKind::I64 - .parse_param(fields.remove(KEY_UNBONDING_TIME).unwrap()) + .parse_param(fields.remove(KEY_UNBONDING_TIME).unwrap_or_corrupt()) .signed_64() .expect("param serialized as i64 should be deserialized without errors"); - let max_validators = String::from_utf8(fields.remove(KEY_MAX_VALIDATORS).unwrap()) - .expect("should be valid utf-8") - .parse::() - .expect("should be valid u32"); - let max_entries = String::from_utf8(fields.remove(KEY_MAX_ENTRIES).unwrap()) - .expect("should be valid utf-8") - .parse::() - .expect("should be valid u32"); - let historical_entries = String::from_utf8(fields.remove(KEY_HISTORICAL_ENTRIES).unwrap()) + let max_validators = + String::from_utf8(fields.remove(KEY_MAX_VALIDATORS).unwrap_or_corrupt()) + .expect("should be valid utf-8") + .parse::() + .expect("should be valid u32"); + let max_entries = String::from_utf8(fields.remove(KEY_MAX_ENTRIES).unwrap_or_corrupt()) .expect("should be valid utf-8") .parse::() .expect("should be valid u32"); + let historical_entries = + String::from_utf8(fields.remove(KEY_HISTORICAL_ENTRIES).unwrap_or_corrupt()) + .expect("should be valid utf-8") + .parse::() + .expect("should be valid u32"); let bond_denom = ParamKind::String - .parse_param(fields.remove(KEY_BOND_DENOM).unwrap()) + .parse_param(fields.remove(KEY_BOND_DENOM).unwrap_or_corrupt()) .string() .expect("param serialized as string should be deserialized without errors") .strip_prefix('\"') - .unwrap() + .unwrap_or_corrupt() .strip_suffix('\"') - .unwrap() + .unwrap_or_corrupt() .try_into() - .unwrap(); + .unwrap_or_corrupt(); // TODO: should we validate the params here? diff --git a/x/staking/src/types/delegations.rs b/x/staking/src/types/delegations.rs index 86f539572..974880503 100644 --- a/x/staking/src/types/delegations.rs +++ b/x/staking/src/types/delegations.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use gears::{ core::{errors::CoreError, Protobuf}, - ext::PaginationKey, + extensions::pagination::PaginationKey, tendermint::types::time::timestamp::Timestamp, types::{ address::{AccAddress, ValAddress}, diff --git a/x/staking/src/types/keys.rs b/x/staking/src/types/keys.rs index 4646e9dc3..038619ec3 100644 --- a/x/staking/src/types/keys.rs +++ b/x/staking/src/types/keys.rs @@ -125,18 +125,20 @@ pub fn get_unbonding_delegation_time_key(timestamp: Timestamp) -> Vec { #[cfg(test)] mod tests { + use gears::extensions::testing::UnwrapTesting; + use super::*; #[test] fn test_redelegation_key() { let del_addr = - AccAddress::from_bech32("cosmos15qzm75pjh0jqsv3u40hzp2vzs2hdp47fkz7j5q").unwrap(); + AccAddress::from_bech32("cosmos15qzm75pjh0jqsv3u40hzp2vzs2hdp47fkz7j5q").unwrap_test(); let val_src_addr = ValAddress::from_bech32("cosmosvaloper1syavy2npfyt9tcncdtsdzf7kny9lh777yfrfs4") - .unwrap(); + .unwrap_test(); let val_dst_addr = ValAddress::from_bech32("cosmosvaloper1syavy2npfyt9tcncdtsdzf7kny9lh777yfrfs4") - .unwrap(); + .unwrap_test(); let key = redelegation_key(&del_addr, &val_src_addr, &val_dst_addr); assert_eq!( @@ -153,7 +155,7 @@ mod tests { #[test] fn test_redelegations_key() { let del_addr = - AccAddress::from_bech32("cosmos15qzm75pjh0jqsv3u40hzp2vzs2hdp47fkz7j5q").unwrap(); + AccAddress::from_bech32("cosmos15qzm75pjh0jqsv3u40hzp2vzs2hdp47fkz7j5q").unwrap_test(); let key = redelegations_key(&del_addr); assert_eq!( @@ -168,13 +170,13 @@ mod tests { #[test] fn test_redelegation_by_val_src_index_key() { let del_addr = - AccAddress::from_bech32("cosmos15qzm75pjh0jqsv3u40hzp2vzs2hdp47fkz7j5q").unwrap(); + AccAddress::from_bech32("cosmos15qzm75pjh0jqsv3u40hzp2vzs2hdp47fkz7j5q").unwrap_test(); let val_src_addr = ValAddress::from_bech32("cosmosvaloper1syavy2npfyt9tcncdtsdzf7kny9lh777yfrfs4") - .unwrap(); + .unwrap_test(); let val_dst_addr = ValAddress::from_bech32("cosmosvaloper1syavy2npfyt9tcncdtsdzf7kny9lh777yfrfs4") - .unwrap(); + .unwrap_test(); let key = redelegation_by_val_src_index_key(&del_addr, &val_src_addr, &val_dst_addr); assert_eq!( @@ -192,7 +194,7 @@ mod tests { fn test_redelegations_from_val_src_index_key() { let val_src_addr = ValAddress::from_bech32("cosmosvaloper1syavy2npfyt9tcncdtsdzf7kny9lh777yfrfs4") - .unwrap(); + .unwrap_test(); let key = redelegations_from_val_src_index_key(&val_src_addr); assert_eq!( @@ -207,13 +209,13 @@ mod tests { #[test] fn test_redelegation_by_val_dst_index_key() { let del_addr = - AccAddress::from_bech32("cosmos15qzm75pjh0jqsv3u40hzp2vzs2hdp47fkz7j5q").unwrap(); + AccAddress::from_bech32("cosmos15qzm75pjh0jqsv3u40hzp2vzs2hdp47fkz7j5q").unwrap_test(); let val_src_addr = ValAddress::from_bech32("cosmosvaloper1syavy2npfyt9tcncdtsdzf7kny9lh777yfrfs4") - .unwrap(); + .unwrap_test(); let val_dst_addr = ValAddress::from_bech32("cosmosvaloper1syavy2npfyt9tcncdtsdzf7kny9lh777yfrfs4") - .unwrap(); + .unwrap_test(); let key = redelegation_by_val_dst_index_key(&del_addr, &val_src_addr, &val_dst_addr); assert_eq!( @@ -231,7 +233,7 @@ mod tests { fn test_redelegations_by_val_dst_index_key() { let val_dst_addr = ValAddress::from_bech32("cosmosvaloper1syavy2npfyt9tcncdtsdzf7kny9lh777yfrfs4") - .unwrap(); + .unwrap_test(); let key = redelegations_by_val_dst_index_key(&val_dst_addr); assert_eq!( diff --git a/x/staking/src/types/validator.rs b/x/staking/src/types/validator.rs index 56df3f53a..69345ba59 100644 --- a/x/staking/src/types/validator.rs +++ b/x/staking/src/types/validator.rs @@ -741,6 +741,7 @@ pub enum ValidatorsError { #[cfg(test)] mod tests { use data_encoding::HEXLOWER; + use gears::extensions::testing::UnwrapTesting; use super::*; @@ -776,7 +777,7 @@ mod tests { "unbonding_time": "1970-01-01T00:00:00Z" }"#; - let val: Validator = serde_json::from_str(val_raw).unwrap(); + let val: Validator = serde_json::from_str(val_raw).unwrap_test(); let val_proto = val.encode_vec(); assert_eq!( @@ -833,7 +834,7 @@ mod tests { } "#; - let val: Validator = serde_json::from_str(val_raw).unwrap(); + let val: Validator = serde_json::from_str(val_raw).unwrap_test(); let res = HEXLOWER.encode(&val.key_by_power_index_key(1000000)); let expected = "230000010000000000149c288ede7df62742fc3b7d0962045a8cef0f79f6"; @@ -875,7 +876,7 @@ mod tests { } "#; - let val: Validator = serde_json::from_str(val_raw).unwrap(); + let val: Validator = serde_json::from_str(val_raw).unwrap_test(); let res = val.tokens_to_consensus_power(1000000); assert_eq!(res, 1099511627776); }