merkle_node.rs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. use std::{io, iter};
  2. use halo2_gadgets::primitives::sinsemilla::HashDomain;
  3. use incrementalmerkletree::{Altitude, Hashable};
  4. use lazy_static::lazy_static;
  5. use pasta_curves::{
  6. group::ff::{PrimeField, PrimeFieldBits},
  7. pallas,
  8. };
  9. use serde::{
  10. de::{Deserializer, Error},
  11. ser::Serializer,
  12. Deserialize, Serialize,
  13. };
  14. use subtle::{Choice, ConditionallySelectable, CtOption};
  15. use crate::{
  16. crypto::{
  17. coin::Coin,
  18. constants::{
  19. sinsemilla::{i2lebsp_k, MERKLE_CRH_PERSONALIZATION},
  20. L_ORCHARD_MERKLE, MERKLE_DEPTH_ORCHARD,
  21. },
  22. },
  23. util::serial::{Decodable, Encodable},
  24. Result,
  25. };
  26. lazy_static! {
  27. static ref UNCOMMITTED_ORCHARD: pallas::Base = pallas::Base::from(2);
  28. static ref EMPTY_ROOTS: Vec<MerkleNode> = {
  29. iter::empty()
  30. .chain(Some(MerkleNode::empty_leaf()))
  31. .chain((0..MERKLE_DEPTH_ORCHARD).scan(MerkleNode::empty_leaf(), |state, l| {
  32. let l = l as u8;
  33. *state = MerkleNode::combine(l.into(), state, state);
  34. Some(*state)
  35. }))
  36. .collect()
  37. };
  38. }
  39. #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
  40. pub struct MerkleNode(pub pallas::Base);
  41. impl MerkleNode {
  42. pub fn to_bytes(&self) -> [u8; 32] {
  43. self.0.to_repr()
  44. }
  45. pub fn from_bytes(bytes: &[u8; 32]) -> CtOption<Self> {
  46. pallas::Base::from_repr(*bytes).map(MerkleNode)
  47. }
  48. pub fn from_coin(coin: &Coin) -> Self {
  49. MerkleNode(coin.0)
  50. }
  51. pub fn inner(&self) -> pallas::Base {
  52. self.0
  53. }
  54. }
  55. impl Serialize for MerkleNode {
  56. fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
  57. self.to_bytes().serialize(serializer)
  58. }
  59. }
  60. impl<'de> Deserialize<'de> for MerkleNode {
  61. fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
  62. let parsed = <[u8; 32]>::deserialize(deserializer)?;
  63. <Option<_>>::from(Self::from_bytes(&parsed)).ok_or_else(|| {
  64. Error::custom("Attempted to deserialize a non-canonical representation of a Pallas base field element")
  65. })
  66. }
  67. }
  68. impl ConditionallySelectable for MerkleNode {
  69. fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
  70. MerkleNode(pallas::Base::conditional_select(&a.0, &b.0, choice))
  71. }
  72. }
  73. impl Hashable for MerkleNode {
  74. fn empty_leaf() -> Self {
  75. MerkleNode(*UNCOMMITTED_ORCHARD)
  76. }
  77. /// Implements `MerkleCRH^Orchard` as defined in
  78. /// <https://zips.z.cash/protocol/protocol.pdf#orchardmerklecrh>
  79. ///
  80. /// The layer with 2^n nodes is called "layer n":
  81. /// - leaves are at layer MERKLE_DEPTH_ORCHARD = 32;
  82. /// - the root is at layer 0.
  83. /// `l` is MERKLE_DEPTH_ORCHARD - layer - 1.
  84. /// - when hashing two leaves, we produce a node on the layer above the leaves, i.e. layer
  85. /// = 31, l = 0
  86. /// - when hashing to the final root, we produce the anchor with layer = 0, l = 31.
  87. fn combine(altitude: Altitude, left: &Self, right: &Self) -> Self {
  88. // MerkleCRH Sinsemilla hash domain.
  89. let domain = HashDomain::new(MERKLE_CRH_PERSONALIZATION);
  90. MerkleNode(
  91. domain
  92. .hash(
  93. iter::empty()
  94. .chain(i2lebsp_k(altitude.into()).iter().copied())
  95. .chain(left.0.to_le_bits().iter().by_val().take(L_ORCHARD_MERKLE))
  96. .chain(right.0.to_le_bits().iter().by_val().take(L_ORCHARD_MERKLE)),
  97. )
  98. .unwrap_or(pallas::Base::zero()),
  99. )
  100. }
  101. fn empty_root(altitude: Altitude) -> Self {
  102. EMPTY_ROOTS[<usize>::from(altitude)]
  103. }
  104. }
  105. impl Encodable for MerkleNode {
  106. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  107. self.0.encode(&mut s)
  108. }
  109. }
  110. impl Decodable for MerkleNode {
  111. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  112. Ok(Self(Decodable::decode(&mut d)?))
  113. }
  114. }
  115. impl Encodable for incrementalmerkletree::Position {
  116. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  117. u64::from(*self).encode(&mut s)
  118. }
  119. }
  120. impl Decodable for incrementalmerkletree::Position {
  121. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  122. let dec: u64 = Decodable::decode(&mut d)?;
  123. Ok(Self::try_from(dec).unwrap())
  124. }
  125. }