holochain 0.7.0-dev.20

Holochain, a framework for distributed applications
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
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
//! A Ribosome is a structure which knows how to execute hApp code.
//!
//! We have only one instance of this: [crate::core::ribosome::real_ribosome::RealRibosome]. The abstract trait exists
//! so that we can write mocks against the `RibosomeT` interface, as well as
//! opening the possibility that we might support applications written in other
//! languages and environments.

// This allow is here because #[automock] automaticaly creates a struct without
// documentation, and there seems to be no way to add docs to it after the fact
pub mod error;

/// How to version guest callbacks.
/// See `genesis_self_check` for an example.
///
/// - Create unversioned structs in the root of the callback module
///   - Invocation, result, host access
///   - The unversioned structs should thinly wrap all their versioned structs
/// - Create versioned submodules for the callback
///   - In these, create versioned structs for the unversioned structs
///   - Write/keep all tests for the versioned copies of the callbacks, test
///     wasms can expose externs directly without the macros for explicit
///     legacy identities if needed.
/// - On the ribosome make sure the trait uses the unversioned struct
///   - Inside the callback method loop over the versioned callbacks, and
///     dispatch each that is found in the wasm
///   - Figure out how to merge/handle results if multiple versions of a callback
///     are found in the target wasm
/// - The ribosome method caller will now be forced by types to provide the
///   unversioned struct, which means they cannot forget to provide and dispatch
///   everything required for each version
/// - Update the `map_extern` macro so that the unversioned name of the callback
///   maps to the latest version of the callback, e.g. `genesis_self_check` is
///   rewritten to `genesis_self_check_2` at the time of writing
///   - This has the effect of newly compiled wasms implementing the callback
///     that is newest when they compile, without polluting the unversioned
///     callback, which is effectively legacy/deprecated behaviour to call it
///     directly.
pub mod guest_callback;

/// How to version host_fns.
/// See `dna_info_1` and `dna_info_2` for an example.
///
/// - Create new versions of the host fn and related IO structs
///   - Any change to an IO struct implies/necessitates a new host fn version
///   - Changes to structs MAY also trigger a new callback version if there is
///     a partially shared data structure in their interfaces
///   - Update the IO type aliases to point to the newest version of all structs
/// - Map both the old and new host functions in the ribosome
/// - Define both of the host functions in the wasm externs in HDI/HDK
/// - Test all versions of every host fn
/// - Ensure the convenience wrapper in the HDI/HDK references the latest version
///   of the host_fn
pub mod host_fn;
pub mod real_ribosome;

mod check_clone_access;

use self::guest_callback::{
    entry_defs::EntryDefsInvocation, genesis_self_check::GenesisSelfCheckResult,
};
use self::{
    error::RibosomeError,
    guest_callback::genesis_self_check::{GenesisSelfCheckHostAccess, GenesisSelfCheckInvocation},
};
use crate::conductor::api::CellConductorHandle;
use crate::conductor::api::CellConductorReadHandle;
use crate::conductor::api::ZomeCallParamsSigned;
use crate::conductor::error::ConductorResult;
use crate::core::ribosome::guest_callback::entry_defs::EntryDefsResult;
use crate::core::ribosome::guest_callback::genesis_self_check::v1::GenesisSelfCheckHostAccessV1;
use crate::core::ribosome::guest_callback::genesis_self_check::v2::GenesisSelfCheckHostAccessV2;
use crate::core::ribosome::guest_callback::init::InitInvocation;
use crate::core::ribosome::guest_callback::init::InitResult;
use crate::core::ribosome::guest_callback::post_commit::PostCommitInvocation;
use crate::core::ribosome::guest_callback::validate::ValidateInvocation;
use crate::core::ribosome::guest_callback::validate::ValidateResult;
use crate::core::ribosome::guest_callback::CallStream;
use derive_more::Constructor;
use error::RibosomeResult;
use guest_callback::entry_defs::EntryDefsHostAccess;
use guest_callback::init::InitHostAccess;
use guest_callback::post_commit::PostCommitHostAccess;
use guest_callback::validate::ValidateHostAccess;
use holo_hash::AgentPubKey;
use holochain_keystore::MetaLairClient;
use holochain_nonce::*;
use holochain_p2p::DynHolochainP2pDna;
use holochain_serialized_bytes::prelude::*;
use holochain_state::host_fn_workspace::HostFnWorkspace;
use holochain_state::host_fn_workspace::HostFnWorkspaceRead;
use holochain_state::nonce::WitnessNonceResult;
use holochain_types::prelude::*;
use holochain_types::zome_types::GlobalZomeTypes;
use holochain_zome_types::block::BlockTargetId;
use mockall::automock;
use must_future::MustBoxFuture;
use std::iter::Iterator;
use std::sync::Arc;
use tokio::sync::broadcast;
use wasmer::RuntimeError;

#[derive(Clone)]
pub struct CallContext {
    pub(crate) zome: Zome,
    pub(crate) function_name: FunctionName,
    pub(crate) auth: InvocationAuth,
    pub(crate) host_context: HostContext,
}

impl CallContext {
    pub fn new(
        zome: Zome,
        function_name: FunctionName,
        host_context: HostContext,
        auth: InvocationAuth,
    ) -> Self {
        Self {
            zome,
            function_name,
            host_context,
            auth,
        }
    }

    pub fn zome(&self) -> &Zome {
        &self.zome
    }

    pub fn function_name(&self) -> &FunctionName {
        &self.function_name
    }

    pub fn host_context(&self) -> HostContext {
        self.host_context.clone()
    }

    pub fn auth(&self) -> InvocationAuth {
        self.auth.clone()
    }

    pub fn switch_host_context(
        &self,
        transform: impl Fn(&HostContext) -> Result<HostContext, RuntimeError>,
    ) -> Result<CallContext, RuntimeError> {
        Ok(Self {
            zome: self.zome.clone(),
            function_name: self.function_name.clone(),
            host_context: transform(&self.host_context)?,
            auth: self.auth.clone(),
        })
    }
}

#[derive(Clone, Debug)]
pub enum HostContext {
    EntryDefs(EntryDefsHostAccess),
    GenesisSelfCheckV1(GenesisSelfCheckHostAccessV1),
    GenesisSelfCheckV2(GenesisSelfCheckHostAccessV2),
    Init(InitHostAccess),
    PostCommit(PostCommitHostAccess),
    Validate(ValidateHostAccess),
    ZomeCall(ZomeCallHostAccess),
}

impl From<&HostContext> for HostFnAccess {
    fn from(host_access: &HostContext) -> Self {
        match host_access {
            HostContext::ZomeCall(access) => access.into(),
            HostContext::GenesisSelfCheckV1(access) => access.into(),
            HostContext::GenesisSelfCheckV2(access) => access.into(),
            HostContext::Validate(access) => access.into(),
            HostContext::Init(access) => access.into(),
            HostContext::EntryDefs(access) => access.into(),
            HostContext::PostCommit(access) => access.into(),
        }
    }
}

impl HostContext {
    /// Get the workspace, panics if none was provided
    pub fn workspace(&self) -> HostFnWorkspaceRead {
        self.maybe_workspace().expect(
            "Gave access to a host function that uses the workspace without providing a workspace",
        )
    }

    /// Get the workspace if it was provided.
    pub fn maybe_workspace(&self) -> Option<HostFnWorkspaceRead> {
        match self.clone() {
            Self::ZomeCall(ZomeCallHostAccess { workspace, .. })
            | Self::Init(InitHostAccess { workspace, .. })
            | Self::PostCommit(PostCommitHostAccess { workspace, .. }) => Some(workspace.into()),
            Self::Validate(ValidateHostAccess { workspace, .. }) => Some(workspace),
            _ => None,
        }
    }

    /// Get the workspace, panics if none was provided
    pub fn workspace_write(&self) -> &HostFnWorkspace {
        match self {
            Self::ZomeCall(ZomeCallHostAccess { workspace, .. })
            | Self::Init(InitHostAccess { workspace, .. })
            | Self::PostCommit(PostCommitHostAccess { workspace, .. }) => workspace,
            _ => panic!(
                "Gave access to a host function that writes to the workspace without providing a workspace"
            ),
        }
    }

    /// Get the keystore, panics if none was provided
    pub fn keystore(&self) -> &MetaLairClient {
        match self {
            Self::ZomeCall(ZomeCallHostAccess { keystore, .. })
            | Self::Init(InitHostAccess { keystore, .. })
            | Self::PostCommit(PostCommitHostAccess { keystore, .. }) => keystore,
            _ => panic!(
                "Gave access to a host function that uses the keystore without providing a keystore"
            ),
        }
    }

    /// Get the network, panics if none was provided
    pub fn network(&self) -> DynHolochainP2pDna {
        match self {
            Self::ZomeCall(ZomeCallHostAccess { network, .. })
            | Self::Init(InitHostAccess { network, .. })
            | Self::PostCommit(PostCommitHostAccess { network, .. }) => network.clone(),
            Self::Validate(ValidateHostAccess { network, .. }) => network.clone(),
            _ => panic!(
                "Gave access to a host function that uses the network without providing a network"
            ),
        }
    }

    /// Get the signal sender, panics if none was provided
    pub fn signal_tx(&mut self) -> &mut broadcast::Sender<Signal> {
        match self {
            Self::ZomeCall(ZomeCallHostAccess { signal_tx, .. })
            | Self::Init(InitHostAccess { signal_tx, .. })
            | Self::PostCommit(PostCommitHostAccess { signal_tx, .. })
            => signal_tx,
            _ => panic!(
                "Gave access to a host function that uses the signal broadcaster without providing one"
            ),
        }
    }

    /// Get the call zome handle, panics if none was provided
    pub fn call_zome_handle(&self) -> &CellConductorReadHandle {
        match self {
            Self::ZomeCall(ZomeCallHostAccess {
                call_zome_handle, ..
            })
            | Self::Init(InitHostAccess { call_zome_handle, .. })
            | Self::PostCommit(PostCommitHostAccess { call_zome_handle: Some(call_zome_handle), .. })
            => call_zome_handle,
            _ => panic!(
                "Gave access to a host function that uses the call zome handle without providing a call zome handle"
            ),
        }
    }
}

#[derive(Clone, Debug)]
pub struct FnComponents(pub Vec<String>);

/// iterating over FnComponents isn't as simple as returning the inner Vec iterator
/// we return the fully joined vector in specificity order
/// specificity is defined as consisting of more components
/// e.g. FnComponents(Vec("foo", "bar", "baz")) would return:
/// - Some("foo_bar_baz")
/// - Some("foo_bar")
/// - Some("foo")
/// - None
impl Iterator for FnComponents {
    type Item = String;
    fn next(&mut self) -> Option<String> {
        match self.0.len() {
            0 => None,
            _ => {
                let ret = self.0.join("_");
                self.0.pop();
                Some(ret)
            }
        }
    }
}

impl From<Vec<String>> for FnComponents {
    fn from(vs: Vec<String>) -> Self {
        Self(vs)
    }
}

impl FnComponents {
    pub fn into_inner(self) -> Vec<String> {
        self.0
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum ZomesToInvoke {
    /// All the integrity zomes.
    AllIntegrity,
    /// All integrity and coordinator zomes.
    All,
    /// A single zome of unknown type.
    One(Zome),
    /// A single integrity zome.
    OneIntegrity(IntegrityZome),
    /// A single coordinator zome.
    OneCoordinator(CoordinatorZome),
}

impl ZomesToInvoke {
    pub fn one(zome: Zome) -> Self {
        Self::One(zome)
    }
    pub fn one_integrity(zome: IntegrityZome) -> Self {
        Self::OneIntegrity(zome)
    }
    pub fn one_coordinator(zome: CoordinatorZome) -> Self {
        Self::OneCoordinator(zome)
    }
}

#[derive(Clone, Debug)]
pub enum InvocationAuth {
    LocalCallback,
    Cap(AgentPubKey, Option<CapSecret>),
}

impl InvocationAuth {
    pub fn new(agent_pubkey: AgentPubKey, cap_secret: Option<CapSecret>) -> Self {
        Self::Cap(agent_pubkey, cap_secret)
    }
}

pub trait Invocation: Clone + Send + Sync {
    /// Some invocations call into a single zome and some call into many or all zomes.
    /// An example of an invocation that calls across all zomes is init. Init must pass for every
    /// zome in order for the Dna overall to successfully init.
    /// An example of an invocation that calls a single zome is validation of an entry, because
    /// the entry is only defined in a single zome, so it only makes sense for that exact zome to
    /// define the validation logic for that entry.
    /// In the future this may be expanded to support a subset of zomes that is larger than one.
    /// For example, we may want to trigger a callback in all zomes that implement a
    /// trait/interface, but this doesn't exist yet, so the only valid options are All or One.
    fn zomes(&self) -> ZomesToInvoke;
    /// Invocations execute in a "sparse" manner of decreasing specificity. In technical terms this
    /// means that the list of strings in FnComponents will be concatenated into a single function
    /// name to be called, then the last string will be removed and a shorter function name will
    /// be attempted and so on until all variations have been attempted.
    /// For example, if FnComponents was vec!["foo", "bar", "baz"] it would loop as "foo_bar_baz"
    /// then "foo_bar" then "foo". All of those three callbacks that are defined will be called
    /// _unless a definitive callback result is returned_.
    /// See [`CallbackResult::is_definitive`] in zome_types.
    /// All of the individual callback results are then folded into a single overall result value
    /// as a From implementation on the invocation results structs (e.g. zome results vs. ribosome
    /// results).
    fn fn_components(&self) -> FnComponents;
    /// the serialized input from the host for the wasm call
    /// this is intentionally NOT a reference to self because ExternIO may be huge we want to be
    /// careful about cloning invocations
    fn host_input(self) -> Result<ExternIO, SerializedBytesError>;
    fn auth(&self) -> InvocationAuth;
}

impl ZomeCallInvocation {
    /// to decide if a zome call grant is authorized:
    /// - we need to find a live (committed and not deleted) cap grant that matches the secret
    /// - if the live cap grant is for the current author the call is ALWAYS authorized ELSE
    /// - the live cap grant needs to include the invocation's provenance AND zome/function name
    pub async fn verify_grant(
        &self,
        host_access: &ZomeCallHostAccess,
    ) -> RibosomeResult<ZomeCallAuthorization> {
        let check_function = (self.zome.zome_name().clone(), self.fn_name.clone());
        let check_agent = self.provenance.clone();
        let check_secret = self.cap_secret;
        let maybe_grant: Option<CapGrant> = host_access
            .workspace
            .source_chain()
            .as_ref()
            .expect("Must have source chain to make zome calls")
            .valid_cap_grant(check_function, check_agent, check_secret)
            .await?;
        Ok(if maybe_grant.is_some() {
            ZomeCallAuthorization::Authorized
        } else {
            ZomeCallAuthorization::BadCapGrant
        })
    }

    pub async fn verify_nonce(
        &self,
        host_access: &ZomeCallHostAccess,
    ) -> RibosomeResult<ZomeCallAuthorization> {
        Ok(
            match host_access
                .call_zome_handle
                .witness_nonce_from_calling_agent(
                    self.provenance.clone(),
                    self.nonce,
                    self.expires_at,
                )
                .await
                .map_err(Box::new)?
            {
                WitnessNonceResult::Fresh => ZomeCallAuthorization::Authorized,
                nonce_result => ZomeCallAuthorization::BadNonce(format!("{nonce_result:?}")),
            },
        )
    }

    pub async fn verify_blocked_provenance(
        &self,
        host_access: &ZomeCallHostAccess,
    ) -> ConductorResult<ZomeCallAuthorization> {
        if host_access
            .call_zome_handle
            .is_blocked(
                BlockTargetId::Cell(CellId::new(
                    (*self.cell_id.dna_hash()).clone(),
                    self.provenance.clone(),
                )),
                Timestamp::now(),
            )
            .await?
        {
            Ok(ZomeCallAuthorization::BlockedProvenance)
        } else {
            Ok(ZomeCallAuthorization::Authorized)
        }
    }

    /// to verify if the zome call is authorized:
    /// - the nonce must not have already been seen
    /// - the grant must be valid
    /// - the provenance must not have any active blocks against them right now
    ///
    /// The checks MUST be done in this order as witnessing the nonce is a write operation,
    /// and so we MUST NOT write nonces until after we verify the signature.
    pub async fn is_authorized(
        &self,
        host_access: &ZomeCallHostAccess,
    ) -> ConductorResult<ZomeCallAuthorization> {
        Ok(match self.verify_nonce(host_access).await? {
            ZomeCallAuthorization::Authorized => match self.verify_grant(host_access).await? {
                ZomeCallAuthorization::Authorized => {
                    self.verify_blocked_provenance(host_access).await?
                }
                unauthorized => unauthorized,
            },
            unauthorized => unauthorized,
        })
    }
}

mockall::mock! {
    Invocation {}
    impl Invocation for Invocation {
        fn zomes(&self) -> ZomesToInvoke;
        fn fn_components(&self) -> FnComponents;
        fn host_input(self) -> Result<ExternIO, SerializedBytesError>;
        fn auth(&self) -> InvocationAuth;
    }
    impl Clone for Invocation {
        fn clone(&self) -> Self;
    }
}

/// A top-level call into a zome function,
/// i.e. coming from outside the Cell from an external Interface
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ZomeCallInvocation {
    /// The Id of the `Cell` in which this Zome-call would be invoked
    pub cell_id: CellId,
    /// The Zome containing the function that would be invoked
    pub zome: Zome,
    /// The capability request authorization.
    /// This can be `None` and still succeed in the case where the function
    /// in the zome being called has been given an Unrestricted status
    /// via a `CapGrant`. Otherwise, it will be necessary to provide a `CapSecret` for every call.
    pub cap_secret: Option<CapSecret>,
    /// The name of the Zome function to call
    pub fn_name: FunctionName,
    /// The serialized data to pass as an argument to the Zome call
    pub payload: ExternIO,
    /// The provenance of the call. Provenance means the 'source'
    /// so this expects the `AgentPubKey` of the agent calling the Zome function
    pub provenance: AgentPubKey,
    /// The nonce of the call. Must be unique and monotonic.
    /// If a higher nonce has been seen then older zome calls will be discarded.
    pub nonce: Nonce256Bits,
    /// This call MUST NOT be respected after this time, in the opinion of the callee.
    pub expires_at: Timestamp,
}

impl Invocation for ZomeCallInvocation {
    fn zomes(&self) -> ZomesToInvoke {
        ZomesToInvoke::One(self.zome.to_owned())
    }
    fn fn_components(&self) -> FnComponents {
        vec![self.fn_name.to_owned().into()].into()
    }
    fn host_input(self) -> Result<ExternIO, SerializedBytesError> {
        Ok(self.payload)
    }
    fn auth(&self) -> InvocationAuth {
        InvocationAuth::Cap(self.provenance.clone(), self.cap_secret)
    }
}

impl ZomeCallInvocation {
    pub async fn try_from_params(
        conductor_api: CellConductorHandle,
        params: ZomeCallParams,
    ) -> RibosomeResult<Self> {
        let ZomeCallParams {
            cap_secret,
            cell_id,
            expires_at,
            fn_name,
            nonce,
            payload,
            provenance,
            zome_name,
        } = params;
        let zome = conductor_api
            .get_zome(&cell_id, &zome_name)
            .map_err(|conductor_api_error| RibosomeError::from(Box::new(conductor_api_error)))?;
        Ok(Self {
            cell_id,
            zome,
            cap_secret,
            fn_name,
            payload,
            provenance,
            nonce,
            expires_at,
        })
    }
}

impl From<ZomeCallInvocation> for ZomeCallParams {
    fn from(inv: ZomeCallInvocation) -> Self {
        let ZomeCallInvocation {
            cell_id,
            zome,
            fn_name,
            cap_secret,
            payload,
            provenance,
            nonce,
            expires_at,
        } = inv;
        Self {
            cell_id,
            provenance,
            zome_name: zome.zome_name().clone(),
            fn_name,
            cap_secret,
            payload,
            nonce,
            expires_at,
        }
    }
}

#[derive(Clone, Constructor)]
pub struct ZomeCallHostAccess {
    pub workspace: HostFnWorkspace,
    pub keystore: MetaLairClient,
    pub network: DynHolochainP2pDna,
    pub signal_tx: broadcast::Sender<Signal>,
    pub call_zome_handle: CellConductorReadHandle,
}

impl std::fmt::Debug for ZomeCallHostAccess {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ZomeCallHostAccess").finish()
    }
}

impl From<ZomeCallHostAccess> for HostContext {
    fn from(zome_call_host_access: ZomeCallHostAccess) -> Self {
        Self::ZomeCall(zome_call_host_access)
    }
}

impl From<&ZomeCallHostAccess> for HostFnAccess {
    fn from(_: &ZomeCallHostAccess) -> Self {
        Self::all()
    }
}

/// Interface for a Ribosome. Currently used only for mocking, as our only
/// real concrete type is [`RealRibosome`](crate::core::ribosome::real_ribosome::RealRibosome)
#[automock]
#[allow(async_fn_in_trait)]
pub trait RibosomeT: Sized + std::fmt::Debug + Send + Sync {
    fn dna_def_hashed(&self) -> &DnaDefHashed;

    fn dna_hash(&self) -> &DnaHash;

    fn dna_file(&self) -> &DnaFile;

    async fn zome_info(&self, zome: Zome) -> RibosomeResult<ZomeInfo>;

    fn zomes_to_invoke(&self, zomes_to_invoke: ZomesToInvoke) -> Vec<Zome> {
        match zomes_to_invoke {
            ZomesToInvoke::AllIntegrity => self
                .dna_def_hashed()
                .integrity_zomes
                .iter()
                .map(|(n, d)| (n.clone(), d.clone().erase_type()).into())
                .collect(),
            ZomesToInvoke::All => self
                .dna_def_hashed()
                .all_zomes()
                .map(|(n, d)| (n.clone(), d.clone()).into())
                .collect(),
            ZomesToInvoke::One(zome) => vec![zome],
            ZomesToInvoke::OneIntegrity(zome) => vec![zome.erase_type()],
            ZomesToInvoke::OneCoordinator(zome) => vec![zome.erase_type()],
        }
    }

    fn zome_name_to_id(&self, zome_name: &ZomeName) -> RibosomeResult<ZomeIndex> {
        match self
            .dna_def_hashed()
            .all_zomes()
            .position(|(name, _)| name == zome_name)
        {
            Some(index) => Ok(holochain_zome_types::action::ZomeIndex::from(index as u8)),
            None => Err(RibosomeError::ZomeNotExists(zome_name.to_owned())),
        }
    }

    fn get_integrity_zome(&self, zome_index: &ZomeIndex) -> Option<IntegrityZome>;

    fn call_stream<I: Invocation + 'static>(
        &self,
        host_context: HostContext,
        invocation: I,
    ) -> CallStream;

    fn maybe_call<I: Invocation + 'static>(
        &self,
        host_context: HostContext,
        invocation: &I,
        zome: &Zome,
        to_call: &FunctionName,
    ) -> MustBoxFuture<'static, Result<Option<ExternIO>, RibosomeError>>
    where
        Self: 'static;

    /// Get a value from a const wasm function.
    ///
    /// This is really a stand in until Rust can properly support
    /// const wasm values.
    ///
    /// This allows getting values from wasm without the need for any translation.
    /// The same technique can be used with the wasmer cli to validate these
    /// values without needing to make holochain a dependency.
    async fn get_const_fn(&self, zome: &Zome, name: &str) -> Result<Option<i32>, RibosomeError>;

    // @todo list out all the available callbacks and maybe cache them somewhere
    fn list_callbacks(&self) {
        unimplemented!()
        // pseudocode
        // self.instance().exports().filter(|e| e.is_callback())
    }

    // @todo list out all the available zome functions and maybe cache them somewhere
    fn list_zome_fns(&self) {
        unimplemented!()
        // pseudocode
        // self.instance().exports().filter(|e| !e.is_callback())
    }

    async fn run_genesis_self_check(
        &self,
        access: GenesisSelfCheckHostAccess,
        invocation: GenesisSelfCheckInvocation,
    ) -> RibosomeResult<GenesisSelfCheckResult>;

    async fn run_init(
        &self,
        access: InitHostAccess,
        invocation: InitInvocation,
    ) -> RibosomeResult<InitResult>;

    async fn run_entry_defs(
        &self,
        access: EntryDefsHostAccess,
        invocation: EntryDefsInvocation,
    ) -> RibosomeResult<EntryDefsResult>;

    async fn run_post_commit(
        &self,
        access: PostCommitHostAccess,
        invocation: PostCommitInvocation,
    ) -> RibosomeResult<()>;

    /// Helper function for running a validation callback. Calls
    /// private fn `do_callback` under the hood.
    async fn run_validate(
        &self,
        access: ValidateHostAccess,
        invocation: ValidateInvocation,
    ) -> RibosomeResult<ValidateResult>;

    /// Runs the specified zome fn. Returns the cursor used by HDK,
    /// so that it can be passed on to source chain manager for transactional writes
    async fn call_zome_function(
        &self,
        access: ZomeCallHostAccess,
        invocation: ZomeCallInvocation,
    ) -> RibosomeResult<ZomeCallResponse>;

    fn zome_types(&self) -> &Arc<GlobalZomeTypes>;
}

/// Placeholder for weighing. Currently produces zero weight.
pub fn weigh_placeholder() -> EntryRateWeight {
    EntryRateWeight::default()
}

#[cfg(test)]
pub mod wasm_test {
    use crate::core::ribosome::FnComponents;
    use crate::test_utils;
    use core::time::Duration;
    use hdk::prelude::*;
    use holochain_nonce::fresh_nonce;
    use holochain_wasm_test_utils::TestWasm;
    use holochain_zome_types::zome_io::ZomeCallParams;

    pub fn now() -> Duration {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("Time went backwards")
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn verify_zome_call_test() {
        holochain_trace::test_run();
        let test_utils::RibosomeTestFixture {
            conductor,
            alice,
            alice_pubkey,
            bob_pubkey,
            ..
        } = test_utils::RibosomeTestFixture::new(TestWasm::Capability).await;

        let now = Timestamp::now();
        let (nonce, expires_at) = fresh_nonce(now).unwrap();
        let alice_zome_call_params = ZomeCallParams {
            provenance: alice_pubkey.clone(),
            cell_id: alice.cell_id().clone(),
            zome_name: TestWasm::Capability.coordinator_zome_name(),
            fn_name: "needs_cap_claim".into(),
            cap_secret: None,
            payload: ExternIO::encode(()).unwrap(),
            nonce,
            expires_at,
        };

        // Bob observes or forges a valid zome call from alice.
        // He removes Alice's signature but leaves her provenance and adds his own signature.
        let mut bob_zome_call_params = alice_zome_call_params.clone();
        bob_zome_call_params.provenance = bob_pubkey.clone();

        // The call should fail for bob.
        let bob_call_result = conductor.raw_handle().call_zome(bob_zome_call_params).await;

        match bob_call_result {
            Ok(Ok(ZomeCallResponse::Unauthorized(..))) => { /* (☞ ͡° ͜ʖ ͡°)☞ */ }
            _ => panic!("{bob_call_result:?}"),
        }

        // The call should NOT fail for alice (e.g. bob's forgery should not consume alice's nonce).
        let alice_call_result_0 = conductor
            .raw_handle()
            .call_zome(alice_zome_call_params.clone())
            .await;

        match alice_call_result_0 {
            Ok(Ok(ZomeCallResponse::Ok(_))) => { /* ಥ‿ಥ */ }
            _ => panic!("{alice_call_result_0:?}"),
        }

        // The same call cannot be used a second time.
        let alice_call_result_1 = conductor
            .raw_handle()
            .call_zome(alice_zome_call_params)
            .await;

        match alice_call_result_1 {
            Ok(Ok(ZomeCallResponse::Unauthorized(..))) => { /* ☜(゚ヮ゚☜) */ }
            _ => panic!("{bob_call_result:?}"),
        }
    }

    #[test]
    fn fn_components_iterate() {
        let fn_components = FnComponents::from(vec!["foo".into(), "bar".into(), "baz".into()]);
        let expected = vec!["foo_bar_baz", "foo_bar", "foo"];

        assert_eq!(fn_components.into_iter().collect::<Vec<String>>(), expected,);
    }
}