Skip to main content

dig_smt/
lib.rs

1//! # dig-smt — the DIG Network generic sparse-merkle-tree mechanism
2//!
3//! A sha256 **sparse merkle tree** over 32-byte keys, with real membership AND non-membership
4//! proofs, extracted VERBATIM (byte-identical roots) from dig-identity's profile tree. This crate is
5//! the generic MECHANISM only: it knows nothing about DIG slots, values, profiles, or DIDs. A caller
6//! supplies raw 32-byte keys and opaque value bytes; a higher-level crate builds a domain schema
7//! (slot-key derivation, value encoding) on top and CONSUMES this tree.
8//!
9//! The tree wraps the audited Nervos [`sparse_merkle_tree`] crate — we never re-implement the merkle
10//! construction; we only supply the sha256 [`Sha256Hasher`] it hashes nodes with and the
11//! [`hash_leaf_value`] leaf scheme (`sha256(0x01 ‖ key ‖ encoded_value)`, key bound in for
12//! self-contained leaf/branch domain separation — see [`hash`]).
13//!
14//! ## Byte-contract (§5.1 / NC-9)
15//!
16//! For a given set of `(key, encoded_value)` leaves, the 32-byte [`SmtTree::root`] is byte-identical
17//! to dig-identity's current profile root. A profile root is on-chain-anchored, so a drift would
18//! render published profiles unreadable. The invariant is pinned by a golden root vector
19//! (`tests/golden_root.rs`), computed from dig-identity's current behaviour.
20//!
21//! ## What lives here
22//!
23//! | Concern | Item |
24//! |---|---|
25//! | sha256 + the leaf/node hashing | [`hash`] |
26//! | The mutable tree: set/get/root/prove | [`SmtTree`] |
27//! | Serializable proofs + root-only verification | [`SmtProof`], [`verify_membership`], [`verify_non_membership`] |
28//!
29//! ## Proving a key against a root
30//!
31//! ```
32//! use dig_smt::{SmtTree, verify_membership, verify_non_membership};
33//!
34//! let mut tree = SmtTree::new();
35//! let name_key = [1u8; 32];
36//! tree.set(name_key, b"Ada".to_vec()).unwrap();
37//! let root = tree.root();
38//!
39//! // Prove the key holds "Ada" using only (root, key, value, proof).
40//! let membership = tree.prove_membership(name_key).unwrap();
41//! assert!(verify_membership(&root, name_key, b"Ada", &membership).unwrap());
42//!
43//! // Prove a different key is absent.
44//! let absent_key = [2u8; 32];
45//! let absent = tree.prove_non_membership(absent_key).unwrap();
46//! assert!(verify_non_membership(&root, absent_key, &absent).unwrap());
47//! ```
48
49pub mod error;
50pub mod hash;
51pub mod proof;
52pub mod tree;
53
54pub use error::{SmtError, SmtResult};
55pub use hash::{hash_leaf_value, sha256, Digest32, Sha256Hasher, LEAF_DOMAIN};
56pub use proof::{verify_membership, verify_non_membership, SmtProof};
57pub use tree::SmtTree;