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
use std::{
    collections::{BTreeMap, HashMap},
    path::{Path, PathBuf},
};

use crate::prelude::*;
use futures::StreamExt;
use holo_hash::*;
use mr_bundle::{Location, ResourceBytes};

#[cfg(test)]
mod test;

/// A bundle of Wasm zomes, respresented as a file.
#[derive(
    Debug,
    PartialEq,
    Eq,
    serde::Serialize,
    serde::Deserialize,
    SerializedBytes,
    shrinkwraprs::Shrinkwrap,
    derive_more::From,
)]
pub struct DnaBundle(mr_bundle::Bundle<ValidatedDnaManifest>);

impl DnaBundle {
    /// Constructor
    pub fn new(
        manifest: ValidatedDnaManifest,
        resources: Vec<(PathBuf, Vec<u8>)>,
        root_dir: PathBuf,
    ) -> DnaResult<Self> {
        Ok(mr_bundle::Bundle::new(manifest, resources, root_dir)?.into())
    }

    /// Convert to a DnaFile, and return what the hash of the Dna *would* have
    /// been without the provided modifier overrides
    pub async fn into_dna_file(self, modifiers: DnaModifiersOpt) -> DnaResult<(DnaFile, DnaHash)> {
        let (integrity, coordinator, wasms) = self.inner_maps().await?;
        let (dna_def, original_hash) = self.to_dna_def(integrity, coordinator, modifiers)?;

        Ok((DnaFile::from_parts(dna_def, wasms), original_hash))
    }

    /// Construct from raw bytes
    pub fn decode(bytes: &[u8]) -> DnaResult<Self> {
        mr_bundle::Bundle::decode(bytes)
            .map(Into::into)
            .map_err(Into::into)
    }

    /// Read from a bundle file
    pub async fn read_from_file(path: &Path) -> DnaResult<Self> {
        mr_bundle::Bundle::read_from_file(path)
            .await
            .map(Into::into)
            .map_err(Into::into)
    }

    async fn inner_maps(&self) -> DnaResult<(IntegrityZomes, CoordinatorZomes, WasmMap)> {
        let mut resources = self.resolve_all_cloned().await?;
        let data = match &self.manifest().0 {
            DnaManifest::V1(manifest) => {
                let integrity =
                    hash_bytes(manifest.integrity.zomes.iter().cloned(), &mut resources).await?;
                let coordinator =
                    hash_bytes(manifest.coordinator.zomes.iter().cloned(), &mut resources).await?;
                [integrity, coordinator]
            }
        };

        let integrity_zomes = data[0]
            .iter()
            .map(|(zome_name, hash, _, dependencies)| {
                (
                    zome_name.clone(),
                    ZomeDef::Wasm(WasmZome {
                        wasm_hash: hash.clone(),
                        dependencies: dependencies.clone(),
                    })
                    .into(),
                )
            })
            .collect();
        let coordinator_zomes = data[1]
            .iter()
            .map(|(zome_name, hash, _, dependencies)| {
                (
                    zome_name.clone(),
                    ZomeDef::Wasm(WasmZome {
                        wasm_hash: hash.clone(),
                        dependencies: dependencies.clone(),
                    })
                    .into(),
                )
            })
            .collect();
        let code: BTreeMap<_, _> = data
            .into_iter()
            .flatten()
            .map(|(_, hash, wasm, _)| (hash, wasm))
            .collect();

        let wasms = WasmMap::from(code);

        Ok((integrity_zomes, coordinator_zomes, wasms))
    }

    /// Convert to a DnaDef
    pub fn to_dna_def(
        &self,
        integrity_zomes: IntegrityZomes,
        coordinator_zomes: CoordinatorZomes,
        modifiers: DnaModifiersOpt,
    ) -> DnaResult<(DnaDefHashed, DnaHash)> {
        match &self.manifest().0 {
            DnaManifest::V1(manifest) => {
                let dna_def = DnaDef {
                    name: manifest.name.clone(),
                    modifiers: DnaModifiers {
                        network_seed: manifest.integrity.network_seed.clone().unwrap_or_default(),
                        properties: SerializedBytes::try_from(
                            manifest.integrity.properties.clone().unwrap_or_default(),
                        )?,
                        origin_time: manifest.integrity.origin_time.into(),
                    },
                    integrity_zomes,
                    coordinator_zomes,
                };

                let original_hash = DnaHash::with_data_sync(&dna_def);
                let ddh = DnaDefHashed::from_content_sync(dna_def.update_modifiers(modifiers));
                Ok((ddh, original_hash))
            }
        }
    }

    /// Build a bundle from a DnaFile. Useful for tests.
    #[cfg(feature = "test_utils")]
    pub async fn from_dna_file(dna_file: DnaFile) -> DnaResult<Self> {
        let DnaFile { dna, code, .. } = dna_file;
        let manifest = Self::manifest_from_dna_def(dna.into_content())?;
        let resources = code
            .into_iter()
            .map(|(hash, wasm)| (PathBuf::from(hash.to_string()), wasm.code.to_vec()))
            .collect();
        DnaBundle::new(manifest.try_into()?, resources, PathBuf::from("."))
    }

    #[cfg(feature = "test_utils")]
    fn manifest_from_dna_def(dna_def: DnaDef) -> DnaResult<DnaManifest> {
        let integrity = dna_def
            .integrity_zomes
            .into_iter()
            .filter_map(|(name, zome)| {
                let dependencies = zome
                    .as_any_zome_def()
                    .dependencies()
                    .iter()
                    .cloned()
                    .map(|name| ZomeDependency { name })
                    .collect();
                zome.wasm_hash(&name).ok().map(|hash| {
                    let hash = WasmHashB64::from(hash);
                    let filename = format!("{}", hash);
                    ZomeManifest {
                        name,
                        hash: Some(hash),
                        location: Location::Bundled(PathBuf::from(filename)),
                        dependencies: Some(dependencies),
                    }
                })
            })
            .collect();
        let coordinator = dna_def
            .coordinator_zomes
            .into_iter()
            .filter_map(|(name, zome)| {
                let dependencies = zome
                    .as_any_zome_def()
                    .dependencies()
                    .iter()
                    .cloned()
                    .map(|name| ZomeDependency { name })
                    .collect();
                zome.wasm_hash(&name).ok().map(|hash| {
                    let hash = WasmHashB64::from(hash);
                    let filename = format!("{}", hash);
                    ZomeManifest {
                        name,
                        hash: Some(hash),
                        location: Location::Bundled(PathBuf::from(filename)),
                        dependencies: Some(dependencies),
                    }
                })
            })
            .collect();
        Ok(DnaManifestCurrent {
            name: dna_def.name,
            integrity: IntegrityManifest {
                network_seed: Some(dna_def.modifiers.network_seed),
                properties: Some(dna_def.modifiers.properties.try_into().map_err(|e| {
                    DnaError::DnaFileToBundleConversionError(format!(
                        "DnaDef properties were not YAML-deserializable: {}",
                        e
                    ))
                })?),
                origin_time: dna_def.modifiers.origin_time.into(),
                zomes: integrity,
            },
            coordinator: CoordinatorManifest { zomes: coordinator },
        }
        .into())
    }
}

pub(super) async fn hash_bytes(
    zomes: impl Iterator<Item = ZomeManifest>,
    resources: &mut HashMap<Location, ResourceBytes>,
) -> DnaResult<Vec<(ZomeName, WasmHash, DnaWasm, Vec<ZomeName>)>> {
    let iter = zomes.map(|z| {
        let bytes = resources
            .remove(&z.location)
            .expect("resource referenced in manifest must exist");
        let zome_name = z.name;
        let expected_hash = z.hash.map(WasmHash::from);
        let wasm = DnaWasm::from(bytes);
        let dependencies = z.dependencies.map_or(Vec::with_capacity(0), |deps| {
            deps.into_iter().map(|d| d.name).collect()
        });
        async move {
            let hash = wasm.to_hash().await;
            if let Some(expected) = expected_hash {
                if hash != expected {
                    return Err(DnaError::WasmHashMismatch(expected, hash));
                }
            }
            DnaResult::Ok((zome_name, hash, wasm, dependencies))
        }
    });
    futures::stream::iter(iter)
        .buffered(10)
        .collect::<Vec<_>>()
        .await
        .into_iter()
        .collect()
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::*;

    #[tokio::test(flavor = "multi_thread")]
    async fn dna_bundle_to_dna_file() {
        let path1 = PathBuf::from("1");
        let path2 = PathBuf::from("2");
        let wasm1 = vec![1, 2, 3];
        let wasm2 = vec![4, 5, 6];
        let hash1 = DnaWasm::from(wasm1.clone()).to_hash().await;
        let hash2 = DnaWasm::from(wasm2.clone()).to_hash().await;
        let mut manifest = DnaManifestCurrent {
            name: "name".into(),
            integrity: IntegrityManifest {
                network_seed: Some("original network seed".to_string()),
                properties: Some(serde_yaml::Value::Null.into()),
                origin_time: Timestamp::HOLOCHAIN_EPOCH.into(),
                zomes: vec![
                    ZomeManifest {
                        name: "zome1".into(),
                        hash: None,
                        location: mr_bundle::Location::Bundled(path1.clone()),
                        dependencies: Default::default(),
                    },
                    ZomeManifest {
                        name: "zome2".into(),
                        // Intentional wrong hash
                        hash: Some(hash1.clone().into()),
                        location: mr_bundle::Location::Bundled(path2.clone()),
                        dependencies: Default::default(),
                    },
                ],
            },
            coordinator: CoordinatorManifest { zomes: vec![] },
        };
        let resources = vec![(path1, wasm1), (path2, wasm2)];

        // - Show that conversion fails due to hash mismatch
        let bad_bundle: DnaBundle = mr_bundle::Bundle::new_unchecked(
            manifest.clone().try_into().unwrap(),
            resources.clone(),
        )
        .unwrap()
        .into();
        matches::assert_matches!(
            bad_bundle.into_dna_file(DnaModifiersOpt::none()).await,
            Err(DnaError::WasmHashMismatch(h1, h2))
            if h1 == hash1 && h2 == hash2
        );

        // - Correct the hash and try again
        manifest.integrity.zomes[1].hash = Some(hash2.into());
        let bundle: DnaBundle = mr_bundle::Bundle::new_unchecked(
            manifest.clone().try_into().unwrap(),
            resources.clone(),
        )
        .unwrap()
        .into();
        let dna_file: DnaFile = bundle
            .into_dna_file(DnaModifiersOpt::none())
            .await
            .unwrap()
            .0;
        assert_eq!(dna_file.dna_def().integrity_zomes.len(), 2);
        assert_eq!(dna_file.code().len(), 2);

        // - Check that properties and UUID can be overridden
        let properties: YamlProperties = serde_yaml::Value::from(42).into();
        let bundle: DnaBundle =
            mr_bundle::Bundle::new_unchecked(manifest.try_into().unwrap(), resources)
                .unwrap()
                .into();
        let dna_file: DnaFile = bundle
            .into_dna_file(
                DnaModifiersOpt::none()
                    .with_network_seed("network_seed".into())
                    .with_properties(properties.clone())
                    .serialized()
                    .unwrap(),
            )
            .await
            .unwrap()
            .0;
        assert_eq!(
            dna_file.dna.modifiers.network_seed,
            "network_seed".to_string()
        );
        assert_eq!(
            dna_file.dna.modifiers.properties,
            SerializedBytes::try_from(properties).unwrap()
        );
    }
}