Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug fix: StateMap::Keys are not consistent across platforms #804

Merged
merged 18 commits into from
Sep 8, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions examples/demo-prover/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 13 additions & 4 deletions examples/demo-prover/methods/guest/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 36 additions & 0 deletions module-system/sov-state/src/codec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod borsh_codec;
mod json_codec;

pub use bcs_codec::BcsCodec;
use borsh::BorshSerialize;
pub use borsh_codec::BorshCodec;
pub use json_codec::JsonCodec;

Expand Down Expand Up @@ -42,3 +43,38 @@ pub trait StateValueCodec<V> {
.unwrap()
}
}

pub trait EncodeLike<Ref: ?Sized, Target> {
fn encode_like(&self, borrowed: &Ref) -> Vec<u8>;
neysofu marked this conversation as resolved.
Show resolved Hide resolved
}

// All items can be encoded like themselves
impl<C, T> EncodeLike<T, T> for C
where
C: StateValueCodec<T>,
{
fn encode_like(&self, borrowed: &T) -> Vec<u8> {
self.encode_value(borrowed)
}
}

// In borsh, a slice is encoded the same way as a vector
impl<T> EncodeLike<[T], Vec<T>> for BorshCodec
preston-evans98 marked this conversation as resolved.
Show resolved Hide resolved
where
T: BorshSerialize,
{
fn encode_like(&self, borrowed: &[T]) -> Vec<u8> {
preston-evans98 marked this conversation as resolved.
Show resolved Hide resolved
borrowed.try_to_vec().unwrap()
preston-evans98 marked this conversation as resolved.
Show resolved Hide resolved
}
}

#[test]
fn test_borsh_slice_encode_alike() {
let codec = BorshCodec;
let slice = [1, 2, 3];
let vec = vec![1, 2, 3];
assert_eq!(
<BorshCodec as EncodeLike<[i32], Vec<i32>>>::encode_like(&codec, &slice),
codec.encode_value(&vec)
);
}
50 changes: 27 additions & 23 deletions module-system/sov-state/src/containers/accessory_map.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use std::borrow::Borrow;
use std::hash::Hash;
use std::marker::PhantomData;

use super::StateMapError;
use crate::codec::{BorshCodec, StateValueCodec};
use crate::codec::{BorshCodec, EncodeLike, StateValueCodec};
use crate::storage::StorageKey;
use crate::{AccessoryWorkingSet, Prefix, StateReaderAndWriter, Storage};

Expand Down Expand Up @@ -57,8 +56,8 @@ where
/// map’s key type.
pub fn set<Q, S: Storage>(&self, key: &Q, value: &V, working_set: &mut AccessoryWorkingSet<S>)
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
VC: EncodeLike<Q, K>,
preston-evans98 marked this conversation as resolved.
Show resolved Hide resolved
Q: ?Sized,
{
working_set.set_value(self.prefix(), key, value, &self.value_codec)
}
Expand All @@ -68,9 +67,8 @@ where
///
/// # Examples
///
/// The key may be any borrowed form of the map’s key type. Note that
/// [`Hash`] and [`Eq`] on the borrowed form must match those for the key
/// type.
/// The key may be any item that implements [`EncodeLike`] the map's key type
/// using your chosen codec.
///
/// ```
/// use sov_state::{AccessoryStateMap, Storage, AccessoryWorkingSet};
Expand All @@ -85,7 +83,7 @@ where
/// }
/// ```
///
/// If the map's key type does not implement [`Borrow`] for your desired
/// If the map's key type does not implement [`EncodeLike`] for your desired
/// target type, you'll have to convert the key to something else. An
/// example of this would be "slicing" an array to use in [`Vec`]-keyed
/// maps:
Expand All @@ -102,8 +100,8 @@ where
/// ```
pub fn get<Q, S: Storage>(&self, key: &Q, working_set: &mut AccessoryWorkingSet<S>) -> Option<V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
VC: EncodeLike<Q, K>,
Q: ?Sized,
{
working_set.get_value(self.prefix(), key, &self.value_codec)
}
Expand All @@ -116,11 +114,14 @@ where
working_set: &mut AccessoryWorkingSet<S>,
) -> Result<V, StateMapError>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
VC: EncodeLike<Q, K>,
Q: ?Sized,
{
self.get(key, working_set).ok_or_else(|| {
StateMapError::MissingValue(self.prefix().clone(), StorageKey::new(self.prefix(), key))
StateMapError::MissingValue(
self.prefix().clone(),
StorageKey::new(self.prefix(), key, &self.value_codec),
)
})
}

Expand All @@ -132,8 +133,8 @@ where
working_set: &mut AccessoryWorkingSet<S>,
) -> Option<V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
VC: EncodeLike<Q, K>,
Q: ?Sized,
{
working_set.remove_value(self.prefix(), key, &self.value_codec)
}
Expand All @@ -148,11 +149,14 @@ where
working_set: &mut AccessoryWorkingSet<S>,
) -> Result<V, StateMapError>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
VC: EncodeLike<Q, K>,
Q: ?Sized,
{
self.remove(key, working_set).ok_or_else(|| {
StateMapError::MissingValue(self.prefix().clone(), StorageKey::new(self.prefix(), key))
StateMapError::MissingValue(
self.prefix().clone(),
StorageKey::new(self.prefix(), key, &self.value_codec),
)
})
}

Expand All @@ -162,10 +166,10 @@ where
/// return the value beforing deletion.
pub fn delete<Q, S: Storage>(&self, key: &Q, working_set: &mut AccessoryWorkingSet<S>)
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
VC: EncodeLike<Q, K>,
Q: ?Sized,
{
working_set.delete_value(self.prefix(), key);
working_set.delete_value(self.prefix(), key, &self.value_codec);
}
}

Expand All @@ -174,7 +178,7 @@ impl<'a, K, V, VC> AccessoryStateMap<K, V, VC>
where
K: arbitrary::Arbitrary<'a> + Hash + Eq,
V: arbitrary::Arbitrary<'a> + Hash + Eq,
VC: StateValueCodec<V> + Default,
VC: StateValueCodec<V> + StateValueCodec<K> + Default,
{
pub fn arbitrary_workset<S>(
u: &mut arbitrary::Unstructured<'a>,
Expand All @@ -188,7 +192,7 @@ where
let prefix = Prefix::arbitrary(u)?;
let len = u.arbitrary_len::<(K, V)>()?;
let codec = VC::default();
let map = AccessoryStateMap::with_codec(prefix, codec);
let map = Self::with_codec(prefix, codec);

(0..len).try_fold(map, |map, _| {
let key = K::arbitrary(u)?;
Expand Down
12 changes: 4 additions & 8 deletions module-system/sov-state/src/containers/accessory_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,12 @@ where
{
/// Sets a value in the AccessoryStateValue.
pub fn set<S: Storage>(&self, value: &V, working_set: &mut AccessoryWorkingSet<S>) {
working_set.set_value(self.prefix(), &SingletonKey, value, &self.codec)
working_set.set_singleton(self.prefix(), value, &self.codec)
}

/// Gets a value from the AccessoryStateValue or None if the value is absent.
pub fn get<S: Storage>(&self, working_set: &mut AccessoryWorkingSet<S>) -> Option<V> {
working_set.get_value(self.prefix(), &SingletonKey, &self.codec)
working_set.get_singleton(self.prefix(), &self.codec)
}

/// Gets a value from the AccessoryStateValue or Error if the value is absent.
Expand All @@ -71,7 +71,7 @@ where

/// Removes a value from the AccessoryStateValue, returning the value (or None if the key is absent).
pub fn remove<S: Storage>(&self, working_set: &mut AccessoryWorkingSet<S>) -> Option<V> {
working_set.remove_value(self.prefix(), &SingletonKey, &self.codec)
working_set.remove_singleton(self.prefix(), &self.codec)
}

/// Removes a value and from the AccessoryStateValue, returning the value (or Error if the key is absent).
Expand All @@ -85,10 +85,6 @@ where

/// Deletes a value from the AccessoryStateValue.
pub fn delete<S: Storage>(&self, working_set: &mut AccessoryWorkingSet<S>) {
working_set.delete_value(self.prefix(), &SingletonKey);
working_set.delete_singleton(self.prefix());
}
}

// SingletonKey is very similar to the unit type `()` i.e. it has only one value.
#[derive(Debug, PartialEq, Eq, Hash)]
struct SingletonKey;
8 changes: 4 additions & 4 deletions module-system/sov-state/src/containers/accessory_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ where

impl<V, VC> AccessoryStateVec<V, VC>
where
VC: StateValueCodec<V>,
VC: StateValueCodec<V> + StateValueCodec<usize>,
{
/// Creates a new [`AccessoryStateVec`] with the given prefix and codec.
pub fn with_codec(prefix: Prefix, codec: VC) -> Self {
Expand Down Expand Up @@ -187,7 +187,7 @@ where

impl<'a, 'ws, V, VC, S> Iterator for AccessoryStateVecIter<'a, 'ws, V, VC, S>
where
VC: StateValueCodec<V>,
VC: StateValueCodec<V> + StateValueCodec<usize>,
S: Storage,
{
type Item = V;
Expand All @@ -204,7 +204,7 @@ where

impl<'a, 'ws, V, VC, S> ExactSizeIterator for AccessoryStateVecIter<'a, 'ws, V, VC, S>
where
VC: StateValueCodec<V>,
VC: StateValueCodec<V> + StateValueCodec<usize>,
S: Storage,
{
fn len(&self) -> usize {
Expand All @@ -214,7 +214,7 @@ where

impl<'a, 'ws, V, VC, S> FusedIterator for AccessoryStateVecIter<'a, 'ws, V, VC, S>
where
VC: StateValueCodec<V>,
VC: StateValueCodec<V> + StateValueCodec<usize>,
S: Storage,
{
}
Expand Down
Loading