merkle.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. //! Implementation of a Merkle tree of commitments used to prove the existence
  2. //! of notes.
  3. //use byteorder::{LittleEndian, ReadBytesExt};
  4. use crate::serial::{Decodable, Encodable, VarInt};
  5. use crate::{Error, Result};
  6. use std::collections::VecDeque;
  7. use std::io;
  8. use std::io::{Read, Write};
  9. //use super::serialize::{Optional, Vector};
  10. use super::merkle_node::SAPLING_COMMITMENT_TREE_DEPTH;
  11. /// A hashable node within a Merkle tree.
  12. pub trait Hashable: Clone + Copy + Encodable + Decodable {
  13. /// Parses a node from the given byte source.
  14. fn read<R: Read>(reader: R) -> Result<Self>;
  15. /// Serializes this node.
  16. fn write<W: Write>(&self, writer: W) -> Result<()>;
  17. /// Returns the parent node within the tree of the two given nodes.
  18. fn combine(_: usize, _: &Self, _: &Self) -> Self;
  19. /// Returns a blank leaf node.
  20. fn blank() -> Self;
  21. /// Returns the empty root for the given depth.
  22. fn empty_root(_: usize) -> Self;
  23. }
  24. struct PathFiller<Node: Hashable> {
  25. queue: VecDeque<Node>,
  26. }
  27. impl<Node: Hashable> PathFiller<Node> {
  28. fn empty() -> Self {
  29. PathFiller {
  30. queue: VecDeque::new(),
  31. }
  32. }
  33. fn next(&mut self, depth: usize) -> Node {
  34. self.queue
  35. .pop_front()
  36. .unwrap_or_else(|| Node::empty_root(depth))
  37. }
  38. }
  39. /// A Merkle tree of note commitments.
  40. ///
  41. /// The depth of the Merkle tree is fixed at 32, equal to the depth of the
  42. /// Sapling commitment tree.
  43. #[derive(Clone)]
  44. pub struct CommitmentTree<Node: Hashable> {
  45. left: Option<Node>,
  46. right: Option<Node>,
  47. parents: Vec<Option<Node>>,
  48. }
  49. impl<Node: Hashable> CommitmentTree<Node> {
  50. /// Creates an empty tree.
  51. pub fn empty() -> Self {
  52. CommitmentTree {
  53. left: None,
  54. right: None,
  55. parents: vec![],
  56. }
  57. }
  58. /// Returns the number of leaf nodes in the tree.
  59. pub fn size(&self) -> usize {
  60. self.parents.iter().enumerate().fold(
  61. match (self.left, self.right) {
  62. (None, None) => 0,
  63. (Some(_), None) => 1,
  64. (Some(_), Some(_)) => 2,
  65. (None, Some(_)) => unreachable!(),
  66. },
  67. |acc, (i, p)| {
  68. // Treat occupation of parents array as a binary number
  69. // (right-shifted by 1)
  70. acc + if p.is_some() { 1 << (i + 1) } else { 0 }
  71. },
  72. )
  73. }
  74. fn is_complete(&self, depth: usize) -> bool {
  75. self.left.is_some()
  76. && self.right.is_some()
  77. && self.parents.len() == depth - 1
  78. && self.parents.iter().all(|p| p.is_some())
  79. }
  80. /// Adds a leaf node to the tree.
  81. ///
  82. /// Returns an error if the tree is full.
  83. pub fn append(&mut self, node: Node) -> Result<()> {
  84. self.append_inner(node, SAPLING_COMMITMENT_TREE_DEPTH)
  85. }
  86. fn append_inner(&mut self, node: Node, depth: usize) -> Result<()> {
  87. if self.is_complete(depth) {
  88. return Err(Error::TreeFull);
  89. }
  90. match (self.left, self.right) {
  91. (None, _) => self.left = Some(node),
  92. (_, None) => self.right = Some(node),
  93. (Some(l), Some(r)) => {
  94. let mut combined = Node::combine(0, &l, &r);
  95. self.left = Some(node);
  96. self.right = None;
  97. for i in 0..depth {
  98. if i < self.parents.len() {
  99. if let Some(p) = self.parents[i] {
  100. combined = Node::combine(i + 1, &p, &combined);
  101. self.parents[i] = None;
  102. } else {
  103. self.parents[i] = Some(combined);
  104. break;
  105. }
  106. } else {
  107. self.parents.push(Some(combined));
  108. break;
  109. }
  110. }
  111. }
  112. }
  113. Ok(())
  114. }
  115. /// Returns the current root of the tree.
  116. pub fn root(&self) -> Node {
  117. self.root_inner(SAPLING_COMMITMENT_TREE_DEPTH, PathFiller::empty())
  118. }
  119. fn root_inner(&self, depth: usize, mut filler: PathFiller<Node>) -> Node {
  120. assert!(depth > 0);
  121. // 1) Hash left and right leaves together.
  122. // - Empty leaves are used as needed.
  123. let leaf_root = Node::combine(
  124. 0,
  125. &self.left.unwrap_or_else(|| filler.next(0)),
  126. &self.right.unwrap_or_else(|| filler.next(0)),
  127. );
  128. // 2) Hash in parents up to the currently-filled depth.
  129. // - Roots of the empty subtrees are used as needed.
  130. let mid_root = self
  131. .parents
  132. .iter()
  133. .enumerate()
  134. .fold(leaf_root, |root, (i, p)| match p {
  135. Some(node) => Node::combine(i + 1, node, &root),
  136. None => Node::combine(i + 1, &root, &filler.next(i + 1)),
  137. });
  138. // 3) Hash in roots of the empty subtrees up to the final depth.
  139. ((self.parents.len() + 1)..depth)
  140. .fold(mid_root, |root, d| Node::combine(d, &root, &filler.next(d)))
  141. }
  142. }
  143. impl<Node: Hashable> Encodable for CommitmentTree<Node> {
  144. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  145. let mut len = 0;
  146. len += self.left.encode(&mut s)?;
  147. len += self.right.encode(&mut s)?;
  148. len += self.parents.encode(&mut s)?;
  149. Ok(len)
  150. }
  151. }
  152. impl<Node: Hashable> Decodable for CommitmentTree<Node> {
  153. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  154. Ok(Self {
  155. left: Decodable::decode(&mut d)?,
  156. right: Decodable::decode(&mut d)?,
  157. parents: Decodable::decode(&mut d)?,
  158. })
  159. }
  160. }
  161. /*
  162. /// An updatable witness to a path from a position in a particular
  163. /// [`CommitmentTree`].
  164. ///
  165. /// Appending the same commitments in the same order to both the original
  166. /// [`CommitmentTree`] and this `IncrementalWitness` will result in a witness to
  167. /// the path from the target position to the root of the updated tree.
  168. ///
  169. /// # Examples
  170. ///
  171. /// ```
  172. /// use ff::{Field, PrimeField};
  173. /// use rand_core::OsRng;
  174. /// use zcash_primitives::{
  175. /// merkle_tree::{CommitmentTree, IncrementalWitness},
  176. /// sapling::Node,
  177. /// };
  178. ///
  179. /// let mut rng = OsRng;
  180. ///
  181. /// let mut tree = CommitmentTree::<Node>::empty();
  182. ///
  183. /// tree.append(Node::new(bls12_381::Scalar::random(&mut rng).to_repr()));
  184. /// tree.append(Node::new(bls12_381::Scalar::random(&mut rng).to_repr()));
  185. /// let mut witness = IncrementalWitness::from_tree(&tree);
  186. /// assert_eq!(witness.position(), 1);
  187. /// assert_eq!(tree.root(), witness.root());
  188. ///
  189. /// let cmu = Node::new(bls12_381::Scalar::random(&mut rng).to_repr());
  190. /// tree.append(cmu);
  191. /// witness.append(cmu);
  192. /// assert_eq!(tree.root(), witness.root());
  193. /// ```
  194. ///
  195. */
  196. #[derive(Clone)]
  197. pub struct IncrementalWitness<Node: Hashable> {
  198. tree: CommitmentTree<Node>,
  199. filled: Vec<Node>,
  200. cursor_depth: usize,
  201. cursor: Option<CommitmentTree<Node>>,
  202. }
  203. impl<Node: Hashable> Encodable for IncrementalWitness<Node> {
  204. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  205. let mut len = 0;
  206. len += self.tree.encode(&mut s)?;
  207. len += VarInt(self.filled.len() as u64).encode(&mut s)?;
  208. for c in self.filled.iter() {
  209. len += c.encode(&mut s)?;
  210. }
  211. len += self.cursor_depth.encode(&mut s)?;
  212. if let Some(v) = &self.cursor {
  213. len += v.encode(&mut s)?;
  214. }
  215. Ok(len)
  216. }
  217. }
  218. impl<Node: Hashable> Decodable for IncrementalWitness<Node> {
  219. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  220. let tree = Decodable::decode(&mut d)?;
  221. let filled = {
  222. let len = VarInt::decode(&mut d)?.0;
  223. let mut ret = Vec::with_capacity(len as usize);
  224. for _ in 0..len {
  225. ret.push(Decodable::decode(&mut d)?);
  226. }
  227. ret
  228. };
  229. Ok(Self {
  230. tree,
  231. filled,
  232. cursor_depth: Decodable::decode(&mut d)?,
  233. cursor: Decodable::decode(d)?,
  234. })
  235. }
  236. }
  237. impl<Node: Hashable> IncrementalWitness<Node> {
  238. /// Creates an `IncrementalWitness` for the most recent commitment added to
  239. /// the given [`CommitmentTree`].
  240. pub fn from_tree(tree: &CommitmentTree<Node>) -> IncrementalWitness<Node> {
  241. IncrementalWitness {
  242. tree: tree.clone(),
  243. filled: vec![],
  244. cursor_depth: 0,
  245. cursor: None,
  246. }
  247. }
  248. /// Returns the position of the witnessed leaf node in the commitment tree.
  249. pub fn position(&self) -> usize {
  250. self.tree.size() - 1
  251. }
  252. fn filler(&self) -> PathFiller<Node> {
  253. let cursor_root = self
  254. .cursor
  255. .as_ref()
  256. .map(|c| c.root_inner(self.cursor_depth, PathFiller::empty()));
  257. PathFiller {
  258. queue: self.filled.iter().cloned().chain(cursor_root).collect(),
  259. }
  260. }
  261. /// Finds the next "depth" of an unfilled subtree.
  262. fn next_depth(&self) -> usize {
  263. let mut skip = self.filled.len();
  264. if self.tree.left.is_none() {
  265. if skip > 0 {
  266. skip -= 1;
  267. } else {
  268. return 0;
  269. }
  270. }
  271. if self.tree.right.is_none() {
  272. if skip > 0 {
  273. skip -= 1;
  274. } else {
  275. return 0;
  276. }
  277. }
  278. let mut d = 1;
  279. for p in &self.tree.parents {
  280. if p.is_none() {
  281. if skip > 0 {
  282. skip -= 1;
  283. } else {
  284. return d;
  285. }
  286. }
  287. d += 1;
  288. }
  289. d + skip
  290. }
  291. /// Tracks a leaf node that has been added to the underlying tree.
  292. ///
  293. /// Returns an error if the tree is full.
  294. pub fn append(&mut self, node: Node) -> Result<()> {
  295. self.append_inner(node, SAPLING_COMMITMENT_TREE_DEPTH)
  296. }
  297. fn append_inner(&mut self, node: Node, depth: usize) -> Result<()> {
  298. if let Some(mut cursor) = self.cursor.take() {
  299. cursor
  300. .append_inner(node, depth)
  301. .expect("cursor should not be full");
  302. if cursor.is_complete(self.cursor_depth) {
  303. self.filled
  304. .push(cursor.root_inner(self.cursor_depth, PathFiller::empty()));
  305. } else {
  306. self.cursor = Some(cursor);
  307. }
  308. } else {
  309. self.cursor_depth = self.next_depth();
  310. if self.cursor_depth >= depth {
  311. return Err(Error::TreeFull);
  312. }
  313. if self.cursor_depth == 0 {
  314. self.filled.push(node);
  315. } else {
  316. let mut cursor = CommitmentTree::empty();
  317. cursor
  318. .append_inner(node, depth)
  319. .expect("cursor should not be full");
  320. self.cursor = Some(cursor);
  321. }
  322. }
  323. Ok(())
  324. }
  325. /// Returns the current root of the tree corresponding to the witness.
  326. pub fn root(&self) -> Node {
  327. self.root_inner(SAPLING_COMMITMENT_TREE_DEPTH)
  328. }
  329. fn root_inner(&self, depth: usize) -> Node {
  330. self.tree.root_inner(depth, self.filler())
  331. }
  332. /// Returns the current witness, or None if the tree is empty.
  333. pub fn path(&self) -> Option<MerklePath<Node>> {
  334. self.path_inner(SAPLING_COMMITMENT_TREE_DEPTH)
  335. }
  336. fn path_inner(&self, depth: usize) -> Option<MerklePath<Node>> {
  337. let mut filler = self.filler();
  338. let mut auth_path = Vec::new();
  339. if let Some(node) = self.tree.left {
  340. if self.tree.right.is_some() {
  341. auth_path.push((node, true));
  342. } else {
  343. auth_path.push((filler.next(0), false));
  344. }
  345. } else {
  346. // Can't create an authentication path for the beginning of the tree
  347. return None;
  348. }
  349. for (i, p) in self.tree.parents.iter().enumerate() {
  350. auth_path.push(match p {
  351. Some(node) => (*node, true),
  352. None => (filler.next(i + 1), false),
  353. });
  354. }
  355. for i in self.tree.parents.len()..(depth - 1) {
  356. auth_path.push((filler.next(i + 1), false));
  357. }
  358. assert_eq!(auth_path.len(), depth);
  359. Some(MerklePath::from_path(auth_path, self.position() as u64))
  360. }
  361. }
  362. /// A path from a position in a particular commitment tree to the root of that
  363. /// tree.
  364. #[derive(Clone, Debug, PartialEq)]
  365. pub struct MerklePath<Node: Hashable> {
  366. pub auth_path: Vec<(Node, bool)>,
  367. pub position: u64,
  368. }
  369. impl<Node: Hashable> MerklePath<Node> {
  370. /// Constructs a Merkle path directly from a path and position.
  371. pub fn from_path(auth_path: Vec<(Node, bool)>, position: u64) -> Self {
  372. MerklePath {
  373. auth_path,
  374. position,
  375. }
  376. }
  377. /// Returns the root of the tree corresponding to this path applied to
  378. /// `leaf`.
  379. pub fn root(&self, leaf: Node) -> Node {
  380. self.auth_path
  381. .iter()
  382. .enumerate()
  383. .fold(
  384. leaf,
  385. |root, (i, (p, leaf_is_on_right))| match leaf_is_on_right {
  386. false => Node::combine(i, &root, p),
  387. true => Node::combine(i, p, &root),
  388. },
  389. )
  390. }
  391. }