Skip to main content

dig_merkle/
read.rs

1//! Reading on-chain DataLayer state without spending (SPEC §3.6/§3.7) — owner-DID discovery.
2//!
3//! A DIG store can be rooted in a DID: the store's launcher coin is created by spending a
4//! DID-authorized coin (an [`crate::Owner::Custom`] mint whose parent is the DID coin). This module
5//! recovers that owning DID by walking the store's launcher lineage one hop up to its creator and
6//! recognising a DID coin spend.
7//!
8//! ## Two layers
9//!
10//! [`did_ref_from_spend`] is the pure, network-free core — it recognises a DID from a single coin
11//! spend. [`resolve_owner_did`] is the launcher-lineage WALK on top: it fetches the two coin spends
12//! (`store_id` → its creator) through the injected CANONICAL
13//! [`dig_chainsource_interface::ChainSource`] read interface (a reference-DOWN pure leaf) and passes
14//! the creator spend to `did_ref_from_spend`, fail-closed to `Ok(None)` at every missing hop.
15//! dig-merkle itself opens no socket (INV-1) — the caller implements the chain read.
16
17use chia_wallet_sdk::driver::{Did, Puzzle};
18use chia_wallet_sdk::prelude::Allocator;
19use clvm_traits::ToClvm;
20use dig_chainsource_interface::ChainSource;
21
22use crate::types::{Bytes32, CoinSpend};
23use crate::{MerkleError, MerkleResult};
24
25/// A reference to a DID, identified by its immutable `launcher_id` (the DID's on-chain identity).
26///
27/// This is the successful result of owner-DID discovery: the launcher id uniquely names the DID that
28/// authorized a store's creation, and a caller resolves it to a full DID document via its own DID
29/// tooling (dig-merkle deliberately holds no `dig-did` dependency).
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct DidRef {
32    /// The DID's launcher id — its permanent on-chain identity.
33    pub launcher_id: Bytes32,
34}
35
36/// Recognises whether a coin spend is a DID spend and, if so, returns its [`DidRef`]. Fail-closed:
37/// any spend that is not a parseable DID yields `Ok(None)` rather than an error.
38///
39/// This is the pure, network-free core of owner-DID discovery. Given the spend of a store launcher's
40/// PARENT coin, a `Some` result means that parent was a DID — i.e. the store is DID-owned — and names
41/// the owning DID. A `None` result means the parent was an ordinary coin (e.g. a plain standard mint,
42/// SPEC §3.7 fail-closed).
43///
44/// The parse runs in a private [`Allocator`], allocating the spend's puzzle and solution and handing
45/// them to the SDK's [`Did::parse`] (the byte-source-of-truth, INV-4). It performs NO network I/O and
46/// never signs or spends — it only inspects the given bytes.
47///
48/// # Authoritative ONLY for a CONFIRMED on-chain spend (NC-9)
49///
50/// This function trusts its input and only recognises STRUCTURE; it does NOT verify that the spend
51/// happened on chain. A caller feeding an unconfirmed, attacker-shaped, or otherwise unverified spend
52/// can be made to mis-attribute ownership — a crafted puzzle that parses as a DID yields a `Some`
53/// that proves nothing. Genuine chain-proven attribution MUST fetch the store launcher's parent spend
54/// from a TRUSTED chain source and verify it was actually spent on chain before trusting the result.
55/// Do NOT treat a `Some` result from an unverified spend as proof of ownership.
56///
57/// # Errors
58///
59/// Returns [`MerkleError::Parse`] if the spend's puzzle/solution CLVM cannot be allocated, or
60/// [`MerkleError::Driver`] if the SDK's DID parser errors on a puzzle that structurally should have
61/// been a DID. A puzzle that simply is not a DID is `Ok(None)`, not an error.
62pub fn did_ref_from_spend(spend: &CoinSpend) -> MerkleResult<Option<DidRef>> {
63    let mut allocator = Allocator::new();
64
65    let puzzle_ptr = spend
66        .puzzle_reveal
67        .to_clvm(&mut allocator)
68        .map_err(|error| MerkleError::Parse(format!("puzzle reveal: {error}")))?;
69    let solution_ptr = spend
70        .solution
71        .to_clvm(&mut allocator)
72        .map_err(|error| MerkleError::Parse(format!("solution: {error}")))?;
73
74    let puzzle = Puzzle::parse(&allocator, puzzle_ptr);
75
76    match Did::parse(&allocator, spend.coin, puzzle, solution_ptr)? {
77        Some((did, _p2_spend)) => Ok(Some(DidRef {
78            launcher_id: did.info.launcher_id,
79        })),
80        None => Ok(None),
81    }
82}
83
84/// Recovers the DID that OWNS the store launched at `store_id`, walking one lineage hop up (SPEC §3.7).
85///
86/// A DID-owned store has its launcher coin created by spending a DID-authorized coin. This walks that
87/// lineage via the injected [`ChainSource`] (INV-1 — dig-merkle opens no socket; the caller supplies
88/// the chain read):
89///
90/// 1. `chain.coin_spend(store_id)` — the launcher coin's spend (`store_id == launcher_id`).
91/// 2. `launcher_spend.coin.parent_coin_info` — the coin that CREATED the launcher.
92/// 3. `chain.coin_spend(parent_id)` — that creator's spend.
93/// 4. [`did_ref_from_spend`] — `Some(DidRef)` if the creator was a DID, else `None`.
94///
95/// It is **fail-closed to `Ok(None)`** at every missing/non-DID step — a store that is simply not
96/// DID-owned is `Ok(None)`, never an error — and READ-ONLY (never signs, spends, or broadcasts). A
97/// [`ChainSource`] read error surfaces as [`MerkleError::Chain`].
98///
99/// # Authoritative ONLY for a CONFIRMED on-chain spend (NC-9)
100///
101/// The DID recognition in step 4 trusts STRUCTURE, not confirmation (see [`did_ref_from_spend`]).
102/// The result is chain-proven ownership ONLY when the injected [`ChainSource`] returns genuine,
103/// confirmed on-chain spends. A source that can be made to return unconfirmed or attacker-shaped
104/// spends can be made to mis-attribute ownership; do not treat a `Some` result as proof of ownership
105/// unless the `ChainSource` is trusted to return confirmed spends.
106///
107/// # Errors
108///
109/// Returns [`MerkleError::Chain`] if a [`ChainSource`] read fails, or [`MerkleError::Parse`] /
110/// [`MerkleError::Driver`] if the creator spend fails to parse (propagated from
111/// [`did_ref_from_spend`]).
112pub fn resolve_owner_did<C: ChainSource>(
113    store_id: Bytes32,
114    chain: &C,
115) -> MerkleResult<Option<DidRef>> {
116    let Some(launcher_spend) = read_coin_spend(chain, store_id)? else {
117        return Ok(None);
118    };
119
120    let parent_id = launcher_spend.coin.parent_coin_info;
121    let Some(creator_spend) = read_coin_spend(chain, parent_id)? else {
122        return Ok(None);
123    };
124
125    did_ref_from_spend(&creator_spend)
126}
127
128/// Reads the spend that spent `coin_id`, mapping the source's own error into [`MerkleError::Chain`]
129/// so the crate's error surface never leaks a generic `ChainSource::Error` type parameter.
130fn read_coin_spend<C: ChainSource>(chain: &C, coin_id: Bytes32) -> MerkleResult<Option<CoinSpend>> {
131    chain
132        .coin_spend(coin_id)
133        .map_err(|error| MerkleError::Chain(format!("chain read for {coin_id}: {error}")))
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139    use chia_wallet_sdk::driver::{Launcher, SpendContext, StandardLayer};
140    use chia_wallet_sdk::test::Simulator;
141
142    /// A real DID coin spend is recognised, and the returned [`DidRef`] carries the DID's own
143    /// launcher id — the proof `did_ref_from_spend` drives the SDK's DID parser correctly.
144    #[test]
145    fn did_spend_is_recognised_with_its_launcher_id() -> anyhow::Result<()> {
146        let mut sim = Simulator::new();
147        let ctx = &mut SpendContext::new();
148
149        let alice = sim.bls(1);
150        let alice_p2 = StandardLayer::new(alice.pk);
151
152        // Create a DID, then settle it on chain so its coin exists to be spent again.
153        let (create_did, did) =
154            Launcher::new(alice.coin.coin_id(), 1).create_simple_did(ctx, &alice_p2)?;
155        alice_p2.spend(ctx, alice.coin, create_did)?;
156        sim.spend_coins(ctx.take(), std::slice::from_ref(&alice.sk))?;
157
158        // Spend the DID coin (an update spend recreates it) — this is the spend we recognise.
159        let did_coin = did.coin;
160        let _child = did.update(ctx, &alice_p2, chia_wallet_sdk::types::Conditions::new())?;
161        let coin_spends = ctx.take();
162        sim.spend_coins(coin_spends.clone(), std::slice::from_ref(&alice.sk))?;
163
164        let did_spend = coin_spends
165            .iter()
166            .find(|s| s.coin.coin_id() == did_coin.coin_id())
167            .expect("the DID coin spend is present");
168
169        let did_ref = did_ref_from_spend(did_spend)?.expect("a DID spend is recognised");
170        assert_eq!(
171            did_ref.launcher_id, did.info.launcher_id,
172            "the DidRef names the DID's own launcher id"
173        );
174        Ok(())
175    }
176
177    /// A plain standard-coin spend is NOT a DID — discovery fails closed to `None`, never an error
178    /// (SPEC §3.7).
179    #[test]
180    fn plain_standard_spend_is_not_a_did() -> anyhow::Result<()> {
181        let mut sim = Simulator::new();
182        let ctx = &mut SpendContext::new();
183
184        let alice = sim.bls(1);
185        let alice_p2 = StandardLayer::new(alice.pk);
186        let memos = ctx.hint(alice.puzzle_hash)?;
187        alice_p2.spend(
188            ctx,
189            alice.coin,
190            chia_wallet_sdk::types::Conditions::new().create_coin(alice.puzzle_hash, 1, memos),
191        )?;
192        let coin_spends = ctx.take();
193
194        let standard_spend = coin_spends
195            .iter()
196            .find(|s| s.coin.coin_id() == alice.coin.coin_id())
197            .expect("the standard coin spend is present");
198
199        assert_eq!(
200            did_ref_from_spend(standard_spend)?,
201            None,
202            "a plain standard spend is not a DID"
203        );
204        Ok(())
205    }
206
207    use crate::resolve_owner_did;
208    use crate::types::{Coin, CoinSpend};
209    use chia_wallet_sdk::types::Conditions;
210    use dig_chainsource_interface::{ChainSourceError, MockChainSource};
211
212    /// Builds a real, on-chain DID and returns (its coin spend, its launcher id). The DID coin is
213    /// created then update-spent so a genuine DID spend exists to be recognised.
214    fn did_coin_and_spend(sim: &mut Simulator) -> anyhow::Result<(CoinSpend, Bytes32)> {
215        let ctx = &mut SpendContext::new();
216        let alice = sim.bls(1);
217        let alice_p2 = StandardLayer::new(alice.pk);
218
219        let (create_did, did) =
220            Launcher::new(alice.coin.coin_id(), 1).create_simple_did(ctx, &alice_p2)?;
221        alice_p2.spend(ctx, alice.coin, create_did)?;
222        sim.spend_coins(ctx.take(), std::slice::from_ref(&alice.sk))?;
223
224        let did_coin = did.coin;
225        let _child = did.update(ctx, &alice_p2, Conditions::new())?;
226        let coin_spends = ctx.take();
227        sim.spend_coins(coin_spends.clone(), std::slice::from_ref(&alice.sk))?;
228
229        let did_spend = coin_spends
230            .into_iter()
231            .find(|s| s.coin.coin_id() == did_coin.coin_id())
232            .expect("the DID coin spend is present");
233        Ok((did_spend, did.info.launcher_id))
234    }
235
236    /// A DID-owned store resolves to the owning DID: the walk fetches the launcher spend, reads its
237    /// creator (the DID coin), and recognises the DID (SPEC §3.7).
238    #[test]
239    fn resolve_owner_did_returns_the_did_for_a_did_rooted_store() -> anyhow::Result<()> {
240        let mut sim = Simulator::new();
241        let (did_spend, did_launcher_id) = did_coin_and_spend(&mut sim)?;
242        let did_coin_id = did_spend.coin.coin_id();
243
244        // The store's launcher coin was created by spending the DID coin: its parent IS the DID coin.
245        let store_id = Bytes32::new([0xa1; 32]);
246        let launcher_coin = Coin::new(did_coin_id, Bytes32::new([0xb2; 32]), 1);
247        // Only `launcher_spend.coin.parent_coin_info` is read by the walk; reuse a real program pair.
248        let launcher_spend = CoinSpend::new(
249            launcher_coin,
250            did_spend.puzzle_reveal.clone(),
251            did_spend.solution.clone(),
252        );
253
254        let chain = MockChainSource::new()
255            .with_spend(store_id, launcher_spend)
256            .with_spend(did_coin_id, did_spend);
257
258        let did_ref = resolve_owner_did(store_id, &chain)?.expect("store is DID-owned");
259        assert_eq!(
260            did_ref.launcher_id, did_launcher_id,
261            "resolve names the owning DID's launcher id"
262        );
263        Ok(())
264    }
265
266    /// A plain (non-DID) store resolves to `None`: the launcher's creator is an ordinary coin, not a
267    /// DID — fail-closed, never an error (SPEC §3.7).
268    #[test]
269    fn resolve_owner_did_returns_none_for_a_plain_store() -> anyhow::Result<()> {
270        let mut sim = Simulator::new();
271        let ctx = &mut SpendContext::new();
272        let alice = sim.bls(1);
273        let alice_p2 = StandardLayer::new(alice.pk);
274        let memos = ctx.hint(alice.puzzle_hash)?;
275        alice_p2.spend(
276            ctx,
277            alice.coin,
278            Conditions::new().create_coin(alice.puzzle_hash, 1, memos),
279        )?;
280        let creator_spend = ctx
281            .take()
282            .into_iter()
283            .find(|s| s.coin.coin_id() == alice.coin.coin_id())
284            .expect("standard creator spend present");
285
286        let store_id = Bytes32::new([0xc3; 32]);
287        let launcher_coin = Coin::new(alice.coin.coin_id(), Bytes32::new([0xd4; 32]), 1);
288        let launcher_spend = CoinSpend::new(
289            launcher_coin,
290            creator_spend.puzzle_reveal.clone(),
291            creator_spend.solution.clone(),
292        );
293
294        let chain = MockChainSource::new()
295            .with_spend(store_id, launcher_spend)
296            .with_spend(alice.coin.coin_id(), creator_spend);
297
298        assert_eq!(
299            resolve_owner_did(store_id, &chain)?,
300            None,
301            "a plainly-minted store has no owning DID"
302        );
303        Ok(())
304    }
305
306    /// A missing launcher spend fails closed to `Ok(None)` — the store is unknown to the source.
307    #[test]
308    fn resolve_owner_did_none_when_launcher_spend_missing() -> anyhow::Result<()> {
309        let chain = MockChainSource::new();
310        assert_eq!(
311            resolve_owner_did(Bytes32::new([0xee; 32]), &chain)?,
312            None,
313            "an unknown store id resolves to None"
314        );
315        Ok(())
316    }
317
318    /// A missing CREATOR spend (launcher present, its parent unknown) also fails closed to `Ok(None)`.
319    #[test]
320    fn resolve_owner_did_none_when_creator_spend_missing() -> anyhow::Result<()> {
321        let store_id = Bytes32::new([0x1a; 32]);
322        let parent_id = Bytes32::new([0x2b; 32]);
323        // A launcher spend whose creator (parent) is not in the source.
324        let mut sim = Simulator::new();
325        let (any_spend, _) = did_coin_and_spend(&mut sim)?;
326        let launcher_coin = Coin::new(parent_id, Bytes32::new([0x3c; 32]), 1);
327        let launcher_spend = CoinSpend::new(
328            launcher_coin,
329            any_spend.puzzle_reveal.clone(),
330            any_spend.solution.clone(),
331        );
332
333        let chain = MockChainSource::new().with_spend(store_id, launcher_spend);
334        assert_eq!(resolve_owner_did(store_id, &chain)?, None);
335        Ok(())
336    }
337
338    /// A [`ChainSource`] read ERROR surfaces as [`MerkleError::Chain`] — distinct from a fail-closed
339    /// `None` (the chain could not be consulted, so ownership is unknown).
340    #[test]
341    fn resolve_owner_did_maps_chain_error() {
342        let chain = MockChainSource::new().fail_with(ChainSourceError::Timeout);
343        let result = resolve_owner_did(Bytes32::new([0x44; 32]), &chain);
344        assert!(
345            matches!(result, Err(MerkleError::Chain(_))),
346            "a source read error is a Chain error, not None"
347        );
348    }
349}