rgb-core 0.12.0

RGB Core Library: confidential & scalable smart contracts on Bitcoin & Lightning (consensus layer)
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
721
722
723
724
// RGB Core Library: consensus layer for RGB smart contracts.
//
// SPDX-License-Identifier: Apache-2.0
//
// Designed in 2019-2025 by Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
// Written in 2024-2025 by Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
//
// Copyright (C) 2019-2024 LNP/BP Standards Association, Switzerland.
// Copyright (C) 2024-2025 LNP/BP Laboratories,
//                         Institute for Distributed and Cognitive Systems (InDCS), Switzerland.
// Copyright (C) 2025 RGB Consortium, Switzerland.
// Copyright (C) 2019-2025 Dr Maxim Orlovsky.
// All rights under the above copyrights are reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under
// the License.

use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;
use core::error::Error;
use core::fmt::{Debug, Formatter};

use amplify::confinement::SmallOrdMap;
use amplify::ByteArray;
use single_use_seals::{PublishedWitness, SealError, SealWitness};
use ultrasonic::{
    AuthToken, CallError, CellAddr, Codex, ContractId, LibRepo, Memory, Operation, Opid, VerifiedOperation,
};

use crate::{RgbSeal, RgbSealDef, LIB_NAME_RGB};

/// Combination of an operation with operation-defined seals.
///
/// An operation contains only [`AuthToken`]'s, which are commitments to seal definitions.
/// Hence, we have to separately include a full seal definition next to the operation data.
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_RGB)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(
        rename_all = "camelCase",
        bound = "Seal::Definition: serde::Serialize + for<'d> serde::Deserialize<'d>, Seal::PubWitness: \
                 serde::Serialize + for<'d> serde::Deserialize<'d>, Seal::CliWitness: serde::Serialize + for<'d> \
                 serde::Deserialize<'d>"
    )
)]
pub struct OperationSeals<Seal: RgbSeal> {
    /// The operation.
    pub operation: Operation,
    /// Seals defined by an operation.
    pub defined_seals: SmallOrdMap<u16, Seal::Definition>,
    /// An optional witness for the closing of the operation input seals.
    pub witness: Option<SealWitness<Seal>>,
}

impl<Seal: RgbSeal> Clone for OperationSeals<Seal>
where
    Seal::PubWitness: Clone,
    Seal::CliWitness: Clone,
{
    fn clone(&self) -> Self {
        Self {
            operation: self.operation.clone(),
            defined_seals: self.defined_seals.clone(),
            witness: self.witness.clone(),
        }
    }
}

/// Provider which reads an operation and its seals from a consignment stream.
pub trait ReadOperation: Sized {
    /// Seal definition type used by operations.
    type Seal: RgbSeal;

    /// Reads an operation and its seals from a consignment stream and initialize the witness
    /// reader.
    fn read_operation(&mut self) -> Result<Option<OperationSeals<Self::Seal>>, impl Error + 'static>;
}

/// API exposed by the contract required for evaluating and verifying the contract state (see
/// [`ContractVerify`]).
///
/// NB: `apply_operation` is called only after `apply_witness`.
pub trait ContractApi<Seal: RgbSeal> {
    /// Returns contract id for the processed contract.
    ///
    /// Called only once during the operation verification.
    fn contract_id(&self) -> ContractId;

    /// Returns a codex against which the contract must be verified.
    ///
    /// Called only once during the operation verification.
    fn codex(&self) -> &Codex;

    /// Returns repository providing script libraries used during the verification.
    ///
    /// Called only once during the operation verification.
    fn repo(&self) -> &impl LibRepo;

    /// Returns a memory implementation providing read access to all the contract state cells,
    /// including immutable and destructible memory.
    fn memory(&self) -> &impl Memory;

    /// Detects whether an operation with a given id is already known as a _valid_ operation for the
    /// ledger.
    ///
    /// The method MUST return `true` for genesis operation.
    fn is_known(&self, opid: Opid) -> bool;

    /// # Nota bene:
    ///
    /// The method is called only for those operations which are not known (i.e. [`Self::is_known`]
    /// returns `false` for the operation id).
    ///
    /// The method is NOT called for the genesis operation.
    fn apply_operation(&mut self, op: VerifiedOperation);

    /// # Nota bene:
    ///
    /// The method is called for all operations, including known ones, for which the consignment
    /// provides at least single seal definition information (thus, it may be called for the genesis
    /// operation as well).
    fn apply_seals(&mut self, opid: Opid, seals: SmallOrdMap<u16, Seal::Definition>);

    /// # Nota bene:
    ///
    /// The method is called for all operations, including known ones, which have a witness (i.e.,
    /// except genesis or operations with no destroyed state).
    fn apply_witness(&mut self, opid: Opid, witness: SealWitness<Seal>);
}

/// Main implementation of the contract verification procedure.
///
/// # Nota bene
///
/// This trait cannot be manually implemented; it is always accessible as a blanked implementation
/// for all types implementing [`ContractApi`] trait.
///
/// The purpose of the trait is to prevent overriding of the implementation in client libraries.
pub trait ContractVerify<Seal: RgbSeal>: ContractApi<Seal> {
    /// Evaluate contract state by verifying and applying contract operations coming from a
    /// consignment `reader`.
    fn evaluate<R: ReadOperation<Seal = Seal>>(&mut self, mut reader: R) -> Result<(), VerificationError<Seal>> {
        let contract_id = self.contract_id();
        let codex_id = self.codex().codex_id();

        let mut is_genesis = true;
        let mut seals = BTreeMap::<CellAddr, Seal>::new();

        while let Some(mut block) = reader
            .read_operation()
            .map_err(|e| VerificationError::Stream(Box::new(e)))?
        {
            // Genesis cannot commit to the contract id since the contract does not exist yet;
            // thus, we have to apply this little trick
            if is_genesis {
                if block.operation.contract_id.to_byte_array() != codex_id.to_byte_array() {
                    return Err(VerificationError::NoCodexCommitment);
                }
                block.operation.contract_id = contract_id;
            }
            let opid = block.operation.opid();

            // We need to check that all seal definitions strictly match operation-defined destructible cells
            let defined = block
                .operation
                .destructible_out
                .iter()
                .map(|cell| cell.auth)
                .collect::<BTreeSet<_>>();
            let reported = block
                .defined_seals
                .values()
                .map(|seal| seal.auth_token())
                .collect::<BTreeSet<_>>();
            // It is a subset and not an equal set since some seals might be unknown to us:
            // we know their commitment auth token but do not know the definition.
            if !reported.is_subset(&defined) {
                let sources = block
                    .defined_seals
                    .iter()
                    .map(|(pos, seal)| (*pos, seal.to_string()))
                    .collect();
                return Err(VerificationError::SealsDefinitionMismatch { opid, reported, defined, sources });
            }

            // Collect single-use seal closings by the operation
            let mut closed_seals = Vec::<Seal>::new();
            for input in &block.operation.destructible_in {
                let seal = seals
                    .remove(&input.addr)
                    .ok_or(VerificationError::SealUnknown(input.addr))?;
                closed_seals.push(seal);
            }

            // If the operation was validated before, we need to skip its validation, since its inputs are not a
            // part of the state anymore.
            let operation = if self.is_known(opid) {
                None
            } else {
                // Verify the operation
                let verified = self
                    .codex()
                    .verify(contract_id, block.operation, self.memory(), self.repo())?;
                Some(verified)
            };

            // This convoluted logic happens since we use a state machine which ensures the client can't lie to
            // the verifier
            // Now we can add operation-defined seals to the set of known seals
            let mut seal_sources: BTreeSet<_> = block
                .defined_seals
                .iter()
                .filter_map(|(pos, seal)| seal.to_src().map(|seal| (CellAddr::new(opid, *pos), seal)))
                .collect();

            if let Some(witness) = block.witness {
                let msg = opid.to_byte_array();
                witness
                    .verify_seals_closing(&closed_seals, msg.into())
                    .map_err(|e| VerificationError::SealsNotClosed(witness.published.pub_id(), opid, e))?;

                //  Each witness actually produces its own set of witness-output-based seal sources.
                let pub_id = witness.published.pub_id();
                let iter = block
                    .defined_seals
                    .iter()
                    .filter(|(_, seal)| seal.to_src().is_none())
                    .map(|(pos, seal)| (CellAddr::new(opid, *pos), seal.resolve(pub_id)));
                seal_sources.extend(iter);

                self.apply_witness(opid, witness);
            } else if !closed_seals.is_empty() {
                return Err(VerificationError::NoWitness(opid));
            }

            seals.extend(seal_sources);
            if is_genesis {
                is_genesis = false
            } else if let Some(operation) = operation {
                self.apply_operation(operation);
            }

            if !block.defined_seals.is_empty() {
                self.apply_seals(opid, block.defined_seals);
            }
        }

        Ok(())
    }
}

impl<Seal: RgbSeal, C: ContractApi<Seal>> ContractVerify<Seal> for C {}

/// Errors returned from the verification.
#[derive(Display, Error, From)]
#[display(doc_comments)]
pub enum VerificationError<Seal: RgbSeal> {
    /// error reading the consignment stream.
    ///
    /// Details: {0}
    Stream(Box<dyn Error>),

    /// genesis does not commit to the codex id; a wrong contract genesis is used.
    NoCodexCommitment,

    /// no witness known for the operation {0}.
    NoWitness(Opid),

    /// single-use seals are not closed properly with witness {0} for operation {1}.
    ///
    /// Details: {2}
    SealsNotClosed(<Seal::PubWitness as PublishedWitness<Seal>>::PubId, Opid, SealError<Seal>),

    /// unknown seal definition for cell address {0}.
    SealUnknown(CellAddr),

    /// seals, reported to be defined by the operation {opid}, do match the assignments in the
    /// operation.
    ///
    /// Actual operation seals from the assignments: {defined:#?}
    ///
    /// Reported seals: {reported:#?}
    ///
    /// Sources for the reported seals: {sources:#?}
    #[allow(missing_docs)]
    SealsDefinitionMismatch {
        opid: Opid,
        reported: BTreeSet<AuthToken>,
        defined: BTreeSet<AuthToken>,
        sources: BTreeMap<u16, String>,
    },

    /// Eror returned by the virtual machine script.
    #[from]
    #[display(inner)]
    Vm(CallError),
}

// We need manual implementation since otherwise we get an unneeded `Seal::PubWitness: Debug` bound
impl<Seal: RgbSeal> Debug for VerificationError<Seal> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "{self}") }
}

#[cfg(test)]
mod test {
    #![cfg_attr(coverage_nightly, coverage(off))]

    use std::collections::HashMap;
    use std::convert::Infallible;
    use std::vec;

    use bp::seals::{TxoSeal, TxoSealExt, WOutpoint, WTxoSeal};
    use bp::{Outpoint, Sats, ScriptPubkey, SeqNo, Tx, TxIn, TxOut, Vout};
    use strict_encoding::StrictDumb;
    use ultrasonic::aluvm::alu::{aluasm, CoreConfig, Lib, LibId, LibSite};
    use ultrasonic::aluvm::FIELD_ORDER_SECP;
    use ultrasonic::{fe256, CodexId, Genesis, Identity, Input, StateCell, StateData, StateValue};

    use super::*;

    #[derive(Clone)]
    struct TestReader(vec::IntoIter<OperationSeals<TxoSeal>>);
    impl ReadOperation for TestReader {
        type Seal = TxoSeal;
        fn read_operation(&mut self) -> Result<Option<OperationSeals<Self::Seal>>, impl Error + 'static> {
            Result::<_, Infallible>::Ok(self.0.next())
        }
    }
    impl TestReader {
        pub fn new(vec: Vec<OperationSeals<TxoSeal>>) -> Self { Self(vec.into_iter()) }
    }

    struct TestContract {
        pub codex: Codex,
        pub contract_id: ContractId,
        pub libs: HashMap<LibId, Lib>,
        pub global: HashMap<CellAddr, StateValue>,
        pub owned: HashMap<CellAddr, StateCell>,
        pub known_ops: BTreeMap<Opid, Operation>,
        pub seal_definitions: BTreeMap<Opid, HashMap<u16, WTxoSeal>>,
        pub witnesses: BTreeMap<Opid, Vec<SealWitness<TxoSeal>>>,
    }
    impl Memory for TestContract {
        fn destructible(&self, addr: CellAddr) -> Option<StateCell> { self.owned.get(&addr).cloned() }
        fn immutable(&self, addr: CellAddr) -> Option<StateValue> { self.global.get(&addr).cloned() }
    }
    impl LibRepo for TestContract {
        fn get_lib(&self, lib_id: LibId) -> Option<&Lib> { self.libs.get(&lib_id) }
    }
    impl ContractApi<TxoSeal> for TestContract {
        fn contract_id(&self) -> ContractId { self.contract_id }
        fn codex(&self) -> &Codex { &self.codex }
        fn repo(&self) -> &impl LibRepo { self }
        fn memory(&self) -> &impl Memory { self }
        fn is_known(&self, opid: Opid) -> bool { self.known_ops.contains_key(&opid) }
        fn apply_operation(&mut self, op: VerifiedOperation) {
            let opid = op.opid();
            let op = op.into_operation();
            for (no, inp) in op.immutable_out.iter().enumerate() {
                self.global
                    .insert(CellAddr::new(opid, no as u16), inp.value);
            }
            for (no, inp) in op.destructible_out.iter().enumerate() {
                self.owned.insert(CellAddr::new(opid, no as u16), *inp);
            }
            self.known_ops.insert(opid, op);
        }
        fn apply_seals(&mut self, opid: Opid, seals: SmallOrdMap<u16, WTxoSeal>) {
            self.seal_definitions.entry(opid).or_default().extend(seals);
        }
        fn apply_witness(&mut self, opid: Opid, witness: SealWitness<TxoSeal>) {
            self.witnesses.entry(opid).or_default().push(witness);
        }
    }

    fn lib() -> Lib {
        let code = aluasm! {
            stop;
        };
        Lib::assemble(&code).unwrap()
    }

    fn codex() -> Codex {
        let lib_id = lib().lib_id();
        Codex {
            name: tiny_s!("TestCodex"),
            developer: Identity::default(),
            version: default!(),
            features: default!(),
            timestamp: 1732529307,
            field_order: FIELD_ORDER_SECP,
            input_config: CoreConfig::default(),
            verification_config: CoreConfig::default(),
            verifiers: tiny_bmap! {
                0 => LibSite::new(lib_id, 0),
            },
        }
    }

    const SEAL_WOUT: WTxoSeal = WTxoSeal {
        primary: WOutpoint::Wout(Vout::from_u32(0)),
        secondary: TxoSealExt::Fallback(Outpoint::coinbase()),
    };

    const SEAL_1: WTxoSeal = WTxoSeal {
        primary: WOutpoint::Extern(Outpoint::coinbase()),
        secondary: TxoSealExt::Fallback(Outpoint::coinbase()),
    };

    fn genesis() -> Genesis {
        let mut genesis = Genesis::strict_dumb();
        genesis.codex_id = codex().codex_id();
        genesis.immutable_out = small_vec![StateData::new(0u64, 1000u64)];
        genesis.destructible_out = small_vec![StateCell {
            data: StateValue::None,
            auth: SEAL_1.auth_token(),
            lock: None
        }];
        genesis
    }

    fn contract() -> TestContract {
        let lib = lib();
        let lib_id = lib.lib_id();
        let genesis = genesis();
        let genesis_op = genesis.to_operation(ContractId::strict_dumb());
        let genesis_opid = genesis_op.opid();
        TestContract {
            codex: codex(),
            contract_id: ContractId::strict_dumb(),
            libs: map! { lib_id => lib },
            global: none!(),
            owned: map! { CellAddr::new(genesis_opid, 0) => genesis_op.destructible_out[0] },
            known_ops: bmap! { genesis_opid => genesis_op },
            seal_definitions: bmap! { genesis_opid => none!() },
            witnesses: bmap! { genesis_opid => none!() },
        }
    }

    fn operation() -> Operation {
        let genesis = genesis();
        let contract = contract();
        let genesis_op = genesis.to_operation(contract.contract_id);
        let genesis_opid = genesis_op.opid();
        Operation {
            version: default!(),
            contract_id: contract.contract_id,
            call_id: 0,
            nonce: fe256::ZERO,
            witness: StateValue::None,
            destructible_in: small_vec![Input {
                addr: CellAddr::new(genesis_opid, 0),
                witness: StateValue::None
            }],
            immutable_in: Default::default(),
            destructible_out: Default::default(),
            immutable_out: Default::default(),
        }
    }

    #[allow(clippy::result_large_err)]
    fn run(reader: TestReader) -> Result<(), VerificationError<TxoSeal>> {
        let mut contract = contract();
        contract.evaluate(reader.clone())?;

        // Check contract values
        let mut ops = bmap! {};
        let mut seals = bmap! {};
        let mut witnesses = bmap! {};
        for entry in reader.0 {
            let opid = entry.operation.opid();
            ops.insert(opid, entry.operation);
            seals.insert(opid, entry.defined_seals.into_iter().collect());
            witnesses.insert(opid, entry.witness.into_iter().collect());
        }

        ops.pop_first();
        let (genesis_opid, genesis_op) = contract.known_ops.first_key_value().unwrap();
        ops.insert(*genesis_opid, genesis_op.clone());
        seals.pop_first();
        let (genesis_opid, definitions) = contract.seal_definitions.first_key_value().unwrap();
        seals.insert(*genesis_opid, definitions.clone());
        witnesses.pop_first();
        let (genesis_opid, definitions) = contract.witnesses.first_key_value().unwrap();
        witnesses.insert(*genesis_opid, definitions.clone());

        assert_eq!(ops, contract.known_ops);
        assert_eq!(seals, contract.seal_definitions);
        assert_eq!(witnesses, contract.witnesses);
        Ok(())
    }

    #[test]
    fn empty() {
        let reader = TestReader::new(vec![]);
        run(reader).unwrap();
    }

    #[test]
    fn genesis_only() {
        let genesis = genesis();
        let genesis_op = genesis.to_operation(genesis.codex_id.to_byte_array().into());

        let reader =
            TestReader::new(vec![OperationSeals { operation: genesis_op, defined_seals: none!(), witness: None }]);
        run(reader).unwrap();
    }

    #[test]
    #[should_panic(expected = "genesis does not commit to the codex id; a wrong contract genesis is used.")]
    fn invalid_genesis() {
        let mut genesis = genesis();
        genesis.codex_id = CodexId::from_byte_array([0xAD; 32]);
        let genesis_op = genesis.to_operation(genesis.codex_id.to_byte_array().into());

        let reader =
            TestReader::new(vec![OperationSeals { operation: genesis_op, defined_seals: none!(), witness: None }]);
        run(reader).unwrap();
    }

    #[test]
    #[should_panic(expected = "seals, reported to be defined by the operation \
                               k7fHvPyBlnM8m1n0QUaqNhB0I8kTwWXmi7nB_ZjTGVc, do match the assignments in the \
                               operation.
Actual operation seals from the assignments: {
    AuthToken(
        fe256(
            0x0000141b74832b85ca7bc7e2899cc3e5617a29ac4340f09b105524a6f62bd597,
        ),
    ),
}
Reported seals: {
    AuthToken(
        fe256(
            0x000046c31ad97975e90e4ab2ee247f0e2f39ec8461823023e977cc14bcda14f5,
        ),
    ),
}
Sources for the reported seals: {
    0: \"~:0/00000000000000000000000000000000000000000000000000000000000000000000000000000000\",
}")]
    fn invalid_seals() {
        let genesis = genesis();
        let genesis_op = genesis.to_operation(genesis.codex_id.to_byte_array().into());

        let reader = TestReader::new(vec![OperationSeals {
            operation: genesis_op,
            defined_seals: small_bmap! { 0 => WTxoSeal::strict_dumb() },
            witness: None,
        }]);
        run(reader).unwrap();
    }

    #[test]
    #[should_panic(expected = "unknown seal definition for cell address k7fHvPyBlnM8m1n0QUaqNhB0I8kTwWXmi7nB_ZjTGVc:0.")]
    fn seal_unknown() {
        let genesis = genesis();
        let genesis_op = genesis.to_operation(genesis.codex_id.to_byte_array().into());
        let operation = operation();

        let reader = TestReader::new(vec![
            OperationSeals { operation: genesis_op, defined_seals: none!(), witness: None },
            OperationSeals { operation, defined_seals: none!(), witness: None },
        ]);
        run(reader).unwrap();
    }

    #[test]
    #[should_panic(expected = "unknown seal definition for cell address k7fHvPyBlnM8m1n0QUaqNhB0I8kTwWXmi7nB_ZjTGVc:0.")]
    fn genesis_with_wout() {
        let mut genesis = genesis();
        genesis.destructible_out[0].auth = SEAL_WOUT.auth_token();
        let genesis_op = genesis.to_operation(genesis.codex_id.to_byte_array().into());
        let operation = operation();

        let reader = TestReader::new(vec![
            OperationSeals {
                operation: genesis_op,
                defined_seals: small_bmap! { 0 => SEAL_WOUT},
                witness: None,
            },
            OperationSeals { operation, defined_seals: none!(), witness: None },
        ]);
        run(reader).unwrap();
    }

    #[test]
    #[should_panic(expected = "no witness known for the operation KAPb7ikgqk_ofCp1fZWm_T6XfKjuCwNf9BlZfPpoR0E.")]
    fn no_witness() {
        let genesis = genesis();
        let genesis_op = genesis.to_operation(genesis.codex_id.to_byte_array().into());
        let operation = operation();

        let reader = TestReader::new(vec![
            OperationSeals {
                operation: genesis_op,
                defined_seals: small_bmap! { 0 => SEAL_1 },
                witness: None,
            },
            OperationSeals { operation, defined_seals: none!(), witness: None },
        ]);
        run(reader).unwrap();
    }

    #[test]
    #[should_panic(expected = "single-use seals are not closed properly with witness \
                               4ebd325a4b394cff8c57e8317ccf5a8d0e2bdf1b8526f8aad6c8e43d8240621a for operation \
                               KAPb7ikgqk_ofCp1fZWm_T6XfKjuCwNf9BlZfPpoR0E.
Details: seal \
                               0000000000000000000000000000000000000000000000000000000000000000:0/\
                               0000000000000000000000000000000000000000000000000000000000000000:0 is not included in \
                               the public witness 4ebd325a4b394cff8c57e8317ccf5a8d0e2bdf1b8526f8aad6c8e43d8240621a")]
    fn seals_unclosed() {
        let genesis = genesis();
        let genesis_op = genesis.to_operation(genesis.codex_id.to_byte_array().into());
        let operation = operation();

        let reader = TestReader::new(vec![
            OperationSeals {
                operation: genesis_op,
                defined_seals: small_bmap! { 0 => SEAL_1 },
                witness: None,
            },
            OperationSeals {
                operation,
                defined_seals: none!(),
                witness: Some(SealWitness::new(strict_dumb!(), strict_dumb!())),
            },
        ]);
        run(reader).unwrap();
    }

    #[test]
    #[should_panic(expected = "ingle-use seals are not closed properly with witness \
                               1692606e775129a6733b6dc48ec7f5771f8e30d8c5304c0949d36efad2411812 for operation \
                               KAPb7ikgqk_ofCp1fZWm_T6XfKjuCwNf9BlZfPpoR0E.
Details: seal \
                               0000000000000000000000000000000000000000000000000000000000000000:0/\
                               0000000000000000000000000000000000000000000000000000000000000000:0 is not included in \
                               the public witness 1692606e775129a6733b6dc48ec7f5771f8e30d8c5304c0949d36efad2411812")]
    fn not_spending_utxo() {
        let genesis = genesis();
        let genesis_op = genesis.to_operation(genesis.codex_id.to_byte_array().into());
        let operation = operation();

        let mut witness = Tx::strict_dumb();
        witness
            .outputs
            .push(TxOut {
                value: Sats::ZERO,
                script_pubkey: ScriptPubkey::op_return(&[]),
            })
            .unwrap();

        let reader = TestReader::new(vec![
            OperationSeals {
                operation: genesis_op,
                defined_seals: small_bmap! { 0 => SEAL_1 },
                witness: None,
            },
            OperationSeals {
                operation,
                defined_seals: none!(),
                witness: Some(SealWitness::new(witness, strict_dumb!())),
            },
        ]);
        run(reader).unwrap();
    }

    #[test]
    #[should_panic(expected = "single-use seals are not closed properly with witness \
                               0520b790b442e9c023e2ea0e0e284fbe60086d64f01037082f19464b44f9642e for operation \
                               KAPb7ikgqk_ofCp1fZWm_T6XfKjuCwNf9BlZfPpoR0E.
Details: seal \
                               0000000000000000000000000000000000000000000000000000000000000000:0/\
                               0000000000000000000000000000000000000000000000000000000000000000:0 is not included in \
                               the public witness 0520b790b442e9c023e2ea0e0e284fbe60086d64f01037082f19464b44f9642e")]
    fn missing_commitment() {
        let genesis = genesis();
        let genesis_op = genesis.to_operation(genesis.codex_id.to_byte_array().into());
        let operation = operation();

        let mut witness = Tx::strict_dumb();
        witness
            .inputs
            .push(TxIn {
                prev_output: Outpoint::coinbase(),
                sig_script: none!(),
                sequence: SeqNo::from_consensus_u32(0),
                witness: none!(),
            })
            .unwrap();
        witness
            .outputs
            .push(TxOut {
                value: Sats::ZERO,
                script_pubkey: ScriptPubkey::op_return(&[]),
            })
            .unwrap();

        let reader = TestReader::new(vec![
            OperationSeals {
                operation: genesis_op,
                defined_seals: small_bmap! { 0 => SEAL_1 },
                witness: None,
            },
            OperationSeals {
                operation,
                defined_seals: none!(),
                witness: Some(SealWitness::new(witness, strict_dumb!())),
            },
        ]);
        run(reader).unwrap();
    }
}