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
// LNP/BP Core Library implementing LNPBP specifications & standards
// Written in 2020 by
//     Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.

use core::iter::FromIterator;
use core::ops::AddAssign;
use std::collections::{BTreeMap, BTreeSet, VecDeque};

use bitcoin::{Transaction, Txid};
use lnpbp::client_side_validation::CommitConceal;
use wallet::resolvers::TxResolver;

use super::schema::{NodeType, OccurrencesError};
use super::{
    schema, seal, Anchor, AnchorId, Assignments, Consignment, ContractId, Node,
    NodeId, Schema, SchemaId,
};
use crate::SealEndpoint;

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Display)]
#[display(Debug)]
#[repr(u8)]
pub enum Validity {
    Valid,
    UnresolvedTransactions,
    Invalid,
}

#[derive(Clone, Debug, Display, Default, StrictEncode, StrictDecode)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
#[strict_encoding_crate(lnpbp::strict_encoding)]
// TODO: Display via YAML
#[display(Debug)]
pub struct Status {
    pub unresolved_txids: Vec<Txid>,
    pub failures: Vec<Failure>,
    pub warnings: Vec<Warning>,
    pub info: Vec<Info>,
}

impl AddAssign for Status {
    fn add_assign(&mut self, rhs: Self) {
        self.unresolved_txids.extend(rhs.unresolved_txids);
        self.failures.extend(rhs.failures);
        self.warnings.extend(rhs.warnings);
        self.info.extend(rhs.info);
    }
}

// TODO: (new) With rust `try_trait` stabilization re-implement using
//       `Try` trait
// impl Try for Status {
//    type Ok = Status;
//    type Error = Failure;
//    pub fn into_result(self) -> Result<Self::Ok, Self::Error> {
//        unimplemented!()
//    }
//    pub fn from_ok(v: Self::Ok) -> Self {
//        v
//    }
impl Status {
    pub fn from_error(v: Failure) -> Self {
        Status {
            unresolved_txids: vec![],
            failures: vec![v],
            warnings: vec![],
            info: vec![],
        }
    }
}

impl FromIterator<Failure> for Status {
    fn from_iter<T: IntoIterator<Item = Failure>>(iter: T) -> Self {
        Self {
            failures: iter.into_iter().collect(),
            ..Self::default()
        }
    }
}

impl Status {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_failure(failure: Failure) -> Self {
        Self {
            failures: vec![failure],
            ..Self::default()
        }
    }

    pub fn add_failure(&mut self, failure: Failure) -> &Self {
        self.failures.push(failure);
        self
    }

    pub fn add_warning(&mut self, warning: Warning) -> &Self {
        self.warnings.push(warning);
        self
    }

    pub fn add_info(&mut self, info: Info) -> &Self {
        self.info.push(info);
        self
    }

    pub fn validity(&self) -> Validity {
        if !self.failures.is_empty() {
            Validity::Invalid
        } else if !self.unresolved_txids.is_empty() {
            Validity::UnresolvedTransactions
        } else {
            Validity::Valid
        }
    }
}

#[derive(
    Clone, PartialEq, Eq, Debug, Display, From, StrictEncode, StrictDecode,
)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
#[strict_encoding_crate(lnpbp::strict_encoding)]
// TODO: (v0.3) convert to detailed error description using doc_comments
#[display(Debug)]
pub enum Failure {
    SchemaUnknown(SchemaId),
    /// Root schema for this schema has another root, which is prohibited
    SchemaRootHierarchy(SchemaId),
    SchemaRootNoFieldTypeMatch(schema::FieldType),
    SchemaRootNoOwnedRightTypeMatch(schema::OwnedRightType),
    SchemaRootNoPublicRightTypeMatch(schema::PublicRightType),
    SchemaRootNoTransitionTypeMatch(schema::TransitionType),
    SchemaRootNoExtensionTypeMatch(schema::ExtensionType),

    SchemaRootNoMetadataMatch(NodeType, schema::FieldType),
    SchemaRootNoParentOwnedRightsMatch(NodeType, schema::OwnedRightType),
    SchemaRootNoParentPublicRightsMatch(NodeType, schema::PublicRightType),
    SchemaRootNoOwnedRightsMatch(NodeType, schema::OwnedRightType),
    SchemaRootNoPublicRightsMatch(NodeType, schema::PublicRightType),
    SchemaRootNoAbiMatch {
        node_type: NodeType,
        action_id: u16,
    },

    SchemaUnknownExtensionType(NodeId, schema::ExtensionType),
    SchemaUnknownTransitionType(NodeId, schema::TransitionType),
    SchemaUnknownFieldType(NodeId, schema::FieldType),
    SchemaUnknownOwnedRightType(NodeId, schema::OwnedRightType),
    SchemaUnknownPublicRightType(NodeId, schema::PublicRightType),

    SchemaDeniedScriptExtension(NodeId),

    SchemaMetaValueTooSmall(schema::FieldType),
    SchemaMetaValueTooLarge(schema::FieldType),
    SchemaStateValueTooSmall(schema::OwnedRightType),
    SchemaStateValueTooLarge(schema::OwnedRightType),

    SchemaMismatchedBits {
        field_or_state_type: usize,
        expected: schema::Bits,
    },
    SchemaWrongEnumValue {
        field_or_state_type: usize,
        unexpected: u8,
    },
    SchemaWrongDataLength {
        field_or_state_type: usize,
        max_expected: u16,
        found: usize,
    },
    SchemaMismatchedDataType(usize),
    SchemaMismatchedStateType(schema::OwnedRightType),

    SchemaMetaOccurencesError(NodeId, schema::FieldType, OccurrencesError),
    SchemaParentOwnedRightOccurencesError(
        NodeId,
        schema::OwnedRightType,
        OccurrencesError,
    ),
    SchemaOwnedRightOccurencesError(
        NodeId,
        schema::OwnedRightType,
        OccurrencesError,
    ),

    TransitionAbsent(NodeId),
    TransitionNotAnchored(NodeId),
    TransitionNotInAnchor(NodeId, AnchorId),
    TransitionParentWrongSealType {
        node_id: NodeId,
        ancestor_id: NodeId,
        assignment_type: schema::OwnedRightType,
    },
    TransitionParentWrongSeal {
        node_id: NodeId,
        ancestor_id: NodeId,
        assignment_type: schema::OwnedRightType,
        seal_index: u16,
    },
    TransitionParentConfidentialSeal {
        node_id: NodeId,
        ancestor_id: NodeId,
        assignment_type: schema::OwnedRightType,
        seal_index: u16,
    },
    TransitionParentIsNotWitnessInput {
        node_id: NodeId,
        ancestor_id: NodeId,
        assignment_type: schema::OwnedRightType,
        seal_index: u16,
        outpoint: bitcoin::OutPoint,
    },

    ExtensionAbsent(NodeId),
    ExtensionParentWrongValenciesType {
        node_id: NodeId,
        ancestor_id: NodeId,
        valencies_type: schema::PublicRightType,
    },

    WitnessTransactionMissed(Txid),
    WitnessNoCommitment(NodeId, AnchorId, Txid),

    EndpointTransitionNotFound(NodeId),

    SimplicityIsNotSupportedYet,
    ScriptFailure(NodeId, u8),
}

#[derive(
    Clone, PartialEq, Eq, Debug, Display, From, StrictEncode, StrictDecode,
)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
#[strict_encoding_crate(lnpbp::strict_encoding)]
// TODO: (v0.3) convert to detailed descriptions using doc_comments
#[display(Debug)]
pub enum Warning {
    EndpointDuplication(NodeId, SealEndpoint),
    EndpointTransitionSealNotFound(NodeId, SealEndpoint),
    ExcessiveTransition(NodeId),
}

#[derive(
    Clone, PartialEq, Eq, Debug, Display, From, StrictEncode, StrictDecode,
)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
#[strict_encoding_crate(lnpbp::strict_encoding)]
// TODO: (v0.3) convert to detailed descriptions using doc_comments
#[display(Debug)]
pub enum Info {
    UncheckableConfidentialStateData(NodeId, usize),
}

pub struct Validator<'validator, R: TxResolver> {
    consignment: &'validator Consignment,

    status: Status,

    schema_id: SchemaId,
    genesis_id: NodeId,
    contract_id: ContractId,
    node_index: BTreeMap<NodeId, &'validator dyn Node>,
    anchor_index: BTreeMap<NodeId, &'validator Anchor>,
    end_transitions: Vec<&'validator dyn Node>,
    validation_index: BTreeSet<NodeId>,

    resolver: R,
}

impl<'validator, R: TxResolver> Validator<'validator, R> {
    fn init(consignment: &'validator Consignment, resolver: R) -> Self {
        // We use validation status object to store all detected failures and
        // warnings
        let mut status = Status::default();

        // Frequently used computation-heavy data
        let genesis_id = consignment.genesis.node_id();
        let contract_id = consignment.genesis.contract_id();
        let schema_id = consignment.genesis.schema_id();

        // Create indexes
        let mut node_index = BTreeMap::<NodeId, &dyn Node>::new();
        let mut anchor_index = BTreeMap::<NodeId, &Anchor>::new();
        for (anchor, transition) in &consignment.state_transitions {
            let node_id = transition.node_id();
            node_index.insert(node_id, transition);
            anchor_index.insert(node_id, anchor);
        }
        node_index.insert(genesis_id, &consignment.genesis);
        for extension in &consignment.state_extensions {
            let node_id = extension.node_id();
            node_index.insert(node_id, extension);
        }

        // Collect all endpoint transitions
        // This is pretty simple operation; it takes a lot of code because
        // we would like to detect any potential issues with the consignment
        // structure and notify user about them (in form of generated warnings)
        let mut end_transitions = Vec::<&dyn Node>::new();
        for (node_id, seal_endpoint) in &consignment.endpoints {
            if let Some(node) = node_index.get(node_id) {
                // Checking for endpoint definition duplicates
                if node
                    .all_seal_definitions()
                    .contains(&seal_endpoint.commit_conceal())
                {
                    if end_transitions
                        .iter()
                        .filter(|n| n.node_id() == *node_id)
                        .collect::<Vec<_>>()
                        .len()
                        > 0
                    {
                        status.add_warning(Warning::EndpointDuplication(
                            *node_id,
                            *seal_endpoint,
                        ));
                    } else {
                        end_transitions.push(*node);
                    }
                } else {
                    // We generate just a warning here because it's up to a user
                    // to decide whether to accept consignment with wrong
                    // endpoint list
                    status.add_warning(
                        Warning::EndpointTransitionSealNotFound(
                            *node_id,
                            *seal_endpoint,
                        ),
                    );
                }
            } else {
                // ~~We generate just a warning here because it's up to a user
                // to decide whether to accept consignment with wrong
                // endpoint list~~
                // Update: warning is transformed into an error, since it may
                // lead to acceptance of non-verified consignment assigning
                // positive fake balance to the user-controlled UTXO
                status
                    .add_failure(Failure::EndpointTransitionNotFound(*node_id));
            }
        }

        // Validation index is used to check that all transitions presented
        // in the consignment were validated. Also, we use it to avoid double
        // schema validations for transitions.
        let validation_index = BTreeSet::<NodeId>::new();

        Self {
            consignment,
            status,
            schema_id,
            genesis_id,
            contract_id,
            node_index,
            anchor_index,
            end_transitions,
            validation_index,
            resolver,
        }
    }

    /// Validation procedure takes a schema object, resolver function
    /// returning transaction and its fee for a given transaction id, and
    /// returns a validation object listing all detected failures, warnings and
    /// additional information.
    ///
    /// When a failure detected, it not stopped; the failure is is logged into
    /// the status object, but the validation continues for the rest of the
    /// consignment data. This can help it debugging and detecting all problems
    /// with the consignment.
    pub fn validate(
        schema: &Schema,
        consignment: &'validator Consignment,
        resolver: R,
    ) -> Status {
        let mut validator = Validator::init(consignment, resolver);

        validator.validate_root(schema);

        // Done. Returning status report with all possible failures, issues,
        // warnings and notifications about transactions we were unable to
        // obtain.
        let validator = validator;
        validator.status.clone()
    }

    fn validate_root(&mut self, schema: &Schema) {
        // [VALIDATION]: Making sure that we were supplied with the schema
        //               that corresponds to the schema of the contract genesis
        if schema.schema_id() != self.schema_id {
            self.status
                .add_failure(Failure::SchemaUnknown(self.schema_id));
            // Unlike other failures, here we return immediatelly, since there
            // is no point to validate all consignment data against an invalid
            // schema: it will result in a plenty of meaningless errors
            return;
        }

        // [VALIDATION]: Validate genesis
        self.status +=
            schema.validate(&self.node_index, &self.consignment.genesis);
        self.validation_index.insert(self.genesis_id);

        // [VALIDATION]: Iterating over each endpoint, reconstructing node graph
        //               up to genesis for each one of them. NB: We are not
        //               aiming to validate the consignment as a whole, but
        //               instead treat it as a superposition of subgraphs, one
        //               for each endpoint; and validate them independently.
        for node in self.end_transitions.clone() {
            self.validate_branch(schema, node);
        }

        // Generate warning if some of the transitions within the consignment
        // were excessive (i.e. not part of validation_index). Nothing critical,
        // but still good to report the user that the consignment is not perfect
        for node_id in self
            .validation_index
            .difference(&self.consignment.node_ids())
        {
            self.status
                .add_warning(Warning::ExcessiveTransition(*node_id));
        }
    }

    fn validate_branch(&mut self, schema: &Schema, node: &'validator dyn Node) {
        let mut queue: VecDeque<&dyn Node> = VecDeque::new();

        // Instead of constructing complex graph structures or using a
        // recursions we utilize queue to keep the track of the upstream
        // (ancestor) nodes and make sure that ve have validated each one
        // of them up to genesis. The graph is valid when each of its nodes
        // and each of its edges is valid, i.e. when all individual nodes
        // has passed validation against the schema (we track that fact with
        // `validation_index`) and each of the node ancestor state change to
        // a given node is valid against the schema + committed into bitcoin
        // transaction graph with proper anchor. That is what we are
        // checking in the code below:
        queue.push_back(node);
        while let Some(node) = queue.pop_front() {
            let node_id = node.node_id();
            let node_type = node.node_type();

            // [VALIDATION]: Verify node against the schema. Here we check
            //               only a single node, not state evolution (it
            //               will be checked lately)
            if !self.validation_index.contains(&node_id) {
                self.status += schema.validate(&self.node_index, node);
                self.validation_index.insert(node_id);
            }

            // Making sure we do have a corresponding anchor; otherwise
            // reporting failure (see below) - with the except of genesis and
            // extension nodes, which does not have a corresponding anchor
            if let Some(anchor) = self.anchor_index.get(&node_id).cloned() {
                // Ok, now we have the `node` and the `anchor`, let's do all
                // required checks

                // [VALIDATION]: Check that transition is committed into the
                //               anchor. This must be done with
                //               deterministic bitcoin commitments & LNPBP-4
                if !anchor.validate(&self.contract_id, &node_id) {
                    self.status.add_failure(Failure::TransitionNotInAnchor(
                        node_id,
                        anchor.anchor_id(),
                    ));
                }

                self.validate_graph_node(node, anchor);

            // Ouch, we are out of that multi-level nested cycles :)
            } else if node_type != NodeType::Genesis
                && node_type != NodeType::StateExtension
            {
                // This point is actually unreachable: b/c of the
                // consignment structure, each state transition
                // has a corresponding anchor. So if we've got here there
                // is something broken with LNP/BP core library.
                self.status
                    .add_failure(Failure::TransitionNotAnchored(node_id));
            }

            // Now, we must collect all parent nodes and add them to the
            // verification queue
            let parent_nodes_1: Vec<&dyn Node> = node
                .parent_owned_rights()
                .into_iter()
                .filter_map(|(id, _)| {
                    self.node_index.get(id).cloned().or_else(|| {
                        // This will not actually happen since we already
                        // checked that each ancrstor reference has a
                        // corresponding node in the code above. But rust
                        // requires to double-check :)
                        self.status.add_failure(Failure::TransitionAbsent(*id));
                        None
                    })
                })
                .collect();

            let parent_nodes_2: Vec<&dyn Node> = node
                .parent_public_rights()
                .into_iter()
                .filter_map(|(id, _)| {
                    self.node_index.get(id).cloned().or_else(|| {
                        // This will not actually happen since we already
                        // checked that each ancrstor reference has a
                        // corresponding node in the code above. But rust
                        // requires to double-check :)
                        self.status.add_failure(Failure::TransitionAbsent(*id));
                        None
                    })
                })
                .collect();

            queue.extend(parent_nodes_1);
            queue.extend(parent_nodes_2);
        }
    }

    fn validate_graph_node(
        &mut self,
        node: &'validator dyn Node,
        anchor: &'validator Anchor,
    ) {
        let txid = anchor.txid;
        let node_id = node.node_id();

        // Check that the anchor is committed into a transaction spending all of
        // the transition inputs.
        match self.resolver.resolve(&txid) {
            Err(_) => {
                // We wre unable to retrieve corresponding transaction, so can't
                // check. Reporting this incident and continuing further.
                // Why this happens? no connection to Bitcoin Core, Electrum or
                // other backend etc. So this is not a failure in a strict
                // sense, however we can't be sure that the
                // consignment is valid. That's why we keep the
                // track of such information in a separate place
                // (`unresolved_txids` field of the validation
                // status object).
                self.status.unresolved_txids.push(txid);
            }
            Ok(None) => {
                // There is no mined transaction with the id provided by the
                // anchor. Literally, the whole consignment is fucked up, but we
                // are proceeding with further validation in order to detect the
                // rest of fuck ups (and reporting the failure!)
                self.status
                    .add_failure(Failure::WitnessTransactionMissed(txid));
            }
            Ok(Some((witness_tx, fee))) => {
                // Ok, now we have the transaction and fee information for a
                // single state change from some ancestors array to the
                // currently validated transition node: that's everything
                // required to do the complete validation

                // [VALIDATION]: Checking anchor deterministic bitcoin
                //               commitment
                if !anchor.verify(&self.contract_id, &witness_tx, fee) {
                    // The node is not committed to bitcoin transaction graph!
                    // Ultimate failure. But continuing to detect the rest
                    // (after reporting it).
                    self.status.add_failure(Failure::WitnessNoCommitment(
                        node_id,
                        anchor.anchor_id(),
                        txid,
                    ));
                }

                // Checking that bitcoin transaction closes seals defined by
                // transition ancestors.
                for (ancestor_id, assignments) in node.parent_owned_rights() {
                    let ancestor_id = *ancestor_id;
                    let ancestor_node = if let Some(ancestor_node) =
                        self.node_index.get(&ancestor_id)
                    {
                        *ancestor_node
                    } else {
                        // Node, referenced as the ancestor, was not found
                        // in the consignment. Usually this means that the
                        // consignment data are broken
                        self.status.add_failure(Failure::TransitionAbsent(
                            ancestor_id,
                        ));
                        continue;
                    };

                    for (assignment_type, assignment_indexes) in assignments {
                        let assignment_type = *assignment_type;

                        let variant = if let Some(variant) =
                            ancestor_node.owned_rights_by_type(assignment_type)
                        {
                            variant
                        } else {
                            self.status.add_failure(
                                Failure::TransitionParentWrongSealType {
                                    node_id,
                                    ancestor_id,
                                    assignment_type,
                                },
                            );
                            continue;
                        };

                        for seal_index in assignment_indexes {
                            self.validate_witness_input(
                                &witness_tx,
                                node_id,
                                ancestor_id,
                                assignment_type,
                                variant,
                                *seal_index,
                            );
                        }
                    }
                }
            }
        }
    }

    // TODO: Move part of logic into single-use-seals and bitcoin seals
    fn validate_witness_input(
        &mut self,
        witness_tx: &Transaction,
        node_id: NodeId,
        ancestor_id: NodeId,
        assignment_type: schema::OwnedRightType,
        variant: &'validator Assignments,
        seal_index: u16,
    ) {
        // Getting bitcoin transaction outpoint for the current ancestor ... ->
        match (
            variant.seal_definition(seal_index),
            self.anchor_index.get(&ancestor_id),
        ) {
            (Err(_), _) => {
                self.status.add_failure(Failure::TransitionParentWrongSeal {
                    node_id,
                    ancestor_id,
                    assignment_type,
                    seal_index,
                });
                None
            }
            (Ok(None), _) => {
                // Everything is ok, but we have incomplete data (confidential),
                // thus can't do a full verification and have to report the
                // failure
                eprintln!("{:#?}", variant);
                self.status.add_failure(
                    Failure::TransitionParentConfidentialSeal {
                        node_id,
                        ancestor_id,
                        assignment_type,
                        seal_index,
                    },
                );
                None
            }
            (Ok(Some(seal::Revealed::TxOutpoint(outpoint))), None) => {
                // We are at genesis, so the outpoint must contain tx
                Some(bitcoin::OutPoint::from(outpoint.clone()))
            }
            (Ok(Some(_)), None) => {
                // This can't happen, since if we have a node in the index
                // and the node is not genesis, we always have an anchor
                unreachable!()
            }
            (Ok(Some(seal)), Some(anchor)) => {
                Some(bitcoin::OutPoint::from(seal.outpoint_reveal(anchor.txid)))
            } /* -> ... so we can check that the bitcoin transaction
               * references it as one of its inputs */
        }
        .map(|outpoint| {
            if witness_tx
                .input
                .iter()
                .find(|txin| txin.previous_output == outpoint)
                .is_none()
            {
                // Another failure: we do not spend one of the transition
                // ancestors in the witness transaction. The consignment is
                // clearly invalid; reporting this and processing to other
                // potential issues.
                self.status.add_failure(
                    Failure::TransitionParentIsNotWitnessInput {
                        node_id,
                        ancestor_id,
                        assignment_type,
                        seal_index,
                        outpoint,
                    },
                );
            }
        });
    }
}