use std::fmt;
use byteorder::{BigEndian, ByteOrder};
use incrementalmerkletree::frontier::Frontier;
use lazy_static::lazy_static;
use sha2::digest::generic_array::GenericArray;
use thiserror::Error;
use super::commitment::NoteCommitment;
pub mod legacy;
use legacy::LegacyNoteCommitmentTree;
#[cfg(any(test, feature = "proptest-impl"))]
use proptest_derive::Arbitrary;
pub(super) const MERKLE_DEPTH: u8 = 29;
fn merkle_crh_sprout(left: [u8; 32], right: [u8; 32]) -> [u8; 32] {
let mut other_block = [0u8; 64];
other_block[..32].copy_from_slice(&left[..]);
other_block[32..].copy_from_slice(&right[..]);
let mut state = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19,
];
sha2::compress256(&mut state, &[GenericArray::clone_from_slice(&other_block)]);
let mut derived_bytes = [0u8; 32];
BigEndian::write_u32_into(&state, &mut derived_bytes);
derived_bytes
}
lazy_static! {
pub(super) static ref EMPTY_ROOTS: Vec<[u8; 32]> = {
let mut v = vec![NoteCommitmentTree::uncommitted()];
for _ in 0..MERKLE_DEPTH {
v.insert(0, merkle_crh_sprout(v[0], v[0]));
}
v
};
}
#[derive(Clone, Copy, Default, Eq, PartialEq, Serialize, Deserialize, Hash)]
#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
pub struct Root([u8; 32]);
impl Root {
pub fn bytes_in_display_order(&self) -> [u8; 32] {
let mut root: [u8; 32] = self.into();
root.reverse();
root
}
}
impl fmt::Debug for Root {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Root").field(&hex::encode(self.0)).finish()
}
}
impl From<[u8; 32]> for Root {
fn from(bytes: [u8; 32]) -> Root {
Self(bytes)
}
}
impl From<Root> for [u8; 32] {
fn from(rt: Root) -> [u8; 32] {
rt.0
}
}
impl From<&[u8; 32]> for Root {
fn from(bytes: &[u8; 32]) -> Root {
(*bytes).into()
}
}
impl From<&Root> for [u8; 32] {
fn from(root: &Root) -> Self {
(*root).into()
}
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct Node([u8; 32]);
impl fmt::Debug for Node {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Node").field(&hex::encode(self.0)).finish()
}
}
impl incrementalmerkletree::Hashable for Node {
fn empty_leaf() -> Self {
Self(NoteCommitmentTree::uncommitted())
}
fn combine(_level: incrementalmerkletree::Level, a: &Self, b: &Self) -> Self {
Self(merkle_crh_sprout(a.0, b.0))
}
fn empty_root(level: incrementalmerkletree::Level) -> Self {
let layer_below = usize::from(MERKLE_DEPTH) - usize::from(level);
Self(EMPTY_ROOTS[layer_below])
}
}
impl From<NoteCommitment> for Node {
fn from(cm: NoteCommitment) -> Self {
Node(cm.into())
}
}
impl serde::Serialize for Node {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.serialize(serializer)
}
}
impl<'de> serde::Deserialize<'de> for Node {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let bytes = <[u8; 32]>::deserialize(deserializer)?;
let cm = NoteCommitment::from(bytes);
let node = Node::from(cm);
Ok(node)
}
}
#[derive(Error, Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[allow(missing_docs)]
pub enum NoteCommitmentTreeError {
#[error("the note commitment tree is full")]
FullTree,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(into = "LegacyNoteCommitmentTree")]
#[serde(from = "LegacyNoteCommitmentTree")]
pub struct NoteCommitmentTree {
inner: Frontier<Node, MERKLE_DEPTH>,
cached_root: std::sync::RwLock<Option<Root>>,
}
impl NoteCommitmentTree {
#[allow(clippy::unwrap_in_result)]
pub fn append(&mut self, cm: NoteCommitment) -> Result<(), NoteCommitmentTreeError> {
if self.inner.append(cm.into()) {
let cached_root = self
.cached_root
.get_mut()
.expect("a thread that previously held exclusive lock access panicked");
*cached_root = None;
Ok(())
} else {
Err(NoteCommitmentTreeError::FullTree)
}
}
pub fn root(&self) -> Root {
if let Some(root) = self.cached_root() {
return root;
}
let mut write_root = self
.cached_root
.write()
.expect("a thread that previously held exclusive lock access panicked");
let read_root = write_root.as_ref().cloned();
match read_root {
Some(root) => root,
None => {
let root = self.recalculate_root();
*write_root = Some(root);
root
}
}
}
#[allow(clippy::unwrap_in_result)]
pub fn cached_root(&self) -> Option<Root> {
*self
.cached_root
.read()
.expect("a thread that previously held exclusive lock access panicked")
}
pub fn recalculate_root(&self) -> Root {
Root(self.inner.root().0)
}
pub fn hash(&self) -> [u8; 32] {
self.root().into()
}
pub fn uncommitted() -> [u8; 32] {
[0; 32]
}
pub fn count(&self) -> u64 {
self.inner
.value()
.map_or(0, |x| u64::from(x.position()) + 1)
}
#[cfg(any(test, feature = "proptest-impl"))]
pub fn assert_frontier_eq(&self, other: &Self) {
assert_eq!(self.cached_root(), other.cached_root());
assert_eq!(self.inner, other.inner);
}
}
impl Clone for NoteCommitmentTree {
fn clone(&self) -> Self {
let cached_root = self.cached_root();
Self {
inner: self.inner.clone(),
cached_root: std::sync::RwLock::new(cached_root),
}
}
}
impl Default for NoteCommitmentTree {
fn default() -> Self {
Self {
inner: Frontier::empty(),
cached_root: Default::default(),
}
}
}
impl Eq for NoteCommitmentTree {}
impl PartialEq for NoteCommitmentTree {
fn eq(&self, other: &Self) -> bool {
if let (Some(root), Some(other_root)) = (self.cached_root(), other.cached_root()) {
root == other_root
} else {
self.inner == other.inner
}
}
}
impl From<Vec<NoteCommitment>> for NoteCommitmentTree {
fn from(values: Vec<NoteCommitment>) -> Self {
let mut tree = Self::default();
if values.is_empty() {
return tree;
}
for cm in values {
let _ = tree.append(cm);
}
tree
}
}