From dc3b43a4f9e8015897b8a896b9cddd6a56ed8ae0 Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Mon, 22 Jan 2024 06:08:32 -0800 Subject: [PATCH] imp: remove `ibc` from `basecoin-store` (#149) * imp: decouple basecoin-store from ibc * nit * fix: remove infallable path tests * fix: remove redundant deps * perform clippy suggestion * impl Debug for NullCodec * add minimal unit tests --------- Co-authored-by: Ranadeep Biswas --- Cargo.lock | 117 ---------------- Cargo.toml | 2 +- crates/app/src/abci/v0_37/impls.rs | 2 +- crates/app/src/modules/auth/account.rs | 2 +- crates/app/src/modules/bank/util.rs | 2 +- crates/app/src/modules/gov/path.rs | 2 +- crates/app/src/modules/ibc/client_contexts.rs | 8 +- crates/app/src/modules/ibc/impls.rs | 30 +--- crates/app/src/modules/ibc/router.rs | 2 +- crates/app/src/modules/upgrade/impls.rs | 5 +- crates/app/src/modules/upgrade/path.rs | 2 +- crates/store/Cargo.toml | 42 +++--- crates/store/src/types/mod.rs | 2 +- crates/store/src/types/path.rs | 129 +++--------------- crates/store/src/types/store.rs | 19 +-- crates/store/src/utils/codec.rs | 33 ++--- crates/store/src/utils/macros.rs | 32 ----- crates/store/src/utils/mod.rs | 3 +- 18 files changed, 83 insertions(+), 351 deletions(-) delete mode 100644 crates/store/src/utils/macros.rs diff --git a/Cargo.lock b/Cargo.lock index b22b2a2e..708044d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -232,17 +232,9 @@ dependencies = [ name = "basecoin-store" version = "0.1.0" dependencies = [ - "base64 0.21.5", - "bytes", - "derive_more", "displaydoc", - "ed25519", - "ibc", "ics23", - "lazy_static", - "proptest", "prost", - "rand", "serde", "serde_json", "sha2 0.10.8", @@ -266,21 +258,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "bit-set" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - [[package]] name = "bitflags" version = "1.3.2" @@ -700,12 +677,6 @@ dependencies = [ "once_cell", ] -[[package]] -name = "fastrand" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" - [[package]] name = "ff" version = "0.13.0" @@ -1592,12 +1563,6 @@ version = "0.2.151" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" -[[package]] -name = "libm" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" - [[package]] name = "linux-raw-sys" version = "0.4.12" @@ -1686,7 +1651,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" dependencies = [ "autocfg", - "libm", ] [[package]] @@ -1868,26 +1832,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "proptest" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31b476131c3c86cb68032fdc5cb6d5a1045e3e42d96b69fa599fd77701e1f5bf" -dependencies = [ - "bit-set", - "bit-vec", - "bitflags 2.4.1", - "lazy_static", - "num-traits", - "rand", - "rand_chacha", - "rand_xorshift", - "regex-syntax", - "rusty-fork", - "tempfile", - "unarray", -] - [[package]] name = "prost" version = "0.12.3" @@ -1920,12 +1864,6 @@ dependencies = [ "prost", ] -[[package]] -name = "quick-error" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" - [[package]] name = "quote" version = "1.0.33" @@ -1965,15 +1903,6 @@ dependencies = [ "getrandom", ] -[[package]] -name = "rand_xorshift" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d25bf25ec5ae4a3f1b92f929810509a2f53d7dca2f50b794ff57e3face536c8f" -dependencies = [ - "rand_core", -] - [[package]] name = "redox_syscall" version = "0.4.1" @@ -1983,12 +1912,6 @@ dependencies = [ "bitflags 1.3.2", ] -[[package]] -name = "regex-syntax" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" - [[package]] name = "reqwest" version = "0.11.22" @@ -2130,18 +2053,6 @@ version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" -[[package]] -name = "rusty-fork" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb3dcc6e454c328bb824492db107ab7c0ae8fcffe4ad210136ef014458c1bc4f" -dependencies = [ - "fnv", - "quick-error", - "tempfile", - "wait-timeout", -] - [[package]] name = "ryu" version = "1.0.16" @@ -2501,19 +2412,6 @@ dependencies = [ "libc", ] -[[package]] -name = "tempfile" -version = "3.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef1adac450ad7f4b3c28589471ade84f25f731a7a0fe30d71dfa9f60fd808e5" -dependencies = [ - "cfg-if", - "fastrand", - "redox_syscall", - "rustix", - "windows-sys 0.48.0", -] - [[package]] name = "tendermint" version = "0.34.0" @@ -3024,12 +2922,6 @@ dependencies = [ "static_assertions", ] -[[package]] -name = "unarray" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" - [[package]] name = "unicode-bidi" version = "0.3.14" @@ -3092,15 +2984,6 @@ version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" -[[package]] -name = "wait-timeout" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6" -dependencies = [ - "libc", -] - [[package]] name = "walkdir" version = "2.4.0" diff --git a/Cargo.toml b/Cargo.toml index 31bffc82..75ea7bc5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ base64 = { version = "0.21", default-features = false, features = ["alloc"] } displaydoc = { version = "0.2", default-features = false } derive_more = { version = "0.99.17", default-features = false, features = ["from", "into", "display"] } ed25519 = { version = "2.1.0", default-features = false } -ibc = { version = "0.49.1", default-features = false } +ibc = { version = "0.49.1", default-features = false, features = ["serde"] } ibc-query = { version = "0.49.1", default-features = false } ibc-proto = { version = "0.39.1", default-features = false } ics23 = { version = "0.11", default-features = false } diff --git a/crates/app/src/abci/v0_37/impls.rs b/crates/app/src/abci/v0_37/impls.rs index 6e762918..f86a6a7a 100644 --- a/crates/app/src/abci/v0_37/impls.rs +++ b/crates/app/src/abci/v0_37/impls.rs @@ -121,7 +121,7 @@ pub fn query( ) -> ResponseQuery { debug!("Got query request: {:?}", request); - let path: Option = request.path.try_into().ok(); + let path: Option = Some(request.path.into()); let modules = app.modules.read_access(); let height = Height::from(request.height as u64); for IdentifiedModule { id, module } in modules.iter() { diff --git a/crates/app/src/modules/auth/account.rs b/crates/app/src/modules/auth/account.rs index fe278c03..74a45e8b 100644 --- a/crates/app/src/modules/auth/account.rs +++ b/crates/app/src/modules/auth/account.rs @@ -12,7 +12,7 @@ use std::convert::{TryFrom, TryInto}; pub const RELAYER_ACCOUNT: &str = "cosmos12xpmzmfpf7tn57xg93rne2hc2q26lcfql5efws"; pub const ACCOUNT_PREFIX: &str = "cosmos"; -#[derive(Clone)] +#[derive(Clone, derive_more::Display)] pub struct AccountsPath(pub AccountId); impl From for Path { diff --git a/crates/app/src/modules/bank/util.rs b/crates/app/src/modules/bank/util.rs index 785f3898..39b946d8 100644 --- a/crates/app/src/modules/bank/util.rs +++ b/crates/app/src/modules/bank/util.rs @@ -72,7 +72,7 @@ impl From<&MsgCoin> for Coin { #[serde(transparent)] pub struct Balances(pub Vec); -#[derive(Clone, Debug)] +#[derive(Clone, Debug, derive_more::Display)] pub(super) struct BalancesPath(pub AccountId); impl From for Path { diff --git a/crates/app/src/modules/gov/path.rs b/crates/app/src/modules/gov/path.rs index cc2c30ab..186a2851 100644 --- a/crates/app/src/modules/gov/path.rs +++ b/crates/app/src/modules/gov/path.rs @@ -23,6 +23,6 @@ impl ProposalPath { impl From for Path { fn from(value: ProposalPath) -> Self { - Self::try_from(value.to_string()).unwrap() + Self::from(value.to_string()) } } diff --git a/crates/app/src/modules/ibc/client_contexts.rs b/crates/app/src/modules/ibc/client_contexts.rs index 39d55baf..669d4989 100644 --- a/crates/app/src/modules/ibc/client_contexts.rs +++ b/crates/app/src/modules/ibc/client_contexts.rs @@ -1,8 +1,6 @@ use super::impls::{AnyConsensusState, IbcContext}; - use basecoin_store::context::Store; use basecoin_store::types::Height; - use ibc::clients::tendermint::client_state::ClientState as TmClientState; use ibc::clients::tendermint::consensus_state::ConsensusState as TmConsensusState; use ibc::clients::tendermint::context::{CommonContext, ValidationContext as TmValidationContext}; @@ -224,7 +222,7 @@ where let keys = self.store.get_keys(&path); let found_path = keys.into_iter().find_map(|path| { - if let Ok(Path::ClientConsensusState(path)) = Path::try_from(path) { + if let Ok(Path::ClientConsensusState(path)) = path.try_into() { if height > &IbcHeight::new(path.revision_number, path.revision_height).unwrap() { return Some(path); } @@ -258,7 +256,7 @@ where let keys = self.store.get_keys(&path); let pos = keys.iter().position(|path| { - if let Ok(Path::ClientConsensusState(path)) = Path::try_from(path.clone()) { + if let Ok(Path::ClientConsensusState(path)) = path.clone().try_into() { height >= &IbcHeight::new(path.revision_number, path.revision_height).unwrap() } else { false @@ -267,7 +265,7 @@ where if let Some(pos) = pos { if pos > 0 { - let prev_path = match Path::try_from(keys[pos - 1].clone()) { + let prev_path = match keys[pos - 1].clone().try_into() { Ok(Path::ClientConsensusState(p)) => p, _ => unreachable!(), // safety - path retrieved from store }; diff --git a/crates/app/src/modules/ibc/impls.rs b/crates/app/src/modules/ibc/impls.rs index c3f627b8..2296e136 100644 --- a/crates/app/src/modules/ibc/impls.rs +++ b/crates/app/src/modules/ibc/impls.rs @@ -229,12 +229,9 @@ where .map_err(|_| AppError::Custom { reason: "Invalid domain path".to_string(), })? - .try_into() - .map_err(|_| AppError::Custom { - reason: "Invalid IBC path".to_string(), - })?; + .into(); - let _ = IbcPath::try_from(path.clone()).map_err(|_| AppError::Custom { + let _: IbcPath = path.clone().try_into().map_err(|_| AppError::Custom { reason: "Invalid IBC path".to_string(), })?; @@ -612,7 +609,7 @@ where /// Returns the proof for the given [`IbcHeight`] and [`Path`] fn get_proof(&self, height: IbcHeight, path: &IbcPath) -> Option> { self.store - .get_proof(height.revision_height().into(), &path.clone().into()) + .get_proof(height.revision_height().into(), &path.to_string().into()) .map(|p| p.encode_to_vec()) } } @@ -624,12 +621,7 @@ where { /// Returns the list of all client states. fn client_states(&self) -> Result, ContextError> { - let path = "clients" - .to_owned() - .try_into() - .map_err(|_| ClientError::Other { - description: "Invalid client state path: clients".into(), - })?; + let path = "clients".to_owned().into(); self.client_state_store .get_keys(&path) @@ -725,12 +717,7 @@ where /// Connections queries all the IBC connections of a chain. fn connection_ends(&self) -> Result, ContextError> { - let path = "connections" - .to_owned() - .try_into() - .map_err(|_| ConnectionError::Other { - description: "Invalid connection path: connections".into(), - })?; + let path = "connections".to_owned().into(); self.connection_end_store .get_keys(&path) @@ -772,12 +759,7 @@ where /// Channels queries all the IBC channels of a chain. fn channel_ends(&self) -> Result, ContextError> { - let path = "channelEnds" - .to_owned() - .try_into() - .map_err(|_| ChannelError::Other { - description: "Invalid channel path: channels".into(), - })?; + let path = "channelEnds".to_owned().into(); self.channel_end_store .get_keys(&path) diff --git a/crates/app/src/modules/ibc/router.rs b/crates/app/src/modules/ibc/router.rs index dbe5800a..ef1015fa 100644 --- a/crates/app/src/modules/ibc/router.rs +++ b/crates/app/src/modules/ibc/router.rs @@ -67,7 +67,7 @@ where .ok_or(RouterError::UnknownPort { port_id: port_id.clone(), }) - .map(Clone::clone) + .cloned() .ok() } } diff --git a/crates/app/src/modules/upgrade/impls.rs b/crates/app/src/modules/upgrade/impls.rs index de3f647b..943aede4 100644 --- a/crates/app/src/modules/upgrade/impls.rs +++ b/crates/app/src/modules/upgrade/impls.rs @@ -94,10 +94,7 @@ where .map_err(|_| AppError::Custom { reason: "Invalid path".to_string(), })? - .try_into() - .map_err(|_| AppError::Custom { - reason: "Failed to parse path".to_string(), - })?; + .into(); debug!( "Querying for path ({}) at height {:?}", diff --git a/crates/app/src/modules/upgrade/path.rs b/crates/app/src/modules/upgrade/path.rs index 2fa334fb..0b2c4ca0 100644 --- a/crates/app/src/modules/upgrade/path.rs +++ b/crates/app/src/modules/upgrade/path.rs @@ -30,6 +30,6 @@ impl UpgradePlanPath { impl From for Path { fn from(value: UpgradePlanPath) -> Self { - Self::try_from(value.to_string()).unwrap() + Self::from(value.to_string()) } } diff --git a/crates/store/Cargo.toml b/crates/store/Cargo.toml index 6c05ecec..11d65ab0 100644 --- a/crates/store/Cargo.toml +++ b/crates/store/Cargo.toml @@ -1,32 +1,22 @@ [package] -name = "basecoin-store" -version = "0.1.0" -edition = "2021" -license = "Apache-2.0" -readme = "README.md" -categories = ["cryptography::cryptocurrencies", "iavl"] -repository = "https://github.com/informalsystems/basecoin-rs" -authors = ["Informal Systems "] +name = "basecoin-store" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +readme = "README.md" +categories = ["cryptography::cryptocurrencies", "iavl"] +repository = "https://github.com/informalsystems/basecoin-rs" +authors = ["Informal Systems "] description = """ A simple implementation of an AVL store tailored for the basecoin application. """ [dependencies] -base64 = { workspace = true } -displaydoc = { workspace = true } -derive_more = { workspace = true } -ed25519 = { workspace = true } -ibc = { workspace = true, features = ["serde"] } -ics23 = { workspace = true } -prost = { workspace = true } -serde = { workspace = true } -serde_json = { workspace = true } -sha2 = { workspace = true } -tendermint = { workspace = true } -tracing = { workspace = true } - -[dev-dependencies] -bytes = "1.0.1" -lazy_static = "1.4.0" -proptest = "*" -rand = "*" +displaydoc = { workspace = true } +ics23 = { workspace = true, features = ["host-functions"] } +prost = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +sha2 = { workspace = true } +tendermint = { workspace = true } +tracing = { workspace = true } diff --git a/crates/store/src/types/mod.rs b/crates/store/src/types/mod.rs index 3f5c9ce2..14136420 100644 --- a/crates/store/src/types/mod.rs +++ b/crates/store/src/types/mod.rs @@ -5,5 +5,5 @@ pub mod store; pub use height::{Height, RawHeight}; pub use identifier::Identifier; -pub use path::Path; +pub use path::*; pub use store::{BinStore, JsonStore, MainStore, ProtobufStore, State, TypedSet, TypedStore}; diff --git a/crates/store/src/types/path.rs b/crates/store/src/types/path.rs index 316b250e..8c73e225 100644 --- a/crates/store/src/types/path.rs +++ b/crates/store/src/types/path.rs @@ -1,10 +1,8 @@ use super::Identifier; use crate::avl::{AsBytes, ByteSlice}; use displaydoc::Display as DisplayDoc; -use ibc::core::host::types::path::{Path as IbcPath, PathError}; use std::fmt::{Display, Formatter}; -use std::str::FromStr; -use std::str::{from_utf8, Utf8Error}; +use std::str::{from_utf8, FromStr, Utf8Error}; #[derive(Debug, DisplayDoc)] pub enum Error { @@ -23,18 +21,23 @@ impl Path { pub fn get(&self, index: usize) -> Option<&Identifier> { self.0.get(index) } -} -impl TryFrom for Path { - type Error = Error; + pub fn try_into(self) -> Result + where + K: FromStr, + { + K::from_str(self.to_string().as_str()) + } +} - fn try_from(s: String) -> Result { +impl From for Path { + fn from(s: String) -> Self { let mut identifiers = vec![]; let parts = s.split('/'); // split will never return an empty iterator for part in parts { identifiers.push(Identifier::from(part.to_owned())); } - Ok(Self(identifiers)) + Self(identifiers) } } @@ -43,7 +46,7 @@ impl TryFrom<&[u8]> for Path { fn try_from(value: &[u8]) -> Result { let s = from_utf8(value).map_err(|e| Error::MalformedPathString { error: e })?; - s.to_owned().try_into() + Ok(s.to_owned().into()) } } @@ -73,111 +76,19 @@ impl AsBytes for Path { } } -impl TryFrom for IbcPath { - type Error = PathError; - - fn try_from(path: Path) -> Result { - Self::from_str(path.to_string().as_str()) - } -} - -impl From for Path { - fn from(ibc_path: IbcPath) -> Self { - Self::try_from(ibc_path.to_string()).unwrap() // safety - `IbcPath`s are correct-by-construction - } -} - #[cfg(test)] mod tests { use super::*; - use std::{collections::HashSet, convert::TryFrom}; - - use lazy_static::lazy_static; - use proptest::prelude::*; - use rand::{distributions::Standard, seq::SliceRandom}; - - const ALLOWED_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ - abcdefghijklmnopqrstuvwxyz\ - ._+-#[]<>"; - - lazy_static! { - static ref VALID_CHARS: HashSet = { - ALLOWED_CHARS - .iter() - .map(|c| char::from(*c)) - .collect::>() - }; - } - fn gen_valid_identifier(len: usize) -> String { - let mut rng = rand::thread_rng(); - - (0..=len) - .map(|_| { - let idx = rng.gen_range(0..ALLOWED_CHARS.len()); - ALLOWED_CHARS[idx] as char - }) - .collect::() - } - - fn gen_invalid_identifier(len: usize) -> String { - let mut rng = rand::thread_rng(); - - (0..=len) - .map(|_| loop { - let c = rng.sample::(Standard); - - if c.is_ascii() && !VALID_CHARS.contains(&c) { - return c; - } - }) - .collect::() + #[test] + fn happy_test() { + let bytes: &[u8] = b"hello/world"; + assert!(Path::try_from(bytes).is_ok()); } - proptest! { - #[test] - fn path_with_valid_parts_is_valid(n_parts in 1usize..=10) { - let mut rng = rand::thread_rng(); - - let parts = (0..n_parts) - .map(|_| { - let len = rng.gen_range(1usize..=10); - gen_valid_identifier(len) - }) - .collect::>(); - - let path = parts.join("/"); - - assert!(Path::try_from(path).is_ok()); - } - - #[test] - #[ignore] - fn path_with_invalid_parts_is_invalid(n_parts in 1usize..=10) { - let mut rng = rand::thread_rng(); - let n_invalid_parts = rng.gen_range(1usize..=n_parts); - let n_valid_parts = n_parts - n_invalid_parts; - - let mut parts = (0..n_invalid_parts) - .map(|_| { - let len = rng.gen_range(1usize..=10); - gen_invalid_identifier(len) - }) - .collect::>(); - - let mut valid_parts = (0..n_valid_parts) - .map(|_| { - let len = rng.gen_range(1usize..=10); - gen_valid_identifier(len) - }) - .collect::>(); - - parts.append(&mut valid_parts); - parts.shuffle(&mut rng); - - let path = parts.join("/"); - - assert!(Path::try_from(path).is_err()); - } + #[test] + fn sad_test() { + let bytes: &[u8] = b"hello/\xf0\x28\x8c\xbc"; + assert!(Path::try_from(bytes).is_err()); } } diff --git a/crates/store/src/types/store.rs b/crates/store/src/types/store.rs index 44187f77..79635c7c 100644 --- a/crates/store/src/types/store.rs +++ b/crates/store/src/types/store.rs @@ -34,8 +34,8 @@ pub struct TypedStore { impl TypedStore where S: Store, - C: Codec, - K: Into + Clone, + C: Codec, + K: ToString, { #[inline] pub fn new(store: S) -> Self { @@ -49,19 +49,22 @@ where #[inline] pub fn set(&mut self, path: K, value: V) -> Result, S::Error> { self.store - .set(path.into(), C::encode(&value).unwrap().as_ref().to_vec()) + .set( + path.to_string().into(), + C::encode(&value).unwrap().as_ref().to_vec(), + ) .map(|prev_val| prev_val.and_then(|v| C::decode(&v))) } #[inline] pub fn delete(&mut self, path: K) { - self.store.delete(&path.into()) + self.store.delete(&path.to_string().into()) } #[inline] pub fn get(&self, height: Height, path: &K) -> Option { self.store - .get(height, &path.clone().into()) + .get(height, &path.to_string().into()) .and_then(|v| C::decode(&v)) } @@ -79,17 +82,17 @@ where impl TypedStore where S: Store, - K: Into + Clone, + K: ToString, { #[inline] pub fn set_path(&mut self, path: K) -> Result<(), S::Error> { self.store - .set(path.into(), NullCodec::encode(&()).unwrap()) + .set(path.to_string().into(), NullCodec::encode(&()).unwrap()) .map(|_| ()) } #[inline] pub fn is_path_set(&self, height: Height, path: &K) -> bool { - self.store.get(height, &path.clone().into()).is_some() + self.store.get(height, &path.to_string().into()).is_some() } } diff --git a/crates/store/src/utils/codec.rs b/crates/store/src/utils/codec.rs index c4ff7d14..38626319 100644 --- a/crates/store/src/utils/codec.rs +++ b/crates/store/src/utils/codec.rs @@ -3,12 +3,13 @@ use std::marker::PhantomData; /// A trait that defines how types are decoded/encoded. pub trait Codec { - type Type; + type Value; + type Encoded: AsRef<[u8]>; - fn encode(d: &Self::Type) -> Option; + fn encode(d: &Self::Value) -> Option; - fn decode(bytes: &[u8]) -> Option; + fn decode(bytes: &[u8]) -> Option; } /// A JSON codec that uses `serde_json` to encode/decode as a JSON string @@ -19,14 +20,14 @@ impl Codec for JsonCodec where T: Serialize + DeserializeOwned, { - type Type = T; + type Value = T; type Encoded = String; - fn encode(d: &Self::Type) -> Option { + fn encode(d: &Self::Value) -> Option { serde_json::to_string(d).ok() } - fn decode(bytes: &[u8]) -> Option { + fn decode(bytes: &[u8]) -> Option { let json_string = String::from_utf8(bytes.to_vec()).ok()?; serde_json::from_str(&json_string).ok() } @@ -34,19 +35,19 @@ where /// A Null codec that can be used for paths that are only meant to be set/reset and do not hold any /// typed value. -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct NullCodec; impl Codec for NullCodec { - type Type = (); + type Value = (); type Encoded = Vec; - fn encode(_d: &Self::Type) -> Option { + fn encode(_d: &Self::Value) -> Option { // using [0x00] to represent null Some(vec![0x00]) } - fn decode(bytes: &[u8]) -> Option { + fn decode(bytes: &[u8]) -> Option { match bytes { // the encoded bytes must be [0x00] [0x00] => Some(()), @@ -67,15 +68,15 @@ where T: Into + Clone, R: TryInto + Default + prost::Message, { - type Type = T; + type Value = T; type Encoded = Vec; - fn encode(d: &Self::Type) -> Option { + fn encode(d: &Self::Value) -> Option { let r = d.clone().into(); Some(r.encode_to_vec()) } - fn decode(bytes: &[u8]) -> Option { + fn decode(bytes: &[u8]) -> Option { let r = R::decode(bytes).ok()?; r.try_into().ok() } @@ -89,14 +90,14 @@ impl Codec for BinCodec where T: AsRef<[u8]> + From>, { - type Type = T; + type Value = T; type Encoded = Vec; - fn encode(d: &Self::Type) -> Option { + fn encode(d: &Self::Value) -> Option { Some(d.as_ref().to_vec()) } - fn decode(bytes: &[u8]) -> Option { + fn decode(bytes: &[u8]) -> Option { Some(bytes.to_vec().into()) } } diff --git a/crates/store/src/utils/macros.rs b/crates/store/src/utils/macros.rs deleted file mode 100644 index a614aaf9..00000000 --- a/crates/store/src/utils/macros.rs +++ /dev/null @@ -1,32 +0,0 @@ -use crate::types::Path; - -use ibc::core::host::types::path::{ - AckPath, ChannelEndPath, ClientConnectionPath, ClientConsensusStatePath, ClientStatePath, - CommitmentPath, ConnectionPath, ReceiptPath, SeqAckPath, SeqRecvPath, SeqSendPath, - UpgradeClientPath, -}; - -macro_rules! impl_into_path_for { - ($($path:ty),+) => { - $(impl From<$path> for Path { - fn from(ibc_path: $path) -> Self { - Self::try_from(ibc_path.to_string()).unwrap() // safety - `IbcPath`s are correct-by-construction - } - })+ - }; -} - -impl_into_path_for!( - ClientStatePath, - ClientConsensusStatePath, - ConnectionPath, - ClientConnectionPath, - ChannelEndPath, - SeqSendPath, - SeqRecvPath, - SeqAckPath, - CommitmentPath, - ReceiptPath, - AckPath, - UpgradeClientPath -); diff --git a/crates/store/src/utils/mod.rs b/crates/store/src/utils/mod.rs index dc406c54..ff020978 100644 --- a/crates/store/src/utils/mod.rs +++ b/crates/store/src/utils/mod.rs @@ -1,6 +1,5 @@ pub(crate) mod codec; -pub mod macros; pub(crate) mod sync; -pub use codec::{Codec, JsonCodec}; +pub use codec::*; pub use sync::{Async, SharedRw, SharedRwExt};