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
//! This file contains the define_zome! macro, and smaller helper macros.

#[doc(hidden)]
#[macro_export]
macro_rules! load_json {
    ($encoded_allocation_of_input:ident) => {{

        let maybe_input = $crate::holochain_wasm_utils::memory::ribosome::load_ribosome_encoded_json(
            $encoded_allocation_of_input,
        );

        match maybe_input {
            Ok(input) => input,
            Err(hc_err) => return $crate::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result(
                $crate::global_fns::write_json(hc_err)
            ).into(),
        }

    }};
}

#[doc(hidden)]
#[macro_export]
macro_rules! load_string {
    ($encoded_allocation_of_input:ident) => {{

        let maybe_input = $crate::holochain_wasm_utils::memory::ribosome::load_ribosome_encoded_string(
            $encoded_allocation_of_input,
        );

        match maybe_input {
            Ok(input) => input,
            Err(hc_err) => return $crate::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result(
                $crate::global_fns::write_json(hc_err)
            ).into(),
        }

    }};
}

/// Every Zome must utilize the `define_zome`
/// macro in the main library file in their Zome.
/// The `define_zome` macro has 4 component parts:
/// 1. entries: an array of [ValidatingEntryType](entry_definition/struct.ValidatingEntryType.html) as returned by using the [entry](macro.entry.html) macro
/// 2. init: `init` is a callback called by Holochain to every Zome implemented within a DNA.
///     It gets called when a new agent is initializing an instance of the DNA for the first time, and
///     should return `Ok` or an `Err`, depending on whether the agent can join the network or not.
/// 3. receive (optional): `receive` is a callback called by Holochain when another agent on a hApp has initiated a node-to-node direct message.
///     That node-to-node message is initiated via the [**send** function of the API](api/fn.send.html), which is where you can read further about use of `send` and `receive`.
///     `receive` is optional to include, based on whether you use `send` anywhere in the code.
/// 4. functions:
///     `functions` declares all the zome's functions with their input/output signatures
/// # Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate hdk;
/// # extern crate serde;
/// # #[macro_use]
/// # extern crate serde_derive;
/// # #[macro_use]
/// # extern crate serde_json;
/// # extern crate boolinator;
/// # extern crate holochain_core_types;
/// # #[macro_use]
/// # extern crate holochain_json_derive;
/// # extern crate holochain_json_api;
/// # extern crate holochain_persistence_api;
/// # use holochain_core_types::entry::Entry;
/// # use holochain_core_types::entry::entry_type::AppEntryType;
/// # use holochain_json_api::{error::JsonError, json::JsonString};
/// # use holochain_core_types::error::HolochainError;
/// # use holochain_core_types::error::RibosomeEncodedValue;
/// # use boolinator::Boolinator;
/// use hdk::error::ZomeApiResult;
/// use holochain_core_types::{
///     dna::entry_types::Sharing,
///     validation::EntryValidationData
/// };
/// # use holochain_persistence_api::cas::content::Address;
/// # use holochain_core_types::error::RibosomeEncodingBits;
/// # // Adding empty functions so that the cfg(test) build can link.
/// # #[no_mangle]
/// # pub fn hc_init_globals(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_commit_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_get_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_entry_address(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_query(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_update_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_remove_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_send(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_sleep(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_debug(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_call(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// #[no_mangle]
/// # pub fn hc_crypto(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// #[no_mangle]
/// # pub fn hc_meta(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_sign_one_time(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_verify_signature(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_get_links(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_get_links_count(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_link_entries(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_remove_link(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_keystore_list(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_keystore_new_random(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_keystore_derive_seed(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_keystore_derive_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_keystore_sign(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_keystore_get_public_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_commit_capability_grant(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_commit_capability_claim(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
/// # #[no_mangle]
/// # pub fn hc_emit_signal(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() }
///
/// # fn main() {
///
/// #[derive(Serialize, Deserialize, Debug, DefaultJson,Clone)]
/// pub struct Post {
///     content: String,
///     date_created: String,
/// }
///
/// fn handle_post_address(content: String) -> ZomeApiResult<Address> {
///     let post_entry = Entry::App("post".into(), Post {
///         content,
///         date_created: "now".into(),
///     }.into());
///
///     hdk::entry_address(&post_entry)
/// }
///
/// define_zome! {
///     entries: [
///         entry!(
///             name: "post",
///             description: "",
///             sharing: Sharing::Public,
///
///             validation_package: || {
///                 hdk::ValidationPackageDefinition::ChainFull
///             },
///
///             validation: |validation_data: hdk::EntryValidationData<Post>| {
///              match validation_data
///              {
///              EntryValidationData::Create{entry:test_entry,validation_data:_} =>
///              {
///
///
///                        (test_entry.content != "FAIL")
///                        .ok_or_else(|| "FAIL content is not allowed".to_string())
///                }
///                _ =>
///                 {
///                      Err("Failed to validate with wrong entry type".to_string())
///                }
///         }}
///
///         )
///     ]
///
///     init: || {
///         Ok(())
///     }
///     
///     validate_agent: |validation_data : EntryValidationData::<AgentId>| {
///         Ok(())
///     }
///
///     receive: |from, payload| {
///       // just return what was received, but modified
///       format!("Received: {} from {}", payload, from)
///     }
///
///     functions: [
///             // the name of this function, "post_address" is the
///             // one to give while performing a `call` method to this function.
///             // the name of the handler function must be different than the
///             // name of the Zome function.
///             post_address: {
///                 inputs: |content: String|,
///                 outputs: |post: ZomeApiResult<Address>|,
///                 handler: handle_post_address
///             }
///     ]
///
///     // trait named "hc_public" will grant public access to all its functions
///     traits: {
///         hc_public [post_address]
///     }
/// }
///
/// # }
/// ```
#[macro_export]
macro_rules! define_zome {
    (
        entries : [
            $( $entry_expr:expr ),*
        ]

        init : || {
            $init_expr:expr
        }


        validate_agent: |$agent_validation_param:ident : EntryValidationData::<AgentId>| {
            $agent_validation_expr:expr
        }


        $(
            receive : |$receive_from:ident, $receive_param:ident| {
                $receive_expr:expr
            }
        )*

        functions : [
            $(
                        $zome_function_name:ident : {
                            inputs: | $( $input_param_name:ident : $input_param_type:ty ),* |,
                            outputs: | $( $output_param_name:ident : $output_param_type:ty ),* |,
                            handler: $handler_path:path
                        }
            )*
        ]

        traits : {
                $(
                    $trait:ident [
                        $($trait_fn:ident),*
                    ]
                )*
            }


    ) => {
        #[no_mangle]
        #[allow(unused_variables)]
        pub extern "C" fn zome_setup(zd: &mut $crate::meta::ZomeDefinition) {
            $(
                zd.define($entry_expr);
            )*

            let validator = Box::new(|validation_data: hdk::holochain_wasm_utils::holochain_core_types::validation::EntryValidationData<hdk::holochain_core_types::agent::AgentId>| {
                let $agent_validation_param = validation_data;
                $agent_validation_expr
            });
            zd.define_agent_validator(validator);
        }

        #[no_mangle]
        pub extern "C" fn init(encoded_allocation_of_input: hdk::holochain_core_types::error::RibosomeEncodingBits) -> hdk::holochain_core_types::error::RibosomeEncodingBits {
            let maybe_allocation = $crate::holochain_wasm_utils::memory::allocation::WasmAllocation::try_from_ribosome_encoding(encoded_allocation_of_input);
            let allocation = match maybe_allocation {
                Ok(allocation) => allocation,
                Err(allocation_error) => return hdk::holochain_core_types::error::RibosomeEncodedValue::from(allocation_error).into(),
            };
            let init = $crate::global_fns::init_global_memory(allocation);
            if init.is_err() {
                return $crate::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result(
                    init
                ).into();
            }

            fn execute() -> Result<(), String> {
                $init_expr
            }

            match execute() {
                Ok(_) => hdk::holochain_core_types::error::RibosomeEncodedValue::Success.into(),
                Err(e) => $crate::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result(
                    $crate::global_fns::write_json(
                        $crate::holochain_wasm_utils::holochain_json_api::json::RawString::from(e)
                    )
                ).into(),
            }
        }

        $(
            #[no_mangle]
            pub extern "C" fn receive(encoded_allocation_of_input: hdk::holochain_core_types::error::RibosomeEncodingBits) -> hdk::holochain_core_types::error::RibosomeEncodingBits {
                let maybe_allocation = $crate::holochain_wasm_utils::memory::allocation::WasmAllocation::try_from_ribosome_encoding(encoded_allocation_of_input);
                let allocation = match maybe_allocation {
                    Ok(allocation) => allocation,
                    Err(allocation_error) => return hdk::holochain_core_types::error::RibosomeEncodedValue::from(allocation_error).into(),
                };
                let init = $crate::global_fns::init_global_memory(allocation);
                if init.is_err() {
                    return $crate::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result(
                        init
                    ).into();
                }

                // Deserialize input
                let input = load_json!(encoded_allocation_of_input);

                fn execute(input: $crate::holochain_wasm_utils::api_serialization::receive::ReceiveParams ) -> String {
                    let $receive_param = input.payload;
                    let $receive_from = input.from;
                    $receive_expr
                }

                $crate::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result(
                    $crate::global_fns::write_json(
                        JsonString::from_json(&execute(input))
                    )
                ).into()
            }
        )*

        use std::collections::HashMap;

        #[no_mangle]
        #[allow(unused_imports)]
        pub fn __list_traits() -> $crate::holochain_core_types::dna::zome::ZomeTraits {

            use $crate::holochain_core_types::dna::{
                fn_declarations::{FnParameter, FnDeclaration, TraitFns},
            };

            use std::collections::BTreeMap;

            let return_value: $crate::holochain_core_types::dna::zome::ZomeTraits = {
                let mut traitfns_map = BTreeMap::new();

                $(
                    {
                        let mut traitfns = TraitFns::new();
                        traitfns.functions = vec![
                            $(
                                stringify!($trait_fn).into()
                            ),*
                        ];

                        traitfns_map.insert(stringify!($trait).into(), traitfns);
                    }
                ),*

                traitfns_map
            };

            return_value
        }

        #[no_mangle]
        #[allow(unused_imports)]
        pub fn __list_functions() -> $crate::holochain_core_types::dna::zome::ZomeFnDeclarations {

            use $crate::holochain_core_types::dna::fn_declarations::{FnParameter, FnDeclaration};

            let return_value: $crate::holochain_core_types::dna::zome::ZomeFnDeclarations = {
                vec![

                    $(
                         FnDeclaration {
                                    name: stringify!($zome_function_name).into(),
                                    inputs: vec![
                                        $(
                                            FnParameter::new(stringify!($input_param_name), stringify!($input_param_type))
                                        ),*
                                    ],
                                    outputs: vec![
                                        $(
                                            FnParameter::new(stringify!($output_param_name), stringify!($output_param_type))
                                        ),*
                                    ]
                                }
                    ),*

                ]
            };

            return_value
        }


        #[no_mangle]
        pub extern "C" fn __install_panic_handler() -> () {
            use $crate::{api::debug, holochain_json_api::json::RawString};
            use std::panic;
            panic::set_hook(Box::new(move |info| {
                let _ = debug(RawString::from(
                    info.payload().downcast_ref::<String>().unwrap().clone(),
                ));

                let _ = if let Some(location) = info.location() {
                    debug(RawString::from(format!(
                        "panic occurred in file '{}' at line {}",
                        location.file(),
                        location.line()
                    )))
                } else {
                    debug(RawString::from(format!(
                        "panic occurred but can't get location information..."
                    )))
                };
            }));
        }


        $(
                #[no_mangle]
                pub extern "C" fn $zome_function_name(encoded_allocation_of_input: hdk::holochain_core_types::error::RibosomeEncodingBits) -> hdk::holochain_core_types::error::RibosomeEncodingBits {
                    let maybe_allocation = $crate::holochain_wasm_utils::memory::allocation::WasmAllocation::try_from_ribosome_encoding(encoded_allocation_of_input);
                    let allocation = match maybe_allocation {
                        Ok(allocation) => allocation,
                        Err(allocation_error) => return hdk::holochain_core_types::error::RibosomeEncodedValue::from(allocation_error).into(),
                    };
                    let init = $crate::global_fns::init_global_memory(allocation);
                    if init.is_err() {
                        return $crate::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result(
                            init
                        ).into();
                    }

                    // Macro'd InputStruct
                    #[derive(Deserialize, Serialize, Debug, $crate::holochain_json_derive::DefaultJson)]
                    struct InputStruct {
                        $($input_param_name : $input_param_type),*
                    }

                    // Deserialize input
                    let input: InputStruct = load_json!(encoded_allocation_of_input);

                    // Macro'd function body
                    fn execute (params: InputStruct) -> $( $output_param_type )* {
                        let InputStruct { $($input_param_name),* } = params;

                        $handler_path($($input_param_name),*)
                    }

                    $crate::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result(
                        $crate::global_fns::write_json(execute(input))
                    ).into()
                }
        )*
    };
}