sidestr-core 0.4.2

sidestr user-activated sidechains beside a Bitcoin-family parent: the chain document, the parents table, signed blocks generic over the header family (BIP-325 challenge, no subsidy), the peg-in claim and peg-out burn rules, Knots' unified sighash, the block file and an in-memory validating chain. A port of siding by Melvin Carvalho.
Documentation
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
//! The `assets` rule (SPEC 12.2) as a **view**: what each unspent output
//! carries, derived from the chain one block at a time. A port of the check
//! in `siding/lib/overlays/assets.mjs` (AGPL-3.0, Melvin Carvalho), without
//! the pool rule.
//!
//! For every asset in every non-coinbase transaction, what the inputs carry
//! must be at least what the transaction's tallies assign; the difference is
//! destroyed. Issuance (`issue:` with `tally:self:`) is the one creation.
//!
//! # Two ways to hold the rule
//!
//! On a chain whose document names `assets` — or names any rule at all:
//! `siding/lib/overlays/index.mjs rulesFor` installs the assets rule
//! whenever `rules` is not empty, so an `evm` chain carries it too — the
//! rule is consensus: a transaction that breaks it is refused and so is its
//! block. [`AssetsRule`] is that rule, a [`BlockRule`] for
//! [`crate::state::StateOf::from_genesis_with_rules`]. On a chain
//! that names no rules the records are still mined, as any `OP_RETURN` is,
//! and a client may *read* them under the same rule. That is an asset
//! validated by its holders rather than by the chain's signers, and
//! [`AssetView`] is that reading: a transaction that breaks the rule is
//! kept (the chain kept it), its inputs are spent, and its outputs carry
//! nothing, so what it tried to move is destroyed rather than created. Two
//! clients that replay the same blocks reach the same view. The view never
//! refuses a block; [`Outcome`] says which transactions it read as broken.
//!
//! A wallet that spends a coin carrying an asset without tallying the asset
//! onward destroys it. Only a wallet that knows the view should hold such
//! coins.
//!
//! ```
//! use bitcoin::{absolute::LockTime, transaction::Version, Amount, OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Witness};
//! use sidestr_core::assets::AssetView;
//! use sidestr_core::records::record_script;
//!
//! let me = ScriptBuf::from_hex(&format!("5120{}", "ab".repeat(32))).unwrap();
//! let input = |txid: bitcoin::Txid, vout| TxIn { previous_output: OutPoint { txid, vout }, script_sig: ScriptBuf::new(), sequence: Sequence::MAX, witness: Witness::new() };
//! let out = |script: &ScriptBuf, sats| TxOut { value: Amount::from_sat(sats), script_pubkey: script.clone() };
//! let rec = |t: &str| TxOut { value: Amount::ZERO, script_pubkey: record_script(t).unwrap() };
//!
//! // issue 1000 DREAM onto output 0
//! let issue = Transaction { version: Version::TWO, lock_time: LockTime::ZERO,
//!     input: vec![input("11".repeat(32).parse().unwrap(), 0)],
//!     output: vec![out(&me, 330), rec("issue:DREAM:0"), rec("tally:self:0=1000")] };
//! let id = issue.compute_txid();
//! let mut view = AssetView::new();
//! view.apply_transactions(&[issue], 5);
//! assert_eq!(view.carried(&OutPoint { txid: id, vout: 0 }).unwrap()[&id], 1000);
//! assert_eq!(view.issued()[&id].ticker, "DREAM");
//!
//! // move 300 on, 700 back
//! let send = Transaction { version: Version::TWO, lock_time: LockTime::ZERO,
//!     input: vec![input(id, 0)],
//!     output: vec![out(&me, 330), out(&me, 330), rec(&format!("tally:{id}:0=300,1=700"))] };
//! let sid = send.compute_txid();
//! let outcome = view.apply_transactions(&[send], 6);
//! assert!(outcome[0].error.is_none());
//! assert_eq!(view.carried(&OutPoint { txid: sid, vout: 1 }).unwrap()[&id], 700);
//! assert!(view.carried(&OutPoint { txid: id, vout: 0 }).is_none());
//! ```

use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex, MutexGuard};

use bitcoin::{BlockHash, OutPoint, Transaction, Txid};

use crate::block::{HeaderFamily, SidestrBlock};
use crate::records::{classify, AssetRef, Classified};
use crate::rules::{BlockContext, BlockRule};

/// The id the assets rule reports in a verdict (`siding/lib/overlays/assets.mjs RULE`).
pub const RULE: &str = "sidestr:rule-assets";

/// What one output carries: asset id → amount.
pub type Carry = BTreeMap<Txid, u64>;

/// An issued asset.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Issued {
    /// Its ticker.
    pub ticker: String,
    /// Display decimals.
    pub decimals: u8,
    /// The height of the block that issued it.
    pub height: u32,
    /// The supply created: what `tally:self:` assigned.
    pub supply: u64,
    /// The binary market this asset is an outcome of, when it is a market's
    /// synthetic YES or NO asset.
    pub market: Option<Txid>,
}

/// A narrowly scoped exception to asset conservation.
///
/// The pool rule accounts for share minting and the markets rule accounts
/// for paired YES/NO minting.  [`AssetsRule`] consults this policy before it
/// accepts an assignment larger than the transaction's inputs carry; the
/// corresponding rule then validates the mint against its own collateral.
pub trait AssetMintPolicy: core::fmt::Debug + Send + Sync {
    /// Whether `asset` may be created by this classified transaction.
    fn allows(&self, asset: &Txid, txid: &Txid, classified: &Classified) -> bool;
}

/// How the view read one transaction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Outcome {
    /// The transaction.
    pub txid: Txid,
    /// `None` when the transaction keeps the rule; otherwise why its
    /// outputs carry nothing (the reference's `bad-tally` reason).
    pub error: Option<String>,
    /// What its inputs carried, per asset.
    pub carried_in: Carry,
    /// What each output carries now, by vout; empty when `error` is set.
    pub carried_out: BTreeMap<u32, Carry>,
}

/// The assets view over a chain: what each unspent output carries and
/// which assets exist. Feed it every block's transactions in order with
/// [`AssetView::apply_transactions`] (the coinbase included).
#[derive(Debug, Clone, Default)]
pub struct AssetView {
    carried: HashMap<OutPoint, Carry>,
    issued: BTreeMap<Txid, Issued>,
}

fn sum_into(total: &mut Carry, c: &Carry) {
    for (a, n) in c {
        let e = total.entry(*a).or_insert(0);
        *e = e.saturating_add(*n);
    }
}

impl AssetView {
    /// An empty view: a chain before its genesis.
    pub fn new() -> Self {
        Self::default()
    }

    /// What an unspent output carries, or `None` when it carries nothing.
    pub fn carried(&self, outpoint: &OutPoint) -> Option<&Carry> {
        self.carried.get(outpoint)
    }

    /// Every asset issued so far, by id.
    pub fn issued(&self) -> &BTreeMap<Txid, Issued> {
        &self.issued
    }

    /// The asset issued under `ticker`, the earliest when several share it.
    /// A ticker is not unique on a chain; an application that means one
    /// asset pins its id and uses this only to show a name.
    pub fn by_ticker(&self, ticker: &str) -> Option<(&Txid, &Issued)> {
        self.issued
            .iter()
            .filter(|(_, i)| i.ticker == ticker)
            .min_by_key(|(id, i)| (i.height, **id))
    }

    /// Check one transaction against the view as it stands, without
    /// changing it: `Ok(outputs)` is what each output would carry,
    /// `Err(reason)` is why the rule is broken. `carried_in` is filled in
    /// either way. A wallet runs this on what it built before it signs.
    pub fn check(
        &self,
        tx: &Transaction,
        carried_in: &mut Carry,
    ) -> Result<BTreeMap<u32, Carry>, String> {
        self.check_inner(tx, carried_in, None)
    }

    /// [`AssetView::check`] with a collateral rule allowed to account for
    /// selected minting (pool shares or market outcome pairs).
    pub fn check_with_mint_policy(
        &self,
        tx: &Transaction,
        carried_in: &mut Carry,
        policy: &dyn AssetMintPolicy,
    ) -> Result<BTreeMap<u32, Carry>, String> {
        self.check_inner(tx, carried_in, Some(policy))
    }

    fn check_inner(
        &self,
        tx: &Transaction,
        carried_in: &mut Carry,
        policy: Option<&dyn AssetMintPolicy>,
    ) -> Result<BTreeMap<u32, Carry>, String> {
        let txid = tx.compute_txid();
        let cls = classify(tx);
        if let Some(b) = cls.bad.first() {
            return Err(format!(
                "malformed record: {}",
                b.chars().take(40).collect::<String>()
            ));
        }
        if cls.issues.len() > 1 {
            return Err("at most one issue: per transaction".into());
        }
        let opens_pool = cls.pools.iter().any(|(_, p)| p.pool == AssetRef::SelfTx);
        if !cls.issues.is_empty() && opens_pool {
            return Err("a transaction that opens a pool does not issue".into());
        }
        for i in &tx.input {
            if let Some(c) = self.carried.get(&i.previous_output) {
                sum_into(carried_in, c);
            }
        }
        let mut out: BTreeMap<u32, Carry> = BTreeMap::new();
        let mut assigned: Carry = BTreeMap::new();
        let mut seen: Vec<Txid> = Vec::new();
        for (_, t) in &cls.tallies {
            let asset = match &t.asset {
                AssetRef::SelfTx => {
                    if cls.issues.is_empty() && !opens_pool {
                        return Err("tally:self without issue: or pool:self:".into());
                    }
                    txid
                }
                AssetRef::Id(id) => *id,
            };
            if seen.contains(&asset) {
                return Err(format!("asset {}… tallied twice", &asset.to_string()[..8]));
            }
            seen.push(asset);
            for (vout, amount) in &t.assigns {
                let o = tx
                    .output
                    .get(*vout as usize)
                    .ok_or_else(|| format!("tally names output {vout}, which does not exist"))?;
                if o.script_pubkey.is_op_return() {
                    return Err(format!("tally names output {vout}, an OP_RETURN"));
                }
                if o.value.to_sat() < 1 {
                    return Err(format!("tally names output {vout}, which has no value"));
                }
                out.entry(*vout).or_default().insert(asset, *amount);
                let e = assigned.entry(asset).or_insert(0);
                *e = e
                    .checked_add(*amount)
                    .ok_or_else(|| "a tally's sum overflows".to_string())?;
            }
        }
        for (asset, n) in &assigned {
            if *asset == txid && !cls.issues.is_empty() {
                continue; // issuance: created from nothing
            }
            if policy.is_some_and(|p| p.allows(asset, &txid, &cls)) {
                continue; // a collateral rule accounts for this mint
            }
            let have = carried_in.get(asset).copied().unwrap_or(0);
            if *n > have {
                return Err(format!(
                    "assigns {n} of {}… but carries {have}",
                    &asset.to_string()[..8]
                ));
            }
        }
        Ok(out)
    }

    /// Apply one block's transactions, the coinbase first, at `height`.
    /// Returns how each non-coinbase transaction was read. The coinbase
    /// carries nothing: records in it are ignored here, where a chain that
    /// names the rule would refuse the block.
    pub fn apply_transactions(&mut self, txs: &[Transaction], height: u32) -> Vec<Outcome> {
        self.apply_transactions_inner(txs, height, None)
    }

    /// [`AssetView::apply_transactions`] with a collateral rule accounting
    /// for selected mints.
    pub fn apply_transactions_with_mint_policy(
        &mut self,
        txs: &[Transaction],
        height: u32,
        policy: &dyn AssetMintPolicy,
    ) -> Vec<Outcome> {
        self.apply_transactions_inner(txs, height, Some(policy))
    }

    fn apply_transactions_inner(
        &mut self,
        txs: &[Transaction],
        height: u32,
        policy: Option<&dyn AssetMintPolicy>,
    ) -> Vec<Outcome> {
        let mut outcomes = Vec::new();
        for (i, tx) in txs.iter().enumerate() {
            let txid = tx.compute_txid();
            if i == 0 && tx.is_coinbase() {
                continue;
            }
            let mut carried_in = Carry::new();
            let result = self.check_inner(tx, &mut carried_in, policy);
            for inp in &tx.input {
                self.carried.remove(&inp.previous_output);
            }
            match result {
                Ok(out) => {
                    for (vout, c) in &out {
                        self.carried
                            .insert(OutPoint { txid, vout: *vout }, c.clone());
                    }
                    let cls = classify(tx);
                    if let Some((_, issue)) = cls.issues.first() {
                        let supply = out.values().filter_map(|c| c.get(&txid)).sum();
                        self.issued.insert(
                            txid,
                            Issued {
                                ticker: issue.ticker.clone(),
                                decimals: issue.decimals,
                                height,
                                supply,
                                market: None,
                            },
                        );
                    }
                    outcomes.push(Outcome {
                        txid,
                        error: None,
                        carried_in,
                        carried_out: out,
                    });
                }
                Err(e) => outcomes.push(Outcome {
                    txid,
                    error: Some(e),
                    carried_in,
                    carried_out: BTreeMap::new(),
                }),
            }
        }
        outcomes
    }

    /// Every unspent output carrying `asset`, with its amount.
    pub fn holdings(&self, asset: &Txid) -> impl Iterator<Item = (&OutPoint, u64)> + '_ {
        let asset = *asset;
        self.carried
            .iter()
            .filter_map(move |(op, c)| c.get(&asset).map(|n| (op, *n)))
    }
}

/// The assets rule as **consensus** (SPEC 12.2, `sidestr:rule-assets`,
/// `siding/lib/overlays/assets.mjs installChecks`, without the pool rule): a
/// block is valid under it when its coinbase carries no `issue:`, `tally:`
/// or malformed record, and every other transaction, in order, keeps the
/// rule against the view the ones before it leave ([`AssetView::check`]).
///
/// It answers to the document name `assets` ([`BlockRule::name`]). The view
/// a block leaves is kept until the block is applied
/// ([`BlockRule::applied`]); a block any rule refuses leaves the view as it
/// was. The rule is a handle: clones share one view, so a caller keeps a
/// clone to read it ([`AssetsRule::view`]) while the state holds another.
///
/// ```
/// use sidestr_core::assets::AssetsRule;
/// use sidestr_core::rules::BlockRule;
/// use sidestr_core::Stock;
///
/// let rule = AssetsRule::new();
/// assert_eq!(BlockRule::<Stock>::name(&rule), Some("assets"));
/// assert!(rule.view().issued().is_empty());
/// ```
#[derive(Debug, Clone)]
pub struct AssetsRule {
    held: Arc<Mutex<Held>>,
    mint_policy: Option<Arc<dyn AssetMintPolicy>>,
}

#[derive(Debug, Default)]
struct Held {
    view: AssetView,
    // the views candidate blocks would leave, by block hash, until one is applied
    pending: Vec<(BlockHash, AssetView, Vec<AssetTrace>)>,
}

#[derive(Debug, Clone, Default)]
pub(crate) struct AssetTrace {
    pub(crate) inputs: HashMap<OutPoint, Carry>,
    pub(crate) outputs: BTreeMap<u32, Carry>,
}

impl Default for AssetsRule {
    fn default() -> Self {
        Self {
            held: Arc::new(Mutex::new(Held::default())),
            mint_policy: None,
        }
    }
}

impl AssetsRule {
    /// The rule on an empty view: a chain before its genesis.
    pub fn new() -> Self {
        Self::default()
    }

    /// The rule with a collateral rule accounting for selected asset mints.
    pub fn with_mint_policy(policy: Arc<dyn AssetMintPolicy>) -> Self {
        Self {
            held: Arc::new(Mutex::new(Held::default())),
            mint_policy: Some(policy),
        }
    }

    /// The view as the applied blocks leave it.
    pub fn view(&self) -> AssetView {
        self.lock().view.clone()
    }

    /// Check one transaction against an independent candidate view using
    /// this rule's configured mint policy. Producers use this while ordering
    /// their mempool before a block exists.
    pub fn check_transaction(
        &self,
        view: &AssetView,
        tx: &Transaction,
        carried_in: &mut Carry,
    ) -> Result<BTreeMap<u32, Carry>, String> {
        view.check_inner(tx, carried_in, self.mint_policy.as_deref())
    }

    /// Apply transactions to an independent candidate view using this
    /// rule's configured mint policy.
    pub fn apply_to_view(&self, view: &mut AssetView, txs: &[Transaction], height: u32) {
        view.apply_transactions_inner(txs, height, self.mint_policy.as_deref());
    }

    fn lock(&self) -> MutexGuard<'_, Held> {
        // a panic while the lock was held leaves the data as consistent as the panicking call left it;
        // the next block is judged afresh from the applied view either way
        self.held.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// The view `txdata` (coinbase first) leaves on top of `view` at
    /// `height`, or why the block breaks the rule.
    pub fn judge(
        view: &AssetView,
        txdata: &[Transaction],
        height: u32,
    ) -> Result<AssetView, String> {
        Self::candidate(view, txdata, height, None).map(|(view, _)| view)
    }

    fn candidate(
        view: &AssetView,
        txdata: &[Transaction],
        height: u32,
        policy: Option<&dyn AssetMintPolicy>,
    ) -> Result<(AssetView, Vec<AssetTrace>), String> {
        if let Some(cb) = txdata.first() {
            let cls = classify(cb);
            if !cls.issues.is_empty() || !cls.tallies.is_empty() || !cls.bad.is_empty() {
                return Err("the coinbase carries no records".into());
            }
        }
        let mut next = view.clone();
        let mut traces = Vec::with_capacity(txdata.len());
        for (index, tx) in txdata.iter().enumerate() {
            let inputs = tx
                .input
                .iter()
                .filter_map(|input| {
                    next.carried(&input.previous_output)
                        .cloned()
                        .map(|carry| (input.previous_output, carry))
                })
                .collect();
            if index == 0 && tx.is_coinbase() {
                traces.push(AssetTrace {
                    inputs,
                    outputs: BTreeMap::new(),
                });
                continue;
            }
            let outcomes = next.apply_transactions_inner(std::slice::from_ref(tx), height, policy);
            let o = outcomes
                .into_iter()
                .next()
                .expect("a non-coinbase transaction has one asset outcome");
            if let Some(e) = o.error {
                return Err(format!("{}: {e}", o.txid));
            }
            traces.push(AssetTrace {
                inputs,
                outputs: o.carried_out,
            });
        }
        Ok((next, traces))
    }

    pub(crate) fn trace(&self, hash: &BlockHash) -> Option<Vec<AssetTrace>> {
        self.lock()
            .pending
            .iter()
            .find(|(candidate, _, _)| candidate == hash)
            .map(|(_, _, trace)| trace.clone())
    }

    pub(crate) fn register_market_assets(&self, market: Txid, no: Txid, height: u32) {
        let mut held = self.lock();
        for (id, ticker) in [(market, "YES"), (no, "NO")] {
            held.view.issued.entry(id).or_insert_with(|| Issued {
                ticker: ticker.into(),
                decimals: 0,
                height,
                supply: 0,
                market: Some(market),
            });
        }
    }
}

impl<F: HeaderFamily> BlockRule<F> for AssetsRule {
    fn id(&self) -> &str {
        RULE
    }

    fn name(&self) -> Option<&str> {
        Some("assets")
    }

    fn check(&self, ctx: &BlockContext<F>) -> Option<bool> {
        let hash = F::default().block_hash(ctx.block.header());
        let mut held = self.lock();
        match Self::candidate(
            &held.view,
            ctx.block.txdata(),
            ctx.height,
            self.mint_policy.as_deref(),
        ) {
            Ok((next, trace)) => {
                held.pending.retain(|(h, _, _)| *h != hash);
                held.pending.push((hash, next, trace));
                Some(true)
            }
            Err(_) => Some(false),
        }
    }

    fn applied(&self, block: &F::Block, height: u32) {
        let hash = F::default().block_hash(block.header());
        let mut held = self.lock();
        let pending = std::mem::take(&mut held.pending);
        match pending.into_iter().find(|(h, _, _)| *h == hash) {
            Some((_, v, _)) => held.view = v,
            // a block applied without this rule's check (the rule was added to the state later): read
            // as the view reads any block, a broken transaction carrying nothing onward
            None => {
                if let Some(policy) = self.mint_policy.as_deref() {
                    held.view
                        .apply_transactions_with_mint_policy(block.txdata(), height, policy);
                } else {
                    held.view.apply_transactions(block.txdata(), height);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::records::record_script;
    use bitcoin::{
        absolute::LockTime, transaction::Version, Amount, ScriptBuf, Sequence, TxIn, TxOut, Witness,
    };

    fn me() -> ScriptBuf {
        ScriptBuf::from_hex(&format!("5120{}", "ab".repeat(32))).unwrap()
    }
    fn tx(inputs: Vec<OutPoint>, outputs: Vec<TxOut>) -> Transaction {
        Transaction {
            version: Version::TWO,
            lock_time: LockTime::ZERO,
            input: inputs
                .into_iter()
                .map(|previous_output| TxIn {
                    previous_output,
                    script_sig: ScriptBuf::new(),
                    sequence: Sequence::MAX,
                    witness: Witness::new(),
                })
                .collect(),
            output: outputs,
        }
    }
    fn coin(sats: u64) -> TxOut {
        TxOut {
            value: Amount::from_sat(sats),
            script_pubkey: me(),
        }
    }
    fn rec(t: &str) -> TxOut {
        TxOut {
            value: Amount::ZERO,
            script_pubkey: record_script(t).unwrap(),
        }
    }
    fn op(txid: Txid, vout: u32) -> OutPoint {
        OutPoint { txid, vout }
    }
    fn funding() -> OutPoint {
        op("11".repeat(32).parse().unwrap(), 0)
    }

    fn issued(view: &mut AssetView, supply: u64) -> Txid {
        let t = tx(
            vec![funding()],
            vec![
                coin(330),
                rec("issue:DREAM:0"),
                rec(&format!("tally:self:0={supply}")),
            ],
        );
        let id = t.compute_txid();
        let o = view.apply_transactions(&[t], 1);
        assert!(o[0].error.is_none(), "{:?}", o[0].error);
        id
    }

    #[test]
    fn issuance_creates_the_supply() {
        let mut v = AssetView::new();
        let id = issued(&mut v, 1_000_000);
        assert_eq!(v.issued()[&id].supply, 1_000_000);
        assert_eq!(v.by_ticker("DREAM").unwrap().0, &id);
        assert_eq!(v.holdings(&id).map(|(_, n)| n).sum::<u64>(), 1_000_000);
    }

    #[test]
    fn over_assigning_is_broken_and_destroys_what_the_inputs_carried() {
        let mut v = AssetView::new();
        let id = issued(&mut v, 100);
        let t = tx(
            vec![op(id, 0)],
            vec![coin(330), rec(&format!("tally:{id}:0=101"))],
        );
        let o = v.apply_transactions(std::slice::from_ref(&t), 2);
        assert!(o[0].error.as_deref().unwrap().starts_with("assigns 101"));
        assert!(v.carried(&op(t.compute_txid(), 0)).is_none());
        assert_eq!(v.holdings(&id).count(), 0);
    }

    #[test]
    fn spending_without_a_tally_burns() {
        let mut v = AssetView::new();
        let id = issued(&mut v, 100);
        let t = tx(vec![op(id, 0)], vec![coin(300)]);
        let o = v.apply_transactions(&[t], 2);
        assert!(o[0].error.is_none());
        assert_eq!(o[0].carried_in[&id], 100);
        assert_eq!(v.holdings(&id).count(), 0);
    }

    #[test]
    fn the_rules_edges_follow_the_reference() {
        let mut v = AssetView::new();
        let id = issued(&mut v, 100);
        let two_issues = tx(
            vec![funding()],
            vec![coin(1), rec("issue:A:0"), rec("issue:B:0")],
        );
        let self_without_issue = tx(vec![funding()], vec![coin(1), rec("tally:self:0=5")]);
        let op_return = tx(
            vec![op(id, 0)],
            vec![rec("x"), rec(&format!("tally:{id}:0=5"))],
        );
        let missing = tx(
            vec![op(id, 0)],
            vec![coin(1), rec(&format!("tally:{id}:7=5"))],
        );
        let twice = tx(
            vec![op(id, 0)],
            vec![
                coin(1),
                rec(&format!("tally:{id}:0=5")),
                rec(&format!("tally:{id}:0=5")),
            ],
        );
        let malformed = tx(vec![funding()], vec![coin(1), rec("tally:nope")]);
        let zero_value = tx(
            vec![op(id, 0)],
            vec![coin(0), rec(&format!("tally:{id}:0=5"))],
        );
        for (t, want) in [
            (two_issues, "at most one issue"),
            (self_without_issue, "tally:self without"),
            (op_return, "an OP_RETURN"),
            (missing, "does not exist"),
            (twice, "tallied twice"),
            (malformed, "malformed record"),
            (zero_value, "has no value"),
        ] {
            let mut c = Carry::new();
            let e = v.check(&t, &mut c).unwrap_err();
            assert!(e.contains(want), "{e} lacks {want}");
        }
    }

    #[test]
    fn a_later_transaction_in_the_block_spends_an_earlier_ones_output() {
        let mut v = AssetView::new();
        let issue = tx(
            vec![funding()],
            vec![coin(330), rec("issue:DREAM:0"), rec("tally:self:0=10")],
        );
        let id = issue.compute_txid();
        let next = tx(
            vec![op(id, 0)],
            vec![coin(330), rec(&format!("tally:{id}:0=10"))],
        );
        let nid = next.compute_txid();
        let o = v.apply_transactions(&[issue, next], 1);
        assert!(o.iter().all(|o| o.error.is_none()));
        assert_eq!(v.carried(&op(nid, 0)).unwrap()[&id], 10);
    }
}