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

make prefix iterator ordered by storage keys and add reverse order prefix iterator #458

Merged
merged 40 commits into from
Oct 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
1a57908
ledger: add tx and VP traits with host env functions
tzemanovic Jul 20, 2022
5d8c61a
shared/vm: rename host_env TxEnv/VpEnv to TxVmEnv/VpVmEnv
tzemanovic Jul 20, 2022
fe365d9
shared/ledger/native_vp: implement VpEnv
tzemanovic Jul 20, 2022
4e46aca
shared: update native_vp implementations for VpEnv methods
tzemanovic Jul 20, 2022
e4b84a0
VM: move vm_env sub-mod into tx/vp_prelude and add Tx/VpEnv and Ctx
tzemanovic Jul 20, 2022
71820f6
tests: update for VM API changes
tzemanovic Jul 20, 2022
d7d0ef1
wasm: update for VM API changes
tzemanovic Jul 20, 2022
bf604a4
macros: add error handling to transaction and validity_predicate macros
tzemanovic Jul 20, 2022
d868424
wasm: improve error handling
tzemanovic Jul 21, 2022
221e9f2
changelog: add #1093
tzemanovic Jul 21, 2022
8bce915
Update shared/src/ledger/vp_env.rs
tzemanovic Jul 25, 2022
affa0b5
wasm_for_tests: make
tzemanovic Aug 11, 2022
14f638a
update wasm checksums
tzemanovic Aug 11, 2022
18526da
[ci skip] wasm checksums update
github-actions[bot] Aug 17, 2022
9a135eb
ledger: add StorageRead trait with extensible error type
tzemanovic Aug 12, 2022
97c6947
ledger/native_vp: implement StorageRead for pre and post state
tzemanovic Aug 12, 2022
7552c1e
ledger/vp: impl StorageRead for WASM VPs pre and post state
tzemanovic Aug 12, 2022
45f3f94
ledger/storage: impl StorageRead for Storage
tzemanovic Aug 12, 2022
5989412
ledger/tx: inherit StorageRead in TxEnv
tzemanovic Aug 12, 2022
10f94c2
ledger/pos: implement PosReadOnly using StorageRead trait
tzemanovic Aug 12, 2022
eeb1e8c
update wasm checksums
tzemanovic Aug 12, 2022
abd10c1
ledger: factor out TxEnv write methods into a new StorageWrite trait
tzemanovic Aug 12, 2022
08b0a8f
ledger: impl StorageWrite for Storage
tzemanovic Aug 12, 2022
773033d
add <'iter> lifetime to StorageRead trait to get around lack of GATs
tzemanovic Aug 16, 2022
28b4307
add more comments for StorageRead lifetime with an example usage
tzemanovic Aug 16, 2022
8bc5816
storage: remove unnecessary clone
tzemanovic Aug 16, 2022
7decfab
fix missing StorageWrite for Storage merkle tree update
tzemanovic Aug 16, 2022
b92edd4
update wasm checksums
tzemanovic Aug 20, 2022
ace6716
changelog: add #331
tzemanovic Aug 21, 2022
d737acd
storage_api: build a nicer `iter_prefix` function on top of StorageRead
tzemanovic Aug 15, 2022
4558dfa
test/vm_host_env: refactor prefix iter tests with new `iter_prefix` fn
tzemanovic Aug 15, 2022
d32d7af
wasm checksums update
github-actions[bot] Aug 15, 2022
fec7220
changelog: add #335
tzemanovic Aug 22, 2022
b8eccf3
deps: replace hex with data-encoding
tzemanovic Sep 8, 2022
b47d1c1
shared/storage/key: add support for int/uint keys that maintain order
tzemanovic Sep 8, 2022
e648085
test/vm_host_env: check prefix iter order in tx and VP
tzemanovic Sep 8, 2022
1429b92
add support for rev_iter_prefix in storage and VP and tx envs
tzemanovic Sep 8, 2022
881c93c
tests: extend prefix iter tests for reverse order
tzemanovic Sep 8, 2022
d786a4a
changelog: add #458
tzemanovic Sep 8, 2022
1d2f1dd
[ci skip] wasm checksums update
github-actions[bot] Sep 9, 2022
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
- Added WASM transaction and validity predicate `Ctx` with methods for host
environment functions to unify the interface of native VPs and WASM VPs under
`trait VpEnv` ([#1093](https://github.com/anoma/anoma/pull/1093))
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- Added a StorageWrite trait for a common interface for transactions and direct
storage access for protocol ([#331](https://github.com/anoma/namada/pull/331))
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
- Added a simpler prefix iterator API that returns `std::iter::Iterator` with
the storage keys parsed and a variant that also decodes stored values with
Borsh ([#335](https://github.com/anoma/namada/pull/335))
3 changes: 3 additions & 0 deletions .changelog/unreleased/improvements/409-sorted-prefix-iter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
- Fix order of prefix iterator to be sorted by storage
keys and add support for a reverse order prefix iterator.
([#409](https://github.com/anoma/namada/issues/409))
19 changes: 13 additions & 6 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion apps/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ clap = {git = "https://github.com/clap-rs/clap/", tag = "v3.0.0-beta.2", default
color-eyre = "0.5.10"
config = "0.11.0"
curl = "0.4.43"
data-encoding = "2.3.2"
derivative = "2.2.0"
directories = "4.0.1"
ed25519-consensus = "1.2.0"
Expand All @@ -71,7 +72,6 @@ eyre = "0.6.5"
flate2 = "1.0.22"
file-lock = "2.0.2"
futures = "0.3"
hex = "0.4.3"
itertools = "0.10.1"
jsonpath_lib = "0.3.0"
libc = "0.2.97"
Expand Down
3 changes: 2 additions & 1 deletion apps/src/lib/client/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use async_std::fs::{self};
use async_std::path::PathBuf;
use async_std::prelude::*;
use borsh::BorshDeserialize;
use data_encoding::HEXLOWER;
use itertools::Itertools;
use namada::ledger::governance::storage as gov_storage;
use namada::ledger::governance::utils::Votes;
Expand Down Expand Up @@ -81,7 +82,7 @@ pub async fn query_raw_bytes(_ctx: Context, args: args::QueryRawBytes) {
.unwrap();
match response.code {
Code::Ok => {
println!("{}", hex::encode(&response.value));
println!("{}", HEXLOWER.encode(&response.value));
}
Code::Err(err) => {
eprintln!(
Expand Down
12 changes: 6 additions & 6 deletions apps/src/lib/config/genesis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub mod genesis_config {
use std::path::Path;
use std::str::FromStr;

use hex;
use data_encoding::HEXLOWER;
use namada::ledger::governance::parameters::GovParams;
use namada::ledger::parameters::{EpochDuration, Parameters};
use namada::ledger::pos::types::BasisPoints;
Expand All @@ -50,12 +50,12 @@ pub mod genesis_config {

impl HexString {
pub fn to_bytes(&self) -> Result<Vec<u8>, HexKeyError> {
let bytes = hex::decode(&self.0)?;
let bytes = HEXLOWER.decode(self.0.as_ref())?;
Ok(bytes)
}

pub fn to_sha256_bytes(&self) -> Result<[u8; 32], HexKeyError> {
let bytes = hex::decode(&self.0)?;
let bytes = HEXLOWER.decode(self.0.as_ref())?;
let slice = bytes.as_slice();
let array: [u8; 32] = slice.try_into()?;
Ok(array)
Expand All @@ -76,15 +76,15 @@ pub mod genesis_config {
#[derive(Error, Debug)]
pub enum HexKeyError {
#[error("Invalid hex string: {0:?}")]
InvalidHexString(hex::FromHexError),
InvalidHexString(data_encoding::DecodeError),
#[error("Invalid sha256 checksum: {0}")]
InvalidSha256(TryFromSliceError),
#[error("Invalid public key: {0}")]
InvalidPublicKey(ParsePublicKeyError),
}

impl From<hex::FromHexError> for HexKeyError {
fn from(err: hex::FromHexError) -> Self {
impl From<data_encoding::DecodeError> for HexKeyError {
fn from(err: data_encoding::DecodeError) -> Self {
Self::InvalidHexString(err)
}
}
Expand Down
6 changes: 4 additions & 2 deletions apps/src/lib/node/gossip/p2p/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub struct Identity {
// TODO this is needed because libp2p does not export ed255519 serde
// feature maybe a MR for libp2p to export theses functions ?
mod keypair_serde {
use data_encoding::HEXLOWER;
use libp2p::identity::ed25519::Keypair;
use serde::de::Error;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
Expand All @@ -33,15 +34,16 @@ mod keypair_serde {
S: Serializer,
{
let bytes = value.encode();
let string = hex::encode(&bytes[..]);
let string = HEXLOWER.encode(&bytes[..]);
string.serialize(serializer)
}
pub fn deserialize<'d, D>(deserializer: D) -> Result<Keypair, D::Error>
where
D: Deserializer<'d>,
{
let string = String::deserialize(deserializer)?;
let mut bytes = hex::decode(&string).map_err(Error::custom)?;
let mut bytes =
HEXLOWER.decode(string.as_ref()).map_err(Error::custom)?;
Keypair::decode(bytes.as_mut()).map_err(Error::custom)
}
}
Expand Down
3 changes: 3 additions & 0 deletions apps/src/lib/node/ledger/protocol/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,10 +249,13 @@ where
}
Address::Internal(internal_addr) => {
let ctx = native_vp::Ctx::new(
addr,
storage,
write_log,
tx,
gas_meter,
&keys_changed,
&verifiers,
vp_wasm_cache.clone(),
);
let tx_data = match tx.data.as_ref() {
Expand Down
42 changes: 27 additions & 15 deletions apps/src/lib/node/ledger/storage/rocksdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -806,24 +806,36 @@ impl<'iter> DBIter<'iter> for RocksDB {
&'iter self,
prefix: &Key,
) -> PersistentPrefixIterator<'iter> {
let db_prefix = "subspace/".to_owned();
let prefix = format!("{}{}", db_prefix, prefix);
iter_prefix(self, prefix, Direction::Forward)
}

let mut read_opts = ReadOptions::default();
// don't use the prefix bloom filter
read_opts.set_total_order_seek(true);
let mut upper_prefix = prefix.clone().into_bytes();
if let Some(last) = upper_prefix.pop() {
upper_prefix.push(last + 1);
}
read_opts.set_iterate_upper_bound(upper_prefix);
fn rev_iter_prefix(&'iter self, prefix: &Key) -> Self::PrefixIter {
iter_prefix(self, prefix, Direction::Reverse)
}
}

let iter = self.0.iterator_opt(
IteratorMode::From(prefix.as_bytes(), Direction::Forward),
read_opts,
);
PersistentPrefixIterator(PrefixIterator::new(iter, db_prefix))
fn iter_prefix<'iter>(
db: &'iter RocksDB,
prefix: &Key,
direction: Direction,
) -> PersistentPrefixIterator<'iter> {
let db_prefix = "subspace/".to_owned();
let prefix = format!("{}{}", db_prefix, prefix);

let mut read_opts = ReadOptions::default();
// don't use the prefix bloom filter
read_opts.set_total_order_seek(true);
let mut upper_prefix = prefix.clone().into_bytes();
if let Some(last) = upper_prefix.pop() {
upper_prefix.push(last + 1);
}
read_opts.set_iterate_upper_bound(upper_prefix);

let iter = db.0.iterator_opt(
IteratorMode::From(prefix.as_bytes(), direction),
read_opts,
);
PersistentPrefixIterator(PrefixIterator::new(iter, db_prefix))
}

#[derive(Debug)]
Expand Down
7 changes: 4 additions & 3 deletions apps/src/lib/wallet/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::rc::Rc;
use std::str::FromStr;

use borsh::{BorshDeserialize, BorshSerialize};
use data_encoding::HEXLOWER;
use namada::types::key::*;
use orion::{aead, kdf};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -108,15 +109,15 @@ pub struct EncryptedKeypair(Vec<u8>);

impl Display for EncryptedKeypair {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", hex::encode(&self.0))
write!(f, "{}", HEXLOWER.encode(self.0.as_ref()))
}
}

impl FromStr for EncryptedKeypair {
type Err = hex::FromHexError;
type Err = data_encoding::DecodeError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
hex::decode(s).map(Self)
HEXLOWER.decode(s.as_ref()).map(Self)
}
}

Expand Down
4 changes: 2 additions & 2 deletions apps/src/lib/wasm_loader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use std::collections::HashMap;
use std::fs;
use std::path::Path;

use data_encoding::HEXLOWER;
use futures::future::join_all;
use hex;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use thiserror::Error;
Expand Down Expand Up @@ -144,7 +144,7 @@ pub async fn pre_fetch_wasm(wasm_directory: impl AsRef<Path>) {
Ok(bytes) => {
let mut hasher = Sha256::new();
hasher.update(bytes);
let result = hex::encode(hasher.finalize());
let result = HEXLOWER.encode(&hasher.finalize());
let derived_name = format!(
"{}.{}.wasm",
&name.split('.').collect::<Vec<&str>>()[0],
Expand Down
Loading