Skip to main content

heika_core/
patricia.rs

1//! 状態の Patricia Merkle の木と、その証明。catapult の `tree/TreeNode.cpp`、`tree/PatriciaTree.h`、
2//! `tree/PatriciaTreeSerializer.cpp`、`cache/CatapultCache.cpp`。
3//!
4//! ノードは状態を種類ごとに9本の木に分けて持ち、それぞれの根を並べた SHA3-256 が、ブロックのヘッダーの StateHash になる。
5//! 木のキーは、種類ごとに決まったキーのバイト列の SHA3-256 で、値は状態のバイト列の SHA3-256。
6//! キーを16進の1桁(ニブル)ずつたどる木で、たどった先のノードを根から順に並べたものが、
7//! そのキーが木に「ある」こと(とその値)か、「ない」ことの証明になる。
8
9use alloc::boxed::Box;
10use alloc::vec;
11use alloc::vec::Vec;
12use core::fmt;
13
14use sha3::{Digest, Sha3_256};
15
16use crate::address::Address;
17use crate::hash::Hash256;
18
19/// キーのニブルの数。キーは SHA3-256 なので64。
20const KEY_NIBBLES: usize = 64;
21
22/// StateHash の元になる9本の木。catapult の `CacheId` のうち、木を持つものを同じ順に並べる。
23#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
24pub enum SubCache {
25    /// アカウント。キーはアドレス
26    AccountState,
27    /// ネームスペース。キーはルートのネームスペースの ID
28    Namespace,
29    /// モザイク。キーはモザイクの ID
30    Mosaic,
31    /// マルチシグ。キーはアドレス
32    Multisig,
33    /// ハッシュロック。キーはロックしたアグリゲートのハッシュ
34    HashLockInfo,
35    /// シークレットロック。キーはシークレットと受取人から求めたハッシュ
36    SecretLockInfo,
37    /// アカウントの制限。キーはアドレス
38    AccountRestriction,
39    /// モザイクの制限。キーはモザイクの ID とアドレスから求めたハッシュ
40    MosaicRestriction,
41    /// メタデータ。キーはメタデータの1件を指すハッシュ
42    Metadata,
43}
44
45impl SubCache {
46    /// StateHash に並べる順。
47    pub const ALL: [Self; 9] = [
48        Self::AccountState,
49        Self::Namespace,
50        Self::Mosaic,
51        Self::Multisig,
52        Self::HashLockInfo,
53        Self::SecretLockInfo,
54        Self::AccountRestriction,
55        Self::MosaicRestriction,
56        Self::Metadata,
57    ];
58
59    /// 9本の根の中での位置。
60    pub fn index(self) -> usize {
61        Self::ALL
62            .iter()
63            .position(|&cache| cache == self)
64            .expect("listed in ALL")
65    }
66}
67
68/// 9本の木の根から StateHash を求める。catapult の `CalculateStateHash`。根を順に続けた SHA3-256。
69pub fn state_hash(roots: &[Hash256; 9]) -> Hash256 {
70    let mut hasher = Sha3_256::new();
71    for root in roots {
72        hasher.update(root.0);
73    }
74    Hash256(hasher.finalize().into())
75}
76
77/// アドレスをキーにする木(アカウント、マルチシグ、アカウントの制限)の、木のキー。
78pub fn address_key(address: &Address) -> Hash256 {
79    key(&address.0)
80}
81
82/// ID をキーにする木(ネームスペース、モザイク)の、木のキー。ID はリトルエンディアンの8バイトにする。
83pub fn id_key(id: u64) -> Hash256 {
84    key(&id.to_le_bytes())
85}
86
87/// ハッシュをキーにする木(ロック2種類、モザイクの制限、メタデータ)の、木のキー。
88pub fn hash_key(hash: &Hash256) -> Hash256 {
89    key(&hash.0)
90}
91
92/// catapult の `SerializerHashedKeyEncoder`。キーのバイト列の SHA3-256。
93fn key(bytes: &[u8]) -> Hash256 {
94    Hash256(Sha3_256::digest(bytes).into())
95}
96
97/// 木のノード。経路はニブル(0 から 15)の並び。
98#[derive(Clone, PartialEq, Eq, Debug)]
99pub enum TreeNode {
100    /// 葉。経路はキーの残りすべてで、値は状態のハッシュ
101    Leaf { path: Vec<u8>, value: Hash256 },
102    /// 枝。経路のあとに、次のニブルごとの子のハッシュを持つ
103    Branch {
104        path: Vec<u8>,
105        links: Box<[Option<Hash256>; 16]>,
106    },
107}
108
109impl TreeNode {
110    /// ノードのハッシュ。catapult の `LeafTreeNode` と `BranchTreeNode` の `hash`。
111    /// 符号化した経路に、葉なら値を、枝なら16の子のハッシュ(ないところは0)を続けた SHA3-256。
112    pub fn hash(&self) -> Hash256 {
113        let mut hasher = Sha3_256::new();
114        match self {
115            Self::Leaf { path, value } => {
116                hasher.update(encode_path(path, true));
117                hasher.update(value.0);
118            }
119            Self::Branch { path, links } => {
120                hasher.update(encode_path(path, false));
121                for link in links {
122                    hasher.update(link.unwrap_or(Hash256([0; 32])).0);
123                }
124            }
125        }
126        Hash256(hasher.finalize().into())
127    }
128
129    pub fn path(&self) -> &[u8] {
130        match self {
131            Self::Leaf { path, .. } | Self::Branch { path, .. } => path,
132        }
133    }
134
135    /// ノードを並べたバイト列から読む。catapult の `PatriciaTreeSerializer` の形で、ノードの状態の経路を問い合わせた答えもこれ。
136    ///
137    /// ```text
138    /// 葉  u8 0xFF  u8 ニブルの数  経路(2ニブルで1バイト、奇数なら最後の下位は0)  [32] 値
139    /// 枝  u8 0x00  u8 ニブルの数  経路  u16 子があるところのビット  [32] 子のハッシュをビットの順に
140    /// ```
141    pub fn decode_all(bytes: &[u8]) -> Result<Vec<Self>, TreeNodeDecodeError> {
142        let mut rest = bytes;
143        let mut nodes = Vec::new();
144        while let Some((&marker, after)) = rest.split_first() {
145            let offset = bytes.len() - rest.len();
146            let mut reader = Reader::new(after);
147            let node = match marker {
148                0xFF => {
149                    let path = reader
150                        .path()
151                        .ok_or(TreeNodeDecodeError::TooShort { offset })?;
152                    let value = reader
153                        .hash()
154                        .ok_or(TreeNodeDecodeError::TooShort { offset })?;
155                    Self::Leaf { path, value }
156                }
157                0x00 => {
158                    let path = reader
159                        .path()
160                        .ok_or(TreeNodeDecodeError::TooShort { offset })?;
161                    let mask = reader
162                        .take(2)
163                        .map(|bytes| u16::from_le_bytes([bytes[0], bytes[1]]))
164                        .ok_or(TreeNodeDecodeError::TooShort { offset })?;
165                    let mut links = [None; 16];
166                    for (index, link) in links.iter_mut().enumerate() {
167                        if mask & (1 << index) != 0 {
168                            *link = Some(
169                                reader
170                                    .hash()
171                                    .ok_or(TreeNodeDecodeError::TooShort { offset })?,
172                            );
173                        }
174                    }
175                    Self::Branch {
176                        path,
177                        links: Box::new(links),
178                    }
179                }
180                marker => return Err(TreeNodeDecodeError::UnknownMarker { offset, marker }),
181            };
182            if !reader.filler_is_zero {
183                return Err(TreeNodeDecodeError::NonZeroFiller { offset });
184            }
185            nodes.push(node);
186            rest = reader.rest;
187        }
188        Ok(nodes)
189    }
190
191    /// [`TreeNode::decode_all`] の形の1つのノードにする。経路のニブルが奇数なら、最後のバイトの下位は0
192    pub fn encode(&self) -> Vec<u8> {
193        let (marker, path) = match self {
194            Self::Leaf { path, .. } => (0xFF, path),
195            Self::Branch { path, .. } => (0x00, path),
196        };
197        let mut out = vec![marker, path.len() as u8];
198        out.extend(
199            path.chunks(2)
200                .map(|pair| (pair[0] << 4) | pair.get(1).copied().unwrap_or(0)),
201        );
202        match self {
203            Self::Leaf { value, .. } => out.extend_from_slice(&value.0),
204            Self::Branch { links, .. } => {
205                let mask = links
206                    .iter()
207                    .enumerate()
208                    .filter(|(_, link)| link.is_some())
209                    .fold(0u16, |mask, (index, _)| mask | (1 << index));
210                out.extend_from_slice(&mask.to_le_bytes());
211                for link in links.iter().flatten() {
212                    out.extend_from_slice(&link.0);
213                }
214            }
215        }
216        out
217    }
218}
219
220/// ハッシュに使う経路の符号化。catapult の `UpdateEncodedKey`。
221/// 先頭の1バイトは、葉なら 0x20、ニブルが奇数なら 0x10 と最初のニブルを足す。残りは2ニブルずつ1バイトにする。
222fn encode_path(path: &[u8], is_leaf: bool) -> Vec<u8> {
223    let mut encoded = vec![if is_leaf { 0x20 } else { 0 }];
224    let rest = if path.len() % 2 == 1 {
225        encoded[0] |= 0x10 | path[0];
226        &path[1..]
227    } else {
228        path
229    };
230    encoded.extend(rest.chunks(2).map(|pair| (pair[0] << 4) | pair[1]));
231    encoded
232}
233
234/// キーを16進の1桁ずつに分ける。上位のニブルが先。
235fn nibbles(key: &Hash256) -> [u8; KEY_NIBBLES] {
236    core::array::from_fn(|index| {
237        let byte = key.0[index / 2];
238        if index % 2 == 0 {
239            byte >> 4
240        } else {
241            byte & 0x0F
242        }
243    })
244}
245
246/// 根から順に並べたノードで、`key` が根 `root` の木にあるかを確かめる。catapult の `PatriciaTree::lookup` が
247/// 返すノードの並びを、根からたどり直す。あれば `Some(値)`、ないことが示されれば `None`。
248///
249/// 並びは、根のハッシュから始めて、それぞれのノードのハッシュが1つ前の枝の、キーの次のニブルの子と合っていなければならない。
250/// ないことは、キーがどこかのノードの経路と食い違うか、枝の次のニブルに子がないことで示される。
251/// 空の木(根が全部0)には何もない。
252///
253/// 公式の SDK の `prove_patricia_merkle` と違い、葉で食い違って終わる「ない」の証明も受け付ける。
254pub fn prove(
255    key: &Hash256,
256    nodes: &[TreeNode],
257    root: &Hash256,
258) -> Result<Option<Hash256>, PatriciaProofError> {
259    if nodes.is_empty() {
260        return if *root == Hash256([0; 32]) {
261            Ok(None)
262        } else {
263            Err(PatriciaProofError::Incomplete)
264        };
265    }
266    let key = nibbles(key);
267    let mut position = 0;
268    let mut expected = *root;
269    for (index, node) in nodes.iter().enumerate() {
270        if node.hash() != expected {
271            return Err(PatriciaProofError::Unlinked { index });
272        }
273        let is_last = index + 1 == nodes.len();
274        let conclude = |result: Option<Hash256>| {
275            if is_last {
276                Ok(result)
277            } else {
278                Err(PatriciaProofError::TrailingNodes { index: index + 1 })
279            }
280        };
281        let path = node.path();
282        let remaining = &key[position..];
283        if !remaining.starts_with(path) {
284            // 経路の途中でキーと食い違うので、このキーは木にない
285            return conclude(None);
286        }
287        position += path.len();
288        match node {
289            TreeNode::Leaf { value, .. } => {
290                return conclude((position == KEY_NIBBLES).then_some(*value));
291            }
292            TreeNode::Branch { links, .. } => {
293                let Some(&nibble) = key.get(position) else {
294                    return Err(PatriciaProofError::BranchAtKeyEnd { index });
295                };
296                position += 1;
297                match links[nibble as usize] {
298                    None => return conclude(None),
299                    Some(_) if is_last => return Err(PatriciaProofError::Incomplete),
300                    Some(link) => expected = link,
301                }
302            }
303        }
304    }
305    unreachable!("the last node always concludes")
306}
307
308struct Reader<'a> {
309    rest: &'a [u8],
310    filler_is_zero: bool,
311}
312
313impl<'a> Reader<'a> {
314    fn new(rest: &'a [u8]) -> Self {
315        Self {
316            rest,
317            filler_is_zero: true,
318        }
319    }
320
321    fn take(&mut self, size: usize) -> Option<&'a [u8]> {
322        if self.rest.len() < size {
323            return None;
324        }
325        let (head, rest) = self.rest.split_at(size);
326        self.rest = rest;
327        Some(head)
328    }
329
330    fn hash(&mut self) -> Option<Hash256> {
331        self.take(32)
332            .map(|bytes| Hash256(bytes.try_into().expect("32 bytes")))
333    }
334
335    /// ニブルの数と経路を読む。catapult と同じく、奇数のときの埋め草のニブルは0でなければならない
336    fn path(&mut self) -> Option<Vec<u8>> {
337        let count = *self.take(1)?.first()? as usize;
338        let bytes = self.take(count.div_ceil(2))?;
339        let mut path: Vec<u8> = bytes
340            .iter()
341            .flat_map(|byte| [byte >> 4, byte & 0x0F])
342            .collect();
343        if count % 2 == 1 && path.pop() != Some(0) {
344            self.filler_is_zero = false;
345        }
346        Some(path)
347    }
348}
349
350#[derive(Debug, Clone, PartialEq, Eq)]
351pub enum TreeNodeDecodeError {
352    /// `offset` から始まるノードが途中で切れている
353    TooShort { offset: usize },
354    /// `offset` のノードの印が、葉(0xFF)でも枝(0x00)でもない
355    UnknownMarker { offset: usize, marker: u8 },
356    /// `offset` のノードの経路の、奇数のときの埋め草のニブルが0ではない
357    NonZeroFiller { offset: usize },
358}
359
360impl fmt::Display for TreeNodeDecodeError {
361    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362        match self {
363            Self::TooShort { offset } => {
364                write!(f, "{offset} バイト目からのノードが途中で切れています")
365            }
366            Self::UnknownMarker { offset, marker } => write!(
367                f,
368                "{offset} バイト目のノードの印 0x{marker:02X} は、葉でも枝でもありません"
369            ),
370            Self::NonZeroFiller { offset } => write!(
371                f,
372                "{offset} バイト目からのノードの経路の、埋め草のニブルが0ではありません"
373            ),
374        }
375    }
376}
377
378impl core::error::Error for TreeNodeDecodeError {}
379
380#[derive(Debug, Clone, PartialEq, Eq)]
381pub enum PatriciaProofError {
382    /// `index` 番目のノードのハッシュが、根か1つ前の枝の子と合わない
383    Unlinked { index: usize },
384    /// 最後の枝の、キーの次のニブルに子があるのに、その先のノードがない
385    Incomplete,
386    /// 答えが出たあとに、`index` 番目からノードが余っている
387    TrailingNodes { index: usize },
388    /// `index` 番目の枝で、キーのニブルを使い切っている
389    BranchAtKeyEnd { index: usize },
390}
391
392impl fmt::Display for PatriciaProofError {
393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394        match self {
395            Self::Unlinked { index } => write!(
396                f,
397                "{index} 番目のノードのハッシュが、根か1つ前の枝の子と合いません"
398            ),
399            Self::Incomplete => {
400                f.write_str("ノードが途中で終わっていて、あるともないとも言えません")
401            }
402            Self::TrailingNodes { index } => {
403                write!(f, "答えが出たあとに、{index} 番目からノードが余っています")
404            }
405            Self::BranchAtKeyEnd { index } => {
406                write!(f, "{index} 番目の枝で、キーを使い切っています")
407            }
408        }
409    }
410}
411
412impl core::error::Error for PatriciaProofError {}
413
414#[cfg(test)]
415mod tests {
416    use super::*;
417
418    fn hash(byte: u8) -> Hash256 {
419        Hash256([byte; 32])
420    }
421
422    fn sha3(parts: &[&[u8]]) -> Hash256 {
423        let mut hasher = Sha3_256::new();
424        for part in parts {
425            hasher.update(part);
426        }
427        Hash256(hasher.finalize().into())
428    }
429
430    /// キーを、ニブルの並びで書く(足りないところは0)
431    fn key(nibbles: &[u8]) -> Hash256 {
432        let mut bytes = [0; 32];
433        for (index, nibble) in nibbles.iter().enumerate() {
434            bytes[index / 2] |= if index % 2 == 0 { nibble << 4 } else { *nibble };
435        }
436        Hash256(bytes)
437    }
438
439    /// 根の枝(経路 [1, 2])の下に、次のニブル 3 と 7 の2つの葉がある木。
440    /// キーは 1 2 3 0 0 … と 1 2 7 0 0 …
441    fn tree() -> (TreeNode, TreeNode, TreeNode) {
442        let leaf_a = TreeNode::Leaf {
443            path: vec![0; 61],
444            value: hash(0xAA),
445        };
446        let leaf_b = TreeNode::Leaf {
447            path: vec![0; 61],
448            value: hash(0xBB),
449        };
450        let mut links = [None; 16];
451        links[3] = Some(leaf_a.hash());
452        links[7] = Some(leaf_b.hash());
453        let root = TreeNode::Branch {
454            path: vec![1, 2],
455            links: Box::new(links),
456        };
457        (root, leaf_a, leaf_b)
458    }
459
460    #[test]
461    fn encodes_paths_like_catapult() {
462        assert_eq!(encode_path(&[], false), [0x00]);
463        assert_eq!(encode_path(&[], true), [0x20]);
464        assert_eq!(encode_path(&[1, 2], true), [0x20, 0x12]);
465        assert_eq!(encode_path(&[1, 2, 3], false), [0x11, 0x23]);
466        assert_eq!(encode_path(&[1, 2, 3], true), [0x31, 0x23]);
467    }
468
469    #[test]
470    fn hashes_nodes_like_catapult() {
471        let leaf = TreeNode::Leaf {
472            path: vec![1, 2, 3],
473            value: hash(9),
474        };
475        assert_eq!(leaf.hash(), sha3(&[&[0x31, 0x23], &[9; 32]]));
476        let mut links = [None; 16];
477        links[2] = Some(hash(5));
478        let branch = TreeNode::Branch {
479            path: vec![],
480            links: Box::new(links),
481        };
482        let mut expected = vec![0x00];
483        for index in 0..16 {
484            expected.extend_from_slice(if index == 2 { &[5; 32] } else { &[0; 32] });
485        }
486        assert_eq!(branch.hash(), sha3(&[&expected]));
487    }
488
489    #[test]
490    fn encoded_nodes_read_back() {
491        let (root, leaf_a, leaf_b) = tree();
492        let nodes = vec![root, leaf_a, leaf_b];
493        let bytes: Vec<u8> = nodes.iter().flat_map(TreeNode::encode).collect();
494        assert_eq!(TreeNode::decode_all(&bytes), Ok(nodes));
495    }
496
497    #[test]
498    fn reads_serialized_nodes() {
499        let (root, leaf_a, _) = tree();
500        // 枝:印、ニブル2つ、経路、ビット(3 と 7)、子2つ
501        let mut bytes = vec![0x00, 2, 0x12];
502        bytes.extend_from_slice(&0b1000_1000_u16.to_le_bytes());
503        let TreeNode::Branch { links, .. } = &root else {
504            unreachable!()
505        };
506        bytes.extend_from_slice(&links[3].unwrap().0);
507        bytes.extend_from_slice(&links[7].unwrap().0);
508        // 葉:ニブル61個は31バイトで、最後の下位のニブルは埋め草
509        bytes.extend_from_slice(&[0xFF, 61]);
510        bytes.extend_from_slice(&[0; 31]);
511        bytes.extend_from_slice(&[0xAA; 32]);
512        assert_eq!(TreeNode::decode_all(&bytes), Ok(vec![root, leaf_a]));
513
514        let mut bad = bytes.clone();
515        bad[2 + 1 + 2 + 64 + 2 + 30] = 0x01;
516        assert_eq!(
517            TreeNode::decode_all(&bad),
518            Err(TreeNodeDecodeError::NonZeroFiller { offset: 69 })
519        );
520        assert_eq!(
521            TreeNode::decode_all(&bytes[..bytes.len() - 1]),
522            Err(TreeNodeDecodeError::TooShort { offset: 69 })
523        );
524        assert_eq!(
525            TreeNode::decode_all(&[0x01]),
526            Err(TreeNodeDecodeError::UnknownMarker {
527                offset: 0,
528                marker: 0x01
529            })
530        );
531        assert_eq!(TreeNode::decode_all(&[]), Ok(vec![]));
532    }
533
534    #[test]
535    fn proves_that_a_key_is_present() {
536        let (root, leaf_a, leaf_b) = tree();
537        let root_hash = root.hash();
538        assert_eq!(
539            prove(&key(&[1, 2, 3]), &[root.clone(), leaf_a], &root_hash),
540            Ok(Some(hash(0xAA)))
541        );
542        assert_eq!(
543            prove(&key(&[1, 2, 7]), &[root, leaf_b], &root_hash),
544            Ok(Some(hash(0xBB)))
545        );
546    }
547
548    #[test]
549    fn proves_that_a_key_is_absent() {
550        let (root, leaf_a, _) = tree();
551        let root_hash = root.hash();
552        // 枝の経路で食い違う
553        assert_eq!(
554            prove(&key(&[1, 5]), core::slice::from_ref(&root), &root_hash),
555            Ok(None)
556        );
557        // 枝の次のニブルに子がない
558        assert_eq!(
559            prove(&key(&[1, 2, 4]), core::slice::from_ref(&root), &root_hash),
560            Ok(None)
561        );
562        // 葉の経路で食い違う
563        assert_eq!(
564            prove(&key(&[1, 2, 3, 1]), &[root, leaf_a], &root_hash),
565            Ok(None)
566        );
567        // 空の木
568        assert_eq!(prove(&key(&[1]), &[], &Hash256([0; 32])), Ok(None));
569    }
570
571    #[test]
572    fn refuses_broken_proofs() {
573        let (root, leaf_a, leaf_b) = tree();
574        let root_hash = root.hash();
575        assert_eq!(
576            prove(&key(&[1, 2, 3]), &[root.clone(), leaf_a.clone()], &hash(0)),
577            Err(PatriciaProofError::Unlinked { index: 0 })
578        );
579        // 3 の子のところに、7 の葉を置く
580        assert_eq!(
581            prove(&key(&[1, 2, 3]), &[root.clone(), leaf_b], &root_hash),
582            Err(PatriciaProofError::Unlinked { index: 1 })
583        );
584        assert_eq!(
585            prove(&key(&[1, 2, 3]), core::slice::from_ref(&root), &root_hash),
586            Err(PatriciaProofError::Incomplete)
587        );
588        assert_eq!(
589            prove(&key(&[1, 5]), &[root.clone(), leaf_a.clone()], &root_hash),
590            Err(PatriciaProofError::TrailingNodes { index: 1 })
591        );
592        assert_eq!(
593            prove(&key(&[1, 2, 3]), &[], &root_hash),
594            Err(PatriciaProofError::Incomplete)
595        );
596    }
597
598    #[test]
599    fn hashes_the_roots_in_cache_order() {
600        let roots: [Hash256; 9] = core::array::from_fn(|index| hash(index as u8));
601        let concatenated: Vec<u8> = roots.iter().flat_map(|root| root.0).collect();
602        assert_eq!(state_hash(&roots), sha3(&[&concatenated]));
603        assert_eq!(SubCache::AccountState.index(), 0);
604        assert_eq!(SubCache::Metadata.index(), 8);
605    }
606
607    #[test]
608    fn hashes_keys_by_their_bytes() {
609        assert_eq!(id_key(0x0102), sha3(&[&0x0102_u64.to_le_bytes()]));
610        assert_eq!(address_key(&Address([0x68; 24])), sha3(&[&[0x68; 24]]));
611        assert_eq!(hash_key(&hash(3)), sha3(&[&[3; 32]]));
612    }
613}