Skip to content

Commit

Permalink
Cleanup commented code
Browse files Browse the repository at this point in the history
  • Loading branch information
richardpringle committed Sep 25, 2023
1 parent 8bf4307 commit 810623b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 164 deletions.
79 changes: 12 additions & 67 deletions firewood/src/merkle/node.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (C) 2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE.md for licensing terms.

use bincode::Options;
use bincode::{Error, Options};
use enum_as_inner::EnumAsInner;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use sha3::{Digest, Keccak256};
Expand All @@ -17,7 +17,6 @@ use std::{

use crate::merkle::to_nibble_array;
use crate::nibbles::Nibbles;
use thiserror::Error;

use super::{from_nibbles, PartialPath, TrieHash, TRIE_HASH_LEN};

Expand Down Expand Up @@ -58,12 +57,6 @@ impl<T: DeserializeOwned + AsRef<[u8]>> Encoded<T> {
}
}

#[derive(Debug, Error)]
pub enum Error {
#[error("decoding error")]
Decode(#[from] bincode::Error),
}

#[derive(PartialEq, Eq, Clone)]
pub struct BranchNode {
pub(super) chd: [Option<DiskAddress>; NBRANCH],
Expand Down Expand Up @@ -133,15 +126,14 @@ impl BranchNode {
}

fn calc_eth_rlp<S: ShaleStore<Node>>(&self, store: &S) -> Vec<u8> {
// let mut stream = rlp::RlpStream::new_list(NBRANCH + 1);
let mut list = <[Encoded<Vec<u8>>; NBRANCH + 1]>::default();

for (i, c) in self.chd.iter().enumerate() {
match c {
Some(c) => {
let mut c_ref = store.get_item(*c).unwrap();

if c_ref.get_eth_rlp_long::<S>(store) {
// stream.append(&&(*c_ref.get_root_hash::<S>(store))[..]);
list[i] = Encoded::Data(
bincode::DefaultOptions::new()
.serialize(&&(*c_ref.get_root_hash::<S>(store))[..])
Expand All @@ -155,50 +147,28 @@ impl BranchNode {
}
} else {
let c_rlp = &c_ref.get_eth_rlp::<S>(store);
// stream.append_raw(c_rlp, 1);
list[i] = Encoded::Raw(c_rlp.to_vec());
}
}
None => {
// Check if there is already a calculated rlp for the child, which
// can happen when manually constructing a trie from proof.
if let Some(v) = self.chd_eth_rlp[i].clone() {
if let Some(v) = &self.chd_eth_rlp[i] {
if v.len() == TRIE_HASH_LEN {
// stream.append(&v);
list[i] = Encoded::Data(
bincode::DefaultOptions::new().serialize(&v).unwrap(),
);
list[i] =
Encoded::Data(bincode::DefaultOptions::new().serialize(v).unwrap());
} else {
// stream.append_raw(&v, 1);
list[i] = Encoded::Raw(v);
list[i] = Encoded::Raw(v.clone());
}
}
// if self.chd_eth_rlp[i].is_none() {
// stream.append_empty_data();
// } else {
// let v = self.chd_eth_rlp[i].clone().unwrap();
// if v.len() == TRIE_HASH_LEN {
// stream.append(&v);
// } else {
// stream.append_raw(&v, 1);
// }
// }
}
};
}

// match &self.value {
// Some(val) => stream.append(&val.to_vec()),
// None => stream.append_empty_data(),
// };
// stream.out().into()

if let Some(val) = self.value.clone() {
list[NBRANCH] = Encoded::Data(
bincode::DefaultOptions::new()
.serialize(&val.to_vec())
.unwrap(),
);
if let Some(Data(val)) = &self.value {
list[NBRANCH] = Encoded::Data(bincode::DefaultOptions::new().serialize(val).unwrap());
}

bincode::DefaultOptions::new()
Expand Down Expand Up @@ -249,13 +219,6 @@ impl Debug for LeafNode {
}

impl LeafNode {
// fn calc_eth_rlp(&self) -> Vec<u8> {
// rlp::encode_list::<Vec<u8>, _>(&[
// from_nibbles(&self.0.encode(true)).collect(),
// self.1.to_vec(),
// ])
// .into()
// }
fn calc_eth_rlp(&self) -> Vec<u8> {
bincode::DefaultOptions::new()
.serialize(
Expand Down Expand Up @@ -306,10 +269,8 @@ impl ExtNode {

if !self.1.is_null() {
let mut r = store.get_item(self.1).unwrap();
// stream.append(&from_nibbles(&self.0.encode(false)).collect::<Vec<_>>());

if r.get_eth_rlp_long(store) {
// stream.append(&&(*r.get_root_hash(store))[..]);
list[1] = Encoded::Data(
bincode::DefaultOptions::new()
.serialize(&&(*r.get_root_hash(store))[..])
Expand All @@ -321,29 +282,15 @@ impl ExtNode {
r.lazy_dirty.store(false, Ordering::Relaxed);
}
} else {
// stream.append_raw(r.get_eth_rlp(store), 1);
list[1] = Encoded::Raw(r.get_eth_rlp(store).to_vec());
}
} else {
// Check if there is already a caclucated rlp for the child, which
// can happen when manually constructing a trie from proof.
// if self.2.is_none() {
// stream.append_empty_data();
// } else {
// let v = self.2.clone().unwrap();
// if v.len() == TRIE_HASH_LEN {
// stream.append(&v);
// } else {
// stream.append_raw(&v, 1);
// }
// }

if let Some(v) = self.2.as_ref() {
if let Some(v) = &self.2 {
if v.len() == TRIE_HASH_LEN {
// stream.append(&v);
list[1] = Encoded::Data(bincode::DefaultOptions::new().serialize(v).unwrap());
} else {
// stream.append_raw(&v, 1);
list[1] = Encoded::Raw(v.clone());
}
}
Expand Down Expand Up @@ -434,9 +381,7 @@ impl NodeType {
}

pub fn decode(buf: &[u8]) -> Result<NodeType, Error> {
let items: Vec<Encoded<Vec<u8>>> = bincode::DefaultOptions::new()
.deserialize(dbg!(buf))
.map_err(Error::Decode)?;
let items: Vec<Encoded<Vec<u8>>> = bincode::DefaultOptions::new().deserialize(buf)?;

match items.len() {
EXT_NODE_SIZE => {
Expand All @@ -461,8 +406,8 @@ impl NodeType {
}
}
BRANCH_NODE_SIZE => Ok(NodeType::Branch(BranchNode::decode(buf)?)),
_ => Err(Error::Decode(Box::new(bincode::ErrorKind::Custom(
String::from(""),
size => Err(Box::new(bincode::ErrorKind::Custom(format!(
"invalid size: {size}"
)))),
}
}
Expand Down
106 changes: 9 additions & 97 deletions firewood/src/proof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,19 +149,12 @@ impl<N: AsRef<[u8]> + Send> Proof<N> {
mut key_nibbles: NibblesIterator<'a, 0>,
rlp_encoded_node: &[u8],
) -> Result<(Option<SubProof>, NibblesIterator<'a, 0>), ProofError> {
// let rlp = rlp::Rlp::new(rlp_encoded_node);
let items: Vec<Encoded<Vec<u8>>> = bincode::DefaultOptions::new()
.deserialize(rlp_encoded_node)
.map_err(ProofError::DecodeError)?;

// match rlp.item_count() {
match items.len() {
// Ok(EXT_NODE_SIZE) => {
// [Encoded<Vec<u8>>; 2]
// 0 is always Encoded::Data
// 1 could be either
EXT_NODE_SIZE => {
// let decoded_key = rlp.at(0).unwrap().as_val::<Vec<u8>>().unwrap();
let mut items = items.into_iter();
let decoded_key: Vec<u8> = items.next().unwrap().decode()?;

Expand All @@ -171,13 +164,6 @@ impl<N: AsRef<[u8]> + Send> Proof<N> {
PartialPath::from_nibbles(decoded_key_nibbles.into_iter());
let cur_key = cur_key_path.into_inner();

// let rlp = rlp.at(1).unwrap();
// let data = if rlp.is_data() {
// rlp.as_val::<Vec<u8>>().unwrap()
// } else {
// rlp.as_raw().to_vec()
// };

let data: Vec<u8> = items.next().unwrap().decode()?;

// Check if the key of current node match with the given key
Expand All @@ -201,32 +187,20 @@ impl<N: AsRef<[u8]> + Send> Proof<N> {
Ok((sub_proof.into(), key_nibbles))
}

// Ok(BRANCH_NODE_SIZE) if key_nibbles.size_hint().0 == 0 => Err(ProofError::NoSuchNode),
BRANCH_NODE_SIZE if key_nibbles.size_hint().0 == 0 => Err(ProofError::NoSuchNode),

// Ok(BRANCH_NODE_SIZE) => {
BRANCH_NODE_SIZE => {
let index = key_nibbles.next().unwrap() as usize;
// let rlp = rlp.at(index).unwrap();

// let data = if rlp.is_data() {
// rlp.as_val::<Vec<u8>>().unwrap()
// } else {
// rlp.as_raw().to_vec()
// };

// consume items returning the item at index

let data: Vec<u8> = items.into_element_at(index).decode()?;
let data: Vec<u8> = items.into_iter().nth(index).unwrap().decode()?;

self.generate_subproof(data)
.map(|subproof| (Some(subproof), key_nibbles))
}

// Ok(_) => Err(ProofError::DecodeError(rlp::DecoderError::RlpInvalidLength)),
// Err(e) => Err(ProofError::DecodeError(e)),
_ => Err(ProofError::DecodeError(Box::new(
bincode::ErrorKind::Custom(String::from("")),
size => Err(ProofError::DecodeError(Box::new(
bincode::ErrorKind::Custom(format!("invalid size: {size}")),
))),
}
}
Expand All @@ -240,6 +214,7 @@ impl<N: AsRef<[u8]> + Send> Proof<N> {
hash: Some(sub_hash),
})
}

32 => {
let sub_hash: &[u8] = &data;
let sub_hash = sub_hash.try_into().unwrap();
Expand All @@ -249,9 +224,9 @@ impl<N: AsRef<[u8]> + Send> Proof<N> {
hash: Some(sub_hash),
})
}
// _ => Err(ProofError::DecodeError(rlp::DecoderError::RlpInvalidLength)),
_ => Err(ProofError::DecodeError(Box::new(
bincode::ErrorKind::Custom(String::from("")),

len => Err(ProofError::DecodeError(Box::new(
bincode::ErrorKind::Custom(format!("invalid proof length: {len}")),
))),
}
}
Expand Down Expand Up @@ -568,20 +543,11 @@ impl<N: AsRef<[u8]> + Send> Proof<N> {
buf: &[u8],
end_node: bool,
) -> Result<(DiskAddress, Option<SubProof>, usize), ProofError> {
// let rlp = rlp::Rlp::new(buf);
// let size = rlp.item_count()?;

let mut items: Vec<Encoded<Vec<u8>>> = bincode::DefaultOptions::new().deserialize(buf)?;
let size = items.len();

match size {
EXT_NODE_SIZE => {
// let cur_key_path: Vec<_> = rlp
// .at(0)?
// .as_val::<Vec<u8>>()?
// .into_iter()
// .flat_map(to_nibble_array)
// .collect();
let mut items = items.into_iter();

let cur_key_path: Vec<u8> = items
Expand All @@ -594,15 +560,6 @@ impl<N: AsRef<[u8]> + Send> Proof<N> {

let (cur_key_path, term) = PartialPath::decode(&cur_key_path);
let cur_key = cur_key_path.into_inner();

// let rlp = rlp.at(1)?;

// let data = if rlp.is_data() {
// rlp.as_val::<Vec<u8>>()?
// } else {
// rlp.as_raw().to_vec()
// };

let data: Vec<u8> = items.next().unwrap().decode()?;

// Check if the key of current node match with the given key.
Expand All @@ -629,22 +586,6 @@ impl<N: AsRef<[u8]> + Send> Proof<N> {
}

BRANCH_NODE_SIZE => {
// let data_rlp = rlp.at(NBRANCH)?;

// // Extract the value of the branch node.
// // Skip if rlp is empty data
// let value = if !data_rlp.is_empty() {
// let data = if data_rlp.is_data() {
// data_rlp.as_val::<Vec<u8>>().unwrap()
// } else {
// data_rlp.as_raw().to_vec()
// };

// Some(data)
// } else {
// None
// };

// we've already validated the size, that's why we can safely unwrap
let data = items.pop().unwrap().decode()?;
// Extract the value of the branch node and set to None if it's an empty Vec
Expand All @@ -653,19 +594,6 @@ impl<N: AsRef<[u8]> + Send> Proof<N> {
// Record rlp values of all children.
let mut chd_eth_rlp: [Option<Vec<u8>>; NBRANCH] = Default::default();

// for (i, chd) in rlp.into_iter().take(NBRANCH).enumerate() {
// if !chd.is_empty() {
// // Skip if chd is empty data
// let data = if chd.is_data() {
// chd.as_val()?
// } else {
// chd.as_raw().to_vec()
// };

// chd_eth_rlp[i] = Some(data);
// }
// }

// we popped the last element, so their should only be NBRANCH items left
for (i, chd) in items.into_iter().enumerate() {
let data = chd.decode()?;
Expand Down Expand Up @@ -698,10 +626,8 @@ impl<N: AsRef<[u8]> + Send> Proof<N> {
Ok((branch_ptr, Some(subproof), 1))
}

// RLP length can only be the two cases above.
// _ => Err(ProofError::DecodeError(rlp::DecoderError::RlpInvalidLength)),
_ => Err(ProofError::DecodeError(Box::new(
bincode::ErrorKind::Custom(String::from("")),
size => Err(ProofError::DecodeError(Box::new(
bincode::ErrorKind::Custom(format!("invalid size: {size}")),
))),
}
}
Expand Down Expand Up @@ -1132,17 +1058,3 @@ fn unset_node_ref<K: AsRef<[u8]>, S: ShaleStore<Node> + Send + Sync>(
}
}
}

trait IntoElementAt {
type Element;

fn into_element_at(self, index: usize) -> Self::Element;
}

impl<T> IntoElementAt for Vec<T> {
type Element = T;

fn into_element_at(self, index: usize) -> Self::Element {
self.into_iter().nth(index).unwrap()
}
}

0 comments on commit 810623b

Please sign in to comment.