holochain 0.6.0

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
use crate::{conductor::error::ConductorError, sweettest::*};
use holochain_types::prelude::*;
use holochain_wasm_test_utils::TestWasm;
#[cfg(feature = "unstable-migration")]
use maplit::btreeset;
use matches::assert_matches;
#[cfg(feature = "unstable-migration")]
use std::collections::BTreeSet;
use std::collections::HashMap;

#[tokio::test(flavor = "multi_thread")]
async fn clone_only_provisioning_creates_no_cell_and_allows_cloning() {
    holochain_trace::test_run();

    let mut conductor = SweetConductor::from_standard_config().await;

    async fn make_payload(clone_limit: u32) -> InstallAppPayload {
        // The integrity zome in this WASM will fail if the properties are not set. This helps verify that genesis
        // is not being run for the clone-only cell and will only run for the cloned cells.
        let (dna, _, _) = SweetDnaFile::unique_from_test_wasms(vec![
            TestWasm::GenesisSelfCheckRequiresProperties,
        ])
        .await;
        let path = format!("{}", dna.dna_hash());
        let modifiers = DnaModifiersOpt::none();

        let roles = vec![AppRoleManifest {
            name: "name".into(),
            dna: AppRoleDnaManifest {
                path: Some(path.clone()),
                modifiers: modifiers.clone(),
                installed_hash: None,
                clone_limit,
            },
            provisioning: Some(CellProvisioning::CloneOnly),
        }];

        let manifest = AppManifestCurrentBuilder::default()
            .name("test_app".into())
            .description(None)
            .roles(roles)
            .build()
            .unwrap();
        let dna_bundle = DnaBundle::from_dna_file(dna.clone()).unwrap();
        let resources = vec![(path.clone(), dna_bundle)];
        let bundle = AppBundle::new(manifest.clone().into(), resources).unwrap();

        let bundle_bytes = bundle.pack().unwrap();
        InstallAppPayload {
            agent_key: None,
            source: AppBundleSource::Bytes(bundle_bytes),
            installed_app_id: Some("app_1".into()),
            network_seed: None,
            roles_settings: Default::default(),
            ignore_genesis_failure: false,
        }
    }

    // Fails due to clone limit of 0
    assert_matches!(
        conductor
            .clone()
            .install_app_bundle(make_payload(0).await)
            .await
            .unwrap_err(),
        ConductorError::AppBundleError(AppBundleError::AppManifestError(
            AppManifestError::InvalidStrategyCloneOnly(_)
        ))
    );

    {
        // Succeeds with clone limit of 1
        let app = conductor
            .clone()
            .install_app_bundle(make_payload(1).await)
            .await
            .unwrap();

        // No cells in this app due to CloneOnly provisioning strategy
        assert_eq!(app.all_cells().count(), 0);
        assert_eq!(app.role_assignments().len(), 1);
    }
    {
        let clone_cell = conductor
            .create_clone_cell(
                &"app_1".into(),
                CreateCloneCellPayload {
                    role_name: "name".into(),
                    modifiers: DnaModifiersOpt::none()
                        .with_network_seed("1".into())
                        .with_properties(YamlProperties::new(serde_yaml::Value::String(
                            "foo".into(),
                        ))),
                    membrane_proof: None,
                    name: Some("Johnny".into()),
                },
            )
            .await
            .unwrap();

        let state = conductor.get_state().await.unwrap();
        let app = state.get_app(&"app_1".to_string()).unwrap();

        assert_eq!(clone_cell.name, "Johnny".to_string());
        assert_eq!(app.role_assignments().len(), 1);
        assert_eq!(app.clone_cells().count(), 1);
    }
    {
        let err = conductor
            .create_clone_cell(
                &"app_1".into(),
                CreateCloneCellPayload {
                    role_name: "name".into(),
                    modifiers: DnaModifiersOpt::none()
                        .with_network_seed("1".into())
                        .with_properties(YamlProperties::new(serde_yaml::Value::String(
                            "foo".into(),
                        ))),
                    membrane_proof: None,
                    name: None,
                },
            )
            .await
            .unwrap_err();
        assert_matches!(
            err,
            ConductorError::AppError(AppError::CloneLimitExceeded(1, _))
        );
        let state = conductor.get_state().await.unwrap();
        let app = state.get_app(&"app_1".to_string()).unwrap();

        assert_eq!(app.all_cells().count(), 1);
    }
    // TODO: test that the cell can't be provisioned later
}

#[tokio::test(flavor = "multi_thread")]
async fn reject_duplicate_app_for_same_agent() {
    let conductor = SweetConductor::from_standard_config().await;

    let (dna, _, _) = SweetDnaFile::unique_from_test_wasms(vec![TestWasm::Create]).await;
    let path = format!("{}", dna.dna_hash());
    let modifiers = DnaModifiersOpt::none();

    let roles = vec![AppRoleManifest {
        name: "name".into(),
        dna: AppRoleDnaManifest {
            path: Some(path.clone()),
            modifiers: modifiers.clone(),
            installed_hash: None,
            clone_limit: 0,
        },
        provisioning: Some(CellProvisioning::Create { deferred: false }),
    }];

    let manifest = AppManifestCurrentBuilder::default()
        .name("test_app".into())
        .description(None)
        .roles(roles)
        .build()
        .unwrap();
    let resources = vec![(path.clone(), DnaBundle::from_dna_file(dna.clone()).unwrap())];
    let bundle = AppBundle::new(manifest.clone().into(), resources).unwrap();

    let bundle_bytes = bundle.pack().unwrap();
    let app = conductor
        .clone()
        .install_app_bundle(InstallAppPayload {
            agent_key: None,
            source: AppBundleSource::Bytes(bundle_bytes),
            installed_app_id: Some("app_1".into()),
            network_seed: None,
            roles_settings: Default::default(),
            ignore_genesis_failure: false,
        })
        .await
        .unwrap();
    let alice = app.agent_key().clone();

    let cell_id = CellId::new(dna.dna_hash().to_owned(), app.agent_key().clone());

    let resources = vec![(path.clone(), DnaBundle::from_dna_file(dna.clone()).unwrap())];
    let bundle = AppBundle::new(manifest.clone().into(), resources).unwrap();
    let bundle_bytes = bundle.pack().unwrap();
    let duplicate_install_with_app_disabled = conductor
        .clone()
        .install_app_bundle(InstallAppPayload {
            source: AppBundleSource::Bytes(bundle_bytes),
            agent_key: Some(alice.clone()),
            installed_app_id: Some("app_2".into()),
            roles_settings: Default::default(),
            ignore_genesis_failure: false,
            network_seed: None,
        })
        .await;
    assert_matches!(
        duplicate_install_with_app_disabled.unwrap_err(),
        ConductorError::CellAlreadyExists(id) if id == cell_id
    );

    // enable app
    conductor.enable_app("app_1".into()).await.unwrap();

    let resources = vec![(path.clone(), DnaBundle::from_dna_file(dna.clone()).unwrap())];
    let bundle = AppBundle::new(manifest.clone().into(), resources).unwrap();
    let bundle_bytes = bundle.pack().unwrap();
    let duplicate_install_with_app_enabled = conductor
        .clone()
        .install_app_bundle(InstallAppPayload {
            source: AppBundleSource::Bytes(bundle_bytes),
            agent_key: Some(alice.clone()),
            installed_app_id: Some("app_2".into()),
            roles_settings: Default::default(),
            ignore_genesis_failure: false,
            network_seed: None,
        })
        .await;
    assert_matches!(
        duplicate_install_with_app_enabled.unwrap_err(),
        ConductorError::CellAlreadyExists(id) if id == cell_id
    );

    let resources = vec![(path, DnaBundle::from_dna_file(dna.clone()).unwrap())];
    let bundle = AppBundle::new(manifest.into(), resources).unwrap();
    let bundle_bytes = bundle.pack().unwrap();
    let valid_install_of_second_app = conductor
        .clone()
        .install_app_bundle(InstallAppPayload {
            source: AppBundleSource::Bytes(bundle_bytes),
            agent_key: Some(alice.clone()),
            installed_app_id: Some("app_2".into()),
            roles_settings: Default::default(),
            ignore_genesis_failure: false,
            network_seed: Some("network".into()),
        })
        .await;
    assert!(valid_install_of_second_app.is_ok());
}

#[cfg(feature = "unstable-migration")]
#[tokio::test(flavor = "multi_thread")]
async fn cells_by_dna_lineage() {
    let mut conductor = SweetConductor::from_standard_config().await;

    async fn mk_dna(lineage: &[&DnaHash]) -> DnaFile {
        let (dna, _, _) = SweetDnaFile::unique_from_test_wasms(vec![TestWasm::Create]).await;
        let (def, code) = dna.into_parts();
        let mut def = def.into_content();
        def.lineage = lineage.iter().map(|h| (**h).to_owned()).collect();
        DnaFile::from_parts(def.into_hashed(), code)
    }

    // The lineage of a DNA includes the DNA itself
    let dna1 = mk_dna(&[]).await;
    let dna2 = mk_dna(&[dna1.dna_hash()]).await;
    let dna3 = mk_dna(&[dna1.dna_hash(), dna2.dna_hash()]).await;
    // dna1 is removed from the lineage
    let dna4 = mk_dna(&[dna2.dna_hash(), dna3.dna_hash()]).await;
    let dnax = mk_dna(&[]).await;

    let app1 = conductor.setup_app("app1", [&dna1, &dnax]).await.unwrap();
    let app2 = conductor.setup_app("app2", [&dna2]).await.unwrap();
    let app3 = conductor.setup_app("app3", [&dna3]).await.unwrap();
    let app4 = conductor.setup_app("app4", [&dna4]).await.unwrap();

    let lin1 = conductor
        .cells_by_dna_lineage(dna1.dna_hash())
        .await
        .unwrap();
    let lin2 = conductor
        .cells_by_dna_lineage(dna2.dna_hash())
        .await
        .unwrap();
    let lin3 = conductor
        .cells_by_dna_lineage(dna3.dna_hash())
        .await
        .unwrap();
    let lin4 = conductor
        .cells_by_dna_lineage(dna4.dna_hash())
        .await
        .unwrap();
    let linx = conductor
        .cells_by_dna_lineage(dnax.dna_hash())
        .await
        .unwrap();

    fn app_cells(app: &SweetApp, indices: &[usize]) -> (String, BTreeSet<CellId>) {
        (
            app.installed_app_id().clone(),
            indices
                .iter()
                .map(|i| app.cells()[*i].cell_id().clone())
                .collect(),
        )
    }

    pretty_assertions::assert_eq!(
        lin1,
        btreeset![
            app_cells(&app1, &[0]),
            app_cells(&app2, &[0]),
            app_cells(&app3, &[0]),
            // no dna4: dna1 was "removed"
        ]
    );
    pretty_assertions::assert_eq!(
        lin2,
        btreeset![
            // no dna1: it's in the past
            app_cells(&app2, &[0]),
            app_cells(&app3, &[0]),
            app_cells(&app4, &[0]),
        ]
    );
    pretty_assertions::assert_eq!(
        lin3,
        btreeset![
            // no dna1 or dna2: they're in the past
            app_cells(&app3, &[0]),
            app_cells(&app4, &[0]),
        ]
    );
    pretty_assertions::assert_eq!(
        lin4,
        btreeset![
            // all other dnas are in the past
            app_cells(&app4, &[0]),
        ]
    );
    pretty_assertions::assert_eq!(linx, btreeset![app_cells(&app1, &[1]),]);
}

#[tokio::test(flavor = "multi_thread")]
async fn use_existing_integration() {
    let conductor = SweetConductor::from_standard_config().await;

    let (dna1, _, _) = SweetDnaFile::unique_from_test_wasms(vec![TestWasm::WhoAmI]).await;
    let (dna2, _, _) = SweetDnaFile::unique_from_test_wasms(vec![TestWasm::WhoAmI]).await;

    let bundle1 = {
        let path = format!("{}", dna1.dna_hash());

        let roles = vec![AppRoleManifest {
            name: "created".into(),
            dna: AppRoleDnaManifest {
                path: Some(path.clone()),
                modifiers: DnaModifiersOpt::none(),
                installed_hash: None,
                clone_limit: 0,
            },
            provisioning: Some(CellProvisioning::Create { deferred: false }),
        }];

        let manifest = AppManifestCurrentBuilder::default()
            .name("test_app".into())
            .description(None)
            .roles(roles)
            .build()
            .unwrap();

        let resources = vec![(
            path.clone(),
            DnaBundle::from_dna_file(dna1.clone()).unwrap(),
        )];
        AppBundle::new(manifest.clone().into(), resources)
            .unwrap()
            .pack()
            .unwrap()
    };

    let bundle2 = |correct: bool| {
        let dna2 = dna2.clone();
        async move {
            let path = format!("{}", dna2.dna_hash());
            let installed_hash = if correct {
                Some(dna2.dna_hash().clone().into())
            } else {
                None
            };

            let roles = vec![
                AppRoleManifest {
                    name: "created".into(),
                    dna: AppRoleDnaManifest {
                        path: Some(path.clone()),
                        modifiers: DnaModifiersOpt::none(),
                        installed_hash: None,
                        clone_limit: 0,
                    },
                    provisioning: Some(CellProvisioning::Create { deferred: false }),
                },
                AppRoleManifest {
                    name: "extant".into(),
                    dna: AppRoleDnaManifest {
                        path: None,
                        modifiers: DnaModifiersOpt::none(),
                        installed_hash,
                        clone_limit: 0,
                    },
                    #[allow(deprecated)]
                    provisioning: Some(CellProvisioning::UseExisting { protected: true }),
                },
            ];

            let manifest = AppManifestCurrentBuilder::default()
                .name("test_app".into())
                .description(None)
                .roles(roles)
                .build()
                .unwrap();

            let resources = vec![(
                path.clone(),
                DnaBundle::from_dna_file(dna2.clone()).unwrap(),
            )];
            AppBundle::new(manifest.clone().into(), resources)
                .unwrap()
                .pack()
                .unwrap()
        }
    };

    // Install the "dependency" app
    let app_1 = conductor
        .clone()
        .install_app_bundle(InstallAppPayload {
            agent_key: None,
            source: AppBundleSource::Bytes(bundle1),
            installed_app_id: Some("app_1".into()),
            network_seed: None,
            roles_settings: Default::default(),
            ignore_genesis_failure: false,
        })
        .await
        .unwrap();

    {
        // Fail to install the "dependent" app because the dependent DNA hash is not set in the manifest
        let err = conductor
            .clone()
            .install_app_bundle(InstallAppPayload {
                agent_key: None,
                source: AppBundleSource::Bytes(bundle2(false).await),
                installed_app_id: Some("app_2".into()),
                network_seed: None,
                roles_settings: Default::default(),
                ignore_genesis_failure: false,
            })
            .await
            .unwrap_err();

        assert!(matches!(
            err,
            ConductorError::AppBundleError(AppBundleError::AppManifestError(_))
        ));
    }
    {
        // Fail to install the dependent app because the existing CellId is not specified
        let err = conductor
            .clone()
            .install_app_bundle(InstallAppPayload {
                agent_key: None,
                source: AppBundleSource::Bytes(bundle2(true).await),
                installed_app_id: Some("app_2".into()),
                network_seed: None,
                roles_settings: Default::default(),
                ignore_genesis_failure: false,
            })
            .await
            .unwrap_err();

        assert!(matches!(
            err,
            ConductorError::AppBundleError(AppBundleError::CellResolutionFailure(_, _))
        ));
    }

    let cell_id = app_1
        .all_cells()
        .collect::<Vec<CellId>>()
        .first()
        .unwrap()
        .to_owned();

    #[allow(deprecated)]
    let role_settings = ("extant".into(), RoleSettings::UseExisting { cell_id });

    let app_2 = conductor
        .clone()
        .install_app_bundle(InstallAppPayload {
            agent_key: None,
            source: AppBundleSource::Bytes(bundle2(true).await),
            installed_app_id: Some("app_2".into()),
            network_seed: None,
            roles_settings: Some(HashMap::from([role_settings])),
            ignore_genesis_failure: false,
        })
        .await
        .unwrap();

    let cell_id_1 = app_1.all_cells().next().unwrap().clone();
    let cell_id_2 = app_2.all_cells().next().unwrap().clone();
    let zome2 = SweetZome::new(cell_id_2.clone(), "whoami".into());

    conductor.enable_app("app_1".into()).await.unwrap();
    conductor.enable_app("app_2".into()).await.unwrap();
    {
        // - Call the existing dependency cell via the dependent cell, which fails
        // because the proper capability has not been granted
        let r: Result<AgentInfo, _> = conductor
            .call_fallible(&zome2, "who_are_they_role", "extant".to_string())
            .await;
        assert!(r.is_err());
    }

    {
        // - Grant the capability
        let secret = CapSecret::from([1; 64]);
        conductor
            .grant_zome_call_capability(GrantZomeCallCapabilityPayload {
                cell_id: cell_id_1.clone(),
                cap_grant: ZomeCallCapGrant {
                    tag: "tag".into(),
                    // access: CapAccess::Unrestricted,
                    access: CapAccess::Transferable { secret },
                    functions: GrantedFunctions::All,
                },
            })
            .await
            .unwrap();

        // - Call the existing dependency cell via the dependent cell
        let r: AgentInfo = conductor
            .call_from_fallible(
                cell_id_2.agent_pubkey(),
                None,
                &zome2,
                "who_are_they_role_secret",
                ("extant".to_string(), Some(secret)),
            )
            .await
            .unwrap();
        assert_eq!(r.agent_initial_pubkey, *cell_id_1.agent_pubkey());
    }

    // Ideally, we shouldn't be able to disable app_1 because it's depended on by enabled app_2.
    // For now, we are just emitting warnings about this.
    conductor
        .disable_app("app_1".into(), DisabledAppReason::User)
        .await
        .unwrap();
    conductor
        .disable_app("app_2".into(), DisabledAppReason::User)
        .await
        .unwrap();
    conductor
        .disable_app("app_1".into(), DisabledAppReason::User)
        .await
        .unwrap();

    // Can't uninstall app because of dependents
    let err = conductor
        .clone()
        .uninstall_app(&"app_1".to_string(), false)
        .await
        .unwrap_err();
    assert_matches!(
        err,
        ConductorError::AppHasDependents(a, b) if a == *"app_1" && b == vec!["app_2".to_string()]
    );

    // Can still uninstall app with force
    conductor
        .clone()
        .uninstall_app(&"app_1".to_string(), true)
        .await
        .unwrap();
}