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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
//! # System Validation Checks
//! This module contains all the checks we run for sys validation

use super::queue_consumer::TriggerSender;
use super::ribosome::RibosomeT;
use super::workflow::incoming_dht_ops_workflow::incoming_dht_ops_workflow;
use super::workflow::sys_validation_workflow::SysValidationWorkspace;
use crate::conductor::entry_def_store::get_entry_def;
use crate::conductor::space::Space;
use crate::conductor::Conductor;
use holochain_cascade::Cascade;
use holochain_cascade::CascadeSource;
use holochain_keystore::AgentPubKeyExt;
use holochain_types::prelude::*;
use holochain_zome_types::countersigning::CounterSigningSessionData;
use std::convert::TryInto;
use std::sync::Arc;

pub use error::*;
pub use holo_hash::*;
pub use holochain_state::source_chain::SourceChainError;
pub use holochain_state::source_chain::SourceChainResult;
pub use holochain_zome_types::ActionHashed;
pub use holochain_zome_types::Timestamp;

#[allow(missing_docs)]
mod error;
#[cfg(test)]
mod tests;

/// 16mb limit on Entries due to websocket limits.
/// 4mb limit to constrain bandwidth usage on uploading.
/// (Assuming a baseline 5mbps upload for now... update this
/// as consumer internet connections trend toward more upload)
/// Consider splitting large entries up.
pub const MAX_ENTRY_SIZE: usize = ENTRY_SIZE_LIMIT;

/// 1kb limit on LinkTags.
/// Tags are used as keys to the database to allow
/// fast lookup so they should be small.
pub const MAX_TAG_SIZE: usize = 1000;

/// Verify the signature for this action
pub async fn verify_action_signature(sig: &Signature, action: &Action) -> SysValidationResult<()> {
    if action.author().verify_signature(sig, action).await {
        Ok(())
    } else {
        Err(SysValidationError::ValidationOutcome(
            ValidationOutcome::Counterfeit((*sig).clone(), (*action).clone()),
        ))
    }
}

/// Verify the author key was valid at the time
/// of signing with dpki
/// TODO: This is just a stub until we have dpki.
pub async fn author_key_is_valid(_author: &AgentPubKey) -> SysValidationResult<()> {
    Ok(())
}

/// Verify the countersigning session contains the specified action.
pub fn check_countersigning_session_data_contains_action(
    entry_hash: EntryHash,
    session_data: &CounterSigningSessionData,
    action: NewEntryActionRef<'_>,
) -> SysValidationResult<()> {
    let weight = match action {
        NewEntryActionRef::Create(h) => h.weight.clone(),
        NewEntryActionRef::Update(h) => h.weight.clone(),
    };
    let action_is_in_session = session_data
        .build_action_set(entry_hash, weight)
        .map_err(SysValidationError::from)?
        .iter()
        .any(|session_action| match (&action, session_action) {
            (NewEntryActionRef::Create(create), Action::Create(session_create)) => {
                create == &session_create
            }
            (NewEntryActionRef::Update(update), Action::Update(session_update)) => {
                update == &session_update
            }
            _ => false,
        });
    if !action_is_in_session {
        Err(SysValidationError::ValidationOutcome(
            ValidationOutcome::ActionNotInCounterSigningSession(
                session_data.to_owned(),
                action.to_new_entry_action(),
            ),
        ))
    } else {
        Ok(())
    }
}

/// Verify that the signature on a preflight request is valid.
pub async fn check_countersigning_preflight_response_signature(
    preflight_response: &PreflightResponse,
) -> SysValidationResult<()> {
    let signature_is_valid = preflight_response
        .request()
        .signing_agents
        .get(*preflight_response.agent_state().agent_index() as usize)
        .ok_or_else(|| {
            SysValidationError::ValidationOutcome(ValidationOutcome::PreflightResponseSignature(
                (*preflight_response).clone(),
            ))
        })?
        .0
        .verify_signature_raw(
            preflight_response.signature(),
            preflight_response
                .encode_for_signature()
                .map_err(|_| {
                    SysValidationError::ValidationOutcome(
                        ValidationOutcome::PreflightResponseSignature(
                            (*preflight_response).clone(),
                        ),
                    )
                })?
                .into(),
        )
        .await;
    if signature_is_valid {
        Ok(())
    } else {
        Err(SysValidationError::ValidationOutcome(
            ValidationOutcome::PreflightResponseSignature((*preflight_response).clone()),
        ))
    }
}

/// Verify all the countersigning session data together.
pub async fn check_countersigning_session_data(
    entry_hash: EntryHash,
    session_data: &CounterSigningSessionData,
    action: NewEntryActionRef<'_>,
) -> SysValidationResult<()> {
    session_data.check_integrity()?;
    check_countersigning_session_data_contains_action(entry_hash, session_data, action)?;

    let tasks: Vec<_> = session_data
        .responses()
        .iter()
        .map(|(response, signature)| async move {
            let preflight_response = PreflightResponse::try_new(
                session_data.preflight_request().clone(),
                response.clone(),
                signature.clone(),
            )?;
            check_countersigning_preflight_response_signature(&preflight_response).await
        })
        .collect();

    let results: Vec<SysValidationResult<()>> = futures::future::join_all(tasks).await;
    let results: SysValidationResult<()> = results.into_iter().collect();
    match results {
        Ok(_) => Ok(()),
        Err(e) => Err(e),
    }
}

/// Check that the correct actions have the correct setting for prev_action:
/// - Dna can never have a prev_action, and must have seq == 0.
/// - All other actions must have prev_action, and seq > 0.
pub fn check_prev_action(action: &Action) -> SysValidationResult<()> {
    let is_dna = matches!(action, Action::Dna(_));
    let has_prev = action.prev_action().is_some();
    let is_first = action.action_seq() == 0;
    #[allow(clippy::collapsible_else_if)]
    if is_first {
        if is_dna && !has_prev {
            Ok(())
        } else {
            Err(PrevActionError::InvalidRoot)
        }
    } else {
        if !is_dna && has_prev {
            Ok(())
        } else {
            Err(PrevActionError::MissingPrev)
        }
    }
    .map_err(|e| ValidationOutcome::from(e).into())
}

/// Check that Dna actions are only added to empty source chains
pub fn check_valid_if_dna(action: &Action, dna_def: &DnaDefHashed) -> SysValidationResult<()> {
    match action {
        Action::Dna(a) => {
            let dna_hash = dna_def.as_hash();
            if a.hash != *dna_hash {
                Err(ValidationOutcome::WrongDna(a.hash.clone(), dna_hash.clone()).into())
            } else if action.timestamp() < dna_def.modifiers.origin_time {
                // If the Dna timestamp is ahead of the origin time, every other action
                // will be inductively so also due to the prev_action check
                Err(PrevActionError::InvalidRootOriginTime)
                    .map_err(|e| ValidationOutcome::from(e).into())
            } else {
                Ok(())
            }
        }
        _ => Ok(()),
    }
}

/// Check if there are other actions at this
/// sequence number
pub async fn check_chain_rollback(
    action: &Action,
    workspace: &SysValidationWorkspace,
) -> SysValidationResult<()> {
    let empty = workspace.action_seq_is_empty(action).await?;

    // Ok or log warning
    if empty {
        Ok(())
    } else {
        // TODO: implement real rollback detection once we know what that looks like
        tracing::error!(
            "Chain rollback detected at position {} for agent {:?} from action {:?}",
            action.action_seq(),
            action.author(),
            action,
        );
        Ok(())
    }
}

/// Placeholder for future spam check.
/// Check action timestamps don't exceed MAX_PUBLISH_FREQUENCY
pub async fn check_spam(_action: &Action) -> SysValidationResult<()> {
    Ok(())
}

/// Check that created agents are always paired with an AgentValidationPkg and vice versa
pub fn check_agent_validation_pkg_predecessor(
    action: &Action,
    prev_action: &Action,
) -> SysValidationResult<()> {
    let maybe_error = match (prev_action, action) {
        (
            Action::AgentValidationPkg(AgentValidationPkg { .. }),
            Action::Create(Create { .. }) | Action::Update(Update { .. }),
        ) => None,
        (Action::AgentValidationPkg(AgentValidationPkg { .. }), _) => Some(
            "Every AgentValidationPkg must be followed by a Create or Update for an AgentPubKey",
        ),
        (
            _,
            Action::Create(Create {
                entry_type: EntryType::AgentPubKey,
                ..
            })
            | Action::Update(Update {
                entry_type: EntryType::AgentPubKey,
                ..
            }),
        ) => Some(
            "Every Create or Update for an AgentPubKey must be preceded by an AgentValidationPkg",
        ),
        _ => None,
    };

    if let Some(error) = maybe_error {
        Err(PrevActionError::InvalidSuccessor(
            error.to_string(),
            Box::new((prev_action.clone(), action.clone())),
        ))
        .map_err(|e| ValidationOutcome::from(e).into())
    } else {
        Ok(())
    }
}

/// Check that the author didn't change between actions
pub fn check_prev_author(action: &Action, prev_action: &Action) -> SysValidationResult<()> {
    // Agent updates will be valid when DPKI support lands
    let a1: AgentPubKey = if let Action::Update(
        u @ Update {
            entry_type: EntryType::AgentPubKey,
            ..
        },
    ) = prev_action
    {
        #[cfg(feature = "dpki")]
        {
            u.entry_hash.clone().into()
        }

        #[cfg(not(feature = "dpki"))]
        {
            u.author.clone()
        }
    } else {
        prev_action.author().clone()
    };

    let a2 = action.author();
    if a1 == *a2 {
        Ok(())
    } else {
        Err(PrevActionError::Author(a1, a2.clone())).map_err(|e| ValidationOutcome::from(e).into())
    }
}

/// Check previous action timestamp is before this action
pub fn check_prev_timestamp(action: &Action, prev_action: &Action) -> SysValidationResult<()> {
    let t1 = prev_action.timestamp();
    let t2 = action.timestamp();
    if t2 > t1 {
        Ok(())
    } else {
        Err(PrevActionError::Timestamp(t1, t2)).map_err(|e| ValidationOutcome::from(e).into())
    }
}

/// Check the previous action is one less than the current
pub fn check_prev_seq(action: &Action, prev_action: &Action) -> SysValidationResult<()> {
    let action_seq = action.action_seq();
    let prev_seq = prev_action.action_seq();
    if action_seq > 0 && prev_seq == action_seq - 1 {
        Ok(())
    } else {
        Err(PrevActionError::InvalidSeq(action_seq, prev_seq))
            .map_err(|e| ValidationOutcome::from(e).into())
    }
}

/// Check the entry variant matches the variant in the actions entry type
pub fn check_entry_type(entry_type: &EntryType, entry: &Entry) -> SysValidationResult<()> {
    match (entry_type, entry) {
        (EntryType::AgentPubKey, Entry::Agent(_)) => Ok(()),
        (EntryType::App(_), Entry::App(_)) => Ok(()),
        (EntryType::App(_), Entry::CounterSign(_, _)) => Ok(()),
        (EntryType::CapClaim, Entry::CapClaim(_)) => Ok(()),
        (EntryType::CapGrant, Entry::CapGrant(_)) => Ok(()),
        _ => Err(ValidationOutcome::EntryType.into()),
    }
}

/// Check the AppEntryDef is valid for the zome.
/// Check the EntryDefId and ZomeIndex are in range.
// TODO: MD: shouldn't this be part of App validation, since it invokes Wasm?
pub async fn check_app_entry_def(
    dna_hash: &DnaHash,
    entry_type: &AppEntryDef,
    conductor: &Conductor,
) -> SysValidationResult<EntryDef> {
    // We want to be careful about holding locks open to the conductor api
    // so calls are made in blocks
    let ribosome = conductor
        .get_ribosome(dna_hash)
        .map_err(|_| SysValidationError::DnaMissing(dna_hash.clone()))?;

    // Check if the zome is found
    let zome = ribosome
        .get_integrity_zome(&entry_type.zome_index())
        .ok_or_else(|| ValidationOutcome::ZomeIndex(entry_type.clone()))?
        .into_inner()
        .1;

    let entry_def = get_entry_def(entry_type.entry_index(), zome, dna_hash, conductor).await?;

    // Check the visibility and return
    match entry_def {
        Some(entry_def) => {
            if entry_def.visibility == *entry_type.visibility() {
                Ok(entry_def)
            } else {
                Err(ValidationOutcome::EntryVisibility(entry_type.clone()).into())
            }
        }
        None => Err(ValidationOutcome::EntryDefId(entry_type.clone()).into()),
    }
}

/// Check the app entry type isn't private for store entry
pub fn check_not_private(entry_def: &EntryDef) -> SysValidationResult<()> {
    match entry_def.visibility {
        EntryVisibility::Public => Ok(()),
        EntryVisibility::Private => Err(ValidationOutcome::PrivateEntry.into()),
    }
}

/// Check the actions entry hash matches the hash of the entry
pub async fn check_entry_hash(hash: &EntryHash, entry: &Entry) -> SysValidationResult<()> {
    if *hash == EntryHash::with_data_sync(entry) {
        Ok(())
    } else {
        Err(ValidationOutcome::EntryHash.into())
    }
}

/// Check the action should have an entry.
/// Is either a Create or Update
pub fn check_new_entry_action(action: &Action) -> SysValidationResult<()> {
    match action {
        Action::Create(_) | Action::Update(_) => Ok(()),
        _ => Err(ValidationOutcome::NotNewEntry(action.clone()).into()),
    }
}

/// Check the entry size is under the MAX_ENTRY_SIZE
pub fn check_entry_size(entry: &Entry) -> SysValidationResult<()> {
    match entry {
        Entry::App(bytes) => {
            let size = std::mem::size_of_val(&bytes.bytes()[..]);
            if size < MAX_ENTRY_SIZE {
                Ok(())
            } else {
                Err(ValidationOutcome::EntryTooLarge(size, MAX_ENTRY_SIZE).into())
            }
        }
        // Other entry types are small
        _ => Ok(()),
    }
}

/// Check the link tag size is under the MAX_TAG_SIZE
pub fn check_tag_size(tag: &LinkTag) -> SysValidationResult<()> {
    let size = std::mem::size_of_val(&tag.0[..]);
    if size < MAX_TAG_SIZE {
        Ok(())
    } else {
        Err(ValidationOutcome::TagTooLarge(size, MAX_TAG_SIZE).into())
    }
}

/// Check a Update's entry type is the same for
/// original and new entry.
pub fn check_update_reference(
    eu: &Update,
    original_entry_action: &NewEntryActionRef<'_>,
) -> SysValidationResult<()> {
    if eu.entry_type == *original_entry_action.entry_type() {
        Ok(())
    } else {
        Err(ValidationOutcome::UpdateTypeMismatch(
            eu.entry_type.clone(),
            original_entry_action.entry_type().clone(),
        )
        .into())
    }
}

/// Validate a chain of actions with an optional starting point.
pub fn validate_chain<'iter, A: 'iter + ChainItem>(
    mut actions: impl Iterator<Item = &'iter A>,
    persisted_chain_head: &Option<(A::Hash, u32)>,
) -> SysValidationResult<()> {
    // Check the chain starts in a valid way.
    let mut last_item = match actions.next() {
        Some(item) => {
            match persisted_chain_head {
                Some((prev_hash, prev_seq)) => {
                    check_prev_action_chain(prev_hash, *prev_seq, item)
                        .map_err(ValidationOutcome::from)?;
                }
                None => {
                    // If there's no persisted chain head, then the first action
                    // must have no parent.
                    if item.prev_hash().is_some() {
                        return Err(ValidationOutcome::from(PrevActionError::InvalidRoot).into());
                    }
                }
            }
            (item.get_hash(), item.seq())
        }
        None => return Ok(()),
    };

    for item in actions {
        // Check each item of the chain is valid.
        check_prev_action_chain(last_item.0, last_item.1, item).map_err(ValidationOutcome::from)?;
        last_item = (item.get_hash(), item.seq());
    }
    Ok(())
}

// Check the action is valid for the previous action.
fn check_prev_action_chain<A: ChainItem>(
    prev_action_hash: &A::Hash,
    prev_action_seq: u32,
    action: &A,
) -> Result<(), PrevActionError> {
    // The root cannot appear later in the chain
    if action.prev_hash().is_none() {
        Err(PrevActionError::MissingPrev)
    } else if action.prev_hash().map_or(true, |p| p != prev_action_hash) {
        // Check the prev hash matches.
        Err(PrevActionError::HashMismatch(action.seq()))
    } else if action
        .seq()
        .checked_sub(1)
        .map_or(true, |s| prev_action_seq != s)
    {
        // Check the prev seq is one less.
        Err(PrevActionError::InvalidSeq(action.seq(), prev_action_seq))
    } else {
        Ok(())
    }
}

/// If we are not holding this action then
/// retrieve it and send it as a RegisterAddLink DhtOp
/// to our incoming_dht_ops_workflow.
///
/// Apply a checks callback to the Record.
///
/// Additionally sys validation will be triggered to
/// run again if we weren't holding it.
pub async fn check_and_hold_register_add_link<F>(
    hash: &ActionHash,
    cascade: &Cascade,
    incoming_dht_ops_sender: Option<IncomingDhtOpSender>,
    f: F,
) -> SysValidationResult<()>
where
    F: FnOnce(&Record) -> SysValidationResult<()>,
{
    let source = check_and_hold(hash, cascade).await?;
    f(source.as_ref())?;
    if let (Some(incoming_dht_ops_sender), Source::Network(record)) =
        (incoming_dht_ops_sender, source)
    {
        incoming_dht_ops_sender
            .send_register_add_link(record)
            .await?;
    }
    Ok(())
}

/// If we are not holding this action then
/// retrieve it and send it as a RegisterAgentActivity DhtOp
/// to our incoming_dht_ops_workflow.
///
/// Apply a checks callback to the Record.
///
/// Additionally sys validation will be triggered to
/// run again if we weren't holding it.
pub async fn check_and_hold_register_agent_activity<F>(
    hash: &ActionHash,
    cascade: &Cascade,
    incoming_dht_ops_sender: Option<IncomingDhtOpSender>,
    f: F,
) -> SysValidationResult<()>
where
    F: FnOnce(&Record) -> SysValidationResult<()>,
{
    let source = check_and_hold(hash, cascade).await?;
    f(source.as_ref())?;
    if let (Some(incoming_dht_ops_sender), Source::Network(record)) =
        (incoming_dht_ops_sender, source)
    {
        incoming_dht_ops_sender
            .send_register_agent_activity(record)
            .await?;
    }
    Ok(())
}

/// If we are not holding this action then
/// retrieve it and send it as a StoreEntry DhtOp
/// to our incoming_dht_ops_workflow.
///
/// Apply a checks callback to the Record.
///
/// Additionally sys validation will be triggered to
/// run again if we weren't holding it.
pub async fn check_and_hold_store_entry<F>(
    hash: &ActionHash,
    cascade: &Cascade,
    incoming_dht_ops_sender: Option<IncomingDhtOpSender>,
    f: F,
) -> SysValidationResult<()>
where
    F: FnOnce(&Record) -> SysValidationResult<()>,
{
    let source = check_and_hold(hash, cascade).await?;
    f(source.as_ref())?;
    if let (Some(incoming_dht_ops_sender), Source::Network(record)) =
        (incoming_dht_ops_sender, source)
    {
        incoming_dht_ops_sender.send_store_entry(record).await?;
    }
    Ok(())
}

/// If we are not holding this entry then
/// retrieve any record at this EntryHash
/// and send it as a StoreEntry DhtOp
/// to our incoming_dht_ops_workflow.
///
/// Note this is different to check_and_hold_store_entry
/// because it gets the Record via an EntryHash which
/// means it will be any Record.
///
/// Apply a checks callback to the Record.
///
/// Additionally sys validation will be triggered to
/// run again if we weren't holding it.
pub async fn check_and_hold_any_store_entry<F>(
    hash: &EntryHash,
    cascade: &Cascade,
    incoming_dht_ops_sender: Option<IncomingDhtOpSender>,
    f: F,
) -> SysValidationResult<()>
where
    F: FnOnce(&Record) -> SysValidationResult<()>,
{
    let source = check_and_hold(hash, cascade).await?;
    f(source.as_ref())?;
    if let (Some(incoming_dht_ops_sender), Source::Network(record)) =
        (incoming_dht_ops_sender, source)
    {
        incoming_dht_ops_sender.send_store_entry(record).await?;
    }
    Ok(())
}

/// If we are not holding this action then
/// retrieve it and send it as a StoreRecord DhtOp
/// to our incoming_dht_ops_workflow.
///
/// Apply a checks callback to the Record.
///
/// Additionally sys validation will be triggered to
/// run again if we weren't holding it.
pub async fn check_and_hold_store_record<F>(
    hash: &ActionHash,
    cascade: &Cascade,
    incoming_dht_ops_sender: Option<IncomingDhtOpSender>,
    f: F,
) -> SysValidationResult<()>
where
    F: FnOnce(&Record) -> SysValidationResult<()>,
{
    let source = check_and_hold(hash, cascade).await?;
    f(source.as_ref())?;
    if let (Some(incoming_dht_ops_sender), Source::Network(record)) =
        (incoming_dht_ops_sender, source)
    {
        incoming_dht_ops_sender.send_store_record(record).await?;
    }
    Ok(())
}

/// Allows you to send an op to the
/// incoming_dht_ops_workflow if you
/// found it on the network and were supposed
/// to be holding it.
#[derive(derive_more::Constructor, Clone)]
pub struct IncomingDhtOpSender {
    space: Arc<Space>,
    sys_validation_trigger: TriggerSender,
}

impl IncomingDhtOpSender {
    /// Sends the op to the incoming workflow
    async fn send_op(
        self,
        record: Record,
        make_op: fn(Record) -> Option<(DhtOpHash, DhtOp)>,
    ) -> SysValidationResult<()> {
        if let Some(op) = make_op(record) {
            let ops = vec![op];
            incoming_dht_ops_workflow(
                self.space.as_ref().clone(),
                self.sys_validation_trigger,
                ops,
                false,
            )
            .await
            .map_err(Box::new)?;
        }
        Ok(())
    }
    async fn send_store_record(self, record: Record) -> SysValidationResult<()> {
        self.send_op(record, make_store_record).await
    }
    async fn send_store_entry(self, record: Record) -> SysValidationResult<()> {
        // TODO: MD: isn't it already too late if we've received a private entry from the network at this point?
        let is_public_entry = record.action().entry_type().map_or(false, |et| {
            matches!(et.visibility(), EntryVisibility::Public)
        });
        if is_public_entry {
            self.send_op(record, make_store_entry).await?;
        }
        Ok(())
    }
    async fn send_register_add_link(self, record: Record) -> SysValidationResult<()> {
        self.send_op(record, make_register_add_link).await
    }
    async fn send_register_agent_activity(self, record: Record) -> SysValidationResult<()> {
        self.send_op(record, make_register_agent_activity).await
    }
}

/// Where the record was found.
enum Source {
    /// Locally because we are holding it or
    /// because we will be soon
    Local(Record),
    /// On the network.
    /// This means we aren't holding it so
    /// we should add it to our incoming ops
    Network(Record),
}

impl AsRef<Record> for Source {
    fn as_ref(&self) -> &Record {
        match self {
            Source::Local(el) | Source::Network(el) => el,
        }
    }
}

/// Check if we are holding a dependency and
/// run a check callback on the it.
/// This function also returns where the dependency
/// was found so you can decide whether or not to add
/// it to the incoming ops.
async fn check_and_hold<I: Into<AnyDhtHash> + Clone>(
    hash: &I,
    cascade: &Cascade,
) -> SysValidationResult<Source> {
    let hash: AnyDhtHash = hash.clone().into();
    match cascade.retrieve(hash.clone(), Default::default()).await? {
        Some((el, CascadeSource::Local)) => Ok(Source::Local(el)),
        Some((el, CascadeSource::Network)) => Ok(Source::Network(el.privatized().0)),
        None => Err(ValidationOutcome::NotHoldingDep(hash).into()),
    }
}

/// Make a StoreRecord DhtOp from a Record.
/// Note that this can fail if the op is missing an
/// Entry when it was supposed to have one.
///
/// Because adding ops to incoming limbo while we are checking them
/// is only faster then waiting for them through gossip we don't care enough
/// to return an error.
fn make_store_record(record: Record) -> Option<(DhtOpHash, DhtOp)> {
    // Extract the data
    let (shh, record_entry) = record.privatized().0.into_inner();
    let (action, signature) = shh.into_inner();
    let action = action.into_content();

    // Check the entry
    let maybe_entry_box = record_entry.into_option().map(Box::new);

    // Create the hash and op
    let op = DhtOp::StoreRecord(signature, action, maybe_entry_box);
    let hash = op.to_hash();
    Some((hash, op))
}

/// Make a StoreEntry DhtOp from a Record.
/// Note that this can fail if the op is missing an Entry or
/// the action is the wrong type.
///
/// Because adding ops to incoming limbo while we are checking them
/// is only faster then waiting for them through gossip we don't care enough
/// to return an error.
fn make_store_entry(record: Record) -> Option<(DhtOpHash, DhtOp)> {
    // Extract the data
    let (shh, record_entry) = record.into_inner();
    let (action, signature) = shh.into_inner();

    // Check the entry and exit early if it's not there
    let entry_box = record_entry.into_option()?.into();
    // If the action is the wrong type exit early
    let action = action.into_content().try_into().ok()?;

    // Create the hash and op
    let op = DhtOp::StoreEntry(signature, action, entry_box);
    let hash = op.to_hash();
    Some((hash, op))
}

/// Make a RegisterAddLink DhtOp from a Record.
/// Note that this can fail if the action is the wrong type
///
/// Because adding ops to incoming limbo while we are checking them
/// is only faster then waiting for them through gossip we don't care enough
/// to return an error.
fn make_register_add_link(record: Record) -> Option<(DhtOpHash, DhtOp)> {
    // Extract the data
    let (shh, _) = record.into_inner();
    let (action, signature) = shh.into_inner();

    // If the action is the wrong type exit early
    let action = action.into_content().try_into().ok()?;

    // Create the hash and op
    let op = DhtOp::RegisterAddLink(signature, action);
    let hash = op.to_hash();
    Some((hash, op))
}

/// Make a RegisterAgentActivity DhtOp from a Record.
/// Note that this can fail if the action is the wrong type
///
/// Because adding ops to incoming limbo while we are checking them
/// is only faster then waiting for them through gossip we don't care enough
/// to return an error.
fn make_register_agent_activity(record: Record) -> Option<(DhtOpHash, DhtOp)> {
    // Extract the data
    let (shh, _) = record.into_inner();
    let (action, signature) = shh.into_inner();

    // If the action is the wrong type exit early
    let action = action.into_content();

    // Create the hash and op
    let op = DhtOp::RegisterAgentActivity(signature, action);
    let hash = op.to_hash();
    Some((hash, op))
}

#[cfg(test)]
pub mod test {
    use super::check_countersigning_preflight_response_signature;
    use crate::core::sys_validate::error::SysValidationError;
    use crate::core::ValidationOutcome;
    use arbitrary::Arbitrary;
    use fixt::fixt;
    use fixt::Predictable;
    use hdk::prelude::AgentPubKeyFixturator;
    use holochain_keystore::AgentPubKeyExt;
    use holochain_state::test_utils::test_keystore;
    use holochain_zome_types::countersigning::PreflightResponse;
    use matches::assert_matches;

    #[tokio::test(flavor = "multi_thread")]
    pub async fn test_check_countersigning_preflight_response_signature() {
        let keystore = test_keystore();
        let mut u = arbitrary::Unstructured::new(&[0; 1000]);
        let mut preflight_response = PreflightResponse::arbitrary(&mut u).unwrap();
        assert_matches!(
            check_countersigning_preflight_response_signature(&preflight_response).await,
            Err(SysValidationError::ValidationOutcome(
                ValidationOutcome::PreflightResponseSignature(_)
            ))
        );

        let alice = fixt!(AgentPubKey, Predictable);
        let bob = fixt!(AgentPubKey, Predictable, 1);

        preflight_response
            .request_mut()
            .signing_agents
            .push((alice.clone(), vec![]));
        preflight_response
            .request_mut()
            .signing_agents
            .push((bob, vec![]));

        *preflight_response.signature_mut() = alice
            .sign_raw(
                &keystore,
                preflight_response.encode_for_signature().unwrap().into(),
            )
            .await
            .unwrap();

        assert_eq!(
            check_countersigning_preflight_response_signature(&preflight_response)
                .await
                .unwrap(),
            (),
        );
    }
}