Skip to content

Commit

Permalink
wip: fixup split
Browse files Browse the repository at this point in the history
  • Loading branch information
tzemanovic committed Nov 4, 2022
1 parent 08a162e commit 42d711c
Show file tree
Hide file tree
Showing 5 changed files with 141 additions and 96 deletions.
26 changes: 0 additions & 26 deletions core/src/types/governance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use super::key::common::{self, Signature};
use super::key::SigScheme;
use super::storage::Epoch;
use super::token::SCALE;
use super::transaction::governance::InitProposalData;

/// Type alias for vote power
pub type VotePower = u128;
Expand Down Expand Up @@ -163,31 +162,6 @@ pub enum ProposalError {
InvalidProposalData,
}

impl TryFrom<Proposal> for InitProposalData {
type Error = ProposalError;

fn try_from(proposal: Proposal) -> Result<Self, Self::Error> {
let proposal_code = if let Some(path) = proposal.proposal_code_path {
match std::fs::read(path) {
Ok(bytes) => Some(bytes),
Err(_) => return Err(Self::Error::InvalidProposalData),
}
} else {
None
};

Ok(InitProposalData {
id: proposal.id,
content: proposal.content.try_to_vec().unwrap(),
author: proposal.author,
voting_start_epoch: proposal.voting_start_epoch,
voting_end_epoch: proposal.voting_end_epoch,
grace_epoch: proposal.grace_epoch,
proposal_code,
})
}
}

#[derive(
Debug, Clone, BorshSerialize, BorshDeserialize, Serialize, Deserialize,
)]
Expand Down
43 changes: 36 additions & 7 deletions core/src/types/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
use std::fmt::{self, Display};
use std::ops::Deref;

// use arse_merkle_tree::traits::Value;
// use arse_merkle_tree::Hash as TreeHash;
use arse_merkle_tree::traits::Value;
use arse_merkle_tree::{Hash as TreeHash, H256};
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
Expand Down Expand Up @@ -116,8 +116,37 @@ impl Hash {
// }
// }

// impl From<Hash> for TreeHash {
// fn from(hash: Hash) -> Self {
// Self::from(hash.0)
// }
// }
impl From<Hash> for TreeHash {
fn from(hash: Hash) -> Self {
Self::from(hash.0)
}
}

impl Value for Hash {
fn as_slice(&self) -> &[u8] {
self.0.as_slice()
}

fn zero() -> Self {
Hash([0u8; 32])
}
}

impl From<Hash> for H256 {
fn from(hash: Hash) -> Self {
hash.0.into()
}
}

impl From<H256> for Hash {
fn from(hash: H256) -> Self {
Self(hash.into())
}
}

impl From<&H256> for Hash {
fn from(hash: &H256) -> Self {
let hash = hash.to_owned();
Self(hash.into())
}
}
163 changes: 100 additions & 63 deletions core/src/types/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,23 @@ use std::num::ParseIntError;
use std::ops::{Add, Deref, Div, Mul, Rem, Sub};
use std::str::FromStr;

// use arse_merkle_tree::InternalKey;
use arse_merkle_tree::traits::{Hasher, Value};
use arse_merkle_tree::{InternalKey, Key as TreeKey, H256};
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use data_encoding::BASE32HEX_NOPAD;
// use ics23::CommitmentProof;
use serde::{Deserialize, Serialize};
use thiserror::Error;

#[cfg(feature = "ferveo-tpke")]
use super::transaction::WrapperTx;
use crate::bytes::ByteBuf;
// use crate::ledger::storage::IBC_KEY_LIMIT;
use crate::types::address::{self, Address};
use crate::types::hash::Hash;
use crate::types::time::DateTimeUtc;

/// The maximum size of an IBC key (in bytes) allowed in merkle-ized storage
pub const IBC_KEY_LIMIT: usize = 120;

#[allow(missing_docs)]
#[derive(Error, Debug)]
pub enum Error {
Expand Down Expand Up @@ -267,55 +269,91 @@ where
}
}

// /// Storage keys that are utf8 encoded strings
// #[derive(Eq, PartialEq, Copy, Clone, Hash)]
// pub struct StringKey {
// /// The original key string, in bytes
// pub original: [u8; IBC_KEY_LIMIT],
// /// The utf8 bytes representation of the key to be
// /// used internally in the merkle tree
// pub tree_key: InternalKey<IBC_KEY_LIMIT>,
// /// The length of the input (without the padding)
// pub length: usize,
// }

// impl Deref for StringKey {
// type Target = InternalKey<IBC_KEY_LIMIT>;

// fn deref(&self) -> &Self::Target {
// &self.tree_key
// }
// }

// impl BorshSerialize for StringKey {
// fn serialize<W: Write>(&self, writer: &mut W) -> std::io::Result<()> {
// let to_serialize = (self.original.to_vec(), self.tree_key,
// self.length); BorshSerialize::serialize(&to_serialize, writer)
// }
// }

// impl BorshDeserialize for StringKey {
// fn deserialize(buf: &mut &[u8]) -> std::io::Result<Self> {
// use std::io::ErrorKind;
// let (original, tree_key, length): (
// Vec<u8>,
// InternalKey<IBC_KEY_LIMIT>,
// usize,
// ) = BorshDeserialize::deserialize(buf)?;
// let original: [u8; IBC_KEY_LIMIT] =
// original.try_into().map_err(|_| {
// std::io::Error::new(
// ErrorKind::InvalidData,
// "Input byte vector is too large",
// )
// })?;
// Ok(Self {
// original,
// tree_key,
// length,
// })
// }
// }
/// Storage keys that are utf8 encoded strings
#[derive(Eq, PartialEq, Copy, Clone, Hash)]
pub struct StringKey {
/// The original key string, in bytes
pub original: [u8; IBC_KEY_LIMIT],
/// The utf8 bytes representation of the key to be
/// used internally in the merkle tree
pub tree_key: InternalKey<IBC_KEY_LIMIT>,
/// The length of the input (without the padding)
pub length: usize,
}

#[allow(missing_docs)]
#[derive(Error, Debug)]
pub enum TreeKeyError {
#[error("Invalid key for merkle tree: {0}")]
InvalidMerkleKey(String),
}

impl TreeKey<IBC_KEY_LIMIT> for StringKey {
type Error = TreeKeyError;

fn as_slice(&self) -> &[u8] {
&self.original.as_slice()[..self.length]
}

fn try_from_bytes(bytes: &[u8]) -> std::result::Result<Self, Self::Error> {
let mut tree_key = [0u8; IBC_KEY_LIMIT];
let mut original = [0u8; IBC_KEY_LIMIT];
let mut length = 0;
for (i, byte) in bytes.iter().enumerate() {
if i >= IBC_KEY_LIMIT {
return Err(TreeKeyError::InvalidMerkleKey(
"Input IBC key is too large".into(),
));
}
original[i] = *byte;
tree_key[i] = byte.wrapping_add(1);
length += 1;
}
Ok(Self {
original,
tree_key: tree_key.into(),
length,
})
}
}

impl Deref for StringKey {
type Target = InternalKey<IBC_KEY_LIMIT>;

fn deref(&self) -> &Self::Target {
&self.tree_key
}
}

impl BorshSerialize for StringKey {
fn serialize<W: Write>(&self, writer: &mut W) -> std::io::Result<()> {
let to_serialize = (self.original.to_vec(), self.tree_key, self.length);
BorshSerialize::serialize(&to_serialize, writer)
}
}

impl BorshDeserialize for StringKey {
fn deserialize(buf: &mut &[u8]) -> std::io::Result<Self> {
use std::io::ErrorKind;
let (original, tree_key, length): (
Vec<u8>,
InternalKey<IBC_KEY_LIMIT>,
usize,
) = BorshDeserialize::deserialize(buf)?;
let original: [u8; IBC_KEY_LIMIT] =
original.try_into().map_err(|_| {
std::io::Error::new(
ErrorKind::InvalidData,
"Input byte vector is too large",
)
})?;
Ok(Self {
original,
tree_key,
length,
})
}
}

/// A wrapper around raw bytes to be stored as values
/// in a merkle tree
Expand Down Expand Up @@ -346,18 +384,17 @@ impl From<TreeBytes> for Vec<u8> {
}
}

impl Value for TreeBytes {
fn as_slice(&self) -> &[u8] {
self.0.as_slice()
}

fn zero() -> Self {
TreeBytes::zero()
}
}

// TODO not sure
// /// Type of membership proof from a merkle tree
// pub enum MembershipProof {
// /// ICS23 compliant membership proof
// ICS23(CommitmentProof),
// }

// impl From<CommitmentProof> for MembershipProof {
// fn from(proof: CommitmentProof) -> Self {
// Self::ICS23(proof)
// }
// }

impl Key {
/// Parses string and returns a key
Expand Down
1 change: 1 addition & 0 deletions shared/src/ledger/storage_api.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub use namada_core::ledger::storage_api::*;
4 changes: 4 additions & 0 deletions shared/src/types/key/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
//! Cryptographic keys
pub use namada_core::types::key::*;
pub mod dkg_session_keys;

0 comments on commit 42d711c

Please sign in to comment.