1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! Domain types for dig-coinstore.
//!
//! Core data structures: [`CoinRecord`], [`ChiaCoinRecord`], [`BlockData`], [`CoinAddition`],
//! [`ApplyBlockResult`], [`RollbackResult`], [`CoinStoreStats`],
//! [`CoinStoreSnapshot`], [`UnspentLineageInfo`].
//!
//! Also defines type aliases: [`CoinId`] = [`Bytes32`], [`PuzzleHash`] = [`Bytes32`] (see API-009).
//!
//! # Requirements
//! - **API-002:** [`CoinRecord`], [`ChiaCoinRecord`], [`CoinId`]
//! - **API-005:** [`BlockData`], [`CoinAddition`]
//! - **API-006:** [`ApplyBlockResult`], [`RollbackResult`]
//! - **API-007:** [`CoinStoreStats`]
//! - **API-008:** [`CoinStoreSnapshot`]
//! - **API-009:** [`CoinId`], [`PuzzleHash`], [`UnspentLineageInfo`]
//!
//! ## `ChiaCoinRecord` vs `chia_protocol::CoinRecord`
//!
//! The upstream streamable type is documented at
//! [docs.rs `chia_protocol::CoinRecord`](https://docs.rs/chia-protocol/latest/chia_protocol/struct.CoinRecord.html).
//! This crate pins `chia-protocol` **0.26** together with [`dig_clvm`](https://github.com/DIG-Network/dig-clvm)
//! for a single `Coin` / [`Bytes32`] identity graph. That protocol release does **not** yet export
//! `CoinRecord`, so we define [`ChiaCoinRecord`] here with **identical fields and semantics** to the
//! current Chia reference implementation. When `dig-clvm` upgrades `chia-protocol`, [`ChiaCoinRecord`]
//! should become `pub use chia_protocol::CoinRecord as ChiaCoinRecord` (STR-005).
use HashMap;
use ;
use crateBytes32;
use crateCoin;
use crateCoinState;
// ─────────────────────────────────────────────────────────────────────────────
// Type aliases (API-002 / API-009)
// ─────────────────────────────────────────────────────────────────────────────
/// 32-byte coin identifier: `sha256(parent_coin_info || puzzle_hash || amount)`.
///
/// Alias of [`Bytes32`] for readable APIs (`get_coin_record(&CoinId)`).
///
/// See: [`Coin::coin_id`], docs/resources/SPEC.md §2.1
pub type CoinId = Bytes32;
/// Puzzle hash (SHA256 of serialized puzzle program). Same underlying type as [`CoinId`].
///
/// Fully specified under API-009; exported early for `CoinRecord::coin_id()` return type clarity.
pub type PuzzleHash = Bytes32;
// ─────────────────────────────────────────────────────────────────────────────
// Chia wire-shaped coin row (interop)
// ─────────────────────────────────────────────────────────────────────────────
/// Row-shaped coin metadata matching Chia full-node / light-wallet `CoinRecord` streamable layout.
///
/// **Why this exists:** `chia-protocol` 0.26 (bundled via `dig-clvm`) does not define this struct;
/// Chia’s reference layout is still the contract for RPC and cross-repo interop. Field names mirror
/// [`chia_protocol::CoinRecord`](https://docs.rs/chia-protocol/latest/chia_protocol/struct.CoinRecord.html).
///
/// **`spent_block_index` sentinel:** `0` means *unspent* in Chia’s encoding; positive values are
/// spent heights. Fast-forward–eligible rows (Python `spent_index == -1`) are not represented here;
/// dig-coinstore uses [`CoinRecord::ff_eligible`] instead once ingested.
// ─────────────────────────────────────────────────────────────────────────────
// CoinRecord — authoritative stored row (API-002)
// ─────────────────────────────────────────────────────────────────────────────
/// Full lifecycle state of one coin in the coinstore.
///
/// Persists after spending for history + rollback (SPEC.md §2.2). Prefer [`Option<u64>`] for
/// [`CoinRecord::spent_height`] over Chia’s `spent_block_index == 0` sentinel to keep Rust matches
/// exhaustive and avoid double meanings for `0`.
///
/// See: [`API-002`](../../docs/requirements/domains/crate_api/specs/API-002.md),
/// Chia reference: <https://github.com/Chia-Network/chia-blockchain/blob/main/chia/full_node/coin_store.py>
// ─────────────────────────────────────────────────────────────────────────────
// Block application input (API-005)
// ─────────────────────────────────────────────────────────────────────────────
//
// See: docs/requirements/domains/crate_api/specs/API-005.md,
// docs/resources/SPEC.md §2.4, Chia `coin_store.py` `new_block()` parameters.
/// One transaction-created coin plus ingestion metadata for [`BlockData::additions`].
///
/// **`same_as_parent`:** `true` when this coin’s [`Coin::puzzle_hash`] and [`Coin::amount`] match the
/// spent parent’s puzzle hash and amount — the block pipeline uses this for singleton **fast-forward**
/// eligibility ([`CoinRecord::ff_eligible`], BLK-007).
///
/// **`coin_id`:** For valid blocks this MUST equal [`Coin::coin_id`] on [`Self::coin`]. The struct does not
/// enforce equality at construction time; BLK-* / `apply_block` validation rejects mismatches so callers
/// cannot poison the store with an inconsistent ID ([API-005 test plan](docs/requirements/domains/crate_api/specs/API-005.md#verification)).
///
/// **Chia reference:** `tx_additions` tuples in
/// [`coin_store.py`](https://github.com/Chia-Network/chia-blockchain/blob/main/chia/full_node/coin_store.py).
/// Pre-validated block state changes: input to `CoinStore::apply_block` (BLK-*).
///
/// The coinstore **does not** run CLVM — the caller extracts additions, removals, coinbase rewards, and
/// hints from execution results, then fills this struct ([API-005](docs/requirements/domains/crate_api/specs/API-005.md#summary)).
///
/// | Field | Role |
/// |-------|------|
/// | `height` / `timestamp` / `block_hash` / `parent_hash` | Chain linkage + time (validated in BLK-002, BLK-003) |
/// | `additions` / `removals` | UTXO delta |
/// | `coinbase_coins` | Farmer + pool rewards (count rules: BLK-004) |
/// | `hints` | CREATE_COIN hint bytes for the hint index (HNT-*) |
/// | `expected_state_root` | Optional post-apply root check (BLK-009) |
/// Summary returned after a successful [`crate::coin_store::CoinStore::apply_block`] (success path of
/// `Result<ApplyBlockResult, CoinStoreError>`).
///
/// **Source of truth:** [`docs/resources/SPEC.md`](../../docs/resources/SPEC.md) §3.2. Field meanings:
/// post-apply Merkle **state root**, how many coins were **created** (tx additions + coinbase),
/// how many were **marked spent**, and the new tip **height** (= input block height when validation passes).
///
/// **Chia note:** Chia’s `new_block()` updates storage in place and returns nothing; this struct is the
/// dig-coinstore contract for observability and tests ([API-006](docs/requirements/domains/crate_api/specs/API-006.md)).
///
/// # Requirement: API-006
/// Summary returned after a successful rollback ([`crate::coin_store::CoinStore::rollback_to_block`],
/// [`crate::coin_store::CoinStore::rollback_n_blocks`]).
///
/// **`modified_coins`:** Chia’s `rollback_to_block` returns `dict[bytes32, CoinRecord]`
/// ([`coin_store.py:567`](https://github.com/Chia-Network/chia-blockchain/blob/6e7a4954edccd8ab83fcacf938cfc42ddfcad7f2/chia/full_node/coin_store.py#L567)).
/// dig-coinstore keeps that map and adds explicit **`coins_deleted`** / **`coins_unspent`** counts
/// (SPEC §1.6 improvement #11; [API-006](docs/requirements/domains/crate_api/specs/API-006.md)).
///
/// **Count invariant (well-formed results):** For each entry in `modified_coins`, the rollback either
/// **deleted** a coin confirmed after the target height (`coins_deleted`) or **reverted a spend**
/// for a coin spent after the target (`coins_unspent`). Callers assembling this struct should ensure
/// `coins_deleted + coins_unspent == modified_coins.len()` when every modified coin is accounted for once.
///
/// # Requirement: API-006
/// Aggregated chain + coinset metrics returned by [`crate::coin_store::CoinStore::stats`] (API-007 / QRY-010).
///
/// **Design goal (SPEC §1.6 #18):** eventually all aggregate fields are **O(1)** materialized counters
/// updated in the same write batch as `apply_block` / rollback ([`docs/resources/SPEC.md`](../../docs/resources/SPEC.md)).
/// Until PRF-003 lands, [`CoinStore::stats`](crate::coin_store::CoinStore::stats) may derive some fields by
/// scanning `coin_records` (documented on that method) while still returning this single struct shape.
///
/// **Operational use:** dashboards, health checks, and mempool admission logic read one snapshot instead of
/// issuing multiple Chia-style COUNT queries ([`coin_store.py:96-103`](https://github.com/Chia-Network/chia-blockchain/blob/6e7a4954edccd8ab83fcacf938cfc42ddfcad7f2/chia/full_node/coin_store.py#L96)).
///
/// # Requirement: API-007
/// # Spec: docs/requirements/domains/crate_api/specs/API-007.md
/// Serializable checkpoint of the full coinstate at one instant (fast sync / backup / restore).
///
/// **Why it exists:** Chia has no first-class snapshot object; nodes replay from genesis. dig-coinstore
/// standardizes this struct for bincode persistence and future checkpoint sync ([`SPEC.md`](../../docs/resources/SPEC.md)
/// §1.6 improvement #6, §3.14; [API-008](docs/requirements/domains/crate_api/specs/API-008.md)).
///
/// **`block_hash`:** Tip header hash at capture time (same role as [`crate::coin_store::CoinStore::tip_hash`]
/// when produced by a future `CoinStore::snapshot` implementation — tracked under PRF-008).
///
/// **`coins` / `hints`:** Full materialized rows and `(coin_id, hint)` pairs — same `hints` element type as
/// [`BlockData::hints`] for consistency across APIs.
///
/// **`total_coins` / `total_value`:** Per API-008 field table, `total_coins` SHOULD equal `coins.len()` as `u64`,
/// and `total_value` SHOULD be the sum of **unspent** [`CoinRecord`] amounts at capture time. The type does
/// not enforce these invariants; `CoinStore::snapshot` (PRF-008) must populate them coherently.
///
/// # Requirement: API-008
/// # Spec: docs/requirements/domains/crate_api/specs/API-008.md
/// Lineage chain for **one unspent coin**, used when resolving singleton **fast-forward** candidates
/// ([`SPEC.md`](../../docs/resources/SPEC.md) §2.5, [`QRY-008`](../../docs/requirements/domains/queries/specs/QRY-008.md)).
///
/// # Field semantics
///
/// - **`coin_id`:** The unspent leaf’s identity (`sha256(parent || puzzle_hash || amount)`), same as
/// [`Coin::coin_id()`](crate::Coin::coin_id).
/// - **`parent_id`:** That coin’s `parent_coin_info` (the parent coin’s name / id in Chia terminology).
/// - **`parent_parent_id`:** The parent coin row’s `parent_coin_info` (grandparent link in the lineage chain).
///
/// # Genesis / missing rows
///
/// Chia encodes coinbase parents with fixed sentinel bytes; there may be **no** grandparent coin row in the
/// coinset. Callers still store a [`CoinId`] value (often all-zero bytes) for `parent_parent_id` when the
/// wallet or mempool has no further ancestor ([`API-009.md`](../../docs/requirements/domains/crate_api/specs/API-009.md) implementation notes).
///
/// **Serde:** Not required by API-009; QRY-008 returns this in-process. Add `Serialize`/`Deserialize` only if
/// an RPC boundary needs a stable wire shape.
///
/// # Requirement: API-009
/// # Spec: docs/requirements/domains/crate_api/specs/API-009.md