2021-06-17 18:17:47 -07:00
|
|
|
/// Sample implementation of the Tree interface.
|
2021-06-17 18:24:18 -07:00
|
|
|
use super::{Hashable, Level, Recording, Tree};
|
2021-06-17 18:17:47 -07:00
|
|
|
|
|
|
|
#[derive(Clone)]
|
2021-06-17 18:24:18 -07:00
|
|
|
pub struct CompleteTree<H: Hashable> {
|
|
|
|
leaves: Vec<H>,
|
2021-06-17 18:17:47 -07:00
|
|
|
current_position: usize,
|
2021-06-17 18:24:18 -07:00
|
|
|
witnesses: Vec<(usize, H)>,
|
2021-06-17 18:17:47 -07:00
|
|
|
checkpoints: Vec<usize>,
|
|
|
|
depth: usize,
|
2021-06-17 18:24:18 -07:00
|
|
|
max_checkpoints: usize,
|
2021-06-17 18:17:47 -07:00
|
|
|
}
|
|
|
|
|
2021-06-17 18:24:18 -07:00
|
|
|
impl<H: Hashable + Clone> CompleteTree<H> {
|
2021-06-17 18:17:47 -07:00
|
|
|
/// Creates a new, empty binary tree of specified depth.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// Panics if the specified depth is zero.
|
2021-06-17 18:24:18 -07:00
|
|
|
pub fn new(depth: usize, max_checkpoints: usize) -> Self {
|
2021-06-17 18:17:47 -07:00
|
|
|
if depth == 0 {
|
|
|
|
panic!("invalid depth for incremental merkle tree");
|
|
|
|
}
|
|
|
|
|
|
|
|
CompleteTree {
|
|
|
|
leaves: vec![H::empty_leaf(); 1 << depth],
|
|
|
|
current_position: 0,
|
|
|
|
witnesses: vec![],
|
|
|
|
checkpoints: vec![],
|
|
|
|
depth,
|
2021-06-17 18:24:18 -07:00
|
|
|
max_checkpoints,
|
2021-06-17 18:17:47 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-17 18:24:18 -07:00
|
|
|
impl<H: Hashable + PartialEq + Clone> CompleteTree<H> {
|
|
|
|
/// Removes the oldest checkpoint. Returns true if successful and false if
|
|
|
|
/// there are no checkpoints.
|
|
|
|
fn drop_oldest_checkpoint(&mut self) -> bool {
|
|
|
|
if self.checkpoints.is_empty() {
|
|
|
|
false
|
|
|
|
} else {
|
|
|
|
self.checkpoints.remove(0);
|
|
|
|
true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<H: Hashable + PartialEq + Clone> Tree<H> for CompleteTree<H> {
|
2021-06-17 18:17:47 -07:00
|
|
|
type Recording = CompleteRecording<H>;
|
|
|
|
|
|
|
|
/// Appends a new value to the tree at the next available slot. Returns true
|
|
|
|
/// if successful and false if the tree is full.
|
2021-06-17 18:24:18 -07:00
|
|
|
fn append(&mut self, value: &H) -> bool {
|
2021-06-17 18:17:47 -07:00
|
|
|
if self.current_position == (1 << self.depth) {
|
|
|
|
false
|
|
|
|
} else {
|
|
|
|
self.leaves[self.current_position] = value.clone();
|
|
|
|
self.current_position += 1;
|
|
|
|
true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Obtains the current root of this Merkle tree.
|
2021-06-17 18:24:18 -07:00
|
|
|
fn root(&self) -> H {
|
|
|
|
lazy_root(self.leaves.clone())
|
2021-06-17 18:17:47 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Marks the current tree state leaf as a value that we're interested in
|
|
|
|
/// witnessing. Returns true if successful and false if the tree is empty.
|
|
|
|
fn witness(&mut self) -> bool {
|
|
|
|
if self.current_position == 0 {
|
2021-06-17 18:24:18 -07:00
|
|
|
false
|
2021-06-17 18:17:47 -07:00
|
|
|
} else {
|
|
|
|
let value = self.leaves[self.current_position - 1].clone();
|
2021-06-17 18:24:18 -07:00
|
|
|
if !self.witnesses.iter().any(|(_, v)| v == &value) {
|
|
|
|
self.witnesses.push((self.current_position - 1, value));
|
|
|
|
}
|
2021-06-17 18:17:47 -07:00
|
|
|
true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Obtains an authentication path to the value specified in the tree.
|
|
|
|
/// Returns `None` if there is no available authentication path to the
|
|
|
|
/// specified value.
|
2021-06-17 18:24:18 -07:00
|
|
|
fn authentication_path(&self, value: &H) -> Option<(usize, Vec<H>)> {
|
2021-06-17 18:17:47 -07:00
|
|
|
self.witnesses
|
|
|
|
.iter()
|
|
|
|
.find(|witness| witness.1 == *value)
|
|
|
|
.map(|&(pos, _)| {
|
|
|
|
let mut path = vec![];
|
|
|
|
|
|
|
|
let mut index = pos;
|
|
|
|
for bit in 0..self.depth {
|
|
|
|
index ^= 1 << bit;
|
|
|
|
path.push(lazy_root::<H>(self.leaves[index..][0..(1 << bit)].to_vec()));
|
|
|
|
index &= usize::MAX << (bit + 1);
|
|
|
|
}
|
|
|
|
|
|
|
|
(pos, path)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Marks the specified tree state value as a value we're no longer
|
|
|
|
/// interested in maintaining a witness for. Returns true if successful and
|
|
|
|
/// false if the value is not a known witness.
|
2021-06-17 18:24:18 -07:00
|
|
|
fn remove_witness(&mut self, value: &H) -> bool {
|
2021-06-17 18:17:47 -07:00
|
|
|
if let Some((position, _)) = self
|
|
|
|
.witnesses
|
|
|
|
.iter()
|
|
|
|
.enumerate()
|
|
|
|
.find(|witness| (witness.1).1 == *value)
|
|
|
|
{
|
|
|
|
self.witnesses.remove(position);
|
|
|
|
|
|
|
|
true
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Marks the current tree state as a checkpoint if it is not already a
|
|
|
|
/// checkpoint.
|
|
|
|
fn checkpoint(&mut self) {
|
|
|
|
self.checkpoints.push(self.current_position);
|
2021-06-17 18:24:18 -07:00
|
|
|
if self.checkpoints.len() > self.max_checkpoints {
|
|
|
|
self.drop_oldest_checkpoint();
|
|
|
|
}
|
2021-06-17 18:17:47 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Rewinds the tree state to the previous checkpoint. This function will
|
|
|
|
/// fail and return false if there is no previous checkpoint or in the event
|
|
|
|
/// witness data would be destroyed in the process.
|
|
|
|
fn rewind(&mut self) -> bool {
|
|
|
|
if let Some(checkpoint) = self.checkpoints.pop() {
|
|
|
|
if self.witnesses.iter().any(|&(pos, _)| pos >= checkpoint) {
|
|
|
|
self.checkpoints.push(checkpoint);
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
self.current_position = checkpoint;
|
|
|
|
if checkpoint != (1 << self.depth) {
|
|
|
|
self.leaves[checkpoint..].fill(H::empty_leaf());
|
|
|
|
}
|
|
|
|
|
|
|
|
true
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Start a recording of append operations performed on a tree.
|
|
|
|
fn recording(&self) -> CompleteRecording<H> {
|
|
|
|
CompleteRecording {
|
|
|
|
start_position: self.current_position,
|
|
|
|
current_position: self.current_position,
|
|
|
|
depth: self.depth,
|
|
|
|
appends: vec![],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Plays a recording of append operations back. Returns true if successful
|
|
|
|
/// and false if the recording is incompatible with the current tree state.
|
|
|
|
fn play(&mut self, recording: &CompleteRecording<H>) -> bool {
|
2021-06-17 18:24:18 -07:00
|
|
|
#[allow(clippy::suspicious_operation_groupings)]
|
2021-06-17 18:17:47 -07:00
|
|
|
if recording.start_position == self.current_position && self.depth == recording.depth {
|
|
|
|
for val in recording.appends.iter() {
|
|
|
|
self.append(val);
|
|
|
|
}
|
|
|
|
true
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
2021-06-17 18:24:18 -07:00
|
|
|
pub struct CompleteRecording<H: Hashable> {
|
2021-06-17 18:17:47 -07:00
|
|
|
start_position: usize,
|
|
|
|
current_position: usize,
|
|
|
|
depth: usize,
|
2021-06-17 18:24:18 -07:00
|
|
|
appends: Vec<H>,
|
2021-06-17 18:17:47 -07:00
|
|
|
}
|
|
|
|
|
2021-06-17 18:24:18 -07:00
|
|
|
impl<H: Hashable + Clone> Recording<H> for CompleteRecording<H> {
|
2021-06-17 18:17:47 -07:00
|
|
|
/// Appends a new value to the tree at the next available slot. Returns true
|
|
|
|
/// if successful and false if the tree is full.
|
2021-06-17 18:24:18 -07:00
|
|
|
fn append(&mut self, value: &H) -> bool {
|
2021-06-17 18:17:47 -07:00
|
|
|
if self.current_position == (1 << self.depth) {
|
|
|
|
false
|
|
|
|
} else {
|
|
|
|
self.appends.push(value.clone());
|
|
|
|
self.current_position += 1;
|
|
|
|
|
|
|
|
true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Plays a recording of append operations back. Returns true if successful
|
|
|
|
/// and false if the provided recording is incompatible with `Self`.
|
|
|
|
fn play(&mut self, recording: &Self) -> bool {
|
2021-06-17 18:24:18 -07:00
|
|
|
#[allow(clippy::suspicious_operation_groupings)]
|
2021-06-17 18:17:47 -07:00
|
|
|
if self.current_position == recording.start_position && self.depth == recording.depth {
|
|
|
|
self.appends.extend_from_slice(&recording.appends);
|
|
|
|
self.current_position = recording.current_position;
|
|
|
|
true
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-17 18:24:18 -07:00
|
|
|
pub(crate) fn lazy_root<H: Hashable + Clone>(mut leaves: Vec<H>) -> H {
|
|
|
|
//leaves are always at level zero, so we start there.
|
|
|
|
let mut level = Level::zero();
|
2021-06-17 18:17:47 -07:00
|
|
|
while leaves.len() != 1 {
|
|
|
|
leaves = leaves
|
|
|
|
.iter()
|
|
|
|
.enumerate()
|
|
|
|
.filter(|(i, _)| (i % 2) == 0)
|
|
|
|
.map(|(_, a)| a)
|
|
|
|
.zip(
|
|
|
|
leaves
|
|
|
|
.iter()
|
|
|
|
.enumerate()
|
|
|
|
.filter(|(i, _)| (i % 2) == 1)
|
|
|
|
.map(|(_, b)| b),
|
|
|
|
)
|
2021-06-17 18:24:18 -07:00
|
|
|
.map(|(a, b)| H::combine(level, a, b))
|
2021-06-17 18:17:47 -07:00
|
|
|
.collect();
|
2021-06-17 18:24:18 -07:00
|
|
|
level = level + 1;
|
2021-06-17 18:17:47 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
leaves[0].clone()
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2021-06-17 18:24:18 -07:00
|
|
|
use crate::tests::{compute_root_from_auth_path, SipHashable};
|
|
|
|
use crate::{Hashable, Level, Tree};
|
2021-06-17 18:17:47 -07:00
|
|
|
|
|
|
|
use super::CompleteTree;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn correct_empty_root() {
|
2021-06-17 18:24:18 -07:00
|
|
|
const DEPTH: u32 = 5;
|
|
|
|
let mut expected = SipHashable(0u64);
|
|
|
|
for lvl in 0u32..DEPTH {
|
|
|
|
expected = SipHashable::combine(lvl.into(), &expected, &expected);
|
2021-06-17 18:17:47 -07:00
|
|
|
}
|
|
|
|
|
2021-06-17 18:24:18 -07:00
|
|
|
let tree = CompleteTree::<SipHashable>::new(DEPTH as usize, 100);
|
2021-06-17 18:17:47 -07:00
|
|
|
assert_eq!(tree.root(), expected);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn correct_root() {
|
|
|
|
const DEPTH: usize = 3;
|
2021-06-17 18:24:18 -07:00
|
|
|
let values = (0..(1 << DEPTH)).into_iter().map(SipHashable);
|
2021-06-17 18:17:47 -07:00
|
|
|
|
2021-06-17 18:24:18 -07:00
|
|
|
let mut tree = CompleteTree::<SipHashable>::new(DEPTH, 100);
|
|
|
|
for value in values {
|
|
|
|
assert!(tree.append(&value));
|
2021-06-17 18:17:47 -07:00
|
|
|
}
|
2021-06-17 18:24:18 -07:00
|
|
|
assert!(!tree.append(&SipHashable(0)));
|
|
|
|
|
|
|
|
let expected = SipHashable::combine(
|
|
|
|
<Level>::from(2),
|
|
|
|
&SipHashable::combine(
|
|
|
|
Level::one(),
|
|
|
|
&SipHashable::combine(Level::zero(), &SipHashable(0), &SipHashable(1)),
|
|
|
|
&SipHashable::combine(Level::zero(), &SipHashable(2), &SipHashable(3)),
|
|
|
|
),
|
|
|
|
&SipHashable::combine(
|
|
|
|
Level::one(),
|
|
|
|
&SipHashable::combine(Level::zero(), &SipHashable(4), &SipHashable(5)),
|
|
|
|
&SipHashable::combine(Level::zero(), &SipHashable(6), &SipHashable(7)),
|
|
|
|
),
|
2021-06-17 18:17:47 -07:00
|
|
|
);
|
|
|
|
|
|
|
|
assert_eq!(tree.root(), expected);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn correct_auth_path() {
|
|
|
|
const DEPTH: usize = 3;
|
2021-06-17 18:24:18 -07:00
|
|
|
let values = (0..(1 << DEPTH)).into_iter().map(SipHashable);
|
2021-06-17 18:17:47 -07:00
|
|
|
|
2021-06-17 18:24:18 -07:00
|
|
|
let mut tree = CompleteTree::<SipHashable>::new(DEPTH, 100);
|
|
|
|
for value in values {
|
|
|
|
assert!(tree.append(&value));
|
2021-06-17 18:17:47 -07:00
|
|
|
tree.witness();
|
|
|
|
}
|
2021-06-17 18:24:18 -07:00
|
|
|
assert!(!tree.append(&SipHashable(0)));
|
|
|
|
|
|
|
|
let expected = SipHashable::combine(
|
|
|
|
<Level>::from(2),
|
|
|
|
&SipHashable::combine(
|
|
|
|
Level::one(),
|
|
|
|
&SipHashable::combine(Level::zero(), &SipHashable(0), &SipHashable(1)),
|
|
|
|
&SipHashable::combine(Level::zero(), &SipHashable(2), &SipHashable(3)),
|
|
|
|
),
|
|
|
|
&SipHashable::combine(
|
|
|
|
Level::one(),
|
|
|
|
&SipHashable::combine(Level::zero(), &SipHashable(4), &SipHashable(5)),
|
|
|
|
&SipHashable::combine(Level::zero(), &SipHashable(6), &SipHashable(7)),
|
|
|
|
),
|
2021-06-17 18:17:47 -07:00
|
|
|
);
|
|
|
|
|
|
|
|
assert_eq!(tree.root(), expected);
|
|
|
|
|
|
|
|
for i in 0..(1 << DEPTH) {
|
2021-06-17 18:24:18 -07:00
|
|
|
let (position, path) = tree.authentication_path(&SipHashable(i)).unwrap();
|
2021-06-17 18:17:47 -07:00
|
|
|
assert_eq!(
|
2021-06-17 18:24:18 -07:00
|
|
|
compute_root_from_auth_path(SipHashable(i), position, &path),
|
2021-06-17 18:17:47 -07:00
|
|
|
expected
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|