diff --git a/Cargo.lock b/Cargo.lock index 8b353686b6..c72c8957c0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,7 +10,7 @@ name = "aho-corasick" version = "0.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -41,23 +41,12 @@ name = "ascii" version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "assert_cmd" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "escargot 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "predicates 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "predicates-core 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "predicates-tree 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "atty" version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "hermit-abi 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "hermit-abi 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -205,11 +194,16 @@ version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "regex-automata 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "byte-slice-cast" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "byte-tools" version = "0.2.0" @@ -394,7 +388,7 @@ dependencies = [ "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "smallvec 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "target-lexicon 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", - "thiserror 1.0.10 (registry+https://github.com/rust-lang/crates.io-index)", + "thiserror 1.0.11 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -445,24 +439,26 @@ dependencies = [ [[package]] name = "crossbeam-deque" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "crossbeam-epoch 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-epoch 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "crossbeam-epoch" -version = "0.8.0" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "memoffset 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)", - "scopeguard 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "scopeguard 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -479,7 +475,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -493,10 +489,10 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.7.0" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -530,7 +526,7 @@ version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "bstr 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", - "csv-core 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "csv-core 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", "itoa 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "ryu 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", @@ -538,10 +534,10 @@ dependencies = [ [[package]] name = "csv-core" -version = "0.1.6" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -550,7 +546,7 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -574,11 +570,6 @@ name = "detach" version = "0.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "deunicode" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "difference" version = "2.0.0" @@ -619,36 +610,6 @@ dependencies = [ "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "dirs" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "dirs-sys 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "dirs-sys" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", - "redox_users 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "dns-lookup" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", - "socket2 0.3.11 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "dtoa" version = "0.4.5" @@ -715,24 +676,6 @@ dependencies = [ "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "error-chain" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "backtrace 0.3.27 (registry+https://github.com/rust-lang/crates.io-index)", - "version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "escargot" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.47 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "failure" version = "0.1.5" @@ -749,7 +692,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)", "synstructure 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -931,7 +874,7 @@ dependencies = [ "proc-macro-hack 0.5.11 (registry+https://github.com/rust-lang/crates.io-index)", "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -976,7 +919,7 @@ dependencies = [ "futures-macro 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", "futures-sink 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", "futures-task 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", - "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "pin-utils 0.1.0-alpha.4 (registry+https://github.com/rust-lang/crates.io-index)", "proc-macro-hack 0.5.11 (registry+https://github.com/rust-lang/crates.io-index)", "proc-macro-nested 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -992,7 +935,7 @@ dependencies = [ "futures-core-preview 0.3.0-alpha.17 (registry+https://github.com/rust-lang/crates.io-index)", "futures-io-preview 0.3.0-alpha.17 (registry+https://github.com/rust-lang/crates.io-index)", "futures-sink-preview 0.3.0-alpha.17 (registry+https://github.com/rust-lang/crates.io-index)", - "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "pin-utils 0.1.0-alpha.4 (registry+https://github.com/rust-lang/crates.io-index)", "slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1046,7 +989,7 @@ dependencies = [ "aho-corasick 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)", "fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "regex 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1086,57 +1029,6 @@ dependencies = [ "scopeguard 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "hc" -version = "0.0.43-alpha3" -dependencies = [ - "assert_cmd 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)", - "base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", - "colored 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-channel 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", - "dns-lookup 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", - "flate2 1.0.12 (registry+https://github.com/rust-lang/crates.io-index)", - "glob 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "hcid 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "holochain_common 0.0.43-alpha3", - "holochain_conductor_lib 0.0.43-alpha3", - "holochain_core 0.0.43-alpha3", - "holochain_core_types 0.0.43-alpha3", - "holochain_dpki 0.0.43-alpha3", - "holochain_json_api 0.0.23 (registry+https://github.com/rust-lang/crates.io-index)", - "holochain_locksmith 0.0.43-alpha3", - "holochain_net 0.0.43-alpha3", - "holochain_persistence_api 0.0.17 (registry+https://github.com/rust-lang/crates.io-index)", - "holochain_persistence_file 0.0.17 (registry+https://github.com/rust-lang/crates.io-index)", - "holochain_tracing 0.0.19 (registry+https://github.com/rust-lang/crates.io-index)", - "holochain_tracing_macros 0.0.19 (registry+https://github.com/rust-lang/crates.io-index)", - "holochain_wasm_utils 0.0.43-alpha3", - "ignore 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "in_stream 0.0.43-alpha3", - "json-patch 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "lib3h_crypto_api 0.0.38 (registry+https://github.com/rust-lang/crates.io-index)", - "lib3h_protocol 0.0.38 (registry+https://github.com/rust-lang/crates.io-index)", - "lib3h_sodium 0.0.38 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "newrelic 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "reqwest 0.9.11 (registry+https://github.com/rust-lang/crates.io-index)", - "rpassword 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "rustyline 5.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_derive 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.47 (registry+https://github.com/rust-lang/crates.io-index)", - "sim2h 0.0.43-alpha3", - "structopt 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "tar 0.4.26 (registry+https://github.com/rust-lang/crates.io-index)", - "tempfile 3.0.7 (registry+https://github.com/rust-lang/crates.io-index)", - "tera 0.11.20 (registry+https://github.com/rust-lang/crates.io-index)", - "toml 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "url2 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "hcid" version = "0.0.6" @@ -1158,7 +1050,8 @@ dependencies = [ "holochain_json_api 0.0.23 (registry+https://github.com/rust-lang/crates.io-index)", "holochain_json_derive 0.0.23 (registry+https://github.com/rust-lang/crates.io-index)", "holochain_persistence_api 0.0.17 (registry+https://github.com/rust-lang/crates.io-index)", - "holochain_wasm_utils 0.0.43-alpha3", + "holochain_wasm_types 0.0.43-alpha3", + "holochain_wasmer_guest 0.0.18 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "pretty_assertions 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1189,7 +1082,7 @@ dependencies = [ [[package]] name = "hermit-abi" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1274,7 +1167,7 @@ dependencies = [ "holochain_persistence_pickle 0.0.17 (registry+https://github.com/rust-lang/crates.io-index)", "holochain_tracing 0.0.19 (registry+https://github.com/rust-lang/crates.io-index)", "holochain_tracing_macros 0.0.19 (registry+https://github.com/rust-lang/crates.io-index)", - "holochain_wasm_utils 0.0.43-alpha3", + "holochain_wasm_types 0.0.43-alpha3", "hyper 0.12.25 (registry+https://github.com/rust-lang/crates.io-index)", "json-patch 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-core 14.0.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1316,7 +1209,7 @@ dependencies = [ "holochain_core_types 0.0.43-alpha3", "holochain_locksmith 0.0.43-alpha3", "holochain_tracing_macros 0.0.19 (registry+https://github.com/rust-lang/crates.io-index)", - "holochain_wasm_utils 0.0.43-alpha3", + "holochain_wasm_types 0.0.43-alpha3", "jsonrpc-core 14.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-lite 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1364,7 +1257,8 @@ dependencies = [ "holochain_persistence_mem 0.0.17 (registry+https://github.com/rust-lang/crates.io-index)", "holochain_tracing 0.0.19 (registry+https://github.com/rust-lang/crates.io-index)", "holochain_tracing_macros 0.0.19 (registry+https://github.com/rust-lang/crates.io-index)", - "holochain_wasm_utils 0.0.43-alpha3", + "holochain_wasm_types 0.0.43-alpha3", + "holochain_wasmer_host 0.0.18 (registry+https://github.com/rust-lang/crates.io-index)", "im 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "itertools 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-core 14.0.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1374,6 +1268,7 @@ dependencies = [ "lib3h_sodium 0.0.38 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "newrelic 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "num 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "num-derive 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", "pin-utils 0.1.0-alpha.4 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1392,7 +1287,6 @@ dependencies = [ "url 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "wabt 0.7.4 (registry+https://github.com/rust-lang/crates.io-index)", "wasmer-runtime 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)", - "wasmi 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1411,6 +1305,7 @@ dependencies = [ "holochain_locksmith 0.0.43-alpha3", "holochain_logging 0.0.7 (registry+https://github.com/rust-lang/crates.io-index)", "holochain_persistence_api 0.0.17 (registry+https://github.com/rust-lang/crates.io-index)", + "holochain_wasmer_common 0.0.18 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "lib3h_crypto_api 0.0.38 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1428,7 +1323,6 @@ dependencies = [ "snowflake 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "test_utils 0.0.43-alpha3", "uuid 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", - "wasmi 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1755,24 +1649,53 @@ dependencies = [ "newrelic 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "holochain_wasm_utils" +name = "holochain_wasm_types" version = "0.0.43-alpha3" dependencies = [ - "holochain_conductor_lib 0.0.43-alpha3", - "holochain_core 0.0.43-alpha3", "holochain_core_types 0.0.43-alpha3", "holochain_json_api 0.0.23 (registry+https://github.com/rust-lang/crates.io-index)", "holochain_json_derive 0.0.23 (registry+https://github.com/rust-lang/crates.io-index)", "holochain_persistence_api 0.0.17 (registry+https://github.com/rust-lang/crates.io-index)", + "holochain_wasmer_guest 0.0.18 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.47 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "holochain_wasmer_common" +version = "0.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byte-slice-cast 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", + "holochain_json_api 0.0.23 (registry+https://github.com/rust-lang/crates.io-index)", + "holochain_json_derive 0.0.23 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.47 (registry+https://github.com/rust-lang/crates.io-index)", - "tempfile 3.0.7 (registry+https://github.com/rust-lang/crates.io-index)", - "test_utils 0.0.43-alpha3", +] + +[[package]] +name = "holochain_wasmer_guest" +version = "0.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "holochain_wasmer_common 0.0.18 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "holochain_wasmer_host" +version = "0.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byte-slice-cast 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", + "holochain_wasmer_common 0.0.18 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "wasmer-runtime 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1807,11 +1730,6 @@ name = "httparse" version = "1.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "humansize" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "humantime" version = "1.3.0" @@ -1897,23 +1815,6 @@ dependencies = [ "unicode-normalization 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "ignore" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "crossbeam-channel 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", - "globset 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "regex 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "same-file 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "walkdir 2.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "im" version = "14.0.0" @@ -2264,7 +2165,7 @@ name = "lock_api" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "scopeguard 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "scopeguard 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2272,7 +2173,7 @@ name = "lock_api" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "scopeguard 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "scopeguard 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2332,11 +2233,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "memchr" -version = "2.3.0" +version = "2.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", -] [[package]] name = "memmap" @@ -2355,11 +2253,6 @@ dependencies = [ "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "memory_units" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "mime" version = "0.2.6" @@ -2679,7 +2572,7 @@ name = "num_cpus" version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "hermit-abi 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "hermit-abi 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -2786,14 +2679,6 @@ dependencies = [ "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "parity-wasm" -version = "0.31.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "byteorder 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "parking_lot" version = "0.4.8" @@ -2926,45 +2811,6 @@ name = "percent-encoding" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "pest" -version = "2.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "ucd-trie 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "pest_derive" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "pest 2.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "pest_generator 2.1.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "pest_generator" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "pest 2.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "pest_meta 2.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "pest_meta" -version = "2.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "maplit 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "pest 2.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "sha-1 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "petgraph" version = "0.4.13" @@ -3036,15 +2882,6 @@ name = "predicates-core" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "predicates-tree" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "predicates-core 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "treeline 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "pretty_assertions" version = "0.6.1" @@ -3076,7 +2913,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3094,7 +2931,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3349,7 +3186,7 @@ name = "rayon" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "crossbeam-deque 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-deque 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", "either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)", "rayon-core 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -3359,9 +3196,9 @@ name = "rayon-core" version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "crossbeam-deque 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-deque 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", "crossbeam-queue 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "num_cpus 1.11.1 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -3400,7 +3237,7 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "aho-corasick 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)", - "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "regex-syntax 0.6.14 (registry+https://github.com/rust-lang/crates.io-index)", "thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "utf8-ranges 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3590,7 +3427,7 @@ dependencies = [ "base64 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "blake2b_simd 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)", "constant_time_eq 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3669,22 +3506,6 @@ dependencies = [ "trackable 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "rustyline" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "dirs 2.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-segmentation 1.6.0 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-width 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", - "utf8parse 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "ryu" version = "1.0.2" @@ -3695,14 +3516,6 @@ name = "safemem" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "winapi-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "schannel" version = "0.1.17" @@ -3719,7 +3532,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "scopeguard" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -3747,7 +3560,6 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3805,7 +3617,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3926,7 +3738,7 @@ dependencies = [ "itertools 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4030,14 +3842,6 @@ name = "slab" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "slug" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "deunicode 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "smallvec" version = "0.6.13" @@ -4143,7 +3947,7 @@ dependencies = [ "proc-macro-error 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4173,7 +3977,7 @@ dependencies = [ [[package]] name = "syn" -version = "1.0.14" +version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", @@ -4199,7 +4003,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -4237,26 +4041,6 @@ dependencies = [ "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "tera" -version = "0.11.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "error-chain 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)", - "glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", - "humansize 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "pest 2.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "pest_derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "regex 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.47 (registry+https://github.com/rust-lang/crates.io-index)", - "slug 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "unic-segment 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.7.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "term" version = "0.5.2" @@ -4291,7 +4075,7 @@ dependencies = [ "holochain_locksmith 0.0.43-alpha3", "holochain_net 0.0.43-alpha3", "holochain_persistence_api 0.0.17 (registry+https://github.com/rust-lang/crates.io-index)", - "holochain_wasm_utils 0.0.43-alpha3", + "holochain_wasm_types 0.0.43-alpha3", "jsonrpc-ws-server 14.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "lib3h_sodium 0.0.38 (registry+https://github.com/rust-lang/crates.io-index)", @@ -4314,20 +4098,20 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "thiserror-impl 1.0.10 (registry+https://github.com/rust-lang/crates.io-index)", + "thiserror-impl 1.0.11 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "thiserror-impl" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4419,7 +4203,7 @@ dependencies = [ "iovec 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", - "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "mio 0.6.21 (registry+https://github.com/rust-lang/crates.io-index)", "mio-named-pipes 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "mio-uds 0.6.7 (registry+https://github.com/rust-lang/crates.io-index)", @@ -4455,7 +4239,7 @@ name = "tokio-executor" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", "futures 0.1.29 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -4486,7 +4270,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4512,7 +4296,7 @@ name = "tokio-reactor" version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", "futures 0.1.29 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", @@ -4568,9 +4352,9 @@ name = "tokio-threadpool" version = "0.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "crossbeam-deque 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-deque 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", "crossbeam-queue 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", "futures 0.1.29 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", @@ -4584,7 +4368,7 @@ name = "tokio-timer" version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", "futures 0.1.29 (registry+https://github.com/rust-lang/crates.io-index)", "slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", "tokio-executor 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", @@ -4643,7 +4427,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4659,11 +4443,6 @@ dependencies = [ "serde_json 1.0.47 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "treeline" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "try-lock" version = "0.2.2" @@ -4724,55 +4503,6 @@ name = "typenum" version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "ucd-trie" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "unic-char-property" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "unic-char-range 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "unic-char-range" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "unic-common" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "unic-segment" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "unic-ucd-segment 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "unic-ucd-segment" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "unic-char-property 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", - "unic-char-range 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", - "unic-ucd-version 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "unic-ucd-version" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "unic-common 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "unicase" version = "1.4.2" @@ -4967,16 +4697,6 @@ dependencies = [ "glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "walkdir" -version = "2.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "same-file 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "want" version = "0.0.6" @@ -5083,7 +4803,7 @@ dependencies = [ "cranelift-codegen 0.52.0 (registry+https://github.com/rust-lang/crates.io-index)", "cranelift-entity 0.52.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "thiserror 1.0.10 (registry+https://github.com/rust-lang/crates.io-index)", + "thiserror 1.0.11 (registry+https://github.com/rust-lang/crates.io-index)", "wasmer-clif-fork-frontend 0.52.0 (registry+https://github.com/rust-lang/crates.io-index)", "wasmparser 0.45.2 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -5139,15 +4859,6 @@ dependencies = [ "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "wasmi" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "memory_units 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-wasm 0.31.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "wasmparser" version = "0.45.2" @@ -5309,7 +5020,6 @@ dependencies = [ "checksum arrayref 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "0d382e583f07208808f6b1249e60848879ba3543f57c32277bf52d69c2f0f0ee" "checksum arrayvec 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cff77d8686867eceff3105329d4698d96c2391c176d5d03adc90c7389162b5b8" "checksum ascii 0.8.7 (registry+https://github.com/rust-lang/crates.io-index)" = "97be891acc47ca214468e09425d02cef3af2c94d0d82081cd02061f996802f14" -"checksum assert_cmd 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b7ac5c260f75e4e4ba87b7342be6edcecbcb3eb6741a0507fda7ad115845cc65" "checksum atty 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)" = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" "checksum autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "1d49d90015b3c36167a20fe2810c5cd875ad504b39cff3d4eae7977e6b7c1cb2" "checksum autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" @@ -5329,6 +5039,7 @@ dependencies = [ "checksum block-padding 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" "checksum boolinator 2.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "cfa8873f51c92e232f9bac4065cddef41b714152812bfc5f7672ba16d6ef8cd9" "checksum bstr 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "502ae1441a0a5adb8fbd38a5955a6416b9493e92b465de5e4a9bde6a539c2c48" +"checksum byte-slice-cast 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "b0a5e3906bcbf133e33c1d4d95afc664ad37fbdb9f6568d8043e7ea8c27d93d3" "checksum byte-tools 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "560c32574a12a89ecd91f5e742165893f86e3ab98d21f8ea548658eb9eef5f40" "checksum byte-tools 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" "checksum byteorder 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a7c3dd8985a7111efc5c80b44e23ecdd8c007de8ade3b96595387e812b957cf5" @@ -5359,30 +5070,26 @@ dependencies = [ "checksum cranelift-native 0.52.0 (registry+https://github.com/rust-lang/crates.io-index)" = "21398a0bc6ba389ea86964ac4a495426dd61080f2ddd306184777a8560fe9976" "checksum crc32fast 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ba125de2af0df55319f41944744ad91c71113bf74a4646efff39afe1f6842db1" "checksum crossbeam-channel 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "0f0ed1a4de2235cabda8558ff5840bffb97fcb64c97827f354a451307df5f72b" -"checksum crossbeam-deque 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c3aa945d63861bfe624b55d153a39684da1e8c0bc8fba932f7ee3a3c16cea3ca" -"checksum crossbeam-epoch 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5064ebdbf05ce3cb95e45c8b086f72263f4166b29b97f6baff7ef7fe047b55ac" +"checksum crossbeam-deque 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)" = "9f02af974daeee82218205558e51ec8768b48cf524bd01d550abe5573a608285" +"checksum crossbeam-epoch 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)" = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" "checksum crossbeam-queue 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7c979cd6cfe72335896575c6b5688da489e420d36a27a0b9eb0c73db574b4a4b" "checksum crossbeam-queue 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c695eeca1e7173472a32221542ae469b3e9aac3a4fc81f7696bcad82029493db" "checksum crossbeam-utils 0.6.6 (registry+https://github.com/rust-lang/crates.io-index)" = "04973fa96e96579258a5091af6003abde64af786b860f18622b82e026cca60e6" -"checksum crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ce446db02cdc3165b94ae73111e570793400d0794e46125cc4056c81cbb039f4" +"checksum crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" "checksum crunchy 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" "checksum crypto-mac 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "0999b4ff4d3446d4ddb19a63e9e00c1876e75cd7000d20e57a693b4b3f08d958" "checksum crypto-mac 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4434400df11d95d556bac068ddfedd482915eb18fe8bea89bc80b6e4b1c179e5" "checksum csv 1.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "00affe7f6ab566df61b4be3ce8cf16bc2576bca0963ceb0955e45d514bf9a279" -"checksum csv-core 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "9b5cadb6b25c77aeff80ba701712494213f4a8418fcda2ee11b6560c3ad0bf4c" +"checksum csv-core 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" "checksum ctor 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "cd8ce37ad4184ab2ce004c33bf6379185d3b1c95801cab51026bd271bf68eedc" "checksum derive_more 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)" = "6d944ac6003ed268757ef1ee686753b57efc5fcf0ebe7b64c9fc81e7e32ff839" "checksum detach 0.0.19 (registry+https://github.com/rust-lang/crates.io-index)" = "891f5117f720f720924586e087b7eb385d816afb467a231c2fec64239de00986" "checksum detach 0.0.38 (registry+https://github.com/rust-lang/crates.io-index)" = "63222ce1fb32684cbb8b2035dbfd62fbc98faf134286d3be0c43e03ec327b11e" -"checksum deunicode 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "850878694b7933ca4c9569d30a34b55031b9b139ee1fc7b94a527c4ef960d690" "checksum difference 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "524cbf6897b527295dff137cec09ecf3a05f4fddffd7dfcd1585403449e74198" "checksum digest 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)" = "03b072242a8cbaf9c145665af9d250c59af3b958f83ed6824e13533cf76d5b90" "checksum digest 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" "checksum directories 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "72d337a64190607d4fcca2cb78982c5dd57f4916e19696b48a575fa746b6cb0f" "checksum dirs 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "3fd78930633bd1c6e35c4b42b1df7b0cbc6bc191146e512bb3bedf243fcc3901" -"checksum dirs 2.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "13aea89a5c93364a98e9b37b2fa237effbb694d5cfe01c5b70941f7eb087d5e3" -"checksum dirs-sys 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "afa0b23de8fd801745c471deffa6e12d248f962c9fd4b4c33787b055599bde7b" -"checksum dns-lookup 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "13988670860b076248c74e1b54444efc4f1dec70c8bb25da4b7c0024396b72bf" "checksum dtoa 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "4358a9e11b9a09cf52383b451b49a169e8d797b68aa02301ff586d70d9661ea3" "checksum either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" "checksum encode_unicode 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" @@ -5391,8 +5098,6 @@ dependencies = [ "checksum env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36" "checksum errno 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "c2a071601ed01b988f896ab14b95e67335d1eeb50190932a1320f7fe3cadc84e" "checksum errno-dragonfly 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "14ca354e36190500e1e1fb267c647932382b54053c50b14970856c0b00a35067" -"checksum error-chain 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3ab49e9dcb602294bc42f9a7dfc9bc6e936fca4418ea300dbfb84fe16de0b7d9" -"checksum escargot 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "19db1f7e74438642a5018cdf263bb1325b2e792f02dd0a3ca6d6c0f0d7b1d5a5" "checksum failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "795bd83d3abeb9220f257e597aa0080a508b27533824adf336529648f6abf7e2" "checksum failure_derive 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0bc225b78e0391e4b8683440bf2e63c2deeeb2ce5189eab46e2b68c6d3725d08" "checksum fake-simd 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" @@ -5438,7 +5143,7 @@ dependencies = [ "checksum hashbrown 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "3bae29b6653b3412c2e71e9d486db9f9df5d701941d86683005efb9f2d28e3da" "checksum hcid 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "9e5ea27f6b17df2ded5dcfc492ecd0db719d00b144dbaaf2df1658a7e38cfd2e" "checksum heck 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205" -"checksum hermit-abi 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "eff2656d88f158ce120947499e971d743c05dbcbed62e5bd2f38f1698bbc3772" +"checksum hermit-abi 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "e2c55f143919fbc0bc77e427fe2d74cf23786d7c1875666f2fde3ac3c659bb67" "checksum hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "805026a5d0141ffc30abb3be3173848ad46a1b1664fe632428479619a3644d77" "checksum hmac 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "44f3bdb08579d99d7dc761c0e266f13b5f2ab8c8c703b9fc9ef333cd8f48f55e" "checksum hmac 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5dcb5e64cda4c23119ab41ba960d1e170a774c8e4b9d9e6a9bc18aabf5e59695" @@ -5452,18 +5157,19 @@ dependencies = [ "checksum holochain_persistence_pickle 0.0.17 (registry+https://github.com/rust-lang/crates.io-index)" = "dd09d8cefe9229380445dc616b15077f6ffe94d1afd6082ffd7b51cb11e911cb" "checksum holochain_tracing 0.0.19 (registry+https://github.com/rust-lang/crates.io-index)" = "df4ee35cd41fc91a56aeb6268858148ae8b27459072d938c476cac39b5e4258b" "checksum holochain_tracing_macros 0.0.19 (registry+https://github.com/rust-lang/crates.io-index)" = "e2fb0dfa4bb2b392c10ef687641a22637580f23a8a493d9044cd31f6dcabc947" +"checksum holochain_wasmer_common 0.0.18 (registry+https://github.com/rust-lang/crates.io-index)" = "e5838f85be44a1449ecc20c83bf6e8591d5b86a794c0373951554e4a7ae4210a" +"checksum holochain_wasmer_guest 0.0.18 (registry+https://github.com/rust-lang/crates.io-index)" = "8de52621b7b7633a4a7b901575d65f2a9d89afa4f1809c80f022370ecbd27700" +"checksum holochain_wasmer_host 0.0.18 (registry+https://github.com/rust-lang/crates.io-index)" = "56544ccd3c2b896e067fd6bf81ef507151e2f8da88054dd4161afda9812ea3e6" "checksum hostname 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "21ceb46a83a85e824ef93669c8b390009623863b5c195d1ba747292c0c72f94e" "checksum http 0.1.21 (registry+https://github.com/rust-lang/crates.io-index)" = "d6ccf5ede3a895d8856620237b2f02972c1bbc78d2965ad7fe8838d4a0ed41f0" "checksum http_req 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "23fdb3445813f5f5e7fdb9d93df8f1c7e382237f2656b21c42e93e3a63e25c11" "checksum httparse 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "cd179ae861f0c2e53da70d892f5f3029f9594be0c41dc5269cd371691b1dc2f9" -"checksum humansize 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b6cab2627acfc432780848602f3f558f7e9dd427352224b0d9324025796d2a5e" "checksum humantime 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f" "checksum hyper 0.10.16 (registry+https://github.com/rust-lang/crates.io-index)" = "0a0652d9a2609a968c14be1a9ea00bf4b1d64e2e1f53a1b51b6fff3a6e829273" "checksum hyper 0.12.25 (registry+https://github.com/rust-lang/crates.io-index)" = "7d5b6658b016965ae301fa995306db965c93677880ea70765a84235a96eae896" "checksum hyper-tls 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "3a800d6aa50af4b5850b2b0f659625ce9504df908e9733b635720483be26174f" "checksum idna 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "38f09e0f0b1fb55fdee1f17470ad800da77af5186a1a76c026b679358b7e844e" "checksum idna 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "02e2673c30ee86b5b96a9cb52ad15718aa1f966f5ab9ad54a8b95d5ca33120a9" -"checksum ignore 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "ad03ca67dc12474ecd91fdb94d758cbd20cb4e7a78ebe831df26a9b7511e1162" "checksum im 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a1f9b6540e530defef7f2df4ed330d45b739b10450548c74a9913f63ea1acc6b" "checksum indexmap 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "076f042c5b7b98f31d205f1249267e12a6518c1481e9dae9764af19b707d2292" "checksum input_buffer 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8e1b822cc844905551931d6f81608ed5f50a79c1078a4e2b4d42dbc7c1eedfbf" @@ -5504,10 +5210,9 @@ dependencies = [ "checksum matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08" "checksum maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" "checksum md5 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "79c56d6a0b07f9e19282511c83fc5b086364cbae4ba8c7d5f190c3d9b0425a48" -"checksum memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3197e20c7edb283f87c071ddfc7a2cca8f8e0b888c242959846a6fce03c72223" +"checksum memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400" "checksum memmap 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6585fd95e7bb50d6cc31e20d4cf9afb4e2ba16c5846fc76793f11218da9c475b" "checksum memoffset 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "75189eb85871ea5c2e2c15abbdd541185f63b408415e5051f5cac122d8c774b9" -"checksum memory_units 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "71d96e3f3c0b6325d8ccd83c33b28acb183edcb6c67938ba104ec546854b0882" "checksum mime 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "ba626b8a6de5da682e1caa06bdb42a335aee5a84db8e5046a3e8ab17ba0a3ae0" "checksum mime 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)" = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" "checksum mime_guess 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1a0ed03949aef72dbdf3116a383d7b38b4768e6f960528cd6a6044aa9ed68599" @@ -5554,7 +5259,6 @@ dependencies = [ "checksum owning_ref 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "cdf84f41639e037b484f93433aa3897863b561ed65c6e59c7073d7c561710f37" "checksum owning_ref 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "49a4b8ea2179e6a2e27411d3bca09ca6dd630821cf6894c6c7c8467a8ee7ef13" "checksum page_size 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "eebde548fbbf1ea81a99b128872779c437752fb99f217c45245e1a61dcd9edcd" -"checksum parity-wasm 0.31.3 (registry+https://github.com/rust-lang/crates.io-index)" = "511379a8194230c2395d2f5fa627a5a7e108a9f976656ce723ae68fca4097bfc" "checksum parking_lot 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "92e98c49ab0b7ce5b222f2cc9193fc4efe11c6d0bd4f648e374684a6857b1cfc" "checksum parking_lot 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "149d8f5b97f3c1133e3cfcd8886449959e856b557ff281e292b733d7c69e005e" "checksum parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ab41b4aed082705d1056416ae4468b6ea99d52599ecf3169b00088d43113e337" @@ -5568,10 +5272,6 @@ dependencies = [ "checksum pbkdf2 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "006c038a43a45995a9670da19e67600114740e8511d4333bf97a56e66a7542d9" "checksum percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831" "checksum percent-encoding 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" -"checksum pest 2.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7e4fb201c5c22a55d8b24fef95f78be52738e5e1361129be1b5e862ecdb6894a" -"checksum pest_derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "833d1ae558dc601e9a60366421196a8d94bc0ac980476d0b67e1d0988d72b2d0" -"checksum pest_generator 2.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7b9fcf299b5712d06ee128a556c94709aaa04512c4dffb8ead07c5c998447fc0" -"checksum pest_meta 2.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "df43fd99896fd72c485fe47542c7b500e4ac1e8700bf995544d1317a60ded547" "checksum petgraph 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)" = "9c3659d1ee90221741f65dd128d9998311b0e40c5d3c23a62445938214abce4f" "checksum pickledb 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f84c239b2c2dc17025deda2d513de8218f1afd9ec7c34de45797ab35cf97d8a0" "checksum pin-project-lite 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "237844750cfbb86f67afe27eee600dfbbcb6188d734139b534cbfbf4f96792ae" @@ -5582,7 +5282,6 @@ dependencies = [ "checksum ppv-lite86 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "74490b50b9fbe561ac330df47c08f3f33073d2d00c150f719147d7c54522fa1b" "checksum predicates 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "53e09015b0d3f5a0ec2d4428f7559bb7b3fff341b4e159fedd1d57fac8b939ff" "checksum predicates-core 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "06075c3a3e92559ff8929e7a280684489ea27fe44805174c3ebd9328dcb37178" -"checksum predicates-tree 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8e63c4859013b38a76eca2414c64911fba30def9e3202ac461a2d22831220124" "checksum pretty_assertions 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3f81e1644e1b54f5a68959a29aa86cde704219254669da328ecfdf6a1f09d427" "checksum prettytable-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0fd04b170004fa2daccf418a7f8253aaf033c27760b5f225889024cf66d7ac2e" "checksum proc-macro-error 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "aeccfe4d5d8ea175d5f0e4a2ad0637e0f4121d63bd99d356fb1f39ab2e7c6097" @@ -5644,13 +5343,11 @@ dependencies = [ "checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" "checksum rustracing 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1033dbbcfe140c3f3bec3b5e2165e11583a1eb0bc08056faaeb2b3bfaa753ddc" "checksum rustracing_jaeger 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5840ca7d3fb57a07e79f7cfe0393f5cd9491cefd6fe38db3dc085dcc5585ea17" -"checksum rustyline 5.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "67e12e40e0240de07f0dab4f4dd01bdb15d74dc977026d4ba91666c41c679ade" "checksum ryu 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "bfa8506c1de11c9c4e4c38863ccbe02a305c8188e85a05a784c9e11e1c3910c8" "checksum safemem 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ef703b7cb59335eae2eb93ceb664c0eb7ea6bf567079d843e09420219668e072" -"checksum same-file 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" "checksum schannel 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)" = "507a9e6e8ffe0a4e0ebb9a10293e62fdf7657c06f1b8bb07a8fcf697d2abf295" "checksum scopeguard 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "94258f53601af11e6a49f722422f6e3425c52b06245a5cf9bc09908b174f5e27" -"checksum scopeguard 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b42e15e59b18a828bbf5c58ea01debb36b9b096346de35d941dcb89009f24a0d" +"checksum scopeguard 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" "checksum security-framework 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "8ef2429d7cefe5fd28bd1d2ed41c944547d4ff84776f5935b456da44593a16df" "checksum security-framework-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e31493fc37615debb8c5090a7aeb4a9730bc61e77ab10b9af59f1a202284f895" "checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" @@ -5678,7 +5375,6 @@ dependencies = [ "checksum signal-hook-registry 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "94f478ede9f64724c5d173d7bb56099ec3e2d9fc2774aac65d34b8b890405f41" "checksum sized-chunks 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "6f59f81ec9833a580d2448e958d16bd872637798f3ab300b693c48f136fb76ff" "checksum slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" -"checksum slug 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "b3bc762e6a4b6c6fcaade73e77f9ebc6991b676f88bb2358bddb56560f073373" "checksum smallvec 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "f7b0758c52e15a8b5e3691eae6cc559f08eee9406e548a4477ba4e67770a82b6" "checksum smallvec 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5c2fb2ec9bcd216a5b0d0ccf31ab17b5ed1d627960edff65bbe95d3ce221cefc" "checksum snowflake 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "27207bb65232eda1f588cf46db2fee75c0808d557f6b3cf19a75f5d6d7c94df1" @@ -5695,19 +5391,18 @@ dependencies = [ "checksum subtle 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2d67a5a62ba6e01cb2192ff309324cb4875d0c451d55fe2319433abe7a05a8ee" "checksum syn 0.12.15 (registry+https://github.com/rust-lang/crates.io-index)" = "c97c05b8ebc34ddd6b967994d5c6e9852fa92f8b82b3858c39451f97346dcce5" "checksum syn 0.15.31 (registry+https://github.com/rust-lang/crates.io-index)" = "d2b4cfac95805274c6afdb12d8f770fa2d27c045953e7b630a81801953699a9a" -"checksum syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)" = "af6f3550d8dff9ef7dc34d384ac6f107e5d31c8f57d9f28e0081503f547ac8f5" +"checksum syn 1.0.15 (registry+https://github.com/rust-lang/crates.io-index)" = "7a0294dc449adc58bb6592fff1a23d3e5e6e235afc6a0ffca2657d19e7bbffe5" "checksum synstructure 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)" = "02353edf96d6e4dc81aea2d8490a7e9db177bf8acb0e951c24940bf866cb313f" "checksum synstructure 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)" = "67656ea1dc1b41b1451851562ea232ec2e5a80242139f7e679ceccfb5d61f545" "checksum take_mut 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f764005d11ee5f36500a149ace24e00e3da98b0158b3e2d53a7495660d3f4d60" "checksum tar 0.4.26 (registry+https://github.com/rust-lang/crates.io-index)" = "b3196bfbffbba3e57481b6ea32249fbaf590396a52505a2615adbb79d9d826d3" "checksum target-lexicon 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6f4c118a7a38378f305a9e111fcb2f7f838c0be324bfb31a77ea04f7f6e684b4" "checksum tempfile 3.0.7 (registry+https://github.com/rust-lang/crates.io-index)" = "b86c784c88d98c801132806dadd3819ed29d8600836c4088e855cdf3e178ed8a" -"checksum tera 0.11.20 (registry+https://github.com/rust-lang/crates.io-index)" = "4b505279e19d8f7d24b1a9dc58327c9c36174b1a2c7ebdeac70792d017cb64f3" "checksum term 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "edd106a334b7657c10b7c540a0106114feadeb4dc314513e97df481d5d966f42" "checksum termcolor 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bb6bfa289a4d7c5766392812c0a1f4c1ba45afa1ad47803c11e1f407d846d75f" "checksum textwrap 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" -"checksum thiserror 1.0.10 (registry+https://github.com/rust-lang/crates.io-index)" = "205684fd018ca14432b12cce6ea3d46763311a571c3d294e71ba3f01adcf1aad" -"checksum thiserror-impl 1.0.10 (registry+https://github.com/rust-lang/crates.io-index)" = "57e4d2e50ca050ed44fb58309bdce3efa79948f84f9993ad1978de5eebdce5a7" +"checksum thiserror 1.0.11 (registry+https://github.com/rust-lang/crates.io-index)" = "ee14bf8e6767ab4c687c9e8bc003879e042a96fd67a3ba5934eadb6536bef4db" +"checksum thiserror-impl 1.0.11 (registry+https://github.com/rust-lang/crates.io-index)" = "a7b51e1fbc44b5a0840be594fbc0f960be09050f2617e61e6aa43bef97cd3ef4" "checksum thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b" "checksum threadpool 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "e2f0c90a5f3459330ac8bc0d2f879c693bb7a2f59689c1083fc4ef83834da865" "checksum thrift_codec 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8fb61fb3d0a0af14949f3a6949b2639112e13226647112824f4d081533f9b1a8" @@ -5736,19 +5431,11 @@ dependencies = [ "checksum trackable_derive 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "edcf0b9b2caa5f4804ef77aeee1b929629853d806117c48258f402b69737e65c" "checksum traitobject 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "efd1f82c56340fdf16f2a953d7bda4f8fdffba13d93b00844c25572110b26079" "checksum treediff 3.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "761e8d5ad7ce14bb82b7e61ccc0ca961005a275a060b9644a2431aa11553c2ff" -"checksum treeline 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a7f741b240f1a48843f9b8e0444fb55fb2a4ff67293b50a9179dfd5ea67f8d41" "checksum try-lock 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e604eb7b43c06650e854be16a2a03155743d3752dd1c943f6829e26b7a36e382" "checksum tungstenite 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)" = "8a0c2bd5aeb7dcd2bb32e472c8872759308495e5eccc942e929a513cd8d36110" "checksum typeable 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1410f6f91f21d1612654e7cc69193b0334f909dcf2c790c4826254fbb86f8887" "checksum typemap 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "653be63c80a3296da5551e1bfd2cca35227e13cdd08c6668903ae2f4f77aa1f6" "checksum typenum 1.11.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6d2783fe2d6b8c1101136184eb41be8b1ad379e4657050b8aaff0c79ee7575f9" -"checksum ucd-trie 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "8f00ed7be0c1ff1e24f46c3d2af4859f7e863672ba3a6e92e7cff702bf9f06c2" -"checksum unic-char-property 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ce36d3f7ce754afdbccccf8ff0dd0134e50fb44aaae579f96218856e9e5dbd1e" -"checksum unic-char-range 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d9ab85fab42ad1b26cafc03bf891f69cb4d6e15f491030e89a0122197baa8ae8" -"checksum unic-common 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ff8d4a7ade929ef7d971e16ced21a8cd56a63869aa6032dfb8cb083cf7d077bf" -"checksum unic-segment 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c9ca47cbb09fb5fcd066b5867d11dc528302fa465277882797d6a836e1ee6f9e" -"checksum unic-ucd-segment 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "48f1a08ce0409a9e391b88d1930118eec48af12742fc538bcec55f775865776e" -"checksum unic-ucd-version 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1f5e6c6c53c2d0ece4a5964bc55fcff8602153063cb4fab20958ff32998ff6" "checksum unicase 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7f4765f83163b74f957c797ad9253caf97f103fb064d3999aea9568d09fc8a33" "checksum unicase 2.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" "checksum unicode-bidi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "49f2bd0c6468a8230e1db229cff8029217cf623c767ea5d60bfbd42729ea54d5" @@ -5777,7 +5464,6 @@ dependencies = [ "checksum vte 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "4f42f536e22f7fcbb407639765c8fd78707a33109301f834a594758bedd6e8cf" "checksum wabt 0.7.4 (registry+https://github.com/rust-lang/crates.io-index)" = "74e463a508e390cc7447e70f640fbf44ad52e1bd095314ace1fdf99516d32add" "checksum wabt-sys 0.5.4 (registry+https://github.com/rust-lang/crates.io-index)" = "a6265b25719e82598d104b3717375e37661d41753e2c84cde3f51050c7ed7e3c" -"checksum walkdir 2.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "777182bc735b6424e1a57516d35ed72cb8019d85c8c9bf536dccb3445c1a2f7d" "checksum want 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "797464475f30ddb8830cc529aaaae648d581f99e2036a928877dfde027ddf6b3" "checksum wasi 0.9.0+wasi-snapshot-preview1 (registry+https://github.com/rust-lang/crates.io-index)" = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" "checksum wasm-bindgen 0.2.32 (registry+https://github.com/rust-lang/crates.io-index)" = "710152b9cc4b688f91a23ad1574d0f3d6334ccb883896f6886531dc536944330" @@ -5791,7 +5477,6 @@ dependencies = [ "checksum wasmer-runtime 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05726a0bc546d57e06cde6a7754cf9afbf21a5869d080a3c654d35902cd6fab3" "checksum wasmer-runtime-core 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7b1131f1bb9a0610eeef2974275de019027fa8dcfac78a9976439ce5f4561ade" "checksum wasmer-win-exception-handler 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)" = "eac6af8ef69d582a851bb116be4faebc42d1f52ef00922e1688f3eff48d0d96b" -"checksum wasmi 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "f6a891b45c79e9f96fb66cc84a057211ef9cd2e5e8d093f3dbbd480e146a8758" "checksum wasmparser 0.45.2 (registry+https://github.com/rust-lang/crates.io-index)" = "8b4eab1d9971d0803729cba3617b56eb04fcb4bd25361cb63880ed41a42f20d5" "checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" "checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" diff --git a/Cargo.toml b/Cargo.toml index cc50d8b56c..acd0846514 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,8 @@ [workspace] members = [ - "crates/cli", + # @TODO make cli work with wasmer + # "crates/cli", "crates/metrics", "crates/common", "crates/holochain", @@ -20,7 +21,7 @@ members = [ "crates/trycp_server", "crates/sim2h", "crates/sim2h_server", - "crates/wasm_utils" + "crates/wasm_types", ] exclude = [ "test_utils", diff --git a/Makefile b/Makefile index b2c111787d..ccb0c22b49 100644 --- a/Makefile +++ b/Makefile @@ -147,7 +147,7 @@ test_holochain: build_holochain cd crates/hdk_v2 && RUSTFLAGS="-D warnings" $(CARGO) test --all --exclude hc cd crates/holochain && RUSTFLAGS="-D warnings" $(CARGO) test --all --exclude hc cd crates/net && RUSTFLAGS="-D warnings" $(CARGO) test --all --exclude hc - cd crates/wasm_utils && RUSTFLAGS="-D warnings" $(CARGO) test --all --exclude hc + cd crates/wasm_engine && RUSTFLAGS="-D warnings" $(CARGO) test --all --exclude hc # Execute cargo tests matching % # Eg. make test-stacked will run "cargo test stacked" @@ -185,7 +185,7 @@ wasm_build: ensure_wasm_target cd crates/conductor_lib/wasm-test && $(CARGO) build --release --target wasm32-unknown-unknown cd crates/conductor_lib/test-bridge-caller && $(CARGO) build --release --target wasm32-unknown-unknown cd crates/hdk/wasm-test && $(CARGO) build --release --target wasm32-unknown-unknown - cd crates/wasm_utils/wasm-test/integration-test && $(CARGO) build --release --target wasm32-unknown-unknown + cd crates/wasm_engine/wasm-test/integration-test && $(CARGO) build --release --target wasm32-unknown-unknown .PHONY: install_wasm_bindgen_cli install_wasm_bindgen_cli: @@ -207,7 +207,7 @@ build_holochain: wasm_build cd crates/hdk_v2 && $(CARGO) build cd crates/holochain && $(CARGO) build cd crates/net && $(CARGO) build - cd crates/wasm_utils && $(CARGO) build + cd crates/wasm_engine && $(CARGO) build .PHONY: build_cli build_cli: core_toolchain ensure_wasm_target diff --git a/app_spec/zomes/blog/code/src/lib.rs b/app_spec/zomes/blog/code/src/lib.rs index 532db44d96..a15e3c3106 100755 --- a/app_spec/zomes/blog/code/src/lib.rs +++ b/app_spec/zomes/blog/code/src/lib.rs @@ -1,7 +1,7 @@ use hdk::prelude::*; use hdk::{ holochain_core_types::{signature::Provenance}, - holochain_wasm_utils::api_serialization::{ + holochain_wasm_types::{ get_entry::{EntryHistory, GetEntryResult}, get_links::GetLinksResult, }, diff --git a/app_spec/zomes/blog/code/src/post.rs b/app_spec/zomes/blog/code/src/post.rs index 70f4f026c6..5370c23c37 100644 --- a/app_spec/zomes/blog/code/src/post.rs +++ b/app_spec/zomes/blog/code/src/post.rs @@ -122,7 +122,7 @@ mod tests { validation::{EntryLifecycle, EntryValidationData, ValidationData, ValidationPackage}, }, holochain_json_api::json::JsonString, - holochain_wasm_utils::api_serialization::validation::LinkDirection, + holochain_wasm_types::validation::LinkDirection, }; use std::convert::TryInto; diff --git a/app_spec/zomes/converse/code/src/lib.rs b/app_spec/zomes/converse/code/src/lib.rs index 2228ddf1ae..2f43e00cdf 100755 --- a/app_spec/zomes/converse/code/src/lib.rs +++ b/app_spec/zomes/converse/code/src/lib.rs @@ -3,7 +3,7 @@ use hdk::{ holochain_core_types::{ signature::{Provenance, Signature}, }, - holochain_wasm_utils::api_serialization::keystore::KeyType, + holochain_wasm_types::keystore::KeyType, }; pub fn handle_sign_message(key_id: String, message: String) -> ZomeApiResult { diff --git a/app_spec_proc_macro/zomes/blog/code/src/lib.rs b/app_spec_proc_macro/zomes/blog/code/src/lib.rs index aa43d3ef66..0c1e902349 100755 --- a/app_spec_proc_macro/zomes/blog/code/src/lib.rs +++ b/app_spec_proc_macro/zomes/blog/code/src/lib.rs @@ -2,7 +2,7 @@ use hdk::prelude::*; use hdk::{ holochain_core_types::{signature::Provenance}, - holochain_wasm_utils::api_serialization::{ + holochain_wasm_types::{ get_entry::{EntryHistory, GetEntryResult}, get_links::GetLinksResult, }, diff --git a/app_spec_proc_macro/zomes/blog/code/src/post.rs b/app_spec_proc_macro/zomes/blog/code/src/post.rs index f5cfbd57af..ba243f4cd6 100644 --- a/app_spec_proc_macro/zomes/blog/code/src/post.rs +++ b/app_spec_proc_macro/zomes/blog/code/src/post.rs @@ -121,7 +121,7 @@ mod tests { validation::{EntryLifecycle, EntryValidationData, ValidationData, ValidationPackage}, }, holochain_json_api::json::JsonString, - holochain_wasm_utils::api_serialization::validation::LinkDirection, + holochain_wasm_types::validation::LinkDirection, }; use std::convert::TryInto; diff --git a/app_spec_proc_macro/zomes/converse/code/src/lib.rs b/app_spec_proc_macro/zomes/converse/code/src/lib.rs index 78a6ce7878..d9437adc1c 100755 --- a/app_spec_proc_macro/zomes/converse/code/src/lib.rs +++ b/app_spec_proc_macro/zomes/converse/code/src/lib.rs @@ -7,7 +7,7 @@ use hdk::{ holochain_core_types::{ signature::{Provenance, Signature}, }, - holochain_wasm_utils::api_serialization::keystore::KeyType, + holochain_wasm_types::keystore::KeyType, }; #[zome] diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 8164fbf259..12abf0bd29 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -15,6 +15,7 @@ holochain_conductor_lib = { version = "=0.0.43-alpha3", path = "../conductor_lib holochain_net = { version = "=0.0.43-alpha3", path = "../net" } holochain_dpki = { version = "=0.0.43-alpha3", path = "../dpki" } holochain_locksmith = { version = "=0.0.43-alpha3", path = "../locksmith" } +holochain_wasmer_host = "=0.0.18" holochain_tracing = "=0.0.19" holochain_tracing_macros = "=0.0.19" newrelic="0.2" @@ -26,7 +27,6 @@ lib3h_sodium = "=0.0.38" holochain_json_api = "=0.0.23" holochain_persistence_api = "=0.0.17" holochain_persistence_file = "=0.0.17" -holochain_wasm_utils = { path = "../wasm_utils" } crossbeam-channel = "=0.3.8" structopt = "=0.3.3" failure = "=0.1.5" diff --git a/crates/cli/src/cli/init.rs b/crates/cli/src/cli/init.rs index 497f0fd618..a6964e4188 100644 --- a/crates/cli/src/cli/init.rs +++ b/crates/cli/src/cli/init.rs @@ -6,7 +6,7 @@ use crate::{ config_files::App as AppConfig, error::DefaultResult, util::DIST_DIR_NAME, - NEW_RELIC_LICENSE_KEY, + }; use colored::*; use serde_json; diff --git a/crates/cli/src/cli/package.rs b/crates/cli/src/cli/package.rs index 7d44cb2326..9f0b49ad6c 100644 --- a/crates/cli/src/cli/package.rs +++ b/crates/cli/src/cli/package.rs @@ -1,8 +1,9 @@ use crate::{config_files::Build, error::DefaultResult, util, NEW_RELIC_LICENSE_KEY}; use base64; use colored::*; -use holochain_core::wasm_engine::{run_dna, WasmCallData}; +use holochain_core::wasm_engine::{WasmCallData}; use holochain_core_types::dna::Dna; +use holochain_core_types::error::HolochainError; use holochain_json_api::json::JsonString; use holochain_persistence_api::cas::content::AddressableContent; use ignore::WalkBuilder; @@ -15,7 +16,7 @@ use std::{ path::PathBuf, sync::Arc, }; - +use holochain_core_types::dna::zome::PartialZome; use holochain_core_types::hdk_version::{HDKVersion, HDK_VERSION}; pub const BUILD_CONFIG_FILE_NAME: &str = ".hcbuild"; @@ -188,21 +189,24 @@ impl Packager { let wasm = build.run(&dir_with_code)?; let wasm_binary = Arc::new(base64::decode(&wasm)?); - let json_string = run_dna( - Some("{}".as_bytes().to_vec()), - WasmCallData::DirectCall( - "__hdk_get_json_definition".to_string(), - wasm_binary.clone(), - ), - )?; + let call_data = WasmCallData::DirectCall( + "__hdk_get_json_definition".to_string(), + wasm_binary.clone(), + ); - let json_from_wasm: Map = - serde_json::from_str(&String::from(json_string))?; + let partial_zome: PartialZome = match holochain_wasmer_host::guest::call( + &mut call_data.instance()?, + &call_data.fn_name(), + (), + ) { + Ok(v) => v, + Err(e) => return Err(HolochainError::Wasm(e))?, + }; let mut sub_tree_content = self.bundle_recurse(&node)?; - for key in json_from_wasm.keys() { + for key in partial_zome.keys() { sub_tree_content - .insert(key.clone(), json_from_wasm.get(key).unwrap().clone()); + .insert(key.clone(), partial_zome.get(key).unwrap().clone()); } // here insert json generated by the wasm, alongside the rest of the sub-tree diff --git a/crates/cli/src/cli/scaffold/rust-proc-macro/Cargo.template.toml b/crates/cli/src/cli/scaffold/rust-proc-macro/Cargo.template.toml index 139b018188..42b404ffb2 100644 --- a/crates/cli/src/cli/scaffold/rust-proc-macro/Cargo.template.toml +++ b/crates/cli/src/cli/scaffold/rust-proc-macro/Cargo.template.toml @@ -10,7 +10,7 @@ serde_json = { version = "=1.0.47", features = ["preserve_order"] } serde_derive = "=1.0.104" hdk = <> hdk_proc_macros = <> -holochain_wasm_utils = <> +holochain_wasm_engine = <> holochain_json_derive = "=0.0.20" [lib] diff --git a/crates/cli/src/cli/scaffold/rust/Cargo.template.toml b/crates/cli/src/cli/scaffold/rust/Cargo.template.toml index 22cf4b5b1d..9b44731b98 100644 --- a/crates/cli/src/cli/scaffold/rust/Cargo.template.toml +++ b/crates/cli/src/cli/scaffold/rust/Cargo.template.toml @@ -9,7 +9,7 @@ serde = "=1.0.104" serde_json = { version = "=1.0.47", features = ["preserve_order"] } serde_derive = "=1.0.104" hdk = <> -holochain_wasm_utils = <> +holochain_wasm_engine = <> holochain_json_derive = "=0.0.20" [lib] diff --git a/crates/conductor_api/Cargo.toml b/crates/conductor_api/Cargo.toml index 1f239ff665..c171530c4e 100644 --- a/crates/conductor_api/Cargo.toml +++ b/crates/conductor_api/Cargo.toml @@ -10,7 +10,7 @@ edition = "2018" [dependencies] holochain_core_types = { version = "=0.0.43-alpha3", path = "../core_types" } -holochain_wasm_utils = { version = "=0.0.43-alpha3", path = "../wasm_utils" } +holochain_wasm_types = { version = "=0.0.43-alpha3", path = "../wasm_types" } holochain_locksmith = { version = "=0.0.43-alpha3", path = "../locksmith" } holochain_tracing_macros = "=0.0.19" holochain_common = { version = "=0.0.43-alpha3", path = "../common" } diff --git a/crates/conductor_api/src/conductor_api.rs b/crates/conductor_api/src/conductor_api.rs index 00b7a1d04b..4ee9e12535 100644 --- a/crates/conductor_api/src/conductor_api.rs +++ b/crates/conductor_api/src/conductor_api.rs @@ -1,7 +1,7 @@ use crate::NEW_RELIC_LICENSE_KEY; use holochain_core_types::error::HolochainError; use holochain_locksmith::RwLock; -use holochain_wasm_utils::api_serialization::crypto::CryptoMethod; +use holochain_wasm_types::crypto::CryptoMethod; use jsonrpc_core::IoHandler; use jsonrpc_lite::JsonRpc; use serde_json::json; diff --git a/crates/conductor_api/src/lib.rs b/crates/conductor_api/src/lib.rs index 913c8d336e..5422ac0506 100644 --- a/crates/conductor_api/src/lib.rs +++ b/crates/conductor_api/src/lib.rs @@ -3,6 +3,6 @@ extern crate holochain_common; pub mod conductor_api; pub use conductor_api::ConductorApi; -pub use holochain_wasm_utils::api_serialization::crypto::CryptoMethod; +pub use holochain_wasm_types::crypto::CryptoMethod; new_relic_setup!("NEW_RELIC_LICENSE_KEY"); diff --git a/crates/conductor_lib/Cargo.toml b/crates/conductor_lib/Cargo.toml index 1a13bdbd3d..37624395ae 100644 --- a/crates/conductor_lib/Cargo.toml +++ b/crates/conductor_lib/Cargo.toml @@ -11,6 +11,7 @@ edition = "2018" [dependencies] holochain_core = { version = "=0.0.43-alpha3", path = "../core" } holochain_core_types = { version = "=0.0.43-alpha3", path = "../core_types" } +holochain_wasm_types = { version = "=0.0.43-alpha3", path = "../wasm_types" } holochain_locksmith = { version = "=0.0.43-alpha3", path = "../locksmith" } holochain_json_derive = "=0.0.23" holochain_json_api = "=0.0.23" @@ -59,7 +60,6 @@ newrelic="0.2" [dev-dependencies] test_utils = { version = "=0.0.43-alpha3", path = "../../test_utils" } tempfile = "=3.0.7" -holochain_wasm_utils = { version = "=0.0.43-alpha3", path = "../wasm_utils" } structopt = "=0.2.15" pretty_assertions = "=0.6.1" ws = "=0.8.0" diff --git a/crates/conductor_lib/src/conductor/base.rs b/crates/conductor_lib/src/conductor/base.rs index 74204e60e9..2d9470bf1a 100644 --- a/crates/conductor_lib/src/conductor/base.rs +++ b/crates/conductor_lib/src/conductor/base.rs @@ -10,7 +10,7 @@ use crate::{ key_loaders::test_keystore, keystore::{Keystore, PRIMARY_KEYBUNDLE_ID}, port_utils::{try_with_port, INTERFACE_CONNECT_ATTEMPTS_MAX}, - Holochain, NEW_RELIC_LICENSE_KEY, + Holochain, }; use crossbeam_channel::{unbounded, Receiver, Sender}; use holochain_common::paths::DNA_EXTENSION; @@ -53,6 +53,7 @@ use crate::{ signal_wrapper::SignalWrapper, static_file_server::ConductorStaticFileServer, static_server_impls::NickelStaticServer as StaticServer, + NEW_RELIC_LICENSE_KEY, }; use boolinator::Boolinator; use holochain_core::context::InstanceStats; @@ -1572,7 +1573,7 @@ pub mod tests { use holochain_core_types::dna; use holochain_dpki::{key_bundle::KeyBundle, password_encryption::PwHashConfig, SEED_SIZE}; use holochain_persistence_api::cas::content::Address; - use holochain_wasm_utils::wasm_target_dir; + use holochain_core::wasm_engine::io::wasm_target_dir; use lib3h_sodium::secbuf::SecBuf; use std::{ fs::{File, OpenOptions}, diff --git a/crates/conductor_lib/src/holochain.rs b/crates/conductor_lib/src/holochain.rs index ca787dcf49..6219a58708 100644 --- a/crates/conductor_lib/src/holochain.rs +++ b/crates/conductor_lib/src/holochain.rs @@ -100,13 +100,13 @@ use holochain_core::{ instance::Instance, nucleus::{call_zome_function, ZomeFnCall}, persister::{Persister, SimplePersister}, - wasm_engine::{run_dna, WasmCallData}, + wasm_engine::{WasmCallData}, }; use holochain_core_types::{ dna::{capabilities::CapabilityRequest, Dna}, error::HolochainError, }; - +use holochain_wasm_types::wasm_string::WasmString; use holochain_json_api::json::JsonString; use holochain_core::{ @@ -116,7 +116,6 @@ use holochain_core::{ use holochain_persistence_api::cas::content::Address; use jsonrpc_core::IoHandler; use std::sync::Arc; - use holochain_metrics::with_latency_publishing; /// contains a Holochain application instance @@ -134,22 +133,26 @@ impl Holochain { let instance = Instance::new(context.clone()); for zome in dna.zomes.values() { - let maybe_json_string = run_dna( - Some("{}".as_bytes().to_vec()), - WasmCallData::DirectCall("__hdk_hdk_version".to_string(), zome.code.code.clone()), - ); - - if let Ok(json_string) = maybe_json_string { - if json_string.to_string() - != holochain_core_types::hdk_version::HDK_VERSION.to_string() - { - eprintln!("WARNING! The HDK Version of the runtime and the zome don't match."); - eprintln!( - "Runtime HDK Version: {}", - holochain_core_types::hdk_version::HDK_VERSION.to_string() - ); - eprintln!("Zome HDK Version: {}", json_string); - } + let call_data = WasmCallData::DirectCall("__hdk_hdk_version".to_string(), zome.code.code.clone()); + + let hdk_version: WasmString = match holochain_core::wasm_engine::guest::call( + &mut call_data.instance()?, + &call_data.fn_name(), + (), + ) { + Ok(v) => v, + Err(e) => return Err(HolochainInstanceError::InternalFailure(HolochainError::Wasm(e))), + }; + + if hdk_version.to_string() + != holochain_core_types::hdk_version::HDK_VERSION.to_string() + { + eprintln!("WARNING! The HDK Version of the runtime and the zome don't match."); + eprintln!( + "Runtime HDK Version: {}", + holochain_core_types::hdk_version::HDK_VERSION.to_string() + ); + eprintln!("Zome HDK Version: {}", hdk_version.to_string()); } } @@ -247,7 +250,7 @@ impl Holochain { params: &str, ) -> HolochainResult { let zome_call = ZomeFnCall::new(&zome, cap, &fn_name, JsonString::from_json(¶ms)); - Ok(context.block_on(call_zome_function(zome_call, context.clone()))?) + Ok(context.block_on(call_zome_function(Arc::clone(&context), zome_call))?) } /// call a function in a zome @@ -329,7 +332,7 @@ mod tests { use holochain_json_api::json::RawString; use holochain_locksmith::Mutex; use holochain_persistence_api::cas::content::{Address, AddressableContent}; - use holochain_wasm_utils::wasm_target_dir; + use holochain_core::wasm_engine::io::wasm_target_dir; use std::{path::PathBuf, sync::Arc}; use tempfile; use test_utils::{ diff --git a/crates/conductor_lib/test-bridge-caller/Cargo.toml b/crates/conductor_lib/test-bridge-caller/Cargo.toml index e4e2f0f897..a4b9637fa2 100644 --- a/crates/conductor_lib/test-bridge-caller/Cargo.toml +++ b/crates/conductor_lib/test-bridge-caller/Cargo.toml @@ -19,3 +19,4 @@ hdk = { path = "../../hdk" } serde_derive = "=1.0.104" holochain_json_derive = "=0.0.23" holochain_persistence_api = "=0.0.17" +holochain_wasmer_guest = "=0.0.18" diff --git a/crates/conductor_lib/test-bridge-caller/src/lib.rs b/crates/conductor_lib/test-bridge-caller/src/lib.rs index 27ab858bf6..0ac702fbf0 100755 --- a/crates/conductor_lib/test-bridge-caller/src/lib.rs +++ b/crates/conductor_lib/test-bridge-caller/src/lib.rs @@ -1,48 +1,36 @@ -#[macro_use] extern crate hdk; -extern crate serde; -#[macro_use] -extern crate serde_derive; -extern crate serde_json; - -use hdk::holochain_persistence_api::{ - cas::content::Address, -}; - -use hdk::holochain_json_api::{ - json::JsonString, - error::JsonError -}; - -fn handle_call_bridge() -> JsonString { - hdk::call("test-callee", "greeter", Address::from("token"), "hello", JsonString::empty_object()).unwrap() + +use hdk::prelude::*; + +fn handle_call_bridge() -> ZomeApiResult { + Ok(hdk::call("test-callee", "greeter", Address::from("token"), "hello", JsonString::empty_object())?) } -fn handle_call_bridge_error() -> JsonString { - hdk::call("test-callee", "greeter", Address::from("token"), "non-existent-function", JsonString::empty_object()).into() +fn handle_call_bridge_error() -> ZomeApiResult { + Ok(hdk::call("test-callee", "greeter", Address::from("token"), "non-existent-function", JsonString::empty_object())?) } define_zome! { entries: [] init: || { - Ok(()) + CallbackResult::Pass } validate_agent: |validation_data : EntryValidationData::| { - Ok(()) + ValidationResult::Ok } functions: [ call_bridge: { inputs: | |, - outputs: |result: JsonString|, + outputs: |result: ZomeApiResult|, handler: handle_call_bridge } call_bridge_error: { inputs: | |, - outputs: |result: JsonString|, + outputs: |result: ZomeApiResult|, handler: handle_call_bridge_error } ] diff --git a/crates/conductor_lib/wasm-test/Cargo.toml b/crates/conductor_lib/wasm-test/Cargo.toml index 6265999173..f886ca4eb5 100644 --- a/crates/conductor_lib/wasm-test/Cargo.toml +++ b/crates/conductor_lib/wasm-test/Cargo.toml @@ -16,6 +16,8 @@ members = [] serde = "=1.0.104" serde_derive = "=1.0.104" serde_json = { version = "=1.0.47", features = ["preserve_order"] } -holochain_wasm_utils = { path = "../../wasm_utils" } +holochain_wasm_types = { path = "../../wasm_types" } holochain_core_types = { path = "../../core_types" } holochain_json_derive = "=0.0.23" +holochain_wasmer_guest = "=0.0.18" +holochain_persistence_api = "=0.0.17" diff --git a/crates/conductor_lib/wasm-test/src/lib.rs b/crates/conductor_lib/wasm-test/src/lib.rs index 32f8054711..7dc68d8f6b 100644 --- a/crates/conductor_lib/wasm-test/src/lib.rs +++ b/crates/conductor_lib/wasm-test/src/lib.rs @@ -3,27 +3,26 @@ extern crate holochain_core_types; extern crate holochain_json_derive; #[macro_use] extern crate serde_derive; -extern crate holochain_wasm_utils; +extern crate holochain_wasm_types; extern crate serde_json; +extern crate holochain_wasmer_guest; +extern crate holochain_persistence_api; use holochain_core_types::{ entry::Entry, error::{ - RibosomeEncodedValue, RibosomeEncodingBits, RibosomeRuntimeBits, ZomeApiInternalResult, }, - signature::Provenance + signature::Provenance, + validation::{ValidationPackageDefinition, ValidationResult}, }; -use holochain_wasm_utils::{ - holochain_persistence_api::cas::content::Address, +use holochain_persistence_api::cas::content::Address; +use holochain_wasm_types::{ holochain_json_api::{error::JsonError, json::{JsonString, RawString}}, }; +use holochain_wasmer_guest::*; -use holochain_wasm_utils::memory::{ - ribosome::{load_ribosome_encoded_json, return_code_for_allocation_result}, - stack::WasmStack, -}; use std::convert::TryInto; //------------------------------------------------------------------------------------------------- @@ -31,23 +30,7 @@ use std::convert::TryInto; //------------------------------------------------------------------------------------------------- extern "C" { - fn hc_debug(encoded_allocation_of_input: RibosomeEncodingBits) -> RibosomeEncodingBits; -} - -/// Call HC API DEBUG function with proper input struct: a string -/// return error code -fn hdk_debug(mem_stack: &mut WasmStack, json_string: &JsonString) { - // Write input string on stack - let allocation = match mem_stack.write_json(json_string.to_owned()) { - Ok(allocation) => allocation, - Err(_) => return, - }; - - // Call WASMI-able DEBUG - unsafe { hc_debug(allocation.as_ribosome_encoding()) }; - - // Free input allocation and all allocations made inside print() - mem_stack.deallocate(allocation).ok(); + fn hc_debug(host_allocation_ptr: AllocationPtr) -> AllocationPtr; } //------------------------------------------------------------------------------------------------- @@ -55,41 +38,28 @@ fn hdk_debug(mem_stack: &mut WasmStack, json_string: &JsonString) { //------------------------------------------------------------------------------------------------- /// Function called by Holochain Instance -/// encoded_allocation_of_input : encoded memory offset and length of the memory allocation +/// host_allocation_ptr : encoded memory offset and length of the memory allocation /// holding input arguments #[no_mangle] pub extern "C" fn debug_hello( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { - let mut mem_stack = match WasmStack::try_from_ribosome_encoding(encoded_allocation_of_input) { - Ok(mem_stack) => mem_stack, - Err(code) => return code.into(), - }; - - hdk_debug( - &mut mem_stack, - &JsonString::from(RawString::from("Hello world!")), - ); - RibosomeEncodedValue::Success.into() + _: AllocationPtr, +) -> AllocationPtr { + let _: () = try_result!(host_call!(hc_debug, RawString::from("Hello world!")), "failed to handle hc_debug result"); + ret!(()); } /// Function called by Holochain Instance -/// encoded_allocation_of_input : encoded memory offset and length of the memory allocation +/// host_allocation_ptr : encoded memory offset and length of the memory allocation /// holding input arguments #[no_mangle] pub extern "C" fn debug_multiple( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { - let mut mem_stack = match WasmStack::try_from_ribosome_encoding(encoded_allocation_of_input) { - Ok(mem_stack) => mem_stack, - Err(code) => return code.into(), - }; - - hdk_debug(&mut mem_stack, &JsonString::from(RawString::from("Hello"))); - hdk_debug(&mut mem_stack, &JsonString::from(RawString::from("world"))); - hdk_debug(&mut mem_stack, &JsonString::from(RawString::from("!"))); + _: AllocationPtr, +) -> AllocationPtr { + let _: () = try_result!(host_call!(hc_debug, RawString::from("Hello")), "debug_multiple one"); + let _: () = try_result!(host_call!(hc_debug, RawString::from("world")), "debug_multiple two"); + let _: () = try_result!(host_call!(hc_debug, RawString::from("!")), "debug_multiple three"); - RibosomeEncodedValue::Success.into() + ret!(()); } //------------------------------------------------------------------------------------------------- @@ -98,23 +68,18 @@ pub extern "C" fn debug_multiple( #[no_mangle] pub extern "C" fn debug_stacked_hello( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { + _: AllocationPtr, +) -> AllocationPtr { #[derive(Serialize, Default, Clone, PartialEq, Deserialize, Debug, DefaultJson)] struct TestStruct { value: String, } - let mut mem_stack = match WasmStack::try_from_ribosome_encoding(encoded_allocation_of_input) { - Ok(mem_stack) => mem_stack, - Err(code) => return code.into(), - }; - - let fish = mem_stack.write_json(TestStruct { + let fish = TestStruct { value: "fish".to_string(), - }); - hdk_debug(&mut mem_stack, &JsonString::from(RawString::from("disruptive debug log"))); - return_code_for_allocation_result(fish).into() + }; + let _: () = try_result!(host_call!(hc_debug, RawString::from("disruptive debug log")), "debug_stacked_hello fail"); + ret!(fish); } //------------------------------------------------------------------------------------------------- @@ -122,13 +87,12 @@ pub extern "C" fn debug_stacked_hello( //------------------------------------------------------------------------------------------------- extern "C" { - fn hc_commit_entry(encoded_allocation_of_input: RibosomeEncodingBits) -> RibosomeEncodingBits; + fn hc_commit_entry(host_allocation_ptr: AllocationPtr) -> AllocationPtr; } /// Call HC API COMMIT function with proper input struct /// return address of entry added source chain fn hdk_commit( - mem_stack: &mut WasmStack, entry_type_name: &str, entry_value: &'static str, provenance: &Vec @@ -139,23 +103,12 @@ fn hdk_commit( RawString::from(entry_value).into(), ); - let args = holochain_wasm_utils::api_serialization::commit_entry::CommitEntryArgs { + let args = holochain_wasm_types::commit_entry::CommitEntryArgs { entry, - options:holochain_wasm_utils::api_serialization::commit_entry::CommitEntryOptions::new(provenance.to_vec()) + options:holochain_wasm_types::commit_entry::CommitEntryOptions::new(provenance.to_vec()) }; - let allocation_of_input = mem_stack.write_json(args)?; - - // Call WASMI-able commit - let encoded_allocation_of_result = - unsafe { hc_commit_entry(allocation_of_input.as_ribosome_encoding()) }; - // Deserialize complex result stored in memory - let result: ZomeApiInternalResult = load_ribosome_encoded_json(encoded_allocation_of_result)?; - - // Free result & input allocations and all allocations made inside commit() - mem_stack - .deallocate(allocation_of_input) - .expect("deallocate failed"); + let result: ZomeApiInternalResult = host_call!(hc_commit_entry, args)?; match JsonString::from_json(&result.value).try_into() { Ok(address) => Ok(address), Err(hc_err) => Err(hc_err.into()), @@ -167,22 +120,11 @@ fn hdk_commit( //------------------------------------------------------------------------------------------------- // Simulate error in commit function by inputing output struct as input -fn hdk_commit_fail(mem_stack: &mut WasmStack) -> Result { +fn hdk_commit_fail() -> Result { // Put args in struct and serialize into memory let input = ZomeApiInternalResult::failure(Address::from("whatever")); - let allocation_of_input = mem_stack.write_json(input)?; - - // Call WASMI-able commit - let encoded_allocation_of_result = - unsafe { hc_commit_entry(allocation_of_input.as_ribosome_encoding()) }; - // Deserialize complex result stored in memory - let result: ZomeApiInternalResult = load_ribosome_encoded_json(encoded_allocation_of_result)?; - - // Free result & input allocations and all allocations made inside commit() - mem_stack - .deallocate(allocation_of_input) - .expect("deallocate failed"); + let result: ZomeApiInternalResult = host_call!(hc_commit_entry, input)?; let address = JsonString::from_json(&result.value).try_into()?; @@ -218,78 +160,46 @@ fn test_inner(input: InputStruct) -> OutputStruct { //------------------------------------------------------------------------------------------------- /// Function called by Holochain Instance -/// encoded_allocation_of_input : encoded memory offset and length of the memory allocation +/// host_allocation_ptr : encoded memory offset and length of the memory allocation /// holding input arguments /// returns encoded allocation used to store output #[no_mangle] pub extern "C" fn commit_test( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { - let mut mem_stack = match WasmStack::try_from_ribosome_encoding(encoded_allocation_of_input) { - Ok(mem_stack) => mem_stack, - Err(code) => return code.into(), - }; - - let result = hdk_commit(&mut mem_stack, "testEntryType", "hello", &vec![]); - - return_code_for_allocation_result(mem_stack.write_json(result)).into() + _: AllocationPtr, +) -> AllocationPtr { + let result = try_result!(hdk_commit("testEntryType", "hello", &vec![]), "failed to commit in commit_test"); + ret!(result); } /// Function called by Holochain Instance -/// encoded_allocation_of_input : encoded memory offset and length of the memory allocation +/// host_allocation_ptr : encoded memory offset and length of the memory allocation /// holding input arguments /// returns encoded allocation used to store output #[no_mangle] pub extern "C" fn commit_fail_test( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { - let mut mem_stack = match WasmStack::try_from_ribosome_encoding(encoded_allocation_of_input) { - Ok(mem_stack) => mem_stack, - Err(code) => return code.into(), - }; - - let result = hdk_commit_fail(&mut mem_stack); - - return_code_for_allocation_result(mem_stack.write_json(result)).into() + _: AllocationPtr, +) -> AllocationPtr { + let result = try_result!(hdk_commit_fail(), "failed to fail in commit_fail_test"); + ret!(result); } #[no_mangle] pub extern "C" fn __hdk_validate_app_entry( - _encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() + _: AllocationPtr, +) -> AllocationPtr { + ret!(ValidationResult::Ok); } #[no_mangle] pub extern "C" fn __hdk_get_validation_package_for_entry_type( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeRuntimeBits { - let mut mem_stack = match WasmStack::try_from_ribosome_encoding(encoded_allocation_of_input) { - Ok(mem_stack) => mem_stack, - Err(code) => return code.into(), - }; - - return_code_for_allocation_result(mem_stack.write_json(RawString::from("ChainFull"))).into() + _: AllocationPtr, +) -> AllocationPtr { + ret!(ValidationPackageDefinition::ChainFull); } -/// Function called by Holochain Instance -/// encoded_allocation_of_input : encoded memory offset and length of the memory allocation -/// holding input arguments -/// returns encoded allocation used to store output #[no_mangle] pub extern "C" fn round_trip_test( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { - let mut mem_stack = match WasmStack::try_from_ribosome_encoding(encoded_allocation_of_input) { - Ok(mem_stack) => mem_stack, - Err(code) => return code.into(), - }; - - let input = match load_ribosome_encoded_json(encoded_allocation_of_input) { - Ok(input) => input, - Err(e) => return RibosomeEncodedValue::from(e).into(), - }; - let output = test_inner(input); - - return_code_for_allocation_result(mem_stack.write_json(output)).into() + host_allocation_ptr: AllocationPtr, +) -> AllocationPtr { + ret!(test_inner(host_args!(host_allocation_ptr))); } diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 8bf7d16e5f..96bca22b6a 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -8,6 +8,9 @@ documentation = "https://github.com/holochain/holochain-rust" authors = ["Holochain Core Dev Team "] edition = "2018" +[lib] +path = "src/lib.rs" + [dependencies] base64 = "=0.10.1" serde = { version = "=1.0.104", features = ["rc"] } @@ -16,17 +19,16 @@ chrono = "=0.4.6" serde_json = { version = "=1.0.47", features = ["preserve_order"] } snowflake = { version = "=1.3.0", features = ["serde_support"] } bitflags = "=1.2.1" -wasmi = "=0.4.4" wasmer-runtime = "=0.13.1" failure = "=0.1.5" lazy_static = "=1.4.0" unwrap_to = "=0.1.0" num-traits = "=0.2.6" num-derive = "=0.2.4" +num = "=0.2.0" toml = "=0.5.0" futures = { version = "=0.3.2", features = [ "thread-pool" ] } holochain_net = { version = "=0.0.43-alpha3", path = "../net" } -holochain_wasm_utils = { version = "=0.0.43-alpha3", path = "../wasm_utils" } holochain_common = { version = "=0.0.43-alpha3", path = "../common" } holochain_conductor_lib_api = { version = "=0.0.43-alpha3", path = "../conductor_api" } lib3h_protocol = "=0.0.38" @@ -37,6 +39,7 @@ holochain_persistence_api = "=0.0.17" holochain_persistence_file = "=0.0.17" holochain_persistence_mem = "=0.0.17" holochain_core_types = { version = "=0.0.43-alpha3", path = "../core_types" } +holochain_wasm_types = { version = "=0.0.43-alpha3", path = "../wasm_types" } holochain_dpki = { version = "=0.0.43-alpha3", path = "../dpki" } holochain_locksmith = { version = "=0.0.43-alpha3", path = "../locksmith" } holochain_metrics = { version = "=0.0.43-alpha3", path = "../metrics" } @@ -60,6 +63,7 @@ threadpool = "=1.7.1" im = { version = "=14.0.0", features = ["serde"] } itertools = "0.8.2" newrelic="0.2" +holochain_wasmer_host = "=0.0.18" [dev-dependencies] wabt = "=0.7.4" diff --git a/crates/core/src/action.rs b/crates/core/src/action.rs index 558de916a6..61ca72ca8f 100644 --- a/crates/core/src/action.rs +++ b/crates/core/src/action.rs @@ -11,7 +11,7 @@ use crate::{ nucleus::{ actions::{call_zome_function::ExecuteZomeFnResponse, initialize::Initialization}, state::NucleusState, - HdkFnCall, HdkFnCallResult, ZomeFnCall, + WasmApiFnCall, WasmApiFnCallResult, ZomeFnCall, }, state::State, }; @@ -231,10 +231,10 @@ pub enum Action { ReturnZomeFunctionResult(ExecuteZomeFnResponse), /// Let the State track that a zome call has called an HDK function - TraceInvokeHdkFunction((ZomeFnCall, HdkFnCall)), + TraceInvokeWasmApiFunction((ZomeFnCall, WasmApiFnCall)), /// Let the State track that an HDK function called by a zome call has returned - TraceReturnHdkFunction((ZomeFnCall, HdkFnCall, HdkFnCallResult)), + TraceReturnWasmApiFunction((ZomeFnCall, WasmApiFnCall, WasmApiFnCallResult)), /// Remove all traces of the given call from state (mainly the result) ClearZomeFunctionCall(ZomeFnCall), diff --git a/crates/core/src/agent/actions/commit.rs b/crates/core/src/agent/actions/commit.rs index b4186e4b64..40d0e0ac29 100644 --- a/crates/core/src/agent/actions/commit.rs +++ b/crates/core/src/agent/actions/commit.rs @@ -3,7 +3,7 @@ use crate::{ agent::state::AgentActionResponse, context::Context, instance::dispatch_action, - NEW_RELIC_LICENSE_KEY, + }; use futures::{future::Future, task::Poll}; use holochain_core_types::{entry::Entry, error::HolochainError}; @@ -15,7 +15,7 @@ use std::{pin::Pin, sync::Arc}; /// be called from zome api functions and other contexts that don't care about implementation details. /// /// Returns a future that resolves to an ActionResponse. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn commit_entry( entry: Entry, maybe_link_update_delete: Option
, @@ -41,7 +41,7 @@ pub struct CommitFuture { action: ActionWrapper, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Future for CommitFuture { type Output = Result; diff --git a/crates/core/src/agent/chain_store.rs b/crates/core/src/agent/chain_store.rs index f88696f7db..1307b58dce 100644 --- a/crates/core/src/agent/chain_store.rs +++ b/crates/core/src/agent/chain_store.rs @@ -1,21 +1,17 @@ use crate::{ content_store::{AddContent, GetContent}, - NEW_RELIC_LICENSE_KEY, + }; use globset::{GlobBuilder, GlobSetBuilder}; use holochain_core_types::{ - chain_header::ChainHeader, - entry::entry_type::EntryType, - error::{ - HcResult, - RibosomeErrorCode::{self, *}, - }, + chain_header::ChainHeader, entry::entry_type::EntryType, error::HcResult, }; use holochain_locksmith::RwLock; use holochain_persistence_api::cas::{ content::{Address, AddressableContent, Content}, storage::ContentAddressableStorage, }; +use holochain_wasmer_host::*; use std::{str::FromStr, sync::Arc}; #[derive(Debug, Clone)] @@ -47,7 +43,7 @@ pub enum ChainStoreQueryResult { Headers(Vec), } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl ChainStore { pub fn new(content_storage: Arc>) -> Self { ChainStore { content_storage } @@ -78,7 +74,7 @@ impl ChainStore { start_chain_header: &Option, entry_type_names: &[&str], options: ChainStoreQueryOptions, - ) -> Result { + ) -> Result { // Get entry_type name(s), if any. If empty/blank, returns the complete source chain. A // single matching entry type name with no glob pattern matching will use the single // entry_type optimization. Otherwise, we'll construct a GlobSet match and scan the list to @@ -124,7 +120,7 @@ impl ChainStore { // Single EntryType without "glob" pattern; uses .iter_type() let entry_type = match EntryType::from_str(&one) { Ok(inner) => inner, - Err(..) => return Err(UnknownEntryType), + Err(..) => return Err(WasmError::UnknownEntryType), }; if headers { ChainStoreQueryResult::Headers( @@ -155,10 +151,10 @@ impl ChainStore { GlobBuilder::new(name) .literal_separator(true) .build() - .map_err(|_| UnknownEntryType)?, + .map_err(|_| WasmError::UnknownEntryType)?, ); } - let globset = builder.build().map_err(|_| UnknownEntryType)?; + let globset = builder.build().map_err(|_| WasmError::UnknownEntryType)?; if headers { ChainStoreQueryResult::Headers( self.iter(start_chain_header) @@ -226,7 +222,7 @@ impl ChainStoreIterator { } /// Follows ChainHeader.link through every previous Entry (of any EntryType) in the chain -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Iterator for ChainStoreIterator { type Item = ChainHeader; diff --git a/crates/core/src/agent/state.rs b/crates/core/src/agent/state.rs index 380ae2e239..ccaa78093b 100644 --- a/crates/core/src/agent/state.rs +++ b/crates/core/src/agent/state.rs @@ -3,7 +3,7 @@ use crate::{ agent::chain_store::{ChainStore, ChainStoreIterator}, network::entry_with_header::EntryWithHeader, state::State, - NEW_RELIC_LICENSE_KEY, + }; use holochain_persistence_api::cas::content::{Address, AddressableContent, Content}; @@ -24,7 +24,7 @@ use holochain_json_api::{ error::{JsonError, JsonResult}, json::JsonString, }; -use holochain_wasm_utils::api_serialization::crypto::CryptoMethod; +use holochain_wasm_types::crypto::CryptoMethod; use im::HashMap; use serde_json; use std::{convert::TryFrom, ops::Deref, sync::Arc, time::SystemTime}; @@ -41,7 +41,7 @@ pub struct AgentState { } #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl AgentState { /// builds a new, empty AgentState pub fn new(chain_store: ChainStore, initial_agent_address: Address) -> AgentState { @@ -183,7 +183,7 @@ impl From for Response { } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn create_new_chain_header( entry: &Entry, agent_state: &AgentState, @@ -231,7 +231,7 @@ pub fn create_new_chain_header( /// Create an entry-with-header for a header. /// Since published headers are treated as entries, the header must also /// have its own header! -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn create_entry_with_header_for_header( root_state: &StateWrapper, chain_header: ChainHeader, @@ -266,7 +266,7 @@ pub fn create_entry_with_header_for_header( /// Intended for use inside the reducer, isolated for unit testing. /// callback checks (e.g. validate_commit) happen elsewhere because callback functions cause /// action reduction to hang -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn reduce_commit_entry( agent_state: &mut AgentState, root_state: &State, @@ -298,7 +298,7 @@ fn reduce_commit_entry( ); } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn reduce_prune(agent_state: &mut AgentState, _root_state: &State, action_wrapper: &ActionWrapper) { assert_eq!(action_wrapper.action(), &Action::Prune); @@ -321,7 +321,7 @@ fn reduce_prune(agent_state: &mut AgentState, _root_state: &State, action_wrappe }); } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn reduce_clear_action_response( agent_state: &mut AgentState, _root_state: &State, @@ -339,7 +339,7 @@ fn reduce_clear_action_response( } /// maps incoming action to the correct handler -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn resolve_reducer(action_wrapper: &ActionWrapper) -> Option { match action_wrapper.action() { Action::ClearActionResponse(_) => Some(reduce_clear_action_response), @@ -350,7 +350,7 @@ fn resolve_reducer(action_wrapper: &ActionWrapper) -> Option { } /// Reduce Agent's state according to provided Action -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce( old_state: Arc, root_state: &State, diff --git a/crates/core/src/consistency.rs b/crates/core/src/consistency.rs index c9f48ddf61..961fc4f30b 100644 --- a/crates/core/src/consistency.rs +++ b/crates/core/src/consistency.rs @@ -1,5 +1,5 @@ use crate::{ - action::Action, context::Context, entry::CanPublish, nucleus::ZomeFnCall, NEW_RELIC_LICENSE_KEY, + action::Action, context::Context, entry::CanPublish, nucleus::ZomeFnCall, }; use holochain_core_types::{ entry::Entry, link::link_data::LinkData, network::entry_aspect::EntryAspect, @@ -97,7 +97,7 @@ pub struct ConsistencyModel { context: Arc, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl ConsistencyModel { pub fn new(context: Arc) -> Self { Self { diff --git a/crates/core/src/context.rs b/crates/core/src/context.rs index 13157aab27..47f7e548a8 100644 --- a/crates/core/src/context.rs +++ b/crates/core/src/context.rs @@ -6,7 +6,7 @@ use crate::{ persister::Persister, signal::{Signal, SignalSender}, state::StateWrapper, - NEW_RELIC_LICENSE_KEY, + }; use crossbeam_channel::{unbounded, Receiver, Sender}; use futures::{ @@ -109,7 +109,7 @@ pub struct Context { pub tracer: Arc, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Context { // test_check_conductor_api() is used to inject a conductor_api with a working // mock of agent/sign to be used in tests. diff --git a/crates/core/src/dht/actions/hold_aspect.rs b/crates/core/src/dht/actions/hold_aspect.rs index 8165419e34..a1fe12060d 100644 --- a/crates/core/src/dht/actions/hold_aspect.rs +++ b/crates/core/src/dht/actions/hold_aspect.rs @@ -2,7 +2,7 @@ use crate::{ action::{Action, ActionWrapper}, context::Context, instance::dispatch_action, - NEW_RELIC_LICENSE_KEY, + }; use futures::{future::Future, task::Poll}; use holochain_core_types::{error::HolochainError, network::entry_aspect::EntryAspect}; @@ -19,7 +19,7 @@ pub struct HoldAspectFuture { aspect: EntryAspect, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Future for HoldAspectFuture { type Output = Result<(), HolochainError>; diff --git a/crates/core/src/dht/actions/queue_holding_workflow.rs b/crates/core/src/dht/actions/queue_holding_workflow.rs index 3f0575968c..ba0cf3f61f 100644 --- a/crates/core/src/dht/actions/queue_holding_workflow.rs +++ b/crates/core/src/dht/actions/queue_holding_workflow.rs @@ -3,7 +3,7 @@ use crate::{ context::Context, dht::pending_validations::PendingValidation, instance::dispatch_action, - NEW_RELIC_LICENSE_KEY, + }; use futures::{future::Future, task::Poll}; use std::{ @@ -12,11 +12,11 @@ use std::{ time::{Duration, SystemTime}, }; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn dispatch_queue_holding_workflow( + context: Arc, pending: PendingValidation, delay: Option, - context: Arc, ) { let delay_with_now = delay.map(|d| (SystemTime::now(), d)); let action_wrapper = @@ -24,11 +24,11 @@ pub fn dispatch_queue_holding_workflow( dispatch_action(context.action_channel(), action_wrapper); } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn queue_holding_workflow( + context: Arc, pending: PendingValidation, delay: Option, - context: Arc, ) { if !context .state() @@ -37,7 +37,7 @@ pub async fn queue_holding_workflow( .has_exact_queued_holding_workflow(&pending) { log_trace!(context, "Queueing holding workflow: {:?}", pending); - dispatch_queue_holding_workflow(pending.clone(), delay, context.clone()); + dispatch_queue_holding_workflow(Arc::clone(&context), Arc::clone(&pending), delay); QueueHoldingWorkflowFuture { context, pending }.await } else { log_trace!( @@ -53,7 +53,7 @@ pub struct QueueHoldingWorkflowFuture { pending: PendingValidation, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Future for QueueHoldingWorkflowFuture { type Output = (); diff --git a/crates/core/src/dht/actions/remove_queued_holding_workflow.rs b/crates/core/src/dht/actions/remove_queued_holding_workflow.rs index f1f2979e15..f73fa9c97b 100644 --- a/crates/core/src/dht/actions/remove_queued_holding_workflow.rs +++ b/crates/core/src/dht/actions/remove_queued_holding_workflow.rs @@ -3,13 +3,13 @@ use crate::{ context::Context, dht::pending_validations::PendingValidation, instance::dispatch_action, - NEW_RELIC_LICENSE_KEY, + }; use futures::{future::Future, task::Poll}; use std::{pin::Pin, sync::Arc}; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub async fn remove_queued_holding_workflow(pending: PendingValidation, context: Arc) { +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn remove_queued_holding_workflow(context: Arc, pending: PendingValidation) { let action_wrapper = ActionWrapper::new(Action::RemoveQueuedHoldingWorkflow(pending.clone())); dispatch_action(context.action_channel(), action_wrapper.clone()); RemoveQueuedHoldingWorkflowFuture { context, pending }.await @@ -20,7 +20,7 @@ pub struct RemoveQueuedHoldingWorkflowFuture { pending: PendingValidation, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Future for RemoveQueuedHoldingWorkflowFuture { type Output = (); diff --git a/crates/core/src/dht/aspect_map.rs b/crates/core/src/dht/aspect_map.rs index a99fe0f471..c066b3acc0 100644 --- a/crates/core/src/dht/aspect_map.rs +++ b/crates/core/src/dht/aspect_map.rs @@ -1,7 +1,4 @@ -use crate::{ - holochain_wasm_utils::holochain_persistence_api::cas::content::AddressableContent, - NEW_RELIC_LICENSE_KEY, -}; +use holochain_wasm_types::holochain_persistence_api::cas::content::AddressableContent; use holochain_core_types::network::entry_aspect::EntryAspect; use im::{HashMap, HashSet}; use lib3h_protocol::types::{AspectHash, EntryHash}; @@ -12,7 +9,7 @@ pub type AspectMapBare = HashMap; #[derive(Clone, Debug, Default, PartialEq)] pub struct AspectMap(AspectMapBare); -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl AspectMap { pub fn new() -> Self { Self::default() diff --git a/crates/core/src/dht/dht_inner_reducers.rs b/crates/core/src/dht/dht_inner_reducers.rs index ac55d9dee4..1787455830 100644 --- a/crates/core/src/dht/dht_inner_reducers.rs +++ b/crates/core/src/dht/dht_inner_reducers.rs @@ -10,7 +10,7 @@ use crate::dht::dht_store::DhtStore; use crate::{ content_store::{AddContent, GetContent}, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::{ crud_status::{create_crud_link_eav, create_crud_status_eav, CrudStatus}, @@ -34,7 +34,7 @@ pub(crate) enum LinkModification { } /// Used as the inner function for both commit and hold reducers -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub(crate) fn reduce_store_entry_inner(store: &mut DhtStore, entry: &Entry) -> HcResult<()> { match store.add(entry) { Ok(()) => create_crud_status_eav(&entry.address(), CrudStatus::Live).map(|status_eav| { @@ -46,7 +46,7 @@ pub(crate) fn reduce_store_entry_inner(store: &mut DhtStore, entry: &Entry) -> H } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub(crate) fn reduce_add_remove_link_inner( store: &mut DhtStore, link: &LinkData, @@ -80,7 +80,7 @@ pub(crate) fn reduce_add_remove_link_inner( } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub(crate) fn reduce_update_entry_inner( store: &mut DhtStore, old_address: &Address, @@ -96,7 +96,7 @@ pub(crate) fn reduce_update_entry_inner( Ok(new_address.clone()) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub(crate) fn reduce_remove_entry_inner( store: &mut DhtStore, latest_deleted_address: &Address, diff --git a/crates/core/src/dht/dht_reducers.rs b/crates/core/src/dht/dht_reducers.rs index 6472bf97de..f54e045465 100644 --- a/crates/core/src/dht/dht_reducers.rs +++ b/crates/core/src/dht/dht_reducers.rs @@ -6,7 +6,7 @@ use crate::{ dht_store::DhtStore, pending_validations::{PendingValidationWithTimeout, ValidationTimeout}, }, - NEW_RELIC_LICENSE_KEY, + }; use std::sync::Arc; @@ -24,7 +24,7 @@ type DhtReducer = fn(&DhtStore, &ActionWrapper) -> Option; /// DHT state-slice Reduce entry point. /// Note: Can't block when dispatching action here because we are inside the reduce's mutex -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce(old_store: Arc, action_wrapper: &ActionWrapper) -> Arc { // Get reducer let reducer = match resolve_reducer(action_wrapper) { @@ -41,7 +41,7 @@ pub fn reduce(old_store: Arc, action_wrapper: &ActionWrapper) -> Arc Option { match action_wrapper.action() { Action::Commit(_) => Some(reduce_commit_entry), @@ -53,7 +53,7 @@ fn resolve_reducer(action_wrapper: &ActionWrapper) -> Option { } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub(crate) fn reduce_commit_entry( old_store: &DhtStore, action_wrapper: &ActionWrapper, @@ -69,7 +69,7 @@ pub(crate) fn reduce_commit_entry( } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub(crate) fn reduce_hold_aspect( old_store: &DhtStore, action_wrapper: &ActionWrapper, @@ -151,7 +151,7 @@ pub(crate) fn reduce_hold_aspect( } #[allow(dead_code)] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub(crate) fn reduce_get_links( _old_store: &DhtStore, _action_wrapper: &ActionWrapper, @@ -162,7 +162,7 @@ pub(crate) fn reduce_get_links( #[allow(unknown_lints)] #[allow(clippy::needless_pass_by_value)] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_queue_holding_workflow( old_store: &DhtStore, action_wrapper: &ActionWrapper, @@ -195,7 +195,7 @@ pub fn reduce_queue_holding_workflow( } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_prune(old_store: &DhtStore, _action_wrapper: &ActionWrapper) -> Option { let pruned_queue = old_store .queued_holding_workflows @@ -220,7 +220,7 @@ pub fn reduce_prune(old_store: &DhtStore, _action_wrapper: &ActionWrapper) -> Op #[allow(unknown_lints)] #[allow(clippy::needless_pass_by_value)] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_remove_queued_holding_workflow( old_store: &DhtStore, action_wrapper: &ActionWrapper, diff --git a/crates/core/src/dht/dht_store.rs b/crates/core/src/dht/dht_store.rs index 27255931da..9b77cd783c 100644 --- a/crates/core/src/dht/dht_store.rs +++ b/crates/core/src/dht/dht_store.rs @@ -4,7 +4,7 @@ use crate::{ aspect_map::{AspectMap, AspectMapBare}, pending_validations::{PendingValidationWithTimeout, ValidationTimeout}, }, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::{ chain_header::ChainHeader, @@ -97,7 +97,7 @@ impl AddressableContent for DhtStoreSnapshot { } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn create_get_links_eavi_query<'a>( address: Address, link_type: String, @@ -129,7 +129,7 @@ pub fn create_get_links_eavi_query<'a>( )) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl DhtStore { // LifeCycle // ========= diff --git a/crates/core/src/dht/pending_validations.rs b/crates/core/src/dht/pending_validations.rs index 6f7a5a995c..f15aa266fb 100644 --- a/crates/core/src/dht/pending_validations.rs +++ b/crates/core/src/dht/pending_validations.rs @@ -6,6 +6,7 @@ use holochain_core_types::{ entry::{deletion_entry::DeletionEntry, Entry}, error::HolochainError, network::entry_aspect::EntryAspect, + validation::ValidationResult, }; use holochain_json_api::{error::JsonError, json::JsonString}; use holochain_persistence_api::cas::content::Address; @@ -126,8 +127,8 @@ impl TryFrom for PendingValidationStruct { EntryAspect::Deletion(header) => { // reconstruct the deletion entry from the header. let deleted_entry_address = header.link_update_delete().ok_or_else(|| { - HolochainError::ValidationFailed(String::from( - "Deletion header is missing deletion link", + HolochainError::ValidationFailed(ValidationResult::Fail( + "Deletion header is missing deletion link".into() )) })?; let entry = Entry::Deletion(DeletionEntry::new(deleted_entry_address)); diff --git a/crates/core/src/entry/mod.rs b/crates/core/src/entry/mod.rs index 80cb2dce5e..1264022b08 100644 --- a/crates/core/src/entry/mod.rs +++ b/crates/core/src/entry/mod.rs @@ -4,12 +4,12 @@ pub mod validation_dependencies; use holochain_core_types::entry::entry_type::EntryType; -use crate::{context::Context, NEW_RELIC_LICENSE_KEY}; +use crate::{context::Context}; pub trait CanPublish { fn can_publish(&self, context: &Context) -> bool; } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl CanPublish for EntryType { fn can_publish(&self, context: &Context) -> bool { match self { diff --git a/crates/core/src/entry/validation_dependencies.rs b/crates/core/src/entry/validation_dependencies.rs index 051ef35136..54b60b58c7 100644 --- a/crates/core/src/entry/validation_dependencies.rs +++ b/crates/core/src/entry/validation_dependencies.rs @@ -1,4 +1,4 @@ -use crate::{network::entry_with_header::EntryWithHeader, NEW_RELIC_LICENSE_KEY}; +use crate::{network::entry_with_header::EntryWithHeader}; use holochain_core_types::entry::Entry; use holochain_persistence_api::cas::content::Address; @@ -6,7 +6,7 @@ pub trait ValidationDependencies { fn get_validation_dependencies(&self) -> Vec
; } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl ValidationDependencies for EntryWithHeader { fn get_validation_dependencies(&self) -> Vec
{ match &self.entry { diff --git a/crates/core/src/instance.rs b/crates/core/src/instance.rs index 12e374cbb7..f423311639 100644 --- a/crates/core/src/instance.rs +++ b/crates/core/src/instance.rs @@ -12,7 +12,7 @@ use crate::{ signal::Signal, state::{State, StateWrapper}, workflows::{application, run_holding_workflow}, - NEW_RELIC_LICENSE_KEY, + // }; #[cfg(test)] use crate::{ @@ -66,7 +66,8 @@ pub struct Observer { pub static DISPATCH_WITHOUT_CHANNELS: &str = "dispatch called without channels open"; #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// @TODO fix swallowed line numbers +// // #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Instance { /// This is initializing and starting the redux action loop and adding channels to dispatch /// actions and observers to the context @@ -331,15 +332,15 @@ impl Instance { // NB: If for whatever reason we pop_next_holding_workflow anywhere else other than here, // we can run into a race condition. context.block_on(remove_queued_holding_workflow( - pending.clone(), - context.clone(), + Arc::clone(&context), + Arc::clone(&pending), )); - let c = context.clone(); - let pending = pending.clone(); + let closure_context = Arc::clone(&context); + let closure_pending = Arc::clone(&pending); let closure = async move || { - match run_holding_workflow(pending.clone(), c.clone()).await { + match run_holding_workflow(Arc::clone(&closure_context), Arc::clone(&closure_pending)).await { // If we couldn't run the validation due to unresolved dependencies, // we have to re-add this entry at the end of the queue: Err(HolochainError::ValidationPending) => { @@ -358,19 +359,19 @@ impl Instance { } queue_holding_workflow( - Arc::new(pending.same()), + Arc::clone(&closure_context), + Arc::new(closure_pending.same()), Some(delay), - c.clone(), ) .await } Err(e) => log_error!( - c, + closure_context, "Error running holding workflow for {:?}: {:?}", pending, e, ), - Ok(()) => log_info!(c, "Successfully processed: {:?}", pending), + Ok(()) => log_info!(closure_context, "Successfully processed: {:?}", pending), } }; let future = closure(); diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index ad89a6113c..b88ef93911 100755 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -15,8 +15,6 @@ extern crate unwrap_to; #[macro_use] extern crate num_derive; -#[macro_use] -extern crate holochain_wasm_utils; #[macro_use] extern crate holochain_json_derive; #[macro_use] @@ -31,18 +29,21 @@ extern crate holochain_tracing_macros; #[macro_use] extern crate holochain_common; +use holochain_wasm_types; +// use holochain_wasmer_host; + #[macro_use] pub mod macros; -// #[autotrace] +#[autotrace] pub mod action; -// #[autotrace] +#[autotrace] pub mod agent; -// #[autotrace] +#[autotrace] pub mod consistency; -// #[autotrace] +#[autotrace] pub mod content_store; -// #[autotrace] +#[autotrace] pub mod context; pub mod dht; pub mod entry; @@ -51,20 +52,20 @@ pub mod instance; #[cfg(test)] pub mod link_tests; pub mod logger; -// #[autotrace] +#[autotrace] pub mod network; -// #[autotrace] +#[autotrace] pub mod nucleus; -// #[autotrace] +#[autotrace] pub mod persister; pub mod scheduled_jobs; -// #[autotrace] +#[autotrace] pub mod signal; -// #[autotrace] +#[autotrace] pub mod state; -// #[autotrace] +#[autotrace] pub mod state_dump; -pub mod wasm_engine; pub mod workflows; +pub mod wasm_engine; new_relic_setup!("NEW_RELIC_LICENSE_KEY"); diff --git a/crates/core/src/network/actions/custom_send.rs b/crates/core/src/network/actions/custom_send.rs index f87813608a..41b450191c 100644 --- a/crates/core/src/network/actions/custom_send.rs +++ b/crates/core/src/network/actions/custom_send.rs @@ -3,7 +3,7 @@ use crate::{ context::Context, instance::dispatch_action, network::direct_message::{CustomDirectMessage, DirectMessage}, - NEW_RELIC_LICENSE_KEY, + }; use futures::{future::Future, task::Poll}; use holochain_core_types::{error::HolochainError, time::Timeout}; @@ -16,12 +16,12 @@ use std::{pin::Pin, sync::Arc, time::SystemTime}; /// This triggers the network module to open a synchronous node-to-node connection /// by sending the given CustomDirectMessage and preparing to receive a response. #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn custom_send( + context: Arc, to_agent: Address, custom_direct_message: CustomDirectMessage, timeout: Timeout, - context: Arc, ) -> Result { let rand_string: String = thread_rng().sample_iter(&Alphanumeric).take(10).collect(); let id = format!("{}-{}", ProcessUniqueId::new().to_string(), rand_string); @@ -51,7 +51,7 @@ pub struct SendResponseFuture { id: String, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Future for SendResponseFuture { type Output = Result; diff --git a/crates/core/src/network/actions/get_validation_package.rs b/crates/core/src/network/actions/get_validation_package.rs index 76c066623a..1dadffb14f 100644 --- a/crates/core/src/network/actions/get_validation_package.rs +++ b/crates/core/src/network/actions/get_validation_package.rs @@ -2,7 +2,7 @@ use crate::{ action::{Action, ActionWrapper}, context::Context, instance::dispatch_action, - NEW_RELIC_LICENSE_KEY, + }; use futures::{future::Future, task::Poll}; @@ -20,7 +20,7 @@ use std::{pin::Pin, sync::Arc}; /// /// Returns a future that resolves to Option (or HolochainError). /// If that is None this means that we couldn't get a validation package from the source. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn get_validation_package( header: ChainHeader, context: &Arc, @@ -43,7 +43,7 @@ pub struct GetValidationPackageFuture { address: Address, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Future for GetValidationPackageFuture { type Output = HcResult>; diff --git a/crates/core/src/network/actions/initialize_network.rs b/crates/core/src/network/actions/initialize_network.rs index 764b90cfd4..6917ad49b0 100644 --- a/crates/core/src/network/actions/initialize_network.rs +++ b/crates/core/src/network/actions/initialize_network.rs @@ -3,7 +3,7 @@ use crate::{ context::{get_dna_and_agent, Context}, instance::dispatch_action, network::handler::create_handler, - NEW_RELIC_LICENSE_KEY, + }; use futures::{task::Poll, Future}; use holochain_core_types::error::HcResult; @@ -13,7 +13,7 @@ use std::{pin::Pin, sync::Arc}; /// Creates a network proxy object and stores DNA and agent hash in the network state. #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn initialize_network(context: &Arc) -> HcResult<()> { let (dna_address, agent_id) = get_dna_and_agent(context).await?; let handler = create_handler(&context, dna_address.to_string()); diff --git a/crates/core/src/network/actions/publish.rs b/crates/core/src/network/actions/publish.rs index 6eec4f52a6..998e68beb2 100644 --- a/crates/core/src/network/actions/publish.rs +++ b/crates/core/src/network/actions/publish.rs @@ -3,7 +3,7 @@ use crate::{ context::Context, instance::dispatch_action, network::actions::NetworkActionResponse, - NEW_RELIC_LICENSE_KEY, + }; use futures::{future::Future, task::Poll}; use holochain_core_types::error::HcResult; @@ -15,7 +15,7 @@ use std::{pin::Pin, sync::Arc}; /// be called from zome api functions and other contexts that don't care about implementation details. /// /// Returns a future that resolves to an ActionResponse. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn publish(address: Address, context: &Arc) -> HcResult
{ let action_wrapper = ActionWrapper::new(Action::Publish(address)); dispatch_action(context.action_channel(), action_wrapper.clone()); @@ -33,7 +33,7 @@ pub struct PublishFuture { action: ActionWrapper, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Future for PublishFuture { type Output = HcResult
; diff --git a/crates/core/src/network/actions/publish_header_entry.rs b/crates/core/src/network/actions/publish_header_entry.rs index a27e170541..1fbf7d4d74 100644 --- a/crates/core/src/network/actions/publish_header_entry.rs +++ b/crates/core/src/network/actions/publish_header_entry.rs @@ -3,7 +3,7 @@ use crate::{ context::Context, instance::dispatch_action, network::actions::NetworkActionResponse, - NEW_RELIC_LICENSE_KEY, + }; use futures::{future::Future, task::Poll}; use holochain_core_types::error::HcResult; @@ -12,7 +12,7 @@ use std::{pin::Pin, sync::Arc}; /// Publish Header Entry Action Creator /// Returns a future that resolves to an ActionResponse. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn publish_header_entry(address: Address, context: &Arc) -> HcResult
{ let action_wrapper = ActionWrapper::new(Action::PublishHeaderEntry(address)); dispatch_action(context.action_channel(), action_wrapper.clone()); @@ -30,7 +30,7 @@ pub struct PublishHeaderEntryFuture { action: ActionWrapper, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Future for PublishHeaderEntryFuture { type Output = HcResult
; diff --git a/crates/core/src/network/actions/query.rs b/crates/core/src/network/actions/query.rs index e7c450ed3b..ab3ec456e5 100644 --- a/crates/core/src/network/actions/query.rs +++ b/crates/core/src/network/actions/query.rs @@ -3,7 +3,7 @@ use crate::{ context::Context, instance::dispatch_action, network::query::{GetLinksNetworkQuery, NetworkQueryResult}, - NEW_RELIC_LICENSE_KEY, + }; use futures::{future::Future, task::Poll}; @@ -15,7 +15,7 @@ use std::{pin::Pin, sync::Arc}; use snowflake::ProcessUniqueId; -use holochain_wasm_utils::api_serialization::get_links::{GetLinksArgs, LinksStatusRequestKind}; +use holochain_wasm_types::get_links::{GetLinksArgs, LinksStatusRequestKind}; use std::time::SystemTime; /// FetchEntry Action Creator @@ -30,7 +30,7 @@ pub enum QueryMethod { Link(GetLinksArgs, GetLinksNetworkQuery), } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn query( context: Arc, method: QueryMethod, @@ -85,7 +85,7 @@ pub struct QueryFuture { key: QueryKey, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Future for QueryFuture { type Output = HcResult; diff --git a/crates/core/src/network/actions/shutdown.rs b/crates/core/src/network/actions/shutdown.rs index affd2b65d7..d91eeb3a73 100644 --- a/crates/core/src/network/actions/shutdown.rs +++ b/crates/core/src/network/actions/shutdown.rs @@ -2,7 +2,7 @@ use crate::{ action::{Action, ActionWrapper}, context::ActionSender, instance::dispatch_action, - NEW_RELIC_LICENSE_KEY, + }; use futures::{future::Future, task::Poll}; use holochain_core_types::error::{HcResult, HolochainError}; @@ -14,7 +14,7 @@ use std::{pin::Pin, sync::Arc}; /// Shutdown the network /// This tells the network to untrack this instance and then stops the network thread /// and sets the P2pNetwork instance in the state to None. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn shutdown( state: Arc>, action_channel: &ActionSender, @@ -34,7 +34,7 @@ pub struct ShutdownFuture { state: Arc>, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Future for ShutdownFuture { type Output = HcResult<()>; diff --git a/crates/core/src/network/entry_with_header.rs b/crates/core/src/network/entry_with_header.rs index 55585651f8..2d9740e748 100644 --- a/crates/core/src/network/entry_with_header.rs +++ b/crates/core/src/network/entry_with_header.rs @@ -2,18 +2,20 @@ use crate::{ agent::find_chain_header, content_store::GetContent, state::{State, StateWrapper}, - NEW_RELIC_LICENSE_KEY, + }; -use holochain_core_types::{chain_header::ChainHeader, entry::Entry, error::HolochainError}; +use holochain_core_types::{chain_header::ChainHeader, entry::Entry, error::HolochainError, validation::ValidationResult}; use holochain_persistence_api::cas::content::{Address, AddressableContent}; +use holochain_json_api::json::JsonString; +use holochain_json_api::error::JsonError; -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, DefaultJson)] pub struct EntryWithHeader { pub entry: Entry, pub header: ChainHeader, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl EntryWithHeader { pub fn new(entry: Entry, header: ChainHeader) -> EntryWithHeader { EntryWithHeader { entry, header } @@ -24,8 +26,8 @@ impl EntryWithHeader { header: ChainHeader, ) -> Result { if entry.address() != *header.entry_address() { - Err(HolochainError::ValidationFailed(String::from( - "Entry/Header mismatch", + Err(HolochainError::ValidationFailed(ValidationResult::Fail( + "Entry/Header mismatch".into() ))) } else { Ok(EntryWithHeader::new(entry, header)) diff --git a/crates/core/src/network/handler/fetch.rs b/crates/core/src/network/handler/fetch.rs index 6d515c0ffe..40bccb195a 100644 --- a/crates/core/src/network/handler/fetch.rs +++ b/crates/core/src/network/handler/fetch.rs @@ -5,7 +5,7 @@ use crate::{ network::handler::{ get_content_aspect, get_meta_aspects_from_chain, get_meta_aspects_from_dht_eav, }, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::network::entry_aspect::EntryAspect; use lib3h_protocol::data_types::FetchEntryData; @@ -14,8 +14,8 @@ use std::{collections::HashSet, sync::Arc}; /// The network has requested a DHT entry from us. /// Lets try to get it and trigger a response. #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn handle_fetch_entry(get_dht_data: FetchEntryData, context: Arc) { +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub fn handle_fetch_entry(context: Arc, get_dht_data: FetchEntryData) { let address = get_dht_data.entry_address.clone(); let mut aspects: HashSet = HashSet::new(); @@ -27,7 +27,7 @@ pub fn handle_fetch_entry(get_dht_data: FetchEntryData, context: Arc) { aspects.insert(content_aspect); for result in &[ get_meta_aspects_from_chain(&address, context.clone()), - get_meta_aspects_from_dht_eav(&address, context.clone()), + get_meta_aspects_from_dht_eav(Arc::clone(&context), &address), ] { match result { Ok(meta_aspects) => meta_aspects.into_iter().for_each(|a| { diff --git a/crates/core/src/network/handler/lists.rs b/crates/core/src/network/handler/lists.rs index d51f4f3a9c..db5b5e10cb 100644 --- a/crates/core/src/network/handler/lists.rs +++ b/crates/core/src/network/handler/lists.rs @@ -9,7 +9,7 @@ use crate::{ entry_aspect::EntryAspect, handler::{entry_to_meta_aspect, get_content_aspect}, }, - NEW_RELIC_LICENSE_KEY, + }; use holochain_persistence_api::cas::content::{Address, AddressableContent}; use im::HashSet; @@ -20,7 +20,7 @@ use lib3h_protocol::{ use std::sync::Arc; #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn handle_get_authoring_list(get_list_data: GetListData, context: Arc) { let c = context.clone(); let closure = async move || { @@ -39,7 +39,7 @@ pub fn handle_get_authoring_list(get_list_data: GetListData, context: Arc) -> AspectMap { let mut address_map: AspectMapBare = AspectMapBare::new(); for entry_address in get_all_public_chain_entries(context.clone()) { @@ -111,7 +111,7 @@ fn create_authoring_map(context: Arc) -> AspectMap { address_map.into() } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn get_all_public_chain_entries(context: Arc) -> Vec
{ let chain = context.state().unwrap().agent().iter_chain(); chain @@ -120,7 +120,7 @@ fn get_all_public_chain_entries(context: Arc) -> Vec
{ .collect() } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn handle_get_gossip_list(get_list_data: GetListData, context: Arc) { let c = context.clone(); let closure = async move || { diff --git a/crates/core/src/network/handler/mod.rs b/crates/core/src/network/handler/mod.rs index 3e38bbf62b..71e740ef8a 100644 --- a/crates/core/src/network/handler/mod.rs +++ b/crates/core/src/network/handler/mod.rs @@ -1,6 +1,6 @@ use crate::{ agent::state::create_entry_with_header_for_header, content_store::GetContent, - NEW_RELIC_LICENSE_KEY, + }; use holochain_logging::prelude::*; #[autotrace] @@ -131,7 +131,7 @@ fn handle_failure_result( /// Creates the network handler. /// The returned closure is called by the network thread for every network event that core /// has to handle. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn create_handler(c: &Arc, my_dna_address: String) -> NetHandler { let context = c.clone(); NetHandler::new(Box::new(move |message| { @@ -185,7 +185,7 @@ pub fn create_handler(c: &Arc, my_dna_address: String) -> NetHandler { "net/handle: HandleFetchEntry: {:?}", fetch_entry_data ); - handle_fetch_entry(fetch_entry_data, context.clone()) + handle_fetch_entry(Arc::clone(&context), fetch_entry_data) } Lib3hServerProtocol::FetchEntryResult(fetch_result_data) => { if !is_my_dna( @@ -303,7 +303,7 @@ pub fn create_handler(c: &Arc, my_dna_address: String) -> NetHandler { /// NB: this can be optimized by starting with a CAS lookup for the entry directly, /// to avoid traversing the chain unnecessarily in the case of a miss /// (https://github.com/holochain/holochain-rust/pull/1727#discussion_r330258624) -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn get_content_aspect( entry_address: &Address, context: Arc, @@ -394,7 +394,7 @@ fn get_content_aspect( /// base address to which it is meta, if the entry is the source entry of a meta aspect, /// i.e. a CRUD or link entry. /// If the entry is not that it returns None. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn entry_to_meta_aspect(entry: Entry, header: ChainHeader) -> Option<(Address, EntryAspect)> { match entry { Entry::App(app_type, app_value) => header.link_update_delete().map(|updated_entry| { @@ -419,7 +419,7 @@ fn entry_to_meta_aspect(entry: Entry, header: ChainHeader) -> Option<(Address, E } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn get_meta_aspects_from_chain( entry_address: &Address, context: Arc, @@ -454,10 +454,10 @@ fn get_meta_aspects_from_chain( .collect::>()) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn get_meta_aspects_from_dht_eav( - entry_address: &Address, context: Arc, + entry_address: &Address, ) -> Result, HolochainError> { let eavis = context .state() @@ -476,7 +476,7 @@ fn get_meta_aspects_from_dht_eav( .map(|eavi| { let value_entry = context .block_on(get_entry_with_meta_workflow( - &context, + Arc::clone(&context), &eavi.value(), &Timeout::default(), ))? diff --git a/crates/core/src/network/handler/query.rs b/crates/core/src/network/handler/query.rs index 654a9e5f7c..614c639361 100644 --- a/crates/core/src/network/handler/query.rs +++ b/crates/core/src/network/handler/query.rs @@ -8,7 +8,7 @@ use crate::{ }, nucleus, workflows::get_entry_result::get_entry_result_workflow, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::{ crud_status::CrudStatus, @@ -19,17 +19,16 @@ use holochain_core_types::{ }; use holochain_json_api::json::JsonString; use holochain_persistence_api::cas::content::Address; -use holochain_wasm_utils::api_serialization::get_entry::{ +use holochain_wasm_types::get_entry::{ GetEntryArgs, GetEntryOptions, GetEntryResultType, }; use lib3h_protocol::data_types::{QueryEntryData, QueryEntryResultData}; use std::{convert::TryInto, sync::Arc}; pub type LinkTag = String; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn get_links( - context: &Arc, + context: Arc, base: Address, link_type: String, tag: String, @@ -78,7 +77,7 @@ fn get_links( context .block_on(get_entry_result_workflow( - &context.clone(), + Arc::clone(&context), &link_add_entry_args, )) .map(|get_entry_result| match get_entry_result.result { @@ -140,9 +139,9 @@ fn get_links( } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -fn get_entry(context: &Arc, address: Address) -> Option { - nucleus::actions::get_entry::get_entry_with_meta(&context, address.clone()) +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +fn get_entry(context: Arc, address: Address) -> Option { + nucleus::actions::get_entry::get_entry_with_meta(Arc::clone(&context), address.clone()) .map(|entry_with_meta_opt| { let state = context .state() @@ -179,14 +178,14 @@ fn get_entry(context: &Arc, address: Address) -> Option) { let query_json = JsonString::from_json(&std::str::from_utf8(&*query_data.query.clone()).unwrap()); let action_wrapper = match query_json.clone().try_into() { Ok(NetworkQuery::GetLinks(link_type, tag, options, query)) => { match get_links( - &context, + Arc::clone(&context), query_data.entry_address.clone().into(), link_type.clone(), tag.clone(), @@ -215,7 +214,7 @@ pub fn handle_query_entry_data(query_data: QueryEntryData, context: Arc } } Ok(NetworkQuery::GetEntry) => { - let maybe_entry = get_entry(&context, query_data.entry_address.clone().into()); + let maybe_entry = get_entry(Arc::clone(&context), query_data.entry_address.clone().into()); let respond_get = NetworkQueryResult::Entry(maybe_entry); ActionWrapper::new(Action::RespondQuery((query_data, respond_get))) } @@ -235,7 +234,7 @@ pub fn handle_query_entry_data(query_data: QueryEntryData, context: Arc /// The network comes back with a result to our previous query with a result, so we /// examine the query result for its type and dispatch different actions according to variant #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn handle_query_entry_result(query_result_data: QueryEntryResultData, context: Arc) { let query_result_json = JsonString::from_json( std::str::from_utf8(&*query_result_data.clone().query_result).unwrap(), diff --git a/crates/core/src/network/handler/send.rs b/crates/core/src/network/handler/send.rs index c7a0b41cf7..eb48c35ce9 100644 --- a/crates/core/src/network/handler/send.rs +++ b/crates/core/src/network/handler/send.rs @@ -7,7 +7,7 @@ use crate::{ handle_custom_direct_message::handle_custom_direct_message, respond_validation_package_request::respond_validation_package_request, }, - NEW_RELIC_LICENSE_KEY, + }; use std::sync::Arc; @@ -16,7 +16,7 @@ use lib3h_protocol::data_types::DirectMessageData; use std::convert::TryFrom; #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn parse_direct_message(content: &[u8]) -> Result { DirectMessage::try_from(JsonString::from_json( std::str::from_utf8(content) @@ -27,7 +27,7 @@ fn parse_direct_message(content: &[u8]) -> Result { /// We got a ProtocolWrapper::SendMessage, this means somebody initiates message roundtrip /// -> we are being called #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn handle_send_message(message_data: DirectMessageData, context: Arc) { let message = match parse_direct_message(&*message_data.content.clone()) { Ok(message) => message, @@ -88,7 +88,7 @@ pub fn handle_send_message(message_data: DirectMessageData, context: Arc) { let response = match parse_direct_message(&message_data.content.clone()) { Ok(message) => message, diff --git a/crates/core/src/network/handler/store.rs b/crates/core/src/network/handler/store.rs index dc7d0488f6..aa5dc479db 100644 --- a/crates/core/src/network/handler/store.rs +++ b/crates/core/src/network/handler/store.rs @@ -4,7 +4,7 @@ use crate::{ actions::queue_holding_workflow::dispatch_queue_holding_workflow, pending_validations::PendingValidationStruct, }, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::network::entry_aspect::EntryAspect; use holochain_json_api::json::JsonString; @@ -16,7 +16,7 @@ use std::{ /// The network requests us to store (i.e. hold) the given entry aspect data. #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn handle_store(dht_data: StoreEntryAspectData, context: Arc) { let aspect_json = JsonString::from_json(std::str::from_utf8(&*dht_data.entry_aspect.aspect).unwrap()); @@ -48,7 +48,7 @@ pub fn handle_store(dht_data: StoreEntryAspectData, context: Arc) { "net/handle: handle_store: Adding {} to holding queue...", pending.workflow, ); - dispatch_queue_holding_workflow(Arc::new(pending), None, context); + dispatch_queue_holding_workflow(Arc::clone(&context), Arc::new(pending), None); } } } else { @@ -59,83 +59,3 @@ pub fn handle_store(dht_data: StoreEntryAspectData, context: Arc) { ) } } - -/* -/// The network requests us to store meta information (links/CRUD/etc) for an -/// entry that we hold. -pub fn handle_store_meta(dht_meta_data: DhtMetaData, context: Arc) { - let attr = dht_meta_data.clone().attribute; - // @TODO: If network crates will switch to using the `Attribute` enum, - // we can match on the enum directly - if attr == Attribute::Link.to_string() { - log_debug!(context, "net/handle: HandleStoreMeta: got LINK. processing..."); - // TODO: do a loop on content once links properly implemented - assert_eq!(dht_meta_data.content_list.len(), 1); - let entry_with_header: EntryWithHeader = serde_json::from_str( - &serde_json::to_string(&dht_meta_data.content_list[0]) - .expect("dht_meta_data should be EntryWithHeader"), - ) - .expect("dht_meta_data should be EntryWithHeader"); - thread::spawn(move || { - match context.block_on(hold_link_workflow(&entry_with_header, &context.clone())) { - Err(error) => log_error!(context, "net/dht: {}", error), - _ => (), - } - }); - } else if attr == Attribute::LinkRemove.to_string() { - log_debug!(context, "net/handle: HandleStoreMeta: got LINK REMOVAL. processing..."); - // TODO: do a loop on content once links properly implemented - assert_eq!(dht_meta_data.content_list.len(), 1); - let entry_with_header: EntryWithHeader = serde_json::from_str( - //should be careful doing slice access, it might panic - &serde_json::to_string(&dht_meta_data.content_list[0]) - .expect("dht_meta_data should be EntryWithHader"), - ) - .expect("dht_meta_data should be EntryWithHader"); - thread::spawn(move || { - if let Err(error) = - context.block_on(remove_link_workflow(&entry_with_header, &context.clone())) - { - log_error!(context, "net/dht: {}", error) - } - }); - } else if CrudStatus::from_str(&attr) - .expect("Could not convert deleted attribute to CrudStatus") - == CrudStatus::Deleted - { - log_debug!(context, "net/handle: HandleStoreMeta: got CRUD STATUS. processing..."); - - let entry_with_header: EntryWithHeader = serde_json::from_str( - //should be careful doing slice access, it might panic - &serde_json::to_string(&dht_meta_data.content_list[0]) - .expect("dht_meta_data should be EntryWithHader"), - ) - .expect("dht_meta_data should be EntryWithHader"); - thread::spawn(move || { - if let Err(error) = - context.block_on(hold_remove_workflow(entry_with_header, context.clone())) - { - log_error!(context, "net/dht: {}", error) - } - }); - } else if CrudStatus::from_str(&attr) - .expect("Could not convert modified attribute to CrudStatus") - == CrudStatus::Modified - { - log_debug!(context, "net/handle: HandleStoreMeta: got CRUD LINK. processing..."); - let entry_with_header: EntryWithHeader = serde_json::from_str( - //should be careful doing slice access, it might panic - &serde_json::to_string(&dht_meta_data.content_list[0]) - .expect("dht_meta_data should be EntryWithHader"), - ) - .expect("dht_meta_data should be EntryWithHader"); - thread::spawn(move || { - if let Err(error) = - context.block_on(hold_update_workflow(entry_with_header, context.clone())) - { - log_error!(context, "net/dht: {}", error) - } - }); - } -} -*/ diff --git a/crates/core/src/network/mod.rs b/crates/core/src/network/mod.rs index 9a48c68221..4f026097ab 100644 --- a/crates/core/src/network/mod.rs +++ b/crates/core/src/network/mod.rs @@ -37,7 +37,7 @@ pub mod tests { }; use holochain_json_api::json::JsonString; use holochain_persistence_api::cas::content::{Address, AddressableContent}; - use holochain_wasm_utils::api_serialization::get_links::GetLinksArgs; + use holochain_wasm_types::get_links::GetLinksArgs; use test_utils::*; // TODO: Bring the old in-memory network up to speed and turn on this test again! @@ -145,7 +145,7 @@ pub mod tests { ..Default::default() }, }; - let result = context1.block_on(get_entry_result_workflow(&context1, &args)); + let result = context1.block_on(get_entry_result_workflow(Arc::clone(&context1), &args)); if let GetEntryResultType::Single(item) = result.unwrap().result { let headers = item.headers; assert_eq!(headers, vec![header1, header2]); diff --git a/crates/core/src/network/reducers/clear.rs b/crates/core/src/network/reducers/clear.rs index 21b5fcf913..0d96988ad5 100644 --- a/crates/core/src/network/reducers/clear.rs +++ b/crates/core/src/network/reducers/clear.rs @@ -2,10 +2,10 @@ use crate::{ action::{Action, ActionWrapper}, network::state::NetworkState, state::State, - NEW_RELIC_LICENSE_KEY, + }; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_clear_query_result( network_state: &mut NetworkState, _root_state: &State, @@ -16,7 +16,7 @@ pub fn reduce_clear_query_result( network_state.get_query_results.remove(query_key); } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_clear_validation_package_result( network_state: &mut NetworkState, _root_state: &State, @@ -27,7 +27,7 @@ pub fn reduce_clear_validation_package_result( network_state.get_validation_package_results.remove(address); } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_clear_custom_send_response( network_state: &mut NetworkState, _root_state: &State, diff --git a/crates/core/src/network/reducers/clear_action_response.rs b/crates/core/src/network/reducers/clear_action_response.rs index 59a109d664..b767d18fa1 100644 --- a/crates/core/src/network/reducers/clear_action_response.rs +++ b/crates/core/src/network/reducers/clear_action_response.rs @@ -2,10 +2,10 @@ use crate::{ action::{Action, ActionWrapper}, network::state::NetworkState, state::State, - NEW_RELIC_LICENSE_KEY, + }; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_clear_action_response( network_state: &mut NetworkState, _root_state: &State, diff --git a/crates/core/src/network/reducers/get_validation_package.rs b/crates/core/src/network/reducers/get_validation_package.rs index e0ffbba76a..33c4239097 100644 --- a/crates/core/src/network/reducers/get_validation_package.rs +++ b/crates/core/src/network/reducers/get_validation_package.rs @@ -2,7 +2,7 @@ use crate::{ action::ActionWrapper, network::{direct_message::DirectMessage, reducers::send_message, state::NetworkState}, state::State, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::{chain_header::ChainHeader, error::HolochainError}; use std::time::{Duration, SystemTime}; @@ -11,7 +11,7 @@ use std::time::{Duration, SystemTime}; // Should probably also be configurable via config or env vars const GET_VALIDATION_PACKAGE_MESSAGE_TIMEOUT_MS: u64 = 10000; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn inner(network_state: &mut NetworkState, header: &ChainHeader) -> Result<(), HolochainError> { network_state.initialized()?; @@ -24,7 +24,7 @@ fn inner(network_state: &mut NetworkState, header: &ChainHeader) -> Result<(), H send_message(network_state, source_address, direct_message) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_get_validation_package( network_state: &mut NetworkState, _root_state: &State, @@ -51,7 +51,7 @@ pub fn reduce_get_validation_package( .get_validation_package_timeouts .insert(entry_address, timeout); } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_get_validation_package_timeout( network_state: &mut NetworkState, _root_state: &State, diff --git a/crates/core/src/network/reducers/handle_custom_send_response.rs b/crates/core/src/network/reducers/handle_custom_send_response.rs index 5b19de33a3..5ce747a1a5 100644 --- a/crates/core/src/network/reducers/handle_custom_send_response.rs +++ b/crates/core/src/network/reducers/handle_custom_send_response.rs @@ -1,10 +1,10 @@ use crate::{ - action::ActionWrapper, network::state::NetworkState, state::State, NEW_RELIC_LICENSE_KEY, + action::ActionWrapper, network::state::NetworkState, state::State, }; use holochain_core_types::error::HolochainError; #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_handle_custom_send_response( network_state: &mut NetworkState, _root_state: &State, diff --git a/crates/core/src/network/reducers/handle_get_result.rs b/crates/core/src/network/reducers/handle_get_result.rs index ccbfb1e18f..00e158ecf6 100644 --- a/crates/core/src/network/reducers/handle_get_result.rs +++ b/crates/core/src/network/reducers/handle_get_result.rs @@ -1,7 +1,7 @@ use crate::{ - action::ActionWrapper, network::state::NetworkState, state::State, NEW_RELIC_LICENSE_KEY, + action::ActionWrapper, network::state::NetworkState, state::State, }; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_handle_get_result( network_state: &mut NetworkState, _root_state: &State, diff --git a/crates/core/src/network/reducers/handle_get_validation_package.rs b/crates/core/src/network/reducers/handle_get_validation_package.rs index 50f1a0a6d6..e4fe189b21 100644 --- a/crates/core/src/network/reducers/handle_get_validation_package.rs +++ b/crates/core/src/network/reducers/handle_get_validation_package.rs @@ -1,8 +1,8 @@ use crate::{ - action::ActionWrapper, network::state::NetworkState, state::State, NEW_RELIC_LICENSE_KEY, + action::ActionWrapper, network::state::NetworkState, state::State, }; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_handle_get_validation_package( network_state: &mut NetworkState, _root_state: &State, diff --git a/crates/core/src/network/reducers/init.rs b/crates/core/src/network/reducers/init.rs index 6672d3e3ee..57fc68a385 100644 --- a/crates/core/src/network/reducers/init.rs +++ b/crates/core/src/network/reducers/init.rs @@ -2,7 +2,7 @@ use crate::{ action::{Action, ActionWrapper}, network::state::NetworkState, state::State, - NEW_RELIC_LICENSE_KEY, + }; use holochain_net::{ connection::net_connection::NetSend, p2p_config::BackendConfig, p2p_network::P2pNetwork, @@ -12,7 +12,7 @@ use lib3h_protocol::{data_types::SpaceData, protocol_client::Lib3hClientProtocol use log::{debug, error, info}; #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_init(state: &mut NetworkState, root_state: &State, action_wrapper: &ActionWrapper) { let action = action_wrapper.action(); let network_settings = unwrap_to!(action => Action::InitNetwork); diff --git a/crates/core/src/network/reducers/mod.rs b/crates/core/src/network/reducers/mod.rs index 4b6d1f0f31..e237bc31fa 100644 --- a/crates/core/src/network/reducers/mod.rs +++ b/crates/core/src/network/reducers/mod.rs @@ -45,7 +45,7 @@ use crate::{ state::NetworkState, }, state::State, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::error::HolochainError; use holochain_json_api::json::JsonString; @@ -64,7 +64,7 @@ use std::sync::Arc; /// maps incoming action to the correct handler #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn resolve_reducer(action_wrapper: &ActionWrapper) -> Option { match action_wrapper.action() { Action::ClearActionResponse(_) => Some(reduce_clear_action_response), @@ -95,7 +95,7 @@ fn resolve_reducer(action_wrapper: &ActionWrapper) -> Option { } #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce( old_state: Arc, root_state: &State, @@ -115,7 +115,7 @@ pub fn reduce( /// Sends the given Lib3hClientProtocol over the network using the network proxy instance /// that lives in the NetworkState. #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn send( network_state: &mut NetworkState, msg: Lib3hClientProtocol, @@ -142,7 +142,7 @@ pub fn send( /// request-response pattern. This function therefore logs the open connection /// (expecting a response) in network_state.direct_message_connections. #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn send_message( network_state: &mut NetworkState, to_agent_id: &Address, diff --git a/crates/core/src/network/reducers/prune.rs b/crates/core/src/network/reducers/prune.rs index 433012980c..91d27be804 100644 --- a/crates/core/src/network/reducers/prune.rs +++ b/crates/core/src/network/reducers/prune.rs @@ -2,11 +2,11 @@ use crate::{ action::{Action, ActionWrapper}, network::state::NetworkState, state::{State, ACTION_PRUNE_MS}, - NEW_RELIC_LICENSE_KEY, + }; use std::time::Duration; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_prune( network_state: &mut NetworkState, _root_state: &State, diff --git a/crates/core/src/network/reducers/publish.rs b/crates/core/src/network/reducers/publish.rs index 38ebd1a683..4f60b3b920 100644 --- a/crates/core/src/network/reducers/publish.rs +++ b/crates/core/src/network/reducers/publish.rs @@ -8,7 +8,7 @@ use crate::{ state::NetworkState, }, state::State, - NEW_RELIC_LICENSE_KEY, + }; use chrono::{offset::FixedOffset, DateTime}; use holochain_core_types::{ @@ -25,7 +25,7 @@ use lib3h_protocol::{ use crate::network::actions::Response; use holochain_persistence_api::cas::content::{Address, AddressableContent}; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn entry_data_to_entry_aspect_data(ea: &EntryAspect) -> EntryAspectData { let type_hint = ea.type_hint(); let aspect_address = ea.address(); @@ -40,7 +40,7 @@ pub fn entry_data_to_entry_aspect_data(ea: &EntryAspect) -> EntryAspectData { } /// Send to network a PublishDhtData message -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn publish_entry( network_state: &mut NetworkState, entry_with_header: &EntryWithHeader, @@ -62,7 +62,7 @@ fn publish_entry( } /// Send to network a publish request for either delete or update aspect information -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn publish_update_delete_meta( network_state: &mut NetworkState, orig_entry_address: Address, @@ -102,7 +102,7 @@ fn publish_update_delete_meta( } /// Send to network a PublishMeta message holding a link metadata to `entry_with_header` -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn publish_link_meta( network_state: &mut NetworkState, entry_with_header: &EntryWithHeader, @@ -139,7 +139,7 @@ fn publish_link_meta( ) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn reduce_publish_inner( network_state: &mut NetworkState, root_state: &State, @@ -184,7 +184,7 @@ fn reduce_publish_inner( } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_publish( network_state: &mut NetworkState, root_state: &State, diff --git a/crates/core/src/network/reducers/publish_header_entry.rs b/crates/core/src/network/reducers/publish_header_entry.rs index 59a377955c..dcfab31f67 100644 --- a/crates/core/src/network/reducers/publish_header_entry.rs +++ b/crates/core/src/network/reducers/publish_header_entry.rs @@ -9,7 +9,7 @@ use crate::{ state::NetworkState, }, state::State, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::{chain_header::ChainHeader, error::HolochainError}; use lib3h_protocol::{ @@ -22,7 +22,7 @@ use holochain_persistence_api::cas::content::{Address, AddressableContent}; /// Send to network a request to publish a header entry alone /// This is similar to publishing a regular entry but it has its own special dummy header. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn publish_header( network_state: &mut NetworkState, root_state: &State, @@ -45,7 +45,7 @@ fn publish_header( ) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn reduce_publish_header_entry_inner( network_state: &mut NetworkState, root_state: &State, @@ -56,7 +56,7 @@ fn reduce_publish_header_entry_inner( publish_header(network_state, root_state, entry_with_header.header) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_publish_header_entry( network_state: &mut NetworkState, root_state: &State, diff --git a/crates/core/src/network/reducers/query.rs b/crates/core/src/network/reducers/query.rs index 5645b7056b..3e94f6495c 100644 --- a/crates/core/src/network/reducers/query.rs +++ b/crates/core/src/network/reducers/query.rs @@ -2,13 +2,13 @@ use crate::{ action::{ActionWrapper, QueryKey}, network::{query::NetworkQuery, reducers::send, state::NetworkState}, state::State, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::error::HolochainError; use holochain_json_api::json::JsonString; use lib3h_protocol::{data_types::QueryEntryData, protocol_client::Lib3hClientProtocol}; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn reduce_query_inner( network_state: &mut NetworkState, key: QueryKey, @@ -32,7 +32,7 @@ fn reduce_query_inner( ) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_query( network_state: &mut NetworkState, _root_state: &State, @@ -62,7 +62,7 @@ pub fn reduce_query( } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_query_timeout( network_state: &mut NetworkState, _root_state: &State, diff --git a/crates/core/src/network/reducers/resolve_direct_connection.rs b/crates/core/src/network/reducers/resolve_direct_connection.rs index 458ecb02e9..94d1dc17b8 100644 --- a/crates/core/src/network/reducers/resolve_direct_connection.rs +++ b/crates/core/src/network/reducers/resolve_direct_connection.rs @@ -1,8 +1,8 @@ use crate::{ - action::ActionWrapper, network::state::NetworkState, state::State, NEW_RELIC_LICENSE_KEY, + action::ActionWrapper, network::state::NetworkState, state::State, }; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_resolve_direct_connection( network_state: &mut NetworkState, _root_state: &State, diff --git a/crates/core/src/network/reducers/respond_authoring_list.rs b/crates/core/src/network/reducers/respond_authoring_list.rs index 3cc6fa81b3..6b0c7bade2 100644 --- a/crates/core/src/network/reducers/respond_authoring_list.rs +++ b/crates/core/src/network/reducers/respond_authoring_list.rs @@ -2,11 +2,11 @@ use crate::{ action::ActionWrapper, network::{reducers::send, state::NetworkState}, state::State, - NEW_RELIC_LICENSE_KEY, + }; use lib3h_protocol::protocol_client::Lib3hClientProtocol; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_respond_authoring_list( network_state: &mut NetworkState, _root_state: &State, diff --git a/crates/core/src/network/reducers/respond_fetch.rs b/crates/core/src/network/reducers/respond_fetch.rs index 9b8f549e86..01fc7cccd0 100644 --- a/crates/core/src/network/reducers/respond_fetch.rs +++ b/crates/core/src/network/reducers/respond_fetch.rs @@ -7,7 +7,7 @@ use crate::{ state::NetworkState, }, state::State, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::error::HolochainError; @@ -19,7 +19,7 @@ use lib3h_protocol::{ /// Send back to network a HandleFetchEntryResult, no matter what. /// Will return an empty content field if it actually doesn't have the data. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn reduce_respond_fetch_data_inner( network_state: &mut NetworkState, fetch_data: &FetchEntryData, @@ -43,7 +43,7 @@ fn reduce_respond_fetch_data_inner( ) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_respond_fetch_data( network_state: &mut NetworkState, _root_state: &State, diff --git a/crates/core/src/network/reducers/respond_gossip_list.rs b/crates/core/src/network/reducers/respond_gossip_list.rs index df2c47e5b8..aa02c22ac6 100644 --- a/crates/core/src/network/reducers/respond_gossip_list.rs +++ b/crates/core/src/network/reducers/respond_gossip_list.rs @@ -2,11 +2,11 @@ use crate::{ action::ActionWrapper, network::{reducers::send, state::NetworkState}, state::State, - NEW_RELIC_LICENSE_KEY, + }; use lib3h_protocol::protocol_client::Lib3hClientProtocol; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_respond_gossip_list( network_state: &mut NetworkState, _root_state: &State, diff --git a/crates/core/src/network/reducers/respond_query.rs b/crates/core/src/network/reducers/respond_query.rs index c6a7a3bd26..65674e5f9b 100644 --- a/crates/core/src/network/reducers/respond_query.rs +++ b/crates/core/src/network/reducers/respond_query.rs @@ -7,7 +7,7 @@ use crate::{ state::NetworkState, }, state::State, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::error::HolochainError; use holochain_json_api::json::JsonString; @@ -16,7 +16,7 @@ use lib3h_protocol::{ protocol_client::Lib3hClientProtocol, }; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn reduce_respond_query_inner( network_state: &mut NetworkState, network_query_result: &NetworkQueryResult, diff --git a/crates/core/src/network/reducers/send_direct_message.rs b/crates/core/src/network/reducers/send_direct_message.rs index 1fc9fe2319..6dadab3313 100644 --- a/crates/core/src/network/reducers/send_direct_message.rs +++ b/crates/core/src/network/reducers/send_direct_message.rs @@ -2,7 +2,7 @@ use crate::{ action::{ActionWrapper, DirectMessageData}, network::{reducers::send, state::NetworkState}, state::State, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::error::HolochainError; use holochain_json_api::json::JsonString; @@ -11,7 +11,7 @@ use lib3h_protocol::{ }; #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn inner( network_state: &mut NetworkState, direct_message_data: &DirectMessageData, @@ -41,7 +41,7 @@ fn inner( } #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_send_direct_message( network_state: &mut NetworkState, _root_state: &State, @@ -59,7 +59,7 @@ pub fn reduce_send_direct_message( } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_send_direct_message_timeout( network_state: &mut NetworkState, _root_state: &State, diff --git a/crates/core/src/network/reducers/shutdown.rs b/crates/core/src/network/reducers/shutdown.rs index d616533fb5..9d651f5d39 100644 --- a/crates/core/src/network/reducers/shutdown.rs +++ b/crates/core/src/network/reducers/shutdown.rs @@ -2,7 +2,7 @@ use crate::{ action::{Action, ActionWrapper}, network::state::NetworkState, state::State, - NEW_RELIC_LICENSE_KEY, + }; use holochain_net::connection::net_connection::NetSend; @@ -12,7 +12,7 @@ use log::error; use std::{thread::sleep, time::Duration}; #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_shutdown( state: &mut NetworkState, _root_state: &State, diff --git a/crates/core/src/network/state.rs b/crates/core/src/network/state.rs index 0dffbf2104..f5d7d1839f 100644 --- a/crates/core/src/network/state.rs +++ b/crates/core/src/network/state.rs @@ -1,7 +1,7 @@ use crate::{ action::{ActionWrapper, QueryKey}, network::{actions::Response, direct_message::DirectMessage, query::NetworkQueryResult}, - NEW_RELIC_LICENSE_KEY, + }; use boolinator::*; use holochain_core_types::{error::HolochainError, validation::ValidationPackage}; @@ -58,7 +58,7 @@ impl PartialEq for NetworkState { } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl NetworkState { pub fn new() -> Self { NetworkState { diff --git a/crates/core/src/nucleus/actions/build_validation_package.rs b/crates/core/src/nucleus/actions/build_validation_package.rs index 30854aad22..96c91a29ec 100644 --- a/crates/core/src/nucleus/actions/build_validation_package.rs +++ b/crates/core/src/nucleus/actions/build_validation_package.rs @@ -1,28 +1,29 @@ use crate::{ agent::{self, find_chain_header}, content_store::GetContent, + workflows::{ + callback::validation_package::get_validation_package_definition, + }, context::Context, entry::CanPublish, state::{State, StateWrapper}, - wasm_engine::callback::{ - validation_package::get_validation_package_definition, CallbackResult, - }, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::{ + callback::CallbackResult, chain_header::ChainHeader, entry::{entry_type::EntryType, Entry}, error::HolochainError, signature::Provenance, - validation::{ValidationPackage, ValidationPackageDefinition::*}, + validation::{ValidationPackage, ValidationPackageDefinition::*, ValidationResult}, }; use std::{sync::Arc, vec::Vec}; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn build_validation_package<'a>( - entry: &'a Entry, +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub fn build_validation_package( context: Arc, - provenances: &'a Vec, + entry: &Entry, + provenances: &Vec, ) -> Result { match entry.entry_type() { EntryType::App(app_entry_type) => { @@ -35,10 +36,10 @@ pub fn build_validation_package<'a>( .get_zome_name_for_app_entry_type(&app_entry_type) .is_none() { - return Err(HolochainError::ValidationFailed(format!( + return Err(HolochainError::ValidationFailed(ValidationResult::Fail(format!( "Unknown app entry type '{}'", String::from(app_entry_type), - ))); + )))); } } @@ -62,10 +63,10 @@ pub fn build_validation_package<'a>( // FIXME } _ => { - return Err(HolochainError::ValidationFailed(format!( + return Err(HolochainError::ValidationFailed(ValidationResult::Fail(format!( "Attempted to validate system entry type {:?}", entry.entry_type(), - ))); + )))); } }; @@ -103,7 +104,7 @@ pub fn build_validation_package<'a>( Some(entry_header) => entry_header, }; - get_validation_package_definition(&entry, context.clone()) + get_validation_package_definition(Arc::clone(&context), &entry) .and_then(|callback_result| match callback_result { CallbackResult::Fail(error_string) => Err(HolochainError::ErrorGeneric(error_string)), CallbackResult::ValidationPackageDefinition(def) => Ok(def), @@ -151,7 +152,7 @@ pub fn build_validation_package<'a>( } // given a slice of headers return the entries for those marked public -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn public_chain_entries_from_headers( context: &Arc, headers: &[ChainHeader], @@ -172,7 +173,7 @@ fn public_chain_entries_from_headers( .collect::>() } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn all_chain_headers_before_header( context: &Arc, header: &ChainHeader, @@ -205,7 +206,7 @@ mod tests { let chain_header = commit(test_entry_package_entry(), &context); let maybe_validation_package = - build_validation_package(&test_entry_package_entry(), context.clone(), &vec![]); + build_validation_package(Arc::clone(&context), &test_entry_package_entry(), &vec![]); println!("{:?}", maybe_validation_package); assert!(maybe_validation_package.is_ok()); @@ -231,8 +232,8 @@ mod tests { let chain_header = commit(test_entry_package_chain_entries(), &context); let maybe_validation_package = build_validation_package( + Arc::clone(&context), &test_entry_package_chain_entries(), - context.clone(), &vec![], ); println!("{:?}", maybe_validation_package); @@ -263,8 +264,8 @@ mod tests { let chain_header = commit(test_entry_package_chain_headers(), &context); let maybe_validation_package = build_validation_package( + Arc::clone(&context), &test_entry_package_chain_headers(), - context.clone(), &vec![], ); assert!(maybe_validation_package.is_ok()); @@ -291,7 +292,7 @@ mod tests { let chain_header = commit(test_entry_package_chain_full(), &context); let maybe_validation_package = - build_validation_package(&test_entry_package_chain_full(), context.clone(), &vec![]); + build_validation_package(Arc::clone(&context), &test_entry_package_chain_full(), &vec![]); assert!(maybe_validation_package.is_ok()); let headers = all_chain_headers_before_header(&context, &chain_header); diff --git a/crates/core/src/nucleus/actions/call_init.rs b/crates/core/src/nucleus/actions/call_init.rs index 17707abdc1..dddcdd84e1 100644 --- a/crates/core/src/nucleus/actions/call_init.rs +++ b/crates/core/src/nucleus/actions/call_init.rs @@ -1,16 +1,18 @@ use crate::{ context::Context, - wasm_engine::callback::{init::init, CallbackParams, CallbackResult}, - NEW_RELIC_LICENSE_KEY, + wasm_engine::callback::{CallbackParams}, + workflows::{callback::init::init}, + }; use holochain_core_types::{ dna::Dna, error::{HcResult, HolochainError}, + callback::CallbackResult }; use std::sync::Arc; /// Creates a network proxy object and stores DNA and agent hash in the network state. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn call_init(dna: Dna, context: &Arc) -> HcResult<()> { // map init across every zome. Find which zomes init callback errored, if any let errors: Vec<(String, String)> = dna diff --git a/crates/core/src/nucleus/actions/call_zome_function.rs b/crates/core/src/nucleus/actions/call_zome_function.rs index 4215c27fa9..5e09c36d2d 100644 --- a/crates/core/src/nucleus/actions/call_zome_function.rs +++ b/crates/core/src/nucleus/actions/call_zome_function.rs @@ -2,8 +2,8 @@ use crate::{ action::{Action, ActionWrapper}, context::Context, nucleus::{actions::get_entry::get_entry_from_agent_chain, ZomeFnCall, ZomeFnResult}, - wasm_engine::{self, WasmCallData}, - NEW_RELIC_LICENSE_KEY, + wasm_engine::{WasmCallData}, + }; use holochain_core_types::{ dna::{capabilities::CapabilityRequest, wasm::DnaWasm}, @@ -24,8 +24,12 @@ use holochain_dpki::utils::Verify; use crate::instance::dispatch_action; use base64; use futures::{future::Future, task::Poll}; -use holochain_wasm_utils::api_serialization::crypto::CryptoMethod; +use holochain_wasm_types::crypto::CryptoMethod; use std::{pin::Pin, sync::Arc}; +use std::convert::TryFrom; +use holochain_wasmer_host::JsonError; +use holochain_wasmer_host::WasmError; +use wasmer_runtime::Instance; #[derive(Clone, Debug, PartialEq, Hash, Serialize)] pub struct ExecuteZomeFnResponse { @@ -33,7 +37,7 @@ pub struct ExecuteZomeFnResponse { result: ZomeFnResult, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl ExecuteZomeFnResponse { pub fn new(call: ZomeFnCall, result: Result) -> Self { ExecuteZomeFnResponse { call, result } @@ -64,10 +68,10 @@ impl ExecuteZomeFnResponse { /// /// Use Context::block_on to wait for the call result. #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn call_zome_function( - zome_call: ZomeFnCall, context: Arc, + zome_call: ZomeFnCall, ) -> Result { log_debug!( context, @@ -108,7 +112,7 @@ pub async fn call_zome_function( } /// validates that a given zome function call specifies a correct zome function and capability grant -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn validate_call( context: Arc, fn_call: &ZomeFnCall, @@ -146,12 +150,12 @@ pub fn validate_call( } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn is_token_the_agent(context: Arc, request: &CapabilityRequest) -> bool { context.agent_id.pub_sign_key == request.cap_token.to_string() } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn get_grant(context: &Arc, address: &Address) -> Option { match get_entry_from_agent_chain(context, address).ok()?? { Entry::CapTokenGrant(grant) => Some(grant), @@ -161,7 +165,7 @@ fn get_grant(context: &Arc, address: &Address) -> Option /// checks to see if a given function call is allowable according to the capabilities /// that have been registered to callers by looking for grants in the chain. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn check_capability(context: Arc, fn_call: &ZomeFnCall) -> bool { let maybe_grant = get_grant(&context.clone(), &fn_call.cap_token()); match maybe_grant { @@ -170,13 +174,13 @@ pub fn check_capability(context: Arc, fn_call: &ZomeFnCall) -> bool { } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn encode_call_data_for_signing>(function: &str, parameters: J) -> String { base64::encode(&format!("{}:{}", function, parameters.into())) } // temporary function to create a mock signature of for a zome call cap request -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn make_call_sig>( context: Arc, function: &str, @@ -192,7 +196,7 @@ fn make_call_sig>( } // temporary function to verify a mock signature of for a zome call cap request -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn verify_call_sig>( provenance: &Provenance, function: &str, @@ -203,7 +207,7 @@ pub fn verify_call_sig>( } /// creates a capability request for a zome call by signing the function name and parameters -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn make_cap_request_for_call>( callers_context: Arc, cap_token: Address, @@ -218,7 +222,7 @@ pub fn make_cap_request_for_call>( } /// verifies that this grant is valid for a given requester and token value -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn verify_grant(context: Arc, grant: &CapTokenGrant, fn_call: &ZomeFnCall) -> bool { let cap_functions = grant.functions(); let maybe_zome_grants = cap_functions.get(&fn_call.zome_name); @@ -285,22 +289,47 @@ pub fn verify_grant(context: Arc, grant: &CapTokenGrant, fn_call: &Zome } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn spawn_zome_function(context: Arc, zome_call: ZomeFnCall) { + // this is a hack for backwards compatibility + struct CallResult(JsonString); + + impl TryFrom for CallResult { + type Error = JsonError; + fn try_from(j: JsonString) -> Result { + Ok(CallResult(j)) + } + } + std::thread::Builder::new() .name(format!("{:?}", zome_call)) .spawn(move || { // Have Ribosome spin up DNA and call the zome function - let call_result = wasm_engine::run_dna( - Some(zome_call.clone().parameters.to_bytes()), - WasmCallData::new_zome_call(context.clone(), zome_call.clone()), - ); + let call_data = WasmCallData::new_zome_call(context.clone(), zome_call.clone()); + let maybe_instance: Result = call_data.instance(); + + let call_result: ZomeFnResult = match maybe_instance { + Err(e) => Err(e), + Ok(mut instance) => { + let call_result_hack: Result = holochain_wasmer_host::guest::call( + &mut instance, + &call_data.fn_name(), + zome_call.clone().parameters, + ); + match call_result_hack { + Ok(call_result) => Ok(call_result.0), + Err(e) => Err(HolochainError::Wasm(e)), + } + }, + }; + log_debug!( context, "actions/call_zome_fn: got call_result from ribosome::run_dna." ); // Construct response let response = ExecuteZomeFnResponse::new(zome_call, call_result); + // Send ReturnZomeFunctionResult Action log_debug!( context, @@ -328,7 +357,7 @@ pub struct CallResultFuture { } impl Unpin for CallResultFuture {} -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Future for CallResultFuture { type Output = Result; @@ -450,7 +479,7 @@ pub mod tests { .unwrap(); let grant_entry = Entry::CapTokenGrant(grant.clone()); let grant_addr = context - .block_on(author_entry(&grant_entry, None, &context, &vec![])) + .block_on(author_entry(Arc::clone(&context), &grant_entry, None, &vec![])) .unwrap() .address(); let maybe_grant = get_grant(&context, &grant_addr); diff --git a/crates/core/src/nucleus/actions/get_entry.rs b/crates/core/src/nucleus/actions/get_entry.rs index 00edd8af17..60734ec59a 100644 --- a/crates/core/src/nucleus/actions/get_entry.rs +++ b/crates/core/src/nucleus/actions/get_entry.rs @@ -1,4 +1,4 @@ -use crate::{content_store::GetContent, context::Context, NEW_RELIC_LICENSE_KEY}; +use crate::{content_store::GetContent, context::Context}; use holochain_core_types::{ crud_status::CrudStatus, eav::{Attribute, EaviQuery, EntityAttributeValueIndex}, @@ -8,7 +8,7 @@ use holochain_core_types::{ use holochain_persistence_api::{cas::content::Address, eav::IndexFilter}; use std::{collections::BTreeSet, str::FromStr, sync::Arc}; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn get_entry_from_agent_chain( context: &Arc, address: &Address, @@ -26,17 +26,17 @@ pub fn get_entry_from_agent_chain( agent.chain_store().get(address) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub(crate) fn get_entry_from_dht( - context: &Arc, + context: Arc, address: &Address, ) -> Result, HolochainError> { context.state().unwrap().dht().get(address) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub(crate) fn get_entry_crud_meta_from_dht( - context: &Arc, + context: Arc, address: &Address, ) -> Result)>, HolochainError> { // Get crud-status @@ -98,13 +98,13 @@ pub(crate) fn get_entry_crud_meta_from_dht( Ok(Some((crud_status, maybe_link_update_delete))) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn get_entry_with_meta( - context: &Arc, + context: Arc, address: Address, ) -> Result, HolochainError> { // 1. try to get the entry - let entry = match get_entry_from_dht(context, &address) { + let entry = match get_entry_from_dht(Arc::clone(&context), &address) { Err(err) => return Err(err), Ok(None) => return Ok(None), Ok(Some(entry)) => entry, @@ -112,7 +112,7 @@ pub fn get_entry_with_meta( // 2. try to get the entry's metadata let (crud_status, maybe_link_update_delete) = - match get_entry_crud_meta_from_dht(context, &address)? { + match get_entry_crud_meta_from_dht(Arc::clone(&context), &address)? { Some(crud_info) => crud_info, None => { log_debug!( @@ -140,15 +140,16 @@ pub mod tests { use crate::{content_store::AddContent, instance::tests::test_context_with_state}; use holochain_core_types::entry::test_entry; use holochain_persistence_api::cas::content::AddressableContent; + use std::sync::Arc; #[test] fn test_get_entry_from_dht_cas() { let entry = test_entry(); let context = test_context_with_state(None); - let result = super::get_entry_from_dht(&context, &entry.address()); + let result = super::get_entry_from_dht(Arc::clone(&context), &entry.address()); assert_eq!(Ok(None), result); let _ = (*context.state().unwrap().dht()).clone().add(&entry); - let result = super::get_entry_from_dht(&context, &entry.address()); + let result = super::get_entry_from_dht(Arc::clone(&context), &entry.address()); assert_eq!(Ok(Some(entry.clone())), result); } /* diff --git a/crates/core/src/nucleus/actions/initialize.rs b/crates/core/src/nucleus/actions/initialize.rs index f75c38e0b4..a7475ef671 100644 --- a/crates/core/src/nucleus/actions/initialize.rs +++ b/crates/core/src/nucleus/actions/initialize.rs @@ -3,7 +3,7 @@ use crate::{ agent::actions::commit::commit_entry, context::Context, nucleus::state::NucleusStatus, - NEW_RELIC_LICENSE_KEY, + }; use futures::{future::Future, task::Poll}; use holochain_core_types::{ @@ -29,7 +29,7 @@ pub struct Initialization { payload: Option, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Initialization { pub fn new() -> Initialization { Initialization::default() @@ -52,7 +52,7 @@ const INITIALIZATION_TIMEOUT: u64 = 60; /// /// Use futures::executor::block_on to wait for an initialized instance. #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn initialize_chain( dna: Dna, context: &Arc, @@ -192,7 +192,7 @@ pub struct InitializingFuture { context: Arc, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Future for InitializingFuture { type Output = Result; @@ -230,7 +230,7 @@ pub struct InitializationFuture { created_at: Instant, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Future for InitializationFuture { type Output = Result; diff --git a/crates/core/src/nucleus/actions/mod.rs b/crates/core/src/nucleus/actions/mod.rs index b20e136a1c..daac9803c8 100644 --- a/crates/core/src/nucleus/actions/mod.rs +++ b/crates/core/src/nucleus/actions/mod.rs @@ -4,8 +4,8 @@ pub mod call_zome_function; pub mod get_entry; pub mod initialize; pub mod run_validation_callback; -pub mod trace_invoke_hdk_function; -pub mod trace_return_hdk_function; +pub mod trace_invoke_wasm_api_function; +pub mod trace_return_wasm_api_function; #[cfg(test)] pub mod tests { @@ -28,7 +28,7 @@ pub mod tests { use holochain_json_api::json::RawString; use holochain_persistence_api::cas::content::AddressableContent; - use holochain_wasm_utils::wasm_target_dir; + use crate::wasm_engine::io::wasm_target_dir; use std::{collections::BTreeMap, path::PathBuf, sync::Arc}; use test_utils::*; diff --git a/crates/core/src/nucleus/actions/run_validation_callback.rs b/crates/core/src/nucleus/actions/run_validation_callback.rs index 6b7cc87d8d..dffaae9295 100644 --- a/crates/core/src/nucleus/actions/run_validation_callback.rs +++ b/crates/core/src/nucleus/actions/run_validation_callback.rs @@ -1,16 +1,15 @@ use crate::{ context::Context, nucleus::{ - validation::{ValidationError, ValidationResult}, CallbackFnCall, }, - wasm_engine::{self, runtime::WasmCallData}, - NEW_RELIC_LICENSE_KEY, + wasm_engine::{runtime::WasmCallData}, + // }; -use holochain_core_types::error::HolochainError; +use holochain_core_types::validation::ValidationResult; use holochain_persistence_api::cas::content::Address; use std::sync::Arc; - +use holochain_wasm_types::WasmError; use holochain_metrics::with_latency_publishing; /// Validation callback action creator. @@ -19,11 +18,12 @@ use holochain_metrics::with_latency_publishing; /// Dispatches an `Action::ReturnValidationResult` after completion of the WASM call. /// Returns a future that waits for the result to appear in the nucleus state. #[no_autotrace] // TODO: get autotrace working for this future -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// TODO: uncommenting this causes line numbers to disappear in this file for compiler errors +// // #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn run_validation_callback( + context: Arc, _address: Address, call: CallbackFnCall, - context: &Arc, ) -> ValidationResult { let metric_name_prefix = format!( "run_validation_callback.{}.{}", @@ -36,30 +36,25 @@ pub async fn run_validation_callback( |()| { let cloned_context = context.clone(); - match wasm_engine::run_dna( - Some(call.clone().parameters.to_bytes()), - WasmCallData::new_callback_call(cloned_context, call), + let call_data = WasmCallData::new_callback_call(cloned_context, call.clone()); + match holochain_wasmer_host::guest::call( + &mut call_data.instance().expect(&format!("there is no wasm module for call data: {:?}", &call_data)), + &call_data.fn_name(), + call.clone().parameters, ) { - Ok(call_result) => { - if call_result.is_null() { - Ok(()) - } else { - Err(ValidationError::Fail(call_result.to_string())) - } - } + Ok(v) => v, // TODO: have "not matching schema" be its own error - Err(HolochainError::RibosomeFailed(error_string)) => { - if error_string == "Argument deserialization failed" { - Err(ValidationError::Error( - String::from("JSON object does not match entry schema").into(), - )) + Err(wasm_error) => { + if wasm_error == WasmError::ArgumentDeserializationFailed { + ValidationResult::Fail( + "JSON object does not match entry schema".into() + ) } else { // an unknown error from the ribosome should panic rather than // silently failing validation - panic!(error_string) + panic!(wasm_error) } - } - Err(error) => panic!(error.to_string()), // same here + }, } }, () diff --git a/crates/core/src/nucleus/actions/trace_invoke_hdk_function.rs b/crates/core/src/nucleus/actions/trace_invoke_hdk_function.rs deleted file mode 100644 index 5f0b26eb45..0000000000 --- a/crates/core/src/nucleus/actions/trace_invoke_hdk_function.rs +++ /dev/null @@ -1,18 +0,0 @@ -use crate::{ - action::{Action, ActionWrapper}, - context::Context, - instance::dispatch_action, - nucleus::{HdkFnCall, ZomeFnCall}, -}; -use std::sync::Arc; - -pub fn trace_invoke_hdk_function( - zome_fn_call: ZomeFnCall, - hdk_fn_call: HdkFnCall, - context: &Arc, -) { - dispatch_action( - context.action_channel(), - ActionWrapper::new(Action::TraceInvokeHdkFunction((zome_fn_call, hdk_fn_call))), - ); -} diff --git a/crates/core/src/nucleus/actions/trace_return_hdk_function.rs b/crates/core/src/nucleus/actions/trace_invoke_wasm_api_function.rs similarity index 51% rename from crates/core/src/nucleus/actions/trace_return_hdk_function.rs rename to crates/core/src/nucleus/actions/trace_invoke_wasm_api_function.rs index 1623c84802..a369a2964d 100644 --- a/crates/core/src/nucleus/actions/trace_return_hdk_function.rs +++ b/crates/core/src/nucleus/actions/trace_invoke_wasm_api_function.rs @@ -2,22 +2,20 @@ use crate::{ action::{Action, ActionWrapper}, context::Context, instance::dispatch_action, - nucleus::{HdkFnCall, HdkFnCallResult, ZomeFnCall}, + nucleus::{WasmApiFnCall, ZomeFnCall}, }; use std::sync::Arc; -pub fn trace_return_hdk_function( +pub fn trace_invoke_wasm_api_function( zome_fn_call: ZomeFnCall, - hdk_fn_call: HdkFnCall, - hdk_fn_call_result: HdkFnCallResult, + wasm_api_fn_call: WasmApiFnCall, context: &Arc, ) { dispatch_action( context.action_channel(), - ActionWrapper::new(Action::TraceReturnHdkFunction(( + ActionWrapper::new(Action::TraceInvokeWasmApiFunction(( zome_fn_call, - hdk_fn_call, - hdk_fn_call_result, + wasm_api_fn_call, ))), ); } diff --git a/crates/core/src/nucleus/actions/trace_return_wasm_api_function.rs b/crates/core/src/nucleus/actions/trace_return_wasm_api_function.rs new file mode 100644 index 0000000000..ae11160a67 --- /dev/null +++ b/crates/core/src/nucleus/actions/trace_return_wasm_api_function.rs @@ -0,0 +1,23 @@ +use crate::{ + action::{Action, ActionWrapper}, + context::Context, + instance::dispatch_action, + nucleus::{WasmApiFnCall, WasmApiFnCallResult, ZomeFnCall}, +}; +use std::sync::Arc; + +pub fn trace_return_wasm_api_function( + zome_fn_call: ZomeFnCall, + wasm_api_fn_call: WasmApiFnCall, + wasm_api_fn_call_result: WasmApiFnCallResult, + context: &Arc, +) { + dispatch_action( + context.action_channel(), + ActionWrapper::new(Action::TraceReturnWasmApiFunction(( + zome_fn_call, + wasm_api_fn_call, + wasm_api_fn_call_result, + ))), + ); +} diff --git a/crates/core/src/nucleus/actions/wasm-test/Cargo.toml b/crates/core/src/nucleus/actions/wasm-test/Cargo.toml index a4814e51f3..e88b2c68c7 100644 --- a/crates/core/src/nucleus/actions/wasm-test/Cargo.toml +++ b/crates/core/src/nucleus/actions/wasm-test/Cargo.toml @@ -19,3 +19,4 @@ serde = "=1.0.104" serde_json = { version = "=1.0.47", features = ["preserve_order"] } serde_derive = "=1.0.104" boolinator = "=2.4.0" +holochain_wasmer_guest = "=0.0.18" diff --git a/crates/core/src/nucleus/actions/wasm-test/src/lib.rs b/crates/core/src/nucleus/actions/wasm-test/src/lib.rs index 75b31421f0..9f5d25f208 100755 --- a/crates/core/src/nucleus/actions/wasm-test/src/lib.rs +++ b/crates/core/src/nucleus/actions/wasm-test/src/lib.rs @@ -1,31 +1,21 @@ -#[macro_use] extern crate hdk; -extern crate serde; -extern crate serde_json; -#[macro_use] -extern crate serde_derive; -#[macro_use] -extern crate holochain_json_derive; extern crate boolinator; +extern crate holochain_wasmer_guest; -use boolinator::Boolinator; - - +use holochain_wasmer_guest::*; use hdk::holochain_core_types::{ dna::entry_types::Sharing, validation::EntryValidationData }; -use hdk::holochain_json_api::{error::JsonError, json::JsonString}; +use hdk::prelude::*; #[derive(Serialize, Deserialize, DefaultJson, Debug,Clone)] struct TestEntryType { stuff: String, } - - define_zome! { entries: [ entry!( @@ -42,11 +32,15 @@ define_zome! { { EntryValidationData::Create{entry:test_entry,validation_data:_} => { - (test_entry.stuff != "FAIL") - .ok_or_else(|| "FAIL content is not allowed".to_string()) + if test_entry.stuff != "FAIL" { + ValidationResult::Ok + } + else { + ValidationResult::Fail("FAIL content is not allowed".into()) + } } _ =>{ - Err("Failed to validate with wrong entry type".to_string()) + ValidationResult::Fail("Failed to validate with wrong entry type".into()) } } } @@ -66,11 +60,14 @@ define_zome! { { EntryValidationData::Create{entry:test_entry,validation_data:_} => { - (test_entry.stuff != "FAIL") - .ok_or_else(|| "FAIL content is not allowed".to_string()) + if test_entry.stuff != "FAIL" { + ValidationResult::Ok + } else { + ValidationResult::Fail("FAIL content is not allowed".into()) + } } _ =>{ - Err("Failed to validate with wrong entry type".to_string()) + ValidationResult::Fail("Failed to validate with wrong entry type".into()) } } @@ -91,12 +88,14 @@ define_zome! { { EntryValidationData::Create{entry:test_entry,validation_data:_} => { - - (test_entry.stuff != "FAIL") - .ok_or_else(|| "FAIL content is not allowed".to_string()) + if test_entry.stuff != "FAIL" { + ValidationResult::Ok + } else { + ValidationResult::Fail("FAIL content is not allowed".into()) + } } _ =>{ - Err("Failed to validate with wrong entry type".to_string()) + ValidationResult::Fail("Failed to validate with wrong entry type".into()) } } } @@ -117,11 +116,14 @@ define_zome! { EntryValidationData::Create{entry:test_entry,validation_data:_} => { - (test_entry.stuff != "FAIL") - .ok_or_else(|| "FAIL content is not allowed".to_string()) + if test_entry.stuff != "FAIL" { + ValidationResult::Ok + } else { + ValidationResult::Fail("FAIL content is not allowed".into()) + } } _ =>{ - Err("Failed to validate with wrong entry type".to_string()) + ValidationResult::Fail("Failed to validate with wrong entry type".into()) } } } @@ -142,11 +144,14 @@ define_zome! { EntryValidationData::Create{entry:test_entry,validation_data:_} => { - (test_entry.stuff != "FAIL") - .ok_or_else(|| "FAIL content is not allowed".to_string()) + if test_entry.stuff != "FAIL" { + ValidationResult::Ok + } else { + ValidationResult::Fail("FAIL content is not allowed".into()) + } } _ =>{ - Err("Failed to validate with wrong entry type".to_string()) + ValidationResult::Fail("Failed to validate with wrong entry type".into()) } } } @@ -154,11 +159,11 @@ define_zome! { ] init: || { - Ok(()) + CallbackResult::Pass } validate_agent: |validation_data : EntryValidationData::| { - Ok(()) + ValidationResult::Ok } functions: [ diff --git a/crates/core/src/nucleus/mod.rs b/crates/core/src/nucleus/mod.rs index fa58d6abb7..e10c87f38d 100644 --- a/crates/core/src/nucleus/mod.rs +++ b/crates/core/src/nucleus/mod.rs @@ -13,7 +13,6 @@ pub use crate::{ reducers::reduce, state::ZomeFnCallState, }, - wasm_engine::api::ZomeApiFunction, }; use holochain_core_types::{dna::capabilities::CapabilityRequest, error::HcResult}; use holochain_json_api::json::JsonString; @@ -23,12 +22,13 @@ use std::sync::Arc; /// Struct holding data for tracing the call of an HDK function from a zome function #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] -pub struct HdkFnCall { - pub function: ZomeApiFunction, +pub struct WasmApiFnCall { + /// imports! name of the function that is invoked by the wasm guest + pub function: String, pub parameters: JsonString, } -pub type HdkFnCallResult = Result; +pub type WasmApiFnCallResult = Result; /// Struct holding data for requesting the execution of a Zome function (QueueZomeFunctionCall Action) #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] @@ -125,7 +125,7 @@ pub mod tests { call_zome_function, state::{NucleusState, NucleusStatus}, }, - wasm_engine::api::call::tests::setup_test, + // wasm_engine::call::tests::setup_test, }; use test_utils; @@ -134,7 +134,7 @@ pub mod tests { error::{DnaError, HolochainError}, signature::Signature, }; - use holochain_json_api::json::{JsonString, RawString}; + use holochain_json_api::json::{JsonString}; use holochain_persistence_api::cas::content::AddressableContent; /// dummy zome name compatible with ZomeFnCall @@ -264,27 +264,27 @@ pub mod tests { assert_eq!(nucleus_state.status(), NucleusStatus::New); } - #[test] - /// tests that calling a valid zome function returns a valid result - fn test_call_zome_function() { - let _netname = Some("test_call_zome_function"); - let dna = test_utils::create_test_dna_with_wat("test_zome", None); - //let (_instance, context) = - // test_instance_and_context(dna, None).expect("Could not initialize test instance"); - //let context = instance.initialize_context(test_context("janet", netname)); - let test_setup = setup_test(dna, "test_call_zome_function"); - let context = test_setup.context.clone(); - let token = context.get_public_token().unwrap(); - - // Create zome function call - let zome_call = - ZomeFnCall::create(context.clone(), "test_zome", token, "public_test_fn", ""); - - let result = context.block_on(call_zome_function(zome_call, context.clone())); - - assert!(result.is_ok()); - assert_eq!(JsonString::from(RawString::from(1337)), result.unwrap()); - } + // #[test] + // /// tests that calling a valid zome function returns a valid result + // fn test_call_zome_function() { + // let _netname = Some("test_call_zome_function"); + // let dna = test_utils::create_test_dna_with_wat("test_zome", None); + // //let (_instance, context) = + // // test_instance_and_context(dna, None).expect("Could not initialize test instance"); + // //let context = instance.initialize_context(test_context("janet", netname)); + // let test_setup = setup_test(dna, "test_call_zome_function"); + // let context = test_setup.context.clone(); + // let token = context.get_public_token().unwrap(); + // + // // Create zome function call + // let zome_call = + // ZomeFnCall::create(context.clone(), "test_zome", token, "public_test_fn", ""); + // + // let result = context.block_on(call_zome_function(Arc::clone(&context), zome_call)); + // + // assert!(result.is_ok()); + // assert_eq!(JsonString::from(RawString::from(1337)), result.unwrap()); + // } #[test] /// tests that calling an invalid DNA returns the correct error @@ -299,7 +299,7 @@ pub mod tests { "public_test_fn", "{}", ); - let result = context.block_on(call_zome_function(call, context.clone())); + let result = context.block_on(call_zome_function(Arc::clone(&context), call)); match result { Err(HolochainError::DnaMissing) => {} @@ -317,7 +317,7 @@ pub mod tests { // Create zome function call: let call = ZomeFnCall::new("test_zome", dummy_capability_request(), "xxx", "{}"); - let result = context.block_on(call_zome_function(call, context.clone())); + let result = context.block_on(call_zome_function(Arc::clone(&context), call)); match result { Err(HolochainError::Dna(DnaError::ZomeFunctionNotFound(err))) => { @@ -337,7 +337,7 @@ pub mod tests { // Create bad zome function call let call = ZomeFnCall::new("xxx", dummy_capability_request(), "public_test_fn", "{}"); - let result = context.block_on(call_zome_function(call, context.clone())); + let result = context.block_on(call_zome_function(Arc::clone(&context), call)); match result { Err(HolochainError::Dna(err)) => assert_eq!(err.to_string(), "Zome 'xxx' not found"), diff --git a/crates/core/src/nucleus/reducers/clear_zome_function_call.rs b/crates/core/src/nucleus/reducers/clear_zome_function_call.rs index a355d374b6..aa4e1ac473 100644 --- a/crates/core/src/nucleus/reducers/clear_zome_function_call.rs +++ b/crates/core/src/nucleus/reducers/clear_zome_function_call.rs @@ -2,10 +2,10 @@ use crate::{ action::{Action, ActionWrapper}, nucleus::state::NucleusState, state::State, - NEW_RELIC_LICENSE_KEY, + }; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_clear_zome_function_call( nucleus_state: &mut NucleusState, _root_state: &State, @@ -21,6 +21,6 @@ pub fn reduce_clear_zome_function_call( .cloned() .collect(); nucleus_state.running_zome_calls.remove(&call); - nucleus_state.hdk_function_calls.remove(&call); + nucleus_state.wasm_api_function_calls.remove(&call); nucleus_state.zome_call_results.remove(&call); } diff --git a/crates/core/src/nucleus/reducers/init_application.rs b/crates/core/src/nucleus/reducers/init_application.rs index 3eb13c0170..f9ceef52ba 100644 --- a/crates/core/src/nucleus/reducers/init_application.rs +++ b/crates/core/src/nucleus/reducers/init_application.rs @@ -2,7 +2,7 @@ use crate::{ action::{Action, ActionWrapper}, nucleus::state::{NucleusState, NucleusStatus}, state::State, - NEW_RELIC_LICENSE_KEY, + }; /// Reduce InitializeChain Action @@ -10,7 +10,7 @@ use crate::{ /// already initialized, or initializing instance. #[allow(unknown_lints)] #[allow(clippy::needless_pass_by_value)] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_initialize_chain( state: &mut NucleusState, _root_state: &State, diff --git a/crates/core/src/nucleus/reducers/mod.rs b/crates/core/src/nucleus/reducers/mod.rs index 940a5e26ef..0f57451099 100644 --- a/crates/core/src/nucleus/reducers/mod.rs +++ b/crates/core/src/nucleus/reducers/mod.rs @@ -3,8 +3,8 @@ pub mod init_application; pub mod queue_zome_function_call; pub mod return_initialization_result; pub mod return_zome_function_result; -pub mod trace_invoke_hdk_function; -pub mod trace_return_hdk_function; +pub mod trace_invoke_wasm_api_function; +pub mod trace_return_wasm_api_function; use crate::{ action::{Action, ActionWrapper, NucleusReduceFn}, @@ -15,8 +15,8 @@ use crate::{ queue_zome_function_call::reduce_queue_zome_function_call, return_initialization_result::reduce_return_initialization_result, return_zome_function_result::reduce_return_zome_function_result, - trace_invoke_hdk_function::reduce_trace_invoke_hdk_function, - trace_return_hdk_function::reduce_trace_return_hdk_function, + trace_invoke_wasm_api_function::reduce_trace_invoke_wasm_api_function, + trace_return_wasm_api_function::reduce_trace_return_wasm_api_function, }, state::NucleusState, }, @@ -33,8 +33,8 @@ fn resolve_reducer(action_wrapper: &ActionWrapper) -> Option { Action::InitializeChain(_) => Some(reduce_initialize_chain), Action::ReturnZomeFunctionResult(_) => Some(reduce_return_zome_function_result), Action::QueueZomeFunctionCall(_) => Some(reduce_queue_zome_function_call), - Action::TraceInvokeHdkFunction(_) => Some(reduce_trace_invoke_hdk_function), - Action::TraceReturnHdkFunction(_) => Some(reduce_trace_return_hdk_function), + Action::TraceInvokeWasmApiFunction(_) => Some(reduce_trace_invoke_wasm_api_function), + Action::TraceReturnWasmApiFunction(_) => Some(reduce_trace_return_wasm_api_function), _ => None, } } diff --git a/crates/core/src/nucleus/reducers/queue_zome_function_call.rs b/crates/core/src/nucleus/reducers/queue_zome_function_call.rs index b1ba06adb1..3c2cb667e1 100644 --- a/crates/core/src/nucleus/reducers/queue_zome_function_call.rs +++ b/crates/core/src/nucleus/reducers/queue_zome_function_call.rs @@ -3,7 +3,7 @@ use crate::{ nucleus::state::NucleusState, state::State, wasm_engine::MAX_ZOME_CALLS, - NEW_RELIC_LICENSE_KEY, + }; /// Reduce AddPendingValidation Action. @@ -11,7 +11,7 @@ use crate::{ /// the entry's address. #[allow(unknown_lints)] #[allow(clippy::needless_pass_by_value)] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_queue_zome_function_call( state: &mut NucleusState, _root_state: &State, diff --git a/crates/core/src/nucleus/reducers/return_initialization_result.rs b/crates/core/src/nucleus/reducers/return_initialization_result.rs index 66525871dd..aa172c1c27 100644 --- a/crates/core/src/nucleus/reducers/return_initialization_result.rs +++ b/crates/core/src/nucleus/reducers/return_initialization_result.rs @@ -2,7 +2,7 @@ use crate::{ action::{Action, ActionWrapper}, nucleus::state::{NucleusState, NucleusStatus}, state::State, - NEW_RELIC_LICENSE_KEY, + }; /// Reduce ReturnInitializationResult Action @@ -10,7 +10,7 @@ use crate::{ /// otherwise set the failed message #[allow(unknown_lints)] #[allow(clippy::needless_pass_by_value)] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_return_initialization_result( state: &mut NucleusState, _root_state: &State, diff --git a/crates/core/src/nucleus/reducers/return_zome_function_result.rs b/crates/core/src/nucleus/reducers/return_zome_function_result.rs index e8fc14c899..dc00221d24 100644 --- a/crates/core/src/nucleus/reducers/return_zome_function_result.rs +++ b/crates/core/src/nucleus/reducers/return_zome_function_result.rs @@ -2,12 +2,12 @@ use crate::{ action::{Action, ActionWrapper}, nucleus::state::NucleusState, state::State, - NEW_RELIC_LICENSE_KEY, + }; /// Reduce ReturnZomeFunctionResult Action. /// Simply drops function call into zome_calls state. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn reduce_return_zome_function_result( state: &mut NucleusState, _root_state: &State, @@ -19,7 +19,9 @@ pub fn reduce_return_zome_function_result( .zome_call_results .insert(zome_fn_response.call(), zome_fn_response.result()); state.running_zome_calls.remove(&zome_fn_response.call()); - state.hdk_function_calls.remove(&zome_fn_response.call()); + state + .wasm_api_function_calls + .remove(&zome_fn_response.call()); if let Some(next_call) = state.queued_zome_calls.pop_front() { state.running_zome_calls.insert(next_call); } diff --git a/crates/core/src/nucleus/reducers/trace_invoke_hdk_function.rs b/crates/core/src/nucleus/reducers/trace_invoke_wasm_api_function.rs similarity index 58% rename from crates/core/src/nucleus/reducers/trace_invoke_hdk_function.rs rename to crates/core/src/nucleus/reducers/trace_invoke_wasm_api_function.rs index 09cff07179..69f5bd4cfb 100644 --- a/crates/core/src/nucleus/reducers/trace_invoke_hdk_function.rs +++ b/crates/core/src/nucleus/reducers/trace_invoke_wasm_api_function.rs @@ -6,16 +6,18 @@ use crate::{ /// Reduce InvokeHdkFunction Action. /// Adds unfinished HDK call info to state -pub fn reduce_trace_invoke_hdk_function( +pub fn reduce_trace_invoke_wasm_api_function( state: &mut NucleusState, _root_state: &State, action_wrapper: &ActionWrapper, ) { let action = action_wrapper.action(); - let (zome_fn_call, hdk_fn_call) = unwrap_to!(action => Action::TraceInvokeHdkFunction); + let (zome_fn_call, wasm_api_fn_call) = unwrap_to!(action => Action::TraceInvokeWasmApiFunction); state - .hdk_function_calls + .wasm_api_function_calls .entry(zome_fn_call.clone()) - .and_modify(|zome_fn_call_state| zome_fn_call_state.begin_hdk_call(hdk_fn_call.clone())) + .and_modify(|zome_fn_call_state| { + zome_fn_call_state.begin_wasm_api_call(wasm_api_fn_call.clone()) + }) .or_insert_with(|| ZomeFnCallState::default()); } diff --git a/crates/core/src/nucleus/reducers/trace_return_hdk_function.rs b/crates/core/src/nucleus/reducers/trace_return_hdk_function.rs deleted file mode 100644 index 869114afc6..0000000000 --- a/crates/core/src/nucleus/reducers/trace_return_hdk_function.rs +++ /dev/null @@ -1,23 +0,0 @@ -use crate::{ - action::{Action, ActionWrapper}, - nucleus::state::NucleusState, - state::State, -}; - -/// Reduce ReturnHdkFunction Action. -/// Updates HDK call state with result of api call -pub fn reduce_trace_return_hdk_function( - state: &mut NucleusState, - _root_state: &State, - action_wrapper: &ActionWrapper, -) { - let action = action_wrapper.action(); - let (zome_fn_call, hdk_fn_call, hdk_fn_call_result) = - unwrap_to!(action => Action::TraceReturnHdkFunction); - state - .hdk_function_calls - .get_mut(zome_fn_call) - .ok_or_else(|| format!("Cannot record hdk function return for zome call, because its invocation was never recorded. zome call = {:?}, hdk call = {:?}", zome_fn_call, hdk_fn_call)) - .and_then(|zome_fn_call_state| zome_fn_call_state.end_hdk_call(hdk_fn_call.clone(), hdk_fn_call_result.clone()).map_err(|e| e.to_string())) - .unwrap_or_else(|err| error!("{}", err)); -} diff --git a/crates/core/src/nucleus/reducers/trace_return_wasm_api_function.rs b/crates/core/src/nucleus/reducers/trace_return_wasm_api_function.rs new file mode 100644 index 0000000000..a6a18dfaba --- /dev/null +++ b/crates/core/src/nucleus/reducers/trace_return_wasm_api_function.rs @@ -0,0 +1,23 @@ +use crate::{ + action::{Action, ActionWrapper}, + nucleus::state::NucleusState, + state::State, +}; + +/// Reduce ReturnHdkFunction Action. +/// Updates HDK call state with result of api call +pub fn reduce_trace_return_wasm_api_function( + state: &mut NucleusState, + _root_state: &State, + action_wrapper: &ActionWrapper, +) { + let action = action_wrapper.action(); + let (zome_fn_call, wasm_api_fn_call, wasm_api_fn_call_result) = + unwrap_to!(action => Action::TraceReturnWasmApiFunction); + state + .wasm_api_function_calls + .get_mut(zome_fn_call) + .ok_or_else(|| format!("Cannot record wasm api function return for zome call, because its invocation was never recorded. zome call = {:?}, hdk call = {:?}", zome_fn_call, wasm_api_fn_call)) + .and_then(|zome_fn_call_state| zome_fn_call_state.end_wasm_api_call(wasm_api_fn_call.clone(), wasm_api_fn_call_result.clone()).map_err(|e| e.to_string())) + .unwrap_or_else(|err| error!("{}", err)); +} diff --git a/crates/core/src/nucleus/state.rs b/crates/core/src/nucleus/state.rs index 4dd0d6a314..d54e9faee9 100644 --- a/crates/core/src/nucleus/state.rs +++ b/crates/core/src/nucleus/state.rs @@ -1,11 +1,14 @@ use crate::{ dht::pending_validations::ValidatingWorkflow, - nucleus::{actions::initialize::Initialization, HdkFnCall, HdkFnCallResult, ZomeFnCall}, - NEW_RELIC_LICENSE_KEY, + nucleus::{actions::initialize::Initialization, ZomeFnCall}, + }; use holochain_core_types::{dna::Dna, error::HolochainError}; -use crate::state::StateWrapper; +use crate::{ + nucleus::{WasmApiFnCall, WasmApiFnCallResult}, + state::StateWrapper, +}; use holochain_json_api::{ error::{JsonError, JsonResult}, json::JsonString, @@ -104,11 +107,11 @@ pub struct NucleusState { //read from there when loading an instance/chain. pub queued_zome_calls: VecDeque, pub running_zome_calls: HashSet, - pub hdk_function_calls: HashMap, + pub wasm_api_function_calls: HashMap, pub zome_call_results: HashMap>, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl NucleusState { pub fn new() -> Self { NucleusState { @@ -117,7 +120,7 @@ impl NucleusState { queued_zome_calls: VecDeque::new(), running_zome_calls: HashSet::new(), zome_call_results: HashMap::new(), - hdk_function_calls: HashMap::new(), + wasm_api_function_calls: HashMap::new(), } } @@ -179,7 +182,7 @@ impl From for NucleusState { queued_zome_calls: VecDeque::new(), running_zome_calls: HashSet::new(), zome_call_results: HashMap::new(), - hdk_function_calls: HashMap::new(), + wasm_api_function_calls: HashMap::new(), } } } @@ -201,35 +204,35 @@ impl AddressableContent for NucleusStateSnapshot { #[derive(Clone, Default, Debug, PartialEq, Serialize)] pub struct ZomeFnCallState { - hdk_fn_invocations: Vec<(HdkFnCall, Option)>, + wasm_api_fn_invocations: Vec<(WasmApiFnCall, Option)>, } impl ZomeFnCallState { - pub fn begin_hdk_call(&mut self, call: HdkFnCall) { - self.hdk_fn_invocations.push((call, None)) + pub fn begin_wasm_api_call(&mut self, call: WasmApiFnCall) { + self.wasm_api_fn_invocations.push((call, None)) } - pub fn end_hdk_call( + pub fn end_wasm_api_call( &mut self, - call: HdkFnCall, - result: HdkFnCallResult, + call: WasmApiFnCall, + result: WasmApiFnCallResult, ) -> Result<(), HolochainError> { - if let Some((current_call, current_result)) = self.hdk_fn_invocations.pop() { + if let Some((current_call, current_result)) = self.wasm_api_fn_invocations.pop() { if call != current_call { Err(HolochainError::new( - "HDK call other than the current call was ended.", + "Wasm API call other than the current call was ended.", )) } else if current_result.is_some() { Err(HolochainError::new( - "Ending and HDK which was already ended.", + "Ending and Wasm API which was already ended.", )) } else { - self.hdk_fn_invocations.push((call, Some(result))); + self.wasm_api_fn_invocations.push((call, Some(result))); Ok(()) } } else { Err(HolochainError::new( - "Attempted to end HDK call, but none was started!", + "Attempted to end Wasm API call, but none was started!", )) } } @@ -238,8 +241,7 @@ impl ZomeFnCallState { #[cfg(test)] pub mod tests { - use super::{HdkFnCall, NucleusState, ZomeFnCallState}; - use crate::wasm_engine::api::ZomeApiFunction; + use super::{NucleusState, WasmApiFnCall, ZomeFnCallState}; /// dummy nucleus state pub fn test_nucleus_state() -> NucleusState { @@ -249,23 +251,23 @@ pub mod tests { #[test] fn test_zome_fn_call_state() { let mut state = ZomeFnCallState::default(); - let call1 = HdkFnCall { - function: ZomeApiFunction::Call, + let call1 = WasmApiFnCall { + function: "hc_call".into(), parameters: "params1".into(), }; - let call2 = HdkFnCall { - function: ZomeApiFunction::Call, + let call2 = WasmApiFnCall { + function: "hc_call".into(), parameters: "params2".into(), }; - state.begin_hdk_call(call1.clone()); - state.end_hdk_call(call1, Ok("result".into())).unwrap(); + state.begin_wasm_api_call(call1.clone()); + state.end_wasm_api_call(call1, Ok("result".into())).unwrap(); - state.begin_hdk_call(call2.clone()); + state.begin_wasm_api_call(call2.clone()); state - .end_hdk_call(call2, Err("call failed for reasons".into())) + .end_wasm_api_call(call2, Err("call failed for reasons".into())) .unwrap(); - assert_eq!(state.hdk_fn_invocations.len(), 2); + assert_eq!(state.wasm_api_fn_invocations.len(), 2); } } diff --git a/crates/core/src/nucleus/validation/agent_entry.rs b/crates/core/src/nucleus/validation/agent_entry.rs index 5a21a06404..a9e3d8bb8d 100644 --- a/crates/core/src/nucleus/validation/agent_entry.rs +++ b/crates/core/src/nucleus/validation/agent_entry.rs @@ -2,27 +2,27 @@ use crate::{ context::Context, nucleus::{ actions::run_validation_callback::run_validation_callback, - validation::{ValidationError, ValidationResult}, CallbackFnCall, }, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::{ + validation::{ValidationResult}, agent::AgentId, entry::Entry, validation::{EntryValidationData, ValidationData}, }; use holochain_persistence_api::cas::content::AddressableContent; -use holochain_wasm_utils::api_serialization::validation::AgentIdValidationArgs; +use holochain_wasm_types::validation::AgentIdValidationArgs; use futures::{future, future::FutureExt}; use std::sync::Arc; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn validate_agent_entry( + context: Arc, entry: Entry, validation_data: ValidationData, - context: &Arc, ) -> ValidationResult { let dna = context.get_dna().expect("Callback called without DNA set!"); @@ -41,24 +41,24 @@ pub async fn validate_agent_entry( let call = CallbackFnCall::new(&zome_name, "__hdk_validate_agent_entry", params.clone()); // Need to return a boxed future for it to work with join_all // https://users.rust-lang.org/t/the-trait-unpin-is-not-implemented-for-genfuture-error-when-using-join-all/23612/2 - run_validation_callback(entry.address(), call, &context).boxed() + run_validation_callback(Arc::clone(&context), entry.address(), call).boxed() })) .await; - let errors: Vec = results + let errors: Vec = results .iter() .filter_map(|r| match r { - Ok(_) => None, - Err(e) => Some(e.to_owned()), + ValidationResult::Ok => None, + v => Some(v.to_owned()), }) .collect(); if errors.is_empty() { log_debug!(context, "Validating agent entry success!: {:?}", results); - Ok(()) + ValidationResult::Ok } else { - Err(ValidationError::Error( + ValidationResult::Fail( format!("Failed to validate agent ID on a zome, {:?}", errors).into(), - )) + ) } } diff --git a/crates/core/src/nucleus/validation/app_entry.rs b/crates/core/src/nucleus/validation/app_entry.rs index 55fae5cad9..1fc18a2bf4 100644 --- a/crates/core/src/nucleus/validation/app_entry.rs +++ b/crates/core/src/nucleus/validation/app_entry.rs @@ -4,46 +4,49 @@ use crate::{ actions::{ get_entry::get_entry_from_dht, run_validation_callback::run_validation_callback, }, - validation::{entry_to_validation_data, ValidationError, ValidationResult}, + validation::{entry_to_validation_data}, CallbackFnCall, }, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::{ entry::{entry_type::AppEntryType, Entry}, validation::ValidationData, + validation::{ValidationResult}, }; use holochain_persistence_api::cas::content::{Address, AddressableContent}; -use holochain_wasm_utils::api_serialization::validation::EntryValidationArgs; +use holochain_wasm_types::validation::EntryValidationArgs; use std::sync::Arc; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn validate_app_entry( + context: Arc, entry: Entry, app_entry_type: AppEntryType, - context: &Arc, link: Option
, validation_data: ValidationData, ) -> ValidationResult { let dna = context.get_dna().expect("Callback called without DNA set!"); - let zome_name = dna - .get_zome_name_for_app_entry_type(&app_entry_type) - .ok_or(ValidationError::NotImplemented)?; + let zome_name = match dna.get_zome_name_for_app_entry_type(&app_entry_type) { + Some(v) => v, + None => return ValidationResult::NotImplemented, + }; + if let Some(expected_link_update) = link.clone() { - get_entry_from_dht(&context.clone(), &expected_link_update).map_err(|_| { - ValidationError::UnresolvedDependencies(vec![expected_link_update.clone()]) - })?; + if let Err(_) = get_entry_from_dht(Arc::clone(&context), &expected_link_update) { + return ValidationResult::UnresolvedDependencies(vec![expected_link_update.clone()]); + }; }; let params = EntryValidationArgs { - validation_data: entry_to_validation_data(context.clone(), &entry, link, validation_data) - .map_err(|_| { - ValidationError::Fail("Could not get entry validation".to_string()) - })?, + validation_data: match entry_to_validation_data(context.clone(), &entry, link, validation_data) { + Ok(v) => v, + Err(_) => return ValidationResult::Fail("Could not get entry validation".to_string()), + }, }; let call = CallbackFnCall::new(&zome_name, "__hdk_validate_app_entry", params); - run_validation_callback(entry.address(), call, &context).await + run_validation_callback(Arc::clone(&context), entry.address(), call).await } diff --git a/crates/core/src/nucleus/validation/build_from_dht.rs b/crates/core/src/nucleus/validation/build_from_dht.rs index 15e3f796b2..e2deb93a09 100644 --- a/crates/core/src/nucleus/validation/build_from_dht.rs +++ b/crates/core/src/nucleus/validation/build_from_dht.rs @@ -1,6 +1,6 @@ use crate::{ context::Context, entry::CanPublish, network::entry_with_header::EntryWithHeader, - workflows::get_entry_result::get_entry_with_meta_workflow, NEW_RELIC_LICENSE_KEY, + workflows::get_entry_result::get_entry_with_meta_workflow, }; use holochain_core_types::{ chain_header::ChainHeader, @@ -14,7 +14,7 @@ use std::sync::Arc; const GET_TIMEOUT_MS: usize = 1000; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] async fn all_chain_headers_before_header_dht( context: Arc, header: &ChainHeader, @@ -27,7 +27,7 @@ async fn all_chain_headers_before_header_dht( let timeout = Timeout::new(GET_TIMEOUT_MS); let get_entry_result = - get_entry_with_meta_workflow(&context, &next_header_addr, &timeout).await; + get_entry_with_meta_workflow(Arc::clone(&context), &next_header_addr, &timeout).await; log_debug!( context, @@ -68,7 +68,7 @@ async fn public_chain_entries_from_headers_dht( for header in public_headers { let timeout = Timeout::new(GET_TIMEOUT_MS); let get_entry_result = - get_entry_with_meta_workflow(&context, &header.entry_address(), &timeout).await?; + get_entry_with_meta_workflow(Arc::clone(&context), &header.entry_address(), &timeout).await?; if let Some(EntryWithMetaAndHeader { entry_with_meta: EntryWithMeta { entry, .. }, @@ -146,9 +146,9 @@ pub mod tests { let _entry_address = context .block_on(author_entry( + Arc::clone(&context), &test_entry_with_value("{\"stuff\":\"test entry value\"}"), None, - &context, &vec![], )) .unwrap() @@ -190,7 +190,7 @@ pub mod tests { // jack authors the entry context2 - .block_on(author_entry(&entry, None, &context2, &vec![])) + .block_on(author_entry(Arc::clone(&context2), &entry, None, &vec![])) .unwrap() .address(); diff --git a/crates/core/src/nucleus/validation/header_address.rs b/crates/core/src/nucleus/validation/header_address.rs index 12fb925074..4ff707f552 100644 --- a/crates/core/src/nucleus/validation/header_address.rs +++ b/crates/core/src/nucleus/validation/header_address.rs @@ -1,14 +1,14 @@ -use crate::{ - nucleus::validation::{ValidationError, ValidationResult}, - NEW_RELIC_LICENSE_KEY, -}; -use boolinator::Boolinator; + use holochain_core_types::{chain_header::ChainHeader, entry::Entry}; +use holochain_core_types::validation::{ValidationResult}; use holochain_persistence_api::cas::content::AddressableContent; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn validate_header_address(entry: &Entry, header: &ChainHeader) -> ValidationResult { - (entry.address() == *header.entry_address()) - .ok_or(ValidationError::Fail("Wrong header for entry".to_string())) + if entry.address() == *header.entry_address() { + ValidationResult::Ok + } else { + ValidationResult::Fail("Wrong header for entry".to_string()) + } } diff --git a/crates/core/src/nucleus/validation/link_entry.rs b/crates/core/src/nucleus/validation/link_entry.rs index 434a91c9e7..92d81c4f5d 100644 --- a/crates/core/src/nucleus/validation/link_entry.rs +++ b/crates/core/src/nucleus/validation/link_entry.rs @@ -2,48 +2,52 @@ use crate::{ context::Context, nucleus::{ actions::run_validation_callback::run_validation_callback, - validation::{ValidationError, ValidationResult}, CallbackFnCall, }, - wasm_engine::callback::links_utils, - NEW_RELIC_LICENSE_KEY, + workflows::callback::links_utils, + }; -use boolinator::*; use holochain_core_types::{ entry::Entry, + validation::{ValidationResult}, validation::{LinkValidationData, ValidationData}, }; use holochain_persistence_api::cas::content::AddressableContent; -use holochain_wasm_utils::api_serialization::validation::{LinkDirection, LinkValidationArgs}; +use holochain_wasm_types::validation::{LinkDirection, LinkValidationArgs}; use std::sync::Arc; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn validate_link_entry( + context: Arc, entry: Entry, validation_data: ValidationData, - context: &Arc, ) -> ValidationResult { let address = entry.address(); let link = match entry.clone() { Entry::LinkAdd(link_add) => link_add.clone(), Entry::LinkRemove((link_remove, _)) => link_remove, _ => { - return Err(ValidationError::Error( + return ValidationResult::Fail( "Could not extract link_add from entry".into(), - )); + ); } }; let link = link.link().clone(); - let (base, target) = links_utils::get_link_entries(&link, context).map_err(|_| { - ValidationError::UnresolvedDependencies( - [link.base().clone(), link.target().clone()].to_vec(), - ) - })?; + let (base, target) = match links_utils::get_link_entries(Arc::clone(&context), &link) { + Ok(v) => v, + Err(_) => { + return ValidationResult::UnresolvedDependencies( + [link.base().clone(), link.target().clone()].to_vec(), + ); + }, + }; - let link_definition_path = links_utils::find_link_definition_by_type(link.link_type(), context) - .map_err(|_| ValidationError::NotImplemented)?; + let link_definition_path = match links_utils::find_link_definition_by_type(Arc::clone(&context), link.link_type()) { + Ok(v) => v, + Err(_) => return ValidationResult::NotImplemented, + }; let dna = context .state() @@ -78,33 +82,35 @@ pub async fn validate_link_entry( ) }; - (base.entry_type().to_string() == base_type) - .ok_or(ValidationError::Fail(format!( + if base.entry_type().to_string() != base_type { + return ValidationResult::Fail(format!( "Wrong base type for link of type '{}'. Found '{}', but link is defined to link from '{}'s.", link.link_type(), base_type, base.entry_type().to_string(), - )))?; + )); + }; - (target.entry_type().to_string() == target_type) - .ok_or(ValidationError::Fail(format!( + if target.entry_type().to_string() != target_type { + return ValidationResult::Fail(format!( "Wrong target type for link of type '{}'. Found '{}', but link is defined to link to '{}'s.", link.link_type(), target_type, target.entry_type().to_string(), - )))?; + )); + }; let validation_data = match entry.clone() { - Entry::LinkAdd(link) => Ok(LinkValidationData::LinkAdd { + Entry::LinkAdd(link) => LinkValidationData::LinkAdd { link, validation_data, - }), - Entry::LinkRemove((link, _)) => Ok(LinkValidationData::LinkRemove { + }, + Entry::LinkRemove((link, _)) => LinkValidationData::LinkRemove { link, validation_data, - }), - _ => Err(ValidationError::Fail("Entry is not link".to_string())), - }?; + }, + _ => return ValidationResult::Fail("Entry is not link".to_string()), + }; let params = LinkValidationArgs { entry_type: link_definition_path.entry_type_name, @@ -118,5 +124,5 @@ pub async fn validate_link_entry( params, ); - run_validation_callback(address, call, context).await + run_validation_callback(Arc::clone(&context), address, call).await } diff --git a/crates/core/src/nucleus/validation/mod.rs b/crates/core/src/nucleus/validation/mod.rs index 7690de8dde..c8d0ee7b3d 100644 --- a/crates/core/src/nucleus/validation/mod.rs +++ b/crates/core/src/nucleus/validation/mod.rs @@ -1,13 +1,13 @@ use crate::{ context::Context, workflows::get_entry_result::get_entry_with_meta_workflow, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::{ chain_header::ChainHeader, entry::{entry_type::EntryType, Entry, EntryWithMeta}, error::HolochainError, time::Timeout, - validation::{EntryValidationData, ValidationData}, + validation::{EntryValidationData, ValidationData, ValidationResult}, }; use holochain_persistence_api::cas::content::Address; @@ -21,48 +21,6 @@ mod link_entry; mod provenances; mod remove_entry; -#[derive(Clone, Debug, PartialEq, Serialize)] -/// A failed validation. -pub enum ValidationError { - /// `Fail` means the validation function did run successfully and recognized the entry - /// as invalid. The String parameter holds the non-zero return value of the app validation - /// function. - Fail(String), - - /// The entry could not get validated because known dependencies (like base and target - /// for links) were not present yet. - UnresolvedDependencies(Vec
), - - /// A validation function for the given entry could not be found. - /// This can happen if the entry's type is not defined in the DNA (which can only happen - /// if somebody is sending wrong entries..) or there is no native implementation for a - /// system entry type yet. - NotImplemented, - - /// An error occurred that is out of the scope of validation (no state?, I/O errors..) - Error(HolochainError), -} - -/// Result of validating an entry. -/// Either Ok(()) if the entry is valid, -/// or any specialization of ValidationError. -pub type ValidationResult = Result<(), ValidationError>; - -impl From for HolochainError { - fn from(ve: ValidationError) -> Self { - match ve { - ValidationError::Fail(reason) => HolochainError::ValidationFailed(reason), - ValidationError::UnresolvedDependencies(_) => { - HolochainError::ValidationFailed("Missing dependencies".to_string()) - } - ValidationError::NotImplemented => { - HolochainError::NotImplemented("Validation not implemented".to_string()) - } - ValidationError::Error(e) => e, - } - } -} - /// Main validation workflow. /// This is the high-level validate function that wraps the whole validation process and is what should /// be called from other workflows for validating an entry. @@ -75,63 +33,71 @@ impl From for HolochainError { /// /// All of this actually happens in the functions of the sub modules. This function is the /// main validation entry point and, like a workflow, stays high-level. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn validate_entry( + context: Arc, entry: Entry, link: Option
, validation_data: ValidationData, - context: &Arc, ) -> ValidationResult { log_debug!(context, "workflow/validate_entry: {:?}", entry); //check_entry_type(entry.entry_type(), context)?; - header_address::validate_header_address(&entry, &validation_data.package.chain_header)?; - provenances::validate_provenances(&validation_data)?; - - match entry.entry_type() { - // DNA entries are not validated currently and always valid - // TODO: Specify when DNA can be commited as an update and how to implement validation of DNA entries then. - EntryType::Dna => Ok(()), - - EntryType::App(app_entry_type) => { - app_entry::validate_app_entry( - entry.clone(), - app_entry_type.clone(), - context, - link, - validation_data, - ) - .await - } - - EntryType::LinkAdd => { - link_entry::validate_link_entry(entry.clone(), validation_data, context).await - } - - EntryType::LinkRemove => { - link_entry::validate_link_entry(entry.clone(), validation_data, context).await - } - - // Deletion entries are not validated currently and always valid - // TODO: Specify how Deletion can be commited to chain. - EntryType::Deletion => { - remove_entry::validate_remove_entry(entry.clone(), validation_data, context).await - } - - // a grant should always be private, so it should always pass - EntryType::CapTokenGrant => Ok(()), - - EntryType::AgentId => { - agent_entry::validate_agent_entry(entry.clone(), validation_data, context).await - } - - // chain headers always pass for now. In future this should check that the entry is valid - EntryType::ChainHeader => Ok(()), - - _ => Err(ValidationError::NotImplemented), + match header_address::validate_header_address(&entry, &validation_data.package.chain_header) { + ValidationResult::Ok => { + match provenances::validate_provenances(&validation_data) { + ValidationResult::Ok => { + match entry.entry_type() { + // DNA entries are not validated currently and always valid + // TODO: Specify when DNA can be commited as an update and how to implement validation of DNA entries then. + EntryType::Dna => ValidationResult::Ok, + + EntryType::App(app_entry_type) => { + app_entry::validate_app_entry( + Arc::clone(&context), + entry.clone(), + app_entry_type.clone(), + link, + validation_data, + ) + .await + } + + EntryType::LinkAdd => { + link_entry::validate_link_entry(Arc::clone(&context), entry.clone(), validation_data).await + } + + EntryType::LinkRemove => { + link_entry::validate_link_entry(Arc::clone(&context), entry.clone(), validation_data).await + } + + // Deletion entries are not validated currently and always valid + // TODO: Specify how Deletion can be commited to chain. + EntryType::Deletion => { + remove_entry::validate_remove_entry(Arc::clone(&context), entry.clone(), validation_data).await + } + + // a grant should always be private, so it should always pass + EntryType::CapTokenGrant => ValidationResult::Ok, + + EntryType::AgentId => { + agent_entry::validate_agent_entry(Arc::clone(&context), entry.clone(), validation_data).await + } + + // chain headers always pass for now. In future this should check that the entry is valid + EntryType::ChainHeader => ValidationResult::Ok, + + _ => ValidationResult::NotImplemented, + } + }, + v => v, + } + }, + v => v, } + } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn entry_to_validation_data( context: Arc, entry: &Entry, @@ -188,13 +154,13 @@ pub fn entry_to_validation_data( } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn get_entry_with_header( context: Arc, address: &Address, ) -> Result<(EntryWithMeta, ChainHeader), HolochainError> { let pair = context.block_on(get_entry_with_meta_workflow( - &context, + Arc::clone(&context), address, &Timeout::default(), ))?; diff --git a/crates/core/src/nucleus/validation/provenances.rs b/crates/core/src/nucleus/validation/provenances.rs index de5ce1d389..6ff879d036 100644 --- a/crates/core/src/nucleus/validation/provenances.rs +++ b/crates/core/src/nucleus/validation/provenances.rs @@ -1,36 +1,39 @@ -use crate::{ - nucleus::validation::{ValidationError, ValidationResult}, - NEW_RELIC_LICENSE_KEY, -}; -use boolinator::Boolinator; + +use holochain_core_types::validation::{ValidationResult}; use holochain_core_types::validation::ValidationData; use holochain_dpki::utils::Verify; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn validate_provenances(validation_data: &ValidationData) -> ValidationResult { let header = &validation_data.package.chain_header; - header + match header .provenances() .iter() .map(|provenance| { let maybe_has_authored = provenance.verify(header.entry_address().to_string()); match maybe_has_authored { Err(_) => { - Err(ValidationError::Fail(format!( + Err(ValidationResult::Fail(format!( "Signature of entry {} from author {} failed to verify public signing key. Key might be invalid.", header.entry_address(), provenance.source(), ))) }, Ok(has_authored) => { - has_authored.ok_or(ValidationError::Fail(format!( - "Signature of entry {} from author {} invalid", - header.entry_address(), - provenance.source(), - ))) + if has_authored { + Ok(()) + } else { + Err(ValidationResult::Fail(format!( + "Signature of entry {} from author {} invalid", + header.entry_address(), + provenance.source(), + ))) + } }, } }) - .collect::, ValidationError>>()?; - Ok(()) + .collect::, ValidationResult>>() { + Ok(_) => ValidationResult::Ok, + Err(v) => v, + } } diff --git a/crates/core/src/nucleus/validation/remove_entry.rs b/crates/core/src/nucleus/validation/remove_entry.rs index 638f989a59..81a9697936 100644 --- a/crates/core/src/nucleus/validation/remove_entry.rs +++ b/crates/core/src/nucleus/validation/remove_entry.rs @@ -4,48 +4,50 @@ use crate::{ actions::{ get_entry::get_entry_from_dht, run_validation_callback::run_validation_callback, }, - validation::{entry_to_validation_data, ValidationError, ValidationResult}, + validation::{entry_to_validation_data}, CallbackFnCall, }, - NEW_RELIC_LICENSE_KEY, + }; +use holochain_core_types::validation::ValidationResult; use holochain_core_types::{entry::Entry, validation::ValidationData}; use holochain_persistence_api::cas::content::AddressableContent; -use holochain_wasm_utils::api_serialization::validation::EntryValidationArgs; +use holochain_wasm_types::validation::EntryValidationArgs; use std::sync::Arc; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn validate_remove_entry( + context: Arc, entry: Entry, validation_data: ValidationData, - context: &Arc, ) -> ValidationResult { let dna = context.get_dna().expect("Callback called without DNA set"); let deletion_entry = unwrap_to!(entry=>Entry::Deletion); let deletion_address = deletion_entry.deleted_entry_address().clone(); - let entry_to_delete = get_entry_from_dht(&context.clone(), &deletion_address) - .map_err(|_| ValidationError::UnresolvedDependencies(vec![deletion_address.clone()]))? - .ok_or_else(|| { - ValidationError::Fail("Could not obtain entry for link_update_delte".to_string()) - })?; + + let entry_to_delete = match get_entry_from_dht(Arc::clone(&context), &deletion_address) { + Err(_) => return ValidationResult::UnresolvedDependencies(vec![deletion_address.clone()]), + Ok(None) => return ValidationResult::Fail("Could not obtain entry for link_update_delte".to_string()), + Ok(Some(v)) => v, + }; + let app_entry_type = match entry_to_delete.clone() { - Entry::App(app_entry_type, _) => Ok(app_entry_type), - _ => Err(ValidationError::Fail( - "Entry type should be App Type".to_string(), - )), - }?; + Entry::App(v, _) => v, + _ => return ValidationResult::Fail("Entry type should be App Type".to_string()), + }; - let zome_name = dna - .get_zome_name_for_app_entry_type(&app_entry_type) - .ok_or(ValidationError::NotImplemented)?; + let zome_name = match dna.get_zome_name_for_app_entry_type(&app_entry_type) { + Some(v) => v, + None => return ValidationResult::NotImplemented, + }; let params = EntryValidationArgs { - validation_data: entry_to_validation_data(context.clone(), &entry, None, validation_data) - .map_err(|_| { - ValidationError::Fail("Could not get entry validation".to_string()) - })?, + validation_data: match entry_to_validation_data(context.clone(), &entry, None, validation_data) { + Ok(v) => v, + Err(_) => return ValidationResult::Fail("Could not get entry validation".to_string()), + }, }; let call = CallbackFnCall::new(&zome_name, "__hdk_validate_app_entry", params); - run_validation_callback(entry.address(), call, context).await + run_validation_callback(Arc::clone(&context), entry.address(), call).await } diff --git a/crates/core/src/persister.rs b/crates/core/src/persister.rs index a243ffb114..fa5ecb9ff6 100644 --- a/crates/core/src/persister.rs +++ b/crates/core/src/persister.rs @@ -3,7 +3,7 @@ use crate::{ context::Context, nucleus::state::{NucleusStateSnapshot, NUCLEUS_SNAPSHOT_ADDRESS}, state::State, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::error::HolochainError; use holochain_locksmith::RwLock; @@ -40,7 +40,7 @@ impl PartialEq for SimplePersister { } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Persister for SimplePersister { fn save(&mut self, state: &StateWrapper) -> Result<(), HolochainError> { let lock = &*self.storage.clone(); diff --git a/crates/core/src/scheduled_jobs/state_dump.rs b/crates/core/src/scheduled_jobs/state_dump.rs index dd7d67a9ca..9da2364c07 100644 --- a/crates/core/src/scheduled_jobs/state_dump.rs +++ b/crates/core/src/scheduled_jobs/state_dump.rs @@ -2,13 +2,13 @@ use crate::{ context::Context, dht::pending_validations::PendingValidationWithTimeout, state_dump::{address_to_content_and_type, StateDump}, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::chain_header::ChainHeader; use holochain_persistence_api::cas::content::{Address, AddressableContent}; use std::sync::Arc; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn header_to_string(h: &ChainHeader) -> String { format!( r#"===========Header=========== @@ -30,7 +30,7 @@ Prev. address: {:?} ) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn address_to_content_string(address: &Address, context: Arc) -> String { let maybe_content = address_to_content_and_type(address, context); maybe_content @@ -46,7 +46,7 @@ fn address_to_content_string(address: &Address, context: Arc) -> String }) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn state_dump(context: Arc) { let dump = StateDump::from(context.clone()); diff --git a/crates/core/src/scheduled_jobs/timeouts.rs b/crates/core/src/scheduled_jobs/timeouts.rs index 0c955bf92b..7ad8e6120b 100644 --- a/crates/core/src/scheduled_jobs/timeouts.rs +++ b/crates/core/src/scheduled_jobs/timeouts.rs @@ -2,11 +2,11 @@ use crate::{ action::{Action, ActionWrapper}, context::Context, instance::dispatch_action, - NEW_RELIC_LICENSE_KEY, + }; use std::sync::Arc; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn check_network_processes_for_timeouts(context: Arc) { let state = context.state().expect("Couldn't get state in timeout job"); for (key, (time, duration)) in state.network().query_timeouts.iter() { diff --git a/crates/core/src/signal.rs b/crates/core/src/signal.rs index cf9114e88c..b8d3ceb159 100644 --- a/crates/core/src/signal.rs +++ b/crates/core/src/signal.rs @@ -1,7 +1,7 @@ use crate::{action::ActionWrapper, consistency::ConsistencySignal}; use crossbeam_channel::{unbounded, Receiver, Sender}; use holochain_json_api::{error::JsonError, json::JsonString}; -use holochain_wasm_utils::api_serialization::emit_signal::EmitSignalArgs; +use holochain_wasm_types::emit_signal::EmitSignalArgs; use serde::{Deserialize, Deserializer}; use snowflake::ProcessUniqueId; use std::thread; diff --git a/crates/core/src/state.rs b/crates/core/src/state.rs index 008976923f..e60410a546 100644 --- a/crates/core/src/state.rs +++ b/crates/core/src/state.rs @@ -9,7 +9,7 @@ use crate::{ dht::dht_store::DhtStore, network::state::NetworkState, nucleus::state::{NucleusState, NucleusStateSnapshot}, - NEW_RELIC_LICENSE_KEY, + }; use holochain_conductor_lib_api::ConductorApi; use holochain_core_types::{ @@ -65,7 +65,7 @@ pub struct State { pub conductor_api: ConductorApi, } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl State { pub fn new(context: Arc) -> Self { // @TODO file table diff --git a/crates/core/src/state_dump.rs b/crates/core/src/state_dump.rs index 197b6dccc5..470391ca35 100644 --- a/crates/core/src/state_dump.rs +++ b/crates/core/src/state_dump.rs @@ -4,7 +4,7 @@ use crate::{ dht::{aspect_map::AspectMapBare, pending_validations::PendingValidationWithTimeout}, network::direct_message::DirectMessage, nucleus::{ZomeFnCall, ZomeFnCallState}, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::{chain_header::ChainHeader, entry::Entry, error::HolochainError}; use holochain_json_api::json::JsonString; @@ -40,7 +40,7 @@ impl From> for StateDump { let source_chain: Vec = source_chain.into_iter().rev().collect(); let queued_calls: Vec = nucleus.queued_zome_calls.into_iter().collect(); - let invocations = nucleus.hdk_function_calls; + let invocations = nucleus.wasm_api_function_calls; let running_calls: Vec<(ZomeFnCall, Option)> = nucleus .running_zome_calls .into_iter() @@ -92,7 +92,7 @@ impl From> for StateDump { } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn address_to_content_and_type( address: &Address, context: Arc, diff --git a/crates/core/src/wasm_engine/api/call.rs b/crates/core/src/wasm_engine/api/call.rs deleted file mode 100644 index bc3816f32d..0000000000 --- a/crates/core/src/wasm_engine/api/call.rs +++ /dev/null @@ -1,561 +0,0 @@ -use crate::{ - context::Context, - nucleus::{ - actions::call_zome_function::{call_zome_function, make_cap_request_for_call}, - ZomeFnCall, - }, - wasm_engine::{api::ZomeApiResult, Runtime}, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_core_types::error::HolochainError; -use holochain_json_api::json::JsonString; -use holochain_logging::prelude::*; - -use holochain_wasm_utils::api_serialization::{ZomeFnCallArgs, THIS_INSTANCE}; -use jsonrpc_lite::JsonRpc; -use snowflake::ProcessUniqueId; -use std::{convert::TryFrom, sync::Arc}; -use wasmi::{RuntimeArgs, RuntimeValue}; - -// ZomeFnCallArgs to ZomeFnCall -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -impl ZomeFnCall { - fn from_args(context: Arc, args: ZomeFnCallArgs) -> Self { - // TODO we are currently signing the call ourself. This signature - // should have happend at the client and be extracted from the args. - let cap_call = make_cap_request_for_call( - context, - args.cap_token, - &args.fn_name, - JsonString::from_json(&args.fn_args.clone()), - ); - ZomeFnCall::new( - &args.zome_name, - cap_call, - &args.fn_name, - JsonString::from_json(&args.fn_args), - ) - } -} - -/// HcApiFuncIndex::CALL function code -/// args: [0] encoded MemoryAllocation as u64 -/// expected complex argument: {zome_name: String, cap_token: Address, fn_name: String, args: String} -/// args from API call are converted into a ZomeFnCall -/// Launch an Action::Call with newly formed ZomeFnCall- -/// Waits for a ZomeFnResult -/// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_call(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - - let input = match ZomeFnCallArgs::try_from(args_str.clone()) { - Ok(input) => input, - // Exit on error - Err(_) => { - log_error!( - context, - "zome: invoke_call failed to deserialize: {:?}", - args_str - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - }; - - let span = context - .tracer - .span("hdk invoke_call") - .tag(ht::Tag::new("ZomeFnCallArgs", format!("{:?}", input))) - .start() - .into(); - let _spanguard = ht::push_span(span); - - let result = if input.instance_handle == THIS_INSTANCE { - // ZomeFnCallArgs to ZomeFnCall - let zome_call = ZomeFnCall::from_args(context.clone(), input.clone()); - - if let Ok(zome_call_data) = runtime.zome_call_data() { - // Don't allow recursive calls - if zome_call.same_fn_as(&zome_call_data.call) { - return ribosome_error_code!(RecursiveCallForbidden); - } - } - local_call(runtime, input.clone()).map_err(|error| { - log_error!(context, "zome-to-zome-call/[{:?}]: {:?}", input, error); - error - }) - } else { - bridge_call(runtime, input.clone()).map_err(|error| { - log_error!(context, "bridge-call/[{:?}]: {:?}", input, error); - error - }) - }; - - runtime.store_result(result) -} - -#[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -fn local_call(runtime: &mut Runtime, input: ZomeFnCallArgs) -> Result { - let context = runtime.context().map_err(|_| { - HolochainError::ErrorGeneric( - "expecting zome call data in local call not null call".to_string(), - ) - })?; - // ZomeFnCallArgs to ZomeFnCall - let zome_call = ZomeFnCall::from_args(context.clone(), input.clone()); - log_debug!(context, "blocking on zome call: {:?}", input.clone()); - let result = context.block_on(call_zome_function(zome_call, context.clone())); - log_debug!( - context, - "blocked on zome call: {:?} with result {:?}", - input, - result - ); - result -} - -#[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -fn bridge_call(runtime: &mut Runtime, input: ZomeFnCallArgs) -> Result { - let context = runtime.context().map_err(|_| { - HolochainError::ErrorGeneric( - "expecting zome call data in bridge call not null call".to_string(), - ) - })?; - let conductor_api = context.conductor_api.clone(); - - let params = format!( - r#"{{"instance_id":"{}", "zome": "{}", "function": "{}", "args": {}}}"#, - input.instance_handle, input.zome_name, input.fn_name, input.fn_args - ); - - let handler = conductor_api.get().write().unwrap(); - - let id = ProcessUniqueId::new(); - // json-rpc format - let request = format!( - r#"{{"jsonrpc": "2.0", "method": "call", "params": {}, "id": "{}"}}"#, - params, id - ); - - let response = handler - .handle_request_sync(&request) - .ok_or("Bridge call failed")?; - - let response = JsonRpc::parse(&response)?; - - match response { - JsonRpc::Success(_) => { - // First we try to unwrap a potential stringification: - let value_response = response.get_result().unwrap().to_owned(); - let string_response = value_response.to_string(); - let maybe_parsed_string: Result = - serde_json::from_str(&string_response); - let sanitized_response = match maybe_parsed_string { - Ok(string) => string, - Err(_) => string_response, - }; - // Below, sanitized_response is the same response but guaranteed without quotes. - // This should be returned as a JsonString for handling in the zome code. - Ok(JsonString::from_json(&sanitized_response)) - } - JsonRpc::Error(_) => Err(HolochainError::ErrorGeneric( - serde_json::to_string(&response.get_error().unwrap()).unwrap(), - )), - _ => Err(HolochainError::ErrorGeneric( - "Bridge call failed".to_string(), - )), - } -} - -#[cfg(test)] -pub mod tests { - use super::*; - use test_utils; - - use crate::{ - context::Context, - instance::{ - tests::{test_context, test_instance_and_context}, - Instance, - }, - nucleus::{ - actions::call_zome_function::{check_capability, validate_call}, - tests::*, - }, - wasm_engine::{ - api::{ - call::ZomeFnCall, - tests::{ - test_function_name, test_parameters, test_zome_api_function_wasm, - test_zome_name, - }, - ZomeApiFunction, - }, - Defn, - }, - workflows::author_entry::author_entry, - }; - use crossbeam_channel::RecvTimeoutError; - use holochain_core_types::{ - dna::{ - capabilities::CapabilityRequest, - fn_declarations::{FnDeclaration, TraitFns}, - traits::ReservedTraitNames, - Dna, - }, - entry::{ - cap_entries::{CapFunctions, CapTokenGrant, CapabilityType}, - Entry, - }, - error::{DnaError, HolochainError}, - signature::Signature, - }; - use holochain_json_api::json::JsonString; - use holochain_persistence_api::cas::content::{Address, AddressableContent}; - use holochain_wasm_utils::api_serialization::ZomeFnCallArgs; - use serde_json; - use std::{collections::BTreeMap, sync::Arc}; - use test_utils::create_test_dna_with_defs; - - /// dummy commit args from standard test entry - #[cfg_attr(tarpaulin, skip)] - pub fn test_bad_args_bytes() -> Vec { - let args = ZomeFnCallArgs { - instance_handle: "instance_handle".to_string(), - zome_name: "zome_name".to_string(), - cap_token: Address::from("bad cap_token"), - fn_name: "fn_name".to_string(), - fn_args: "fn_args".to_string(), - }; - serde_json::to_string(&args) - .expect("args should serialize") - .into_bytes() - } - - #[cfg_attr(tarpaulin, skip)] - pub fn test_args_bytes() -> Vec { - let args = ZomeFnCallArgs { - instance_handle: THIS_INSTANCE.to_string(), - zome_name: test_zome_name(), - cap_token: Address::from("test_token"), - fn_name: test_function_name(), - fn_args: test_parameters().to_string(), - }; - serde_json::to_string(&args) - .expect("args should serialize") - .into_bytes() - } - - #[allow(dead_code)] - pub struct TestSetup { - pub context: Arc, - pub instance: Instance, - } - - pub fn setup_test(dna: Dna, netname: &str) -> TestSetup { - let netname = Some(netname); - let (instance, context) = - test_instance_and_context(dna, netname).expect("Could not initialize test instance"); - TestSetup { context, instance } - } - - #[cfg_attr(tarpaulin, skip)] - fn test_reduce_call( - test_setup: &TestSetup, - cap_request: CapabilityRequest, - expected: Result, RecvTimeoutError>, - ) { - let zome_call = ZomeFnCall::new("test_zome", cap_request, "test", "{}"); - let result = test_setup - .context - .block_on(call_zome_function(zome_call, test_setup.context.clone())); - assert_eq!(expected, Ok(result)); - } - - #[test] - fn test_call_no_zome() { - let dna = test_utils::create_test_dna_with_wat("bad_zome", None); - let test_setup = setup_test(dna, "test_call_no_zome"); - let expected = Ok(Err(HolochainError::Dna(DnaError::ZomeNotFound( - r#"Zome 'test_zome' not found"#.to_string(), - )))); - test_reduce_call(&test_setup, dummy_capability_request(), expected); - } - - fn setup_dna_for_test(make_public: bool) -> Dna { - let wasm = test_zome_api_function_wasm(ZomeApiFunction::Call.as_str()); - let mut trait_fns = TraitFns::new(); - let fn_decl = FnDeclaration { - name: test_function_name(), - inputs: Vec::new(), - outputs: Vec::new(), - }; - trait_fns.functions = vec![fn_decl.name.clone()]; - let mut traits = BTreeMap::new(); - let trait_name = if make_public { - ReservedTraitNames::Public.as_str().to_string() - } else { - "test_trait".to_string() - }; - traits.insert(trait_name, trait_fns); - let mut functions = Vec::new(); - functions.push(fn_decl); - - create_test_dna_with_defs(&test_zome_name(), (functions, traits), &wasm) - } - - // success to test_reduce_call is when the function gets called which shows up as an - // argument deserialization error because we are reusing the wasm from test_zome_api_function - // which just passes the function parameter through to "invoke_call" which expects a - // ZomeFnCallArgs struct which the test "{}" is not! - // TODO: fix this bit of crazyness - fn success_expected() -> Result, RecvTimeoutError> { - Ok(Err(HolochainError::RibosomeFailed( - "Zome function failure: Argument deserialization failed".to_string(), - ))) - } - - #[test] - fn test_call_public() { - let dna = setup_dna_for_test(true); - let test_setup = setup_test(dna, "test_call_public"); - let token = test_setup.context.get_public_token().unwrap(); - let other_agent_context = test_context("other agent", None); - let cap_request = make_cap_request_for_call(other_agent_context, token, "test", "{}"); - - // make the call with public token capability call - test_reduce_call(&test_setup, cap_request, success_expected()); - - // make the call with a bogus public token capability call - let cap_request = CapabilityRequest::new( - Address::from("foo_token"), - Address::from("some caller"), - Signature::fake(), - ); - let expected_failure = Ok(Err(HolochainError::CapabilityCheckFailed)); - test_reduce_call(&test_setup, cap_request, expected_failure); - } - - #[test] - fn test_call_transferable() { - let dna = setup_dna_for_test(false); - let test_setup = setup_test(dna, "test_call_transferable"); - let expected_failure = Ok(Err(HolochainError::CapabilityCheckFailed)); - - // make the call with an invalid capability call, i.e. incorrect token - let cap_request = CapabilityRequest::new( - Address::from("foo_token"), - Address::from("some caller"), - Signature::fake(), - ); - test_reduce_call(&test_setup, cap_request.clone(), expected_failure.clone()); - - // make the call with an valid capability call from self - let cap_request = test_agent_capability_request(test_setup.context.clone(), "test", "{}"); - test_reduce_call(&test_setup, cap_request, success_expected()); - - // make the call with an invalid valid capability call from self - let cap_request = - test_agent_capability_request(test_setup.context.clone(), "some_fn", "{}"); - test_reduce_call(&test_setup, cap_request, expected_failure); - - let mut cap_functions = CapFunctions::new(); - cap_functions.insert("test_zome".to_string(), vec![String::from("test")]); - // make the call with an valid capability call from a different sources - let grant = CapTokenGrant::create("foo", CapabilityType::Transferable, None, cap_functions) - .unwrap(); - let grant_entry = Entry::CapTokenGrant(grant); - let addr = test_setup - .context - .block_on(author_entry( - &grant_entry, - None, - &test_setup.context, - &vec![], - )) - .unwrap() - .address(); - let other_agent_context = test_context("other agent", None); - let cap_request = - make_cap_request_for_call(other_agent_context.clone(), addr, "test", "{}"); - test_reduce_call(&test_setup, cap_request, success_expected()); - } - - #[test] - fn test_call_assigned() { - let dna = setup_dna_for_test(false); - let test_setup = setup_test(dna, "test_call_assigned"); - let expected_failure = Ok(Err(HolochainError::CapabilityCheckFailed)); - let cap_request = CapabilityRequest::new( - Address::from("foo_token"), - Address::from("any caller"), - Signature::fake(), - ); - test_reduce_call(&test_setup, cap_request, expected_failure.clone()); - - // test assigned capability where the caller is the agent - let agent_token_str = test_setup.context.agent_id.address(); - let cap_request = make_cap_request_for_call( - test_setup.context.clone(), - Address::from(agent_token_str.clone()), - "test", - "{}", - ); - test_reduce_call(&test_setup, cap_request, success_expected()); - - // test assigned capability where the caller is someone else - let other_agent_context = test_context("other agent", None); - let someone = other_agent_context.agent_id.address(); - let mut cap_functions = CapFunctions::new(); - cap_functions.insert("test_zome".to_string(), vec![String::from("test")]); - let grant = CapTokenGrant::create( - "foo", - CapabilityType::Assigned, - Some(vec![someone.clone()]), - cap_functions, - ) - .unwrap(); - let grant_entry = Entry::CapTokenGrant(grant); - let grant_addr = test_setup - .context - .block_on(author_entry( - &grant_entry, - None, - &test_setup.context, - &vec![], - )) - .unwrap() - .address(); - let cap_request = make_cap_request_for_call( - test_context("random other agent", None), - grant_addr.clone(), - "test", - "{}", - ); - test_reduce_call(&test_setup, cap_request, expected_failure.clone()); - - // test assigned capability where the caller is someone else - let cap_request = - make_cap_request_for_call(other_agent_context.clone(), grant_addr, "test", "{}"); - test_reduce_call(&test_setup, cap_request, success_expected()); - } - - #[test] - fn test_validate_call_public() { - let dna = setup_dna_for_test(true); - let test_setup = setup_test(dna, "test_validate_call_public"); - let context = test_setup.context; - - // non existent functions should fail - let zome_call = ZomeFnCall::new("test_zome", dummy_capability_request(), "foo_func", "{}"); - let result = validate_call(context.clone(), &zome_call); - assert_eq!( - result, - Err(HolochainError::Dna(DnaError::ZomeFunctionNotFound( - String::from("Zome function \'foo_func\' not found in Zome \'test_zome\'") - ))) - ); - - // non existent zomes should fial - let zome_call = ZomeFnCall::new("foo_zome", dummy_capability_request(), "test", "{}"); - let result = validate_call(context.clone(), &zome_call); - assert_eq!( - result, - Err(HolochainError::Dna(DnaError::ZomeNotFound(String::from( - "Zome \'foo_zome\' not found" - )))) - ); - } - - #[test] - fn test_validate_call_by_agent() { - let dna = setup_dna_for_test(false); - let test_setup = setup_test(dna, "validate_call_by_agent"); - let context = test_setup.context; - - // non public call should fail - let zome_call = ZomeFnCall::new("test_zome", dummy_capability_request(), "test", "{}"); - let result = validate_call(context.clone(), &zome_call); - assert_eq!(result, Err(HolochainError::CapabilityCheckFailed)); - - // if the agent doesn't correctly sign the call it should fail - let zome_call = ZomeFnCall::new( - "test_zome", - make_cap_request_for_call( - context.clone(), - Address::from(context.agent_id.address()), // <- agent token - "foo_function", //<- not the function in the zome_call! - "{}", - ), - "test", - "{}", - ); - - let result = validate_call(context.clone(), &zome_call); - assert_eq!(result, Err(HolochainError::CapabilityCheckFailed)); - - // should work with correctly signed cap_request - let zome_call = ZomeFnCall::new( - "test_zome", - make_cap_request_for_call( - context.clone(), - Address::from(context.agent_id.address()), // <- agent token - "test", - "{}", - ), - "test", - "{}", - ); - let result = validate_call(context.clone(), &zome_call); - assert!(result.is_ok()); - } - - #[test] - fn test_check_capability_transferable() { - let dna = setup_dna_for_test(false); - let test_setup = setup_test(dna, "test_check_cap_transferable"); - let context = test_setup.context; - - // bogus cap_request should fail - let zome_call = ZomeFnCall::new( - "test_zome", - CapabilityRequest::new( - Address::from("foo_token"), - Address::from("some caller"), - Signature::fake(), - ), - "test", - "{}", - ); - assert!(!check_capability(context.clone(), &zome_call)); - - let mut cap_functions = CapFunctions::new(); - cap_functions.insert("test_zome".to_string(), vec![String::from("test")]); - // add the transferable grant and get the token which is the grant's address - let grant = CapTokenGrant::create("foo", CapabilityType::Transferable, None, cap_functions) - .unwrap(); - let grant_entry = Entry::CapTokenGrant(grant); - let grant_addr = context - .block_on(author_entry(&grant_entry, None, &context, &vec![])) - .unwrap() - .address(); - - // make the call with a valid capability call from a random source should succeed - let zome_call = ZomeFnCall::new( - "test_zome", - make_cap_request_for_call( - test_context("some_random_agent", None), - grant_addr, - "test", - "{}", - ), - "test", - "{}", - ); - assert!(check_capability(context.clone(), &zome_call)); - } -} diff --git a/crates/core/src/wasm_engine/api/capabilities.rs b/crates/core/src/wasm_engine/api/capabilities.rs deleted file mode 100644 index 9080072912..0000000000 --- a/crates/core/src/wasm_engine/api/capabilities.rs +++ /dev/null @@ -1,138 +0,0 @@ -use crate::{ - agent::actions::commit::commit_entry, - wasm_engine::{api::ZomeApiResult, Runtime}, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_core_types::{ - entry::{ - cap_entries::{CapTokenClaim, CapTokenGrant}, - Entry, - }, - error::HolochainError, -}; -use holochain_persistence_api::cas::content::Address; - -use holochain_wasm_utils::api_serialization::capabilities::{ - CommitCapabilityClaimArgs, CommitCapabilityGrantArgs, -}; -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; - -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_commit_capability_grant(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - let args = match CommitCapabilityGrantArgs::try_from(args_str) { - Ok(input) => input, - Err(..) => return ribosome_error_code!(ArgumentDeserializationFailed), - }; - - let task_result: Result = - match CapTokenGrant::create(&args.id, args.cap_type, args.assignees, args.functions) { - Ok(grant) => context.block_on(commit_entry( - Entry::CapTokenGrant(grant), - None, - &context.clone(), - )), - Err(err) => Err(HolochainError::ErrorGeneric(format!( - "Unable to commit capability grant: {}", - err - ))), - }; - - runtime.store_result(task_result) -} -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_commit_capability_claim(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - let args = match CommitCapabilityClaimArgs::try_from(args_str) { - Ok(input) => input, - Err(..) => return ribosome_error_code!(ArgumentDeserializationFailed), - }; - - let claim = CapTokenClaim::new(args.id, args.grantor, args.token); - let task_result: Result = context.block_on(commit_entry( - Entry::CapTokenClaim(claim), - None, - &context.clone(), - )); - runtime.store_result(task_result) -} - -#[cfg(test)] -pub mod tests { - use crate::wasm_engine::{ - api::{tests::test_zome_api_function, ZomeApiFunction}, - Defn, - }; - use holochain_core_types::{entry::cap_entries::CapabilityType, error::ZomeApiInternalResult}; - use holochain_json_api::json::JsonString; - use holochain_persistence_api::cas::content::Address; - use holochain_wasm_utils::api_serialization::capabilities::{ - CommitCapabilityClaimArgs, CommitCapabilityGrantArgs, - }; - use std::collections::BTreeMap; - - /// dummy args - pub fn test_commit_capability_grant_args_bytes() -> Vec { - let mut functions = BTreeMap::new(); - functions.insert("test_zome".to_string(), vec!["test_function".to_string()]); - let grant_args = CommitCapabilityGrantArgs { - id: "some_id".to_string(), - cap_type: CapabilityType::Assigned, - assignees: Some(vec![Address::from("fake address")]), - functions, - }; - - JsonString::from(grant_args).to_bytes() - } - - pub fn test_commit_capability_claim_args_bytes() -> Vec { - let claim_args = CommitCapabilityClaimArgs { - id: "some_id".to_string(), - grantor: Address::from("fake grantor"), - token: Address::from("fake"), - }; - - JsonString::from(claim_args).to_bytes() - } - - #[test] - /// test that we can round trip bytes through a commit_capability_grant action and get the result from WASM - fn test_commit_capability_grant_round_trip() { - let (call_result, _) = test_zome_api_function( - ZomeApiFunction::CommitCapabilityGrant.as_str(), - test_commit_capability_grant_args_bytes(), - ); - - assert_eq!( - call_result, - JsonString::from_json( - &(String::from(JsonString::from(ZomeApiInternalResult::success( - Address::from("Qma8KWBHZwiXNBJ4PBtT4uDUVgPAyUJASHumThZMTPAAJe") - ))) + "\u{0}") - ), - ); - } - - #[test] - /// test that we can round trip bytes through a commit_capability_claim action and get the result from WASM - fn test_commit_capability_claim_round_trip() { - let (call_result, _) = test_zome_api_function( - ZomeApiFunction::CommitCapabilityClaim.as_str(), - test_commit_capability_claim_args_bytes(), - ); - - assert_eq!( - call_result, - JsonString::from_json( - &(String::from(JsonString::from(ZomeApiInternalResult::success( - Address::from("QmeuneB3iJjcGMkei7N8kyoc7Ubi4ab3xMNPYXSse2vdm5") - ))) + "\u{0}") - ), - ); - } -} diff --git a/crates/core/src/wasm_engine/api/commit.rs b/crates/core/src/wasm_engine/api/commit.rs deleted file mode 100644 index 3df2b724e4..0000000000 --- a/crates/core/src/wasm_engine/api/commit.rs +++ /dev/null @@ -1,115 +0,0 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, Runtime}, - workflows::author_entry::author_entry, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_core_types::error::HolochainError; - -use holochain_wasm_utils::api_serialization::commit_entry::{CommitEntryArgs, CommitEntryResult}; - -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; - -/// ZomeApiFunction::CommitAppEntry function code -/// args: [0] encoded MemoryAllocation as u64 -/// Expected complex argument: CommitEntryArg -/// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_commit_app_entry(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - let commit_entry_arg = match CommitEntryArgs::try_from(args_str.clone()) { - Ok(commit_entry_arg_input) => commit_entry_arg_input, - // Exit on error - Err(error) => { - log_error!( - context, - "zome: invoke_commit_app_commit_entry_arg failed to \ - deserialize Entry: {:?} with error {:?}", - args_str, - error - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - }; - let span = context - .tracer - .span("hdk invoke_commit_app_entry") - .tag(ht::Tag::new( - "CommitEntryArgs", - format!("{:?}", commit_entry_arg), - )) - .start() - .into(); - let _spanguard = ht::push_span(span); - - // Wait for future to be resolved - let task_result: Result = context.block_on(author_entry( - &commit_entry_arg.entry(), - None, - &context, - &commit_entry_arg.options().provenance(), - )); - - runtime.store_result(task_result) -} - -#[cfg(test)] -pub mod tests { - use crate::wasm_engine::{ - api::{tests::test_zome_api_function, ZomeApiFunction}, - Defn, - }; - use holochain_core_types::{ - entry::test_entry, - error::ZomeApiInternalResult, - signature::{Provenance, Signature}, - }; - use holochain_json_api::json::JsonString; - use holochain_persistence_api::cas::content::{Address, AddressableContent}; - use holochain_wasm_utils::api_serialization::commit_entry::{ - CommitEntryArgs, CommitEntryOptions, CommitEntryResult, - }; - - /// dummy commit with provenance args from standard test entry - pub fn test_commit_entry_args_bytes() -> Vec { - let entry = test_entry(); - let address: Address = entry.address(); - - let agent_nick = "counter-signer"; - let agent_id = test_utils::mock_signing::registered_test_agent(agent_nick); - - let signature = Signature::from(test_utils::mock_signing::mock_signer( - String::from(address.clone()), - &agent_id, - )); - - let provenances = vec![Provenance::new(agent_id.address(), signature)]; - let serialized_commit_entry_arg = - CommitEntryArgs::new(entry, CommitEntryOptions::new(provenances)); - JsonString::from(serialized_commit_entry_arg).to_bytes() - } - - #[test] - /// test that we can round trip bytes through a commit action with - /// additional provenance and get the result from WASM - fn test_commit_round_trip() { - let (call_result, _) = test_zome_api_function( - ZomeApiFunction::CommitAppEntry.as_str(), - test_commit_entry_args_bytes(), - ); - - assert_eq!( - call_result, - JsonString::from_json( - &(String::from(JsonString::from(ZomeApiInternalResult::success( - CommitEntryResult::new(Address::from( - "Qma6RfzvZRL127UCEVEktPhQ7YSS1inxEFw7SjEsfMJcrq" - )) - ))) + "\u{0}") - ), - ); - } -} diff --git a/crates/core/src/wasm_engine/api/crypto.rs b/crates/core/src/wasm_engine/api/crypto.rs deleted file mode 100644 index cc36e29416..0000000000 --- a/crates/core/src/wasm_engine/api/crypto.rs +++ /dev/null @@ -1,117 +0,0 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, Runtime}, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_json_api::json::*; -use holochain_wasm_utils::api_serialization::crypto::CryptoArgs; -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; - -/// ZomeApiFunction::Sign function code -/// args: [0] encoded MemoryAllocation as u64 -/// Expected argument: u64 -/// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_crypto(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - - let crypto_args = match CryptoArgs::try_from(args_str.clone()) { - Ok(entry_input) => entry_input, - // Exit on error - Err(_) => { - log_error!( - context, - "zome: invoke_crypto failed to deserialize SignArgs: {:?}", - args_str - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - }; - - let message = context - .conductor_api - .execute(crypto_args.payload.clone(), crypto_args.method.clone()) - .map(|sig| JsonString::from_json(&sig)); - - log_debug!( - context, - "zome: crypto method {:?} of data:{:?} by:{:?} is:{:?}", - crypto_args.method, - crypto_args.payload, - context.agent_id, - message - ); - - runtime.store_result(message) -} - -#[cfg(test)] -mod test_super { - use crate::wasm_engine::{ - api::{tests::test_zome_api_function, ZomeApiFunction}, - Defn, - }; - use holochain_core_types::error::ZomeApiInternalResult; - use holochain_json_api::json::*; - use std::convert::TryFrom; - /// test that bytes passed to debug end up in the log - #[test] - fn test_zome_api_crypto_functions() { - let (call_result_json, _) = test_zome_api_function( - ZomeApiFunction::Crypto.as_str(), - r#"{ "payload": "this is data", "method" : "Encrypt" }"# - .as_bytes() - .to_vec(), - ); - - let encrypt_result = ZomeApiInternalResult::try_from(call_result_json) - .expect("Could not try from zomeapiitnernal"); - assert!(encrypt_result.ok); - - let (call_result, _) = test_zome_api_function( - ZomeApiFunction::Crypto.as_str(), - format!( - r#"{{ "payload": "{}", "method" : "Decrypt" }}"#, - encrypt_result.value - ) - .as_bytes() - .to_vec(), - ); - assert_eq!( - JsonString::from_json(r#"{"ok":true,"value":"this is data","error":"null"}"#), - call_result, - ); - } - - #[test] - fn test_zome_api_crypto_signing() { - let payload = r#"{ "payload": "test ' payload", "method" : "Sign" }"#; - let (call_result_json, _) = test_zome_api_function( - ZomeApiFunction::Crypto.as_str(), - payload.as_bytes().to_vec(), - ); - println!("Crypto::Sign( {:?} ) == {:?}", payload, call_result_json); - assert_eq!( - JsonString::from_json( - r#"{"ok":true,"value":"ZDwPQ2TX9Xiq1k73JWczzqWr97rmdAodWWInlGfFjKiE0wFgMc2WvhmaFpNfrCv3y5uSOOLD5MgJqAeDsKb4Cw==","error":"null"}"# - ), - call_result_json - ); - - let payload = r#"{ "payload": "test \" payload", "method" : "Sign" }"#; - let (call_result_json, _) = test_zome_api_function( - ZomeApiFunction::Crypto.as_str(), - payload.as_bytes().to_vec(), - ); - println!("Crypto::Sign( {:?} ) == {:?}", payload, call_result_json); - assert_eq!( - JsonString::from_json( - r#"{"ok":true,"value":"ODn3OE9jcZPfB403T7lFJbySVU4Ugu2Kv/kpkg50lD1cJ5E+gDs3zWwADJjQzkps+qp03k6C5ygegcGd2ERoCA==","error":"null"}"# - ), - call_result_json - ); - } -} diff --git a/crates/core/src/wasm_engine/api/emit_signal.rs b/crates/core/src/wasm_engine/api/emit_signal.rs deleted file mode 100644 index e476ca225a..0000000000 --- a/crates/core/src/wasm_engine/api/emit_signal.rs +++ /dev/null @@ -1,115 +0,0 @@ -use crate::{ - signal::{Signal, UserSignal}, - wasm_engine::{api::ZomeApiResult, Runtime}, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_wasm_utils::api_serialization::emit_signal::EmitSignalArgs; -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; - -/// ZomeApiFunction::EmitSignal function code -/// args: [0] encoded MemoryAllocation as u64 -/// Expecting a string as complex input argument -/// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_emit_signal(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - - let args_str = runtime.load_json_string_from_args(&args); - let emit_signal_args = match EmitSignalArgs::try_from(args_str.clone()) { - Ok(args) => args, - // Exit on error - Err(error) => { - log_error!( - context, - "zome: invoke_emit_signal failed to \ - deserialize arguments: {:?} with error {:?}", - args_str, - error - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - }; - - if let Some(sender) = context.signal_tx() { - let signal = Signal::User(UserSignal::from(emit_signal_args)); - let _ = sender.send(signal).map_err(|err| { - log_error!( - context, - "zome: invoke_emit_signal() could not send signal: {:?}", - err, - ); - }); - } else { - log_error!(context, "zome: invoke_emit_signal() could not send signal because signal channel is not set up!"); - } - - // We only log this case but still return Ok(()) since the semantic of sending a signal - // is all about decoupling sender and receiver - if nobody is listening, the sender - // should not care.. - ribosome_success!() -} - -#[cfg(test)] -pub mod tests { - use crate::{ - instance::tests::test_instance_and_context, - signal::{Signal, UserSignal}, - wasm_engine::{ - api::{ - tests::{test_zome_api_function_call, test_zome_api_function_wasm, test_zome_name}, - ZomeApiFunction, - }, - Defn, - }, - }; - use crossbeam_channel::unbounded; - use holochain_json_api::json::JsonString; - use holochain_wasm_utils::api_serialization::emit_signal::EmitSignalArgs; - use std::sync::Arc; - - pub fn test_signal() -> UserSignal { - UserSignal::from(test_args()) - } - - pub fn test_args() -> EmitSignalArgs { - EmitSignalArgs { - name: String::from("test-signal"), - arguments: JsonString::from_json("{message: \"Hello\"}"), - } - } - - pub fn test_args_bytes() -> Vec { - let args_string: JsonString = test_args().into(); - args_string.to_string().into_bytes() - } - - /// test that bytes passed to debug end up in the log - #[test] - fn test_zome_api_function_emit_signal() { - let wasm = test_zome_api_function_wasm(ZomeApiFunction::EmitSignal.as_str()); - let dna = test_utils::create_test_dna_with_wasm(&test_zome_name(), wasm.clone()); - - let (_instance, context) = - test_instance_and_context(dna, None).expect("Could not create test instance"); - - let (tx, rx) = unbounded::(); - let mut context = (*context).clone(); - context.signal_tx = Some(tx); - let context = Arc::new(context); - - let args_string: JsonString = test_args().into(); - println!("{}", args_string.to_string()); - - let _ = test_zome_api_function_call(context.clone(), test_args_bytes()); - - let received = rx.try_recv(); - assert!(received.is_ok()); - let signal = received.unwrap(); - if let Signal::User(user_signal) = signal { - assert_eq!(user_signal, test_signal()); - } else { - assert!(false, "Expected a Signal::User"); - } - } -} diff --git a/crates/core/src/wasm_engine/api/entry_address.rs b/crates/core/src/wasm_engine/api/entry_address.rs deleted file mode 100644 index c10ca19a11..0000000000 --- a/crates/core/src/wasm_engine/api/entry_address.rs +++ /dev/null @@ -1,65 +0,0 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, Runtime}, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_core_types::{ - self, - dna::Dna, - entry::{entry_type::EntryType, Entry}, - error::RibosomeRuntimeBits, -}; -use holochain_persistence_api::cas::content::AddressableContent; - -use std::{convert::TryFrom, str::FromStr}; -use wasmi::{RuntimeArgs, RuntimeValue}; - -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn get_entry_type(dna: &Dna, entry_type_name: &str) -> Result> { - let entry_type = EntryType::from_str(&entry_type_name).map_err(|_| { - Some(RuntimeValue::I64( - holochain_core_types::error::RibosomeErrorCode::UnknownEntryType as RibosomeRuntimeBits, - )) - })?; - - // Check if AppEntry is a valid AppEntryType - if entry_type.is_app() { - let result = dna.get_entry_type_def(entry_type_name); - if result.is_none() { - return Err(Some(RuntimeValue::I64( - holochain_core_types::error::RibosomeErrorCode::UnknownEntryType - as RibosomeRuntimeBits, - ))); - } - } - // Done - Ok(entry_type) -} - -/// ZomeApiFunction::entry_address function code -/// args: [0] encoded MemoryAllocation as u64 -/// Expected complex argument: entry_type_name and entry_value as JsonString -/// Returns an HcApiReturnCode as I64 -pub fn invoke_entry_address(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - let entry = match Entry::try_from(args_str) { - Ok(input) => input, - Err(_) => return ribosome_error_code!(ArgumentDeserializationFailed), - }; - - // Check if entry_type is valid - let dna = context - .state() - .unwrap() - .nucleus() - .dna() - .expect("Should have DNA"); - let maybe_entry_type = get_entry_type(&dna, &entry.entry_type().to_string()); - if let Err(err) = maybe_entry_type { - return Ok(err); - } - - // Return result - runtime.store_result(Ok(entry.address())) -} diff --git a/crates/core/src/wasm_engine/api/get_entry.rs b/crates/core/src/wasm_engine/api/get_entry.rs deleted file mode 100644 index 27b0e8ed2d..0000000000 --- a/crates/core/src/wasm_engine/api/get_entry.rs +++ /dev/null @@ -1,312 +0,0 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, Runtime}, - workflows::get_entry_result::get_entry_result_workflow, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_wasm_utils::api_serialization::get_entry::GetEntryArgs; -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; - -/// ZomeApiFunction::GetAppEntry function code -/// args: [0] encoded MemoryAllocation as u64 -/// Expected complex argument: GetEntryArgs -/// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_get_entry(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - let input = match GetEntryArgs::try_from(args_str.clone()) { - Ok(input) => input, - // Exit on error - Err(_) => { - log_error!( - context, - "zome: invoke_get_entry() failed to deserialize: {:?}", - args_str - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - }; - // Create workflow future and block on it - let result = context.block_on(get_entry_result_workflow(&context, &input)); - // Store result in wasm memory - runtime.store_result(result) -} - -#[cfg(test)] -pub mod tests { - use test_utils; - use wabt; - - use self::wabt::Wat2Wasm; - use crate::{ - instance::tests::test_instance_and_context, - nucleus::{tests::test_capability_request, ZomeFnCall}, - wasm_engine::{ - self, - api::{ - commit::tests::test_commit_entry_args_bytes, - tests::{test_parameters, test_zome_name}, - }, - runtime::WasmCallData, - }, - }; - use holochain_core_types::{ - crud_status::CrudStatus, - entry::{test_entry, EntryWithMeta}, - error::ZomeApiInternalResult, - }; - use holochain_json_api::json::JsonString; - use holochain_persistence_api::cas::content::{Address, AddressableContent}; - use holochain_wasm_utils::api_serialization::{commit_entry::CommitEntryResult, get_entry::*}; - - use std::sync::Arc; - - /// dummy get args from standard test entry - pub fn test_get_args_bytes() -> Vec { - let entry_args = GetEntryArgs { - address: test_entry().address(), - options: GetEntryOptions::new( - StatusRequestKind::Latest, - true, - false, - Default::default(), - ), - }; - JsonString::from(entry_args).to_bytes() - } - - /// dummy get args from standard test entry - pub fn test_get_args_unknown() -> Vec { - let entry_args = GetEntryArgs { - address: Address::from("xxxxxxxxx"), - options: GetEntryOptions::new( - StatusRequestKind::Latest, - true, - false, - Default::default(), - ), - }; - JsonString::from(entry_args).to_bytes() - } - - /// wat string that exports both get and a commit dispatches so we can test a round trip - pub fn test_get_round_trip_wat() -> Vec { - Wat2Wasm::new() - .canonicalize_lebs(false) - .write_debug_names(true) - .convert( - r#" -(module - (import "env" "hc_get_entry" - (func $get - (param i64) - (result i64) - ) - ) - - (import "env" "hc_commit_entry" - (func $commit - (param i64) - (result i64) - ) - ) - - (memory 1) - (export "memory" (memory 0)) - - (func - (export "get_dispatch") - (param $allocation i64) - (result i64) - - (call - $get - (get_local $allocation) - ) - ) - - (func - (export "commit_dispatch") - (param $allocation i64) - (result i64) - - (call - $commit - (get_local $allocation) - ) - ) - - (func - (export "__hdk_validate_app_entry") - (param $allocation i64) - (result i64) - - (i64.const 0) - ) - - (func - (export "__hdk_validate_agent_entry") - (param $allocation i64) - (result i64) - - (i64.const 0) - ) - - (func - (export "__hdk_get_validation_package_for_entry_type") - (param $allocation i64) - (result i64) - - ;; This writes "Entry" into memory - (i64.store (i32.const 0) (i64.const 34)) - (i64.store (i32.const 1) (i64.const 69)) - (i64.store (i32.const 2) (i64.const 110)) - (i64.store (i32.const 3) (i64.const 116)) - (i64.store (i32.const 4) (i64.const 114)) - (i64.store (i32.const 5) (i64.const 121)) - (i64.store (i32.const 6) (i64.const 34)) - - (i64.const 7) - ) - - (func - (export "__list_traits") - (param $allocation i64) - (result i64) - - (i64.const 0) - ) - - (func - (export "__list_functions") - (param $allocation i64) - (result i64) - - (i64.const 0) - ) -) - "#, - ) - .unwrap() - .as_ref() - .to_vec() - } - - #[test] - /// test that we can round trip bytes through a get action and it comes back from wasm - fn test_get_round_trip() { - let netname = Some("test_get_round_trip"); - let wasm = Arc::new(test_get_round_trip_wat()); - let dna = test_utils::create_test_dna_with_wasm(&test_zome_name(), (*wasm).clone()); - let (instance, context) = test_instance_and_context(dna.clone(), netname) - .expect("Could not initialize test instance"); - let context = instance.initialize_context(context); - - println!("{:?}", instance.state().agent().top_chain_header()); - println!( - "{:?}", - instance - .state() - .agent() - .top_chain_header() - .expect("top chain_header was None") - .address() - ); - - let commit_call = ZomeFnCall::new( - &test_zome_name(), - test_capability_request(context.clone(), "commit_dispatch", test_parameters()), - "commit_dispatch", - test_parameters(), - ); - let call_result = wasm_engine::run_dna( - Some(test_commit_entry_args_bytes()), - WasmCallData::new_zome_call(Arc::clone(&context), commit_call), - ) - .expect("test should be callable"); - - assert_eq!( - call_result, - JsonString::from_json( - &(String::from(JsonString::from(ZomeApiInternalResult::success( - CommitEntryResult::new(test_entry().address()) - ))) + "\u{0}") - ), - ); - - let get_call = ZomeFnCall::new( - &test_zome_name(), - test_capability_request(context.clone(), "get_dispatch", test_parameters()), - "get_dispatch", - test_parameters(), - ); - let call_result = wasm_engine::run_dna( - Some(test_get_args_bytes()), - WasmCallData::new_zome_call(Arc::clone(&context), get_call), - ) - .expect("test should be callable"); - - let entry = test_entry(); - let entry_with_meta = EntryWithMeta { - entry: entry.clone(), - crud_status: CrudStatus::Live, - maybe_link_update_delete: None, - }; - // let header = create_new_chain_header(&entry, context.clone(), &None); - let entry_result = - GetEntryResult::new(StatusRequestKind::Latest, Some((&entry_with_meta, vec![]))); - assert_eq!( - JsonString::from(ZomeApiInternalResult::success(entry_result)), - call_result, - ); - } - - #[test] - #[cfg(not(windows))] - /// test that we get status NotFound on an obviously broken address - fn test_get_not_found() { - // let wasm = test_get_round_trip_wat(); - // let dna = test_utils::create_test_dna_with_wasm( - // &test_zome_name(), - // wasm.clone(), - // ); - // let instance = test_instance(dna.clone()).expect("Could not initialize test instance"); - // let (context, _) = test_context_and_logger("joan"); - // let context = instance.initialize_context(context); - // - // println!("{:?}", instance.state().agent().top_chain_header()); - // println!( - // "{:?}", - // instance - // .state() - // .agent() - // .top_chain_header() - // .expect("top chain_header was None") - // .address() - // ); - // - // let get_call = ZomeFnCall::new( - // &test_zome_name(), - // test_capability_request(), - // "get_dispatch", - // test_parameters(), - // ); - // let call_result = ribosome::run_dna( - // &dna.name.to_string(), - // Arc::clone(&context), - // wasm.clone(), - // &get_call, - // Some(test_get_args_unknown()), - // ) - // .expect("test should be callable"); - // - // assert_eq!( - // JsonString::from(String::from(JsonString::from( - // ZomeApiInternalResult::success(GetEntryResult::new(StatusRequestKind::Latest, None)) - // ))), - // call_result, - // ); - } -} diff --git a/crates/core/src/wasm_engine/api/get_links.rs b/crates/core/src/wasm_engine/api/get_links.rs deleted file mode 100644 index 084e957457..0000000000 --- a/crates/core/src/wasm_engine/api/get_links.rs +++ /dev/null @@ -1,445 +0,0 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, Runtime}, - workflows::get_link_result::get_link_result_workflow, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_wasm_utils::api_serialization::get_links::GetLinksArgs; -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; - -/// ZomeApiFunction::GetLinks function code. -/// args: [0] encoded MemoryAllocation as u64 -/// Expected complex argument: GetLinksArgs -/// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_get_links(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - let input = match GetLinksArgs::try_from(args_str.clone()) { - Ok(input) => { - log_debug!( - context, - "zome/get_links: invoke_get_links called with {:?}", - input, - ); - input - } - Err(_) => { - log_error!( - context, - "zome/get_links: invoke_get_links failed to deserialize GetLinksArgs: {:?}", - args_str - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - }; - - let result = context.block_on(get_link_result_workflow(&context, &input)); - - runtime.store_result(result) -} - -#[cfg(test)] -pub mod tests { - use crate::instance::Instance; - use std::sync::Arc; - use test_utils; - - use crate::{ - agent::actions::commit::commit_entry, - context::Context, - dht::actions::hold_aspect::hold_aspect, - instance::tests::{ - test_context_and_logger_with_in_memory_network, test_instance_and_context, - }, - wasm_engine::{ - api::{tests::*, ZomeApiFunction}, - Defn, - }, - }; - use holochain_core_types::{ - agent::test_agent_id, - chain_header::test_chain_header, - entry::{entry_type::test_app_entry_type, Entry}, - link::{link_data::LinkData, Link, LinkMatch}, - network::entry_aspect::EntryAspect, - }; - use holochain_json_api::json::{JsonString, RawString}; - use holochain_persistence_api::cas::content::Address; - use holochain_wasm_utils::api_serialization::get_links::GetLinksArgs; - use serde_json; - - /// dummy link_entries args from standard test entry - pub fn test_get_links_args_bytes( - base: &Address, - link_type: LinkMatch, - tag: LinkMatch, - ) -> Vec { - let args = GetLinksArgs { - entry_address: base.clone(), - link_type: link_type.to_regex_string().unwrap(), - tag: tag.to_regex_string().unwrap(), - options: Default::default(), - }; - println!("GetLinksArgs: {:?}", args); - serde_json::to_string(&args) - .expect("args should serialize") - .into_bytes() - } - - fn add_test_entries(initialized_context: Arc) -> Vec
{ - let mut entry_addresses: Vec
= Vec::new(); - for i in 0..3 { - let entry = Entry::App( - test_app_entry_type(), - JsonString::from(RawString::from(format!("entry{} value", i))), - ); - let address = initialized_context - .block_on(commit_entry(entry, None, &initialized_context)) - .expect("Could not commit entry for testing"); - entry_addresses.push(address); - } - entry_addresses - } - - fn initialize_context(netname: &str) -> (Instance, Arc) { - let wasm = test_zome_api_function_wasm(ZomeApiFunction::GetLinks.as_str()); - let dna = test_utils::create_test_dna_with_wasm(&test_zome_name(), wasm.clone()); - let netname2 = format!("{}-2", netname); - let (instance, _) = - test_instance_and_context(dna, Some(netname)).expect("Could not create test instance"); - let (context, _) = - test_context_and_logger_with_in_memory_network("joan", Some(netname2.as_str())); - let arc_context = instance.initialize_context(context); - (instance, arc_context) - } - - pub fn add_links(initialized_context: Arc, links: Vec) { - links.iter().for_each(|link| { - println!("adding link {:?}", link); - assert!(initialized_context //commit the AddLink entry first - .block_on(commit_entry( - link.add_entry(test_chain_header(), test_agent_id()), - None, - &initialized_context - )) - .is_ok()); - assert!(initialized_context - .block_on(hold_aspect( - EntryAspect::LinkAdd( - LinkData::add_from_link(link, test_chain_header(), test_agent_id()), - test_chain_header(), - ), - initialized_context.clone() - )) - .is_ok()); - println!("added link {:?}", link); - }); - } - - pub fn get_links( - initialized_context: Arc, - base: &Address, - link_type: LinkMatch, - tag: LinkMatch, - ) -> JsonString { - test_zome_api_function_call( - initialized_context.clone(), - test_get_links_args_bytes(&base, link_type, tag), - ) - } - - // TODO do this for all crate tests somehow - fn enable_logging_for_test() { - if std::env::var("RUST_LOG").is_err() { - std::env::set_var("RUST_LOG", "trace"); - } - let _ = env_logger::builder() - .default_format_timestamp(false) - .default_format_module_path(false) - .is_test(true) - .try_init(); - } - - #[test] - fn returns_list_of_links() { - enable_logging_for_test(); - // setup the instance and links - let (_instance, initialized_context) = initialize_context("returns_list_of_links"); - let entry_addresses = add_test_entries(initialized_context.clone()); - let links = vec![ - Link::new( - &entry_addresses[0], - &entry_addresses[1], - "test-type", - "test-tag", - ), - Link::new( - &entry_addresses[0], - &entry_addresses[2], - "test-type", - "test-tag", - ), - ]; - add_links(initialized_context.clone(), links); - - // calling get_links returns both links in some order - let call_result = get_links( - initialized_context.clone(), - &entry_addresses[0], - LinkMatch::Exactly("test-type".into()), - LinkMatch::Exactly("test-tag".into()), - ); - let expected_1 = JsonString::from_json( - &(format!( - r#"{{"ok":true,"value":"{{\"links\":[{{\"address\":\"{}\",\"headers\":[],\"tag\":\"{}\",\"status\":\"live\"}},{{\"address\":\"{}\",\"headers\":[],\"tag\":\"{}\",\"status\":\"live\"}}]}}","error":"null"}}"#, - entry_addresses[1], "test-tag", entry_addresses[2], "test-tag", - ) + "\u{0}"), - ); - let expected_2 = JsonString::from_json( - &(format!( - r#"{{"ok":true,"value":"{{\"links\":[{{\"address\":\"{}\",\"headers\":[],\"tag\":\"{}\",\"status\":\"live\"}},{{\"address\":\"{}\",\"headers\":[],\"tag\":\"{}\",\"status\":\"live\"}}]}}","error":"null"}}"#, - entry_addresses[2], "test-tag", entry_addresses[1], "test-tag", - ) + "\u{0}"), - ); - assert!( - call_result == expected_1 || call_result == expected_2, - "\n call_result = '{:?}'\n ordering1 = '{:?}'\n ordering2 = '{:?}'", - call_result, - expected_1, - expected_2, - ); - } - - #[test] - fn get_links_with_non_existent_type_returns_nothing() { - let (_instance, initialized_context) = - initialize_context("get_links_with_non_existent_type_returns_nothing"); - let entry_addresses = add_test_entries(initialized_context.clone()); - let links = vec![ - Link::new( - &entry_addresses[0], - &entry_addresses[1], - "test-type", - "test-tag", - ), - Link::new( - &entry_addresses[0], - &entry_addresses[2], - "test-type", - "test-tag", - ), - ]; - add_links(initialized_context.clone(), links); - - // calling get_links with another non-existent type returns nothing - let call_result = get_links( - initialized_context.clone(), - &entry_addresses[0], - LinkMatch::Exactly("other-type".into()), - LinkMatch::Exactly("test-tag".into()), - ); - assert_eq!( - call_result, - JsonString::from_json( - &(String::from(r#"{"ok":true,"value":"{\"links\":[]}","error":"null"}"#,) - + "\u{0}") - ), - ); - } - - #[test] - fn get_links_with_non_existent_tag_returns_nothing() { - let (_instance, initialized_context) = - initialize_context("get_links_with_non_existent_tag_returns_nothing"); - let entry_addresses = add_test_entries(initialized_context.clone()); - let links = vec![ - Link::new( - &entry_addresses[0], - &entry_addresses[1], - "test-type", - "test-tag", - ), - Link::new( - &entry_addresses[0], - &entry_addresses[2], - "test-type", - "test-tag", - ), - ]; - add_links(initialized_context.clone(), links); - - // calling get_links with another non-existent tag returns nothing - let call_result = get_links( - initialized_context.clone(), - &entry_addresses[0], - LinkMatch::Exactly("test-type".into()), - LinkMatch::Exactly("other-tag".into()), - ); - assert_eq!( - call_result, - JsonString::from_json( - &(String::from(r#"{"ok":true,"value":"{\"links\":[]}","error":"null"}"#,) - + "\u{0}") - ), - ); - } - - #[test] - fn can_get_all_links_of_any_tag_or_type() { - // setup the instance and links - let (_instance, initialized_context) = - initialize_context("can_get_all_links_of_any_tag_or_type"); - let entry_addresses = add_test_entries(initialized_context.clone()); - let links = vec![ - Link::new( - &entry_addresses[0], - &entry_addresses[1], - "test-type1", - "test-tag1", - ), - Link::new( - &entry_addresses[0], - &entry_addresses[2], - "test-type2", - "test-tag2", - ), - ]; - add_links(initialized_context.clone(), links); - - let call_result = get_links( - initialized_context.clone(), - &entry_addresses[0], - LinkMatch::Any, - LinkMatch::Any, - ); - let expected_1 = JsonString::from_json( - &(format!( - r#"{{"ok":true,"value":"{{\"links\":[{{\"address\":\"{}\",\"headers\":[],\"tag\":\"{}\",\"status\":\"live\"}},{{\"address\":\"{}\",\"headers\":[],\"tag\":\"{}\",\"status\":\"live\"}}]}}","error":"null"}}"#, - entry_addresses[1], "test-tag1", entry_addresses[2], "test-tag2", - ) + "\u{0}"), - ); - let expected_2 = JsonString::from_json( - &(format!( - r#"{{"ok":true,"value":"{{\"links\":[{{\"address\":\"{}\",\"headers\":[],\"tag\":\"{}\",\"status\":\"live\"}},{{\"address\":\"{}\",\"headers\":[],\"tag\":\"{}\",\"status\":\"live\"}}]}}","error":"null"}}"#, - entry_addresses[2], "test-tag2", entry_addresses[1], "test-tag1", - ) + "\u{0}"), - ); - assert!( - call_result == expected_1 || call_result == expected_2, - "\n call_result = '{:?}'\n ordering1 = '{:?}'\n ordering2 = '{:?}'", - call_result, - expected_1, - expected_2, - ); - } - - #[test] - fn get_links_with_exact_tag_match_returns_only_that_link() { - let (_instance, initialized_context) = - initialize_context("get_links_with_exact_tag_match_returns_only_that"); - let entry_addresses = add_test_entries(initialized_context.clone()); - let links = vec![ - Link::new( - &entry_addresses[0], - &entry_addresses[1], - "test-type", - "test-tag1", - ), - Link::new( - &entry_addresses[0], - &entry_addresses[1], - "test-type", - "test-tag2", - ), - ]; - add_links(initialized_context.clone(), links); - - let call_result = get_links( - initialized_context.clone(), - &entry_addresses[0], - LinkMatch::Exactly("test-type".into()), - LinkMatch::Exactly("test-tag1".into()), - ); - let expected = JsonString::from_json( - &(format!( - r#"{{"ok":true,"value":"{{\"links\":[{{\"address\":\"{}\",\"headers\":[],\"tag\":\"{}\",\"status\":\"live\"}}]}}","error":"null"}}"#, - entry_addresses[1], "test-tag1", - ) + "\u{0}"), - ); - assert_eq!(call_result, expected,); - } - - #[test] - fn test_with_same_target_and_tag_dedup() { - let (_instance, initialized_context) = - initialize_context("test_with_same_target_and_tag_dedup"); - let entry_addresses = add_test_entries(initialized_context.clone()); - // links have same tag, same base and same tag. Are the same - let links = vec![ - Link::new( - &entry_addresses[0], - &entry_addresses[1], - "test-type", - "test-tag", - ), - Link::new( - &entry_addresses[0], - &entry_addresses[1], - "test-type", - "test-tag", - ), - ]; - add_links(initialized_context.clone(), links); - let call_result = get_links( - initialized_context.clone(), - &entry_addresses[0], - LinkMatch::Exactly("test-type".into()), - LinkMatch::Exactly("test-tag".into()), - ); - let expected = JsonString::from_json( - &(format!( - r#"{{"ok":true,"value":"{{\"links\":[{{\"address\":\"{}\",\"headers\":[],\"tag\":\"{}\",\"status\":\"live\"}}]}}","error":"null"}}"#, - entry_addresses[1], "test-tag", - ) + "\u{0}"), - ); - assert_eq!(call_result, expected,); - } - - #[test] - fn test_with_same_target_different_tag_dont_dedup() { - let (_instance, initialized_context) = - initialize_context("test_with_same_target_different_tag_dont_dedup"); - let entry_addresses = add_test_entries(initialized_context.clone()); - // same target and type, different tag - let links = vec![ - Link::new( - &entry_addresses[0], - &entry_addresses[1], - "test-type", - "test-tag1", - ), - Link::new( - &entry_addresses[0], - &entry_addresses[1], - "test-type", - "test-tag2", - ), - ]; - add_links(initialized_context.clone(), links); - let call_result = get_links( - initialized_context.clone(), - &entry_addresses[0], - LinkMatch::Exactly("test-type".into()), - LinkMatch::Any, - ); - let expected = JsonString::from_json( - &(format!( - r#"{{"ok":true,"value":"{{\"links\":[{{\"address\":\"{}\",\"headers\":[],\"tag\":\"{}\",\"status\":\"live\"}},{{\"address\":\"{}\",\"headers\":[],\"tag\":\"{}\",\"status\":\"live\"}}]}}","error":"null"}}"#, - entry_addresses[1], "test-tag2", entry_addresses[1], "test-tag1", - ) + "\u{0}"), - ); - assert_eq!(call_result, expected,); - } -} diff --git a/crates/core/src/wasm_engine/api/get_links_count.rs b/crates/core/src/wasm_engine/api/get_links_count.rs deleted file mode 100644 index 76a312b510..0000000000 --- a/crates/core/src/wasm_engine/api/get_links_count.rs +++ /dev/null @@ -1,38 +0,0 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, Runtime}, - workflows::get_links_count::get_link_result_count_workflow, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_wasm_utils::api_serialization::get_links::GetLinksArgs; -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; - -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_get_links_count(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - - let input = match GetLinksArgs::try_from(args_str.clone()) { - Ok(input) => { - log_debug!( - context, - "get_links: invoke_get_links called with {:?}", - input, - ); - input - } - Err(_) => { - log_error!( - context, - "zome: invoke_get_links failed to deserialize GetLinksArgs: {:?}", - args_str - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - }; - - let result = context.block_on(get_link_result_count_workflow(context.clone(), &input)); - - runtime.store_result(result) -} diff --git a/crates/core/src/wasm_engine/api/init_globals.rs b/crates/core/src/wasm_engine/api/init_globals.rs deleted file mode 100644 index 5885908e04..0000000000 --- a/crates/core/src/wasm_engine/api/init_globals.rs +++ /dev/null @@ -1,135 +0,0 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, Runtime}, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_core_types::entry::entry_type::EntryType; - -use holochain_persistence_api::{ - cas::content::{Address, AddressableContent}, - hash::HashString, -}; - -use holochain_json_api::json::JsonString; - -use holochain_wasm_utils::api_serialization::ZomeApiGlobals; -use wasmi::RuntimeArgs; - -/// ZomeApiFunction::InitGlobals secret function code -/// args: [0] encoded MemoryAllocation as u64 -/// Not expecting any complex input -/// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_init_globals(runtime: &mut Runtime, _args: &RuntimeArgs) -> ZomeApiResult { - let call_data = runtime.call_data()?; - let dna = runtime - .context()? - .get_dna() - .expect("No DNA found in invoke_init_globals"); - let dna_name = dna.name.clone(); - // Create the ZomeApiGlobals struct with some default values - let mut globals = ZomeApiGlobals { - dna_name, - dna_address: Address::from(""), - agent_id_str: JsonString::from(call_data.context.agent_id.clone()).to_string(), - agent_address: call_data.context.agent_id.address(), - agent_initial_hash: HashString::from(""), - agent_latest_hash: HashString::from(""), - public_token: Address::from(""), - cap_request: runtime - .zome_call_data() - .map(|zome_call_data| Some(zome_call_data.call.cap)) - .unwrap_or_else(|_| None), - properties: JsonString::from(dna.properties), - }; - - // Update fields - if let Some(state) = call_data.context.state() { - // Update dna_address - if let Some(dna) = state.nucleus().dna() { - globals.dna_address = dna.address() - } - // Update agent hashes - let maybe_top = state.agent().top_chain_header(); - if maybe_top.is_some() { - let mut found_entries: Vec
= vec![]; - for chain_header in state - .agent() - .chain_store() - .iter_type(&maybe_top, &EntryType::AgentId) - { - found_entries.push(chain_header.entry_address().to_owned()); - } - if !found_entries.is_empty() { - globals.agent_latest_hash = found_entries[0].clone(); - globals.agent_initial_hash = found_entries.pop().unwrap(); - globals.agent_address = globals.agent_latest_hash.clone(); - } - } - }; - - // Update public_token - let maybe_token = call_data.context.get_public_token(); - if let Ok(token) = maybe_token { - globals.public_token = token; - } - - // Store it in wasm memory - runtime.store_result(Ok(globals)) -} - -#[cfg(test)] -pub mod tests { - use crate::wasm_engine::{ - api::{tests::test_zome_api_function, ZomeApiFunction}, - Defn, - }; - use holochain_core_types::{ - dna::capabilities::CapabilityRequest, error::ZomeApiInternalResult, signature::Signature, - }; - use holochain_json_api::json::JsonString; - use holochain_persistence_api::cas::content::Address; - use holochain_wasm_utils::api_serialization::ZomeApiGlobals; - use std::convert::TryFrom; - use test_utils::mock_signing::registered_test_agent; - - #[test] - /// test that the correct globals values are created for zome calls - fn test_init_globals() { - let input: Vec = vec![]; - let (call_result, _) = test_zome_api_function(ZomeApiFunction::InitGlobals.as_str(), input); - - let zome_api_internal_result = ZomeApiInternalResult::try_from(call_result).unwrap(); - let globals = - ZomeApiGlobals::try_from(JsonString::from_json(&zome_api_internal_result.value)) - .unwrap(); - - assert_eq!(globals.dna_name, "TestApp"); - let expected_agent = registered_test_agent("jane"); - assert_eq!( - globals.agent_address.to_string(), - expected_agent.pub_sign_key - ); - // TODO (david.b) this should work: - //assert_eq!(globals.agent_id_str, String::from(AgentId::generate_fake("jane"))); - // assert_eq!( - // globals.agent_initial_hash, - // AgentId::generate_fake("jane").address() - // ); - assert_eq!(globals.agent_initial_hash, globals.agent_latest_hash); - - // this hash should stay the same as long as the public functions in the test zome - // don't change. - assert_eq!( - globals.public_token, - Address::from("QmdZiJWdVCh8s38tCcAAq8f7HpHkd9KLFnHh9vLTddt8D2"), - ); - - assert_eq!( - globals.cap_request, - Some(CapabilityRequest::new( Address::from("dummy_token"), - Address::from("HcSCimiBHJ8y3zejkjtHsu9Q8MZx96ztvfYRJ9fJH3Pbxodac5s8rqmShYqaamz"), - Signature::from("nI/AFdqZPYw1yoCeV92pKWwugdkB54JJDhLLf3JgMFl9sm3aFIWKpiRo+4t8L+wn+S0Pg1Vh0Bzbmq3DSfJwDw=="), - )), - ); - } -} diff --git a/crates/core/src/wasm_engine/api/link_entries.rs b/crates/core/src/wasm_engine/api/link_entries.rs deleted file mode 100644 index be90e8749b..0000000000 --- a/crates/core/src/wasm_engine/api/link_entries.rs +++ /dev/null @@ -1,251 +0,0 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, runtime::Runtime}, - workflows::author_entry::author_entry, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_core_types::{ - entry::Entry, - error::HolochainError, - link::{link_data::LinkData, LinkActionKind}, -}; -use holochain_persistence_api::cas::content::{Address, AddressableContent}; - -use holochain_wasm_utils::api_serialization::link_entries::LinkEntriesArgs; -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; - -/// ZomeApiFunction::LinkEntries function code -/// args: [0] encoded MemoryAllocation as u64 -/// Expected complex argument: LinkEntriesArgs -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_link_entries(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - let input = match LinkEntriesArgs::try_from(args_str.clone()) { - Ok(entry_input) => entry_input, - // Exit on error - Err(_) => { - log_error!( - context, - "zome: invoke_link_entries failed to deserialize LinkEntriesArgs: {:?}", - args_str - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - }; - let top_chain_header_option = context - .state() - .expect("Couldn't get state in invoke_linke_entries") - .agent() - .top_chain_header(); - - let top_chain_header = match top_chain_header_option { - Some(top_chain) => top_chain, - None => { - log_error!( - context, - "zome: invoke_link_entries failed to deserialize LinkEntriesArgs: {:?}", - args_str - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - }; - - let link = input.to_link(); - let link_add = LinkData::from_link( - &link, - LinkActionKind::ADD, - top_chain_header, - context.agent_id.clone(), - ); - let entry = Entry::LinkAdd(link_add); - - // Wait for future to be resolved - // This is where the link entry actually gets created. - let result: Result = context - .block_on(author_entry(&entry, None, &context, &vec![])) - .map(|_| entry.address()); - - runtime.store_result(result) -} - -#[cfg(test)] -pub mod tests { - use test_utils; - - use crate::{ - agent::actions::commit::commit_entry, - context::Context, - instance::{tests::test_instance_and_context, Instance}, - wasm_engine::{ - api::{tests::*, ZomeApiFunction}, - Defn, - }, - }; - use holochain_core_types::{ - entry::{test_entry, Entry}, - error::{CoreError, ZomeApiInternalResult}, - }; - use holochain_json_api::json::JsonString; - use holochain_persistence_api::cas::content::AddressableContent; - use holochain_wasm_utils::api_serialization::link_entries::*; - - use serde_json; - use std::{convert::TryFrom, sync::Arc}; - - pub fn test_entry_b() -> Entry { - Entry::App("testEntryTypeB".into(), "test".into()) - } - - /// dummy link_entries args from standard test entry - pub fn test_link_args_bytes(link_type: String, tag: String) -> Vec { - let entry = test_entry(); - - let args = LinkEntriesArgs { - base: entry.address(), - target: entry.address(), - link_type, - tag, - }; - serde_json::to_string(&args) - .expect("args should serialize") - .into_bytes() - } - - pub fn test_link_2_args_bytes(link_type: String, tag: String) -> Vec { - let base = test_entry(); - let target = test_entry_b(); - - let args = LinkEntriesArgs { - base: base.address(), - target: target.address(), - link_type, - tag, - }; - serde_json::to_string(&args) - .expect("args should serialize") - .into_bytes() - } - - /// dummy commit args from standard test entry - pub fn test_commit_args_bytes() -> Vec { - JsonString::from(test_entry()).to_bytes() - } - - fn create_test_instance_with_name(netname: Option<&str>) -> (Instance, Arc) { - let wasm = test_zome_api_function_wasm(ZomeApiFunction::LinkEntries.as_str()); - let dna = test_utils::create_test_dna_with_wasm(&test_zome_name(), wasm.clone()); - - test_instance_and_context(dna, netname).expect("Could not create test instance") - } - fn create_test_instance() -> (Instance, Arc) { - let wasm = test_zome_api_function_wasm(ZomeApiFunction::LinkEntries.as_str()); - let dna = test_utils::create_test_dna_with_wasm(&test_zome_name(), wasm.clone()); - - let netname = format!("create_test_instance-{}", snowflake::ProcessUniqueId::new()); - - test_instance_and_context(dna, Some(netname.as_str())) - .expect(format!("Could not create test instance for netname: {}", netname).as_str()) - } - - #[test] - /// test that we can round trip bytes through a commit action and get the result from WASM - #[cfg(not(windows))] - fn errors_if_base_is_not_present_test() { - // let (call_result, _) = test_zome_api_function( - // ZomeApiFunction::LinkEntries.as_str(), - // test_link_args_bytes(String::from("test-link")), - // ); - // - // let result = ZomeApiInternalResult::try_from(call_result) - // .expect("valid ZomeApiInternalResult JsonString"); - // - // let core_err = CoreError::try_from(result).expect("valid CoreError JsonString"); - // assert_eq!("Base for link not found", core_err.kind.to_string(),); - } - - #[test] - fn returns_ok_if_base_is_present() { - let (_instance, context) = - create_test_instance_with_name(Some("returns_ok_if_base_present")); - - context - .block_on(commit_entry(test_entry(), None, &context)) - .expect("Could not commit entry for testing"); - - let call_result_json = test_zome_api_function_call( - context.clone(), - test_link_args_bytes("test-link".into(), "test-tag".into()), - ); - - let call_result = ZomeApiInternalResult::try_from(call_result_json); - - assert!(call_result.is_ok()) - } - - #[test] - fn errors_with_wrong_type() { - let (_instance, context) = create_test_instance(); - - context - .block_on(commit_entry(test_entry(), None, &context)) - .expect("Could not commit entry for testing"); - - let call_result = test_zome_api_function_call( - context.clone(), - test_link_args_bytes("wrong-link".into(), "test-tag".into()), - ); - - let result = ZomeApiInternalResult::try_from(call_result) - .expect("valid ZomeApiInternalResult JsonString"); - - let core_err = CoreError::try_from(result).expect("valid CoreError JsonString"); - assert_eq!("Unknown entry type", core_err.kind.to_string(),); - } - - #[test] - fn works_with_linked_from_defined_link() { - let (_instance, context) = create_test_instance(); - - context - .block_on(commit_entry(test_entry(), None, &context)) - .expect("Could not commit entry for testing"); - - context - .block_on(commit_entry(test_entry_b(), None, &context)) - .expect("Could not commit entry for testing"); - - let call_result_json = test_zome_api_function_call( - context.clone(), - test_link_2_args_bytes("test-link".into(), "test-tag".into()), - ); - - let call_result = ZomeApiInternalResult::try_from(call_result_json); - - assert!(call_result.is_ok()) - } - - #[test] - fn test_different_tags_produces_different_hashes() { - let (_instance, context) = create_test_instance(); - - context - .block_on(commit_entry(test_entry(), None, &context)) - .expect("Could not commit entry for testing"); - - let call_result1 = test_zome_api_function_call( - context.clone(), - test_link_args_bytes("test-link".into(), "test-tag1".into()), - ); - let call_result2 = test_zome_api_function_call( - context.clone(), - test_link_args_bytes("test-link".into(), "test-tag2".into()), - ); - - let result1: JsonString = ZomeApiInternalResult::success(call_result1).into(); - let result2: JsonString = ZomeApiInternalResult::success(call_result2).into(); - - assert_ne!(result1, result2); - } -} diff --git a/crates/core/src/wasm_engine/api/macros.rs b/crates/core/src/wasm_engine/api/macros.rs deleted file mode 100644 index 1b373b084a..0000000000 --- a/crates/core/src/wasm_engine/api/macros.rs +++ /dev/null @@ -1,102 +0,0 @@ -#[macro_export] -macro_rules! link_zome_api { - ( - $( - $(#[$meta:meta])* - $internal_name:literal, $enum_variant:ident, $function_name:path ; - )* - ) => { - - use crate::nucleus::{ - actions::{trace_invoke_hdk_function::trace_invoke_hdk_function, trace_return_hdk_function::trace_return_hdk_function}, - HdkFnCall, - }; - use crate::wasm_engine::runtime::WasmCallData; - use holochain_json_api::json::JsonString; - - /// Enumeration of all the Zome Functions known and usable in Zomes. - /// Enumeration can convert to str. - #[repr(usize)] - #[derive(FromPrimitive, Clone, Hash, Debug, PartialEq, Eq, Serialize)] - pub enum ZomeApiFunction { - /// Error index for unimplemented functions - MissingNo = 0, - - /// Abort is a way to receive useful debug info from - /// assemblyscript memory allocators - /// message: mem address in the wasm memory for an error message - /// filename: mem address in the wasm memory for a filename - /// line: line number - /// column: column number - Abort, - - $( - $(#[$meta])* - $enum_variant - ),* - } - - impl Defn for ZomeApiFunction { - fn as_str(&self) -> &'static str { - match *self { - ZomeApiFunction::MissingNo => "", - ZomeApiFunction::Abort => "abort", - $(ZomeApiFunction::$enum_variant => $internal_name),* - } - } - - fn str_to_index(s: &str) -> usize { - ZomeApiFunction::from_str(s).unwrap_or(ZomeApiFunction::MissingNo) as usize - } - - fn from_index(i: usize) -> Self { - FromPrimitive::from_usize(i).unwrap_or(ZomeApiFunction::MissingNo) - } - } - - impl FromStr for ZomeApiFunction { - type Err = &'static str; - fn from_str(s: &str) -> Result { - match s { - "abort" => Ok(ZomeApiFunction::Abort), - $($internal_name => Ok(ZomeApiFunction::$enum_variant),)* - _ => Err("Cannot convert string to ZomeApiFunction"), - } - } - } - - impl ZomeApiFunction { - // cannot test this because PartialEq is not implemented for fns - #[cfg_attr(tarpaulin, skip)] - pub fn apply(&self, runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - // TODO Implement a proper "abort" function for handling assemblyscript aborts - // @see: https://github.com/holochain/holochain-rust/issues/324 - - match *self { - ZomeApiFunction::MissingNo => ribosome_success!(), - ZomeApiFunction::Abort => ribosome_success!(), - $( ZomeApiFunction::$enum_variant => { - if let Ok(context) = runtime.context() { - if let WasmCallData::ZomeCall(zome_call_data) = runtime.data.clone() { - let zome_api_call = zome_call_data.call; - let parameters = runtime.load_json_string_from_args(&args); - let hdk_fn_call = HdkFnCall { function: self.clone(), parameters }; - trace_invoke_hdk_function(zome_api_call.clone(), hdk_fn_call.clone(), &context); - let result = $function_name(runtime, args); - let hdk_fn_result = Ok(JsonString::from("TODO")); - trace_return_hdk_function(zome_api_call.clone(), hdk_fn_call, hdk_fn_result, &context); - result - } else { - error!("Can't record zome call hdk invocations for non zome call"); - $function_name(runtime, args) - } - } else { - error!("Could not get context for runtime"); - $function_name(runtime, args) - } - } , )* - } - } - } - }; -} diff --git a/crates/core/src/wasm_engine/api/meta.rs b/crates/core/src/wasm_engine/api/meta.rs deleted file mode 100644 index cb34613fca..0000000000 --- a/crates/core/src/wasm_engine/api/meta.rs +++ /dev/null @@ -1,66 +0,0 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, Runtime}, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_core_types::{hdk_version::HDK_VERSION, HDK_HASH}; -use holochain_wasm_utils::api_serialization::meta::{MetaArgs, MetaMethod, MetaResult}; -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; - -/// ZomeApiFunction::Meta function code -/// args: [0] encoded MemoryAllocation as u64 -/// Expecting a string as complex input argument -/// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_meta(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - - let args_str = runtime.load_json_string_from_args(&args); - let meta_args = match MetaArgs::try_from(args_str.clone()) { - Ok(args) => args, - // Exit on error - Err(error) => { - log_error!( - context, - "zome: invoke_meta failed to \ - deserialize arguments: {:?} with error {:?}", - args_str, - error - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - }; - - let method = match meta_args.method { - MetaMethod::Version => MetaResult::Version(HDK_VERSION.to_string()), - MetaMethod::Hash => MetaResult::Hash(HDK_HASH.to_string()), - }; - - let result = Ok(method); - - runtime.store_result(result) -} - -#[cfg(test)] -#[cfg(not(windows))] -mod test_super { - use crate::wasm_engine::{ - api::{tests::test_zome_api_function, ZomeApiFunction}, - Defn, - }; - use holochain_core_types::hdk_version::HDK_VERSION; - use holochain_json_api::json::*; - /// test that bytes passed to debug end up in the log - #[test] - fn test_zome_api_meta_functions() { - let (call_result, _) = test_zome_api_function( - ZomeApiFunction::Meta.as_str(), - format!(r#"{{ "method" : "Version" }}"#).as_bytes().to_vec(), - ); - let call_result_json = format!( - r#"{{"ok":true,"value":"{{\"Version\":\"{}\"}}","error":"null"}}"#, - HDK_VERSION.to_string() - ); - assert_eq!(JsonString::from_json(&*call_result_json), call_result,); - } -} diff --git a/crates/core/src/wasm_engine/api/mod.rs b/crates/core/src/wasm_engine/api/mod.rs deleted file mode 100644 index bea04a5851..0000000000 --- a/crates/core/src/wasm_engine/api/mod.rs +++ /dev/null @@ -1,381 +0,0 @@ -//! Module for ZomeApiFunctions -//! ZomeApiFunctions are the functions provided by the ribosome that are callable by Zomes. - -pub mod call; -pub mod commit; -pub mod debug; -pub mod emit_signal; -pub mod entry_address; -pub mod get_entry; -pub mod get_links; -pub mod get_links_count; -pub mod init_globals; -pub mod link_entries; -#[macro_use] -mod macros; -pub mod capabilities; -pub mod crypto; -pub mod keystore; -pub mod meta; -pub mod query; -pub mod remove_entry; -pub mod remove_link; -pub mod send; -pub mod sign; -pub mod sleep; -pub mod update_entry; -pub mod verify_signature; - -use crate::wasm_engine::{ - api::{ - call::invoke_call, - capabilities::{invoke_commit_capability_claim, invoke_commit_capability_grant}, - commit::invoke_commit_app_entry, - crypto::invoke_crypto, - debug::invoke_debug, - emit_signal::invoke_emit_signal, - entry_address::invoke_entry_address, - get_entry::invoke_get_entry, - get_links::invoke_get_links, - get_links_count::invoke_get_links_count, - init_globals::invoke_init_globals, - keystore::{ - invoke_keystore_derive_key, invoke_keystore_derive_seed, - invoke_keystore_get_public_key, invoke_keystore_list, invoke_keystore_new_random, - invoke_keystore_sign, - }, - link_entries::invoke_link_entries, - meta::invoke_meta, - query::invoke_query, - remove_entry::invoke_remove_entry, - remove_link::invoke_remove_link, - send::invoke_send, - sign::invoke_sign_one_time, - sleep::invoke_sleep, - update_entry::invoke_update_entry, - verify_signature::invoke_verify_signature, - }, - runtime::Runtime, -}; - -use crate::wasm_engine::Defn; -use num_traits::FromPrimitive; -use std::str::FromStr; -use wasmi::{RuntimeArgs, RuntimeValue, Trap}; - -pub type ZomeApiResult = Result, Trap>; - -//-------------------------------------------------------------------------------------------------- -// ZOME API FUNCTION DEFINITIONS -//-------------------------------------------------------------------------------------------------- - -link_zome_api! { - /// send debug information to the log - /// debug(s: String) - "hc_debug", Debug, invoke_debug; - - /// Commit an app entry to source chain - /// commit_entry(entry_type: String, entry_value: String) -> Address - "hc_commit_entry", CommitAppEntry, invoke_commit_app_entry; - - /// Get an app entry from source chain by key (header hash) - /// get_entry(address: Address) -> Entry - "hc_get_entry", GetAppEntry, invoke_get_entry; - "hc_update_entry", UpdateEntry, invoke_update_entry; - "hc_remove_entry", RemoveEntry, invoke_remove_entry; - - /// Init Zome API Globals - /// hc_init_globals() -> InitGlobalsOutput - "hc_init_globals", InitGlobals, invoke_init_globals; - - /// Call a zome function in a different zome or dna via a bridge - /// hc_call(zome_name: String, cap_token: Address, fn_name: String, args: String); - "hc_call", Call, invoke_call; - - /// Create a link entry - "hc_link_entries", LinkEntries, invoke_link_entries; - - /// Retrieve links from the DHT - "hc_get_links", GetLinks, invoke_get_links; - - //Retrieve link count from DHT - "hc_get_links_count", GetLinksCount, invoke_get_links_count; - - /// Query the local chain for entries - "hc_query", Query, invoke_query; - - /// Pass an entry to retrieve its address - /// the address algorithm is specific to the entry, typically sha256 but can differ - /// entry_address(entry: Entry) -> Address - "hc_entry_address", EntryAddress, invoke_entry_address; - - /// Send a message directly to another node - "hc_send", Send, invoke_send; - - /// Allow a specified amount of time to pass - "hc_sleep", Sleep, invoke_sleep; - - /// Commit link deletion entry - "hc_remove_link", RemoveLink, invoke_remove_link; - //execute cryptographic function - "hc_crypto",Crypto,invoke_crypto; - /// Sign a block of data with a one-time key that is then shredded - "hc_sign_one_time", SignOneTime, invoke_sign_one_time; - - /// Verify that a block of data was signed by a given public key - "hc_verify_signature", VerifySignature, invoke_verify_signature; - - /// Retrieve a list of identifiers of the secrets in the keystore - "hc_keystore_list", KeystoreList, invoke_keystore_list; - - /// Create a new random seed Secret in the keystore - "hc_keystore_new_random", KeystoreNewRandom, invoke_keystore_new_random; - - /// Derive a new seed from an existing seed in the keystore - "hc_keystore_derive_seed", KeystoreDeriveSeed, invoke_keystore_derive_seed; - - /// Create a new key (signing or encrypting) as derived from an existing seed in the keystore - "hc_keystore_derive_key", KeystoreDeriveKey, invoke_keystore_derive_key; - - /// Sign a block of data using a key in the keystore - "hc_keystore_sign", KeystoreSign, invoke_keystore_sign; - - /// Get the public key for a given secret - "hc_keystore_get_public_key", KeystoreGetPublicKey, invoke_keystore_get_public_key; - - /// Commit a capability grant to the source chain - "hc_commit_capability_grant", CommitCapabilityGrant, invoke_commit_capability_grant; - - /// Commit a capability grant to the source chain - "hc_commit_capability_claim", CommitCapabilityClaim, invoke_commit_capability_claim; - - /// Send a DNA defined signal to UIs and other listeners - "hc_emit_signal", EmitSignal, invoke_emit_signal; - - ///send a meta - "hc_meta",Meta,invoke_meta; -} - -#[cfg(test)] -pub mod tests { - use self::wabt::Wat2Wasm; - use crate::{ - context::Context, - instance::tests::test_instance_and_context, - nucleus::{tests::test_capability_request, ZomeFnCall}, - wasm_engine::{self, runtime::WasmCallData}, - }; - use holochain_json_api::json::JsonString; - use std::sync::Arc; - use test_utils; - use wabt; - - /// generates the wasm to dispatch any zome API function with a single memory managed runtime - /// and bytes argument - pub fn test_zome_api_function_wasm(canonical_name: &str) -> Vec { - Wat2Wasm::new() - .canonicalize_lebs(false) - .write_debug_names(true) - .convert( - // We don't expect everyone to be a pro at hand-coding WAT so here's a "how to". - // WAT does not have comments so code is duplicated in the comments here. - // - // How this works: - // - // root of the s-expression tree - // (module ...) - // - // imports must be the first expressions in a module - // imports the fn from the rust environment using its canonical zome API function - // name as the function named `$zome_api_function` in WAT - // define the signature as 1 input, 1 output - // (import "env" "" - // (func $zome_api_function - // (param i64) - // (result i64) - // ) - // ) - // - // only need 1 page of memory for testing - // (memory 1) - // - // all modules compiled with rustc must have an export named "memory" (or fatal) - // (export "memory" (memory 0)) - // - // define and export the test function that will be called from the - // ribosome rust implementation, where "test" is the fourth arg to `call` - // @see `test_zome_api_function_runtime` - // @see nucleus::ribosome::call - // (func (export "test") ...) - // - // define the memory allocation for the memory manager that the serialized input - // struct can be found across as an i64 to the exported function, also the function - // return type is i64 - // (param $allocation i64) - // (result i64) - // - // call the imported function and pass the exported function arguments straight - // through, let the return also fall straight through - // `get_local` maps the relevant arguments in the local scope - // (call - // $zome_api_function - // (get_local $allocation) - // ) - format!( - r#" -(module - (import "env" "{}" - (func $zome_api_function - (param i64) - (result i64) - ) - ) - - (memory 1) - (export "memory" (memory 0)) - - (func - (export "test") - (param $allocation i64) - (result i64) - - (call - $zome_api_function - (get_local $allocation) - ) - ) - - (func - (export "__hdk_validate_app_entry") - (param $allocation i64) - (result i64) - - (i64.const 0) - ) - - (func - (export "__hdk_validate_agent_entry") - (param $allocation i64) - (result i64) - - (i64.const 0) - ) - - (func - (export "__hdk_validate_link") - (param $allocation i64) - (result i64) - - (i64.const 0) - ) - - - (func - (export "__hdk_get_validation_package_for_entry_type") - (param $allocation i64) - (result i64) - - ;; This writes "Entry" into memory - (i64.store (i32.const 0) (i64.const 34)) - (i64.store (i32.const 1) (i64.const 69)) - (i64.store (i32.const 2) (i64.const 110)) - (i64.store (i32.const 3) (i64.const 116)) - (i64.store (i32.const 4) (i64.const 114)) - (i64.store (i32.const 5) (i64.const 121)) - (i64.store (i32.const 6) (i64.const 34)) - - (i64.const 7) - ) - - (func - (export "__hdk_get_validation_package_for_link") - (param $allocation i64) - (result i64) - - ;; This writes "Entry" into memory - (i64.store (i32.const 0) (i64.const 34)) - (i64.store (i32.const 1) (i64.const 69)) - (i64.store (i32.const 2) (i64.const 110)) - (i64.store (i32.const 3) (i64.const 116)) - (i64.store (i32.const 4) (i64.const 114)) - (i64.store (i32.const 5) (i64.const 121)) - (i64.store (i32.const 6) (i64.const 34)) - - (i64.const 7) - ) - - (func - (export "__list_traits") - (param $allocation i64) - (result i64) - - (i64.const 0) - ) - - (func - (export "__list_functions") - (param $allocation i64) - (result i64) - - (i64.const 0) - ) -) - "#, - canonical_name - ), - ) - .unwrap() - .as_ref() - .to_vec() - } - - /// dummy zome name - pub fn test_zome_name() -> String { - "test_zome".to_string() - } - - /// dummy zome API function name - pub fn test_function_name() -> String { - "test".to_string() - } - - /// dummy parameters for a zome API function call - pub fn test_parameters() -> JsonString { - JsonString::empty_object() - } - - /// calls the zome API function with passed bytes argument using the instance runtime - /// returns the runtime after the call completes - pub fn test_zome_api_function_call(context: Arc, args_bytes: Vec) -> JsonString { - let zome_call = ZomeFnCall::new( - &test_zome_name(), - test_capability_request(context.clone(), &test_function_name(), test_parameters()), - &test_function_name(), - test_parameters(), - ); - wasm_engine::run_dna( - Some(args_bytes), - WasmCallData::new_zome_call(context, zome_call), - ) - .expect("test should be callable") - } - - /// Given a canonical zome API function name and args as bytes: - /// - builds wasm with test_zome_api_function_wasm - /// - builds dna and test instance - /// - calls the zome API function with passed bytes argument using the instance runtime - /// - returns the call result - pub fn test_zome_api_function( - canonical_name: &str, - args_bytes: Vec, - ) -> (JsonString, Arc) { - let wasm = test_zome_api_function_wasm(canonical_name); - let dna = test_utils::create_test_dna_with_wasm(&test_zome_name(), wasm.clone()); - - let (_instance, context) = - test_instance_and_context(dna, None).expect("Could not create test instance"); - - let call_result = test_zome_api_function_call(context.clone(), args_bytes); - (call_result, context) - } -} diff --git a/crates/core/src/wasm_engine/api/remove_entry.rs b/crates/core/src/wasm_engine/api/remove_entry.rs deleted file mode 100644 index 548fa196d7..0000000000 --- a/crates/core/src/wasm_engine/api/remove_entry.rs +++ /dev/null @@ -1,73 +0,0 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, Runtime}, - workflows::{author_entry::author_entry, get_entry_result::get_entry_result_workflow}, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_core_types::{ - entry::{deletion_entry::DeletionEntry, Entry}, - error::HolochainError, -}; - -use holochain_persistence_api::cas::content::{Address, AddressableContent}; - -use holochain_wasm_utils::api_serialization::get_entry::*; -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; - -/// ZomeApiFunction::RemoveEntry function code -/// args: [0] encoded MemoryAllocation -/// Expected Address argument -/// Stores/returns a RibosomeEncodedValue -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_remove_entry(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - let try_address = Address::try_from(args_str.clone()); - - // Exit on error - if try_address.is_err() { - log_error!( - context, - "zome: invoke_remove_entry failed to deserialize Address: {:?}", - args_str - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - let deleted_entry_address = try_address.unwrap(); - - // Get Current entry's latest version - let get_args = GetEntryArgs { - address: deleted_entry_address, - options: Default::default(), - }; - let maybe_entry_result = context - .clone() - .block_on(get_entry_result_workflow(&context, &get_args)); - - if let Err(err) = maybe_entry_result { - log_error!(context, "zome: get_entry_result_workflow failed: {:?}", err); - return ribosome_error_code!(WorkflowFailed); - } - - let entry_result = maybe_entry_result.unwrap(); - if !entry_result.found() { - return ribosome_error_code!(EntryNotFound); - } - let deleted_entry_address = entry_result.latest().unwrap().address(); - - // Create deletion entry - let deletion_entry = Entry::Deletion(DeletionEntry::new(deleted_entry_address.clone())); - - let res: Result = context - .block_on(author_entry( - &deletion_entry.clone(), - Some(deleted_entry_address), - &context.clone(), - &vec![], - )) - .map(|_| deletion_entry.address()); - - runtime.store_result(res) -} diff --git a/crates/core/src/wasm_engine/api/send.rs b/crates/core/src/wasm_engine/api/send.rs deleted file mode 100644 index 7f80d968a7..0000000000 --- a/crates/core/src/wasm_engine/api/send.rs +++ /dev/null @@ -1,47 +0,0 @@ -use crate::{ - network::{actions::custom_send::custom_send, direct_message::CustomDirectMessage}, - wasm_engine::{api::ZomeApiResult, Runtime}, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_json_api::json::JsonString; -use holochain_wasm_utils::api_serialization::send::SendArgs; -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; - -/// ZomeApiFunction::Send function code -/// args: [0] encoded MemoryAllocation as u64 -/// Expected complex argument: SendArgs -/// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_send(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let span = runtime - .call_data() - .ok() - .map(|d| d.context.tracer.span("hdk invoke_send").start().into()) - .unwrap_or_else(|| ht::noop("hdk invoke_send no context")); - let _trace_guard = ht::push_span(span); - let call_data = runtime.call_data()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - let args = match SendArgs::try_from(args_str) { - Ok(input) => input, - Err(..) => return ribosome_error_code!(ArgumentDeserializationFailed), - }; - - let message = CustomDirectMessage { - payload: Ok(args.payload), - zome: call_data.zome_name.clone(), - }; - - let result = call_data - .context - .block_on(custom_send( - args.to_agent, - message, - args.options.0, - call_data.context.clone(), - )) - .map(|s| JsonString::from_json(&s)); - - runtime.store_result(result) -} diff --git a/crates/core/src/wasm_engine/api/sleep.rs b/crates/core/src/wasm_engine/api/sleep.rs deleted file mode 100644 index d714fec326..0000000000 --- a/crates/core/src/wasm_engine/api/sleep.rs +++ /dev/null @@ -1,24 +0,0 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, Runtime}, - NEW_RELIC_LICENSE_KEY, -}; -use std::{convert::TryFrom, thread, time::Duration}; -use wasmi::{RuntimeArgs, RuntimeValue}; - -/// ZomeApiFunction::Sleep function code -/// args: [0] encoded MemoryAllocation as u64 -/// Expected argument: u64 -/// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_sleep(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - let nanos = match u64::try_from(args_str) { - Ok(input) => input, - Err(..) => return ribosome_error_code!(ArgumentDeserializationFailed), - }; - - thread::sleep(Duration::from_nanos(nanos)); - - ribosome_success!() -} diff --git a/crates/core/src/wasm_engine/api/update_entry.rs b/crates/core/src/wasm_engine/api/update_entry.rs deleted file mode 100644 index b1a9e29645..0000000000 --- a/crates/core/src/wasm_engine/api/update_entry.rs +++ /dev/null @@ -1,65 +0,0 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, Runtime}, - workflows::{author_entry::author_entry, get_entry_result::get_entry_result_workflow}, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_core_types::error::HolochainError; - -use holochain_persistence_api::cas::content::{Address, AddressableContent}; - -use holochain_wasm_utils::api_serialization::{get_entry::*, UpdateEntryArgs}; -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; - -/// ZomeApiFunction::UpdateEntry function code -/// args: [0] encoded MemoryAllocation as u64 -/// Expected complex argument: UpdateEntryArgs -/// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_update_entry(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - let entry_args = match UpdateEntryArgs::try_from(args_str.clone()) { - Ok(entry_input) => entry_input, - // Exit on error - Err(_) => { - log_error!( - context, - "zome: invoke_update_entry failed to deserialize SerializedEntry: {:?}", - args_str - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - }; - - // Get Current entry's latest version - let get_args = GetEntryArgs { - address: entry_args.address, - options: Default::default(), - }; - let maybe_entry_result = context.block_on(get_entry_result_workflow(&context, &get_args)); - if let Err(err) = maybe_entry_result { - log_error!(context, "zome: get_entry_result_workflow failed: {:?}", err); - return ribosome_error_code!(WorkflowFailed); - } - let entry_result = maybe_entry_result.clone().unwrap(); - if !entry_result.found() { - return ribosome_error_code!(EntryNotFound); - } - let latest_entry = entry_result.latest().unwrap(); - - // Create Chain Entry - let entry = entry_args.new_entry.clone(); - - let res: Result = context - .block_on(author_entry( - &entry, - Some(latest_entry.address()), - &context.clone(), - &vec![], // TODO should provenance be a parameter? - )) - .map(|result| result.address()); - - runtime.store_result(res) -} diff --git a/crates/core/src/wasm_engine/api/verify_signature.rs b/crates/core/src/wasm_engine/api/verify_signature.rs deleted file mode 100644 index 3e1dcc4e3e..0000000000 --- a/crates/core/src/wasm_engine/api/verify_signature.rs +++ /dev/null @@ -1,86 +0,0 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, Runtime}, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_dpki::utils::Verify; -use holochain_wasm_utils::api_serialization::verify_signature::VerifySignatureArgs; -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; - -/// ZomeApiFunction::VerifySignature function code -/// args: [0] encoded MemoryAllocation as u64 -/// Expected argument: u64 -/// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_verify_signature(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - - let verification_args = match VerifySignatureArgs::try_from(args_str.clone()) { - Ok(verify_signature_input) => verify_signature_input, - // Exit on error - Err(_) => { - log_error!( - context, - "zome: invoke_verify_signature failed to deserialize SerializedEntry: {:?}", - args_str - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - }; - - log_debug!( - context, - "zome: using provenance:{:?} to verify data:{:?}", - verification_args.provenance.clone(), - verification_args.payload.clone() - ); - - let verification_result = verification_args - .provenance - .verify(verification_args.payload.clone()); - - runtime.store_result(verification_result) -} - -#[cfg(test)] -mod test_super { - use crate::{ - holochain_wasm_utils::holochain_persistence_api::cas::content::AddressableContent, - wasm_engine::{ - api::{tests::test_zome_api_function, ZomeApiFunction}, - Defn, - }, - }; - use holochain_json_api::json::JsonString; - - #[test] - fn test_zome_api_function_verify() { - let (call_result, context) = test_zome_api_function( - ZomeApiFunction::Crypto.as_str(), - r#"{ "payload": "this is data", "method":"Sign" }"#.as_bytes().to_vec(), - ); - assert_eq!( - JsonString::from_json( - r#"{"ok":true,"value":"xoEEoLF1yWM4VBNtjEwrfM/iVzjuAxxbkOyBWi0LV0+1CAH/PCs9MErnbmFeZRtQNtw7+SmVrm7Irac4lZsaDA==","error":"null"}"# - ), - call_result, - ); - - let args = format!( - r#"{{ "provenance": ["{}","xoEEoLF1yWM4VBNtjEwrfM/iVzjuAxxbkOyBWi0LV0+1CAH/PCs9MErnbmFeZRtQNtw7+SmVrm7Irac4lZsaDA=="], "payload": "this is data" }}"#, - context.agent_id.address() - ); - let (call_result, _) = test_zome_api_function( - ZomeApiFunction::VerifySignature.as_str(), - args.as_bytes().to_vec(), - ); - - assert_eq!( - JsonString::from_json(r#"{"ok":true,"value":"true","error":"null"}"#), - call_result, - ); - } -} diff --git a/crates/core/src/wasm_engine/callback/mod.rs b/crates/core/src/wasm_engine/callback.rs similarity index 64% rename from crates/core/src/wasm_engine/callback/mod.rs rename to crates/core/src/wasm_engine/callback.rs index 34f5415652..81e4fe2360 100644 --- a/crates/core/src/wasm_engine/callback/mod.rs +++ b/crates/core/src/wasm_engine/callback.rs @@ -1,37 +1,19 @@ //! Module for ZomeCallbacks //! ZomeCallbacks are functions in a Zome that are callable by the ribosome. - -pub mod init; -pub mod links_utils; -pub mod receive; -pub mod validation_package; - -use crate::{ - context::Context, - nucleus::CallbackFnCall, - wasm_engine::{ - self, - callback::{init::init, receive::receive}, - runtime::WasmCallData, - Defn, - }, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_core_types::{ - entry::Entry, error::RibosomeEncodedValue, validation::ValidationPackageDefinition, -}; +use holochain_core_types::{entry::Entry}; use holochain_json_api::{ error::JsonError, - json::{default_to_json, JsonString}, -}; - -use holochain_wasm_utils::{ - api_serialization::receive::ReceiveParams, memory::allocation::WasmAllocation, + json::{JsonString}, }; -use num_traits::FromPrimitive; -use serde_json; -use std::{convert::TryFrom, str::FromStr, sync::Arc}; +use crate::wasm_engine::runtime::WasmCallData; +use crate::nucleus::CallbackFnCall; +use crate::workflows::callback::init::init; +use holochain_wasm_types::receive::ReceiveParams; +use std::{str::FromStr, sync::Arc}; +use crate::context::Context; +use crate::workflows::callback::receive::receive; +use holochain_core_types::callback::CallbackResult; /// Enumeration of all Zome Callbacks known and used by Holochain /// Enumeration can convert to str @@ -62,7 +44,7 @@ impl FromStr for Callback { } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// // #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl Callback { // cannot test this because PartialEq is not implemented for fns #[cfg_attr(tarpaulin, skip)] @@ -81,31 +63,14 @@ impl Callback { Callback::Receive => receive, } } -} -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -impl Defn for Callback { - fn as_str(&self) -> &'static str { + pub fn as_str(&self) -> &'static str { match *self { Callback::MissingNo => "", Callback::Init => "init", Callback::Receive => "receive", } } - - fn str_to_index(s: &str) -> usize { - match Callback::from_str(s) { - Ok(i) => i as usize, - Err(_) => Callback::MissingNo as usize, - } - } - - fn from_index(i: usize) -> Self { - match FromPrimitive::from_usize(i) { - Some(v) => v, - None => Callback::MissingNo, - } - } } #[derive(Clone, Debug, Serialize, Deserialize, DefaultJson)] @@ -128,68 +93,26 @@ impl ToString for CallbackParams { } } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub enum CallbackResult { - Pass, - Fail(String), - NotImplemented(String), - ValidationPackageDefinition(ValidationPackageDefinition), - ReceiveResult(String), -} - -impl From for JsonString { - fn from(v: CallbackResult) -> Self { - default_to_json(v) - } -} - -impl From for CallbackResult { - fn from(json_string: JsonString) -> CallbackResult { - let r#try: Result = - serde_json::from_str(&String::from(json_string.clone())); - match r#try { - Ok(callback_result) => callback_result, - Err(_) => CallbackResult::Fail(String::from(json_string)), - } - } -} - -impl From for CallbackResult { - fn from(ribosome_return_code: RibosomeEncodedValue) -> CallbackResult { - match ribosome_return_code { - RibosomeEncodedValue::Failure(ribosome_error_code) => { - CallbackResult::Fail(ribosome_error_code.to_string()) - } - RibosomeEncodedValue::Allocation(ribosome_allocation) => { - match WasmAllocation::try_from(ribosome_allocation) { - Ok(allocation) => CallbackResult::Fail(allocation.read_to_string()), - Err(allocation_error) => CallbackResult::Fail(String::from(allocation_error)), - } - } - RibosomeEncodedValue::Success => CallbackResult::Pass, - } - } -} - -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// // #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub(crate) fn run_callback(context: Arc, call: CallbackFnCall) -> CallbackResult { - match wasm_engine::run_dna( - Some(call.clone().parameters.to_bytes()), - WasmCallData::new_callback_call(context, call), + println!("callback call {:?}", &call); + println!("{:?}", &call.parameters); + let call_data = WasmCallData::new_callback_call(context, call.clone()); + match holochain_wasmer_host::guest::call( + &mut match call_data.instance() { + Ok(instance) => instance, + Err(_) => return CallbackResult::NotImplemented("run_callback missing instance".into()), + }, + &call_data.fn_name(), + call.clone().parameters, ) { - Ok(call_result) => { - if call_result.is_null() { - CallbackResult::Pass - } else { - CallbackResult::Fail(call_result.to_string()) - } - } + Ok(v) => v, Err(_) => CallbackResult::NotImplemented("run_callback".into()), } } -#[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[autotrace] +// // #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn call( context: Arc, zome: &str, @@ -215,11 +138,11 @@ pub mod tests { use self::wabt::Wat2Wasm; use crate::{ instance::{tests::test_instance, Instance}, - wasm_engine::{callback::Callback, Defn}, + wasm_engine::{callback::Callback}, }; - use std::str::FromStr; use test_utils; use wabt; + use std::str::FromStr; /// generates the wasm to dispatch any zome API function with a single memomry managed runtime /// and bytes argument @@ -324,30 +247,4 @@ pub mod tests { Callback::from_str("foo").expect_err("string literal shouldn't be valid callback"), ); } - - #[test] - fn defn_test() { - // as_str() - for (input, output) in vec![ - (Callback::MissingNo, ""), - (Callback::Init, "init"), - (Callback::Receive, "receive"), - ] { - assert_eq!(output, input.as_str()); - } - - // str_to_index() - for (input, output) in vec![("", 0), ("init", 1), ("receive", 2)] { - assert_eq!(output, Callback::str_to_index(input)); - } - - // from_index() - for (input, output) in vec![ - (0, Callback::MissingNo), - (1, Callback::Init), - (2, Callback::Receive), - ] { - assert_eq!(output, Callback::from_index(input)); - } - } } diff --git a/crates/core/src/wasm_engine/callback/genesis.rs b/crates/core/src/wasm_engine/callback/genesis.rs deleted file mode 100644 index 59ef2a5d0f..0000000000 --- a/crates/core/src/wasm_engine/callback/genesis.rs +++ /dev/null @@ -1,78 +0,0 @@ -use super::call; -use crate::{ - context::Context, - nucleus::ribosome::callback::{Callback, CallbackParams, CallbackResult},NEW_RELIC_LICENSE_KEY -}; -use std::sync::Arc; - -#[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn init( - context: Arc, - zome: &str, - // we ignore params for init - params: &CallbackParams, -) -> CallbackResult { - call(context, zome, &Callback::Init, params) -} - -#[cfg(test)] -pub mod tests { - - use super::init; - use crate::{ - instance::tests::test_context, - nucleus::ribosome::{ - callback::{tests::test_callback_instance, Callback, CallbackParams, CallbackResult}, - Defn, - }, - }; - - #[test] - fn pass() { - let zome = "test_zome"; - let netname = Some("init::pass"); - let instance = test_callback_instance(zome, Callback::Init.as_str(), 0, netname) - .expect("Test callback instance could not be initialized"); - let context = instance.initialize_context(test_context("test", netname)); - - let result = init(context, zome, &CallbackParams::Init); - - assert_eq!(CallbackResult::Pass, result); - } - - #[test] - fn not_implemented() { - let zome = "test_zome"; - let netname = Some("init::not_implemented"); - let instance = test_callback_instance( - zome, - // anything other than Init is fine here - Callback::Receive.as_str(), - 0, - netname, - ) - .expect("Test callback instance could not be initialized"); - - let context = instance.initialize_context(test_context("test", netname)); - - let result = init(context, zome, &CallbackParams::Init); - - if let CallbackResult::NotImplemented(_) = result { - () - } else { - panic!("unexpected result"); - } - } - - #[test] - fn fail() { - let zome = "test_zome"; - let netname = Some("init::fail"); - let instance = test_callback_instance(zome, Callback::Init.as_str(), 1, netname); - assert!(instance.is_err()); - let error = instance.err().unwrap(); - assert_eq!("\"".to_string(), error); - } - -} diff --git a/crates/core/src/wasm_engine/factories.rs b/crates/core/src/wasm_engine/factories.rs deleted file mode 100644 index de46d05dbf..0000000000 --- a/crates/core/src/wasm_engine/factories.rs +++ /dev/null @@ -1,75 +0,0 @@ -use crate::{wasm_engine::api::ZomeApiFunction, NEW_RELIC_LICENSE_KEY}; -use holochain_core_types::error::HolochainError; -use std::{str::FromStr, sync::Arc}; -use wasmi::{ - self, Error as InterpreterError, FuncInstance, FuncRef, ImportsBuilder, Module, - ModuleImportResolver, ModuleInstance, ModuleRef, NopExternals, Signature, ValueType, -}; - -/// Creates a WASM module, that is the executable program, from a given WASM binary byte array. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn wasm_module_factory(wasm: Arc>) -> Result { - wasmi::Module::from_buffer(&*wasm).map_err(|e| HolochainError::ErrorGeneric(e.into())) -} - -/// Creates a runnable WASM module instance from a module reference. -/// Adds the Holochain specific API functions as imports. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn wasm_instance_factory(module: &Module) -> Result { - // invoke_index and resolve_func work together to enable callable host functions - // within WASM modules, which is how the core API functions - // read about the Externals trait for more detail - - // Correlate the names of the core ZomeApiFunction's with their indexes - // and declare its function signature (which is always the same) - struct RuntimeModuleImportResolver; - impl ModuleImportResolver for RuntimeModuleImportResolver { - fn resolve_func( - &self, - field_name: &str, - _signature: &Signature, - ) -> Result { - let api_fn = match ZomeApiFunction::from_str(&field_name) { - Ok(api_fn) => api_fn, - Err(_) => { - return Err(InterpreterError::Function(format!( - "host module doesn't export function with name {}", - field_name - ))); - } - }; - - match api_fn { - // Abort is a way to receive useful debug info from - // assemblyscript memory allocators, see enum definition for function signature - ZomeApiFunction::Abort => Ok(FuncInstance::alloc_host( - Signature::new( - &[ - ValueType::I64, - ValueType::I64, - ValueType::I64, - ValueType::I64, - ][..], - None, - ), - api_fn as usize, - )), - // All of our Zome API Functions have the same signature - _ => Ok(FuncInstance::alloc_host( - Signature::new(&[ValueType::I64][..], Some(ValueType::I64)), - api_fn as usize, - )), - } - } - } - - // Create Imports with previously described Resolver - let mut imports = ImportsBuilder::new(); - imports.push_resolver("env", &RuntimeModuleImportResolver); - - // Create module instance from wasm module, and start it if start is defined - ModuleInstance::new(&module, &imports) - .expect("Failed to instantiate module") - .run_start(&mut NopExternals) - .map_err(|_| HolochainError::RibosomeFailed("Module failed to start".to_string())) -} diff --git a/crates/core/src/wasm_engine/io.rs b/crates/core/src/wasm_engine/io.rs new file mode 100644 index 0000000000..5ca78cf266 --- /dev/null +++ b/crates/core/src/wasm_engine/io.rs @@ -0,0 +1,16 @@ +use std::path::PathBuf; + +pub fn wasm_target_dir(test_path: &PathBuf, wasm_path: &PathBuf) -> PathBuf { + // this env var checker can't use holochain_common + // crate because that uses `directories` crate which doesn't compile to WASM + let mut target_dir = PathBuf::new(); + if let Ok(prefix) = std::env::var("HC_TARGET_PREFIX") { + target_dir.push(PathBuf::from(prefix)); + target_dir.push("crates"); + target_dir.push(test_path); + } + target_dir.push(wasm_path); + target_dir.push(PathBuf::from("target")); + + target_dir +} diff --git a/crates/wasm_utils/src/macros.rs b/crates/core/src/wasm_engine/macros.rs similarity index 60% rename from crates/wasm_utils/src/macros.rs rename to crates/core/src/wasm_engine/macros.rs index e11704e4b6..2e87d88ea9 100644 --- a/crates/wasm_utils/src/macros.rs +++ b/crates/core/src/wasm_engine/macros.rs @@ -1,4 +1,4 @@ -/// Macro for creating a RibosomeErrorCode as a RuntimeValue Result-Option on the spot +/// Macro for creating a WasmError as a RuntimeValue Result-Option on the spot /// Will panic! if out or memory or other serialization error occured. #[macro_export] macro_rules! zome_assert { @@ -11,28 +11,6 @@ macro_rules! zome_assert { }; } -#[macro_export] -macro_rules! ribosome_success { - () => { - Ok(Some(RuntimeValue::I64( - $crate::holochain_core_types::error::RibosomeRuntimeBits::from( - $crate::holochain_core_types::error::RibosomeEncodedValue::Success, - ), - ))) - }; -} - -/// Macro for creating a RibosomeErrorCode as a RuntimeValue Result-Option on the spot -#[macro_export] -macro_rules! ribosome_error_code { - ($s:ident) => { - Ok(Some(RuntimeValue::I64( - $crate::holochain_core_types::error::RibosomeErrorCode::$s - as $crate::holochain_core_types::error::RibosomeRuntimeBits, - ))) - }; -} - /// Macro for creating a CoreError from a HolochainError on the spot with file!() and line!() #[macro_export] macro_rules! core_error { diff --git a/crates/core/src/wasm_engine/memory.rs b/crates/core/src/wasm_engine/memory.rs deleted file mode 100644 index 2488c2bf38..0000000000 --- a/crates/core/src/wasm_engine/memory.rs +++ /dev/null @@ -1,100 +0,0 @@ -use crate::NEW_RELIC_LICENSE_KEY; -use holochain_wasm_utils::memory::{ - allocation::{AllocationError, AllocationResult, Length, WasmAllocation}, - stack::WasmStack, - MemoryBits, MemoryInt, -}; -use wasmi::{MemoryRef, ModuleRef}; - -//-------------------------------------------------------------------------------------------------- -// WASM Memory Manager -//-------------------------------------------------------------------------------------------------- - -#[derive(Clone, Debug)] -/// Struct for managing a WASM Memory Instance as a single page memory stack -pub struct WasmPageManager { - stack: WasmStack, - wasm_memory: MemoryRef, -} - -/// A Memory Manager limited to one wasm memory page that works like a stack. -/// With this Memory Manager, the WASM host (i.e. the Ribosome) and WASM module (i.e. the Zome) -/// only need to pass around an i64 to communicate any data. -/// That u64 is the last memory allocation on the stack: -/// it is split in an i16 'offset' in the upper bits and an i16 'length' in the lower bits. -/// This fits with the 64KiB sized of a memory Page. -/// Complex input arguments should be stored on the latest allocation on the stack. -/// Complex output arguments can be stored anywhere on stack. -/// Since zero sized allocations are not allowed, -/// it is possible to pass around a return and/or error code with the following convention: -/// using the i16 'offset' as return code and i16 'length' set to zero -/// to indicate its a return code. -/// Return code of 0 means success, while any other value means a failure and gives the error code. -/// In the future, to handle bigger memory needs, we could do same with an i64 instead -/// and handle multiple memory Pages. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -impl WasmPageManager { - pub fn new(wasm_instance: &ModuleRef) -> Self { - // get wasm memory reference from module - let wasm_memory = wasm_instance - .export_by_name("memory") - .expect("all modules compiled with rustc should have an export named 'memory'; qed") - .as_memory() - .expect("in module generated by rustc export named 'memory' should be a memory; qed") - .clone(); - - WasmPageManager { - stack: WasmStack::default(), - wasm_memory, - } - } - - /// Allocate on stack without writing in it - pub fn allocate(&mut self, length: Length) -> AllocationResult { - let allocation = self.stack.next_allocation(length)?; - let top = self.stack.allocate(allocation)?; - Ok(WasmAllocation::new(MemoryInt::from(top).into(), length)?) - } - - /// Write data on top of stack - pub fn write(&mut self, data: &[u8]) -> AllocationResult { - if data.len() as MemoryBits > WasmAllocation::max() { - return Err(AllocationError::OutOfBounds); - } - - if data.is_empty() { - return Err(AllocationError::ZeroLength); - } - - // scope for mutable borrow of self - let mem_buf = self.allocate((data.len() as MemoryInt).into())?; - - // @TODO make this work when wasmi is used consistently inside/outside wasm - // let top_bytes = Bytes(MemoryInt::from(self.stack.top()) as usize); - // let top_pages: Pages = top_bytes.round_up_to(); - // let current_pages: Pages = self.wasm_memory.current_size(); - - // if current_pages < top_pages { - // match self.wasm_memory.grow(top_pages - current_pages) { - // Ok(new_pages) => assert_eq!(new_pages, top_pages), - // Err(_) => return Err(AllocationError::OutOfBounds), - // } - // } - - self.wasm_memory - .set(MemoryInt::from(mem_buf.offset()), &data) - .expect("memory should be writable"); - - Ok(mem_buf) - } - - /// Read data somewhere in stack - pub fn read(&self, allocation: WasmAllocation) -> Vec { - self.wasm_memory - .get( - MemoryInt::from(allocation.offset()), - MemoryInt::from(allocation.length()) as usize, - ) - .expect("Successfully retrieve the result") - } -} diff --git a/crates/core/src/wasm_engine/mod.rs b/crates/core/src/wasm_engine/mod.rs index 00b9d50d77..a27e9dfa49 100644 --- a/crates/core/src/wasm_engine/mod.rs +++ b/crates/core/src/wasm_engine/mod.rs @@ -1,24 +1,45 @@ -//! The virtual machine that runs DNA written in WASM - -pub mod api; -pub mod callback; -pub mod factories; -pub mod memory; -#[autotrace] -mod run_dna; +// pub mod callback; pub mod runtime; -pub use self::{run_dna::*, runtime::*}; -use std::str::FromStr; +pub use self::{runtime::*}; +pub mod callback; +pub mod io; +pub use holochain_wasmer_host::*; pub const MAX_ZOME_CALLS: usize = 10; -pub trait Defn: FromStr { - /// return the canonical name of this function definition - fn as_str(&self) -> &'static str; +#[cfg(test)] +pub mod tests { + + // use crate::wasm_engine::runtime::WasmCallData; + // use crate::nucleus::tests::test_capability_request; + // use crate::context::Context; + // use std::sync::Arc; + use holochain_wasm_types::JsonString; + + /// dummy zome name + pub fn test_zome_name() -> String { + "test_zome".to_string() + } + + /// dummy zome API function name + pub fn test_function_name() -> String { + "test".to_string() + } + + /// dummy parameters for a zome API function call + pub fn test_parameters() -> JsonString { + JsonString::empty_object() + } - /// convert the canonical name of this function to an index - fn str_to_index(s: &str) -> usize; + // pub fn test_wasm_call_data(context: Arc) -> WasmCallData { + // let zome_call = ZomeFnCall::new( + // &test_zome_name(), + // test_capability_request(context.clone(), &test_function_name(), test_parameters()), + // &test_function_name(), + // test_parameters(), + // ); + // + // WasmCallData::new_zome_call(context, zome_call) + // } - /// convert an index to the function definition - fn from_index(i: usize) -> Self; } diff --git a/crates/core/src/wasm_engine/run_dna.rs b/crates/core/src/wasm_engine/run_dna.rs deleted file mode 100644 index 6e06294567..0000000000 --- a/crates/core/src/wasm_engine/run_dna.rs +++ /dev/null @@ -1,202 +0,0 @@ -use crate::{ - nucleus::ZomeFnResult, - wasm_engine::{ - factories::{wasm_instance_factory, wasm_module_factory}, - memory::WasmPageManager, - runtime::{Runtime, WasmCallData}, - }, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_core_types::{ - dna::wasm::ModuleArc, - error::{ - HcResult, HolochainError, RibosomeEncodedValue, RibosomeEncodingBits, RibosomeRuntimeBits, - }, -}; -use holochain_json_api::json::JsonString; - -use holochain_wasm_utils::memory::allocation::{AllocationError, WasmAllocation}; -use std::convert::TryFrom; -use wasmi::RuntimeValue; - -/// Returns the WASM module, i.e. the WASM binary program code to run -/// for the given WasmCallData. -/// -/// In case of a direct call, the module gets created from the WASM binary -/// inside the DirectCall specialisation for WasmCallData. -/// -/// For ZomeCalls and CallbackCalls it gets the according module from the DNA. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -fn get_module(data: WasmCallData) -> Result { - let (context, zome_name) = if let WasmCallData::DirectCall(_, wasm) = data { - let transient_module = ModuleArc::new(wasm_module_factory(wasm)?); - return Ok(transient_module); - } else { - match data { - WasmCallData::ZomeCall(d) => (d.context.clone(), d.call.zome_name), - WasmCallData::CallbackCall(d) => (d.context.clone(), d.call.zome_name), - WasmCallData::DirectCall(_, _) => unreachable!(), - } - }; - - let state_lock = context.state()?; - let module = state_lock - .nucleus() - .dna - .as_ref() - .unwrap() - .zomes - .get(&zome_name) - .ok_or_else(|| HolochainError::new(&format!("No Ribosome found for Zome '{}'", zome_name)))? - .code - .get_wasm_module()?; - - Ok(module) -} - -/// Executes an exposed zome function in a wasm binary. -/// Multithreaded function -/// panics if wasm binary isn't valid. -#[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn run_dna(parameters: Option>, data: WasmCallData) -> ZomeFnResult { - let wasm_module = get_module(data.clone())?; - let wasm_instance = wasm_instance_factory(&wasm_module)?; - // write input arguments for module call in memory Buffer - let input_parameters: Vec<_> = parameters.unwrap_or_default(); - - let fn_name = data.fn_name(); - // instantiate runtime struct for passing external state data over wasm but not to wasm - let mut runtime = Runtime { - memory_manager: WasmPageManager::new(&wasm_instance), - data, - }; - - // Write input arguments in wasm memory - // scope for mutable borrow of runtime - let encoded_allocation_of_input: RibosomeEncodingBits = { - let mut_runtime = &mut runtime; - let maybe_allocation = mut_runtime.memory_manager.write(&input_parameters); - - match maybe_allocation { - // No allocation to write is ok - Err(AllocationError::ZeroLength) => RibosomeEncodedValue::Success.into(), - // Any other error is memory related - Err(err) => { - return Err(HolochainError::RibosomeFailed(format!( - "WASM Memory issue: {:?}. data = {:?}", - err, runtime.data - ))); - } - // Write successful, encode allocation - Ok(allocation) => RibosomeEncodedValue::from(allocation).into(), - } - }; - - // scope for mutable borrow of runtime - let returned_encoding: RibosomeEncodingBits = { - let mut_runtime = &mut runtime; - - // Try installing a custom panic handler. - // HDK-rust implements a function __install_panic_handler that reroutes output of - // PanicInfo to hdk::debug. - // Try calling it but fail silently if this function is not there. - let _ = wasm_instance.invoke_export("__install_panic_handler", &[], mut_runtime); - // invoke function in wasm instance - // arguments are info for wasm on how to retrieve complex input arguments - // which have been set in memory module - wasm_instance - .invoke_export( - &fn_name, - &[RuntimeValue::I64( - encoded_allocation_of_input as RibosomeRuntimeBits, - )], - mut_runtime, - ) - .map_err(|err| { - HolochainError::RibosomeFailed(format!( - "WASM invocation failed: {}. data = {:?}", - err, runtime.data - )) - })? - .unwrap() - .try_into() // Option<_> - .ok_or_else(|| { - HolochainError::RibosomeFailed(format!( - "WASM return value missing. data = {:?}", - runtime.data - )) - })? - }; - - // Handle result returned by called zome function - let return_code = RibosomeEncodedValue::from(returned_encoding); - - let return_log_msg: String; - let return_result: HcResult; - - match return_code.clone() { - RibosomeEncodedValue::Success => { - return_log_msg = return_code.to_string(); - return_result = Ok(JsonString::null()); - } - - RibosomeEncodedValue::Failure(err_code) => { - return_log_msg = return_code.to_string(); - return_result = Err(HolochainError::RibosomeFailed(format!( - "Zome function failure: {}", - err_code.as_str() - ))); - let log_message = format!( - "err/nucleus/run_dna: Zome function failure: {}", - err_code.as_str() - ); - match &runtime.data { - WasmCallData::ZomeCall(d) => { - log_info!(d.context, "{}, when calling: {:?}", log_message, d.call) - } - WasmCallData::CallbackCall(d) => { - log_info!(d.context, "{}, when calling: {:?}", log_message, d.call) - } - _ => {} - }; - } - - RibosomeEncodedValue::Allocation(ribosome_allocation) => { - match WasmAllocation::try_from(ribosome_allocation) { - Ok(allocation) => { - let result = runtime.memory_manager.read(allocation); - match String::from_utf8(result) { - Ok(json_string) => { - return_log_msg = json_string.clone(); - return_result = Ok(JsonString::from_json(&json_string)); - } - Err(err) => { - return_log_msg = err.to_string(); - return_result = Err(HolochainError::RibosomeFailed(format!( - "WASM failed to return value: {}", - err - ))); - } - } - } - Err(allocation_error) => { - return_log_msg = String::from(allocation_error.clone()); - return_result = Err(HolochainError::RibosomeFailed(format!( - "WASM return value allocation failed: {:?}", - allocation_error, - ))); - } - } - } - }; - - // Log & done - // @TODO make this more sophisticated (truncation or something) - // right now we have tests that return multiple wasm pages (64k+ bytes) so this is very spammy - // runtime. log_debug!(context, "zome: Zome Function '{}' returned: {}", - // zome_call.fn_name, return_log_msg, - // ); - let _ = return_log_msg; - return_result -} diff --git a/crates/core/src/wasm_engine/runtime.rs b/crates/core/src/wasm_engine/runtime.rs index d15da86791..ff13016ac5 100644 --- a/crates/core/src/wasm_engine/runtime.rs +++ b/crates/core/src/wasm_engine/runtime.rs @@ -1,23 +1,45 @@ use crate::{ context::Context, nucleus::{CallbackFnCall, ZomeFnCall}, - wasm_engine::{ - api::{ZomeApiFunction, ZomeApiResult}, - memory::WasmPageManager, - Defn, - }, - NEW_RELIC_LICENSE_KEY, -}; -use holochain_core_types::error::{ - HolochainError, RibosomeEncodedValue, RibosomeEncodingBits, RibosomeRuntimeBits, - ZomeApiInternalResult, -}; +}; use holochain_json_api::json::JsonString; - -use holochain_wasm_utils::memory::allocation::WasmAllocation; -use std::{convert::TryFrom, fmt, sync::Arc}; -use wasmi::{Externals, HostError, RuntimeArgs, RuntimeValue, Trap, TrapKind}; +use holochain_core_types::error::HolochainError; +use std::{fmt, sync::Arc}; +use wasmer_runtime::{error::RuntimeError, Instance, imports, func}; +use holochain_wasmer_host::WasmError; +use wasmer_runtime::Ctx; +use crate::workflows::debug::debug_workflow; +use holochain_wasm_types::ZomeApiResult; +use crate::workflows::get_links_count::get_link_result_count_workflow; +use crate::workflows::commit::commit_app_entry_workflow; +use crate::workflows::get_entry_result::get_entry_result_workflow; +use crate::workflows::update_entry::update_entry_workflow; +use crate::workflows::remove_entry::remove_entry_workflow; +use crate::workflows::init_globals::init_globals_workflow; +use crate::workflows::get_link_result::get_link_result_workflow; +use crate::workflows::meta::meta_workflow; +use crate::workflows::emit_signal::emit_signal_workflow; +use crate::workflows::sleep::sleep_workflow; +use crate::workflows::verify_signature::verify_signature_workflow; +use crate::workflows::capabilities::commit_capability_grant_workflow; +use crate::workflows::capabilities::commit_capability_claim_workflow; +use crate::workflows::keystore::keystore_list_workflow; +use crate::workflows::keystore::keystore_get_public_key_workflow; +use crate::workflows::keystore::keystore_sign_workflow; +use crate::workflows::keystore::keystore_derive_key_workflow; +use crate::workflows::keystore::keystore_derive_seed_workflow; +use crate::workflows::keystore::keystore_new_random_workflow; +use crate::workflows::sign::sign_one_time_workflow; +use crate::workflows::remove_link_wasm::remove_link_wasm_workflow; +use crate::workflows::send::send_workflow; +use crate::workflows::entry_address::entry_address_workflow; +use crate::workflows::query::query_workflow; +use crate::workflows::call::call_workflow; +use crate::workflows::link_entries::link_entries_workflow; +use crate::workflows::crypto::decrypt_workflow; +use crate::workflows::sign::sign_workflow; +use holochain_wasm_types::WasmResult; #[derive(Clone)] pub struct ZomeCallData { @@ -50,9 +72,9 @@ impl fmt::Display for BadCallError { } } -impl HostError for BadCallError {} +// impl HostError for BadCallError {} -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// // #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] impl WasmCallData { pub fn new_zome_call(context: Arc, call: ZomeFnCall) -> Self { WasmCallData::ZomeCall(ZomeCallData { context, call }) @@ -69,67 +91,35 @@ impl WasmCallData { WasmCallData::DirectCall(name, _) => name.to_string(), } } -} -impl fmt::Display for WasmCallData { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - WasmCallData::ZomeCall(data) => write!(f, "ZomeCall({:?})", data.call), - WasmCallData::CallbackCall(data) => write!(f, "CallbackCall({:?})", data.call), - WasmCallData::DirectCall(name, _) => write!(f, "DirectCall({})", name), + pub fn context(&self) -> Result, HolochainError> { + match &self { + WasmCallData::ZomeCall(ref data) => Ok(data.context.clone()), + WasmCallData::CallbackCall(ref data) => Ok(data.context.clone()), + _ => Err(HolochainError::ErrorGeneric(format!("context data: {:?}", &self))), } } -} - -impl fmt::Debug for WasmCallData { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "WasmCallData({})", self) - } -} - -/// Struct holding data of any call (callback or zome) -#[derive(Clone)] -pub struct CallData { - pub context: Arc, - pub zome_name: String, - pub fn_name: String, - pub parameters: JsonString, -} -/// Object holding data to pass around to invoked Zome API functions -#[derive(Clone)] -pub struct Runtime { - /// Memory state tracker between ribosome and wasm. - pub memory_manager: WasmPageManager, - - /// data to be made available to the function at runtime - pub data: WasmCallData, -} - -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -impl Runtime { - pub fn zome_call_data(&self) -> Result { - match &self.data { + pub fn zome_call_data(&self) -> Result { + match &self { WasmCallData::ZomeCall(ref data) => Ok(data.clone()), - _ => Err(Trap::new(TrapKind::Host(Box::new(BadCallError(format!( - "zome_call_data: {:?}", - &self.data - )))))), + _ => Err(RuntimeError::Trap { + msg: format!("zome_call_data: {:?}", &self).into_boxed_str(), + }), } } - pub fn callback_call_data(&self) -> Result { - match &self.data { + pub fn callback_call_data(&self) -> Result { + match &self { WasmCallData::CallbackCall(ref data) => Ok(data.clone()), - _ => Err(Trap::new(TrapKind::Host(Box::new(BadCallError(format!( - "callback_call_data: {:?}", - &self.data - )))))), + _ => Err(RuntimeError::Trap { + msg: format!("callback_call_data: {:?}", &self).into_boxed_str(), + }), } } - pub fn call_data(&self) -> Result { - match &self.data { + pub fn call_data(&self) -> Result { + match &self { WasmCallData::ZomeCall(ref data) => Ok(CallData { context: data.context.clone(), zome_name: data.call.zome_name.clone(), @@ -142,96 +132,261 @@ impl Runtime { fn_name: data.call.fn_name.clone(), parameters: data.call.parameters.clone(), }), - _ => Err(Trap::new(TrapKind::Host(Box::new(BadCallError(format!( - "call_data: {:?}", - &self.data - )))))), + _ => Err(RuntimeError::Trap { + msg: format!("call_data: {:?}", &self).into_boxed_str(), + }), } } - pub fn context(&self) -> Result, Trap> { - match &self.data { - WasmCallData::ZomeCall(ref data) => Ok(data.context.clone()), - WasmCallData::CallbackCall(ref data) => Ok(data.context.clone()), - _ => Err(Trap::new(TrapKind::Host(Box::new(BadCallError(format!( - "context data: {:?}", - &self.data - )))))), + pub fn instance(&self) -> Result { + let arc = std::sync::Arc::new(self.clone()); + + macro_rules! invoke_workflow_trace { + ( $context:ident, $trace_span:literal, $trace_tag:literal, $args:ident ) => {{ + let span = $context + .tracer + .span(format!("hdk {}", $trace_span)) + .tag(ht::Tag::new( + $trace_tag, + format!("{:?}", $args), + )) + .start() + .into(); + let _spanguard = $crate::ht::push_span(span); + }} } - } - /// Load a JsonString stored in wasm memory. - /// Input RuntimeArgs should only have one input which is the encoded allocation holding - /// the complex data as an utf8 string. - /// Returns the utf8 string. - pub fn load_json_string_from_args(&self, args: &RuntimeArgs) -> JsonString { - // @TODO don't panic in WASM - // @see https://github.com/holochain/holochain-rust/issues/159 - assert_eq!(1, args.len()); - - // Read complex argument serialized in memory - let encoded: RibosomeEncodingBits = args.nth(0); - let return_code = RibosomeEncodedValue::from(encoded); - let allocation = match return_code { - RibosomeEncodedValue::Success => return JsonString::null(), - RibosomeEncodedValue::Failure(_) => { - panic!("received error code instead of valid encoded allocation") - } - RibosomeEncodedValue::Allocation(ribosome_allocation) => { - WasmAllocation::try_from(ribosome_allocation).unwrap() + macro_rules! invoke_workflow_block_and_allocate { + ( $workflow:ident, $context:ident, $args:ident ) => {{ + Ok(holochain_wasmer_host::json::to_allocation_ptr( + $context.block_on( + $workflow(std::sync::Arc::clone(&$context), &$args) + ).map_err(|e| WasmError::Zome(e.to_string()))?.into() + )) + }} + } + + macro_rules! invoke_workflow { + ( $trace_span:literal, $trace_tag:literal, $workflow:ident ) => {{ + let closure_arc = std::sync::Arc::clone(&arc); + move |ctx: &mut Ctx, guest_allocation_ptr: holochain_wasmer_host::AllocationPtr| -> ZomeApiResult { + let context = std::sync::Arc::clone(&closure_arc.context().map_err(|_| WasmError::Unspecified )?); + let guest_data = holochain_wasmer_host::guest::from_allocation_ptr(ctx, guest_allocation_ptr)?; + + invoke_workflow_trace!(context, $trace_span, $trace_tag, guest_data); + invoke_workflow_block_and_allocate!($workflow, context, guest_data) + } + }} + } + + let wasm_imports = imports! { + "env" => { + "__import_allocation" => wasmer_runtime::func!(holochain_wasmer_host::import::__import_allocation), + "__import_bytes" => wasmer_runtime::func!(holochain_wasmer_host::import::__import_bytes), + + // send debug information to the log + // debug(s: String) + "hc_debug" => func!(invoke_workflow!("debug_workflow", "WasmString", debug_workflow)), + + // Commit an app entry to source chain + // commit_entry(entry_type: String, entry_value: String) -> Address + "hc_commit_entry" => func!(invoke_workflow!("commit_app_entry_workflow", "CommitEntryArgs", commit_app_entry_workflow)), + + // Get an app entry from source chain by key (header hash) + // get_entry(address: Address) -> Entry + "hc_get_entry" => func!(invoke_workflow!("get_entry_result_workflow", "GetEntryArgs", get_entry_result_workflow)), + "hc_update_entry" => func!(invoke_workflow!("update_entry_workflow", "UpdateEntryArgs", update_entry_workflow)), + "hc_remove_entry" => func!(invoke_workflow!("remove_entry_workflow", "Address", remove_entry_workflow)), + + // Init Zome API Globals + // hc_init_globals() -> InitGlobalsOutput + // there is no input from the guest for input_globals_workflow + // instead it needs direct access to the wasm call data + "hc_init_globals" => func!({ + let closure_arc = std::sync::Arc::clone(&arc); + move |_: &mut Ctx, _: holochain_wasmer_host::AllocationPtr| -> ZomeApiResult { + let context = Arc::clone(&closure_arc.context().map_err(|_| WasmError::Unspecified )?); + let args = Arc::clone(&closure_arc); + invoke_workflow_trace!(context, "init_globals_workflow", "WasmCallData", args); + invoke_workflow_block_and_allocate!(init_globals_workflow, context, args) + } + }), + + // Call a zome function in a different zome or dna via a bridge + // hc_call(zome_name: String, cap_token: Address, fn_name: String, args: String); + // call_workflow is weird in that it needs BOTH input from the guest AND direct + // access to the wasm call data + // this creates a non-standard workflow function signature with 3 args + // wasm call data cannot be rolled into the input arg as it must be provided by the + // host while the input data must be provided by the guest + "hc_call" => func!({ + let closure_arc = std::sync::Arc::clone(&arc); + move |ctx: &mut Ctx, guest_allocation_ptr: holochain_wasmer_host::AllocationPtr| -> ZomeApiResult { + let context = std::sync::Arc::clone(&closure_arc.context().map_err(|_| WasmError::Unspecified )?); + let guest_data = holochain_wasmer_host::guest::from_allocation_ptr(ctx, guest_allocation_ptr)?; + println!("hc_call guest_data {:?}", &guest_data); + + invoke_workflow_trace!(context, "call_workflow", "ZomeFnCallArgs", guest_data); + Ok(holochain_wasmer_host::json::to_allocation_ptr( + { + let result: WasmResult = context.block_on( + call_workflow(Arc::clone(&context), Arc::clone(&closure_arc), &guest_data) + ).map_err(|e| WasmError::Zome(e.to_string()))?; + println!("hc_call r: {:?}", &result); + JsonString::from(result) + } + )) + } + }), + + // Create a link entry + "hc_link_entries" => func!(invoke_workflow!("link_entries_workflow", "LinkEntriesArgs", link_entries_workflow)), + + /// Retrieve links from the DHT + "hc_get_links" => func!(invoke_workflow!("get_link_result_workflow", "GetLinksArgs", get_link_result_workflow)), + + //Retrieve link count from DHT + "hc_get_links_count" => func!(invoke_workflow!("get_link_result_count_workflow", "GetLinksArgs", get_link_result_count_workflow)), + + // Query the local chain for entries + "hc_query" => func!(invoke_workflow!("query_workflow", "QueryArgs", query_workflow)), + + // Pass an entry to retrieve its address + // the address algorithm is specific to the entry, typically sha256 but can differ + // entry_address(entry: Entry) -> Address + "hc_entry_address" => func!(invoke_workflow!("entry_address_workflow", "Entry", entry_address_workflow)), + + // Send a message directly to another node + "hc_send" => func!(invoke_workflow!("send_workflow", "SendArgs", send_workflow)), + + // Allow a specified amount of time to pass + "hc_sleep" => func!(invoke_workflow!("sleep_workflow", "nanos", sleep_workflow)), + + // Commit link deletion entry + "hc_remove_link" => func!(invoke_workflow!("remove_link_wasm_workflow", "EntryWithHeader", remove_link_wasm_workflow)), + + //execute cryptographic function + // "hc_crypto" => func!(invoke_workflow!("crypto_workflow", "CryptoArgs", crypto_workflow)), + "hc_sign" => func!(invoke_workflow!("sign_workflow", "WasmString", sign_workflow)), + "hc_decrypt" => func!(invoke_workflow!("decrypt_workflow", "WasmString", decrypt_workflow)), + + // Sign a block of data with a one-time key that is then shredded + "hc_sign_one_time" => func!(invoke_workflow!("sign_one_time_workflow", "OneTimeSignArgs", sign_one_time_workflow)), + + // Verify that a block of data was signed by a given public key + "hc_verify_signature" => func!(invoke_workflow!("verify_signature_workflow", "VerifySignatureArgs", verify_signature_workflow)), + + // Retrieve a list of identifiers of the secrets in the keystore + "hc_keystore_list" => func!(invoke_workflow!("keystore_list_workflow", "()", keystore_list_workflow)), + + // Create a new random seed Secret in the keystore + "hc_keystore_new_random" => func!(invoke_workflow!("keystore_new_random_workflow", "WasmString", keystore_new_random_workflow)), + + // Derive a new seed from an existing seed in the keystore + "hc_keystore_derive_seed" => func!(invoke_workflow!("keystore_derive_seed_workflow", "WasmString", keystore_derive_seed_workflow)), + + // Create a new key (signing or encrypting) as derived from an existing seed in the keystore + "hc_keystore_derive_key" => func!(invoke_workflow!("keystore_derive_key_workflow", "WasmString", keystore_derive_key_workflow)), + + // Sign a block of data using a key in the keystore + "hc_keystore_sign" => func!(invoke_workflow!("keystore_sign_workflow", "WasmString", keystore_sign_workflow)), + + // Get the public key for a given secret + "hc_keystore_get_public_key" => func!(invoke_workflow!("keystore_get_public_key_workflow", "WasmString", keystore_get_public_key_workflow)), + + // Commit a capability grant to the source chain + "hc_commit_capability_grant" => func!(invoke_workflow!("commit_capability_grant_workflow", "CommitCapabilityGrantArgs", commit_capability_grant_workflow)), + + // Commit a capability grant to the source chain + "hc_commit_capability_claim" => func!(invoke_workflow!("commit_capability_claim_workflow", "CommitCapabilityClaimArgs", commit_capability_claim_workflow)), + + // Send a DNA defined signal to UIs and other listeners + "hc_emit_signal" => func!(invoke_workflow!("emit_signal_workflow", "EmitSignalArgs", emit_signal_workflow)), + + // send a meta + "hc_meta" => func!(invoke_workflow!("meta_workflow", "MetaArgs", meta_workflow)), + }, + }; + + let (context, zome_name) = if let WasmCallData::DirectCall(_, wasm) = self { + // wasm is the zome cache key as per normal wasmer + return holochain_wasmer_host::instantiate::instantiate(&wasm, &wasm, &wasm_imports).map_err(|e| HolochainError::Wasm(e)); + } else { + match self { + WasmCallData::ZomeCall(d) => (d.context.clone(), d.call.zome_name.clone()), + WasmCallData::CallbackCall(d) => (d.context.clone(), d.call.zome_name.clone()), + WasmCallData::DirectCall(_, _) => unreachable!(), } }; - let bin_arg = self.memory_manager.read(allocation); + let state_lock = context.state()?; + // @TODO caching for wasm and/or modules, just reinstance them + let wasm = state_lock + .nucleus() + .dna + .as_ref() + .unwrap() + .zomes + .get(&zome_name) + .ok_or_else(|| HolochainError::new(&format!("No Ribosome found for Zome '{}'", zome_name)))? + .code + .code + .clone(); - // convert complex argument - JsonString::from_json( - &String::from_utf8(bin_arg) - // @TODO don't panic in WASM - // @see https://github.com/holochain/holochain-rust/issues/159 - .unwrap(), - ) + // cache the wasm under the zome name rather than the hashed wasm + holochain_wasmer_host::instantiate::instantiate(&zome_name.into_bytes(), &wasm, &wasm_imports).map_err(|e| HolochainError::Wasm(e)) } +} - /// Store anything that implements Into in wasm memory. - /// Note that From for JsonString automatically implements Into - /// Input should be a a json string. - /// Returns a Result suitable to return directly from a zome API function, i.e. an encoded allocation - pub fn store_as_json_string>(&mut self, jsonable: J) -> ZomeApiResult { - let j: JsonString = jsonable.into(); - // write str to runtime memory - let mut s_bytes: Vec<_> = j.to_bytes(); - s_bytes.push(0); // Add string terminate character (important) - - match self.memory_manager.write(&s_bytes) { - Err(_) => ribosome_error_code!(Unspecified), - Ok(allocation) => Ok(Some(RuntimeValue::I64(RibosomeEncodingBits::from( - RibosomeEncodedValue::Allocation(allocation.into()), - ) - as RibosomeRuntimeBits))), +impl fmt::Display for WasmCallData { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + WasmCallData::ZomeCall(data) => write!(f, "ZomeCall({:?})", data.call), + WasmCallData::CallbackCall(data) => write!(f, "CallbackCall({:?})", data.call), + WasmCallData::DirectCall(name, _) => write!(f, "DirectCall({})", name), } } +} - pub fn store_result>( - &mut self, - result: Result, - ) -> ZomeApiResult { - self.store_as_json_string(match result { - Ok(value) => ZomeApiInternalResult::success(value), - Err(hc_err) => ZomeApiInternalResult::failure(core_error!(hc_err)), - }) +impl fmt::Debug for WasmCallData { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "WasmCallData({})", self) } } -// Correlate the indexes of core API functions with a call to the actual function -// by implementing the Externals trait from Wasmi. -impl Externals for Runtime { - fn invoke_index(&mut self, index: usize, args: RuntimeArgs) -> ZomeApiResult { - let zf = ZomeApiFunction::from_index(index); - match zf { - ZomeApiFunction::MissingNo => panic!("unknown function index"), - // convert the function to its callable form and call it with the given arguments - _ => zf.apply(self, &args), - } +/// Struct holding data of any call (callback or zome) +#[derive(Clone)] +pub struct CallData { + pub context: Arc, + pub zome_name: String, + pub fn_name: String, + pub parameters: JsonString, +} + +/// Object holding data to pass around to invoked Zome API functions +// #[derive(Clone)] +pub struct Runtime { + pub wasm_instance: Instance, + + /// data to be made available to the function at runtime + pub data: WasmCallData, +} + +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +impl Runtime { + pub fn zome_call_data(&self) -> Result { + self.data.zome_call_data() + } + + pub fn callback_call_data(&self) -> Result { + self.data.callback_call_data() + } + + pub fn call_data(&self) -> Result { + self.data.call_data() + } + + pub fn context(&self) -> Result, HolochainError> { + self.data.context() } } diff --git a/crates/core/src/workflows/application.rs b/crates/core/src/workflows/application.rs index 8344891b1c..af4ae8d3ee 100644 --- a/crates/core/src/workflows/application.rs +++ b/crates/core/src/workflows/application.rs @@ -3,7 +3,7 @@ use crate::{ instance::Instance, network::actions::initialize_network::initialize_network, nucleus::actions::{call_init::call_init, initialize::initialize_chain}, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::{ dna::Dna, @@ -11,7 +11,7 @@ use holochain_core_types::{ }; use std::sync::Arc; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn initialize( instance: &Instance, maybe_dna: Option, diff --git a/crates/core/src/workflows/author_entry.rs b/crates/core/src/workflows/author_entry.rs index 3d87800d1b..4841d30cc4 100644 --- a/crates/core/src/workflows/author_entry.rs +++ b/crates/core/src/workflows/author_entry.rs @@ -6,29 +6,28 @@ use crate::{ nucleus::{ actions::build_validation_package::build_validation_package, validation::validate_entry, }, - NEW_RELIC_LICENSE_KEY, -}; +}; use holochain_core_types::{ entry::Entry, error::HolochainError, signature::Provenance, - validation::{EntryLifecycle, ValidationData}, + validation::{EntryLifecycle, ValidationData, ValidationResult}, }; use holochain_persistence_api::cas::content::{Address, AddressableContent}; -use holochain_wasm_utils::api_serialization::commit_entry::CommitEntryResult; +use holochain_wasm_types::commit_entry::CommitEntryResult; -use crate::wasm_engine::callback::links_utils::get_link_entries; +use crate::workflows::callback::links_utils::get_link_entries; use std::{sync::Arc, vec::Vec}; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub async fn author_entry<'a>( - entry: &'a Entry, +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn author_entry( + context: Arc, + entry: &Entry, maybe_link_update_delete: Option
, - context: &'a Arc, - provenances: &'a Vec, + provenances: &Vec, ) -> Result { let address = entry.address(); log_debug!( @@ -40,14 +39,14 @@ pub async fn author_entry<'a>( // 0. If we are trying to author a link or link removal, make sure the linked entries exist: if let Entry::LinkAdd(link_data) = entry { - get_link_entries(&link_data.link, context)?; + get_link_entries(Arc::clone(&context), &link_data.link)?; } if let Entry::LinkRemove((link_data, _)) = entry { - get_link_entries(&link_data.link, context)?; + get_link_entries(Arc::clone(&context), &link_data.link)?; } // 1. Build the context needed for validation of the entry - let validation_package = build_validation_package(&entry, context.clone(), provenances)?; + let validation_package = build_validation_package(Arc::clone(&context), &entry, provenances)?; let validation_data = ValidationData { package: validation_package, lifecycle: EntryLifecycle::Chain, @@ -59,13 +58,16 @@ pub async fn author_entry<'a>( "workflow/authoring_entry/{}: validating...", address ); - validate_entry( + match validate_entry( + Arc::clone(&context), entry.clone(), maybe_link_update_delete.clone(), validation_data, - &context, ) - .await?; + .await { + ValidationResult::Ok => (), + err => return Err(HolochainError::ValidationFailed(err)), + }; log_debug!(context, "worflow/authoring_entry {}: is valid!", address); // 3. Commit the entry @@ -78,7 +80,7 @@ pub async fn author_entry<'a>( log_debug!(context, "workflow/authoring_entry/{}: committed", address); // 4. Publish the valid entry to DHT. This will call Hold to itself - if entry.entry_type().can_publish(context) { + if entry.entry_type().can_publish(&context) { log_debug!( context, "workflow/authoring_entry/{}: publishing...", @@ -115,7 +117,7 @@ pub async fn author_entry<'a>( pub mod tests { use crate::{ - holochain_wasm_utils::holochain_persistence_api::cas::content::AddressableContent, + holochain_wasm_types::holochain_persistence_api::cas::content::AddressableContent, nucleus::actions::{ get_entry::get_entry_from_dht, tests::{instance_by_name, test_dna}, @@ -127,6 +129,7 @@ pub mod tests { entry::{test_entry_with_value, Entry}, }; use std::{thread, time}; + use std::sync::Arc; // TODO do this for all crate tests somehow #[allow(dead_code)] @@ -153,9 +156,9 @@ pub mod tests { let entry_address = context1 .block_on(author_entry( + Arc::clone(&context1), &test_entry_with_value("{\"stuff\":\"test entry value\"}"), None, - &context1, &vec![], )) .unwrap() @@ -167,7 +170,7 @@ pub mod tests { while entry.is_none() && tries < 10 { tries = tries + 1; { - entry = get_entry_from_dht(&context2, &entry_address) + entry = get_entry_from_dht(Arc::clone(&context2), &entry_address) .expect("Could not retrieve entry from DHT"); } println!("Try {}: {:?}", tries, entry); @@ -193,9 +196,9 @@ pub mod tests { let entry_address = context1 .block_on(author_entry( + Arc::clone(&context1), &test_entry_with_value("{\"stuff\":\"test entry value\"}"), None, - &context1, &vec![], )) .unwrap() @@ -219,7 +222,7 @@ pub mod tests { while entry.is_none() && tries < 10 { tries = tries + 1; { - entry = get_entry_from_dht(&context2, &header_entry.address()) + entry = get_entry_from_dht(Arc::clone(&context2), &header_entry.address()) .expect("Could not retrieve entry from DHT"); } println!("Try {}: {:?}", tries, entry); @@ -243,9 +246,9 @@ pub mod tests { // Jill publishes an entry context1 .block_on(author_entry( + Arc::clone(&context1), &test_entry_with_value("{\"stuff\":\"test entry value number 1\"}"), None, - &context1, &vec![], )) .unwrap() @@ -255,9 +258,9 @@ pub mod tests { // Jill publishes another entry context1 .block_on(author_entry( + Arc::clone(&context1), &test_entry_with_value("{\"stuff\":\"test entry value number 2\"}"), None, - &context1, &vec![], )) .unwrap() @@ -280,7 +283,7 @@ pub mod tests { while entry.is_none() && tries < 10 { tries = tries + 1; { - entry = get_entry_from_dht(&context2, &next_header_addr) + entry = get_entry_from_dht(Arc::clone(&context2), &next_header_addr) .expect("Could not retrieve entry from DHT"); } println!("Try {}: {:?}", tries, entry); diff --git a/crates/core/src/workflows/call.rs b/crates/core/src/workflows/call.rs new file mode 100644 index 0000000000..c2211b1343 --- /dev/null +++ b/crates/core/src/workflows/call.rs @@ -0,0 +1,530 @@ +use crate::{ + context::Context, + nucleus::{ + actions::call_zome_function::{call_zome_function, make_cap_request_for_call}, + ZomeFnCall, + }, + +}; +use holochain_core_types::error::HolochainError; +use holochain_json_api::json::JsonString; +use holochain_json_api::json::RawString; +use holochain_logging::prelude::*; +use holochain_wasm_types::{ZomeFnCallArgs, THIS_INSTANCE, WasmError}; +use jsonrpc_lite::JsonRpc; +use snowflake::ProcessUniqueId; +use std::sync::Arc; +use crate::wasm_engine::runtime::WasmCallData; +use crate::workflows::WorkflowResult; +use holochain_wasm_types::WasmResult; +use std::convert::TryFrom; + +// ZomeFnCallArgs to ZomeFnCall +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +impl ZomeFnCall { + fn from_args(context: Arc, args: ZomeFnCallArgs) -> Self { + // TODO we are currently signing the call ourself. This signature + // should have happend at the client and be extracted from the args. + let cap_call = make_cap_request_for_call( + context, + args.cap_token, + &args.fn_name, + JsonString::from_json(&args.fn_args.clone()), + ); + ZomeFnCall::new( + &args.zome_name, + cap_call, + &args.fn_name, + JsonString::from_json(&args.fn_args), + ) + } +} + +/// HcApiFuncIndex::CALL function code +/// args: [0] encoded MemoryAllocation as u64 +/// expected complex argument: {zome_name: String, cap_token: Address, fn_name: String, args: String} +/// args from API call are converted into a ZomeFnCall +/// Launch an Action::Call with newly formed ZomeFnCall- +/// Waits for a ZomeFnResult +/// Returns an HcApiReturnCode as I64 +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn call_workflow(context: Arc, call_data: Arc, input: &ZomeFnCallArgs) -> WorkflowResult { + if input.instance_handle == THIS_INSTANCE { + // ZomeFnCallArgs to ZomeFnCall + let zome_call = ZomeFnCall::from_args(Arc::clone(&context), input.clone()); + + if let Ok(zome_call_data) = call_data.zome_call_data() { + // Don't allow recursive calls + if zome_call.same_fn_as(&zome_call_data.call) { + return Err(HolochainError::Wasm(WasmError::RecursiveCallForbidden)); + } + } + local_call_workflow(Arc::clone(&context), input.clone()).await.map_err(|error| { + log_error!(context, "zome-to-zome-call/[{:?}]: {:?}", input, error); + error + }) + } else { + // bridge_call_workflow(Arc::clone(&context), input.clone()).await.map_err(|error| { + // log_error!(context, "bridge-call/[{:?}]: {:?}", input, error); + // error + // }) + // @TODO + Ok(WasmResult::Ok(().into())) + } +} + +#[autotrace] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +async fn local_call_workflow(context: Arc, input: ZomeFnCallArgs) -> WorkflowResult { + // ZomeFnCallArgs to ZomeFnCall + let zome_call = ZomeFnCall::from_args(Arc::clone(&context), input.clone()); + log_debug!(context, "blocking on zome call: {:?}", input.clone()); + let result = call_zome_function(Arc::clone(&context), zome_call).await?; + log_debug!( + context, + "blocked on zome call: {:?} with result {:?}", + input, + result + ); + + match WasmResult::try_from(result)? { + WasmResult::Ok(json) => Ok(WasmResult::Ok(JsonString::from(RawString::from(String::from(json))))), + WasmResult::Err(e) => Err(e)?, + } +} + +#[autotrace] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +async fn bridge_call_workflow(context: Arc, input: ZomeFnCallArgs) -> WorkflowResult { + let conductor_api = context.conductor_api.clone(); + + let params = format!( + r#"{{"instance_id":"{}", "zome": "{}", "function": "{}", "args": {}}}"#, + input.instance_handle, input.zome_name, input.fn_name, input.fn_args + ); + + let handler = conductor_api.get().write()?; + + let id = ProcessUniqueId::new(); + // json-rpc format + let request = format!( + r#"{{"jsonrpc": "2.0", "method": "call", "params": {}, "id": "{}"}}"#, + params, id + ); + + let response = handler + .handle_request_sync(&request) + .ok_or("Bridge call failed")?; + + let response = JsonRpc::parse(&response)?; + + match response { + JsonRpc::Success(_) => { + // First we try to unwrap a potential stringification: + let value_response = response.get_result().unwrap().to_owned(); + let string_response = value_response.to_string(); + let maybe_parsed_string: Result = + serde_json::from_str(&string_response); + let sanitized_response = match maybe_parsed_string { + Ok(string) => string, + Err(_) => string_response, + }; + // Below, sanitized_response is the same response but guaranteed without quotes. + // This should be returned as a JsonString for handling in the zome code. + Ok(JsonString::from_json(&sanitized_response)) + } + JsonRpc::Error(_) => Err(HolochainError::ErrorGeneric( + serde_json::to_string(&response.get_error()?)?, + )), + _ => Err(HolochainError::ErrorGeneric( + "Bridge call failed".to_string(), + )), + } +} + +// #[cfg(test)] +// pub mod tests { +// use super::*; +// use test_utils; +// +// use crate::{ +// context::Context, +// instance::{ +// tests::{test_context, test_instance_and_context}, +// Instance, +// }, +// nucleus::{ +// actions::call_zome_function::{check_capability, validate_call}, +// tests::*, +// }, +// wasm_engine::{ +// api::{ +// call::ZomeFnCall, +// tests::{ +// test_function_name, test_parameters, test_zome_api_function_wasm, +// test_zome_name, +// }, +// ZomeApiFunction, +// }, +// Defn, +// }, +// workflows::author_entry::author_entry, +// }; +// use crossbeam_channel::RecvTimeoutError; +// use holochain_core_types::{ +// dna::{ +// capabilities::CapabilityRequest, +// // fn_declarations::{FnDeclaration, TraitFns}, +// // traits::ReservedTraitNames, +// Dna, +// }, +// entry::{ +// cap_entries::{CapFunctions, CapTokenGrant, CapabilityType}, +// Entry, +// }, +// error::{DnaError, HolochainError}, +// signature::Signature, +// }; +// use holochain_json_api::json::JsonString; +// use holochain_persistence_api::cas::content::{Address, AddressableContent}; +// use holochain_wasm_types::ZomeFnCallArgs; +// use serde_json; +// use std::{sync::Arc}; +// // use test_utils::create_test_dna_with_defs; +// +// /// dummy commit args from standard test entry +// #[cfg_attr(tarpaulin, skip)] +// pub fn test_bad_args_bytes() -> Vec { +// let args = ZomeFnCallArgs { +// instance_handle: "instance_handle".to_string(), +// zome_name: "zome_name".to_string(), +// cap_token: Address::from("bad cap_token"), +// fn_name: "fn_name".to_string(), +// fn_args: "fn_args".to_string(), +// }; +// serde_json::to_string(&args) +// .expect("args should serialize") +// .into_bytes() +// } +// +// #[cfg_attr(tarpaulin, skip)] +// pub fn test_args_bytes() -> Vec { +// let args = ZomeFnCallArgs { +// instance_handle: THIS_INSTANCE.to_string(), +// zome_name: test_zome_name(), +// cap_token: Address::from("test_token"), +// fn_name: test_function_name(), +// fn_args: test_parameters().to_string(), +// }; +// serde_json::to_string(&args) +// .expect("args should serialize") +// .into_bytes() +// } +// +// #[allow(dead_code)] +// pub struct TestSetup { +// pub context: Arc, +// pub instance: Instance, +// } +// +// pub fn setup_test(dna: Dna, netname: &str) -> TestSetup { +// let netname = Some(netname); +// let (instance, context) = +// test_instance_and_context(dna, netname).expect("Could not initialize test instance"); +// TestSetup { context, instance } +// } +// +// #[cfg_attr(tarpaulin, skip)] +// fn test_reduce_call( +// test_setup: &TestSetup, +// cap_request: CapabilityRequest, +// expected: Result, RecvTimeoutError>, +// ) { +// let zome_call = ZomeFnCall::new("test_zome", cap_request, "test", "{}"); +// let result = test_setup +// .context +// .block_on(call_zome_function(Arc::clone(&test_setup.context), zome_call)); +// assert_eq!(expected, Ok(result)); +// } +// +// #[test] +// fn test_call_no_zome() { +// let dna = test_utils::create_test_dna_with_wat("bad_zome", None); +// let test_setup = setup_test(dna, "test_call_no_zome"); +// let expected = Ok(Err(HolochainError::Dna(DnaError::ZomeNotFound( +// r#"Zome 'test_zome' not found"#.to_string(), +// )))); +// test_reduce_call(&test_setup, dummy_capability_request(), expected); +// } +// +// // fn setup_dna_for_test(make_public: bool) -> Dna { +// // let wasm = test_zome_api_function_wasm(ZomeApiFunction::Call.as_str()); +// // let mut trait_fns = TraitFns::new(); +// // let fn_decl = FnDeclaration { +// // name: test_function_name(), +// // inputs: Vec::new(), +// // outputs: Vec::new(), +// // }; +// // trait_fns.functions = vec![fn_decl.name.clone()]; +// // let mut traits = BTreeMap::new(); +// // let trait_name = if make_public { +// // ReservedTraitNames::Public.as_str().to_string() +// // } else { +// // "test_trait".to_string() +// // }; +// // traits.insert(trait_name, trait_fns); +// // let mut functions = Vec::new(); +// // functions.push(fn_decl); +// // +// // create_test_dna_with_defs(&test_zome_name(), (functions, traits), &wasm) +// // } +// +// // success to test_reduce_call is when the function gets called which shows up as an +// // argument deserialization error because we are reusing the wasm from test_zome_api_function +// // which just passes the function parameter through to "invoke_call" which expects a +// // ZomeFnCallArgs struct which the test "{}" is not! +// // TODO: fix this bit of crazyness +// fn success_expected() -> Result, RecvTimeoutError> { +// Ok(Err(HolochainError::Wasm(WasmError::ArgumentDeserializationFailed))) +// } +// +// // #[test] +// // fn test_call_public() { +// // let dna = setup_dna_for_test(true); +// // let test_setup = setup_test(dna, "test_call_public"); +// // let token = test_setup.context.get_public_token().unwrap(); +// // let other_agent_context = test_context("other agent", None); +// // let cap_request = make_cap_request_for_call(other_agent_context, token, "test", "{}"); +// // +// // // make the call with public token capability call +// // test_reduce_call(&test_setup, cap_request, success_expected()); +// // +// // // make the call with a bogus public token capability call +// // let cap_request = CapabilityRequest::new( +// // Address::from("foo_token"), +// // Address::from("some caller"), +// // Signature::fake(), +// // ); +// // let expected_failure = Ok(Err(HolochainError::CapabilityCheckFailed)); +// // test_reduce_call(&test_setup, cap_request, expected_failure); +// // } +// +// // #[test] +// // fn test_call_transferable() { +// // let dna = setup_dna_for_test(false); +// // let test_setup = setup_test(dna, "test_call_transferable"); +// // let expected_failure = Ok(Err(HolochainError::CapabilityCheckFailed)); +// // +// // // make the call with an invalid capability call, i.e. incorrect token +// // let cap_request = CapabilityRequest::new( +// // Address::from("foo_token"), +// // Address::from("some caller"), +// // Signature::fake(), +// // ); +// // test_reduce_call(&test_setup, cap_request.clone(), expected_failure.clone()); +// // +// // // make the call with an valid capability call from self +// // let cap_request = test_agent_capability_request(test_setup.context.clone(), "test", "{}"); +// // test_reduce_call(&test_setup, cap_request, success_expected()); +// // +// // // make the call with an invalid valid capability call from self +// // let cap_request = +// // test_agent_capability_request(test_setup.context.clone(), "some_fn", "{}"); +// // test_reduce_call(&test_setup, cap_request, expected_failure); +// // +// // let mut cap_functions = CapFunctions::new(); +// // cap_functions.insert("test_zome".to_string(), vec![String::from("test")]); +// // // make the call with an valid capability call from a different sources +// // let grant = CapTokenGrant::create("foo", CapabilityType::Transferable, None, cap_functions) +// // .unwrap(); +// // let grant_entry = Entry::CapTokenGrant(grant); +// // let addr = test_setup +// // .context +// // .block_on(author_entry( +// // &grant_entry, +// // None, +// // &test_setup.context, +// // &vec![], +// // )) +// // .unwrap() +// // .address(); +// // let other_agent_context = test_context("other agent", None); +// // let cap_request = +// // make_cap_request_for_call(other_agent_context.clone(), addr, "test", "{}"); +// // test_reduce_call(&test_setup, cap_request, success_expected()); +// // } +// +// // #[test] +// // fn test_call_assigned() { +// // let dna = setup_dna_for_test(false); +// // let test_setup = setup_test(dna, "test_call_assigned"); +// // let expected_failure = Ok(Err(HolochainError::CapabilityCheckFailed)); +// // let cap_request = CapabilityRequest::new( +// // Address::from("foo_token"), +// // Address::from("any caller"), +// // Signature::fake(), +// // ); +// // test_reduce_call(&test_setup, cap_request, expected_failure.clone()); +// // +// // // test assigned capability where the caller is the agent +// // let agent_token_str = test_setup.context.agent_id.address(); +// // let cap_request = make_cap_request_for_call( +// // test_setup.context.clone(), +// // Address::from(agent_token_str.clone()), +// // "test", +// // "{}", +// // ); +// // test_reduce_call(&test_setup, cap_request, success_expected()); +// // +// // // test assigned capability where the caller is someone else +// // let other_agent_context = test_context("other agent", None); +// // let someone = other_agent_context.agent_id.address(); +// // let mut cap_functions = CapFunctions::new(); +// // cap_functions.insert("test_zome".to_string(), vec![String::from("test")]); +// // let grant = CapTokenGrant::create( +// // "foo", +// // CapabilityType::Assigned, +// // Some(vec![someone.clone()]), +// // cap_functions, +// // ) +// // .unwrap(); +// // let grant_entry = Entry::CapTokenGrant(grant); +// // let grant_addr = test_setup +// // .context +// // .block_on(author_entry( +// // &grant_entry, +// // None, +// // &test_setup.context, +// // &vec![], +// // )) +// // .unwrap() +// // .address(); +// // let cap_request = make_cap_request_for_call( +// // test_context("random other agent", None), +// // grant_addr.clone(), +// // "test", +// // "{}", +// // ); +// // test_reduce_call(&test_setup, cap_request, expected_failure.clone()); +// // +// // // test assigned capability where the caller is someone else +// // let cap_request = +// // make_cap_request_for_call(other_agent_context.clone(), grant_addr, "test", "{}"); +// // test_reduce_call(&test_setup, cap_request, success_expected()); +// // } +// +// // #[test] +// // fn test_validate_call_public() { +// // let dna = setup_dna_for_test(true); +// // let test_setup = setup_test(dna, "test_validate_call_public"); +// // let context = test_setup.context; +// // +// // // non existent functions should fail +// // let zome_call = ZomeFnCall::new("test_zome", dummy_capability_request(), "foo_func", "{}"); +// // let result = validate_call(context.clone(), &zome_call); +// // assert_eq!( +// // result, +// // Err(HolochainError::Dna(DnaError::ZomeFunctionNotFound( +// // String::from("Zome function \'foo_func\' not found in Zome \'test_zome\'") +// // ))) +// // ); +// // +// // // non existent zomes should fial +// // let zome_call = ZomeFnCall::new("foo_zome", dummy_capability_request(), "test", "{}"); +// // let result = validate_call(context.clone(), &zome_call); +// // assert_eq!( +// // result, +// // Err(HolochainError::Dna(DnaError::ZomeNotFound(String::from( +// // "Zome \'foo_zome\' not found" +// // )))) +// // ); +// // } +// +// // #[test] +// // fn test_validate_call_by_agent() { +// // let dna = setup_dna_for_test(false); +// // let test_setup = setup_test(dna, "validate_call_by_agent"); +// // let context = test_setup.context; +// // +// // // non public call should fail +// // let zome_call = ZomeFnCall::new("test_zome", dummy_capability_request(), "test", "{}"); +// // let result = validate_call(context.clone(), &zome_call); +// // assert_eq!(result, Err(HolochainError::CapabilityCheckFailed)); +// // +// // // if the agent doesn't correctly sign the call it should fail +// // let zome_call = ZomeFnCall::new( +// // "test_zome", +// // make_cap_request_for_call( +// // context.clone(), +// // Address::from(context.agent_id.address()), // <- agent token +// // "foo_function", //<- not the function in the zome_call! +// // "{}", +// // ), +// // "test", +// // "{}", +// // ); +// // +// // let result = validate_call(context.clone(), &zome_call); +// // assert_eq!(result, Err(HolochainError::CapabilityCheckFailed)); +// // +// // // should work with correctly signed cap_request +// // let zome_call = ZomeFnCall::new( +// // "test_zome", +// // make_cap_request_for_call( +// // context.clone(), +// // Address::from(context.agent_id.address()), // <- agent token +// // "test", +// // "{}", +// // ), +// // "test", +// // "{}", +// // ); +// // let result = validate_call(context.clone(), &zome_call); +// // assert!(result.is_ok()); +// // } +// +// #[test] +// fn test_check_capability_transferable() { +// let dna = setup_dna_for_test(false); +// let test_setup = setup_test(dna, "test_check_cap_transferable"); +// let context = test_setup.context; +// +// // bogus cap_request should fail +// let zome_call = ZomeFnCall::new( +// "test_zome", +// CapabilityRequest::new( +// Address::from("foo_token"), +// Address::from("some caller"), +// Signature::fake(), +// ), +// "test", +// "{}", +// ); +// assert!(!check_capability(context.clone(), &zome_call)); +// +// let mut cap_functions = CapFunctions::new(); +// cap_functions.insert("test_zome".to_string(), vec![String::from("test")]); +// // add the transferable grant and get the token which is the grant's address +// let grant = CapTokenGrant::create("foo", CapabilityType::Transferable, None, cap_functions) +// .unwrap(); +// let grant_entry = Entry::CapTokenGrant(grant); +// let grant_addr = context +// .block_on(author_entry(&grant_entry, None, &context, &vec![])) +// .unwrap() +// .address(); +// +// // make the call with a valid capability call from a random source should succeed +// let zome_call = ZomeFnCall::new( +// "test_zome", +// make_cap_request_for_call( +// test_context("some_random_agent", None), +// grant_addr, +// "test", +// "{}", +// ), +// "test", +// "{}", +// ); +// assert!(check_capability(context.clone(), &zome_call)); +// } +// } diff --git a/crates/core/src/wasm_engine/callback/init.rs b/crates/core/src/workflows/callback/init.rs similarity index 89% rename from crates/core/src/wasm_engine/callback/init.rs rename to crates/core/src/workflows/callback/init.rs index a25ea53885..33e63b65de 100644 --- a/crates/core/src/wasm_engine/callback/init.rs +++ b/crates/core/src/workflows/callback/init.rs @@ -1,13 +1,12 @@ -use super::call; use crate::{ context::Context, - wasm_engine::callback::{Callback, CallbackParams, CallbackResult}, - NEW_RELIC_LICENSE_KEY, + wasm_engine::callback::{call, Callback, CallbackParams}, }; +use holochain_core_types::callback::CallbackResult; use std::sync::Arc; #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn init( context: Arc, zome: &str, @@ -24,10 +23,10 @@ pub mod tests { use crate::{ instance::tests::test_context, wasm_engine::{ - callback::{tests::test_callback_instance, Callback, CallbackParams, CallbackResult}, - Defn, + callback::{tests::test_callback_instance, Callback, CallbackParams}, }, }; + use holochain_core_types::callback::CallbackResult; #[test] fn pass() { diff --git a/crates/core/src/wasm_engine/callback/links_utils.rs b/crates/core/src/workflows/callback/links_utils.rs similarity index 85% rename from crates/core/src/wasm_engine/callback/links_utils.rs rename to crates/core/src/workflows/callback/links_utils.rs index cda93ad079..63c0923fa6 100644 --- a/crates/core/src/wasm_engine/callback/links_utils.rs +++ b/crates/core/src/workflows/callback/links_utils.rs @@ -1,41 +1,42 @@ use crate::{ - context::Context, workflows::get_entry_result::get_entry_result_workflow, NEW_RELIC_LICENSE_KEY, + context::Context, workflows::get_entry_result::get_entry_result_workflow, }; use holochain_core_types::{ entry::{entry_type::EntryType, Entry}, error::HolochainError, link::Link, }; -use holochain_wasm_utils::api_serialization::{get_entry::*, validation::LinkDirection}; +use holochain_wasm_types::{get_entry::*, validation::LinkDirection}; use std::sync::Arc; /// Retrieves the base and target entries of the link and returns both. #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// @TODO fix this swallowing line numbers +// // #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn get_link_entries( + context: Arc, link: &Link, - context: &Arc, ) -> Result<(Entry, Entry), HolochainError> { let base_address = link.base(); let target_address = link.target(); - let entry_args = &GetEntryArgs { + let entry_args = GetEntryArgs { address: base_address.clone(), options: Default::default(), }; let base_entry_get_result = - context.block_on(get_entry_result_workflow(&context, entry_args))?; + context.block_on(get_entry_result_workflow(Arc::clone(&context), &entry_args))?; if !base_entry_get_result.found() { return Err(HolochainError::ErrorGeneric(String::from( "Base for link not found", ))); } let base_entry = base_entry_get_result.latest().unwrap(); - let entry_args = &GetEntryArgs { + let entry_args = GetEntryArgs { address: target_address.clone(), options: Default::default(), }; let target_entry_get_result = - context.block_on(get_entry_result_workflow(&context, entry_args))?; + context.block_on(get_entry_result_workflow(Arc::clone(&context), &entry_args))?; if !target_entry_get_result.found() { return Err(HolochainError::ErrorGeneric(String::from( "Target for link not found", @@ -66,10 +67,10 @@ pub struct LinkDefinitionPath { /// zomes, entry types and their links and returns the first match. /// /// Returns a LinkDefinitionPath to uniquely reference the link definition in the DNA. -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// // #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn find_link_definition_by_type( + context: Arc, link_type: &String, - context: &Arc, ) -> Result { let dna = context.get_dna().expect("No DNA found?!"); for (zome_name, zome) in dna.zomes.iter() { diff --git a/crates/core/src/workflows/callback/mod.rs b/crates/core/src/workflows/callback/mod.rs new file mode 100644 index 0000000000..2b5fd722b9 --- /dev/null +++ b/crates/core/src/workflows/callback/mod.rs @@ -0,0 +1,4 @@ +pub mod validation_package; +pub mod links_utils; +pub mod init; +pub mod receive; diff --git a/crates/core/src/wasm_engine/callback/receive.rs b/crates/core/src/workflows/callback/receive.rs similarity index 68% rename from crates/core/src/wasm_engine/callback/receive.rs rename to crates/core/src/workflows/callback/receive.rs index 7243dd21e9..94dc8b792a 100644 --- a/crates/core/src/wasm_engine/callback/receive.rs +++ b/crates/core/src/workflows/callback/receive.rs @@ -2,22 +2,22 @@ use crate::{ context::Context, nucleus::CallbackFnCall, wasm_engine::{ - self, - callback::{Callback, CallbackParams, CallbackResult}, + callback::{Callback, CallbackParams}, runtime::WasmCallData, - Defn, }, - NEW_RELIC_LICENSE_KEY, -}; +}; +use holochain_core_types::callback::CallbackResult; +use holochain_wasmer_host::WasmError; use holochain_json_api::{error::JsonError, json::JsonString}; use std::sync::Arc; #[derive(Serialize, Deserialize, Debug, DefaultJson)] struct ReceiveReturnValue(Result); -#[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// @TODO fix this autotrace +// #[autotrace] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn receive( context: Arc, zome: &str, @@ -35,28 +35,36 @@ pub fn receive( JsonString::from(params), ); - match wasm_engine::run_dna( - Some(call.clone().parameters.to_bytes()), - WasmCallData::new_callback_call(context, call), - ) { - Ok(call_result) => CallbackResult::ReceiveResult(call_result.to_string()), - Err(err) => CallbackResult::Fail(err.to_string()), + let call_data = WasmCallData::new_callback_call(context, call.clone()); + + let call_result: Result = holochain_wasmer_host::guest::call( + &mut match call_data.instance() { + Ok(instance) => instance, + Err(_) => return CallbackResult::Fail(format!("Failed to get an instance for call data: {:?}", &call_data)), + }, + &call_data.fn_name(), + call.clone().parameters, + ); + + match call_result { + Ok(CallbackResult::ReceiveResult(receive_result)) => CallbackResult::ReceiveResult(receive_result), + Ok(v) => CallbackResult::Fail(format!("Expected a CallbackResult::ReceiveResult, got {:?}", v)), + Err(err) => CallbackResult::Fail(format!("Wasm errored while attempting a receive callback {:?}", err)), } } #[cfg(test)] pub mod tests { - use super::receive; use crate::{ instance::tests::test_context, wasm_engine::{ - callback::{tests::test_callback_instance, Callback, CallbackParams, CallbackResult}, - Defn, + callback::{tests::test_callback_instance, Callback, CallbackParams}, }, }; + use holochain_core_types::callback::CallbackResult; use holochain_persistence_api::cas::content::Address; - use holochain_wasm_utils::api_serialization::receive::ReceiveParams; + use holochain_wasm_types::receive::ReceiveParams; #[test] fn receive_fail() { diff --git a/crates/core/src/wasm_engine/callback/validation_package.rs b/crates/core/src/workflows/callback/validation_package.rs similarity index 61% rename from crates/core/src/wasm_engine/callback/validation_package.rs rename to crates/core/src/workflows/callback/validation_package.rs index ab4eabddbb..21fab8b458 100644 --- a/crates/core/src/wasm_engine/callback/validation_package.rs +++ b/crates/core/src/workflows/callback/validation_package.rs @@ -2,31 +2,29 @@ use crate::{ context::Context, nucleus::CallbackFnCall, wasm_engine::{ - self, - callback::{links_utils, CallbackResult}, runtime::WasmCallData, }, - NEW_RELIC_LICENSE_KEY, }; use holochain_core_types::{ + callback::CallbackResult, entry::{entry_type::EntryType, Entry}, error::HolochainError, validation::ValidationPackageDefinition, + validation::ValidationResult, }; +use crate::workflows::callback::links_utils; +use holochain_wasm_types::validation::LinkValidationPackageArgs; +use std::{sync::Arc}; -use holochain_json_api::json::JsonString; - -use holochain_wasm_utils::api_serialization::validation::LinkValidationPackageArgs; -use std::{convert::TryFrom, sync::Arc}; - -#[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// @TODO fix line number mangling +// #[autotrace] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn get_validation_package_definition( - entry: &Entry, context: Arc, + entry: &Entry, ) -> Result { let dna = context.get_dna().expect("Callback called without DNA set!"); - let result = match entry.entry_type() { + let result: ValidationPackageDefinition = match entry.entry_type() { EntryType::App(app_entry_type) => { let zome_name = dna.get_zome_name_for_app_entry_type(&app_entry_type); if zome_name.is_none() { @@ -42,23 +40,26 @@ pub fn get_validation_package_definition( "__hdk_get_validation_package_for_entry_type", app_entry_type.clone(), ); - wasm_engine::run_dna( - Some(app_entry_type.to_string().into_bytes()), - WasmCallData::new_callback_call(context, call), + let call_data = WasmCallData::new_callback_call(context, call); + println!("get_validation_package app entry 1 {}", call_data.fn_name()); + holochain_wasmer_host::guest::call( + &mut call_data.instance()?, + &call_data.fn_name(), + app_entry_type, )? } EntryType::LinkAdd => { let link_add = match entry { Entry::LinkAdd(link_add) => link_add, _ => { - return Err(HolochainError::ValidationFailed( + return Err(HolochainError::ValidationFailed(ValidationResult::Fail( "Failed to extract LinkAdd".into(), - )); + ))); } }; let link_definition_path = - links_utils::find_link_definition_by_type(link_add.link().link_type(), &context)?; + links_utils::find_link_definition_by_type(Arc::clone(&context), link_add.link().link_type())?; let params = LinkValidationPackageArgs { entry_type: link_definition_path.entry_type_name, @@ -72,24 +73,26 @@ pub fn get_validation_package_definition( params, ); - wasm_engine::run_dna( - Some(call.parameters.to_bytes()), - WasmCallData::new_callback_call(context, call), + let call_data = WasmCallData::new_callback_call(context, call.clone()); + holochain_wasmer_host::guest::call( + &mut call_data.instance()?, + &call_data.fn_name(), + call.parameters, )? } EntryType::LinkRemove => { let link_remove = match entry { Entry::LinkRemove((link_remove, _)) => link_remove, _ => { - return Err(HolochainError::ValidationFailed( + return Err(HolochainError::ValidationFailed(ValidationResult::Fail( "Failed to extract LinkRemove".into(), - )); + ))); } }; let link_definition_path = links_utils::find_link_definition_by_type( + Arc::clone(&context), link_remove.link().link_type(), - &context, )?; let params = LinkValidationPackageArgs { @@ -104,30 +107,21 @@ pub fn get_validation_package_definition( params, ); - wasm_engine::run_dna( - Some(call.parameters.to_bytes()), - WasmCallData::new_callback_call(context, call), + let call_data = WasmCallData::new_callback_call(context, call.clone()); + holochain_wasmer_host::guest::call( + &mut call_data.instance()?, + &call_data.fn_name(), + call.parameters, )? } - EntryType::Deletion => JsonString::from(ValidationPackageDefinition::ChainFull), - EntryType::CapTokenGrant => JsonString::from(ValidationPackageDefinition::Entry), - EntryType::AgentId => JsonString::from(ValidationPackageDefinition::Entry), - EntryType::ChainHeader => JsonString::from(ValidationPackageDefinition::Entry), + EntryType::Deletion => ValidationPackageDefinition::ChainFull, + EntryType::CapTokenGrant => ValidationPackageDefinition::Entry, + EntryType::AgentId => ValidationPackageDefinition::Entry, + EntryType::ChainHeader => ValidationPackageDefinition::Entry, _ => Err(HolochainError::NotImplemented( "get_validation_package_definition/3".into(), ))?, }; - if result.is_null() { - Err(HolochainError::SerializationError(String::from( - "__hdk_get_validation_package_for_entry_type returned empty result", - ))) - } else { - match ValidationPackageDefinition::try_from(result) { - Ok(package) => Ok(CallbackResult::ValidationPackageDefinition(package)), - Err(_) => Err(HolochainError::SerializationError(String::from( - "validation_package result could not be deserialized as ValidationPackage", - ))), - } - } + Ok(CallbackResult::ValidationPackageDefinition(result)) } diff --git a/crates/core/src/workflows/capabilities.rs b/crates/core/src/workflows/capabilities.rs new file mode 100644 index 0000000000..5c72aacdae --- /dev/null +++ b/crates/core/src/workflows/capabilities.rs @@ -0,0 +1,109 @@ +use crate::{agent::actions::commit::commit_entry}; +use holochain_core_types::{ + entry::{ + cap_entries::{CapTokenClaim, CapTokenGrant}, + Entry, + }, + error::HolochainError, +}; +use holochain_persistence_api::cas::content::Address; +use holochain_wasm_types::capabilities::{ + CommitCapabilityClaimArgs, CommitCapabilityGrantArgs, +}; +use std::sync::Arc; +use crate::context::Context; +use crate::workflows::WorkflowResult; + +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn commit_capability_grant_workflow( + context: Arc, + args: &CommitCapabilityGrantArgs, +) -> WorkflowResult
{ + match CapTokenGrant::create(&args.id, args.cap_type.clone(), args.assignees.clone(), args.functions.clone()) { + Ok(grant) => commit_entry(Entry::CapTokenGrant(grant), None, &context).await, + Err(err) => Err(HolochainError::ErrorGeneric(format!( + "Unable to commit capability grant: {}", + err + ))), + } +} + +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn commit_capability_claim_workflow( + context: Arc, + args: &CommitCapabilityClaimArgs, +) -> WorkflowResult
{ + let claim = CapTokenClaim::new(args.id.clone(), args.grantor.clone(), args.token.clone()); + commit_entry(Entry::CapTokenClaim(claim), None, &context).await +} + +#[cfg(test)] +pub mod tests { + use holochain_core_types::{entry::cap_entries::CapabilityType}; + use holochain_json_api::json::JsonString; + use holochain_persistence_api::cas::content::Address; + use holochain_wasm_types::capabilities::{ + CommitCapabilityClaimArgs, CommitCapabilityGrantArgs, + }; + use std::collections::BTreeMap; + + /// dummy args + pub fn test_commit_capability_grant_args_bytes() -> Vec { + let mut functions = BTreeMap::new(); + functions.insert("test_zome".to_string(), vec!["test_function".to_string()]); + let grant_args = CommitCapabilityGrantArgs { + id: "some_id".to_string(), + cap_type: CapabilityType::Assigned, + assignees: Some(vec![Address::from("fake address")]), + functions, + }; + + JsonString::from(grant_args).to_bytes() + } + + pub fn test_commit_capability_claim_args_bytes() -> Vec { + let claim_args = CommitCapabilityClaimArgs { + id: "some_id".to_string(), + grantor: Address::from("fake grantor"), + token: Address::from("fake"), + }; + + JsonString::from(claim_args).to_bytes() + } + + // #[test] + // /// test that we can round trip bytes through a commit_capability_grant action and get the result from WASM + // fn test_commit_capability_grant_round_trip() { + // let (call_result, _) = test_zome_api_function( + // ZomeApiFunction::CommitCapabilityGrant.as_str(), + // test_commit_capability_grant_args_bytes(), + // ); + // + // assert_eq!( + // call_result, + // JsonString::from_json( + // &(String::from(JsonString::from(ZomeApiInternalResult::success( + // Address::from("Qma8KWBHZwiXNBJ4PBtT4uDUVgPAyUJASHumThZMTPAAJe") + // ))) + "\u{0}") + // ), + // ); + // } + + // #[test] + // /// test that we can round trip bytes through a commit_capability_claim action and get the result from WASM + // fn test_commit_capability_claim_round_trip() { + // let (call_result, _) = test_zome_api_function( + // ZomeApiFunction::CommitCapabilityClaim.as_str(), + // test_commit_capability_claim_args_bytes(), + // ); + // + // assert_eq!( + // call_result, + // JsonString::from_json( + // &(String::from(JsonString::from(ZomeApiInternalResult::success( + // Address::from("QmeuneB3iJjcGMkei7N8kyoc7Ubi4ab3xMNPYXSse2vdm5") + // ))) + "\u{0}") + // ), + // ); + // } +} diff --git a/crates/core/src/workflows/commit.rs b/crates/core/src/workflows/commit.rs new file mode 100644 index 0000000000..14d80ce898 --- /dev/null +++ b/crates/core/src/workflows/commit.rs @@ -0,0 +1,70 @@ +use crate::{workflows::author_entry::author_entry}; +use holochain_core_types::error::HolochainError; +use holochain_wasm_types::commit_entry::{CommitEntryArgs, CommitEntryResult}; +use crate::context::Context; +use std::sync::Arc; + +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn commit_app_entry_workflow(context: Arc, commit_entry_args: &CommitEntryArgs) -> Result { + println!("commit_app_entry_workflow {:?}", commit_entry_args); + author_entry( + Arc::clone(&context), + &commit_entry_args.entry(), + None, + &commit_entry_args.options().provenance(), + ).await +} + +#[cfg(test)] +pub mod tests { + use holochain_core_types::{ + entry::test_entry, + // error::ZomeApiInternalResult, + signature::{Provenance, Signature}, + }; + use holochain_json_api::json::JsonString; + use holochain_persistence_api::cas::content::{Address, AddressableContent}; + use holochain_wasm_types::commit_entry::{ + CommitEntryArgs, CommitEntryOptions, + }; + + /// dummy commit with provenance args from standard test entry + pub fn test_commit_entry_args_bytes() -> Vec { + let entry = test_entry(); + let address: Address = entry.address(); + + let agent_nick = "counter-signer"; + let agent_id = test_utils::mock_signing::registered_test_agent(agent_nick); + + let signature = Signature::from(test_utils::mock_signing::mock_signer( + String::from(address.clone()), + &agent_id, + )); + + let provenances = vec![Provenance::new(agent_id.address(), signature)]; + let serialized_commit_entry_arg = + CommitEntryArgs::new(entry, CommitEntryOptions::new(provenances)); + JsonString::from(serialized_commit_entry_arg).to_bytes() + } + + // #[test] + // /// test that we can round trip bytes through a commit action with + // /// additional provenance and get the result from WASM + // fn test_commit_round_trip() { + // let (call_result, _) = test_zome_api_function( + // ZomeApiFunction::CommitAppEntry.as_str(), + // test_commit_entry_args_bytes(), + // ); + // + // assert_eq!( + // call_result, + // JsonString::from_json( + // &(String::from(JsonString::from(ZomeApiInternalResult::success( + // CommitEntryResult::new(Address::from( + // "Qma6RfzvZRL127UCEVEktPhQ7YSS1inxEFw7SjEsfMJcrq" + // )) + // ))) + "\u{0}") + // ), + // ); + // } +} diff --git a/crates/core/src/workflows/crypto.rs b/crates/core/src/workflows/crypto.rs new file mode 100644 index 0000000000..d11b8e3d7e --- /dev/null +++ b/crates/core/src/workflows/crypto.rs @@ -0,0 +1,115 @@ +use holochain_wasm_types::crypto::CryptoArgs; +use crate::workflows::WorkflowResult; +use crate::context::Context; +use std::sync::Arc; +use holochain_wasm_types::wasm_string::WasmString; +use holochain_wasm_types::crypto::CryptoMethod; + +/// ZomeApiFunction::Sign function code +/// args: [0] encoded MemoryAllocation as u64 +/// Expected argument: u64 +/// Returns an HcApiReturnCode as I64 +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn crypto_workflow(context: Arc, crypto_args: &CryptoArgs) -> WorkflowResult { + println!("crypto_workflow: {:?}", crypto_args); + let message = context + .conductor_api + .execute(crypto_args.payload.clone(), crypto_args.method.clone()); + println!("crypto_workflow message: {:?}", message); + + log_debug!( + context, + "zome: crypto method {:?} of data:{:?} by:{:?} is:{:?}", + crypto_args.method, + crypto_args.payload, + context.agent_id, + message + ); + + message +} + +pub async fn encrypt_workflow(context: Arc, payload: &WasmString) -> WorkflowResult { + crypto_workflow( + Arc::clone(&context), + &CryptoArgs { + payload: payload.to_string(), + method: CryptoMethod::Encrypt, + } + ).await.map(|encrypted_string| WasmString::from(encrypted_string)) +} + +pub async fn decrypt_workflow(context: Arc, payload: &WasmString) -> WorkflowResult { + crypto_workflow( + Arc::clone(&context), + &CryptoArgs { + payload: payload.to_string(), + method: CryptoMethod::Decrypt, + } + ).await.map(|decrypted_string| WasmString::from(decrypted_string)) +} + +#[cfg(test)] +mod test_super { + + // use holochain_core_types::error::ZomeApiInternalResult; + // use holochain_json_api::json::*; + // use std::convert::TryFrom; + // / test that bytes passed to debug end up in the log + // #[test] + // fn test_zome_api_crypto_functions() { + // let (call_result_json, _) = test_zome_api_function( + // ZomeApiFunction::Crypto.as_str(), + // r#"{ "payload": "this is data", "method" : "Encrypt" }"# + // .as_bytes() + // .to_vec(), + // ); + // + // let encrypt_result = ZomeApiInternalResult::try_from(call_result_json) + // .expect("Could not try from zomeapiitnernal"); + // assert!(encrypt_result.ok); + // + // let (call_result, _) = test_zome_api_function( + // ZomeApiFunction::Crypto.as_str(), + // format!( + // r#"{{ "payload": "{}", "method" : "Decrypt" }}"#, + // encrypt_result.value + // ) + // .as_bytes() + // .to_vec(), + // ); + // assert_eq!( + // JsonString::from_json(r#"{"ok":true,"value":"this is data","error":"null"}"#), + // call_result, + // ); + // } + + // #[test] + // fn test_zome_api_crypto_signing() { + // let payload = r#"{ "payload": "test ' payload", "method" : "Sign" }"#; + // let (call_result_json, _) = test_zome_api_function( + // ZomeApiFunction::Crypto.as_str(), + // payload.as_bytes().to_vec(), + // ); + // println!("Crypto::Sign( {:?} ) == {:?}", payload, call_result_json); + // assert_eq!( + // JsonString::from_json( + // r#"{"ok":true,"value":"ZDwPQ2TX9Xiq1k73JWczzqWr97rmdAodWWInlGfFjKiE0wFgMc2WvhmaFpNfrCv3y5uSOOLD5MgJqAeDsKb4Cw==","error":"null"}"# + // ), + // call_result_json + // ); + // + // let payload = r#"{ "payload": "test \" payload", "method" : "Sign" }"#; + // let (call_result_json, _) = test_zome_api_function( + // ZomeApiFunction::Crypto.as_str(), + // payload.as_bytes().to_vec(), + // ); + // println!("Crypto::Sign( {:?} ) == {:?}", payload, call_result_json); + // assert_eq!( + // JsonString::from_json( + // r#"{"ok":true,"value":"ODn3OE9jcZPfB403T7lFJbySVU4Ugu2Kv/kpkg50lD1cJ5E+gDs3zWwADJjQzkps+qp03k6C5ygegcGd2ERoCA==","error":"null"}"# + // ), + // call_result_json + // ); + // } +} diff --git a/crates/core/src/wasm_engine/api/debug.rs b/crates/core/src/workflows/debug.rs similarity index 74% rename from crates/core/src/wasm_engine/api/debug.rs rename to crates/core/src/workflows/debug.rs index 3a82c5e759..94cfeca59c 100644 --- a/crates/core/src/wasm_engine/api/debug.rs +++ b/crates/core/src/workflows/debug.rs @@ -1,20 +1,18 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, Runtime}, - NEW_RELIC_LICENSE_KEY, -}; -use wasmi::{RuntimeArgs, RuntimeValue}; +use holochain_wasm_types::wasm_string::WasmString; +// use std::sync::Arc; +use crate::context::Context; +use holochain_core_types::error::HolochainError; +// use crate::wasm_engine::runtime::WasmCallData; /// ZomeApiFunction::Debug function code /// args: [0] encoded MemoryAllocation as u64 /// Expecting a string as complex input argument /// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_debug(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - let payload = runtime.load_json_string_from_args(args); - log_debug!(context, "dna: '{}'", payload); - - ribosome_success!() +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn debug_workflow(context: std::sync::Arc, input: &WasmString) -> Result<(), HolochainError> { + println!("debug println: {}", input.to_string()); + log_debug!(context, "dna: '{}'", input.to_string()); + Ok(()) } #[cfg(test)] diff --git a/crates/core/src/workflows/emit_signal.rs b/crates/core/src/workflows/emit_signal.rs new file mode 100644 index 0000000000..1c121af1db --- /dev/null +++ b/crates/core/src/workflows/emit_signal.rs @@ -0,0 +1,90 @@ +use crate::{ + signal::{Signal, UserSignal}, + +}; +use holochain_core_types::error::HolochainError; +use holochain_wasm_types::emit_signal::EmitSignalArgs; +use crate::context::Context; +use std::sync::Arc; + +/// ZomeApiFunction::EmitSignal function code +/// args: [0] encoded MemoryAllocation as u64 +/// Expecting a string as complex input argument +/// Returns an HcApiReturnCode as I64 +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn emit_signal_workflow(context: Arc, input: &EmitSignalArgs) -> Result<(), HolochainError> { + if let Some(sender) = context.signal_tx() { + let signal = Signal::User(UserSignal::from(input.to_owned())); + let _ = sender.send(signal).map_err(|err| { + log_error!( + context, + "zome: invoke_emit_signal() could not send signal: {:?}", + err, + ); + }); + } else { + log_error!(context, "zome: invoke_emit_signal() could not send signal because signal channel is not set up!"); + } + + // We only log this case but still return Ok(()) since the semantic of sending a signal + // is all about decoupling sender and receiver - if nobody is listening, the sender + // should not care.. + Ok(()) +} + +#[cfg(test)] +pub mod tests { + use crate::{ + // instance::tests::test_instance_and_context, + signal::{UserSignal}, + }; + // use crossbeam_channel::unbounded; + use holochain_json_api::json::JsonString; + use holochain_wasm_types::emit_signal::EmitSignalArgs; + // use std::sync::Arc; + + pub fn test_signal() -> UserSignal { + UserSignal::from(test_args()) + } + + pub fn test_args() -> EmitSignalArgs { + EmitSignalArgs { + name: String::from("test-signal"), + arguments: JsonString::from_json("{message: \"Hello\"}"), + } + } + + pub fn test_args_bytes() -> Vec { + let args_string: JsonString = test_args().into(); + args_string.to_string().into_bytes() + } + + // /// test that bytes passed to debug end up in the log + // #[test] + // fn test_zome_api_function_emit_signal() { + // let wasm = test_zome_api_function_wasm(ZomeApiFunction::EmitSignal.as_str()); + // let dna = test_utils::create_test_dna_with_wasm(&test_zome_name(), wasm.clone()); + // + // let (_instance, context) = + // test_instance_and_context(dna, None).expect("Could not create test instance"); + // + // let (tx, rx) = unbounded::(); + // let mut context = (*context).clone(); + // context.signal_tx = Some(tx); + // let context = Arc::new(context); + // + // let args_string: JsonString = test_args().into(); + // println!("{}", args_string.to_string()); + // + // let _ = test_zome_api_function_call(context.clone(), test_args_bytes()); + // + // let received = rx.try_recv(); + // assert!(received.is_ok()); + // let signal = received.unwrap(); + // if let Signal::User(user_signal) = signal { + // assert_eq!(user_signal, test_signal()); + // } else { + // assert!(false, "Expected a Signal::User"); + // } + // } +} diff --git a/crates/core/src/workflows/entry_address.rs b/crates/core/src/workflows/entry_address.rs new file mode 100644 index 0000000000..6e528d1152 --- /dev/null +++ b/crates/core/src/workflows/entry_address.rs @@ -0,0 +1,50 @@ + +use holochain_core_types::{ + self, + dna::Dna, + entry::{entry_type::EntryType, Entry}, + error::HolochainError, +}; +use crate::context::Context; +use crate::workflows::WorkflowResult; +use holochain_persistence_api::cas::content::Address; +use holochain_persistence_api::cas::content::AddressableContent; +use holochain_wasmer_host::*; +use std::str::FromStr; +use std::sync::Arc; + +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub fn get_entry_type(dna: &Dna, entry_type_name: &str) -> Result { + let entry_type = EntryType::from_str(&entry_type_name.to_string()) + .map_err(|_| WasmError::UnknownEntryType)?; + + // Check if AppEntry is a valid AppEntryType + if entry_type.is_app() { + let result = dna.get_entry_type_def(entry_type_name); + if result.is_none() { + Err(WasmError::UnknownEntryType)?; + } + } + // Done + Ok(entry_type) +} + +/// ZomeApiFunction::entry_address function code +/// args: [0] encoded MemoryAllocation as u64 +/// Expected complex argument: entry_type_name and entry_value as JsonString +/// Returns an HcApiReturnCode as I64 +pub async fn entry_address_workflow(context: Arc, entry: &Entry) -> WorkflowResult
{ + // Check if entry_type is valid + let dna = context + .state() + .unwrap() + .nucleus() + .dna() + .expect("Should have DNA"); + + // bail if error + get_entry_type(&dna, &entry.entry_type().to_string())?; + + // Return result + Ok(entry.address()) +} diff --git a/crates/core/src/workflows/get_entry_result.rs b/crates/core/src/workflows/get_entry_result.rs index 8454bb713b..b1ce04c521 100644 --- a/crates/core/src/workflows/get_entry_result.rs +++ b/crates/core/src/workflows/get_entry_result.rs @@ -1,7 +1,7 @@ use crate::{ context::Context, network::{self, actions::query::QueryMethod, query::NetworkQueryResult}, - nucleus, NEW_RELIC_LICENSE_KEY, + nucleus, }; use holochain_core_types::{chain_header::ChainHeader, time::Timeout}; @@ -9,21 +9,22 @@ use holochain_core_types::{ crud_status::CrudStatus, entry::EntryWithMetaAndHeader, error::HolochainError, }; use holochain_persistence_api::cas::content::Address; -use holochain_wasm_utils::api_serialization::get_entry::{ +use holochain_wasm_types::get_entry::{ GetEntryArgs, GetEntryResult, StatusRequestKind, }; use std::sync::Arc; +use crate::workflows::WorkflowResult; /// Get Entry workflow -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub async fn get_entry_with_meta_workflow<'a>( - context: &'a Arc, - address: &'a Address, - timeout: &'a Timeout, -) -> Result, HolochainError> { +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn get_entry_with_meta_workflow( + context: Arc, + address: &Address, + timeout: &Timeout, +) -> WorkflowResult> { // 1. Try to get the entry locally (i.e. local DHT shard) let maybe_entry_with_meta = - nucleus::actions::get_entry::get_entry_with_meta(context, address.clone())?; + nucleus::actions::get_entry::get_entry_with_meta(Arc::clone(&context), address.clone())?; // 2. No result, so try on the network let method = QueryMethod::Entry(address.clone()); if let None = maybe_entry_with_meta { @@ -68,10 +69,10 @@ pub async fn get_entry_with_meta_workflow<'a>( } /// Get GetEntryResult workflow -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub async fn get_entry_result_workflow<'a>( - context: &'a Arc, - args: &'a GetEntryArgs, +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn get_entry_result_workflow( + context: Arc, + args: &GetEntryArgs, ) -> Result { // Setup let mut entry_result = GetEntryResult::new(args.options.status_request.clone(), None); @@ -83,7 +84,7 @@ pub async fn get_entry_result_workflow<'a>( maybe_address = None; // Try to get entry let maybe_entry_with_meta_and_headers = - get_entry_with_meta_workflow(context, &address, &args.options.timeout).await?; + get_entry_with_meta_workflow(Arc::clone(&context), &address, &args.options.timeout).await?; // Entry found if let Some(entry_with_meta_and_headers) = maybe_entry_with_meta_and_headers { @@ -137,7 +138,7 @@ pub async fn get_entry_result_workflow<'a>( // crud_status::{create_crud_status_eav, CrudStatus}, // entry::test_entry, // }; -// use holochain_wasm_utils::api_serialization::get_entry::*; +// use holochain_wasm_types::get_entry::*; // // #[test] // fn can_get_entry_result_workflow() { diff --git a/crates/core/src/workflows/get_link_result.rs b/crates/core/src/workflows/get_link_result.rs index 2717393c01..8f31edf17b 100644 --- a/crates/core/src/workflows/get_link_result.rs +++ b/crates/core/src/workflows/get_link_result.rs @@ -7,19 +7,18 @@ use crate::{ NetworkQueryResult, }, }, - NEW_RELIC_LICENSE_KEY, -}; +}; use holochain_core_types::error::HolochainError; -use holochain_wasm_utils::api_serialization::get_links::{ +use holochain_wasm_types::get_links::{ GetLinksArgs, GetLinksResult, LinksResult, }; use std::sync::Arc; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub async fn get_link_result_workflow<'a>( - context: &'a Arc, - link_args: &'a GetLinksArgs, +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn get_link_result_workflow( + context: Arc, + link_args: &GetLinksArgs, ) -> Result { let config = GetLinksQueryConfiguration { headers: link_args.options.headers, diff --git a/crates/core/src/workflows/get_links_count.rs b/crates/core/src/workflows/get_links_count.rs index 9e2a034050..4c6da9caeb 100644 --- a/crates/core/src/workflows/get_links_count.rs +++ b/crates/core/src/workflows/get_links_count.rs @@ -4,17 +4,16 @@ use crate::{ actions::query::{query, QueryMethod}, query::{GetLinksNetworkQuery, GetLinksNetworkResult, NetworkQueryResult}, }, - NEW_RELIC_LICENSE_KEY, -}; +}; use holochain_core_types::error::HolochainError; -use holochain_wasm_utils::api_serialization::get_links::{GetLinksArgs, GetLinksResultCount}; +use holochain_wasm_types::get_links::{GetLinksArgs, GetLinksResultCount}; use std::sync::Arc; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub async fn get_link_result_count_workflow<'a>( +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn get_link_result_count_workflow( context: Arc, - link_args: &'a GetLinksArgs, + link_args: &GetLinksArgs, ) -> Result { let method = QueryMethod::Link(link_args.clone(), GetLinksNetworkQuery::Count); let response = query(context.clone(), method, link_args.options.timeout.clone()).await?; diff --git a/crates/core/src/workflows/handle_custom_direct_message.rs b/crates/core/src/workflows/handle_custom_direct_message.rs index 6583759e87..5daea4430a 100644 --- a/crates/core/src/workflows/handle_custom_direct_message.rs +++ b/crates/core/src/workflows/handle_custom_direct_message.rs @@ -3,19 +3,20 @@ use crate::{ context::Context, instance::dispatch_action, network::direct_message::{CustomDirectMessage, DirectMessage}, - wasm_engine::callback::{receive::receive, CallbackParams, CallbackResult}, - NEW_RELIC_LICENSE_KEY, + workflows::callback::receive::receive, + wasm_engine::callback::{CallbackParams}, }; use holochain_core_types::error::HolochainError; +use holochain_core_types::callback::CallbackResult; use holochain_persistence_api::cas::content::Address; -use holochain_wasm_utils::api_serialization::receive::ReceiveParams; +use holochain_wasm_types::receive::ReceiveParams; use std::sync::Arc; /// handles receiving a message from an api send call /// call the receive call back, and sends the result back to the /// source of the send message which is in the from_agent_id param -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn handle_custom_direct_message( from_agent_id: Address, msg_id: String, diff --git a/crates/core/src/workflows/hold_entry.rs b/crates/core/src/workflows/hold_entry.rs index dc879f9eb9..35cf642478 100644 --- a/crates/core/src/workflows/hold_entry.rs +++ b/crates/core/src/workflows/hold_entry.rs @@ -1,27 +1,27 @@ use crate::{ context::Context, dht::actions::hold_aspect::hold_aspect, network::entry_with_header::EntryWithHeader, nucleus::validation::validate_entry, - NEW_RELIC_LICENSE_KEY, + }; -use crate::{nucleus::validation::ValidationError, workflows::validation_package}; +use crate::{workflows::validation_package}; use holochain_core_types::{ error::HolochainError, network::entry_aspect::EntryAspect, - validation::{EntryLifecycle, ValidationData}, + validation::{EntryLifecycle, ValidationData, ValidationResult}, }; use holochain_persistence_api::cas::content::AddressableContent; use std::sync::Arc; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn hold_entry_workflow( - entry_with_header: &EntryWithHeader, context: Arc, + entry_with_header: &EntryWithHeader, ) -> Result<(), HolochainError> { // 1. Get hold of validation package - let maybe_validation_package = validation_package(&entry_with_header, context.clone()) + let maybe_validation_package = validation_package(Arc::clone(&context), entry_with_header) .await .map_err(|err| { let message = "Could not get validation package from source! -> Add to pending..."; @@ -44,27 +44,40 @@ pub async fn hold_entry_workflow( }; // 3. Validate the entry - validate_entry( + match validate_entry( + Arc::clone(&context), entry_with_header.entry.clone(), None, validation_data, - &context - ).await - .map_err(|err| { - if let ValidationError::UnresolvedDependencies(dependencies) = &err { + ).await { + ValidationResult::Ok => (), + ValidationResult::UnresolvedDependencies(dependencies) => { log_debug!(context, "workflow/hold_entry: {} could not be validated due to unresolved dependencies and will be tried later. List of missing dependencies: {:?}", entry_with_header.entry.address(), dependencies, ); - HolochainError::ValidationPending - } else { + return Err(HolochainError::ValidationPending); + }, + ValidationResult::Fail(s) => { log_warn!(context, "workflow/hold_entry: Entry {} is NOT valid! Validation error: {:?}", entry_with_header.entry.address(), - err, + s, ); - HolochainError::from(err) - } - })?; + return Err(HolochainError::from(s)); + }, + ValidationResult::NotImplemented => { + log_warn!(context, "workflow/hold_entry: Entry {} could not be validated due to missing validation!", + entry_with_header.entry.address(), + ); + return Err(HolochainError::ValidationFailed(ValidationResult::NotImplemented)); + }, + ValidationResult::Timeout => { + log_debug!(context, "workflow/hold_entry: {} timed out", + entry_with_header.entry.address(), + ); + return Err(HolochainError::Timeout); + }, + }; log_debug!( context, diff --git a/crates/core/src/workflows/hold_entry_remove.rs b/crates/core/src/workflows/hold_entry_remove.rs index 78987dd3aa..ce3137f3dc 100644 --- a/crates/core/src/workflows/hold_entry_remove.rs +++ b/crates/core/src/workflows/hold_entry_remove.rs @@ -1,24 +1,24 @@ use crate::{ context::Context, dht::actions::hold_aspect::hold_aspect, network::entry_with_header::EntryWithHeader, nucleus::validation::validate_entry, - NEW_RELIC_LICENSE_KEY, + }; -use crate::{nucleus::validation::ValidationError, workflows::validation_package}; +use crate::{workflows::validation_package}; use holochain_core_types::{ error::HolochainError, network::entry_aspect::EntryAspect, - validation::{EntryLifecycle, ValidationData}, + validation::{EntryLifecycle, ValidationData, ValidationResult}, }; use std::sync::Arc; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn hold_remove_workflow( - entry_with_header: &EntryWithHeader, context: Arc, + entry_with_header: &EntryWithHeader, ) -> Result<(), HolochainError> { // 1. Get hold of validation package - let maybe_validation_package = validation_package(entry_with_header, context.clone()) + let maybe_validation_package = validation_package(Arc::clone(&context), entry_with_header) .await .map_err(|err| { let message = "Could not get validation package from source! -> Add to pending..."; @@ -36,25 +36,26 @@ pub async fn hold_remove_workflow( }; // 3. Validate the entry - validate_entry( + match validate_entry( + Arc::clone(&context), entry_with_header.entry.clone(), None, validation_data, - &context - ).await - .map_err(|err| { - if let ValidationError::UnresolvedDependencies(dependencies) = &err { + ).await { + ValidationResult::Ok => (), + ValidationResult::UnresolvedDependencies(dependencies) => { log_debug!(context, "workflow/hold_remove: Entry removal could not be validated due to unresolved dependencies and will be tried later. List of missing dependencies: {:?}", dependencies); - HolochainError::ValidationPending - } else { + return Err(HolochainError::ValidationPending); + }, + ValidationResult::Fail(e) => { log_warn!(context, "workflow/hold_remove: Entry removal {:?} is NOT valid! Validation error: {:?}", entry_with_header.entry, - err, + e, ); - HolochainError::from(err) + return Err(HolochainError::from(e)); } - - })?; + v => return Err(HolochainError::ValidationFailed(v)), + }; // 4. If valid store the entry aspect in the local DHT shard let aspect = EntryAspect::Deletion(entry_with_header.header.clone()); diff --git a/crates/core/src/workflows/hold_entry_update.rs b/crates/core/src/workflows/hold_entry_update.rs index 9a58d3124e..82cb2b8bc3 100644 --- a/crates/core/src/workflows/hold_entry_update.rs +++ b/crates/core/src/workflows/hold_entry_update.rs @@ -2,26 +2,27 @@ use crate::{ context::Context, dht::actions::hold_aspect::hold_aspect, network::entry_with_header::EntryWithHeader, - nucleus::validation::{validate_entry, ValidationError}, + nucleus::validation::{validate_entry}, workflows::validation_package, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::{ error::HolochainError, network::entry_aspect::EntryAspect, - validation::{EntryLifecycle, ValidationData}, + validation::{EntryLifecycle, ValidationData, ValidationResult}, }; use std::sync::Arc; +use crate::workflows::WorkflowResult; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn hold_update_workflow( - entry_with_header: &EntryWithHeader, context: Arc, -) -> Result<(), HolochainError> { + entry_with_header: &EntryWithHeader, +) -> WorkflowResult<()> { let EntryWithHeader { entry, header } = entry_with_header; // 1. Get hold of validation package - let maybe_validation_package = validation_package(&entry_with_header, context.clone()) + let maybe_validation_package = validation_package(Arc::clone(&context), &entry_with_header) .await .map_err(|err| { let message = "Could not get validation package from source! -> Add to pending..."; @@ -44,25 +45,26 @@ pub async fn hold_update_workflow( }; // 3. Validate the entry - validate_entry( + match validate_entry( + Arc::clone(&context), entry.clone(), Some(link.clone()), validation_data, - &context - ).await - .map_err(|err| { - if let ValidationError::UnresolvedDependencies(dependencies) = &err { + ).await { + ValidationResult::Ok => (), + ValidationResult::UnresolvedDependencies(dependencies) => { log_debug!(context, "workflow/hold_update: Entry update could not be validated due to unresolved dependencies and will be tried later. List of missing dependencies: {:?}", dependencies); - HolochainError::ValidationPending - } else { + return Err(HolochainError::ValidationPending); + }, + ValidationResult::Fail(e) => { log_warn!(context, "workflow/hold_update: Entry update {:?} is NOT valid! Validation error: {:?}", entry_with_header.entry, - err, + e, ); - HolochainError::from(err) - } - - })?; + return Err(HolochainError::from(e)); + }, + v => return Err(HolochainError::ValidationFailed(v)), + }; // 4. If valid store the entry aspect in the local DHT shard let aspect = EntryAspect::Update( diff --git a/crates/core/src/workflows/hold_link.rs b/crates/core/src/workflows/hold_link.rs index b80faffaa9..9aca4dfed3 100644 --- a/crates/core/src/workflows/hold_link.rs +++ b/crates/core/src/workflows/hold_link.rs @@ -1,25 +1,24 @@ use crate::{ context::Context, dht::actions::hold_aspect::hold_aspect, network::entry_with_header::EntryWithHeader, nucleus::validation::validate_entry, - NEW_RELIC_LICENSE_KEY, + }; use crate::{ - nucleus::validation::ValidationError, workflows::{hold_entry::hold_entry_workflow, validation_package}, }; use holochain_core_types::{ entry::Entry, error::HolochainError, network::entry_aspect::EntryAspect, - validation::{EntryLifecycle, ValidationData}, + validation::{EntryLifecycle, ValidationData, ValidationResult}, }; use std::sync::Arc; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn hold_link_workflow( - entry_with_header: &EntryWithHeader, context: Arc, + entry_with_header: &EntryWithHeader, ) -> Result<(), HolochainError> { let link_add = match &entry_with_header.entry { Entry::LinkAdd(link_add) => link_add, @@ -32,7 +31,7 @@ pub async fn hold_link_workflow( log_debug!(context, "workflow/hold_link: {:?}", link); log_debug!(context, "workflow/hold_link: getting validation package..."); // 1. Get hold of validation package - let maybe_validation_package = validation_package(&entry_with_header, context.clone()) + let maybe_validation_package = validation_package(Arc::clone(&context), &entry_with_header) .await .map_err(|err| { let message = "Could not get validation package from source! -> Add to pending..."; @@ -55,25 +54,27 @@ pub async fn hold_link_workflow( // 3. Validate the entry log_debug!(context, "workflow/hold_link: validate..."); - validate_entry( + match validate_entry( + Arc::clone(&context), entry_with_header.entry.clone(), None, validation_data, - &context - ).await - .map_err(|err| { - if let ValidationError::UnresolvedDependencies(dependencies) = &err { + ).await { + ValidationResult::Ok => (), + ValidationResult::UnresolvedDependencies(dependencies) => { log_debug!(context, "workflow/hold_link: Link could not be validated due to unresolved dependencies and will be tried later. List of missing dependencies: {:?}", dependencies); - HolochainError::ValidationPending - } else { + return Err(HolochainError::ValidationPending); + }, + ValidationResult::Fail(e) => { log_warn!(context, "workflow/hold_link: Link {:?} is NOT valid! Validation error: {:?}", entry_with_header.entry, - err, + e, ); - HolochainError::from(err) - } + return Err(HolochainError::from(e)); + }, + v => return Err(HolochainError::ValidationFailed(v)), + }; - })?; log_debug!(context, "workflow/hold_link: is valid!"); // 3. If valid store the entry aspect in the local DHT shard @@ -83,7 +84,7 @@ pub async fn hold_link_workflow( log_debug!(context, "workflow/hold_link: added! {:?}", link); //4. store link_add entry so we have all we need to respond to get links queries without any other network look-up - hold_entry_workflow(&entry_with_header, context.clone()).await?; + hold_entry_workflow(Arc::clone(&context), &entry_with_header).await?; log_debug!( context, "workflow/hold_entry: added! {:?}", diff --git a/crates/core/src/workflows/init_globals.rs b/crates/core/src/workflows/init_globals.rs new file mode 100644 index 0000000000..955d8c8a9e --- /dev/null +++ b/crates/core/src/workflows/init_globals.rs @@ -0,0 +1,129 @@ +use holochain_core_types::entry::entry_type::EntryType; +use holochain_persistence_api::{ + cas::content::{Address}, + hash::HashString, +}; +use holochain_json_api::json::JsonString; +use crate::holochain_wasm_types::holochain_persistence_api::cas::content::AddressableContent; +use holochain_wasm_types::ZomeApiGlobals; +use holochain_core_types::error::HolochainError; +use std::sync::Arc; +use crate::context::Context; +use crate::wasm_engine::runtime::WasmCallData; + +/// ZomeApiFunction::InitGlobals secret function code +/// args: [0] encoded MemoryAllocation as u64 +/// Not expecting any complex input +/// Returns an HcApiReturnCode as I64 +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn init_globals_workflow(context: Arc, call_data: &Arc) -> Result { + let dna = context + .get_dna() + .expect("No DNA found in invoke_init_globals"); + let dna_name = dna.name.clone(); + // Create the ZomeApiGlobals struct with some default values + let mut globals = ZomeApiGlobals { + dna_name, + dna_address: Address::from(""), + agent_id_str: JsonString::from(context.agent_id.clone()).to_string(), + agent_address: context.agent_id.address(), + agent_initial_hash: HashString::from(""), + agent_latest_hash: HashString::from(""), + public_token: Address::from(""), + cap_request: call_data + .zome_call_data() + .map(|zome_call_data| Some(zome_call_data.call.cap)) + .unwrap_or_else(|_| None), + properties: JsonString::from(dna.properties), + }; + + // Update fields + if let Some(state) = context.state() { + // Update dna_address + if let Some(dna) = state.nucleus().dna() { + globals.dna_address = dna.address() + } + // Update agent hashes + let maybe_top = state.agent().top_chain_header(); + if maybe_top.is_some() { + let mut found_entries: Vec
= vec![]; + for chain_header in state + .agent() + .chain_store() + .iter_type(&maybe_top, &EntryType::AgentId) + { + found_entries.push(chain_header.entry_address().to_owned()); + } + if !found_entries.is_empty() { + globals.agent_latest_hash = found_entries[0].clone(); + globals.agent_initial_hash = found_entries.pop().unwrap(); + globals.agent_address = globals.agent_latest_hash.clone(); + } + } + }; + + // Update public_token + let maybe_token = context.get_public_token(); + if let Ok(token) = maybe_token { + globals.public_token = token; + } + + Ok(globals) +} + +// #[cfg(test)] +// pub mod tests { +// use crate::wasm_engine::{ +// api::{tests::test_zome_api_function, ZomeApiFunction}, +// Defn, +// }; +// use holochain_core_types::{ +// dna::capabilities::CapabilityRequest, error::ZomeApiInternalResult, signature::Signature, +// }; +// use holochain_json_api::json::JsonString; +// use holochain_persistence_api::cas::content::Address; +// use holochain_wasm_types::ZomeApiGlobals; +// use std::convert::TryFrom; +// use test_utils::mock_signing::registered_test_agent; +// +// #[test] +// /// test that the correct globals values are created for zome calls +// fn test_init_globals() { +// let input: Vec = vec![]; +// let (call_result, _) = test_zome_api_function(ZomeApiFunction::InitGlobals.as_str(), input); +// +// let zome_api_internal_result = ZomeApiInternalResult::try_from(call_result).unwrap(); +// let globals = +// ZomeApiGlobals::try_from(JsonString::from_json(&zome_api_internal_result.value)) +// .unwrap(); +// +// assert_eq!(globals.dna_name, "TestApp"); +// let expected_agent = registered_test_agent("jane"); +// assert_eq!( +// globals.agent_address.to_string(), +// expected_agent.pub_sign_key +// ); +// // TODO (david.b) this should work: +// //assert_eq!(globals.agent_id_str, String::from(AgentId::generate_fake("jane"))); +// // assert_eq!( +// // globals.agent_initial_hash, +// // AgentId::generate_fake("jane").address() +// // ); +// assert_eq!(globals.agent_initial_hash, globals.agent_latest_hash); +// +// // this hash should stay the same as long as the public functions in the test zome +// // don't change. +// assert_eq!( +// globals.public_token, +// Address::from("QmdZiJWdVCh8s38tCcAAq8f7HpHkd9KLFnHh9vLTddt8D2"), +// ); +// +// assert_eq!( +// globals.cap_request, +// Some(CapabilityRequest::new( Address::from("dummy_token"), +// Address::from("HcSCimiBHJ8y3zejkjtHsu9Q8MZx96ztvfYRJ9fJH3Pbxodac5s8rqmShYqaamz"), +// Signature::from("nI/AFdqZPYw1yoCeV92pKWwugdkB54JJDhLLf3JgMFl9sm3aFIWKpiRo+4t8L+wn+S0Pg1Vh0Bzbmq3DSfJwDw=="), +// )), +// ); +// } +// } diff --git a/crates/core/src/wasm_engine/api/keystore.rs b/crates/core/src/workflows/keystore.rs similarity index 62% rename from crates/core/src/wasm_engine/api/keystore.rs rename to crates/core/src/workflows/keystore.rs index a6026c1898..deefa16051 100644 --- a/crates/core/src/wasm_engine/api/keystore.rs +++ b/crates/core/src/workflows/keystore.rs @@ -1,20 +1,19 @@ -use crate::{ - context::Context, - wasm_engine::{api::ZomeApiResult, Runtime}, - NEW_RELIC_LICENSE_KEY, -}; +use crate::{context::Context}; use holochain_core_types::error::{HcResult, HolochainError}; - +use holochain_core_types::signature::Signature; use holochain_json_api::json::JsonString; -use holochain_wasm_utils::api_serialization::keystore::KeystoreListResult; +use holochain_wasm_types::{ + keystore::KeystoreListResult, wasm_string::WasmString, +}; +use holochain_wasmer_host::*; use jsonrpc_lite::JsonRpc; use serde_json::{self, Value}; use snowflake::ProcessUniqueId; use std::sync::Arc; -use wasmi::{RuntimeArgs, RuntimeValue}; +use crate::workflows::WorkflowResult; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] fn conductor_callback>( method: S, params: S, @@ -51,10 +50,9 @@ fn conductor_callback>( } } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_keystore_list(runtime: &mut Runtime, _args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - let result = conductor_callback("agent/keystore/list", "{}", context.clone()); +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn keystore_list_workflow(context: Arc, _: &()) -> WorkflowResult { + let result = conductor_callback("agent/keystore/list", "{}", Arc::clone(&context)); let string_list: Vec = match result { Ok(json_array) => serde_json::from_str(&json_array.to_string()).unwrap(), Err(err) => { @@ -63,24 +61,19 @@ pub fn invoke_keystore_list(runtime: &mut Runtime, _args: &RuntimeArgs) -> ZomeA "zome: agent/keystore/list callback failed: {:?}", err ); - return ribosome_error_code!(CallbackFailed); + return Err(WasmError::CallbackFailed)?; } }; - runtime.store_result(Ok(KeystoreListResult { ids: string_list })) + Ok(KeystoreListResult { ids: string_list }) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_keystore_new_random(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn keystore_new_random_workflow(context: Arc, args_str: &WasmString) -> WorkflowResult<()> { let result = conductor_callback( "agent/keystore/add_random_seed", &args_str.to_string(), - context.clone(), + Arc::clone(&context), ); match result { Ok(_) => (), @@ -90,22 +83,18 @@ pub fn invoke_keystore_new_random(runtime: &mut Runtime, args: &RuntimeArgs) -> "zome: agent/keystore/add_random_seed callback failed: {:?}", err ); - return ribosome_error_code!(CallbackFailed); + return Err(WasmError::CallbackFailed)?; } }; - runtime.store_result(Ok(())) + Ok(()) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_keystore_derive_seed(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn keystore_derive_seed_workflow(context: Arc, args_str: &WasmString) -> WorkflowResult<()> { let result = conductor_callback( "agent/keystore/add_seed_from_seed", &args_str.to_string(), - context.clone(), + Arc::clone(&context), ); match result { Ok(_) => (), @@ -115,23 +104,19 @@ pub fn invoke_keystore_derive_seed(runtime: &mut Runtime, args: &RuntimeArgs) -> "zome: agent/keystore/add_seed_from_seed callback failed: {:?}", err ); - return ribosome_error_code!(CallbackFailed); + return Err(WasmError::CallbackFailed)?; } }; - runtime.store_result(Ok(())) + Ok(()) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_keystore_derive_key(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn keystore_derive_key_workflow(context: Arc, args_str: &WasmString) -> WorkflowResult { let result = conductor_callback( "agent/keystore/add_key_from_seed", &args_str.to_string(), - context.clone(), + Arc::clone(&context), ); let string: String = match result { Ok(json_string) => { @@ -149,7 +134,7 @@ pub fn invoke_keystore_derive_key(runtime: &mut Runtime, args: &RuntimeArgs) -> "zome: agent/keystore/add_key_from_seed callback failed: {:?}", err ); - return ribosome_error_code!(CallbackFailed); + return Err(WasmError::CallbackFailed)?; } }; @@ -159,20 +144,12 @@ pub fn invoke_keystore_derive_key(runtime: &mut Runtime, args: &RuntimeArgs) -> args_str, string ); - runtime.store_result(Ok(JsonString::from_json(&string))) + Ok(Signature::from(string)) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_keystore_sign(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - - let result = conductor_callback( - "agent/keystore/sign", - &args_str.to_string(), - context.clone(), - ); +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn keystore_sign_workflow(context: Arc, args_str: &WasmString) -> WorkflowResult { + let result = conductor_callback("agent/keystore/sign", &args_str.to_string(), Arc::clone(&context)); let string: String = match result { Ok(json_string) => { log_debug!(context, "zome: keystore_sign json_string:{:?}", json_string); @@ -186,7 +163,7 @@ pub fn invoke_keystore_sign(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeAp "zome: agent/keystore/sign callback failed: {:?}", err ); - return ribosome_error_code!(CallbackFailed); + return Err(WasmError::CallbackFailed)?; } }; @@ -197,19 +174,18 @@ pub fn invoke_keystore_sign(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeAp string ); - runtime.store_result(Ok(JsonString::from_json(&string))) + Ok(Signature::from(string)) } -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_keystore_get_public_key(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn keystore_get_public_key_workflow( + context: Arc, + args_str: &WasmString, +) -> WorkflowResult { let result = conductor_callback( "agent/keystore/get_public_key", &args_str.to_string(), - context.clone(), + Arc::clone(&context), ); let string: String = match result { Ok(json_string) => { @@ -227,7 +203,7 @@ pub fn invoke_keystore_get_public_key(runtime: &mut Runtime, args: &RuntimeArgs) "zome: agent/keystore/get_public_key callback failed: {:?}", err ); - return ribosome_error_code!(CallbackFailed); + return Err(WasmError::CallbackFailed)?; } }; @@ -237,5 +213,5 @@ pub fn invoke_keystore_get_public_key(runtime: &mut Runtime, args: &RuntimeArgs) args_str, string ); - runtime.store_result(Ok(JsonString::from_json(&string))) + Ok(Signature::from(string)) } diff --git a/crates/core/src/workflows/link_entries.rs b/crates/core/src/workflows/link_entries.rs new file mode 100644 index 0000000000..08e7354475 --- /dev/null +++ b/crates/core/src/workflows/link_entries.rs @@ -0,0 +1,221 @@ +use crate::{workflows::author_entry::author_entry}; +use holochain_core_types::{ + entry::Entry, + link::{link_data::LinkData, LinkActionKind}, +}; +use holochain_persistence_api::cas::content::{Address, AddressableContent}; +use holochain_wasm_types::link_entries::LinkEntriesArgs; +use holochain_wasmer_host::*; +use crate::workflows::WorkflowResult; +use crate::context::Context; +use std::sync::Arc; + +/// ZomeApiFunction::LinkEntries function code +/// args: [0] encoded MemoryAllocation as u64 +/// Expected complex argument: LinkEntriesArgs +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn link_entries_workflow( + context: Arc, + input: &LinkEntriesArgs, +) -> WorkflowResult
{ + let top_chain_header_option = context + .state() + .expect("Couldn't get state in invoke_linke_entries") + .agent() + .top_chain_header(); + + let top_chain_header = match top_chain_header_option { + Some(top_chain) => top_chain, + None => { + log_error!( + context, + "zome: invoke_link_entries failed to deserialize LinkEntriesArgs: {:?}", + input + ); + return Err(WasmError::ArgumentDeserializationFailed)?; + } + }; + + let link = input.to_link(); + let link_add = LinkData::from_link( + &link, + LinkActionKind::ADD, + top_chain_header, + context.agent_id.clone(), + ); + let entry = Entry::LinkAdd(link_add); + + // Wait for future to be resolved + // This is where the link entry actually gets created. + author_entry(Arc::clone(&context), &entry, None, &vec![]).await + .map(|_| entry.address()) +} + +#[cfg(test)] +pub mod tests { + use holochain_core_types::{ + entry::{test_entry, Entry}, + }; + use holochain_json_api::json::JsonString; + use holochain_persistence_api::cas::content::AddressableContent; + use holochain_wasm_types::link_entries::*; + // use crate::wasm_engine::tests::test_zome_name; + use serde_json; + // use std::{sync::Arc}; + + pub fn test_entry_b() -> Entry { + Entry::App("testEntryTypeB".into(), "test".into()) + } + + /// dummy link_entries args from standard test entry + pub fn test_link_args_bytes(link_type: String, tag: String) -> Vec { + let entry = test_entry(); + + let args = LinkEntriesArgs { + base: entry.address(), + target: entry.address(), + link_type, + tag, + }; + serde_json::to_string(&args) + .expect("args should serialize") + .into_bytes() + } + + pub fn test_link_2_args_bytes(link_type: String, tag: String) -> Vec { + let base = test_entry(); + let target = test_entry_b(); + + let args = LinkEntriesArgs { + base: base.address(), + target: target.address(), + link_type, + tag, + }; + serde_json::to_string(&args) + .expect("args should serialize") + .into_bytes() + } + + /// dummy commit args from standard test entry + pub fn test_commit_args_bytes() -> Vec { + JsonString::from(test_entry()).to_bytes() + } + + // fn create_test_instance_with_name(netname: Option<&str>) -> (Instance, Arc) { + // let wasm = test_zome_api_function_wasm(ZomeApiFunction::LinkEntries.as_str()); + // let dna = test_utils::create_test_dna_with_wasm(&test_zome_name(), wasm.clone()); + // + // test_instance_and_context(dna, netname).expect("Could not create test instance") + // } + // fn create_test_instance() -> (Instance, Arc) { + // let wasm = test_zome_api_function_wasm(ZomeApiFunction::LinkEntries.as_str()); + // let dna = test_utils::create_test_dna_with_wasm(&test_zome_name(), wasm.clone()); + // + // let netname = format!("create_test_instance-{}", snowflake::ProcessUniqueId::new()); + // + // test_instance_and_context(dna, Some(netname.as_str())) + // .expect(format!("Could not create test instance for netname: {}", netname).as_str()) + // } + + // #[test] + // /// test that we can round trip bytes through a commit action and get the result from WASM + // #[cfg(not(windows))] + // fn errors_if_base_is_not_present_test() { + // // let (call_result, _) = test_zome_api_function( + // // ZomeApiFunction::LinkEntries.as_str(), + // // test_link_args_bytes(String::from("test-link")), + // // ); + // // + // // let result = ZomeApiInternalResult::try_from(call_result) + // // .expect("valid ZomeApiInternalResult JsonString"); + // // + // // let core_err = CoreError::try_from(result).expect("valid CoreError JsonString"); + // // assert_eq!("Base for link not found", core_err.kind.to_string(),); + // } + + // #[test] + // fn returns_ok_if_base_is_present() { + // let (_instance, context) = + // create_test_instance_with_name(Some("returns_ok_if_base_present")); + // + // context + // .block_on(commit_entry(test_entry(), None, &context)) + // .expect("Could not commit entry for testing"); + // + // let call_result_json = test_zome_api_function_call( + // context.clone(), + // test_link_args_bytes("test-link".into(), "test-tag".into()), + // ); + // + // let call_result = ZomeApiInternalResult::try_from(call_result_json); + // + // assert!(call_result.is_ok()) + // } + + // #[test] + // fn errors_with_wrong_type() { + // let (_instance, context) = create_test_instance(); + // + // context + // .block_on(commit_entry(test_entry(), None, &context)) + // .expect("Could not commit entry for testing"); + // + // let call_result = test_zome_api_function_call( + // context.clone(), + // test_link_args_bytes("wrong-link".into(), "test-tag".into()), + // ); + // + // let result = ZomeApiInternalResult::try_from(call_result) + // .expect("valid ZomeApiInternalResult JsonString"); + // + // let core_err = CoreError::try_from(result).expect("valid CoreError JsonString"); + // assert_eq!("Unknown entry type", core_err.kind.to_string(),); + // } + + // #[test] + // fn works_with_linked_from_defined_link() { + // let (_instance, context) = create_test_instance(); + // + // context + // .block_on(commit_entry(test_entry(), None, &context)) + // .expect("Could not commit entry for testing"); + // + // context + // .block_on(commit_entry(test_entry_b(), None, &context)) + // .expect("Could not commit entry for testing"); + // + // let call_result_json = test_zome_api_function_call( + // context.clone(), + // test_link_2_args_bytes("test-link".into(), "test-tag".into()), + // ); + // + // let call_result = ZomeApiInternalResult::try_from(call_result_json); + // + // assert!(call_result.is_ok()) + // } + + // #[test] + // fn test_different_tags_produces_different_hashes() { + // let (_instance, context) = create_test_instance(); + // + // context + // .block_on(commit_entry(test_entry(), None, &context)) + // .expect("Could not commit entry for testing"); + // + // let call_result1 = test_zome_api_function_call( + // context.clone(), + // test_link_args_bytes("test-link".into(), "test-tag1".into()), + // ); + // + // let call_result2 = test_zome_api_function_call( + // context.clone(), + // test_link_args_bytes("test-link".into(), "test-tag2".into()), + // ); + // + // let result1: JsonString = ZomeApiInternalResult::success(call_result1).into(); + // let result2: JsonString = ZomeApiInternalResult::success(call_result2).into(); + // + // assert_ne!(result1, result2); + // } +} diff --git a/crates/core/src/workflows/meta.rs b/crates/core/src/workflows/meta.rs new file mode 100644 index 0000000000..27509a70db --- /dev/null +++ b/crates/core/src/workflows/meta.rs @@ -0,0 +1,41 @@ +use holochain_core_types::{hdk_version::HDK_VERSION, HDK_HASH}; +use holochain_wasm_types::meta::{MetaArgs, MetaMethod, MetaResult}; +use std::sync::Arc; +use crate::context::Context; +use holochain_core_types::error::HolochainError; + +/// ZomeApiFunction::Meta function code +/// args: [0] encoded MemoryAllocation as u64 +/// Expecting a string as complex input argument +/// Returns an HcApiReturnCode as I64 +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn meta_workflow(_: Arc, meta_args: &MetaArgs) -> Result { + Ok(match meta_args.method { + MetaMethod::Version => MetaResult::Version(HDK_VERSION.to_string()), + MetaMethod::Hash => MetaResult::Hash(HDK_HASH.to_string()), + }) +} + +// #[cfg(test)] +// #[cfg(not(windows))] +// mod test_super { +// use crate::wasm_engine::{ +// api::{tests::test_zome_api_function, ZomeApiFunction}, +// Defn, +// }; +// use holochain_core_types::hdk_version::HDK_VERSION; +// use holochain_json_api::json::*; +// /// test that bytes passed to debug end up in the log +// #[test] +// fn test_zome_api_meta_functions() { +// let (call_result, _) = test_zome_api_function( +// ZomeApiFunction::Meta.as_str(), +// format!(r#"{{ "method" : "Version" }}"#).as_bytes().to_vec(), +// ); +// let call_result_json = format!( +// r#"{{"ok":true,"value":"{{\"Version\":\"{}\"}}","error":"null"}}"#, +// HDK_VERSION.to_string() +// ); +// assert_eq!(JsonString::from_json(&*call_result_json), call_result,); +// } +// } diff --git a/crates/core/src/workflows/mod.rs b/crates/core/src/workflows/mod.rs index 85f5a7df25..fc615c3660 100644 --- a/crates/core/src/workflows/mod.rs +++ b/crates/core/src/workflows/mod.rs @@ -22,6 +22,46 @@ pub mod hold_link; pub mod remove_link; #[autotrace] pub mod respond_validation_package_request; +#[autotrace] +pub mod callback; +#[autotrace] +pub mod debug; +#[autotrace] +pub mod commit; +#[autotrace] +pub mod remove_entry; +#[autotrace] +pub mod update_entry; +#[autotrace] +pub mod call; +#[autotrace] +pub mod meta; +#[autotrace] +pub mod sleep; +#[autotrace] +pub mod init_globals; +#[autotrace] +pub mod query; +#[autotrace] +pub mod entry_address; +#[autotrace] +pub mod send; +#[autotrace] +pub mod remove_link_wasm; +#[autotrace] +pub mod emit_signal; +#[autotrace] +pub mod capabilities; +#[autotrace] +pub mod keystore; +#[autotrace] +pub mod sign; +#[autotrace] +pub mod verify_signature; +#[autotrace] +pub mod crypto; +#[autotrace] +pub mod link_entries; use crate::{ context::Context, @@ -33,22 +73,24 @@ use crate::{ actions::build_validation_package::build_validation_package, validation::build_from_dht::try_make_validation_package_dht, }, - wasm_engine::callback::{ - validation_package::get_validation_package_definition, CallbackResult, - }, workflows::{ + callback::validation_package::get_validation_package_definition, hold_entry::hold_entry_workflow, hold_entry_remove::hold_remove_workflow, hold_entry_update::hold_update_workflow, hold_link::hold_link_workflow, remove_link::remove_link_workflow, }, }; use holochain_core_types::{ + callback::CallbackResult, error::HolochainError, validation::{ValidationPackage, ValidationPackageDefinition}, }; use holochain_persistence_api::cas::content::AddressableContent; use std::sync::Arc; +pub(crate) type WorkflowResult = Result; +pub(crate) type InfallibleWorkflowResult = WorkflowResult<()>; + /// Try to create a ValidationPackage for the given entry without calling out to some other node. /// I.e. either create it just from/with the header if `ValidationPackageDefinition` is `Entry`, /// or build it locally if we are the source (one of the sources). @@ -78,8 +120,8 @@ pub(crate) async fn try_make_local_validation_package( if overlapping_provenance.is_some() { // We authored this entry, so lets build the validation package here and now: build_validation_package( + Arc::clone(&context), &entry_with_header.entry, - context, entry_with_header.header.provenances(), ) } else { @@ -94,13 +136,13 @@ pub(crate) async fn try_make_local_validation_package( /// Gets hold of the validation package for the given entry by trying several different methods. #[autotrace] async fn validation_package( - entry_with_header: &EntryWithHeader, context: Arc, + entry_with_header: &EntryWithHeader, ) -> Result, HolochainError> { // 0. Call into the DNA to get the validation package definition for this entry // e.g. what data is needed to validate it (chain, entry, headers, etc) let entry = &entry_with_header.entry; - let validation_package_definition = get_validation_package_definition(entry, context.clone()) + let validation_package_definition = get_validation_package_definition(Arc::clone(&context), entry) .and_then(|callback_result| match callback_result { CallbackResult::Fail(error_string) => Err(HolochainError::ErrorGeneric(error_string)), CallbackResult::ValidationPackageDefinition(def) => Ok(def), @@ -201,6 +243,7 @@ pub mod tests { use holochain_core_types::entry::Entry; use holochain_json_api::json::JsonString; use std::{thread, time}; + use std::sync::Arc; #[test] fn test_simulate_packge_direct_from_author() { @@ -217,7 +260,7 @@ pub mod tests { // jack authors the entry context2 - .block_on(author_entry(&entry, None, &context2, &vec![])) + .block_on(author_entry(Arc::clone(&context2), &entry, None, &vec![])) .unwrap() .address(); @@ -234,7 +277,7 @@ pub mod tests { let entry_with_header = EntryWithHeader { entry, header }.clone(); let validation_package = context1 - .block_on(validation_package(&entry_with_header, context1.clone())) + .block_on(validation_package(Arc::clone(&context1), &entry_with_header)) .expect("Could not recover a validation package as the non-author"); assert_eq!( @@ -251,24 +294,24 @@ pub mod tests { /// Runs the given pending validation using the right holding workflow /// as specified by PendingValidationStruct::workflow. pub async fn run_holding_workflow( - pending: PendingValidation, context: Arc, + pending: PendingValidation, ) -> Result<(), HolochainError> { match pending.workflow { ValidatingWorkflow::HoldLink => { - hold_link_workflow(&pending.entry_with_header, context.clone()).await + hold_link_workflow(Arc::clone(&context), &pending.entry_with_header).await } ValidatingWorkflow::HoldEntry => { - hold_entry_workflow(&pending.entry_with_header, context.clone()).await + hold_entry_workflow(Arc::clone(&context), &pending.entry_with_header).await } ValidatingWorkflow::RemoveLink => { - remove_link_workflow(&pending.entry_with_header, context.clone()).await + remove_link_workflow(Arc::clone(&context), &pending.entry_with_header).await } ValidatingWorkflow::UpdateEntry => { - hold_update_workflow(&pending.entry_with_header, context.clone()).await + hold_update_workflow(Arc::clone(&context), &pending.entry_with_header).await } ValidatingWorkflow::RemoveEntry => { - hold_remove_workflow(&pending.entry_with_header, context.clone()).await + hold_remove_workflow(Arc::clone(&context), &pending.entry_with_header).await } } } diff --git a/crates/core/src/wasm_engine/api/query.rs b/crates/core/src/workflows/query.rs similarity index 84% rename from crates/core/src/wasm_engine/api/query.rs rename to crates/core/src/workflows/query.rs index 75cdd060f2..4bcd6a608b 100644 --- a/crates/core/src/wasm_engine/api/query.rs +++ b/crates/core/src/workflows/query.rs @@ -2,19 +2,18 @@ use crate::{ agent::chain_store::{ChainStoreQueryOptions, ChainStoreQueryResult}, context::Context, nucleus::actions::get_entry::get_entry_from_agent_chain, - wasm_engine::{api::ZomeApiResult, Runtime}, }; use holochain_persistence_api::cas::content::Address; - use holochain_core_types::{ chain_header::ChainHeader, entry::{entry_type::EntryType, Entry}, error::HolochainError, }; -use holochain_wasm_utils::api_serialization::{QueryArgs, QueryArgsNames, QueryResult}; -use std::{convert::TryFrom, sync::Arc}; -use wasmi::{RuntimeArgs, RuntimeValue}; +use holochain_wasm_types::{QueryArgs, QueryArgsNames, QueryResult}; +use holochain_wasmer_host::*; +use std::sync::Arc; +use crate::workflows::WorkflowResult; /// ZomeApiFunction::query function code /// args: [0] encoded MemoryAllocation as u64 @@ -59,22 +58,14 @@ use wasmi::{RuntimeArgs, RuntimeValue}; /// `*` Zero or more of any character /// `**/` Zero or more of any namespace component /// -pub fn invoke_query(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args. - let args_str = runtime.load_json_string_from_args(&args); - let query = match QueryArgs::try_from(args_str) { - Ok(input) => input, - Err(..) => return ribosome_error_code!(ArgumentDeserializationFailed), - }; - +pub async fn query_workflow(context: Arc, query: &QueryArgs) -> WorkflowResult { // Perform query let agent = context .state() .expect("Couldn't get state in invoke_query") .agent(); let top = agent.top_chain_header().expect("Should have init entries."); - let maybe_result = match query.entry_type_names { + let maybe_result = match &query.entry_type_names { // Result QueryArgsNames::QueryList(pats) => { let refs: Vec<&str> = pats.iter().map(AsRef::as_ref).collect(); // Vec -> Vec<&str> @@ -101,8 +92,9 @@ pub fn invoke_query(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult ) } }; - let result = match maybe_result { - // TODO #793: the Err(_code) is the RibosomeErrorCode, but we can't import that type here. + + match maybe_result { + // TODO #793: the Err(_code) is the WasmError, but we can't import that type here. // Perhaps return chain_store().query should return Some(result)/None instead, and the fixed // UnknownEntryType code here, rather than trying to return a specific error code. Ok(result) => Ok(match (query.options.entries, result) { @@ -125,7 +117,7 @@ pub fn invoke_query(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult match maybe_entries { Ok(entries) => QueryResult::Entries(entries), - Err(_e) => return ribosome_error_code!(UnknownEntryType), // TODO: return actual error? + Err(_e) => Err(WasmError::UnknownEntryType)?, // TODO: return actual error? } } (true, ChainStoreQueryResult::Headers(headers)) => { @@ -141,14 +133,12 @@ pub fn invoke_query(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult Ok(headers_with_entries) => { QueryResult::HeadersWithEntries(headers_with_entries) } - Err(_e) => return ribosome_error_code!(UnknownEntryType), // TODO: return actual error? + Err(_e) => Err(WasmError::UnknownEntryType)?, // TODO: return actual error? } } }), - Err(_code) => return ribosome_error_code!(UnknownEntryType), - }; - - runtime.store_result(result) + Err(_code) => Err(WasmError::UnknownEntryType)?, + } } /// Get an local-chain Entry via the provided context, returning Entry or HolochainError on failure diff --git a/crates/core/src/workflows/remove_entry.rs b/crates/core/src/workflows/remove_entry.rs new file mode 100644 index 0000000000..d33d734f4f --- /dev/null +++ b/crates/core/src/workflows/remove_entry.rs @@ -0,0 +1,52 @@ +use crate::{ + workflows::{author_entry::author_entry, get_entry_result::get_entry_result_workflow}, + +}; +use holochain_core_types::{ + entry::{deletion_entry::DeletionEntry, Entry}, + error::HolochainError, +}; +use holochain_persistence_api::cas::content::{Address, AddressableContent}; +use holochain_wasm_types::get_entry::*; +use holochain_wasmer_host::*; +use std::sync::Arc; +use crate::context::Context; + +/// ZomeApiFunction::RemoveEntry function code +/// args: [0] encoded MemoryAllocation +/// Expected Address argument +/// Stores/returns a RibosomeReturnValue +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn remove_entry_workflow( + context: Arc, + deleted_entry_address: &Address, +) -> Result { + // Get Current entry's latest version + let get_args = GetEntryArgs { + address: deleted_entry_address.to_owned(), + options: Default::default(), + }; + let maybe_entry_result = get_entry_result_workflow(Arc::clone(&context), &get_args).await; + + if let Err(err) = maybe_entry_result { + log_error!(context, "zome: get_entry_result_workflow failed: {:?}", err); + return Err(HolochainError::Wasm(WasmError::WorkflowFailed)); + } + + let entry_result = maybe_entry_result?; + if !entry_result.found() { + return Err(HolochainError::Wasm(WasmError::EntryNotFound)); + } + let deleted_entry_address = entry_result.latest()?.address(); + + // Create deletion entry + let deletion_entry = Entry::Deletion(DeletionEntry::new(deleted_entry_address.clone())); + + author_entry( + Arc::clone(&context), + &deletion_entry.clone(), + Some(deleted_entry_address), + &vec![], + ).await + .map(|_| deletion_entry.address()) +} diff --git a/crates/core/src/workflows/remove_link.rs b/crates/core/src/workflows/remove_link.rs index 06381aec00..93d4cab1aa 100644 --- a/crates/core/src/workflows/remove_link.rs +++ b/crates/core/src/workflows/remove_link.rs @@ -1,23 +1,23 @@ use crate::{ context::Context, dht::actions::hold_aspect::hold_aspect, network::entry_with_header::EntryWithHeader, nucleus::validation::validate_entry, - workflows::hold_entry::hold_entry_workflow, NEW_RELIC_LICENSE_KEY, + workflows::hold_entry::hold_entry_workflow, }; - -use crate::{nucleus::validation::ValidationError, workflows::validation_package}; +use crate::workflows::WorkflowResult; +use crate::{workflows::validation_package}; use holochain_core_types::{ entry::Entry, error::HolochainError, network::entry_aspect::EntryAspect, - validation::{EntryLifecycle, ValidationData}, + validation::{EntryLifecycle, ValidationData, ValidationResult}, }; use std::sync::Arc; -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub async fn remove_link_workflow( - entry_with_header: &EntryWithHeader, context: Arc, -) -> Result<(), HolochainError> { + entry_with_header: &EntryWithHeader, +) -> WorkflowResult<()> { let (link_data, links_to_remove) = match &entry_with_header.entry { Entry::LinkRemove(data) => data, _ => Err(HolochainError::ErrorGeneric( @@ -32,7 +32,7 @@ pub async fn remove_link_workflow( context, "workflow/remove_link: getting validation package..." ); - let maybe_validation_package = validation_package(&entry_with_header, context.clone()) + let maybe_validation_package = validation_package(Arc::clone(&context), &entry_with_header) .await .map_err(|err| { let message = "Could not get validation package from source! -> Add to pending..."; @@ -53,25 +53,26 @@ pub async fn remove_link_workflow( // 3. Validate the entry log_debug!(context, "workflow/remove_link: validate..."); - validate_entry( + match validate_entry( + Arc::clone(&context), entry_with_header.entry.clone(), None, validation_data, - &context - ).await - .map_err(|err| { - if let ValidationError::UnresolvedDependencies(dependencies) = &err { + ).await { + ValidationResult::Ok => (), + ValidationResult::UnresolvedDependencies(dependencies) => { log_debug!(context, "workflow/remove_link: Link could not be validated due to unresolved dependencies and will be tried later. List of missing dependencies: {:?}", dependencies); - HolochainError::ValidationPending - } else { + return Err(HolochainError::ValidationPending); + }, + ValidationResult::Fail(e) => { log_warn!(context, "workflow/remove_link: Link {:?} is NOT valid! Validation error: {:?}", entry_with_header.entry, - err, + e, ); - HolochainError::from(err) - } - - })?; + return Err(HolochainError::from(e)); + }, + v => return Err(HolochainError::ValidationFailed(v)), + }; log_debug!(context, "workflow/remove_link: is valid!"); @@ -84,7 +85,7 @@ pub async fn remove_link_workflow( log_debug!(context, "workflow/remove_link: added! {:?}", link); //4. store link_remove entry so we have all we need to respond to get links queries without any other network look-up``` - hold_entry_workflow(&entry_with_header, context.clone()).await?; + hold_entry_workflow(Arc::clone(&context), entry_with_header).await?; log_debug!( context, "workflow/hold_entry: added! {:?}", diff --git a/crates/core/src/wasm_engine/api/remove_link.rs b/crates/core/src/workflows/remove_link_wasm.rs similarity index 67% rename from crates/core/src/wasm_engine/api/remove_link.rs rename to crates/core/src/workflows/remove_link_wasm.rs index 1ebb617e7f..8eafa068c5 100644 --- a/crates/core/src/wasm_engine/api/remove_link.rs +++ b/crates/core/src/workflows/remove_link_wasm.rs @@ -6,46 +6,32 @@ use crate::{ NetworkQueryResult, }, }, - wasm_engine::{api::ZomeApiResult, Runtime}, workflows::author_entry::author_entry, - NEW_RELIC_LICENSE_KEY, -}; +}; use holochain_core_types::{ entry::Entry, error::HolochainError, link::{link_data::LinkData, LinkActionKind}, time::Timeout, }; -use holochain_wasm_utils::api_serialization::{ +use holochain_wasm_types::{ get_links::{GetLinksArgs, GetLinksOptions}, link_entries::LinkEntriesArgs, }; -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; +use holochain_wasmer_host::*; +use std::sync::Arc; +use crate::context::Context; /// ZomeApiFunction::GetLinks function code /// args: [0] encoded MemoryAllocation as u64 /// Expected complex argument: GetLinksArgs /// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_remove_link(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - let input = match LinkEntriesArgs::try_from(args_str.clone()) { - Ok(entry_input) => entry_input, - // Exit on error - Err(_) => { - log_error!( - context, - "zome: invoke_remove_link failed to deserialize LinkEntriesArgs: {:?}", - args_str - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - }; - +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn remove_link_wasm_workflow( + context: Arc, + input: &LinkEntriesArgs, +) -> Result<(), HolochainError> { let top_chain_header_option = context.state().unwrap().agent().top_chain_header(); let top_chain_header = match top_chain_header_option { @@ -54,9 +40,9 @@ pub fn invoke_remove_link(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiR log_error!( context, "zome: invoke_link_entries failed to deserialize LinkEntriesArgs: {:?}", - args_str + input ); - return ribosome_error_code!(ArgumentDeserializationFailed); + return Err(WasmError::ArgumentDeserializationFailed)?; } }; @@ -78,7 +64,7 @@ pub fn invoke_remove_link(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiR let response_result = context.block_on(query(context.clone(), method, Timeout::default())); if response_result.is_err() { log_error!("zome : Could not get links for remove_link method."); - ribosome_error_code!(WorkflowFailed) + Err(WasmError::WorkflowFailed)? } else { let response = response_result.expect("Could not get response"); let links_result = match response { @@ -89,12 +75,12 @@ pub fn invoke_remove_link(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiR }; if links_result.is_err() { log_error!(context, "zome : Could not get links for remove_link method"); - ribosome_error_code!(WorkflowFailed) + Err(WasmError::WorkflowFailed)? } else { let links = links_result.expect("This is supposed to not fail"); let links = match links { GetLinksNetworkResult::Links(links) => links, - _ => return ribosome_error_code!(WorkflowFailed), + _ => Err(WasmError::WorkflowFailed)?, }; let filtered_links = links .into_iter() @@ -105,11 +91,8 @@ pub fn invoke_remove_link(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiR let entry = Entry::LinkRemove((link_remove, filtered_links)); // Wait for future to be resolved - let result: Result<(), HolochainError> = context - .block_on(author_entry(&entry, None, &context, &vec![])) - .map(|_| ()); - - runtime.store_result(result) + author_entry(Arc::clone(&context), &entry, None, &vec![]).await + .map(|_| ()) } } } diff --git a/crates/core/src/workflows/respond_validation_package_request.rs b/crates/core/src/workflows/respond_validation_package_request.rs index 352f1aab57..9c9db3824b 100644 --- a/crates/core/src/workflows/respond_validation_package_request.rs +++ b/crates/core/src/workflows/respond_validation_package_request.rs @@ -6,7 +6,7 @@ use crate::{ nucleus::actions::{ build_validation_package::build_validation_package, get_entry::get_entry_from_agent_chain, }, - NEW_RELIC_LICENSE_KEY, + }; use holochain_core_types::signature::Provenance; @@ -14,7 +14,7 @@ use holochain_persistence_api::cas::content::Address; use std::{sync::Arc, vec::Vec}; #[autotrace] -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn respond_validation_package_request( to_agent_id: Address, msg_id: String, @@ -24,7 +24,7 @@ pub fn respond_validation_package_request( ) { let maybe_validation_package = match get_entry_from_agent_chain(&context, &requested_entry_address) { - Ok(Some(entry)) => build_validation_package(&entry, context.clone(), &provenances).ok(), + Ok(Some(entry)) => build_validation_package(Arc::clone(&context), &entry, &provenances).ok(), _ => None, }; diff --git a/crates/core/src/workflows/send.rs b/crates/core/src/workflows/send.rs new file mode 100644 index 0000000000..d11ef5771b --- /dev/null +++ b/crates/core/src/workflows/send.rs @@ -0,0 +1,22 @@ +use crate::{ + network::{actions::custom_send::custom_send, direct_message::CustomDirectMessage}, +}; +use holochain_json_api::json::RawString; +use holochain_wasm_types::send::SendArgs; +use std::sync::Arc; +use crate::context::Context; +use crate::workflows::WorkflowResult; + +/// ZomeApiFunction::Send function code +/// args: [0] encoded MemoryAllocation as u64 +/// Expected complex argument: SendArgs +/// Returns an HcApiReturnCode as I64 +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn send_workflow(context: Arc, args: &SendArgs) -> WorkflowResult { + let message = CustomDirectMessage { + payload: Ok(args.payload.to_owned()), + zome: args.zome.to_owned(), + }; + + Ok(RawString::from(custom_send(Arc::clone(&context), args.to_agent.to_owned(), message, args.options.0.to_owned()).await?)) +} diff --git a/crates/core/src/wasm_engine/api/sign.rs b/crates/core/src/workflows/sign.rs similarity index 52% rename from crates/core/src/wasm_engine/api/sign.rs rename to crates/core/src/workflows/sign.rs index 4ba078207b..26abea6120 100644 --- a/crates/core/src/wasm_engine/api/sign.rs +++ b/crates/core/src/workflows/sign.rs @@ -1,41 +1,35 @@ -use crate::{ - wasm_engine::{api::ZomeApiResult, Runtime}, - NEW_RELIC_LICENSE_KEY, -}; use holochain_core_types::{error::HcResult, signature::Signature}; use holochain_dpki::keypair::generate_random_sign_keypair; -use holochain_wasm_utils::api_serialization::sign::{OneTimeSignArgs, SignOneTimeResult}; +use holochain_wasm_types::sign::{OneTimeSignArgs, SignOneTimeResult}; use lib3h_sodium::secbuf::SecBuf; -use std::convert::TryFrom; -use wasmi::{RuntimeArgs, RuntimeValue}; +use crate::workflows::WorkflowResult; +use crate::context::Context; +use std::sync::Arc; +use holochain_wasm_types::wasm_string::WasmString; +use holochain_wasm_types::crypto::CryptoArgs; +use crate::workflows::crypto::crypto_workflow; +use holochain_wasm_types::crypto::CryptoMethod; + +pub async fn sign_workflow(context: Arc, payload: &WasmString) -> WorkflowResult { + Ok(Signature::from(crypto_workflow( + Arc::clone(&context), + &CryptoArgs { + payload: payload.to_string(), + method: CryptoMethod::Sign, + }).await?)) +} /// ZomeApiFunction::SignOneTime function code /// args: [0] encoded MemoryAllocation as u64 /// Expected argument: u64 /// Returns an HcApiReturnCode as I64 -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] -pub fn invoke_sign_one_time(runtime: &mut Runtime, args: &RuntimeArgs) -> ZomeApiResult { - let context = runtime.context()?; - - // deserialize args - let args_str = runtime.load_json_string_from_args(&args); - - let sign_args = match OneTimeSignArgs::try_from(args_str.clone()) { - Ok(sign_input) => sign_input, - // Exit on error - Err(err) => { - log_error!(context, "zome: invoke_sign_one_time failed to deserialize OneTimeSignArgs: {:?} got err: {:?}", - args_str, err - ); - return ribosome_error_code!(ArgumentDeserializationFailed); - } - }; - - runtime.store_result(sign_one_time(sign_args.payloads)) +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn sign_one_time_workflow(_: Arc, sign_args: &OneTimeSignArgs) -> WorkflowResult { + sign_one_time(sign_args.payloads.clone()) } /// creates a one-time private key and sign data returning the signature and the public key -#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] pub fn sign_one_time(payloads: Vec) -> HcResult { let mut sign_keys = generate_random_sign_keypair()?; let mut signatures = Vec::new(); @@ -57,30 +51,26 @@ pub fn sign_one_time(payloads: Vec) -> HcResult { #[cfg(test)] mod test_super { use super::sign_one_time; - use crate::wasm_engine::{ - api::{tests::test_zome_api_function, ZomeApiFunction}, - Defn, - }; use holochain_dpki::utils::verify; - use holochain_json_api::json::JsonString; + // use holochain_json_api::json::JsonString; use holochain_persistence_api::cas::content::Address; - /// test that bytes passed to debug end up in the log - #[test] - fn test_zome_api_function_sign() { - let (call_result, _) = test_zome_api_function( - ZomeApiFunction::Crypto.as_str(), - r#"{ "payload": "this is data", "method" : "Sign" }"# - .as_bytes() - .to_vec(), - ); - assert_eq!( - JsonString::from_json( - r#"{"ok":true,"value":"xoEEoLF1yWM4VBNtjEwrfM/iVzjuAxxbkOyBWi0LV0+1CAH/PCs9MErnbmFeZRtQNtw7+SmVrm7Irac4lZsaDA==","error":"null"}"# - ), - call_result, - ); - } + // /// test that bytes passed to debug end up in the log + // #[test] + // fn test_zome_api_function_sign() { + // let (call_result, _) = test_zome_api_function( + // ZomeApiFunction::Crypto.as_str(), + // r#"{ "payload": "this is data", "method" : "Sign" }"# + // .as_bytes() + // .to_vec(), + // ); + // assert_eq!( + // JsonString::from_json( + // r#"{"ok":true,"value":"xoEEoLF1yWM4VBNtjEwrfM/iVzjuAxxbkOyBWi0LV0+1CAH/PCs9MErnbmFeZRtQNtw7+SmVrm7Irac4lZsaDA==","error":"null"}"# + // ), + // call_result, + // ); + // } #[test] fn test_sign_one_time() { diff --git a/crates/core/src/workflows/sleep.rs b/crates/core/src/workflows/sleep.rs new file mode 100644 index 0000000000..da2a6bf1f4 --- /dev/null +++ b/crates/core/src/workflows/sleep.rs @@ -0,0 +1,14 @@ +use std::{thread, time::Duration}; +use std::sync::Arc; +use crate::context::Context; +use crate::workflows::InfallibleWorkflowResult; + +/// ZomeApiFunction::Sleep function code +/// args: [0] encoded MemoryAllocation as u64 +/// Expected argument: u64 +/// Returns an HcApiReturnCode as I64 +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn sleep_workflow(_: Arc, nanos: &u64) -> InfallibleWorkflowResult { + thread::sleep(Duration::from_nanos(*nanos)); + Ok(()) +} diff --git a/crates/core/src/workflows/update_entry.rs b/crates/core/src/workflows/update_entry.rs new file mode 100644 index 0000000000..ef852ca320 --- /dev/null +++ b/crates/core/src/workflows/update_entry.rs @@ -0,0 +1,49 @@ +use crate::{ + holochain_wasm_types::holochain_persistence_api::cas::content::AddressableContent, + workflows::{author_entry::author_entry, get_entry_result::get_entry_result_workflow}, + +}; +use holochain_persistence_api::cas::content::Address; +use holochain_wasm_types::{get_entry::*, UpdateEntryArgs}; +use holochain_wasmer_host::*; +use holochain_core_types::error::HolochainError; +use std::sync::Arc; +use crate::context::Context; +use crate::workflows::WorkflowResult; + +/// ZomeApiFunction::UpdateEntry function code +/// args: [0] encoded MemoryAllocation as u64 +/// Expected complex argument: UpdateEntryArgs +/// Returns an HcApiReturnCode as I64 +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn update_entry_workflow( + context: Arc, + entry_args: &UpdateEntryArgs, +) -> WorkflowResult
{ + // Get Current entry's latest version + let get_args = GetEntryArgs { + address: entry_args.address.to_owned(), + options: Default::default(), + }; + let maybe_entry_result = get_entry_result_workflow(Arc::clone(&context), &get_args).await; + if let Err(err) = maybe_entry_result { + log_error!(context, "zome: get_entry_result_workflow failed: {:?}", err); + return Err(HolochainError::Wasm(WasmError::WorkflowFailed)); + } + let entry_result = maybe_entry_result?.clone(); + if !entry_result.found() { + return Err(HolochainError::Wasm(WasmError::EntryNotFound)); + } + let latest_entry = entry_result.latest()?; + + // Create Chain Entry + let entry = entry_args.new_entry.clone(); + + author_entry( + Arc::clone(&context), + &entry, + Some(latest_entry.address()), + &vec![], // TODO should provenance be a parameter? + ).await + .map(|result| result.address()) +} diff --git a/crates/core/src/workflows/verify_signature.rs b/crates/core/src/workflows/verify_signature.rs new file mode 100644 index 0000000000..790d9e5ef9 --- /dev/null +++ b/crates/core/src/workflows/verify_signature.rs @@ -0,0 +1,66 @@ +use holochain_dpki::utils::Verify; +use holochain_wasm_types::verify_signature::VerifySignatureArgs; +use crate::workflows::WorkflowResult; +use std::sync::Arc; +use crate::context::Context; + +/// ZomeApiFunction::VerifySignature function code +/// args: [0] encoded MemoryAllocation as u64 +/// Expected argument: u64 +/// Returns an HcApiReturnCode as I64 +// #[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)] +pub async fn verify_signature_workflow( + context: Arc, + verification_args: &VerifySignatureArgs, +) -> WorkflowResult { + log_debug!( + context, + "zome: using provenance:{:?} to verify data:{:?}", + verification_args.provenance.clone(), + verification_args.payload.clone() + ); + + verification_args + .provenance + .verify(verification_args.payload.clone()) +} + +// #[cfg(test)] +// mod test_super { +// use crate::{ +// holochain_wasm_engine::holochain_persistence_api::cas::content::AddressableContent, +// wasm_engine::{ +// api::{tests::test_zome_api_function, ZomeApiFunction}, +// Defn, +// }, +// }; +// use holochain_json_api::json::JsonString; +// +// #[test] +// fn test_zome_api_function_verify() { +// let (call_result, context) = test_zome_api_function( +// ZomeApiFunction::Crypto.as_str(), +// r#"{ "payload": "this is data", "method":"Sign" }"#.as_bytes().to_vec(), +// ); +// assert_eq!( +// JsonString::from_json( +// r#"{"ok":true,"value":"xoEEoLF1yWM4VBNtjEwrfM/iVzjuAxxbkOyBWi0LV0+1CAH/PCs9MErnbmFeZRtQNtw7+SmVrm7Irac4lZsaDA==","error":"null"}"# +// ), +// call_result, +// ); +// +// let args = format!( +// r#"{{ "provenance": ["{}","xoEEoLF1yWM4VBNtjEwrfM/iVzjuAxxbkOyBWi0LV0+1CAH/PCs9MErnbmFeZRtQNtw7+SmVrm7Irac4lZsaDA=="], "payload": "this is data" }}"#, +// context.agent_id.address() +// ); +// let (call_result, _) = test_zome_api_function( +// ZomeApiFunction::VerifySignature.as_str(), +// args.as_bytes().to_vec(), +// ); +// +// assert_eq!( +// JsonString::from_json(r#"{"ok":true,"value":"true","error":"null"}"#), +// call_result, +// ); +// } +// } diff --git a/crates/core_types/Cargo.toml b/crates/core_types/Cargo.toml index bb764ce9a5..5aa685235a 100644 --- a/crates/core_types/Cargo.toml +++ b/crates/core_types/Cargo.toml @@ -22,7 +22,6 @@ serde_json = { version = "=1.0.47", features = ["preserve_order"] } lazy_static = "=1.4.0" multihash = "=0.8.0" mashup = "0.1.9" -wasmi = "=0.4.4" hcid = "=0.0.6" rust-base58 = "=0.0.4" snowflake = "=1.3.0" @@ -39,6 +38,7 @@ lib3h_crypto_api = "=0.0.38" parking_lot ="=0.9.0" log = "=0.4.8" holochain_logging = "=0.0.7" +holochain_wasmer_common = "=0.0.18" [dev-dependencies] test_utils = { version = "=0.0.43-alpha3", path = "../../test_utils"} diff --git a/crates/core_types/src/bits_n_pieces.rs b/crates/core_types/src/bits_n_pieces.rs deleted file mode 100644 index 4d142a5c1e..0000000000 --- a/crates/core_types/src/bits_n_pieces.rs +++ /dev/null @@ -1,126 +0,0 @@ -pub const U16_MAX: u32 = u16::max_value() as u32; -pub const U32_MAX: u64 = u32::max_value() as u64; - -/// returns the u16 high bits from a u32 -pub fn u32_high_bits(i: u32) -> u16 { - (i >> 16) as u16 -} - -/// returns the u16 low bits from a u32 by doing a lossy cast -pub fn u32_low_bits(i: u32) -> u16 { - (i as u16) -} - -/// splits the high and low bits of u32 into a tuple of u16, for destructuring convenience -pub fn u32_split_bits(i: u32) -> (u16, u16) { - (u32_high_bits(i), u32_low_bits(i)) -} - -/// merges 2x u16 into a single u32 -pub fn u32_merge_bits(high: u16, low: u16) -> u32 { - (u32::from(high) << 16) | u32::from(low) -} - -pub fn u64_high_bits(i: u64) -> u32 { - (i >> 32) as u32 -} - -pub fn u64_low_bits(i: u64) -> u32 { - (i as u32) -} - -pub fn u64_split_bits(i: u64) -> (u32, u32) { - (u64_high_bits(i), u64_low_bits(i)) -} - -pub fn u64_merge_bits(high: u32, low: u32) -> u64 { - (u64::from(high) << 32) | u64::from(low) -} - -#[cfg(test)] -pub mod tests { - - #[test] - /// tests that we can extract the high bits from a u32 into the correct u16 - fn u32_high_bits_test() { - assert_eq!( - 0b1010101010101010, - super::u32_high_bits(0b1010101010101010_0101010101010101), - ); - } - - #[test] - /// tests that we can extract the high bits from a u32 into the correct u16 - fn u32_low_bits_test() { - assert_eq!( - 0b0101010101010101, - super::u32_low_bits(0b1010101010101010_0101010101010101), - ); - } - - #[test] - /// tests that we can split a u32 into a tuple of high/low bits - fn u32_split_bits_test() { - assert_eq!( - (0b1010101010101010, 0b0101010101010101), - super::u32_split_bits(0b1010101010101010_0101010101010101), - ); - } - - #[test] - /// tests that we can merge a u16 tuple into a u32 - fn u32_merge_bits_test() { - assert_eq!( - 0b1010101010101010_0101010101010101, - super::u32_merge_bits(0b1010101010101010, 0b0101010101010101), - ); - } - - #[test] - /// tests that we can extract the high bits from a u64 into the correct u32 - fn u64_high_bits_test() { - assert_eq!( - 0b10101010_10101010_10101010_10101010, - super::u64_high_bits( - 0b10101010_10101010_10101010_10101010_01010101_01010101_01010101_01010101 - ), - ); - } - - #[test] - /// tests that we can extract the high bits from a u64 into the correct u32 - fn u64_low_bits_test() { - assert_eq!( - 0b01010101_01010101_01010101_01010101, - super::u64_low_bits( - 0b10101010_10101010_10101010_10101010_01010101_01010101_01010101_01010101 - ), - ); - } - - #[test] - /// tests that we can split a u64 into a tuple of high/low bits - fn u64_split_bits_test() { - assert_eq!( - ( - 0b10101010_10101010_10101010_10101010, - 0b01010101_01010101_01010101_01010101 - ), - super::u64_split_bits( - 0b10101010_10101010_10101010_10101010_01010101_01010101_01010101_01010101 - ), - ); - } - - #[test] - /// tests that we can merge a u32 tuple into a u64 - fn u64_merge_bits_test() { - assert_eq!( - 0b10101010_10101010_10101010_10101010_01010101_01010101_01010101_01010101, - super::u64_merge_bits( - 0b10101010_10101010_10101010_10101010, - 0b01010101_01010101_01010101_01010101 - ), - ); - } -} diff --git a/crates/core_types/src/callback.rs b/crates/core_types/src/callback.rs new file mode 100644 index 0000000000..d968eb922e --- /dev/null +++ b/crates/core_types/src/callback.rs @@ -0,0 +1,11 @@ +use holochain_json_api::{error::JsonError, json::JsonString}; +use validation::ValidationPackageDefinition; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, DefaultJson)] +pub enum CallbackResult { + Pass, + Fail(String), + NotImplemented(String), + ValidationPackageDefinition(ValidationPackageDefinition), + ReceiveResult(String), +} diff --git a/crates/core_types/src/dna/wasm.rs b/crates/core_types/src/dna/wasm.rs index 2963aa00c3..d93cc40594 100644 --- a/crates/core_types/src/dna/wasm.rs +++ b/crates/core_types/src/dna/wasm.rs @@ -3,7 +3,6 @@ //! - and serialized to json use backtrace::Backtrace; -use crate::error::HolochainError; use base64; use serde::{ self, @@ -13,38 +12,8 @@ use serde::{ use std::{ fmt, hash::{Hash, Hasher}, - ops::Deref, - sync::{Arc, RwLock}, + sync::Arc, }; -use wasmi::Module; - -/// Wrapper around wasmi::Module since it does not implement Clone, Debug, PartialEq, Eq, -/// which are all needed to add it to the DnaWasm below, and hence to the state. -#[derive(Clone)] -pub struct ModuleArc(Arc); -impl ModuleArc { - pub fn new(module: Module) -> Self { - ModuleArc(Arc::new(module)) - } -} -impl PartialEq for ModuleArc { - fn eq(&self, _other: &ModuleArc) -> bool { - //*self == *other - false - } -} -impl Eq for ModuleArc {} -impl Deref for ModuleArc { - type Target = Arc; - fn deref(&self) -> &Self::Target { - &self.0 - } -} -impl fmt::Debug for ModuleArc { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "ModuleMutex") - } -} /// Private helper for converting binary WebAssembly into base64 serialized string. fn _vec_u8_to_b64_str(data: &Arc>, s: S) -> Result @@ -95,12 +64,6 @@ pub struct DnaWasm { deserialize_with = "_b64_str_to_vec_u8" )] pub code: Arc>, - - /// This is a transient parsed representation of the binary code. - /// This gets only create once from the code and then cached inside this RwLock - /// because creation of these WASMi modules from bytes is expensive. - #[serde(skip, default = "empty_module")] - module: Arc>>, } impl DnaWasm { @@ -112,15 +75,10 @@ impl DnaWasm { ); DnaWasm { code: Arc::new(vec![]), - module: empty_module(), } } } -fn empty_module() -> Arc>> { - Arc::new(RwLock::new(None)) -} - impl fmt::Debug for DnaWasm { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<<>>") @@ -144,33 +102,6 @@ impl DnaWasm { pub fn from_bytes(wasm: Vec) -> Self { DnaWasm { code: Arc::new(wasm), - module: empty_module(), } } - - /// This returns a parsed WASMi representation of the code, ready to be - /// run in a WASMi ModuleInstance. - /// The first call will create the module from the binary. - pub fn get_wasm_module(&self) -> Result { - if self.module.read().unwrap().is_none() { - self.create_module()?; - } - - Ok(self.module.read().unwrap().as_ref().unwrap().clone()) - } - - fn create_module(&self) -> Result<(), HolochainError> { - let module = wasmi::Module::from_buffer(&*self.code).map_err(|e| { - debug!( - "DnaWasm could not create a wasmi::Module from code bytes! Error: {:?}", - e - ); - debug!("Unparsable bytes: {:?}", *self.code); - HolochainError::ErrorGeneric(e.into()) - })?; - let module_arc = ModuleArc::new(module); - let mut lock = self.module.write().unwrap(); - *lock = Some(module_arc); - Ok(()) - } } diff --git a/crates/core_types/src/dna/zome.rs b/crates/core_types/src/dna/zome.rs index fe21add32a..b058202b7d 100644 --- a/crates/core_types/src/dna/zome.rs +++ b/crates/core_types/src/dna/zome.rs @@ -146,6 +146,21 @@ impl Zome { } } +#[derive(Debug, Serialize, Deserialize, DefaultJson, Default)] +pub struct PartialZome { + #[serde(serialize_with = "serialize_entry_types")] + #[serde(deserialize_with = "deserialize_entry_types")] + entry_types: ZomeEntryTypes, + traits: ZomeTraits, + fn_declarations: ZomeFnDeclarations, +} + +impl PartialZome { + pub fn new(entry_types: &ZomeEntryTypes, traits: &ZomeTraits, fn_declarations: &ZomeFnDeclarations) -> Self { + Self { entry_types: entry_types.to_owned(), traits: traits.to_owned(), fn_declarations: fn_declarations.to_owned() } + } +} + #[cfg(test)] pub mod tests { use super::*; diff --git a/crates/core_types/src/error/mod.rs b/crates/core_types/src/error/mod.rs index 0ca2500451..b496a63f74 100644 --- a/crates/core_types/src/error/mod.rs +++ b/crates/core_types/src/error/mod.rs @@ -2,19 +2,20 @@ //! which is responsible for mounting and running instances of DNA, and executing WASM code. mod dna_error; -mod ribosome_error; +pub use self::dna_error::*; use self::HolochainError::*; -pub use self::{dna_error::*, ribosome_error::*}; use futures::channel::oneshot::Canceled as FutureCanceled; use holochain_json_api::{ error::{JsonError, JsonResult}, json::*, }; +use validation::ValidationResult; use holochain_locksmith::LocksmithError; use holochain_persistence_api::{error::PersistenceError, hash::HashString}; use lib3h_crypto_api::CryptoError; +use holochain_wasmer_common::WasmError; use serde_json::Error as SerdeError; use std::{ error::Error, @@ -106,10 +107,9 @@ pub enum HolochainError { SerializationError(String), InvalidOperationOnSysEntry, CapabilityCheckFailed, - ValidationFailed(String), + ValidationFailed(ValidationResult), ValidationPending, - Ribosome(RibosomeErrorCode), - RibosomeFailed(String), + Wasm(WasmError), ConfigError(String), Timeout, InitializationFailed(String), @@ -120,6 +120,19 @@ pub enum HolochainError { List(Vec), } +impl From for ValidationResult { + fn from(e: HolochainError) -> ValidationResult { + // any error _during_ validation is a failure of validation + ValidationResult::Fail(e.to_string()) + } +} + +impl From for HolochainError { + fn from(wasm_error: WasmError) -> HolochainError { + HolochainError::Wasm(wasm_error) + } +} + pub type HcResult = Result; impl HolochainError { @@ -149,10 +162,9 @@ impl fmt::Display for HolochainError { write!(f, "operation cannot be done on a system entry type") } CapabilityCheckFailed => write!(f, "Caller does not have Capability to make that call"), - ValidationFailed(fail_msg) => write!(f, "{}", fail_msg), + ValidationFailed(fail_msg) => write!(f, "{:?}", fail_msg), ValidationPending => write!(f, "Entry validation could not be completed"), - Ribosome(err_code) => write!(f, "{}", err_code.as_str()), - RibosomeFailed(fail_msg) => write!(f, "{}", fail_msg), + Wasm(err) => write!(f, "{:?}", err), ConfigError(err_msg) => write!(f, "{}", err_msg), Timeout => write!(f, "timeout"), InitializationFailed(err_msg) => write!(f, "{}", err_msg), diff --git a/crates/core_types/src/error/ribosome_error.rs b/crates/core_types/src/error/ribosome_error.rs deleted file mode 100644 index daf478ca3a..0000000000 --- a/crates/core_types/src/error/ribosome_error.rs +++ /dev/null @@ -1,341 +0,0 @@ -use self::{RibosomeEncodedValue::*, RibosomeErrorCode::*}; -use crate::error::HolochainError; -use holochain_json_api::{error::JsonError, json::JsonString}; - -use bits_n_pieces::u64_split_bits; -use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::{convert::TryFrom, str::FromStr}; - -/// size of the integer that encodes ribosome codes -pub type RibosomeEncodingBits = u64; -/// size of the integer that wasm sees -pub type RibosomeRuntimeBits = i64; -/// size of the integer that represents a ribosome code -pub type RibosomeCodeBits = u32; - -#[derive(Clone, Debug, PartialEq)] -pub struct RibosomeEncodedAllocation(RibosomeEncodingBits); - -impl From for RibosomeEncodingBits { - fn from(ribosome_memory_allocation: RibosomeEncodedAllocation) -> RibosomeEncodingBits { - ribosome_memory_allocation.0 - } -} - -impl From for RibosomeEncodedAllocation { - fn from(i: RibosomeEncodingBits) -> Self { - Self(i) - } -} - -impl ToString for RibosomeEncodedAllocation { - fn to_string(&self) -> String { - RibosomeEncodingBits::from(self.to_owned()).to_string() - } -} - -/// Represents all possible values passed to/from wasmi functions -/// All wasmi functions are I64 values -#[repr(u64)] -#[derive(Clone, Debug, PartialEq)] -pub enum RibosomeEncodedValue { - /// @TODO make this unambiguous or remove - /// Contextually represents: - /// - Function succeeded without any allocation - /// - Empty/nil argument to a function - /// - Zero length allocation (error) - Success, - /// A value that can be safely converted to a wasm allocation - /// High bits represent offset, low bits represent length - /// @see WasmAllocation - Allocation(RibosomeEncodedAllocation), - /// A value that should be interpreted as an error - /// Low bits are zero, high bits map to an enum variant - Failure(RibosomeErrorCode), -} - -impl From for RibosomeEncodingBits { - fn from(ribosome_return_code: RibosomeEncodedValue) -> RibosomeEncodingBits { - match ribosome_return_code { - RibosomeEncodedValue::Success => 0, - RibosomeEncodedValue::Allocation(allocation) => RibosomeEncodingBits::from(allocation), - RibosomeEncodedValue::Failure(code) => { - code as RibosomeRuntimeBits as RibosomeEncodingBits - } - } - } -} - -impl From for RibosomeRuntimeBits { - fn from(ribosome_return_code: RibosomeEncodedValue) -> RibosomeRuntimeBits { - RibosomeEncodingBits::from(ribosome_return_code) as RibosomeRuntimeBits - } -} - -impl From for RibosomeEncodedValue { - fn from(i: RibosomeEncodingBits) -> Self { - if i == 0 { - RibosomeEncodedValue::Success - } else { - let (code_int, maybe_allocation_length) = u64_split_bits(i); - if maybe_allocation_length == 0 { - RibosomeEncodedValue::Failure(RibosomeErrorCode::from_code_int(code_int)) - } else { - RibosomeEncodedValue::Allocation(RibosomeEncodedAllocation(i)) - } - } - } -} - -impl ToString for RibosomeEncodedValue { - fn to_string(&self) -> String { - match self { - Success => "Success".to_string(), - Allocation(allocation) => allocation.to_string(), - Failure(code) => code.to_string(), - } - } -} - -impl From for String { - fn from(return_code: RibosomeEncodedValue) -> String { - return_code.to_string() - } -} - -impl FromStr for RibosomeEncodedValue { - type Err = HolochainError; - - fn from_str(s: &str) -> Result { - Ok(match s { - "Success" => RibosomeEncodedValue::Success, - _ => RibosomeEncodedValue::Failure(s.parse()?), - }) - } -} - -impl From for JsonString { - fn from(ribosome_return_code: RibosomeEncodedValue) -> JsonString { - JsonString::from_json(&ribosome_return_code.to_string()) - } -} - -impl From for RibosomeEncodedValue { - fn from(error: HolochainError) -> Self { - RibosomeEncodedValue::Failure(RibosomeErrorCode::from(error)) - } -} - -impl TryFrom for RibosomeEncodedValue { - type Error = HolochainError; - - fn try_from(json_string: JsonString) -> Result { - String::from(json_string).parse() - } -} - -impl RibosomeEncodedValue { - pub fn from_error(err_code: RibosomeErrorCode) -> Self { - Failure(err_code) - } -} - -/// Enum of all possible ERROR codes that a Zome API Function could return. -#[repr(u64)] -#[derive(Clone, Debug, PartialEq, Eq, Hash, DefaultJson, PartialOrd, Ord)] -#[rustfmt::skip] -pub enum RibosomeErrorCode { - Unspecified = 1 << 32, - ArgumentDeserializationFailed = 2 << 32, - OutOfMemory = 3 << 32, - ReceivedWrongActionResult = 4 << 32, - CallbackFailed = 5 << 32, - RecursiveCallForbidden = 6 << 32, - ResponseSerializationFailed = 7 << 32, - NotAnAllocation = 8 << 32, - ZeroSizedAllocation = 9 << 32, - UnknownEntryType = 10 << 32, - MismatchWasmCallDataType = 11 << 32, - EntryNotFound = 12 << 32, - WorkflowFailed = 13 << 32, -} - -#[rustfmt::skip] -impl RibosomeErrorCode { - pub fn as_str(&self) -> &str { - match self { - Unspecified => "Unspecified", - ArgumentDeserializationFailed => "Argument deserialization failed", - OutOfMemory => "Out of memory", - ReceivedWrongActionResult => "Received wrong action result", - CallbackFailed => "Callback failed", - RecursiveCallForbidden => "Recursive call forbidden", - ResponseSerializationFailed => "Response serialization failed", - NotAnAllocation => "Not an allocation", - ZeroSizedAllocation => "Zero-sized allocation", - UnknownEntryType => "Unknown entry type", - MismatchWasmCallDataType => "Mismatched WasmCallData type", - EntryNotFound => "Entry Could Not Be Found", - WorkflowFailed => "Workflow failed", - } - } -} - -impl From for RibosomeErrorCode { - fn from(error: HolochainError) -> RibosomeErrorCode { - // the mapping between HolochainError and RibosomeErrorCode is pretty poor overall - match error { - HolochainError::ErrorGeneric(_) => RibosomeErrorCode::Unspecified, - HolochainError::CryptoError(_) => RibosomeErrorCode::Unspecified, - HolochainError::NotImplemented(_) => RibosomeErrorCode::CallbackFailed, - HolochainError::LoggingError => RibosomeErrorCode::Unspecified, - HolochainError::DnaMissing => RibosomeErrorCode::Unspecified, - HolochainError::Dna(_) => RibosomeErrorCode::Unspecified, - HolochainError::IoError(_) => RibosomeErrorCode::Unspecified, - HolochainError::SerializationError(_) => { - RibosomeErrorCode::ArgumentDeserializationFailed - } - HolochainError::InvalidOperationOnSysEntry => RibosomeErrorCode::UnknownEntryType, - HolochainError::CapabilityCheckFailed => RibosomeErrorCode::Unspecified, - HolochainError::ValidationFailed(_) => RibosomeErrorCode::CallbackFailed, - HolochainError::ValidationPending => RibosomeErrorCode::Unspecified, - HolochainError::Ribosome(e) => e, - HolochainError::RibosomeFailed(_) => RibosomeErrorCode::CallbackFailed, - HolochainError::ConfigError(_) => RibosomeErrorCode::Unspecified, - HolochainError::Timeout => RibosomeErrorCode::Unspecified, - HolochainError::InitializationFailed(_) => RibosomeErrorCode::Unspecified, - HolochainError::LifecycleError(_) => RibosomeErrorCode::Unspecified, - HolochainError::DnaHashMismatch(_, _) => RibosomeErrorCode::Unspecified, - HolochainError::EntryNotFoundLocally => RibosomeErrorCode::Unspecified, - HolochainError::EntryIsPrivate => RibosomeErrorCode::Unspecified, - HolochainError::List(_) => RibosomeErrorCode::Unspecified, - } - } -} - -impl ToString for RibosomeErrorCode { - fn to_string(&self) -> String { - self.as_str().to_string() - } -} - -impl From for String { - fn from(ribosome_error_code: RibosomeErrorCode) -> Self { - ribosome_error_code.to_string() - } -} - -impl RibosomeErrorCode { - pub fn from_code_int(code: RibosomeCodeBits) -> Self { - match code { - 0 => panic!(format!("RibosomeErrorCode == {:?} encountered", code)), - 2 => ArgumentDeserializationFailed, - 3 => OutOfMemory, - 4 => ReceivedWrongActionResult, - 5 => CallbackFailed, - 6 => RecursiveCallForbidden, - 7 => ResponseSerializationFailed, - 8 => NotAnAllocation, - 9 => ZeroSizedAllocation, - 10 => UnknownEntryType, - 12 => EntryNotFound, - 13 => WorkflowFailed, - 1 | _ => Unspecified, - } - } - - pub fn from_return_code(ret_code: RibosomeEncodedValue) -> Self { - match ret_code { - Failure(rib_err) => rib_err, - _ => panic!(format!( - "RibosomeEncodedValue == {:?} encountered", - ret_code - )), - } - } -} - -// @TODO review this serialization, can it be an i32 instead of a full string? -// @see https://github.com/holochain/holochain-rust/issues/591 -impl Serialize for RibosomeErrorCode { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - serializer.serialize_str(&self.to_string()) - } -} - -impl<'de> Deserialize<'de> for RibosomeErrorCode { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - let s = String::deserialize(deserializer)?; - Ok(RibosomeErrorCode::from_str(&s).expect("could not deserialize RibosomeErrorCode")) - } -} - -impl FromStr for RibosomeErrorCode { - type Err = HolochainError; - - fn from_str(s: &str) -> Result { - match s { - "Unspecified" => Ok(RibosomeErrorCode::Unspecified), - "Argument deserialization failed" => { - Ok(RibosomeErrorCode::ArgumentDeserializationFailed) - } - "Out of memory" => Ok(RibosomeErrorCode::OutOfMemory), - "Received wrong action result" => Ok(RibosomeErrorCode::ReceivedWrongActionResult), - "Callback failed" => Ok(RibosomeErrorCode::CallbackFailed), - "Recursive call forbidden" => Ok(RibosomeErrorCode::RecursiveCallForbidden), - "Response serialization failed" => Ok(RibosomeErrorCode::ResponseSerializationFailed), - "Not an allocation" => Ok(RibosomeErrorCode::NotAnAllocation), - "Zero-sized allocation" => Ok(RibosomeErrorCode::ZeroSizedAllocation), - "Unknown entry type" => Ok(RibosomeErrorCode::UnknownEntryType), - "Entry Could Not Be Found" => Ok(EntryNotFound), - "Workflow failed" => Ok(WorkflowFailed), - _ => Err(HolochainError::ErrorGeneric(String::from( - "Unknown RibosomeErrorCode", - ))), - } - } -} - -#[cfg(test)] -pub mod tests { - use super::*; - - #[test] - fn ribosome_error_code_round_trip() { - let oom = RibosomeErrorCode::from_code_int( - ((RibosomeErrorCode::OutOfMemory as u64) >> 32) as RibosomeCodeBits, - ); - assert_eq!(RibosomeErrorCode::OutOfMemory, oom); - assert_eq!(RibosomeErrorCode::OutOfMemory.to_string(), oom.to_string()); - } - - #[test] - fn error_conversion() { - // TODO could use strum crate to iteratively - // gather all known codes. - for code in 1..=13 { - let mut err = RibosomeErrorCode::from_code_int(code); - - let err_str = err.as_str().to_owned(); - - err = err_str.parse().expect("unable to parse error"); - - let inner_code = RibosomeEncodedValue::from_error(err); - - let _one_int: i64 = inner_code.clone().into(); - let _another_int: u64 = inner_code.clone().into(); - } - } - - #[test] - #[should_panic] - fn code_zero() { - RibosomeErrorCode::from_code_int(0); - } -} diff --git a/crates/core_types/src/lib.rs b/crates/core_types/src/lib.rs index f7224d9de8..1b12f2ff3d 100644 --- a/crates/core_types/src/lib.rs +++ b/crates/core_types/src/lib.rs @@ -34,9 +34,9 @@ extern crate maplit; // #[macro_use] // extern crate shrinkwraprs; extern crate hcid; -extern crate wasmi; #[macro_use] extern crate log; +extern crate holochain_wasmer_common; pub mod chain_header; pub mod crud_status; @@ -46,7 +46,6 @@ pub mod error; #[macro_use] extern crate objekt; pub mod agent; -pub mod bits_n_pieces; pub mod chain_migrate; pub mod dna; pub mod hdk_version; @@ -56,6 +55,7 @@ pub mod signature; pub mod time; pub mod ugly; pub mod validation; +pub mod callback; #[macro_use] extern crate holochain_logging; diff --git a/crates/core_types/src/validation.rs b/crates/core_types/src/validation.rs index 2e67445fef..1bac3e27f1 100644 --- a/crates/core_types/src/validation.rs +++ b/crates/core_types/src/validation.rs @@ -19,6 +19,42 @@ use chain_header::test_chain_header; use std::convert::TryFrom; +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, DefaultJson)] +/// The result of a validation +/// NOT used to represent an error somewhere _nearby_ validation, use something like +/// Result to represent related errors +/// If an error occurs _during_ validation, this is a `Fail`. +pub enum ValidationResult { + /// `Ok` means whatever was validated is valid + Ok, + + /// `Fail` means the validation function did run successfully and recognized the entry + /// as invalid. The String parameter holds the non-zero return value of the app validation + /// function. + Fail(String), + + /// The entry could not get validated because known dependencies (like base and target + /// for links) were not present yet. + UnresolvedDependencies(Vec
), + + /// A validation function for the given entry could not be found. + /// This can happen if the entry's type is not defined in the DNA (which can only happen + /// if somebody is sending wrong entries..) or there is no native implementation for a + /// system entry type yet. + NotImplemented, + + /// Something timed out + /// @TODO maybe we want to retry or handle it gracefully somehow? + Timeout, +} + +impl From for ValidationResult { + fn from(e: JsonError) -> Self { + // if we can't (de)serialize some data this de facto implies a validation failure + Self::Fail(e.into()) + } +} + #[derive(Clone, Serialize, Deserialize, Debug, PartialEq, DefaultJson)] pub struct ValidationPackage { pub chain_header: ChainHeader, diff --git a/crates/dpki/src/key_blob.rs b/crates/dpki/src/key_blob.rs index a8db52c4e3..67dfa32495 100755 --- a/crates/dpki/src/key_blob.rs +++ b/crates/dpki/src/key_blob.rs @@ -6,7 +6,7 @@ use crate::{ keypair::*, password_encryption::{self, pw_dec, pw_enc, pw_hash, EncryptedData, PwHashConfig}, seed::*, - utils, NEW_RELIC_LICENSE_KEY, SEED_SIZE, + utils, SEED_SIZE, NEW_RELIC_LICENSE_KEY, }; use holochain_core_types::{ agent::Base32, diff --git a/crates/dpki/src/keypair.rs b/crates/dpki/src/keypair.rs index 7333e6f9c3..b319b6f434 100755 --- a/crates/dpki/src/keypair.rs +++ b/crates/dpki/src/keypair.rs @@ -3,7 +3,7 @@ use crate::{ key_bundle, password_encryption::{self, PwHashConfig}, - utils, CODEC_HCK0, CODEC_HCS0, NEW_RELIC_LICENSE_KEY, SEED_SIZE, SIGNATURE_SIZE, + utils, CODEC_HCK0, CODEC_HCS0, SEED_SIZE, SIGNATURE_SIZE, NEW_RELIC_LICENSE_KEY, }; use hcid::*; use holochain_core_types::{agent::Base32, error::HcResult}; diff --git a/crates/dpki/src/seed.rs b/crates/dpki/src/seed.rs index db4eb81650..a361af2edf 100644 --- a/crates/dpki/src/seed.rs +++ b/crates/dpki/src/seed.rs @@ -2,7 +2,7 @@ use crate::{ key_bundle::KeyBundle, password_encryption::*, utils::{generate_derived_seed_buf, SeedContext}, - AGENT_ID_CTX, NEW_RELIC_LICENSE_KEY, SEED_SIZE, + AGENT_ID_CTX, SEED_SIZE, NEW_RELIC_LICENSE_KEY, }; use bip39::{Language, Mnemonic, MnemonicType}; use holochain_core_types::error::{HcResult, HolochainError}; diff --git a/crates/dpki/src/utils.rs b/crates/dpki/src/utils.rs index b4e8fa75b2..402e592c04 100644 --- a/crates/dpki/src/utils.rs +++ b/crates/dpki/src/utils.rs @@ -1,6 +1,6 @@ use crate::{ password_encryption::{pw_dec, pw_enc, EncryptedData, PwHashConfig}, - CODEC_HCS0, CONTEXT_SIZE, NEW_RELIC_LICENSE_KEY, SEED_SIZE, + CODEC_HCS0, CONTEXT_SIZE, SEED_SIZE, NEW_RELIC_LICENSE_KEY, }; use hcid::*; use holochain_core_types::{ diff --git a/crates/hdk/Cargo.toml b/crates/hdk/Cargo.toml index 8456bb9778..a3438c9449 100644 --- a/crates/hdk/Cargo.toml +++ b/crates/hdk/Cargo.toml @@ -14,7 +14,7 @@ serde_derive = "=1.0.104" serde_json = { version = "=1.0.47", features = ["preserve_order"] } bitflags = "=1.2.1" lazy_static = "=1.4.0" -holochain_wasm_utils = { version = "=0.0.43-alpha3", path = "../wasm_utils" } +holochain_wasm_types = { version = "=0.0.43-alpha3", path = "../wasm_types" } holochain_core_types = { version = "=0.0.43-alpha3", path = "../core_types" } holochain_json_api = "=0.0.23" holochain_json_derive = "=0.0.23" @@ -22,6 +22,7 @@ holochain_persistence_api = "=0.0.17" pretty_assertions = "=0.6.1" env_logger = "=0.6.1" url = "=2.1.0" +holochain_wasmer_guest = "=0.0.18" [dev-dependencies] test_utils = { version = "=0.0.43-alpha3", path = "../../test_utils" } diff --git a/crates/hdk/src/api/bundle.rs b/crates/hdk/src/api/bundle.rs deleted file mode 100644 index 854628c784..0000000000 --- a/crates/hdk/src/api/bundle.rs +++ /dev/null @@ -1,14 +0,0 @@ -use crate::{ - error::{ZomeApiError, ZomeApiResult}, - BundleOnClose, -}; - -/// NOT YET AVAILABLE -pub fn start_bundle(_timeout: usize, _user_param: serde_json::Value) -> ZomeApiResult<()> { - Err(ZomeApiError::FunctionNotImplemented) -} - -/// NOT YET AVAILABLE -pub fn close_bundle(_action: BundleOnClose) -> ZomeApiResult<()> { - Err(ZomeApiError::FunctionNotImplemented) -} diff --git a/crates/hdk/src/api/call.rs b/crates/hdk/src/api/call.rs index 499c836f8f..221a1dc05e 100644 --- a/crates/hdk/src/api/call.rs +++ b/crates/hdk/src/api/call.rs @@ -1,7 +1,14 @@ -use crate::{error::ZomeApiResult, Dispatch}; use holochain_json_api::json::JsonString; +// use holochain_json_api::json::RawString; use holochain_persistence_api::cas::content::Address; -use holochain_wasm_utils::api_serialization::ZomeFnCallArgs; +// use holochain_persistence_api::hash::HashString; +use holochain_wasm_types::call::ZomeFnCallArgs; +use holochain_wasmer_guest::host_call; +use crate::api::hc_call; +use crate::error::ZomeApiResult; +use crate::error::ZomeApiError; +use std::convert::TryFrom; +use holochain_wasm_types::WasmResult; /// Call an exposed function from another zome or another (bridged) instance running /// in the same conductor. @@ -22,66 +29,66 @@ use holochain_wasm_utils::api_serialization::ZomeFnCallArgs; /// # use hdk::holochain_json_api::json::JsonString; /// # use hdk::holochain_json_api::error::JsonError; /// # use hdk::holochain_core_types::error::HolochainError; -/// # use hdk::holochain_core_types::error::RibosomeEncodingBits; -/// # use hdk::holochain_core_types::error::RibosomeEncodedValue; +/// # use hdk::holochain_core_types::error::AllocationPtr; +/// # use hdk::holochain_core_types::error::RibosomeReturnValue; /// /// # // Adding empty functions so that the cfg(test) build can link. /// # #[no_mangle] -/// # pub fn hc_init_globals(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_init_globals(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_commit_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_commit_entry(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_get_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_get_entry(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_entry_address(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_entry_address(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_query(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_query(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_call(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_call(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// #[no_mangle] -/// # pub fn hc_crypto(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_crypto(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// #[no_mangle] -/// # pub fn hc_meta(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_meta(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_sign_one_time(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_sign_one_time(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_verify_signature(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_verify_signature(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_update_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_update_entry(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_remove_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_remove_entry(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_send(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_send(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_sleep(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_sleep(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_debug(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_debug(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_get_links(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_get_links(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_get_links_count(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_get_links_count(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_link_entries(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_link_entries(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_remove_link(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_remove_link(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_list(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_list(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_new_random(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_new_random(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_derive_seed(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_derive_seed(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_derive_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_derive_key(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_sign(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_sign(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_get_public_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_get_public_key(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_commit_capability_grant(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_commit_capability_grant(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_commit_capability_claim(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_commit_capability_claim(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_emit_signal(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_emit_signal(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// /// # fn main() { /// @@ -100,7 +107,7 @@ use holochain_wasm_utils::api_serialization::ZomeFnCallArgs; /// validate_agent: |validation_data : EntryValidationData::| { /// Ok(()) /// } -/// +/// /// functions: [ /// sum: { /// inputs: |num1: u32, num2: u32|, @@ -135,67 +142,67 @@ use holochain_wasm_utils::api_serialization::ZomeFnCallArgs; /// # use hdk::holochain_core_types::error::HolochainError; /// # use hdk::error::ZomeApiResult; /// # use std::convert::TryInto; -/// # use hdk::holochain_core_types::error::RibosomeEncodingBits; -/// # use hdk::holochain_core_types::error::RibosomeEncodedValue; +/// # use hdk::holochain_core_types::error::AllocationPtr; +/// # use hdk::holochain_core_types::error::RibosomeReturnValue; /// # use hdk::holochain_persistence_api::cas::content::Address; /// /// # // Adding empty functions so that the cfg(test) build can link. /// # #[no_mangle] -/// # pub fn hc_init_globals(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_init_globals(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_commit_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_commit_entry(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_get_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_get_entry(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_entry_address(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_entry_address(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_query(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_query(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_call(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_call(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_crypto(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_crypto(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_meta(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_meta(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_sign_one_time(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_sign_one_time(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_verify_signature(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_verify_signature(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_update_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_update_entry(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_remove_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_remove_entry(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_send(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_send(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_sleep(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_sleep(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_debug(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_debug(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_get_links(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_get_links(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// #[no_mangle] -/// # pub fn hc_get_links_count(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_get_links_count(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_link_entries(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_link_entries(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_remove_link(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_remove_link(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_list(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_list(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_new_random(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_new_random(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_derive_seed(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_derive_seed(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_derive_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_derive_key(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_sign(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_sign(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_get_public_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_get_public_key(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_commit_capability_grant(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_commit_capability_grant(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_commit_capability_claim(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_commit_capability_claim(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_emit_signal(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_emit_signal(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// /// # fn main() { /// @@ -218,7 +225,7 @@ use holochain_wasm_utils::api_serialization::ZomeFnCallArgs; /// init: || { /// Ok(()) /// } -/// +/// /// validate_agent: |validation_data : EntryValidationData::| { /// Ok(()) /// } @@ -238,18 +245,37 @@ use holochain_wasm_utils::api_serialization::ZomeFnCallArgs; /// /// # } /// ``` -pub fn call>( +pub fn call, I: Into, O: TryFrom> ( instance_handle: S, zome_name: S, cap_token: Address, fn_name: S, - fn_args: JsonString, -) -> ZomeApiResult { - Dispatch::Call.with_input(ZomeFnCallArgs { + fn_args: I, +) -> ZomeApiResult +where O::Error: ToString + std::fmt::Debug, O: std::fmt::Debug{ + let args_json: JsonString = fn_args.into(); + let wasm_result: WasmResult = match host_call!(hc_call, ZomeFnCallArgs { instance_handle: instance_handle.into(), zome_name: zome_name.into(), cap_token, fn_name: fn_name.into(), - fn_args: String::from(fn_args), - }) + fn_args: String::from(args_json), + }) { + Ok(v) => { + crate::debug(format!("v {:?}", v)).ok(); + v + }, + Err(e) => { + crate::debug(format!("e {:?}", e)).ok(); + return Err(ZomeApiError::Internal("first call error".into())); + }, + }; + let json: JsonString = match wasm_result { + WasmResult::Ok(json) => json, + WasmResult::Err(e) => return Err(ZomeApiError::Internal(format!("{:?}", e))), + }; + match O::try_from(json) { + Ok(v) => Ok(v), + Err(e) => Err(ZomeApiError::Internal(e.to_string())), + } } diff --git a/crates/hdk/src/api/capability.rs b/crates/hdk/src/api/capability.rs index 3ebe882f48..9ffe4d7e56 100644 --- a/crates/hdk/src/api/capability.rs +++ b/crates/hdk/src/api/capability.rs @@ -1,9 +1,12 @@ -use crate::{error::ZomeApiResult, Dispatch}; +use crate::{error::ZomeApiResult}; use holochain_core_types::entry::cap_entries::{CapFunctions, CapabilityType}; use holochain_persistence_api::cas::content::Address; -use holochain_wasm_utils::api_serialization::capabilities::{ +use holochain_wasm_types::capabilities::{ CommitCapabilityClaimArgs, CommitCapabilityGrantArgs, }; +use crate::api::hc_commit_capability_grant; +use crate::api::hc_commit_capability_claim; +use holochain_wasmer_guest::host_call; /// Adds a capability grant to the local chain pub fn commit_capability_grant>( @@ -12,12 +15,12 @@ pub fn commit_capability_grant>( assignees: Option>, functions: CapFunctions, ) -> ZomeApiResult
{ - Dispatch::CommitCapabilityGrant.with_input(CommitCapabilityGrantArgs { + Ok(host_call!(hc_commit_capability_grant, CommitCapabilityGrantArgs { id: id.into(), cap_type, assignees, functions, - }) + })?) } /// Adds a capability claim to the local chain @@ -26,9 +29,9 @@ pub fn commit_capability_claim>( grantor: Address, token: Address, ) -> ZomeApiResult
{ - Dispatch::CommitCapabilityClaim.with_input(CommitCapabilityClaimArgs { + Ok(host_call!(hc_commit_capability_claim, CommitCapabilityClaimArgs { id: id.into(), grantor, token, - }) + })?) } diff --git a/crates/hdk/src/api/commit_entry.rs b/crates/hdk/src/api/commit_entry.rs index 324fab3e7e..f7c51bcd92 100644 --- a/crates/hdk/src/api/commit_entry.rs +++ b/crates/hdk/src/api/commit_entry.rs @@ -1,9 +1,11 @@ -use crate::{error::ZomeApiResult, Dispatch}; +use crate::{error::ZomeApiResult}; use holochain_core_types::entry::Entry; use holochain_persistence_api::cas::content::Address; -use holochain_wasm_utils::api_serialization::commit_entry::{ +use holochain_wasm_types::commit_entry::{ CommitEntryArgs, CommitEntryOptions, CommitEntryResult, }; +use holochain_wasmer_guest::host_call; +use crate::api::hc_commit_entry; /// Attempts to commit an entry to the local source chain. The entry /// will also be checked against the defined validation rules for that entry type. @@ -27,10 +29,10 @@ use holochain_wasm_utils::api_serialization::commit_entry::{ /// # use holochain_core_types::entry::entry_type::AppEntryType; /// # use holochain_core_types::entry::Entry; /// # use holochain_persistence_api::cas::content::Address; -/// # use holochain_core_types::error::RibosomeEncodingBits; +/// # use holochain_core_types::error::AllocationPtr; /// /// # #[no_mangle] -/// # pub fn hc_commit_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { 0 } +/// # pub fn hc_commit_entry(_: AllocationPtr) -> AllocationPtr { 0 } /// /// # fn main() { /// @@ -69,8 +71,8 @@ pub fn commit_entry_result( entry: &Entry, options: CommitEntryOptions, ) -> ZomeApiResult { - Dispatch::CommitEntry.with_input(CommitEntryArgs { + Ok(host_call!(hc_commit_entry, CommitEntryArgs { entry: entry.clone(), options, - }) + })?) } diff --git a/crates/hdk/src/api/debug.rs b/crates/hdk/src/api/debug.rs index b5b6ef2dbf..45f4642a7b 100644 --- a/crates/hdk/src/api/debug.rs +++ b/crates/hdk/src/api/debug.rs @@ -1,5 +1,7 @@ -use crate::{error::ZomeApiResult, Dispatch}; -use holochain_json_api::json::JsonString; +use crate::{error::ZomeApiResult}; +use holochain_wasmer_guest::*; +use holochain_wasm_types::wasm_string::WasmString; +use crate::api::hc_debug; /// Prints a string through the stdout of the running Conductor, and also /// writes that string to the logger in the execution context @@ -20,8 +22,8 @@ use holochain_json_api::json::JsonString; /// # } /// ``` pub fn debug>(msg: J) -> ZomeApiResult<()> { - let _: ZomeApiResult<()> = Dispatch::Debug.with_input(JsonString::from_json(&msg.into())); - // internally returns RibosomeEncodedValue::Success which is a zero length allocation - // return Ok(()) unconditionally instead of the "error" from success - Ok(()) + let s: String = msg.into(); + let ws = WasmString::from(s); + + Ok(host_call!(hc_debug, ws)?) } diff --git a/crates/hdk/src/api/decrypt.rs b/crates/hdk/src/api/decrypt.rs index fa97818f8e..c4275f08bd 100644 --- a/crates/hdk/src/api/decrypt.rs +++ b/crates/hdk/src/api/decrypt.rs @@ -1,7 +1,9 @@ -use crate::error::ZomeApiResult; -use holochain_wasm_utils::api_serialization::crypto::{CryptoArgs, CryptoMethod}; - -use super::Dispatch; +// use crate::error::ZomeApiResult; +use holochain_wasm_types::wasm_string::WasmString; +use holochain_wasmer_guest::host_call; +use std::convert::TryFrom; +use holochain_wasmer_guest::JsonString; +use crate::api::hc_decrypt; /// decrypts a string payload using the agent's private key. /// Returns the message as a string. @@ -25,9 +27,7 @@ use super::Dispatch; /// } /// # } /// ``` -pub fn decrypt>(payload: S) -> ZomeApiResult { - Dispatch::Crypto.with_input(CryptoArgs { - payload: payload.into(), - method: CryptoMethod::Decrypt, - }) +pub fn decrypt, O: TryFrom>(payload: S) -> Result { + let s: String = payload.into(); + Ok(host_call!(hc_decrypt, WasmString::from(s))?) } diff --git a/crates/hdk/src/api/emit_signal.rs b/crates/hdk/src/api/emit_signal.rs index f383badea4..955b072483 100644 --- a/crates/hdk/src/api/emit_signal.rs +++ b/crates/hdk/src/api/emit_signal.rs @@ -1,6 +1,8 @@ -use crate::{error::ZomeApiResult, Dispatch}; +use crate::{error::ZomeApiResult}; use holochain_json_api::json::JsonString; -use holochain_wasm_utils::api_serialization::emit_signal::EmitSignalArgs; +use holochain_wasm_types::emit_signal::EmitSignalArgs; +use holochain_wasmer_guest::host_call; +use crate::api::hc_emit_signal; /// Emits a signal that listeners can receive. /// (Status: MVP) @@ -29,10 +31,10 @@ use holochain_wasm_utils::api_serialization::emit_signal::EmitSignalArgs; /// # use hdk::error::ZomeApiResult; /// # use std::time::Duration; /// # use hdk::holochain_json_api::json::JsonString; -/// # use hdk::holochain_core_types::error::RibosomeEncodingBits; -/// # use hdk::holochain_core_types::error::RibosomeEncodedValue; +/// # use hdk::holochain_core_types::error::AllocationPtr; +/// # use hdk::holochain_core_types::error::RibosomeReturnValue; /// # #[no_mangle] -/// # pub fn hc_emit_signal(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_emit_signal(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// /// # fn main() { /// pub fn handle_receive_chat_message(message: String) -> ZomeApiResult<()> { @@ -50,11 +52,8 @@ pub fn emit_signal, J: Into>( name: S, arguments: J, ) -> ZomeApiResult<()> { - let _: ZomeApiResult<()> = Dispatch::EmitSignal.with_input(EmitSignalArgs { + Ok(host_call!(hc_emit_signal, EmitSignalArgs { name: name.into(), arguments: arguments.into(), - }); - // internally returns RibosomeEncodedValue::Success which is a zero length allocation - // return Ok(()) unconditionally instead of the "error" from success - Ok(()) + })?) } diff --git a/crates/hdk/src/api/encrypt.rs b/crates/hdk/src/api/encrypt.rs index 690f64a7db..17a3f4fdbe 100644 --- a/crates/hdk/src/api/encrypt.rs +++ b/crates/hdk/src/api/encrypt.rs @@ -1,7 +1,8 @@ use crate::error::ZomeApiResult; -use holochain_wasm_utils::api_serialization::crypto::{CryptoArgs, CryptoMethod}; - -use super::Dispatch; +use holochain_wasm_types::crypto::{CryptoArgs, CryptoMethod}; +use holochain_wasmer_guest::host_call; +use crate::api::hc_encrypt; +use holochain_wasm_types::wasm_string::WasmString; /// encrypts a string payload using the agent's private key. /// Returns the message as a string. @@ -26,8 +27,12 @@ use super::Dispatch; /// # } /// ``` pub fn encrypt>(payload: S) -> ZomeApiResult { - Dispatch::Crypto.with_input(CryptoArgs { + let result: WasmString = match host_call!(hc_encrypt, CryptoArgs { payload: payload.into(), method: CryptoMethod::Encrypt, - }) + }) { + Ok(v) => v, + Err(e) => return Err(e)?, + }; + Ok(result.to_string()) } diff --git a/crates/hdk/src/api/entry_address.rs b/crates/hdk/src/api/entry_address.rs index 36203e7b4c..72e4fd6ab7 100644 --- a/crates/hdk/src/api/entry_address.rs +++ b/crates/hdk/src/api/entry_address.rs @@ -1,7 +1,9 @@ -use super::Dispatch; use crate::error::ZomeApiResult; use holochain_core_types::entry::Entry; use holochain_persistence_api::cas::content::Address; +use holochain_wasmer_guest::host_call; +use crate::api::hc_entry_address; + /// Reconstructs an address of the given entry data. /// This is the same value that would be returned if `entry_type_name` and `entry_value` were passed /// to the [commit_entry](fn.commit_entry.html) function and by which it would be retrievable from the DHT using [get_entry](fn.get_entry.html). @@ -45,5 +47,5 @@ use holochain_persistence_api::cas::content::Address; /// # } /// ``` pub fn entry_address(entry: &Entry) -> ZomeApiResult
{ - Dispatch::EntryAddress.with_input(entry) + Ok(host_call!(hc_entry_address, entry)?) } diff --git a/crates/hdk/src/api/get_entry.rs b/crates/hdk/src/api/get_entry.rs index 71c728b397..9e1fee3f7d 100644 --- a/crates/hdk/src/api/get_entry.rs +++ b/crates/hdk/src/api/get_entry.rs @@ -1,13 +1,14 @@ use crate::{ error::{ZomeApiError, ZomeApiResult}, - Dispatch, }; use holochain_core_types::entry::Entry; use holochain_persistence_api::cas::content::Address; -use holochain_wasm_utils::api_serialization::get_entry::{ +use holochain_wasm_types::get_entry::{ EntryHistory, GetEntryArgs, GetEntryOptions, GetEntryResult, GetEntryResultType, StatusRequestKind, }; +use holochain_wasmer_guest::host_call; +use crate::api::hc_get_entry; /// Retrieves latest version of an entry from the local chain or the DHT, by looking it up using /// the specified address. @@ -82,8 +83,8 @@ pub fn get_entry_result( address: &Address, options: GetEntryOptions, ) -> ZomeApiResult { - Dispatch::GetEntry.with_input(GetEntryArgs { + Ok(host_call!(hc_get_entry, GetEntryArgs { address: address.clone(), options, - }) + })?) } diff --git a/crates/hdk/src/api/get_links.rs b/crates/hdk/src/api/get_links.rs index 6f973ccf48..83e4c715ad 100644 --- a/crates/hdk/src/api/get_links.rs +++ b/crates/hdk/src/api/get_links.rs @@ -1,14 +1,16 @@ use crate::{ api::get_entry::get_entry_result, error::{ZomeApiError, ZomeApiResult}, - Dispatch, }; use holochain_core_types::{entry::Entry, link::LinkMatch}; use holochain_persistence_api::{cas::content::Address, hash::HashString}; -use holochain_wasm_utils::api_serialization::{ +use holochain_wasm_types::{ get_entry::{GetEntryOptions, GetEntryResult, GetEntryResultItem, GetEntryResultType}, get_links::{GetLinksArgs, GetLinksOptions, GetLinksResult, GetLinksResultCount}, }; +use holochain_wasmer_guest::host_call; +use crate::api::hc_get_links_count; +use crate::api::hc_get_links; /// Consumes four values; the address of an entry get get links from (the base), the type of the links /// to be retrieved, an optional tag to match, and an options struct for selecting what meta data and crud status links to retrieve. @@ -23,13 +25,13 @@ use holochain_wasm_utils::api_serialization::{ /// ```rust /// # extern crate hdk; /// # extern crate holochain_core_types; -/// # extern crate holochain_wasm_utils; +/// # extern crate holochain_wasm_engine; /// # extern crate holochain_json_api; /// # extern crate holochain_persistence_api; /// # use holochain_json_api::json::JsonString; /// # use holochain_persistence_api::cas::content::Address; /// # use hdk::error::ZomeApiResult; -/// # use holochain_wasm_utils::api_serialization::get_links::{GetLinksResult, GetLinksOptions}; +/// # use holochain_wasm_types::get_links::{GetLinksResult, GetLinksOptions}; /// # use holochain_core_types::link::LinkMatch; /// /// # fn main() { @@ -47,12 +49,12 @@ pub fn get_links_with_options( let type_re = link_type.to_regex_string()?; let tag_re = tag.to_regex_string()?; - Dispatch::GetLinks.with_input(GetLinksArgs { + Ok(host_call!(hc_get_links, GetLinksArgs { entry_address: base.clone(), link_type: type_re, tag: tag_re, options, - }) + })?) } /// Similar to the get_links_with_options but it allows the user to get the number of links in the dht @@ -60,13 +62,13 @@ pub fn get_links_with_options( /// ```rust /// # extern crate hdk; /// # extern crate holochain_core_types; -/// # extern crate holochain_wasm_utils; +/// # extern crate holochain_wasm_engine; /// # extern crate holochain_json_api; /// # extern crate holochain_persistence_api; /// # use holochain_json_api::json::JsonString; /// # use holochain_persistence_api::cas::content::Address; /// # use hdk::error::ZomeApiResult; -/// # use holochain_wasm_utils::api_serialization::get_links::{GetLinksResultCount, GetLinksOptions}; +/// # use holochain_wasm_types::get_links::{GetLinksResultCount, GetLinksOptions}; /// # use holochain_core_types::link::LinkMatch; /// /// # fn main() { @@ -83,12 +85,12 @@ pub fn get_links_count_with_options( ) -> ZomeApiResult { let type_re = link_type.to_regex_string()?; let tag_re = tag.to_regex_string()?; - Dispatch::GetLinksCount.with_input(GetLinksArgs { + Ok(host_call!(hc_get_links_count, GetLinksArgs { entry_address: base.clone(), link_type: type_re, tag: tag_re, options, - }) + })?) } pub fn get_links_count( @@ -115,11 +117,11 @@ pub fn get_links( /// ```rust /// # extern crate hdk; /// # extern crate holochain_core_types; -/// # extern crate holochain_wasm_utils; +/// # extern crate holochain_wasm_engine; /// # extern crate holochain_persistence_api; /// # use hdk::error::ZomeApiResult; /// # use holochain_persistence_api::cas::content::Address; -/// # use holochain_wasm_utils::api_serialization::{ +/// # use holochain_wasm_types::{ /// # get_entry::{GetEntryOptions, GetEntryResult}, /// # get_links::GetLinksOptions}; /// # use holochain_core_types::link::LinkMatch; @@ -152,7 +154,6 @@ pub fn get_links_and_load( link_type: LinkMatch<&str>, tag: LinkMatch<&str>, ) -> ZomeApiResult>> { - println!("get_links_and_load"); let get_links_result = get_links_result( base, link_type, diff --git a/crates/hdk/src/api/keystore.rs b/crates/hdk/src/api/keystore.rs index 30a1272f30..b6407ed16d 100644 --- a/crates/hdk/src/api/keystore.rs +++ b/crates/hdk/src/api/keystore.rs @@ -1,20 +1,28 @@ -use crate::{error::ZomeApiResult, Dispatch}; -use holochain_wasm_utils::api_serialization::keystore::{ +use crate::{error::ZomeApiResult}; +use holochain_wasm_types::keystore::{ KeyType, KeystoreDeriveKeyArgs, KeystoreDeriveSeedArgs, KeystoreGetPublicKeyArgs, KeystoreListResult, KeystoreNewRandomArgs, KeystoreSignArgs, }; +use holochain_wasmer_guest::host_call; +use crate::api::hc_keystore_get_public_key; +use crate::api::hc_keystore_sign; +use crate::api::hc_keystore_derive_key; +use crate::api::hc_keystore_derive_seed; +use crate::api::hc_keystore_new_random; +use crate::api::hc_keystore_list; +use holochain_core_types::signature::Signature; // Returns a list of the named secrets stored in the keystore. pub fn keystore_list() -> ZomeApiResult { - Dispatch::KeystoreList.without_input() + Ok(host_call!(hc_keystore_list, ())?) } /// Creates a new random "root" Seed secret in the keystore pub fn keystore_new_random>(dst_id: S, size: usize) -> ZomeApiResult<()> { - Dispatch::KeystoreNewRandom.with_input(KeystoreNewRandomArgs { + Ok(host_call!(hc_keystore_new_random, KeystoreNewRandomArgs { dst_id: dst_id.into(), size, - }) + })?) } /// Creates a new derived seed secret in the keystore, derived from a previously defined seed. @@ -25,12 +33,12 @@ pub fn keystore_derive_seed>( context: S, index: u64, ) -> ZomeApiResult<()> { - Dispatch::KeystoreDeriveSeed.with_input(KeystoreDeriveSeedArgs { + Ok(host_call!(hc_keystore_derive_seed, KeystoreDeriveSeedArgs { src_id: src_id.into(), dst_id: dst_id.into(), context: context.into(), index, - }) + })?) } /// Creates a new derived key secret in the keystore derived from on a previously defined seed. @@ -39,28 +47,28 @@ pub fn keystore_derive_key>( src_id: S, dst_id: S, key_type: KeyType, -) -> ZomeApiResult { - Dispatch::KeystoreDeriveKey.with_input(KeystoreDeriveKeyArgs { +) -> ZomeApiResult { + Ok(host_call!(hc_keystore_derive_key, KeystoreDeriveKeyArgs { src_id: src_id.into(), dst_id: dst_id.into(), key_type, - }) + })?) } /// Signs a payload using a private key from the keystore. /// Accepts one argument: the keystore ID of the desired private key. -pub fn keystore_sign>(src_id: S, payload: S) -> ZomeApiResult { - Dispatch::KeystoreSign.with_input(KeystoreSignArgs { +pub fn keystore_sign>(src_id: S, payload: S) -> ZomeApiResult { + Ok(host_call!(hc_keystore_sign, KeystoreSignArgs { src_id: src_id.into(), payload: payload.into(), - }) + })?) } /// Returns the public key of a key secret /// Accepts one argument: the keystore ID of the desired public key. /// Fails if the id is a Seed secret. -pub fn keystore_get_public_key>(src_id: S) -> ZomeApiResult { - Dispatch::KeystoreGetPublicKey.with_input(KeystoreGetPublicKeyArgs { +pub fn keystore_get_public_key>(src_id: S) -> ZomeApiResult { + Ok(host_call!(hc_keystore_get_public_key, KeystoreGetPublicKeyArgs { src_id: src_id.into(), - }) + })?) } diff --git a/crates/hdk/src/api/link_entries.rs b/crates/hdk/src/api/link_entries.rs index c84afc8aae..c6ba150679 100644 --- a/crates/hdk/src/api/link_entries.rs +++ b/crates/hdk/src/api/link_entries.rs @@ -1,6 +1,8 @@ -use crate::{error::ZomeApiError, Dispatch}; +use crate::{error::ZomeApiError}; use holochain_persistence_api::cas::content::Address; -use holochain_wasm_utils::api_serialization::link_entries::LinkEntriesArgs; +use holochain_wasm_types::link_entries::LinkEntriesArgs; +use holochain_wasmer_guest::host_call; +use crate::api::hc_link_entries; /// Adds a named, tagged, directed link between two entries on the DHT. /// Consumes four values, two of which are the addresses of entries, and two of which are strings used to describe the link. @@ -33,8 +35,8 @@ use holochain_wasm_utils::api_serialization::link_entries::LinkEntriesArgs; /// # use holochain_persistence_api::cas::content::Address; /// # use hdk::AGENT_ADDRESS; /// # use hdk::error::ZomeApiResult; -/// # use hdk::holochain_wasm_utils::api_serialization::get_entry::GetEntryOptions; -/// # use hdk::holochain_wasm_utils::api_serialization::get_entry::StatusRequestKind; +/// # use hdk::holochain_wasm_types::get_entry::GetEntryOptions; +/// # use hdk::holochain_wasm_types::get_entry::StatusRequestKind; /// # fn main() { /// /// #[derive(Serialize, Deserialize, Debug, DefaultJson)] @@ -76,10 +78,10 @@ pub fn link_entries>( link_type: S, tag: S, ) -> Result { - Dispatch::LinkEntries.with_input(LinkEntriesArgs { + Ok(host_call!(hc_link_entries, LinkEntriesArgs { base: base.clone(), target: target.clone(), link_type: link_type.into(), tag: tag.into(), - }) + })?) } diff --git a/crates/hdk/src/api/mod.rs b/crates/hdk/src/api/mod.rs index 16526ae7ea..c96dc0a3eb 100644 --- a/crates/hdk/src/api/mod.rs +++ b/crates/hdk/src/api/mod.rs @@ -1,25 +1,16 @@ //! developers! Detailed references and examples can be found here for how to use the //! HDK exposed functions to access powerful Holochain functions. -use crate::error::{ZomeApiError, ZomeApiResult}; use bitflags::bitflags; use holochain_json_api::json::{default_to_json, JsonString, RawString}; use holochain_persistence_api::{cas::content::Address, hash::HashString}; use lazy_static::lazy_static; -use holochain_core_types::{ - dna::capabilities::CapabilityRequest, - error::{RibosomeEncodedAllocation, RibosomeEncodingBits, ZomeApiInternalResult}, -}; -pub use holochain_wasm_utils::api_serialization::validation::*; -use holochain_wasm_utils::{ - api_serialization::ZomeApiGlobals, - memory::{ribosome::load_ribosome_encoded_json, stack::WasmStack}, -}; +use holochain_core_types::{dna::capabilities::CapabilityRequest}; +pub use holochain_wasm_types::validation::*; +use holochain_wasm_types::ZomeApiGlobals; use crate::init_globals::init_globals; -use std::convert::{TryFrom, TryInto}; -mod bundle; mod call; mod capability; mod commit_entry; @@ -43,7 +34,6 @@ mod update_remove; mod version; pub use self::{ - bundle::{close_bundle, start_bundle}, call::call, capability::{commit_capability_claim, commit_capability_grant}, commit_entry::{commit_entry, commit_entry_result}, @@ -72,139 +62,48 @@ pub use self::{ update_remove::{remove_entry, update_agent, update_entry}, version::{version, version_hash}, }; - -macro_rules! def_api_fns { - ( - $( - $function_name:ident, $enum_variant:ident ; - )* - ) => { - - pub enum Dispatch { - $( $enum_variant ),* - } - - impl Dispatch { - - pub fn without_input + Into>( - &self, - ) -> ZomeApiResult { - self.with_input(JsonString::empty_object()) - } - - pub fn with_input, O: TryFrom>( - &self, - input: I, - ) -> ZomeApiResult { - let mut mem_stack = unsafe { G_MEM_STACK } - .ok_or_else(|| ZomeApiError::Internal("debug failed to load mem_stack".to_string()))?; - - let wasm_allocation = mem_stack.write_json(input)?; - - // Call Ribosome's function - let encoded_input: RibosomeEncodingBits = - RibosomeEncodedAllocation::from(wasm_allocation).into(); - let encoded_output: RibosomeEncodingBits = unsafe { - (match self { - $(Dispatch::$enum_variant => $function_name),* - })(encoded_input) - }; - - let result: ZomeApiInternalResult = - load_ribosome_encoded_json(encoded_output).or_else(|e| { - mem_stack.deallocate(wasm_allocation)?; - Err(ZomeApiError::from(e)) - })?; - - // Free result & input allocations - mem_stack.deallocate(wasm_allocation)?; - - // Done - if result.ok { - JsonString::from_json(&result.value) - .try_into() - .map_err(|_| ZomeApiError::from(format!("Failed to deserialize return value: {}", result.value))) - } else { - Err(ZomeApiError::from(result.error)) - } - } - } - - // Invokable functions in the Ribosome - // WARNING Names must be in sync with ZomeAPIFunction in holochain-rust - // WARNING All these fns need to be defined in wasms too @see the hdk integration_test.rs - #[allow(dead_code)] - extern "C" { - pub(crate) fn hc_property(_: RibosomeEncodingBits) -> RibosomeEncodingBits; - pub(crate) fn hc_start_bundle(_: RibosomeEncodingBits) -> RibosomeEncodingBits; - pub(crate) fn hc_close_bundle(_: RibosomeEncodingBits) -> RibosomeEncodingBits; - $( pub(crate) fn $function_name (_: RibosomeEncodingBits) -> RibosomeEncodingBits;) * - } - - /// Add stubs for all core API functions when compiled in test mode. - /// This makes it possible to actually build test executable from zome projects to run unit tests - /// on zome functions (though: without being able to actually test integration with core - that is - /// what we need holochain-nodejs for). - /// - /// Without these stubs we would have unresolved references since the API functions are - /// provided by the Ribosome runtime. - /// - /// Attention: - /// We need to make sure to only add these function stubs when compiling tests - /// BUT NOT when building to a WASM binary to be run in a Holochain instance. - /// Hence the `#[cfg(test)]` which is really important! - #[cfg(test)] - mod tests { - use crate::holochain_core_types::error::{RibosomeEncodedValue, RibosomeEncodingBits}; - - $( #[no_mangle] - pub fn $function_name(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() - }) * - } - - }; - -} - -def_api_fns! { - hc_init_globals, InitGlobals; - hc_commit_entry, CommitEntry; - hc_get_entry, GetEntry; - hc_entry_address, EntryAddress; - hc_query, Query; - hc_update_entry, UpdateEntry; - hc_remove_entry, RemoveEntry; - hc_send, Send; - hc_debug, Debug; - hc_call, Call; - hc_crypto,Crypto; - hc_sign_one_time, SignOneTime; - hc_verify_signature, VerifySignature; - hc_link_entries, LinkEntries; - hc_remove_link, RemoveLink; - hc_get_links, GetLinks; - hc_get_links_count,GetLinksCount; - hc_sleep, Sleep; - hc_meta,Meta; - hc_keystore_list, KeystoreList; - hc_keystore_new_random, KeystoreNewRandom; - hc_keystore_derive_seed, KeystoreDeriveSeed; - hc_keystore_derive_key, KeystoreDeriveKey; - hc_keystore_sign, KeystoreSign; - hc_keystore_get_public_key, KeystoreGetPublicKey; - hc_commit_capability_grant, CommitCapabilityGrant; - hc_commit_capability_claim, CommitCapabilityClaim; - hc_emit_signal, EmitSignal; -} +use holochain_wasmer_guest::*; + +holochain_wasmer_guest::memory_externs!(); + +holochain_wasmer_guest::host_externs!( + hc_debug, + hc_commit_entry, + hc_get_entry, + hc_update_entry, + hc_remove_entry, + hc_init_globals, + hc_call, + hc_link_entries, + hc_get_links, + hc_get_links_count, + hc_query, + hc_entry_address, + hc_send, + hc_sleep, + hc_remove_link, + hc_sign, + hc_encrypt, + hc_decrypt, + hc_sign_one_time, + hc_verify_signature, + hc_keystore_list, + hc_keystore_new_random, + hc_keystore_derive_seed, + hc_keystore_derive_key, + hc_keystore_sign, + hc_keystore_get_public_key, + hc_commit_capability_grant, + hc_commit_capability_claim, + hc_emit_signal, + hc_meta, + hc_timestamp +); //-------------------------------------------------------------------------------------------------- // ZOME API GLOBAL VARIABLES //-------------------------------------------------------------------------------------------------- -/// Internal global for memory usage -pub static mut G_MEM_STACK: Option = None; - lazy_static! { /// Internal global for retrieving all Zome API globals pub(crate) static ref GLOBALS: ZomeApiGlobals = init_globals().unwrap(); diff --git a/crates/hdk/src/api/query.rs b/crates/hdk/src/api/query.rs index 80bacb13cd..e9b792ceb5 100644 --- a/crates/hdk/src/api/query.rs +++ b/crates/hdk/src/api/query.rs @@ -1,11 +1,12 @@ use crate::{ error::{ZomeApiError, ZomeApiResult}, - Dispatch, }; use holochain_persistence_api::cas::content::Address; -use holochain_wasm_utils::api_serialization::{ +use holochain_wasm_types::{ QueryArgs, QueryArgsNames, QueryArgsOptions, QueryResult, }; +use holochain_wasmer_guest::host_call; +use crate::api::hc_query; /// Returns a list of entries from your local source chain that match a given entry type name or names. /// @@ -94,8 +95,8 @@ pub fn query_result( entry_type_names: QueryArgsNames, options: QueryArgsOptions, ) -> ZomeApiResult { - Dispatch::Query.with_input(QueryArgs { + Ok(host_call!(hc_query, QueryArgs { entry_type_names, options, - }) + })?) } diff --git a/crates/hdk/src/api/remove_link.rs b/crates/hdk/src/api/remove_link.rs index b395398027..b160e94fc6 100644 --- a/crates/hdk/src/api/remove_link.rs +++ b/crates/hdk/src/api/remove_link.rs @@ -1,6 +1,8 @@ -use crate::{error::ZomeApiError, Dispatch}; +use crate::{error::ZomeApiError}; use holochain_persistence_api::cas::content::Address; -use holochain_wasm_utils::api_serialization::link_entries::LinkEntriesArgs; +use holochain_wasm_types::link_entries::LinkEntriesArgs; +use holochain_wasmer_guest::host_call; +use crate::api::hc_remove_link; /// Commits a LinkRemove entry to your local source chain that marks a link as 'deleted' by setting /// its status metadata to `Deleted` which gets published to the DHT. @@ -26,8 +28,8 @@ use holochain_wasm_utils::api_serialization::link_entries::LinkEntriesArgs; /// # use holochain_persistence_api::cas::content::Address; /// # use hdk::AGENT_ADDRESS; /// # use hdk::error::ZomeApiResult; -/// # use hdk::holochain_wasm_utils::api_serialization::get_entry::GetEntryOptions; -/// # use hdk::holochain_wasm_utils::api_serialization::get_entry::StatusRequestKind; +/// # use hdk::holochain_wasm_types::get_entry::GetEntryOptions; +/// # use hdk::holochain_wasm_types::get_entry::StatusRequestKind; /// # fn main() { /// /// #[derive(Serialize, Deserialize, Debug, DefaultJson)] @@ -64,10 +66,10 @@ pub fn remove_link>( link_type: S, tag: S, ) -> Result<(), ZomeApiError> { - Dispatch::RemoveLink.with_input(LinkEntriesArgs { + Ok(host_call!(hc_remove_link, LinkEntriesArgs { base: base.clone(), target: target.clone(), link_type: link_type.into(), tag: tag.into(), - }) + })?) } diff --git a/crates/hdk/src/api/send.rs b/crates/hdk/src/api/send.rs index 68147aed23..31347dc2df 100644 --- a/crates/hdk/src/api/send.rs +++ b/crates/hdk/src/api/send.rs @@ -1,7 +1,11 @@ -use crate::{error::ZomeApiResult, Dispatch}; +use crate::{error::ZomeApiResult}; use holochain_core_types::time::Timeout; use holochain_persistence_api::cas::content::Address; -use holochain_wasm_utils::api_serialization::send::{SendArgs, SendOptions}; +use holochain_wasm_types::send::{SendArgs, SendOptions}; +use crate::api::DNA_NAME; +use holochain_wasmer_guest::host_call; +use crate::api::hc_send; +use holochain_json_api::json::RawString; /// Sends a node-to-node message to the given agent, specified by their address. /// Addresses of agents can be accessed using [hdk::AGENT_ADDRESS](struct.AGENT_ADDRESS.html). @@ -27,68 +31,68 @@ use holochain_wasm_utils::api_serialization::send::{SendArgs, SendOptions}; /// # use holochain_json_api::error::JsonError; /// # use holochain_json_api::json::JsonString; /// # use holochain_core_types::error::HolochainError; -/// # use holochain_core_types::error::RibosomeEncodingBits; -/// # use holochain_core_types::error::RibosomeEncodedValue; +/// # use holochain_core_types::error::AllocationPtr; +/// # use holochain_core_types::error::RibosomeReturnValue; /// /// # // Adding empty functions so that the cfg(test) build can link. /// # #[no_mangle] -/// # pub fn hc_init_globals(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_init_globals(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_commit_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_commit_entry(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_get_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_get_entry(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_entry_address(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_entry_address(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_query(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_query(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_call(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_call(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_crypto(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_crypto(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_meta(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_meta(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_sign_one_time(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_sign_one_time(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_verify_signature(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_verify_signature(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_update_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_update_entry(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_remove_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_remove_entry(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_send(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_send(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// /// # #[no_mangle] -/// # pub fn hc_encrypt(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_encrypt(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_sleep(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_sleep(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_debug(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_debug(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_get_links(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_get_links(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_get_links_count(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_get_links_count(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_link_entries(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_link_entries(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_remove_link(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_remove_link(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_list(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_list(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_new_random(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_new_random(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_derive_seed(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_derive_seed(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_derive_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_derive_key(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_sign(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_sign(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_keystore_get_public_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_get_public_key(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_commit_capability_grant(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_commit_capability_grant(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_commit_capability_claim(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_commit_capability_claim(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// # #[no_mangle] -/// # pub fn hc_emit_signal(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_emit_signal(_: AllocationPtr) -> AllocationPtr { RibosomeReturnValue::Success.into() } /// /// # fn main() { /// fn handle_send_message(to_agent: Address, message: String) -> ZomeApiResult { @@ -101,7 +105,7 @@ use holochain_wasm_utils::api_serialization::send::{SendArgs, SendOptions}; /// entries: [] /// /// init: || { Ok(()) } -/// +/// /// validate_agent: |validation_data : EntryValidationData::| { /// Ok(()) /// } @@ -127,10 +131,11 @@ use holochain_wasm_utils::api_serialization::send::{SendArgs, SendOptions}; ///} /// # } /// ``` -pub fn send(to_agent: Address, payload: String, timeout: Timeout) -> ZomeApiResult { - Dispatch::Send.with_input(SendArgs { +pub fn send(to_agent: Address, payload: String, timeout: Timeout) -> ZomeApiResult { + Ok(host_call!(hc_send, SendArgs { to_agent, payload, options: SendOptions(timeout), - }) + zome: DNA_NAME.to_string(), + })?) } diff --git a/crates/hdk/src/api/sign.rs b/crates/hdk/src/api/sign.rs index c91e670de1..eac87f8e62 100644 --- a/crates/hdk/src/api/sign.rs +++ b/crates/hdk/src/api/sign.rs @@ -1,12 +1,15 @@ use crate::error::ZomeApiResult; use holochain_core_types::signature::Provenance; -use holochain_wasm_utils::api_serialization::{ - crypto::{CryptoArgs, CryptoMethod}, +use holochain_wasm_types::{ + wasm_string::{WasmString}, sign::{OneTimeSignArgs, SignOneTimeResult}, verify_signature::VerifySignatureArgs, }; - -use super::Dispatch; +use holochain_wasmer_guest::host_call; +use crate::api::hc_verify_signature; +use crate::api::hc_sign_one_time; +use crate::api::hc_sign; +use holochain_core_types::signature::Signature; /// Signs a string payload using the agent's private key. /// Returns the signature as a string. @@ -31,11 +34,9 @@ use super::Dispatch; /// } /// # } /// ``` -pub fn sign>(payload: S) -> ZomeApiResult { - Dispatch::Crypto.with_input(CryptoArgs { - payload: payload.into(), - method: CryptoMethod::Sign, - }) +pub fn sign>(payload: S) -> ZomeApiResult { + let s: String = payload.into(); + Ok(host_call!(hc_sign, WasmString::from(s))?) } /// Signs a vector of payloads with a private key that is generated and shredded. @@ -55,7 +56,7 @@ pub fn sign>(payload: S) -> ZomeApiResult { /// # use holochain_core_types::error::HolochainError; /// # use holochain_core_types::signature::{Provenance, Signature}; /// # use hdk::error::ZomeApiResult; -/// # use hdk::holochain_wasm_utils::api_serialization::sign::{OneTimeSignArgs, SignOneTimeResult}; +/// # use hdk::holochain_wasm_types::sign::{OneTimeSignArgs, SignOneTimeResult}; /// # fn main() { /// pub fn handle_one_time_sign(key_id: String, message: String) -> ZomeApiResult { /// hdk::sign(message).map(Signature::from) @@ -67,9 +68,9 @@ pub fn sign_one_time>(payloads: Vec) -> ZomeApiResult>( provenance: Provenance, payload: S, ) -> ZomeApiResult { - Dispatch::VerifySignature.with_input(VerifySignatureArgs { + Ok(host_call!(hc_verify_signature, VerifySignatureArgs { provenance, payload: payload.into(), - }) + })?) } diff --git a/crates/hdk/src/api/sleep.rs b/crates/hdk/src/api/sleep.rs index 18cdc9c1b9..e7075154fb 100644 --- a/crates/hdk/src/api/sleep.rs +++ b/crates/hdk/src/api/sleep.rs @@ -1,6 +1,8 @@ -use crate::{error::ZomeApiResult, Dispatch}; -use holochain_json_api::json::JsonString; +use crate::{error::ZomeApiResult}; use std::time::Duration; +use holochain_wasmer_guest::host_call; +use crate::api::hc_sleep; + /// Lets the DNA runtime sleep for the given duration. /// # Examples /// ```rust @@ -20,8 +22,5 @@ use std::time::Duration; /// # } /// ``` pub fn sleep(duration: Duration) -> ZomeApiResult<()> { - let _: ZomeApiResult<()> = Dispatch::Sleep.with_input(JsonString::from(duration.as_nanos())); - // internally returns RibosomeEncodedValue::Success which is a zero length allocation - // return Ok(()) unconditionally instead of the "error" from success - Ok(()) + Ok(host_call!(hc_sleep, duration.as_nanos())?) } diff --git a/crates/hdk/src/api/update_remove.rs b/crates/hdk/src/api/update_remove.rs index 25d6c5c5ae..455ed7e141 100644 --- a/crates/hdk/src/api/update_remove.rs +++ b/crates/hdk/src/api/update_remove.rs @@ -1,10 +1,12 @@ use crate::{ error::{ZomeApiError, ZomeApiResult}, - Dispatch, }; use holochain_core_types::entry::Entry; use holochain_persistence_api::cas::content::Address; -use holochain_wasm_utils::api_serialization::UpdateEntryArgs; +use holochain_wasm_types::UpdateEntryArgs; +use holochain_wasmer_guest::host_call; +use crate::api::hc_remove_entry; +use crate::api::hc_update_entry; /// Commit an entry to your local source chain that "updates" a previous entry, meaning when getting /// the previous entry, the updated entry will be returned. @@ -13,10 +15,10 @@ use holochain_wasm_utils::api_serialization::UpdateEntryArgs; /// The updated entry will hold the previous entry's address in its header, /// which will be used by validation routes. pub fn update_entry(new_entry: Entry, address: &Address) -> ZomeApiResult
{ - Dispatch::UpdateEntry.with_input(UpdateEntryArgs { + Ok(host_call!(hc_update_entry, UpdateEntryArgs { new_entry, address: address.clone(), - }) + })?) } /// NOT YET AVAILABLE @@ -28,5 +30,5 @@ pub fn update_agent() -> ZomeApiResult
{ /// its status metadata to `Deleted` and adding the DeleteEntry's address in the deleted entry's /// metadata, which will be used by validation routes. pub fn remove_entry(address: &Address) -> ZomeApiResult
{ - Dispatch::RemoveEntry.with_input(address.to_owned()) + Ok(host_call!(hc_remove_entry, address.to_owned())?) } diff --git a/crates/hdk/src/api/version.rs b/crates/hdk/src/api/version.rs index b4d46ac97f..9e03625fb4 100644 --- a/crates/hdk/src/api/version.rs +++ b/crates/hdk/src/api/version.rs @@ -1,8 +1,9 @@ use crate::{ error::{ZomeApiError, ZomeApiResult}, - Dispatch, }; -use holochain_wasm_utils::api_serialization::meta::{MetaArgs, MetaMethod, MetaResult}; +use holochain_wasm_types::meta::{MetaArgs, MetaMethod, MetaResult}; +use holochain_wasmer_guest::host_call; +use crate::api::hc_meta; /// Returns the current `version` of the HDK as "semver" value (eg. "1.2.3-alpha4"), or /// `version_hash`, a 32-byte MD5 of the holochain-rust source, dependencies and build environment, @@ -10,7 +11,7 @@ use holochain_wasm_utils::api_serialization::meta::{MetaArgs, MetaMethod, MetaRe /// `out` or `HDK_HASH` environment variable is not supplied during build), a hash consisting of all /// "0" is returned. pub fn version() -> ZomeApiResult { - let meta = Dispatch::Meta.with_input(MetaArgs { + let meta = host_call!(hc_meta, MetaArgs { method: MetaMethod::Version, })?; let version = match meta { @@ -23,7 +24,7 @@ pub fn version() -> ZomeApiResult { } pub fn version_hash() -> ZomeApiResult { - let meta = Dispatch::Meta.with_input(MetaArgs { + let meta = host_call!(hc_meta, MetaArgs { method: MetaMethod::Hash, })?; let hash = match meta { diff --git a/crates/hdk/src/entry_definition.rs b/crates/hdk/src/entry_definition.rs index 89828eedfb..aa23932ba9 100644 --- a/crates/hdk/src/entry_definition.rs +++ b/crates/hdk/src/entry_definition.rs @@ -6,17 +6,19 @@ use holochain_core_types::{ agent::AgentId, dna::entry_types::EntryTypeDef, entry::{entry_type::EntryType, AppEntryValue, Entry}, - validation::{EntryValidationData, LinkValidationData, ValidationPackageDefinition}, + validation::{ + EntryValidationData, LinkValidationData, ValidationPackageDefinition, ValidationResult, + }, }; -use holochain_wasm_utils::api_serialization::validation::LinkDirection; +use holochain_wasm_types::validation::LinkDirection; use std::convert::TryFrom; pub type PackageCreator = Box ValidationPackageDefinition + Sync>; -pub type Validator = Box) -> Result<(), String> + Sync>; +pub type Validator = Box) -> ValidationResult + Sync>; -pub type AgentValidator = Box) -> Result<(), String> + Sync>; -pub type LinkValidator = Box Result<(), String> + Sync>; +pub type AgentValidator = Box) -> ValidationResult + Sync>; +pub type LinkValidator = Box ValidationResult + Sync>; /// This struct represents a complete entry type definition. /// It wraps [EntryTypeDef](holochain_core_types::dna::entry_types::EntryTypeDef) defined in the DNA crate @@ -220,10 +222,16 @@ macro_rules! entry { $package_creator }); - let validator = Box::new(|validation_data: $crate::holochain_wasm_utils::holochain_core_types::validation::EntryValidationData<$crate::holochain_core_types::entry::Entry>| { - let $validation_data = $crate::entry_definition::entry_to_native_type::<$native_type>(validation_data.clone())?; + let validator = Box::new(|validation_data: $crate::holochain_core_types::validation::EntryValidationData<$crate::holochain_core_types::entry::Entry>| { + let $validation_data = match $crate::entry_definition::entry_to_native_type::<$native_type>(validation_data.clone()) { + Ok(v) => v, + Err(e) => return e.into(), + }; use std::convert::TryFrom; - let e_type = $crate::holochain_core_types::entry::entry_type::EntryType::try_from(validation_data)?; + let e_type = match $crate::holochain_core_types::entry::entry_type::EntryType::try_from(validation_data) { + Ok(v) => v, + Err(e) => return e.into(), + }; match e_type { $crate::holochain_core_types::entry::entry_type::EntryType::App(_) => { $entry_validation @@ -233,7 +241,7 @@ macro_rules! entry { $entry_validation } _ => { - Err(String::from("Schema validation failed"))? + return ValidationResult::Fail("Schema validation failed".into()); } } }); @@ -292,7 +300,7 @@ macro_rules! link { $package_creator }); - let validator = Box::new(|validation_data: $crate::holochain_wasm_utils::holochain_core_types::validation::LinkValidationData| { + let validator = Box::new(|validation_data: $crate::holochain_core_types::validation::LinkValidationData| { let $validation_data = validation_data; $link_validation }); diff --git a/crates/hdk/src/error.rs b/crates/hdk/src/error.rs index 9e4cabda74..41d565bd29 100644 --- a/crates/hdk/src/error.rs +++ b/crates/hdk/src/error.rs @@ -1,14 +1,14 @@ //! This file contains defitions for Zome errors and also Zome Results. -use crate::holochain_core_types::error::{HolochainError, RibosomeErrorCode}; - -use crate::holochain_persistence_api::error::PersistenceError; +use crate::{ + holochain_core_types::error::HolochainError, holochain_persistence_api::error::PersistenceError, +}; use holochain_json_api::{error::JsonError, json::JsonString}; use holochain_json_derive::DefaultJson; +use holochain_wasmer_guest::*; use serde_derive::{Deserialize, Serialize}; - -use holochain_wasm_utils::memory::allocation::AllocationError; use std::{error::Error, fmt}; +use holochain_core_types::validation::ValidationResult; /// Error for DNA developers to use in their Zome code. /// This does not have to be sent back to Ribosome unless its an InternalError. @@ -16,17 +16,25 @@ use std::{error::Error, fmt}; pub enum ZomeApiError { Internal(String), FunctionNotImplemented, - HashNotFound, - ValidationFailed(String), Timeout, } +impl From for ValidationResult { + fn from(e: ZomeApiError) -> Self { + match e { + // any abitrary zome string is a fail + ZomeApiError::Internal(s) => Self::Fail(s), + ZomeApiError::FunctionNotImplemented => Self::NotImplemented, + ZomeApiError::Timeout => Self::Timeout, + } + } +} + impl From for HolochainError { fn from(zome_api_error: ZomeApiError) -> Self { match zome_api_error { - ZomeApiError::ValidationFailed(s) => HolochainError::ValidationFailed(s), ZomeApiError::Timeout => HolochainError::Timeout, - _ => HolochainError::RibosomeFailed(zome_api_error.to_string()), + _ => HolochainError::Wasm(WasmError::Zome(zome_api_error.to_string())), } } } @@ -40,7 +48,6 @@ impl From for String { impl From for ZomeApiError { fn from(holochain_error: HolochainError) -> Self { match holochain_error { - HolochainError::ValidationFailed(s) => ZomeApiError::ValidationFailed(s), HolochainError::Timeout => ZomeApiError::Timeout, _ => ZomeApiError::Internal(holochain_error.to_string()), } @@ -73,29 +80,6 @@ impl From for ZomeApiError { } } -impl From for ZomeApiError { - fn from(ribosome_error_code: RibosomeErrorCode) -> ZomeApiError { - ZomeApiError::from(ribosome_error_code.to_string()) - } -} - -impl From for ZomeApiError { - fn from(allocation_error: AllocationError) -> ZomeApiError { - match allocation_error { - AllocationError::OutOfBounds => { - ZomeApiError::Internal("Allocation out of bounds".into()) - } - AllocationError::ZeroLength => ZomeApiError::Internal("Allocation zero length".into()), - AllocationError::BadStackAlignment => { - ZomeApiError::Internal("Allocation out of alignment with stack".into()) - } - AllocationError::Serialization => { - ZomeApiError::Internal("Allocation serialization failure".into()) - } - } - } -} - impl Error for ZomeApiError {} impl fmt::Display for ZomeApiError { @@ -103,8 +87,6 @@ impl fmt::Display for ZomeApiError { match self { ZomeApiError::Internal(msg) => write!(f, "{}", msg), ZomeApiError::FunctionNotImplemented => write!(f, "Function not implemented"), - ZomeApiError::HashNotFound => write!(f, "Hash not found"), - ZomeApiError::ValidationFailed(msg) => write!(f, "{}", msg), ZomeApiError::Timeout => write!(f, "Timeout"), } } diff --git a/crates/hdk/src/global_fns.rs b/crates/hdk/src/global_fns.rs deleted file mode 100644 index ffef8e5509..0000000000 --- a/crates/hdk/src/global_fns.rs +++ /dev/null @@ -1,38 +0,0 @@ -//! This file contains small helper functions relating to WASM memory management -//! and serialization used throughout the HDK. - -use crate::api::G_MEM_STACK; -use holochain_core_types::error::RibosomeEncodingBits; -use holochain_json_api::json::JsonString; -pub use holochain_wasm_utils::api_serialization::validation::*; -use holochain_wasm_utils::memory::{ - allocation::{AllocationError, AllocationResult, WasmAllocation}, - stack::WasmStack, -}; -use std::convert::{TryFrom, TryInto}; - -/// Init global memory stack -pub fn init_global_memory(initial_allocation: WasmAllocation) -> AllocationResult { - unsafe { - G_MEM_STACK = Some(WasmStack::try_from(initial_allocation)?); - } - Ok(initial_allocation) -} - -/// sugar -pub fn init_global_memory_from_ribosome_encoding( - encoded_value: RibosomeEncodingBits, -) -> AllocationResult { - init_global_memory(WasmAllocation::try_from_ribosome_encoding(encoded_value)?) -} - -/// Serialize output as json in WASM memory -pub fn write_json>(jsonable: J) -> AllocationResult { - let mut mem_stack = unsafe { - match G_MEM_STACK { - Some(mem_stack) => mem_stack, - None => return Err(AllocationError::BadStackAlignment), - } - }; - mem_stack.write_json(jsonable) -} diff --git a/crates/hdk/src/init_globals.rs b/crates/hdk/src/init_globals.rs index e0cad95f6e..9986c2a586 100644 --- a/crates/hdk/src/init_globals.rs +++ b/crates/hdk/src/init_globals.rs @@ -2,19 +2,22 @@ //! which initializes the Zome API Globals with the values it receives from the Ribosome. //! It is automatically called at startup of each Zome function call. -use crate::{api::Dispatch, error::ZomeApiResult}; -use holochain_core_types::error::RibosomeEncodingBits; -use holochain_wasm_utils::api_serialization::ZomeApiGlobals; +use crate::{error::ZomeApiResult}; +use holochain_wasm_types::ZomeApiGlobals; +use holochain_wasmer_guest::AllocationPtr; +use holochain_wasmer_guest::host_call; +// use crate::debug; #[allow(dead_code)] extern "C" { - pub fn hc_init_globals( - encoded_allocation_of_input: RibosomeEncodingBits, - ) -> RibosomeEncodingBits; + pub fn hc_init_globals(_: AllocationPtr) -> AllocationPtr; } // HC INIT GLOBALS - Secret Api Function // Retrieve all the public global values from the ribosome pub(crate) fn init_globals() -> ZomeApiResult { - Dispatch::InitGlobals.with_input(0) + // let r = host_call!(hc_init_globals, ()); + // debug(format!("{:?}", r)).ok(); + // Ok(r?) + Ok(host_call!(hc_init_globals, ())?) } diff --git a/crates/hdk/src/lib.rs b/crates/hdk/src/lib.rs index 376e4d1966..ca1c3433b8 100644 --- a/crates/hdk/src/lib.rs +++ b/crates/hdk/src/lib.rs @@ -20,22 +20,22 @@ pub use holochain_core_types; pub use holochain_json_api; pub use holochain_json_derive; pub use holochain_persistence_api; -pub use holochain_wasm_utils; +pub use holochain_wasm_types; pub use pretty_assertions; pub use serde; pub use serde_derive; pub use serde_json; +pub use holochain_wasmer_guest; pub mod api; pub mod utils; #[macro_use] pub mod entry_definition; pub mod error; -pub mod global_fns; pub mod init_globals; pub mod macros; -pub use holochain_wasm_utils::api_serialization::{validation::*, THIS_INSTANCE}; +pub use holochain_wasm_types::{validation::*, THIS_INSTANCE}; pub mod meta; pub mod prelude; diff --git a/crates/hdk/src/macros.rs b/crates/hdk/src/macros.rs index 8edf6c322d..05d00868d6 100644 --- a/crates/hdk/src/macros.rs +++ b/crates/hdk/src/macros.rs @@ -1,43 +1,5 @@ //! 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: @@ -70,7 +32,6 @@ macro_rules! load_string { /// # 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::{ @@ -78,64 +39,64 @@ macro_rules! load_string { /// validation::EntryValidationData /// }; /// # use holochain_persistence_api::cas::content::Address; -/// # use holochain_core_types::error::RibosomeEncodingBits; +/// # use holochain_core_types::error::AllocationPtr; /// # // Adding empty functions so that the cfg(test) build can link. /// # #[no_mangle] -/// # pub fn hc_init_globals(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_init_globals(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_commit_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_commit_entry(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_get_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_get_entry(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_entry_address(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_entry_address(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_query(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_query(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_update_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_update_entry(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_remove_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_remove_entry(_: AllocationPtr) -> AllocationPtr { ret!(())); } /// # #[no_mangle] -/// # pub fn hc_send(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_send(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_sleep(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_sleep(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_debug(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_debug(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_call(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_call(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// #[no_mangle] -/// # pub fn hc_crypto(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_crypto(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// #[no_mangle] -/// # pub fn hc_meta(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_meta(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_sign_one_time(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_sign_one_time(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_verify_signature(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_verify_signature(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_get_links(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_get_links(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_get_links_count(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_get_links_count(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_link_entries(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_link_entries(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_remove_link(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_remove_link(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_keystore_list(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_list(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_keystore_new_random(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_new_random(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_keystore_derive_seed(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_derive_seed(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_keystore_derive_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_derive_key(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_keystore_sign(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_sign(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_keystore_get_public_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_keystore_get_public_key(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_commit_capability_grant(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_commit_capability_grant(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_commit_capability_claim(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_commit_capability_claim(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// # #[no_mangle] -/// # pub fn hc_emit_signal(_: RibosomeEncodingBits) -> RibosomeEncodingBits { RibosomeEncodedValue::Success.into() } +/// # pub fn hc_emit_signal(_: AllocationPtr) -> AllocationPtr { ret!(()); } /// /// # fn main() { /// @@ -187,7 +148,7 @@ macro_rules! load_string { /// init: || { /// Ok(()) /// } -/// +/// /// validate_agent: |validation_data : EntryValidationData::| { /// Ok(()) /// } @@ -267,70 +228,36 @@ macro_rules! define_zome { zd.define($entry_expr); )* - let validator = Box::new(|validation_data: hdk::holochain_wasm_utils::holochain_core_types::validation::EntryValidationData| { + let validator = Box::new(|validation_data: $crate::holochain_core_types::validation::EntryValidationData| { let $agent_validation_param = validation_data; - $agent_validation_expr + let result: $crate::holochain_core_types::validation::ValidationResult = $agent_validation_expr; + result }); 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(); - } + pub extern "C" fn init(host_allocation_ptr: holochain_wasmer_guest::AllocationPtr) -> holochain_wasmer_guest::AllocationPtr { - fn execute() -> Result<(), String> { + fn execute() -> $crate::holochain_core_types::callback::CallbackResult { $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(), - } + ret!(execute()); } $( #[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); + pub extern "C" fn receive(host_allocation_ptr: holochain_wasmer_guest::AllocationPtr) -> holochain_wasmer_guest::AllocationPtr { + let input: $crate::holochain_wasm_types::receive::ReceiveParams = holochain_wasmer_guest::host_args!(host_allocation_ptr); - fn execute(input: $crate::holochain_wasm_utils::api_serialization::receive::ReceiveParams ) -> String { + fn execute(input: $crate::holochain_wasm_types::receive::ReceiveParams ) -> CallbackResult { 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() + ret!(&execute(input)); } )* @@ -426,18 +353,13 @@ macro_rules! define_zome { $( #[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(); - } + pub extern "C" fn $zome_function_name(host_allocation_ptr: holochain_wasmer_guest::AllocationPtr) -> holochain_wasmer_guest::AllocationPtr { + // Hack to detect empty params + let mut params = false; + $( + let _ = stringify!($input_param_name); + params = true; + )* // Macro'd InputStruct #[derive(Deserialize, Serialize, Debug, $crate::holochain_json_derive::DefaultJson)] @@ -446,7 +368,18 @@ macro_rules! define_zome { } // Deserialize input - let input: InputStruct = load_json!(encoded_allocation_of_input); + let input: InputStruct = { + if params { + holochain_wasmer_guest::host_args!(host_allocation_ptr) + } else { + // hack to build an empty InputStruct when there are no input params + match InputStruct::try_from(JsonString::from_json("{}")) { + Ok(v) => v, + // this should never happen + Err(e) => ret_err!("failed to create an empty InputStruct from empty JsonString"), + } + } + }; // Macro'd function body fn execute (params: InputStruct) -> $( $output_param_type )* { @@ -455,9 +388,7 @@ macro_rules! define_zome { $handler_path($($input_param_name),*) } - $crate::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result( - $crate::global_fns::write_json(execute(input)) - ).into() + ret!(execute(input)); } )* }; diff --git a/crates/hdk/src/meta.rs b/crates/hdk/src/meta.rs index 8f25b1682e..45bae21f70 100644 --- a/crates/hdk/src/meta.rs +++ b/crates/hdk/src/meta.rs @@ -2,48 +2,25 @@ //! but not every developer should have to write them. A notable function defined here is //! __hdk_get_json_definition which allows Holochain to retrieve JSON defining the Zome. -use crate::{ - api::G_MEM_STACK, - entry_definition::{AgentValidator, ValidatingEntryType}, -}; +use crate::prelude::*; +use crate::entry_definition::{AgentValidator, ValidatingEntryType}; use holochain_core_types::{ dna::{ - entry_types::{deserialize_entry_types, serialize_entry_types}, - zome::{ZomeEntryTypes, ZomeFnDeclarations, ZomeTraits}, + zome::{ZomeFnDeclarations, ZomeTraits, PartialZome}, }, entry::entry_type::{AppEntryType, EntryType}, - error::{RibosomeEncodedValue, RibosomeEncodingBits}, }; -use holochain_json_derive::DefaultJson; -use serde_derive::{Deserialize, Serialize}; - -use holochain_json_api::{error::JsonError, json::JsonString}; -use holochain_wasm_utils::{ - api_serialization::validation::{ - AgentIdValidationArgs, EntryValidationArgs, LinkValidationArgs, LinkValidationPackageArgs, - }, - holochain_core_types::error::RibosomeErrorCode, - memory::{ - allocation::AllocationError, - ribosome::{load_ribosome_encoded_json, return_code_for_allocation_result}, - }, +use holochain_wasm_types::validation::{ + AgentIdValidationArgs, EntryValidationArgs, LinkValidationArgs, LinkValidationPackageArgs, }; +use holochain_wasmer_guest::*; use std::{collections::BTreeMap, convert::TryFrom}; trait Ribosome { fn define_entry_type(&mut self, name: String, entry_type: ValidatingEntryType); } -#[derive(Debug, Serialize, Deserialize, DefaultJson, Default)] -struct PartialZome { - #[serde(serialize_with = "serialize_entry_types")] - #[serde(deserialize_with = "deserialize_entry_types")] - entry_types: ZomeEntryTypes, - traits: ZomeTraits, - fn_declarations: ZomeFnDeclarations, -} - #[allow(improper_ctypes)] #[derive(Default)] pub struct ZomeDefinition { @@ -71,259 +48,127 @@ extern "C" { fn zome_setup(zd: &mut ZomeDefinition); fn __list_traits() -> ZomeTraits; fn __list_functions() -> ZomeFnDeclarations; -} -#[no_mangle] -pub extern "C" fn __hdk_get_validation_package_for_entry_type( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { - let allocation = match crate::global_fns::init_global_memory_from_ribosome_encoding( - encoded_allocation_of_input, - ) { - Ok(allocation) => allocation, - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - }; + // memory stuff + fn __import_allocation(guest_allocation_ptr: AllocationPtr, host_allocation_ptr: AllocationPtr); + fn __import_bytes(host_allocation_ptr: AllocationPtr, guest_bytes_ptr: Ptr); +} +fn zome_definition() -> ZomeDefinition { let mut zd = ZomeDefinition::new(); unsafe { zome_setup(&mut zd) }; + zd +} - let name = allocation.read_to_string(); +#[no_mangle] +pub extern "C" fn __hdk_get_validation_package_for_entry_type( + host_allocation_ptr: AllocationPtr, +) -> AllocationPtr { + let name: RawString = host_args!(host_allocation_ptr); + let name = String::from(name); - match zd + match zome_definition() .entry_types .into_iter() .find(|ref validating_entry_type| { validating_entry_type.name == EntryType::App(AppEntryType::from(name.clone())) }) { - None => RibosomeEncodedValue::Failure(RibosomeErrorCode::CallbackFailed).into(), Some(mut entry_type_definition) => { - let package = (*entry_type_definition.package_creator)(); - return_code_for_allocation_result(crate::global_fns::write_json(package)).into() - } - } + ret!((*entry_type_definition.package_creator)()); + }, + None => ret!(WasmResult::Err(WasmError::CallbackFailed)), + }; } #[no_mangle] -pub extern "C" fn __hdk_validate_app_entry( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { - if let Err(allocation_error) = - crate::global_fns::init_global_memory_from_ribosome_encoding(encoded_allocation_of_input) - { - return allocation_error.as_ribosome_encoding(); - } - - let mut zd = ZomeDefinition::new(); - unsafe { zome_setup(&mut zd) }; - +pub extern "C" fn __hdk_validate_app_entry(host_allocation_ptr: AllocationPtr) -> AllocationPtr { // Deserialize input - let input: EntryValidationArgs = match load_ribosome_encoded_json(encoded_allocation_of_input) { - Ok(v) => v, - Err(e) => return RibosomeEncodedValue::from(e).into(), - }; + let input: EntryValidationArgs = host_args!(host_allocation_ptr); - let entry_type = match EntryType::try_from(input.validation_data.clone()) { - Ok(v) => v, - Err(e) => return RibosomeEncodedValue::from(e).into(), - }; + let entry_type = try_result!( + EntryType::try_from(input.validation_data.clone()), + "Failed to deserialize EntryType" + ); - match zd + match zome_definition() .entry_types .into_iter() .find(|ref validating_entry_type| validating_entry_type.name == entry_type) { - None => RibosomeErrorCode::CallbackFailed as RibosomeEncodingBits, + None => holochain_wasmer_guest::json::to_allocation_ptr(WasmResult::Err(WasmError::CallbackFailed).into()), Some(mut entry_type_definition) => { - let validation_result = (*entry_type_definition.validator)(input.validation_data); - - match validation_result { - Ok(()) => RibosomeEncodedValue::Success.into(), - Err(fail_string) => return_code_for_allocation_result( - crate::global_fns::write_json(JsonString::from_json(&fail_string)), - ) - .into(), - } + ret!((*entry_type_definition.validator)(input.validation_data)); } } } #[no_mangle] -pub extern "C" fn __hdk_validate_agent_entry( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { - if let Err(allocation_error) = - crate::global_fns::init_global_memory_from_ribosome_encoding(encoded_allocation_of_input) - { - return allocation_error.as_ribosome_encoding(); - } - - let mut zd = ZomeDefinition::new(); - unsafe { zome_setup(&mut zd) }; +pub extern "C" fn __hdk_validate_agent_entry(host_allocation_ptr: AllocationPtr) -> AllocationPtr { + let input: AgentIdValidationArgs = host_args!(host_allocation_ptr); //get the validator code - let mut validator = match zd.agent_entry_validator { - None => { - return return_code_for_allocation_result(crate::global_fns::write_json( - JsonString::from_json("No agent validation callback registered for zome."), - )) - .into(); - } - Some(v) => v, - }; - - // Deserialize input - let input: AgentIdValidationArgs = match load_ribosome_encoded_json(encoded_allocation_of_input) - { - Ok(v) => v, - Err(e) => return RibosomeEncodedValue::from(e).into(), - }; + let mut validator = try_result!( + (zome_definition().agent_entry_validator).ok_or(()), + "No agent validation callback registered for zome." + ); - let validation_result = (*validator)(input.validation_data); - - match validation_result { - Ok(()) => RibosomeEncodedValue::Success.into(), - Err(fail_string) => return_code_for_allocation_result(crate::global_fns::write_json( - JsonString::from_json(&fail_string), - )) - .into(), - } + ret!((*validator)(input.validation_data)); } #[no_mangle] pub extern "C" fn __hdk_get_validation_package_for_link( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { - if let Err(allocation_error) = - crate::global_fns::init_global_memory_from_ribosome_encoding(encoded_allocation_of_input) - { - return allocation_error.as_ribosome_encoding(); - }; + host_allocation_ptr: AllocationPtr, +) -> AllocationPtr { + let input: LinkValidationPackageArgs = host_args!(host_allocation_ptr); - let mut zd = ZomeDefinition::new(); - unsafe { zome_setup(&mut zd) }; - - let input: LinkValidationPackageArgs = - match load_ribosome_encoded_json(encoded_allocation_of_input) { - Ok(v) => v, - Err(e) => return RibosomeEncodedValue::from(e).into(), - }; - - RibosomeEncodingBits::from( - zd.entry_types - .into_iter() - .find(|ref validation_entry_type| { - validation_entry_type.name == EntryType::from(input.entry_type.clone()) - }) - .and_then(|entry_type| { - entry_type.links.into_iter().find(|ref link_definition| { - link_definition.link_type == input.link_type - && link_definition.direction == input.direction - }) - }) - .and_then(|mut link_definition| { - let package = (*link_definition.package_creator)(); - Some(return_code_for_allocation_result( - crate::global_fns::write_json(package), - )) + ret!(zome_definition() + .entry_types + .into_iter() + .find(|ref validation_entry_type| { + validation_entry_type.name == EntryType::from(input.entry_type.clone()) + }) + .and_then(|entry_type| { + entry_type.links.into_iter().find(|ref link_definition| { + link_definition.link_type == input.link_type + && link_definition.direction == input.direction }) - .unwrap_or(RibosomeEncodedValue::Failure( - RibosomeErrorCode::CallbackFailed, - )), - ) + }) + .and_then(|mut link_definition| { Some((*link_definition.package_creator)()) })); } #[no_mangle] -pub extern "C" fn __hdk_validate_link( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { - if let Err(allocation_error) = - crate::global_fns::init_global_memory_from_ribosome_encoding(encoded_allocation_of_input) - { - return allocation_error.as_ribosome_encoding(); - }; +pub extern "C" fn __hdk_validate_link(host_allocation_ptr: AllocationPtr) -> AllocationPtr { + let input: LinkValidationArgs = host_args!(host_allocation_ptr); - let mut zd = ZomeDefinition::new(); - unsafe { zome_setup(&mut zd) } - - let input: LinkValidationArgs = match load_ribosome_encoded_json(encoded_allocation_of_input) { - Ok(v) => v, - Err(e) => return RibosomeEncodedValue::from(e).into(), - }; - - RibosomeEncodingBits::from( - zd.entry_types - .into_iter() - .find(|ref validation_entry_type| { - validation_entry_type.name == EntryType::from(input.entry_type.clone()) - }) - .and_then(|entry_type_definition| { - entry_type_definition - .links - .into_iter() - .find(|link_definition| { - link_definition.link_type == *input.link.link_type() - && link_definition.direction == input.direction - }) - }) - .and_then(|mut link_definition| { - let validation_result = (*link_definition.validator)(input.validation_data); - Some(match validation_result { - Ok(()) => RibosomeEncodedValue::Success, - Err(fail_string) => return_code_for_allocation_result( - crate::global_fns::write_json(JsonString::from_json(&fail_string)), - ), + ret!(zome_definition() + .entry_types + .into_iter() + .find(|ref validation_entry_type| { + validation_entry_type.name == EntryType::from(input.entry_type.clone()) + }) + .and_then(|entry_type_definition| { + entry_type_definition + .links + .into_iter() + .find(|link_definition| { + link_definition.link_type == *input.link.link_type() + && link_definition.direction == input.direction }) - }) - .unwrap_or(RibosomeEncodedValue::Failure( - RibosomeErrorCode::CallbackFailed, - )), - ) + }) + .and_then(|mut link_definition| { + Some((*link_definition.validator)(input.validation_data)) + })); } #[no_mangle] -pub extern "C" fn __hdk_hdk_version( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { - if let Err(allocation_error) = - crate::global_fns::init_global_memory_from_ribosome_encoding(encoded_allocation_of_input) - { - return allocation_error.as_ribosome_encoding(); - } - - let mut mem_stack = unsafe { - match G_MEM_STACK { - Some(mem_stack) => mem_stack, - None => { - return AllocationError::BadStackAlignment.as_ribosome_encoding(); - } - } - }; - - return_code_for_allocation_result( - mem_stack.write_string( - holochain_core_types::hdk_version::HDK_VERSION - .to_string() - .as_ref(), - ), - ) - .into() +pub extern "C" fn __hdk_hdk_version(_: AllocationPtr) -> AllocationPtr { + ret!(WasmString::from(holochain_core_types::hdk_version::HDK_VERSION.to_string())) } #[no_mangle] -pub extern "C" fn __hdk_get_json_definition( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { - if let Err(allocation_error) = - crate::global_fns::init_global_memory_from_ribosome_encoding(encoded_allocation_of_input) - { - return allocation_error.as_ribosome_encoding(); - } - - let mut zd = ZomeDefinition::new(); - unsafe { zome_setup(&mut zd) }; - +pub extern "C" fn __hdk_get_json_definition(_: AllocationPtr) -> AllocationPtr { let mut entry_types = BTreeMap::new(); - for validating_entry_type in zd.entry_types { + for validating_entry_type in zome_definition().entry_types { entry_types.insert( validating_entry_type.name, validating_entry_type.entry_type_definition, @@ -333,24 +178,11 @@ pub extern "C" fn __hdk_get_json_definition( let traits = unsafe { __list_traits() }; let fn_declarations = unsafe { __list_functions() }; - let partial_zome = PartialZome { - entry_types, - traits, - fn_declarations, - }; - - let json_string = JsonString::from(partial_zome); - - let mut mem_stack = unsafe { - match G_MEM_STACK { - Some(mem_stack) => mem_stack, - None => { - return AllocationError::BadStackAlignment.as_ribosome_encoding(); - } - } - }; - - return_code_for_allocation_result(mem_stack.write_string(&String::from(json_string))).into() + ret!(PartialZome::new( + &entry_types, + &traits, + &fn_declarations, + )); } #[cfg(test)] @@ -398,7 +230,7 @@ pub mod tests { }, validation: |_validation_data: hdk::EntryValidationData| { - Ok(()) + ValidationResult::Ok } ); @@ -407,10 +239,11 @@ pub mod tests { validating_entry_type.entry_type_definition, ); - let partial_zome = PartialZome { - entry_types, - ..Default::default() - }; + let partial_zome = PartialZome::new( + &entry_types, + &Default::default(), + &Default::default(), + ); assert_eq!( JsonString::from(partial_zome), diff --git a/crates/hdk/src/prelude.rs b/crates/hdk/src/prelude.rs index e8d9786cbc..86889bd38f 100644 --- a/crates/hdk/src/prelude.rs +++ b/crates/hdk/src/prelude.rs @@ -3,34 +3,49 @@ //! by simply adding use hdk::prelude::*; // macros -pub use crate::{define_zome, entry, from, link, load_json, to}; +pub use crate::{define_zome, entry, from, link, to}; // derive macros pub use holochain_json_derive::DefaultJson; pub use serde_derive::{Deserialize, Serialize}; +pub use std::convert::{TryInto, TryFrom}; +pub use holochain_wasmer_guest::*; // types pub use crate::{ + DNA_ADDRESS, + AGENT_ADDRESS, + DNA_NAME, + AGENT_ID_STR, + CAPABILITY_REQ, + PROPERTIES, entry_definition::ValidatingEntryType, error::{ZomeApiError, ZomeApiResult}, holochain_core_types::{ agent::AgentId, dna::entry_types::Sharing, - entry::{entry_type::EntryType, Entry}, + dna::capabilities::CapabilityRequest, + entry::{entry_type::EntryType, entry_type::AppEntryType, Entry, AppEntryValue}, error::HolochainError, link::LinkMatch, network::query::{Pagination, SizePagination, SortOrder, TimePagination}, time::Iso8601, + validation::ValidationResult, + callback::CallbackResult, }, - holochain_json_api::{error::JsonError, json::JsonString}, + holochain_json_api::{error::JsonError, json::JsonString, json::RawString}, holochain_persistence_api::cas::content::{Address, AddressableContent}, - holochain_wasm_utils::api_serialization::{ + holochain_wasm_types::{ + wasm_string::WasmString, commit_entry::CommitEntryOptions, get_entry::{ EntryHistory, GetEntryOptions, GetEntryResult, GetEntryResultType, StatusRequestKind, }, get_links::{GetLinksOptions, GetLinksResult, GetLinksResultCount, LinksStatusRequestKind}, - QueryArgsOptions, QueryResult, + QueryArgsOptions, QueryResult, QueryArgsNames, + }, + holochain_wasmer_guest::{ + ret, }, EntryValidationData, LinkValidationData, ValidationPackageDefinition, }; diff --git a/crates/hdk/tests/entry.rs b/crates/hdk/tests/entry.rs index 93455ce171..103dd6bab8 100644 --- a/crates/hdk/tests/entry.rs +++ b/crates/hdk/tests/entry.rs @@ -8,13 +8,12 @@ extern crate test_utils; #[macro_use] extern crate serde_json; extern crate hdk; -extern crate holochain_wasm_utils; +use hdk::prelude::*; use hdk::error::ZomeApiResult; use holochain_core_types::{ entry::Entry, - error::{RibosomeEncodedValue, RibosomeEncodingBits}, }; use holochain_json_api::json::JsonString; @@ -23,10 +22,9 @@ use holochain_persistence_api::{ hash::HashString, }; -use holochain_wasm_utils::api_serialization::get_entry::{GetEntryResult, StatusRequestKind}; -use std::path::PathBuf; +use holochain_wasm_types::get_entry::{GetEntryResult, StatusRequestKind}; use test_utils::{ - empty_string_validation_fail_entry, example_valid_entry, example_valid_entry_address, + example_valid_entry, example_valid_entry_address, example_valid_entry_params, example_valid_entry_result, make_test_call, start_holochain_instance, wait_for_zome_result, }; @@ -35,178 +33,178 @@ use test_utils::{ // These empty function definitions below are needed for the windows linker // #[no_mangle] -pub fn hc_init_globals(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_init_globals(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_commit_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_commit_entry(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_get_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_get_entry(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_entry_address(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_entry_address(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_query(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_query(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_update_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_update_entry(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_remove_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_remove_entry(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_send(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_send(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_encrypt(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_encrypt(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_property(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_property(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_debug(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_debug(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_call(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_call(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_crypto(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_crypto(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_meta(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_meta(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_sign_one_time(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_sign_one_time(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_verify_signature(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_verify_signature(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_link_entries(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_link_entries(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_get_links(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_get_links(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_get_links_count(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_get_links_count(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_start_bundle(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_start_bundle(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_close_bundle(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_close_bundle(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_sleep(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_sleep(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn zome_setup(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn zome_setup(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn __list_traits(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn __list_traits(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn __list_functions(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn __list_functions(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_remove_link(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_remove_link(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_list(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_list(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_new_random(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_new_random(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_derive_seed(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_derive_seed(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_derive_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_derive_key(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_sign(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_sign(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_get_public_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_get_public_key(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_commit_capability_grant(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_commit_capability_grant(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_commit_capability_claim(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_commit_capability_claim(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_emit_signal(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_emit_signal(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[test] @@ -266,20 +264,20 @@ pub fn test_bad_entry() { #[test] fn can_round_trip() { - let (mut hc, test_logger, _) = start_holochain_instance("can_round_trip", "alice"); - let result = make_test_call( - &mut hc, - "send_tweet", - r#"{ "author": "bob", "content": "had a boring day" }"#, - ); - assert_eq!( - result.unwrap(), - JsonString::from_json("{\"first\":\"bob\",\"second\":\"had a boring day\"}"), - ); - - let test_logger = test_logger.lock().unwrap(); - - println!("{:?}", *test_logger); + let (mut _hc, _test_logger, _) = start_holochain_instance("can_round_trip", "alice"); + // let result = make_test_call( + // &mut hc, + // "send_tweet", + // r#"{ "author": "bob", "content": "had a boring day" }"#, + // ); + // assert_eq!( + // result.unwrap(), + // JsonString::from_json("{\"first\":\"bob\",\"second\":\"had a boring day\"}"), + // ); + // + // let test_logger = test_logger.lock().unwrap(); + // + // println!("{:?}", *test_logger); } #[test] @@ -366,37 +364,11 @@ fn can_commit_entry() { "check_commit_entry", &String::from(JsonString::from(example_valid_entry())), ); + let expected: ZomeApiResult
= Ok(example_valid_entry_address()); println!("\t result = {:?}", result); assert!(result.is_ok(), "result = {:?}", result); assert_eq!( result.unwrap(), - JsonString::from(example_valid_entry_address()), - ); -} -#[test] -fn can_return_empty_string_as_validation_fail() { - let (mut hc, _, _) = - start_holochain_instance("can_return_empty_string_as_validation_fail", "alice"); - - // Call the exposed wasm function that calls the Commit API function - let result = make_test_call( - &mut hc, - "check_commit_entry", - &String::from(JsonString::from(empty_string_validation_fail_entry())), + JsonString::from(expected), ); - let path = PathBuf::new() - .join("crates") - .join("core") - .join("src") - .join("wasm_engine") - .join("runtime.rs"); - let path_string = path - .as_path() - .to_str() - .expect("path should have been created"); - let formatted_path_string = path_string.replace("\\", &vec!["\\", "\\", "\\", "\\"].join("")); - let expected_substr = format!("{{\"Internal\":\"{{\\\"kind\\\":{{\\\"ValidationFailed\\\":\\\"\\\"}},\\\"file\\\":\\\"{}\\\"",formatted_path_string); - let result_str = result.unwrap().to_string(); - - assert!(result_str.contains(&expected_substr)); } diff --git a/crates/hdk/tests/links.rs b/crates/hdk/tests/links.rs index ca0cf985f1..d093b820f9 100644 --- a/crates/hdk/tests/links.rs +++ b/crates/hdk/tests/links.rs @@ -4,21 +4,20 @@ extern crate holochain_core; extern crate holochain_core_types; extern crate holochain_json_api; extern crate holochain_persistence_api; -extern crate holochain_wasm_utils; extern crate tempfile; extern crate test_utils; +use hdk::prelude::*; use hdk::error::{ZomeApiError, ZomeApiResult}; use holochain_core_types::{ crud_status::CrudStatus, - error::{HolochainError, RibosomeEncodedValue, RibosomeEncodingBits}, }; use holochain_core_types::error::CoreError; use holochain_persistence_api::{cas::content::Address, hash::HashString}; -use holochain_wasm_utils::api_serialization::get_links::{GetLinksResult, LinksResult}; +use holochain_wasm_types::get_links::{GetLinksResult, LinksResult}; use test_utils::{ assert_zome_internal_errors_equivalent, generate_zome_internal_error, make_test_call, @@ -29,178 +28,178 @@ use test_utils::{ // These empty function definitions below are needed for the windows linker // #[no_mangle] -pub fn hc_init_globals(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_init_globals(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_commit_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_commit_entry(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_get_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_get_entry(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_entry_address(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_entry_address(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_query(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_query(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_update_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_update_entry(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_remove_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_remove_entry(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_send(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_send(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_encrypt(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_encrypt(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_property(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_property(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_debug(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_debug(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_call(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_call(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_crypto(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_crypto(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_meta(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_meta(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_sign_one_time(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_sign_one_time(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_verify_signature(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_verify_signature(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_link_entries(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_link_entries(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_get_links(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_get_links(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_get_links_count(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_get_links_count(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_start_bundle(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_start_bundle(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_close_bundle(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_close_bundle(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_sleep(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_sleep(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn zome_setup(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn zome_setup(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn __list_traits(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn __list_traits(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn __list_functions(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn __list_functions(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_remove_link(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_remove_link(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_list(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_list(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_new_random(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_new_random(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_derive_seed(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_derive_seed(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_derive_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_derive_key(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_sign(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_sign(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_get_public_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_get_public_key(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_commit_capability_grant(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_commit_capability_grant(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_commit_capability_claim(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_commit_capability_claim(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_emit_signal(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_emit_signal(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[test] @@ -324,7 +323,7 @@ fn can_validate_links() { let core_error: CoreError = serde_json::from_str(&error).unwrap(); assert_eq!( core_error.kind, - HolochainError::ValidationFailed("Target stuff is not longer".to_string()), + HolochainError::ValidationFailed(ValidationResult::Fail("Target stuff is not longer".to_string())), ); } else { assert!(false); diff --git a/crates/hdk/tests/misc.rs b/crates/hdk/tests/misc.rs index 4bcea33c02..2ee7a2b688 100755 --- a/crates/hdk/tests/misc.rs +++ b/crates/hdk/tests/misc.rs @@ -9,20 +9,18 @@ extern crate url; #[macro_use] extern crate serde_json; extern crate hdk; -extern crate holochain_wasm_utils; -use hdk::error::ZomeApiResult; +use hdk::prelude::*; use holochain_core::signal::{Signal, UserSignal}; use holochain_core_types::{ entry::{entry_type::test_app_entry_type, Entry}, - error::{RibosomeEncodedValue, RibosomeEncodingBits}, }; use holochain_json_api::json::JsonString; use holochain_persistence_api::{ - cas::content::{Address, AddressableContent}, hash::HashString, + cas::content::{Address, AddressableContent}, }; use std::{env, path::PathBuf}; @@ -34,178 +32,178 @@ use test_utils::{ // These empty function definitions below are needed for the windows linker // #[no_mangle] -pub fn hc_init_globals(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_init_globals(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_commit_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_commit_entry(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_get_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_get_entry(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_entry_address(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_entry_address(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_query(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_query(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_update_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_update_entry(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_remove_entry(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_remove_entry(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_send(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_send(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_encrypt(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_encrypt(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_property(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_property(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_debug(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_debug(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_call(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_call(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_crypto(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_crypto(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_meta(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_meta(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_sign_one_time(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_sign_one_time(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_verify_signature(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_verify_signature(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_link_entries(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_link_entries(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_get_links(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_get_links(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_get_links_count(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_get_links_count(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_start_bundle(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_start_bundle(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_close_bundle(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_close_bundle(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_sleep(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_sleep(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn zome_setup(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn zome_setup(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn __list_traits(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn __list_traits(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn __list_functions(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn __list_functions(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_remove_link(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_remove_link(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_list(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_list(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_new_random(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_new_random(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_derive_seed(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_derive_seed(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_derive_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_derive_key(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_sign(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_sign(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_keystore_get_public_key(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_keystore_get_public_key(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_commit_capability_grant(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_commit_capability_grant(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_commit_capability_claim(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_commit_capability_claim(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[no_mangle] -pub fn hc_emit_signal(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - RibosomeEncodedValue::Success.into() +pub fn hc_emit_signal(_: AllocationPtr) -> AllocationPtr { + ret!(()); } #[test] @@ -363,30 +361,27 @@ fn can_check_sys_entry_address() { #[test] fn can_check_call() { - //let (mut hc, _) = start_holochain_instance("can_check_call", "alice"); + let (mut hc, _, _) = start_holochain_instance("can_check_call", "alice"); - //let result = make_test_call(&mut hc, "check_call", r#"{}"#); - //assert!(result.is_ok(), "result = {:?}", result); - - //let inner_expected: ZomeApiResult
= Ok(Address::from( - // "QmSbNw63sRS4VEmuqFBd7kJT6V9pkEpMRMY2LWvjNAqPcJ", - //)); - //let expected: ZomeApiResult = - // Ok(ZomeApiInternalResult::success(inner_expected)); + let result = make_test_call(&mut hc, "check_call", r#"{}"#); + assert!(result.is_ok(), "result = {:?}", result); + let inner_expected: ZomeApiResult = Ok(HashString::from( + "xyz".to_string(), + )); - //assert_eq!(result.unwrap(), JsonString::from(expected),); + assert_eq!(result.unwrap(), JsonString::from(inner_expected),); } #[test] fn can_check_call_with_args() { - //let (mut hc, _) = start_holochain_instance("can_check_call_with_args", "alice"); + // let (mut hc, _, _) = start_holochain_instance("can_check_call_with_args", "alice"); - //let result =make_test_call(&mut hc, + // let result = make_test_call(&mut hc, // "check_call_with_args", // &String::from(JsonString::empty_object()), - //); - //println!("\t result = {:?}", result); - //assert!(result.is_ok(), "\t result = {:?}", result); + // ); + // println!("\t result = {:?}", result); + // assert!(result.is_ok(), "\t result = {:?}", result); //let expected_inner: ZomeApiResult
= Ok(Address::from( // "QmefcRdCAXM2kbgLW2pMzqWhUvKSDvwfFSVkvmwKvBQBHd", @@ -459,7 +454,7 @@ fn show_env() { let dna_address_string = dna.address().to_string(); let dna_address = dna_address_string.as_str(); let format = format!( - r#"{{"Ok":{{"dna_name":"TestApp","dna_address":"{}","agent_id":"{{\"nick\":\"show_env\",\"pub_sign_key\":\"HcSCIBgTFMzn8vz5ogz5eW87h9nf5eqpdsJOKJ47ZRDopz74HihmraGXio74e6i\"}}","agent_address":"HcSCIBgTFMzn8vz5ogz5eW87h9nf5eqpdsJOKJ47ZRDopz74HihmraGXio74e6i","cap_request":{{"cap_token":"QmNa15k7quxkQFY18LHZFgBJjUKksBEeHdvKedbkc411jz","provenance":["HcSCIBgTFMzn8vz5ogz5eW87h9nf5eqpdsJOKJ47ZRDopz74HihmraGXio74e6i","FxhnQJzPu+TPqJHCtT2e5CNMky2YnnLXtABMJyNhx5SyztyeuKU/zxS4a1e8uKdPYT5N0ldCcLgpITeHfB7dAg=="]}},"properties":"{{}}"}}}}"#, + r#"{{"Ok":{{"dna_name":"TestApp","dna_address":"{}","agent_id":"{{\"nick\":\"show_env\",\"pub_sign_key\":\"HcSCIBgTFMzn8vz5ogz5eW87h9nf5eqpdsJOKJ47ZRDopz74HihmraGXio74e6i\"}}","agent_address":"HcSCIBgTFMzn8vz5ogz5eW87h9nf5eqpdsJOKJ47ZRDopz74HihmraGXio74e6i","cap_request":{{"cap_token":"QmacQtFc5wsprnWqRNxZKBaWjjqdj2Cyp9haU5y4qwKQLw","provenance":["HcSCIBgTFMzn8vz5ogz5eW87h9nf5eqpdsJOKJ47ZRDopz74HihmraGXio74e6i","FxhnQJzPu+TPqJHCtT2e5CNMky2YnnLXtABMJyNhx5SyztyeuKU/zxS4a1e8uKdPYT5N0ldCcLgpITeHfB7dAg=="]}},"properties":"{{}}"}}}}"#, dna_address ); let json_result = Ok(JsonString::from_json(&format)); diff --git a/crates/hdk/wasm-test/Cargo.toml b/crates/hdk/wasm-test/Cargo.toml index f3f7e6f255..78f8f040b8 100644 --- a/crates/hdk/wasm-test/Cargo.toml +++ b/crates/hdk/wasm-test/Cargo.toml @@ -14,10 +14,10 @@ members = [] [dependencies] hdk = { path = ".." } -holochain_wasm_utils = { path = "../../wasm_utils" } +holochain_wasm_types = { path = "../../wasm_types" } serde = "=1.0.104" serde_derive = "=1.0.104" serde_json = { version = "=1.0.47", features = ["preserve_order"] } boolinator = "=2.4.0" holochain_json_derive = "=0.0.23" - +holochain_wasmer_guest = "=0.0.18" diff --git a/crates/hdk/wasm-test/src/lib.rs b/crates/hdk/wasm-test/src/lib.rs index 71c0ef7745..6d62cc912a 100755 --- a/crates/hdk/wasm-test/src/lib.rs +++ b/crates/hdk/wasm-test/src/lib.rs @@ -1,53 +1,16 @@ -#[macro_use] extern crate hdk; -extern crate holochain_wasm_utils; +extern crate holochain_wasm_types; extern crate serde; extern crate serde_json; -#[macro_use] extern crate serde_derive; extern crate boolinator; -#[macro_use] extern crate holochain_json_derive; +extern crate holochain_wasmer_guest; - -use boolinator::Boolinator; -use hdk::{ - AGENT_ADDRESS, - DNA_ADDRESS, - DNA_NAME, - AGENT_ID_STR, - PROPERTIES, - CAPABILITY_REQ, - api::G_MEM_STACK, - error::{ZomeApiError, ZomeApiResult}, - global_fns::init_global_memory, -}; -use holochain_wasm_utils::{ - api_serialization::{ - get_entry::{GetEntryOptions, GetEntryResult}, - get_links::{GetLinksResult,GetLinksOptions,LinksStatusRequestKind}, - query::{QueryArgsNames, QueryArgsOptions, QueryResult}, - }, - holochain_core_types::{ - dna::{entry_types::Sharing,capabilities::CapabilityRequest}, - entry::{ - entry_type::{AppEntryType, EntryType}, - AppEntryValue, Entry, - }, - error::{RibosomeEncodedValue, RibosomeEncodingBits, RibosomeErrorCode}, - validation::{EntryValidationData, LinkValidationData}, - link::LinkMatch, - }, - holochain_persistence_api::{ - cas::content::{Address, AddressableContent}, - }, - holochain_json_api::{error::JsonError, json::{JsonString, RawString}}, - memory::{ - allocation::WasmAllocation, - ribosome::{load_ribosome_encoded_json, return_code_for_allocation_result}, - }, -}; -use std::{convert::TryFrom, time::Duration}; +use hdk::prelude::*; +use std::time::Duration; +use hdk::holochain_core_types::signature::Signature; +use holochain_wasm_types::holochain_persistence_api::hash::HashString; #[derive(Deserialize, Serialize, Default,Clone, Debug, DefaultJson)] pub struct TestEntryType { @@ -65,7 +28,7 @@ struct EntryStruct { } #[no_mangle] -pub extern "C" fn handle_check_global() -> Address { +pub extern "C" fn handle_check_global() -> HashString { hdk::AGENT_LATEST_HASH.clone() } @@ -106,43 +69,18 @@ pub fn handle_test_emit_signal(message: String) -> ZomeApiResult<()> { #[no_mangle] pub extern "C" fn check_commit_entry( - encoded_allocation_of_input: RibosomeEncodingBits, -) -> RibosomeEncodingBits { - let allocation = match WasmAllocation::try_from_ribosome_encoding(encoded_allocation_of_input) { - Ok(allocation) => allocation, - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - }; - - let memory_init_result = init_global_memory(allocation); - if memory_init_result.is_err() { - return return_code_for_allocation_result(memory_init_result).into(); - } - - // Deserialize and check for an encoded error - let entry: Entry = match load_ribosome_encoded_json(encoded_allocation_of_input) { - Ok(entry) => entry, - Err(hc_err) => { - hdk::debug(format!("ERROR: {:?}", hc_err.to_string())).ok(); - return RibosomeEncodedValue::Failure(RibosomeErrorCode::ArgumentDeserializationFailed) - .into(); - } - }; + host_allocation_ptr: AllocationPtr, +) -> AllocationPtr { + let entry: Entry = host_args!(host_allocation_ptr); hdk::debug(format!("Entry: {:?}", entry)).ok(); let res = hdk::commit_entry(&entry.into()); - let res_obj: JsonString = match res { + ret!(WasmResult::Ok(match res { Ok(hash) => hash.into(), Err(e) => e.into(), - }; - - let mut wasm_stack = match unsafe { G_MEM_STACK } { - Some(wasm_stack) => wasm_stack, - None => return RibosomeEncodedValue::Failure(RibosomeErrorCode::OutOfMemory).into(), - }; - - return_code_for_allocation_result(wasm_stack.write_json(res_obj)).into() + })) } fn handle_check_commit_entry_macro(entry: Entry) -> ZomeApiResult
{ @@ -250,7 +188,7 @@ fn handle_links_roundtrip_create() -> ZomeApiResult
{ pub fn handle_create_tagged_entry(content: String, tag: String) -> Address { - + let test_entry_to_create_1 = Entry::App( "testEntryType".into(), TestEntryType { @@ -274,7 +212,7 @@ pub fn handle_create_tagged_entry(content: String, tag: String) -> Address { pub fn handle_create_tagged_entry_bad_link(content: String, tag: String) -> ZomeApiResult<()> { - + let test_entry_to_create_1 = Entry::App( "testEntryType".into(), TestEntryType { @@ -310,7 +248,7 @@ pub fn handle_create_priv_entry(content: String) -> ZomeApiResult
{ pub fn handle_delete_tagged_entry(content: String, tag: String) -> ZomeApiResult<()> { - + let test_entry_to_create_1 = Entry::App( "testEntryType".into(), TestEntryType { @@ -325,7 +263,7 @@ pub fn handle_delete_tagged_entry(content: String, tag: String) -> ZomeApiResult } .into(), ); - + hdk::remove_link(&test_entry_to_create_1.address(), &test_entry_to_create_2.address(), "intergration test", tag.as_ref())?; Ok(()) } @@ -491,16 +429,17 @@ fn handle_check_app_entry_address() -> ZomeApiResult
{ // json!({"result": "FIXME"}).into() // } -fn handle_check_call() -> ZomeApiResult { - let empty_dumpty = JsonString::empty_object(); - hdk::debug(format!("empty_dumpty = {:?}", empty_dumpty))?; +fn handle_check_call_inner() -> ZomeApiResult { + Ok(HashString::from("xyz")) +} - let maybe_hash = hdk::call( +fn handle_check_call() -> ZomeApiResult { + let maybe_hash: ZomeApiResult = hdk::call( hdk::THIS_INSTANCE, "test_zome", Address::from(hdk::PUBLIC_TOKEN.to_string()), - "check_app_entry_address", - empty_dumpty, + "check_call_inner", + (), ); hdk::debug(format!("maybe_hash = {:?}", maybe_hash))?; @@ -609,13 +548,11 @@ fn handle_hash(content:String) ->ZomeApiResult
)) } - - fn hdk_test_entry() -> Entry { Entry::App(hdk_test_app_entry_type(), hdk_test_entry_value()) } -fn handle_send_message(to_agent: Address, message: String) -> ZomeApiResult { +fn handle_send_message(to_agent: Address, message: String) -> ZomeApiResult { hdk::send(to_agent, message, 60000.into()) } @@ -625,8 +562,6 @@ fn handle_sleep() -> ZomeApiResult<()> { pub fn handle_my_entries_by_tag(tag:Option,maybe_status : Option) -> ZomeApiResult { - - let test_entry_to_create = Entry::App( "testEntryType".into(), TestEntryType { @@ -643,9 +578,9 @@ pub fn handle_my_entries_by_tag(tag:Option,maybe_status : Option ZomeApiResult { } .into(), ); - + hdk::get_links_with_options( &test_entry_to_create.address(), LinkMatch::Exactly("intergration test"), @@ -701,7 +636,7 @@ pub fn handle_get_version(hash: Option) -> ZomeApiResult } } -pub fn handle_sign_payload(payload: String) -> ZomeApiResult +pub fn handle_sign_payload(payload: String) -> ZomeApiResult { hdk::sign(payload) } @@ -718,14 +653,18 @@ define_zome! { }, validation: |valida: hdk::EntryValidationData| { + hdk::debug(format!("entries validation {:?}", valida)).ok(); match valida { EntryValidationData::Create{entry:test_entry,validation_data:_} => { - (test_entry.stuff != "FAIL").ok_or_else(|| "FAIL content is not allowed".to_string()) - + if test_entry.stuff != "FAIL" { + ValidationResult::Ok + } else { + ValidationResult::Fail("FAIL content is not allowed".into()) + } }, - _=> Ok(()), + _=> ValidationResult::Ok, } @@ -739,7 +678,7 @@ define_zome! { hdk::ValidationPackageDefinition::ChainFull }, validation: |validation_data: hdk::LinkValidationData | { - Ok(()) + ValidationResult::Ok } ), from!( @@ -749,7 +688,7 @@ define_zome! { hdk::ValidationPackageDefinition::ChainFull }, validation: | validation_data: hdk::LinkValidationData | { - Ok(()) + ValidationResult::Ok } ), to!( @@ -759,7 +698,7 @@ define_zome! { hdk::ValidationPackageDefinition::ChainFull }, validation: | validation_data: hdk::LinkValidationData | { - Ok(()) + ValidationResult::Ok } ) ] @@ -778,11 +717,15 @@ define_zome! { { EntryValidationData::Create{entry:test_entry,validation_data:_} => { - - Err(serde_json::to_string(&test_entry).unwrap()) + // EntryValidationData::Create is always a fail, we just need to build an + // error string for it + ValidationResult::Fail(match serde_json::to_string(&test_entry) { + Ok(v) => v, + Err(e) => e.to_string(), + }) }, - _ => Ok(()) + _ => ValidationResult::Ok, } } ), @@ -796,7 +739,7 @@ define_zome! { }, validation: |validation_data: hdk::EntryValidationData| { - Ok(()) + ValidationResult::Ok } ), @@ -809,7 +752,7 @@ define_zome! { }, validation: |validation_data: hdk::EntryValidationData| { - Err("".to_string()) + ValidationResult::Fail(String::new()) } ), @@ -823,7 +766,7 @@ define_zome! { }, validation: |validation_data: hdk::EntryValidationData| { - Ok(()) + ValidationResult::Ok }, links: [ @@ -842,31 +785,40 @@ define_zome! { if link.link().tag()=="muffins" { - Err("invalid tag".into()) + ValidationResult::Fail("invalid tag".into()) } else { let base = link.link().base(); let target = link.link().target(); - let base = match hdk::get_entry(&base)? { - Some(entry) => match entry { - Entry::App(_, test_entry) => TestEntryType::try_from(test_entry)?, - _ => Err("System entry found")? + let base = match hdk::get_entry(&base) { + Ok(Some(entry)) => match entry { + Entry::App(_, test_entry) => match TestEntryType::try_from(test_entry) { + Ok(v) => v, + Err(e) => return ValidationResult::Fail(e.into()), + }, + _ => return ValidationResult::Fail("System entry found".into()), }, - None => Err("Base not found")?, + _ => return ValidationResult::UnresolvedDependencies(vec![base.clone()]), }; - let target = match hdk::get_entry(&target)? { - Some(entry) => match entry { - Entry::App(_, test_entry) => TestEntryType::try_from(test_entry)?, - _ => Err("System entry found")?, + let target = match hdk::get_entry(&target) { + Ok(Some(entry)) => match entry { + Entry::App(_, test_entry) => match TestEntryType::try_from(test_entry) { + Ok(v) => v, + Err(e) => return ValidationResult::Fail(e.into()), + }, + _ => return ValidationResult::Fail("System entry found".into()), } - None => Err("Target not found")?, + _ => return ValidationResult::UnresolvedDependencies(vec![target.clone()]), }; - (target.stuff.len() > base.stuff.len()) - .ok_or("Target stuff is not longer".to_string()) + if target.stuff.len() > base.stuff.len() { + ValidationResult::Ok + } else { + ValidationResult::Fail("Target stuff is not longer".into()) + } } - + } ) @@ -875,44 +827,57 @@ define_zome! { ] init: || {{ + // should be able to commit an entry - let entry = Entry::App( + let _entry = Entry::App( "testEntryType".into(), EntryStruct { stuff: "called from init".into(), } .into(), ); - let addr = hdk::commit_entry(&entry)?; - - // should be able to get the entry - let get_result = hdk::get_entry(&addr)?.unwrap(); - if !(entry == get_result) { - return Err("Could not retrieve the same entry in init".into()); - } - - // should be able to access globals - let _agent_addr: Address = AGENT_ADDRESS.to_string().into(); - let _dna_hash: Address = DNA_ADDRESS.to_string().into(); - - // TODO should we allow messages sent to self? - // should be able to call hdk::send, will timeout immedietly but that is ok -// let _send_result = hdk::send(agent_addr, "".to_string(), 10000.into())?; - - // should be able to call other zome funcs - let _call_result = hdk::call( - hdk::THIS_INSTANCE, - "test_zome", - Address::from(hdk::PUBLIC_TOKEN.to_string()), - "check_app_entry_address", - JsonString::empty_object(), - )?; - - Ok(()) + // let _addr = match hdk::commit_entry(&entry) { + // Ok(v) => v, + // Err(e) => { + // hdk::debug(e.clone()).ok(); + // return CallbackResult::Fail(e.into()) + // } + // }; + CallbackResult::Pass + +// // should be able to get the entry +// let get_result = match hdk::get_entry(&addr){ +// Ok(Some(result)) => result, +// Ok(None) => return CallbackResult::Fail("Could not get the entry".into()), +// Err(e) => return CallbackResult::Fail(e.into()), +// }; +// if !(entry == get_result) { +// return CallbackResult::Fail("Could not retrieve the same entry in init".into()); +// } +// +// // should be able to access globals +// let _agent_addr: Address = AGENT_ADDRESS.to_string().into(); +// let _dna_hash: Address = DNA_ADDRESS.to_string().into(); +// +// // TODO should we allow messages sent to self? +// // should be able to call hdk::send, will timeout immedietly but that is ok +// // let _send_result = hdk::send(agent_addr, "".to_string(), 10000.into())?; +// +// // should be able to call other zome funcs +// match hdk::call( +// hdk::THIS_INSTANCE, +// "test_zome", +// Address::from(hdk::PUBLIC_TOKEN.to_string()), +// "check_app_entry_address", +// JsonString::empty_object(), +// ) { +// Ok(_) => CallbackResult::Pass, +// Err(e) => CallbackResult::Fail(e.into()), +// } }} validate_agent: |validation_data : EntryValidationData::| { - Ok(()) + ValidationResult::Ok } receive: |_from, payload| { @@ -924,10 +889,10 @@ define_zome! { } .into(), ); - match hdk::commit_entry(&entry) { + CallbackResult::ReceiveResult(match hdk::commit_entry(&entry) { Ok(address) => format!("Committed: '{}' / address: {}", payload, address.to_string()), Err(error) => format!("Error committing in receive: '{}'", error.to_string()), - } + }) } } @@ -1004,9 +969,15 @@ define_zome! { handler: handle_link_tag_validation } + check_call_inner: { + inputs: | |, + outputs: |result: ZomeApiResult|, + handler: handle_check_call_inner + } + check_call: { inputs: | |, - outputs: |result: ZomeApiResult|, + outputs: |result: ZomeApiResult|, handler: handle_check_call } @@ -1061,7 +1032,7 @@ define_zome! { send_message: { inputs: |to_agent: Address, message: String|, - outputs: |response: ZomeApiResult|, + outputs: |response: ZomeApiResult|, handler: handle_send_message } @@ -1137,10 +1108,10 @@ define_zome! { sign_payload: { inputs: |payload: String|, - outputs: |version: ZomeApiResult|, + outputs: |version: ZomeApiResult|, handler: handle_sign_payload } - + ] traits: {} diff --git a/crates/hdk_v2/src/code_generators/init.rs b/crates/hdk_v2/src/code_generators/init.rs index 5307ff2311..f50c338ec5 100644 --- a/crates/hdk_v2/src/code_generators/init.rs +++ b/crates/hdk_v2/src/code_generators/init.rs @@ -8,15 +8,15 @@ impl ZomeCodeDef { quote! { #[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 = hdk::holochain_wasm_utils::memory::allocation::WasmAllocation::try_from_ribosome_encoding(encoded_allocation_of_input); + pub extern "C" fn init(host_allocation_ptr: hdk::holochain_core_types::error::AllocationPtr) -> hdk::holochain_core_types::error::AllocationPtr { + let maybe_allocation = hdk::holochain_wasm_engine::memory::allocation::WasmAllocation::try_from_ribosome_encoding(host_allocation_ptr); let allocation = match maybe_allocation { Ok(allocation) => allocation, - Err(allocation_error) => return hdk::holochain_core_types::error::RibosomeEncodedValue::from(allocation_error).into(), + Err(allocation_error) => return hdk::holochain_core_types::error::RibosomeReturnValue::from(allocation_error).into(), }; let init = hdk::global_fns::init_global_memory(allocation); if init.is_err() { - return hdk::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result( + return hdk::holochain_wasm_engine::memory::ribosome::return_code_for_allocation_result( init ).into(); } @@ -26,10 +26,10 @@ impl ZomeCodeDef { } match execute() { - Ok(_) => hdk::holochain_core_types::error::RibosomeEncodedValue::Success.into(), - Err(e) => hdk::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result( + Ok(_) => hdk::holochain_core_types::error::RibosomeReturnValue::Success.into(), + Err(e) => hdk::holochain_wasm_engine::memory::ribosome::return_code_for_allocation_result( hdk::global_fns::write_json( - hdk::holochain_wasm_utils::holochain_json_api::json::RawString::from(e) + hdk::holochain_wasm_engine::holochain_json_api::json::RawString::from(e) ) ).into(), } diff --git a/crates/hdk_v2/src/code_generators/receive_callback.rs b/crates/hdk_v2/src/code_generators/receive_callback.rs index dc89bfea47..214b97039d 100644 --- a/crates/hdk_v2/src/code_generators/receive_callback.rs +++ b/crates/hdk_v2/src/code_generators/receive_callback.rs @@ -16,33 +16,16 @@ impl ZomeCodeDef { quote! { #( #[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 = hdk::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 = hdk::global_fns::init_global_memory(allocation); - if init.is_err() { - return hdk::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result( - init - ).into(); - } - - // Deserialize input - let input = load_json!(encoded_allocation_of_input); + pub extern "C" fn receive(host_allocation_ptr: $crate::holochain_wasmer_guest::AllocationPtr) -> $crate::holochain_wasmer_guest::AllocationPtr { + let input: $crate::hdk::holochain_wasm_types::receive::ReceiveParams = $crate::holochain_wasmer_guest::host_args!(host_allocation_ptr); - fn execute(input: hdk::holochain_wasm_utils::api_serialization::receive::ReceiveParams) -> String { + fn execute(input: $crate::hdk::holochain_wasm_types::receive::ReceiveParams) -> String { let #receive_from = input.from; let #receive_param = input.payload; #receive_blocks } - hdk::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result( - hdk::global_fns::write_json( - JsonString::from_json(&execute(input)) - ) - ).into() + $crate::holochain_wasmer_guest::ret!($crate::hdk::holochain_wasm_engine::holochain_json_string::json::RawString::from(execute(input))); } )* } diff --git a/crates/hdk_v2/src/code_generators/zome_setup.rs b/crates/hdk_v2/src/code_generators/zome_setup.rs index ae1ff88af5..0f36a2cf5e 100644 --- a/crates/hdk_v2/src/code_generators/zome_setup.rs +++ b/crates/hdk_v2/src/code_generators/zome_setup.rs @@ -20,7 +20,7 @@ impl ZomeCodeDef { #( zd.define(#entry_fn_idents ()); )* - let validator = Box::new(|validation_data: hdk::holochain_wasm_utils::holochain_core_types::validation::EntryValidationData| { + let validator = Box::new(|validation_data: hdk::holochain_wasm_engine::holochain_core_types::validation::EntryValidationData| { let #agent_validation_param = validation_data; #agent_validation_expr }); diff --git a/crates/hdk_v2/src/to_tokens.rs b/crates/hdk_v2/src/to_tokens.rs index 4da9703a34..01662d26e6 100644 --- a/crates/hdk_v2/src/to_tokens.rs +++ b/crates/hdk_v2/src/to_tokens.rs @@ -28,7 +28,7 @@ impl ToTokens for ZomeFunction { tokens.extend(quote!{ #[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 { + pub extern "C" fn #zome_function_name(host_allocation_ptr: hdk::holochain_core_types::error::AllocationPtr) -> hdk::holochain_core_types::error::AllocationPtr { use hdk::{ holochain_json_api::{ json::JsonString, @@ -36,18 +36,6 @@ impl ToTokens for ZomeFunction { }, }; - let maybe_allocation = hdk::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 = hdk::global_fns::init_global_memory(allocation); - if init.is_err() { - return hdk::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result( - init - ).into(); - } - // Macro'd InputStruct #[derive(Deserialize, Serialize, Debug, hdk::holochain_json_derive::DefaultJson)] struct InputStruct { @@ -55,7 +43,7 @@ impl ToTokens for ZomeFunction { } // Deserialize input - let input: InputStruct = hdk::load_json!(encoded_allocation_of_input); + let input: InputStruct = holochain_wasmer_guest::host_args!(host_allocation_ptr); // Macro'd function body fn execute (params: InputStruct) #output_param_type { @@ -63,9 +51,7 @@ impl ToTokens for ZomeFunction { #function_body } - hdk::holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result( - hdk::global_fns::write_json(execute(input)) - ).into() + ret!(execute(input).into()); } }) } diff --git a/crates/metrics/src/config.rs b/crates/metrics/src/config.rs index f027844a42..4383cac696 100644 --- a/crates/metrics/src/config.rs +++ b/crates/metrics/src/config.rs @@ -1,6 +1,6 @@ use crate::{ - cloudwatch::CloudWatchLogger, logger::LoggerMetricPublisher, MetricPublisher, - NEW_RELIC_LICENSE_KEY, + cloudwatch::CloudWatchLogger, logger::LoggerMetricPublisher, MetricPublisher, NEW_RELIC_LICENSE_KEY, + }; use holochain_locksmith::RwLock; use std::sync::Arc; diff --git a/crates/wasm_utils/Cargo.toml b/crates/wasm_types/Cargo.toml similarity index 56% rename from crates/wasm_utils/Cargo.toml rename to crates/wasm_types/Cargo.toml index e3d7f6c07d..5f17e1d72f 100644 --- a/crates/wasm_utils/Cargo.toml +++ b/crates/wasm_types/Cargo.toml @@ -1,23 +1,21 @@ [package] -name = "holochain_wasm_utils" +name = "holochain_wasm_types" version = "0.0.43-alpha3" -description = "holochain wasm utils" +authors = ["Holochain Core Dev Team "] +edition = "2018" +description = "Specialised types to allow wasm host/guest to work for holochain" +keywords = ["holochain", "holo", "p2p", "network", "simulation"] license = "GPL-3.0-only" -homepage = "https://github.com/holochain/holochain-rust" +readme = "README.md" documentation = "https://github.com/holochain/holochain-rust" -authors = ["Holochain Core Dev Team "] +repository = "https://github.com/holochain/holochain-rust" [dependencies] -serde = "=1.0.104" -serde_derive = "=1.0.104" -serde_json = { version = "=1.0.47", features = ["preserve_order"] } holochain_core_types = { version = "=0.0.43-alpha3", path = "../core_types" } -holochain_json_derive = "=0.0.23" -holochain_persistence_api = "=0.0.17" holochain_json_api = "=0.0.23" - -[dev-dependencies] -test_utils = { version = "=0.0.43-alpha3", path = "../../test_utils" } -holochain_core = { version = "=0.0.43-alpha3", path = "../core" } -holochain_conductor_lib = { version = "=0.0.43-alpha3", path = "../conductor_lib" } -tempfile = "=3.0.7" +holochain_persistence_api = "=0.0.17" +serde_derive = "=1.0.104" +serde = "=1.0.104" +holochain_json_derive = "=0.0.23" +serde_json = { version = "=1.0.47", features = ["preserve_order"] } +holochain_wasmer_guest = "=0.0.18" diff --git a/crates/wasm_utils/LICENSE b/crates/wasm_types/LICENSE similarity index 100% rename from crates/wasm_utils/LICENSE rename to crates/wasm_types/LICENSE diff --git a/crates/wasm_utils/src/api_serialization/call.rs b/crates/wasm_types/src/call.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/call.rs rename to crates/wasm_types/src/call.rs diff --git a/crates/wasm_utils/src/api_serialization/capabilities.rs b/crates/wasm_types/src/capabilities.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/capabilities.rs rename to crates/wasm_types/src/capabilities.rs diff --git a/crates/wasm_utils/src/api_serialization/commit_entry.rs b/crates/wasm_types/src/commit_entry.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/commit_entry.rs rename to crates/wasm_types/src/commit_entry.rs diff --git a/crates/wasm_utils/src/api_serialization/crypto.rs b/crates/wasm_types/src/crypto.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/crypto.rs rename to crates/wasm_types/src/crypto.rs diff --git a/crates/wasm_utils/src/api_serialization/emit_signal.rs b/crates/wasm_types/src/emit_signal.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/emit_signal.rs rename to crates/wasm_types/src/emit_signal.rs diff --git a/crates/wasm_utils/src/api_serialization/get_entry.rs b/crates/wasm_types/src/get_entry.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/get_entry.rs rename to crates/wasm_types/src/get_entry.rs diff --git a/crates/wasm_utils/src/api_serialization/get_links.rs b/crates/wasm_types/src/get_links.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/get_links.rs rename to crates/wasm_types/src/get_links.rs diff --git a/crates/wasm_utils/src/api_serialization/keystore.rs b/crates/wasm_types/src/keystore.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/keystore.rs rename to crates/wasm_types/src/keystore.rs diff --git a/crates/wasm_utils/src/api_serialization/mod.rs b/crates/wasm_types/src/lib.rs similarity index 72% rename from crates/wasm_utils/src/api_serialization/mod.rs rename to crates/wasm_types/src/lib.rs index 19f0aa4551..c56d054c6e 100644 --- a/crates/wasm_utils/src/api_serialization/mod.rs +++ b/crates/wasm_types/src/lib.rs @@ -1,4 +1,12 @@ -mod call; +#[macro_use] +extern crate serde_derive; +#[macro_use] +extern crate holochain_json_derive; +pub extern crate holochain_json_api; +pub extern crate holochain_persistence_api; +pub use holochain_wasmer_guest::*; + +pub mod call; /// This module holds structs for all arguments and return types /// that get serialized and deserialized between core native and /// the WASM based ribosome. @@ -25,6 +33,9 @@ pub mod sign; mod update_entry; pub mod validation; pub mod verify_signature; +pub mod wasm_string; mod zome_api_globals; pub use self::{call::*, query::*, update_entry::*, zome_api_globals::*}; + +pub type ZomeApiResult = Result; diff --git a/crates/wasm_utils/src/api_serialization/link_entries.rs b/crates/wasm_types/src/link_entries.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/link_entries.rs rename to crates/wasm_types/src/link_entries.rs diff --git a/crates/wasm_utils/src/api_serialization/meta.rs b/crates/wasm_types/src/meta.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/meta.rs rename to crates/wasm_types/src/meta.rs diff --git a/crates/wasm_utils/src/api_serialization/query.rs b/crates/wasm_types/src/query.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/query.rs rename to crates/wasm_types/src/query.rs diff --git a/crates/wasm_utils/src/api_serialization/receive.rs b/crates/wasm_types/src/receive.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/receive.rs rename to crates/wasm_types/src/receive.rs diff --git a/crates/wasm_utils/src/api_serialization/send.rs b/crates/wasm_types/src/send.rs similarity index 95% rename from crates/wasm_utils/src/api_serialization/send.rs rename to crates/wasm_types/src/send.rs index 8ea585be2a..a6995a212c 100644 --- a/crates/wasm_utils/src/api_serialization/send.rs +++ b/crates/wasm_types/src/send.rs @@ -8,6 +8,7 @@ pub struct SendArgs { pub to_agent: Address, pub payload: String, pub options: SendOptions, + pub zome: String, } #[derive(Deserialize, Clone, PartialEq, Debug, Serialize, DefaultJson)] diff --git a/crates/wasm_utils/src/api_serialization/sign.rs b/crates/wasm_types/src/sign.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/sign.rs rename to crates/wasm_types/src/sign.rs diff --git a/crates/wasm_utils/src/api_serialization/update_entry.rs b/crates/wasm_types/src/update_entry.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/update_entry.rs rename to crates/wasm_types/src/update_entry.rs diff --git a/crates/wasm_utils/src/api_serialization/validation.rs b/crates/wasm_types/src/validation.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/validation.rs rename to crates/wasm_types/src/validation.rs diff --git a/crates/wasm_utils/src/api_serialization/verify_signature.rs b/crates/wasm_types/src/verify_signature.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/verify_signature.rs rename to crates/wasm_types/src/verify_signature.rs diff --git a/crates/wasm_types/src/wasm_string.rs b/crates/wasm_types/src/wasm_string.rs new file mode 100644 index 0000000000..4b69e7c3b3 --- /dev/null +++ b/crates/wasm_types/src/wasm_string.rs @@ -0,0 +1,16 @@ +use holochain_json_api::{error::JsonError, json::*}; + +#[derive(Deserialize, Clone, PartialEq, Eq, Hash, Debug, Serialize, DefaultJson)] +pub struct WasmString(String); + +impl ToString for WasmString { + fn to_string(&self) -> String { + self.0.clone() + } +} + +impl From for WasmString { + fn from(s: String) -> WasmString { + WasmString(s) + } +} diff --git a/crates/wasm_utils/src/api_serialization/zome_api_globals.rs b/crates/wasm_types/src/zome_api_globals.rs similarity index 100% rename from crates/wasm_utils/src/api_serialization/zome_api_globals.rs rename to crates/wasm_types/src/zome_api_globals.rs diff --git a/crates/wasm_utils/src/lib.rs b/crates/wasm_utils/src/lib.rs deleted file mode 100644 index b34ac86f92..0000000000 --- a/crates/wasm_utils/src/lib.rs +++ /dev/null @@ -1,35 +0,0 @@ -//! Library holding necessary code for the Ribosome that is also useful for hdk-rust, -//! or more generally for making rust code that the Ribosome can run. -//! Must not have any dependency with any other Holochain crates. -#![warn(unused_extern_crates)] -#[macro_use] -extern crate serde_derive; -pub extern crate holochain_core_types; -#[macro_use] -pub extern crate holochain_json_derive; -pub extern crate holochain_json_api; -pub extern crate holochain_persistence_api; - -/// ignore api_serialization because it is nothing but structs to hold serialization -#[cfg_attr(tarpaulin, skip)] -pub mod api_serialization; - -pub mod macros; -pub mod memory; - -use std::path::PathBuf; - -pub fn wasm_target_dir(test_path: &PathBuf, wasm_path: &PathBuf) -> PathBuf { - // this env var checker can't use holochain_common - // crate because that uses `directories` crate which doesn't compile to WASM - let mut target_dir = PathBuf::new(); - if let Ok(prefix) = std::env::var("HC_TARGET_PREFIX") { - target_dir.push(PathBuf::from(prefix)); - target_dir.push("crates"); - target_dir.push(test_path); - } - target_dir.push(wasm_path); - target_dir.push(PathBuf::from("target")); - - target_dir -} diff --git a/crates/wasm_utils/src/memory/allocation.rs b/crates/wasm_utils/src/memory/allocation.rs deleted file mode 100644 index 723ba88501..0000000000 --- a/crates/wasm_utils/src/memory/allocation.rs +++ /dev/null @@ -1,264 +0,0 @@ -use holochain_core_types::error::HolochainError; -use holochain_json_api::{error::JsonError, json::JsonString}; - -use memory::{MemoryBits, MemoryInt, MEMORY_INT_MAX}; - -#[derive(Copy, Clone, Debug, PartialEq)] -pub struct Offset(MemoryInt); -#[derive(Copy, Clone, Debug, PartialEq)] -pub struct Length(MemoryInt); - -impl From for MemoryInt { - fn from(offset: Offset) -> Self { - offset.0 - } -} - -impl From for MemoryBits { - fn from(offset: Offset) -> Self { - MemoryBits::from(offset.0) - } -} - -impl From for Offset { - fn from(i: MemoryInt) -> Self { - Offset(i) - } -} - -impl From for MemoryInt { - fn from(length: Length) -> Self { - length.0 - } -} - -impl From for MemoryBits { - fn from(length: Length) -> Self { - MemoryBits::from(length.0) - } -} - -impl From for Length { - fn from(i: MemoryInt) -> Self { - Length(i) - } -} - -impl From for usize { - fn from(length: Length) -> Self { - length.0 as usize - } -} - -#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone, PartialEq)] -pub enum AllocationError { - /// (de)allocation is either too large or implies negative values - OutOfBounds, - /// cannot allocate zero data - ZeroLength, - /// (de)allocation must occur at the top of the stack - BadStackAlignment, - /// writes can fail to serialize data before allocation occurs e.g. json - Serialization, -} - -impl From for String { - fn from(allocation_error: AllocationError) -> Self { - match allocation_error { - AllocationError::OutOfBounds => "Allocation out of bounds", - AllocationError::ZeroLength => "Allocation is zero length", - AllocationError::BadStackAlignment => "Allocation not aligned with stack", - AllocationError::Serialization => "Allocation could not serialize data", - } - .into() - } -} - -impl From for HolochainError { - fn from(allocation_error: AllocationError) -> Self { - HolochainError::ErrorGeneric(String::from(allocation_error)) - } -} - -#[derive(Copy, Clone, Debug, PartialEq)] -pub struct WasmAllocation { - // public fields to the crate for tests - pub(in crate::memory) offset: Offset, - pub(in crate::memory) length: Length, -} - -impl WasmAllocation { - // represent the max as MemoryBits type to allow gt comparisons - pub fn max() -> MemoryBits { - MEMORY_INT_MAX - } - - pub fn new(offset: Offset, length: Length) -> AllocationResult { - if (MemoryBits::from(offset) + MemoryBits::from(length)) > WasmAllocation::max() { - Err(AllocationError::OutOfBounds) - } else if MemoryInt::from(length) == 0 { - Err(AllocationError::ZeroLength) - } else { - Ok(WasmAllocation { offset, length }) - } - } - - pub fn offset(self) -> Offset { - self.offset - } - - pub fn length(self) -> Length { - self.length - } -} - -pub type AllocationResult = Result; - -#[cfg(test)] -pub mod tests { - - use holochain_core_types::{bits_n_pieces::U16_MAX, error::HolochainError}; - use memory::{ - allocation::{AllocationError, Length, Offset, WasmAllocation}, - MemoryBits, MemoryInt, MEMORY_INT_MAX, - }; - - pub fn fake_offset() -> Offset { - Offset(12345) - } - - pub fn fake_length() -> Length { - Length(12345) - } - - #[test] - pub fn memory_int_from_offset_test() { - assert_eq!(12345 as MemoryInt, MemoryInt::from(fake_offset()),); - } - - #[test] - pub fn memory_bits_from_offset_test() { - assert_eq!(12345 as MemoryBits, MemoryBits::from(fake_offset()),); - } - - #[test] - pub fn offset_from_memory_int_test() { - assert_eq!(fake_offset(), Offset::from(12345 as MemoryInt),); - } - - #[test] - pub fn memory_int_from_length_test() { - assert_eq!(12345 as MemoryInt, MemoryInt::from(fake_length()),); - } - - #[test] - pub fn memory_bits_from_length_test() { - assert_eq!(12345 as MemoryBits, MemoryBits::from(fake_length()),); - } - - #[test] - pub fn length_from_memory_int_test() { - assert_eq!(fake_length(), Length::from(12345 as MemoryInt),); - } - - #[test] - pub fn usize_from_length_test() { - assert_eq!(usize::from(fake_length()), 12345 as usize,); - } - - #[test] - pub fn string_from_allocation_test() { - assert_eq!( - String::from("Allocation out of bounds"), - String::from(AllocationError::OutOfBounds), - ); - assert_eq!( - String::from("Allocation is zero length"), - String::from(AllocationError::ZeroLength), - ); - assert_eq!( - String::from("Allocation not aligned with stack"), - String::from(AllocationError::BadStackAlignment), - ); - assert_eq!( - String::from("Allocation could not serialize data"), - String::from(AllocationError::Serialization), - ); - } - - #[test] - pub fn holochain_error_from_allocation_error_test() { - assert_eq!( - HolochainError::from("Allocation out of bounds"), - HolochainError::from(AllocationError::OutOfBounds), - ); - assert_eq!( - HolochainError::from("Allocation is zero length"), - HolochainError::from(AllocationError::ZeroLength), - ); - assert_eq!( - HolochainError::from("Allocation not aligned with stack"), - HolochainError::from(AllocationError::BadStackAlignment), - ); - assert_eq!( - HolochainError::from("Allocation could not serialize data"), - HolochainError::from(AllocationError::Serialization), - ); - } - - #[test] - pub fn allocation_max_test() { - assert_eq!(MEMORY_INT_MAX, WasmAllocation::max(),); - } - - #[test] - pub fn allocation_new_test() { - assert_eq!( - Err(AllocationError::OutOfBounds), - WasmAllocation::new(Offset::from(std::u32::MAX), Length::from(1)), - ); - - assert_eq!( - Err(AllocationError::ZeroLength), - WasmAllocation::new(Offset::from(1), Length::from(0)), - ); - - assert_eq!( - Ok(WasmAllocation { - offset: Offset::from(1), - length: Length::from(1) - }), - WasmAllocation::new(Offset::from(1), Length::from(1)), - ); - - // allocation larger than 1 wasm page - let big = U16_MAX * 2; - assert_eq!( - Ok(WasmAllocation { - offset: Offset::from(big), - length: Length::from(big), - }), - WasmAllocation::new(Offset::from(big), Length::from(big)), - ); - } - - #[test] - pub fn allocation_offset_test() { - assert_eq!( - Offset::from(1), - WasmAllocation::new(Offset::from(1), Length::from(1)) - .unwrap() - .offset(), - ); - } - - #[test] - pub fn allocation_length_test() { - assert_eq!( - Length::from(1), - WasmAllocation::new(Offset::from(1), Length::from(1)) - .unwrap() - .length(), - ); - } -} diff --git a/crates/wasm_utils/src/memory/mod.rs b/crates/wasm_utils/src/memory/mod.rs deleted file mode 100644 index 0610defc2d..0000000000 --- a/crates/wasm_utils/src/memory/mod.rs +++ /dev/null @@ -1,17 +0,0 @@ -use holochain_core_types::bits_n_pieces::U32_MAX; - -pub mod allocation; -pub mod read; -pub mod ribosome; -pub mod stack; -pub mod write; - -/// offsets, lengths, etc. -pub type MemoryInt = u32; - -/// encodes allocations as 2x MemoryInt in high/low bits etc. -/// must be 2x larger than MemoryInt -pub type MemoryBits = u64; - -/// represents the max MemoryInt in MemoryBits to facilitate gt comparisons -const MEMORY_INT_MAX: MemoryBits = U32_MAX; diff --git a/crates/wasm_utils/src/memory/read.rs b/crates/wasm_utils/src/memory/read.rs deleted file mode 100644 index 825e24cd7e..0000000000 --- a/crates/wasm_utils/src/memory/read.rs +++ /dev/null @@ -1,32 +0,0 @@ -use crate::memory::{allocation::WasmAllocation, MemoryInt}; -use std::{ffi::CStr, os::raw::c_char}; - -/// reads are always from a WasmAllocation -impl WasmAllocation { - fn read_str_raw<'a>(ptr_data: *mut c_char) -> &'a str { - let ptr_safe_c_str = unsafe { CStr::from_ptr(ptr_data) }; - ptr_safe_c_str.to_str().unwrap() - } - - /// Retrieve a stored string from an allocation. - /// Return error code if encoded_allocation is invalid. - pub fn read_to_string(self) -> String { - WasmAllocation::read_str_raw(MemoryInt::from(self.offset()) as *mut c_char).to_string() - } -} - -#[cfg(test)] -pub mod tests { - - use memory::allocation::WasmAllocation; - use std::{ffi::CString, os::raw::c_char}; - - #[test] - pub fn read_str_raw_test() { - let s = "foo"; - let c_string = CString::new(s).expect("could not create cstring"); - let ptr = c_string.as_ptr(); - - assert_eq!(s, WasmAllocation::read_str_raw(ptr as *mut c_char),); - } -} diff --git a/crates/wasm_utils/src/memory/ribosome.rs b/crates/wasm_utils/src/memory/ribosome.rs deleted file mode 100644 index 816c8ce013..0000000000 --- a/crates/wasm_utils/src/memory/ribosome.rs +++ /dev/null @@ -1,335 +0,0 @@ -// extends memory allocation to work with ribosome encodings - -use holochain_core_types::{ - bits_n_pieces::{u64_merge_bits, u64_split_bits}, - error::{ - HolochainError, RibosomeEncodedAllocation, RibosomeEncodedValue, RibosomeEncodingBits, - RibosomeErrorCode, - }, -}; - -use holochain_json_api::json::JsonString; - -use memory::{ - allocation::{AllocationError, AllocationResult, WasmAllocation}, - stack::WasmStack, - MemoryBits, -}; -use std::convert::TryFrom; - -impl TryFrom for WasmAllocation { - type Error = AllocationError; - fn try_from( - ribosome_memory_allocation: RibosomeEncodedAllocation, - ) -> Result { - let (offset, length) = u64_split_bits(MemoryBits::from(ribosome_memory_allocation)); - WasmAllocation::new(offset.into(), length.into()) - } -} - -impl From for RibosomeEncodedAllocation { - fn from(wasm_allocation: WasmAllocation) -> Self { - u64_merge_bits( - wasm_allocation.offset().into(), - wasm_allocation.length().into(), - ) - .into() - } -} - -impl From for RibosomeEncodedValue { - fn from(wasm_allocation: WasmAllocation) -> Self { - RibosomeEncodedValue::Allocation(RibosomeEncodedAllocation::from(wasm_allocation)) - } -} - -impl From for RibosomeErrorCode { - fn from(allocation_error: AllocationError) -> Self { - match allocation_error { - AllocationError::OutOfBounds => RibosomeErrorCode::OutOfMemory, - AllocationError::ZeroLength => RibosomeErrorCode::ZeroSizedAllocation, - AllocationError::BadStackAlignment => RibosomeErrorCode::NotAnAllocation, - AllocationError::Serialization => RibosomeErrorCode::NotAnAllocation, - } - } -} - -impl From for RibosomeEncodedValue { - fn from(allocation_error: AllocationError) -> Self { - RibosomeEncodedValue::Failure(RibosomeErrorCode::from(allocation_error)) - } -} - -impl AllocationError { - pub fn as_ribosome_encoding(&self) -> RibosomeEncodingBits { - RibosomeEncodedValue::from(self.clone()).into() - } -} - -impl WasmAllocation { - /// equivalent to TryFrom for WasmAllocation - /// not implemented as a trait because RibosomeEncodingBits is a primitive and that would couple - /// allocations to ribosome encoding - pub fn try_from_ribosome_encoding(encoded_value: RibosomeEncodingBits) -> AllocationResult { - match RibosomeEncodedValue::from(encoded_value) { - RibosomeEncodedValue::Success => Err(AllocationError::ZeroLength), - RibosomeEncodedValue::Failure(_) => Err(AllocationError::OutOfBounds), - RibosomeEncodedValue::Allocation(ribosome_allocation) => { - WasmAllocation::try_from(ribosome_allocation) - } - } - } - - pub fn as_ribosome_encoding(self) -> RibosomeEncodingBits { - RibosomeEncodedValue::from(self).into() - } -} - -impl WasmStack { - /// equivalent to TryFrom for WasmStack - /// not implemented as a trait because RibosomeEncodingBits is a primitive and that would couple - /// stacks to ribosome encoding - /// wraps WasmAllocation::try_from_ribosome_encoding internally but has a "higher level" - /// return signature intended for direct use/return in/from ribosome fns - pub fn try_from_ribosome_encoding( - maybe_encoded_allocation: RibosomeEncodingBits, - ) -> Result { - match WasmAllocation::try_from_ribosome_encoding(maybe_encoded_allocation) { - Err(allocation_error) => Err(allocation_error), - Ok(allocation) => match WasmStack::try_from(allocation) { - Err(allocation_error) => Err(allocation_error), - Ok(stack) => Ok(stack), - }, - } - .map_err(|e| e.as_ribosome_encoding().into()) - } -} - -/// Equivalent to From for RibosomeEncodedValue -/// not possible to implement the trait as Result and RibosomeEncodedValue from different crates -pub fn return_code_for_allocation_result(result: AllocationResult) -> RibosomeEncodedValue { - match result { - Ok(allocation) => RibosomeEncodedValue::from(allocation), - Err(allocation_error) => RibosomeEncodedValue::from(allocation_error), - } -} - -pub fn load_ribosome_encoded_string( - encoded_value: RibosomeEncodingBits, -) -> Result { - // almost the same as WasmAllocation::try_from_ribosome_encoding but maps to HolochainError - match RibosomeEncodedValue::from(encoded_value) { - RibosomeEncodedValue::Success => Err(HolochainError::Ribosome( - RibosomeErrorCode::ZeroSizedAllocation, - )), - RibosomeEncodedValue::Failure(err_code) => Err(HolochainError::Ribosome(err_code)), - RibosomeEncodedValue::Allocation(ribosome_allocation) => { - Ok(WasmAllocation::try_from(ribosome_allocation)?.read_to_string()) - } - } -} - -pub fn load_ribosome_encoded_json>( - encoded_value: RibosomeEncodingBits, -) -> Result -where - J::Error: Into, -{ - let s = load_ribosome_encoded_string(encoded_value)?; - let j = JsonString::from_json(&s); - - J::try_from(j).map_err(|e| e.into()) -} - -#[cfg(test)] -pub mod tests { - - use holochain_core_types::{ - bits_n_pieces::u64_merge_bits, - error::{ - RibosomeEncodedAllocation, RibosomeEncodedValue, RibosomeEncodingBits, - RibosomeErrorCode, - }, - }; - use memory::{ - allocation::{AllocationError, Length, Offset, WasmAllocation}, - ribosome::return_code_for_allocation_result, - stack::{Top, WasmStack}, - }; - use std::convert::TryFrom; - - #[test] - fn try_allocation_from_ribosome_allocation_test() { - assert_eq!( - Err(AllocationError::ZeroLength), - WasmAllocation::try_from(RibosomeEncodedAllocation::from(0)), - ); - - assert_eq!( - Err(AllocationError::OutOfBounds), - WasmAllocation::try_from(RibosomeEncodedAllocation::from(u64_merge_bits( - std::u32::MAX, - std::u32::MAX - ))), - ); - - assert_eq!( - Ok(WasmAllocation { - offset: Offset::from(4), - length: Length::from(8) - }), - WasmAllocation::try_from(RibosomeEncodedAllocation::from( - 0b000000000000000000000000000000100_00000000000000000000000000001000 - )), - ); - } - - #[test] - fn ribosome_allocation_from_allocation_test() { - assert_eq!( - RibosomeEncodedAllocation::from( - 0b00000000000000000000000000000100_00000000000000000000000000001000 - ), - RibosomeEncodedAllocation::from(WasmAllocation { - offset: Offset::from(4), - length: Length::from(8) - }), - ); - } - - #[test] - fn ribosome_encoded_value_from_allocation_test() { - assert_eq!( - RibosomeEncodedValue::Allocation(RibosomeEncodedAllocation::from( - 0b00000000000000000000000000000100_00000000000000000000000000001000 - )), - RibosomeEncodedValue::from(WasmAllocation { - offset: Offset::from(4), - length: Length::from(8) - }), - ); - } - - #[test] - fn ribosome_error_from_allocation_error_test() { - assert_eq!( - RibosomeErrorCode::OutOfMemory, - RibosomeErrorCode::from(AllocationError::OutOfBounds), - ); - - assert_eq!( - RibosomeErrorCode::ZeroSizedAllocation, - RibosomeErrorCode::from(AllocationError::ZeroLength), - ); - - assert_eq!( - RibosomeErrorCode::NotAnAllocation, - RibosomeErrorCode::from(AllocationError::BadStackAlignment), - ); - - assert_eq!( - RibosomeErrorCode::NotAnAllocation, - RibosomeErrorCode::from(AllocationError::Serialization), - ); - } - - #[test] - fn ribosome_code_from_allocation_error_test() { - assert_eq!( - RibosomeEncodedValue::Failure(RibosomeErrorCode::OutOfMemory), - RibosomeEncodedValue::from(AllocationError::OutOfBounds), - ); - - assert_eq!( - RibosomeEncodedValue::Failure(RibosomeErrorCode::ZeroSizedAllocation), - RibosomeEncodedValue::from(AllocationError::ZeroLength), - ); - - assert_eq!( - RibosomeEncodedValue::Failure(RibosomeErrorCode::NotAnAllocation), - RibosomeEncodedValue::from(AllocationError::BadStackAlignment), - ); - - assert_eq!( - RibosomeEncodedValue::Failure(RibosomeErrorCode::NotAnAllocation), - RibosomeEncodedValue::from(AllocationError::Serialization), - ); - } - - #[test] - fn ribosome_encoding_test() { - assert_eq!( - RibosomeEncodingBits::from(RibosomeEncodedValue::Failure( - RibosomeErrorCode::OutOfMemory - )), - AllocationError::OutOfBounds.as_ribosome_encoding(), - ); - assert_eq!( - RibosomeEncodingBits::from(RibosomeEncodedValue::Failure( - RibosomeErrorCode::ZeroSizedAllocation - )), - AllocationError::ZeroLength.as_ribosome_encoding(), - ); - assert_eq!( - RibosomeEncodingBits::from(RibosomeEncodedValue::Failure( - RibosomeErrorCode::NotAnAllocation - )), - AllocationError::BadStackAlignment.as_ribosome_encoding(), - ); - assert_eq!( - RibosomeEncodingBits::from(RibosomeEncodedValue::Failure( - RibosomeErrorCode::NotAnAllocation - )), - AllocationError::Serialization.as_ribosome_encoding(), - ); - } - - #[test] - fn stack_from_encoding_test() { - assert_eq!( - Err(RibosomeEncodedValue::from(AllocationError::OutOfBounds)), - WasmStack::try_from_ribosome_encoding(u64_merge_bits(std::u32::MAX, std::u32::MAX)), - ); - - assert_eq!( - Err(RibosomeEncodedValue::from(AllocationError::ZeroLength)), - WasmStack::try_from_ribosome_encoding(0), - ); - - assert_eq!( - Ok(WasmStack { top: Top(4) }), - // 2 + 2 = 4 - WasmStack::try_from_ribosome_encoding( - 0b00000000000000000000000000000010_00000000000000000000000000000010 - ), - ); - } - - #[test] - fn return_code_for_allocation_result_test() { - assert_eq!( - RibosomeEncodedValue::from(AllocationError::OutOfBounds), - return_code_for_allocation_result(Err(AllocationError::OutOfBounds)), - ); - assert_eq!( - RibosomeEncodedValue::from(AllocationError::ZeroLength), - return_code_for_allocation_result(Err(AllocationError::ZeroLength)), - ); - assert_eq!( - RibosomeEncodedValue::from(AllocationError::BadStackAlignment), - return_code_for_allocation_result(Err(AllocationError::BadStackAlignment)), - ); - assert_eq!( - RibosomeEncodedValue::from(AllocationError::Serialization), - return_code_for_allocation_result(Err(AllocationError::Serialization)), - ); - let allocation = WasmAllocation { - offset: Offset::from(5), - length: Length::from(5), - }; - assert_eq!( - RibosomeEncodedValue::from(allocation), - return_code_for_allocation_result(Ok(allocation)), - ); - } -} diff --git a/crates/wasm_utils/src/memory/stack.rs b/crates/wasm_utils/src/memory/stack.rs deleted file mode 100644 index 4211f342b3..0000000000 --- a/crates/wasm_utils/src/memory/stack.rs +++ /dev/null @@ -1,269 +0,0 @@ -use memory::{ - allocation::{AllocationError, Length, WasmAllocation}, - MemoryBits, MemoryInt, MEMORY_INT_MAX, -}; -use std::convert::TryFrom; - -#[derive(Copy, Clone, Default, Debug, PartialEq)] -// pub in crate for testing -pub struct Top(pub(in crate::memory) MemoryInt); - -impl From for MemoryInt { - fn from(top: Top) -> Self { - top.0 - } -} - -impl From for usize { - fn from(top: Top) -> Self { - MemoryInt::from(top) as usize - } -} - -impl From for MemoryBits { - fn from(top: Top) -> Self { - MemoryBits::from(top.0) - } -} - -#[derive(Copy, Clone, Default, Debug, PartialEq)] -pub struct WasmStack { - // pub in crate for testing - pub(in crate::memory) top: Top, -} - -impl WasmStack { - // represent the max as MemoryBits type to allow gt comparisons - pub fn max() -> MemoryBits { - MEMORY_INT_MAX - } - - // min compares lt so can be a MemoryInt - pub fn min() -> MemoryInt { - 0 - } - - // A stack can be initialized by giving the last know allocation on this stack - pub fn new() -> WasmStack { - WasmStack { - top: Top(WasmStack::min()), - } - } - - pub fn next_allocation(self, length: Length) -> Result { - WasmAllocation::new(MemoryInt::from(self.top()).into(), length) - } - - pub fn allocate(&mut self, allocation: WasmAllocation) -> Result { - if MemoryInt::from(self.top()) != MemoryInt::from(allocation.offset()) { - Err(AllocationError::BadStackAlignment) - } else if MemoryBits::from(self.top()) + MemoryBits::from(allocation.length()) - > WasmStack::max() - { - Err(AllocationError::OutOfBounds) - } else { - // @todo i don't know why we return the old top instead of new one? - let old_top = self.top; - self.top = - Top(MemoryInt::from(allocation.offset()) + MemoryInt::from(allocation.length())); - Ok(old_top) - } - } - - pub fn deallocate(&mut self, allocation: WasmAllocation) -> Result { - if MemoryInt::from(self.top()) - != MemoryInt::from(allocation.offset()) + MemoryInt::from(allocation.length()) - { - Err(AllocationError::BadStackAlignment) - } else if MemoryInt::from(allocation.offset()) < WasmStack::min() { - Err(AllocationError::OutOfBounds) - } else { - let old_top = self.top; - self.top = Top(allocation.offset().into()); - Ok(old_top) - } - } - - // Getters - pub fn top(self) -> Top { - self.top - } -} - -impl TryFrom for WasmStack { - type Error = AllocationError; - fn try_from(allocation: WasmAllocation) -> Result { - let mut stack = WasmStack { - top: Top(allocation.offset().into()), - }; - stack.allocate(allocation)?; - Ok(stack) - } -} - -#[cfg(test)] -pub mod memory_tests { - - use holochain_core_types::bits_n_pieces::U16_MAX; - use memory::{ - allocation::{AllocationError, Length, Offset, WasmAllocation}, - stack::{Top, WasmStack}, - MemoryBits, MemoryInt, MEMORY_INT_MAX, - }; - use std::convert::TryFrom; - - pub fn fake_top() -> Top { - Top(12345) - } - - #[test] - fn memory_int_from_top_test() { - assert_eq!(12345 as MemoryInt, MemoryInt::from(fake_top()),); - } - - #[test] - fn usize_from_top_test() { - assert_eq!(12345 as usize, usize::from(fake_top()),); - } - - #[test] - fn memory_bits_from_top_test() { - assert_eq!(12345 as MemoryBits, MemoryBits::from(fake_top()),); - } - - #[test] - fn stack_max_test() { - assert_eq!(MEMORY_INT_MAX, WasmStack::max(),); - } - - #[test] - fn stack_min_test() { - assert_eq!(0, WasmStack::min(),); - } - - #[test] - fn stack_new_test() { - assert_eq!(WasmStack { top: Top(0) }, WasmStack::new(),); - } - - #[test] - fn next_allocation_test() { - let mut stack = WasmStack::new(); - - let first_offset = Offset::from(0); - let first_length = Length::from(5); - let first_allocation = stack.next_allocation(first_length); - - assert_eq!( - first_allocation, - WasmAllocation::new(first_offset, first_length), - ); - - stack.allocate(first_allocation.unwrap()).ok(); - - let second_offset = Offset::from(5); - let second_length = Length::from(3); - let second_allocation = stack.next_allocation(second_length); - - assert_eq!( - second_allocation, - WasmAllocation::new(second_offset, second_length), - ); - - stack.allocate(second_allocation.unwrap()).ok(); - - let big_offset = Offset::from(8); - let big_length = Length::from(U16_MAX * 2); - - assert_eq!( - stack.next_allocation(big_length), - WasmAllocation::new(big_offset, big_length), - ); - } - - #[test] - fn allocate_test() { - let mut stack = WasmStack::new(); - let unaligned_allocation = WasmAllocation::new(Offset::from(10), Length::from(10)).unwrap(); - - assert_eq!( - Err(AllocationError::BadStackAlignment), - stack.allocate(unaligned_allocation), - ); - - let first_allocation = stack.next_allocation(Length::from(5)); - stack.allocate(first_allocation.unwrap()).ok(); - - let second_allocation = stack.next_allocation(Length::from(8)); - - assert_eq!(stack.allocate(second_allocation.unwrap()), Ok(Top(5)),); - assert_eq!(stack.top(), Top(13),); - - let out_of_bounds_allocation = WasmAllocation { - offset: Offset::from(13), - length: Length::from(std::u32::MAX), - }; - - assert_eq!( - Err(AllocationError::OutOfBounds), - stack.allocate(out_of_bounds_allocation), - ); - - let big_allocation = stack.next_allocation(Length::from(U16_MAX)).unwrap(); - assert_eq!(stack.allocate(big_allocation), Ok(Top(13)),); - assert_eq!(stack.top(), Top(U16_MAX + 13),); - } - - #[test] - fn deallocate_test() { - let mut stack = WasmStack { top: Top(50) }; - let unaligned_allocation = WasmAllocation::new(Offset::from(50), Length::from(5)).unwrap(); - assert_eq!( - Err(AllocationError::BadStackAlignment), - stack.deallocate(unaligned_allocation), - ); - - // can't test out of bounds for deallocate because unsigned integers don't go below min - - let deallocation = WasmAllocation::new(Offset::from(20), Length::from(30)).unwrap(); - assert_eq!(stack.deallocate(deallocation), Ok(Top(50)),); - assert_eq!(stack.top(), Top(20),); - } - - #[test] - fn top_test() { - let top = Top(123); - let stack = WasmStack { top }; - assert_eq!(top, stack.top(),); - } - - #[test] - fn try_stack_from_allocation_test() { - // can't test bad alignment as it should not be possible - - assert_eq!( - Err(AllocationError::OutOfBounds), - WasmStack::try_from(WasmAllocation { - offset: Offset::from(std::u32::MAX), - length: Length::from(1) - }), - ); - - assert_eq!( - Ok(WasmStack { top: Top(60) }), - WasmStack::try_from(WasmAllocation { - offset: Offset::from(30), - length: Length::from(30) - }), - ); - - let big = U16_MAX * 3; - assert_eq!( - Ok(WasmStack { top: Top(big * 2) }), - WasmStack::try_from(WasmAllocation { - offset: Offset::from(big), - length: Length::from(big), - }), - ); - } -} diff --git a/crates/wasm_utils/src/memory/write.rs b/crates/wasm_utils/src/memory/write.rs deleted file mode 100644 index e67e1a5f4b..0000000000 --- a/crates/wasm_utils/src/memory/write.rs +++ /dev/null @@ -1,48 +0,0 @@ -use crate::memory::{ - allocation::{AllocationError, WasmAllocation}, - stack::WasmStack, - MemoryBits, MemoryInt, -}; -use holochain_json_api::json::JsonString; -use memory::allocation::{AllocationResult, Length}; -use std::{cmp::max, convert::TryInto, os::raw::c_char, slice}; - -impl WasmStack { - /// Write in wasm memory according to stack state. - fn write_in_wasm_memory(&mut self, bytes: &[u8], length: Length) -> AllocationResult { - let next_allocation = self.next_allocation(length)?; - - let ptr = MemoryInt::from(self.allocate(next_allocation)?) as *mut c_char; - let ptr_safe = unsafe { slice::from_raw_parts_mut(ptr, usize::from(length)) }; - for (i, byte) in bytes.iter().enumerate() { - ptr_safe[i] = *byte as c_char; - } - - WasmAllocation::new((ptr as MemoryInt).into(), length) - } - - /// Write a string in wasm memory according to stack state. - pub fn write_string(&mut self, s: &str) -> AllocationResult { - let bytes = s.as_bytes(); - let length = max(bytes.len(), 1) as MemoryInt; // always allocate at least 1 byte - if MemoryBits::from(length) > WasmStack::max() { - return Err(AllocationError::OutOfBounds); - } - - self.write_in_wasm_memory(bytes, Length::from(length)) - } - - /// Write a data struct as a json string in wasm memory according to stack state. - pub fn write_json>(&mut self, jsonable: J) -> AllocationResult { - let j: JsonString = jsonable - .try_into() - .map_err(|_| AllocationError::Serialization)?; - - let json_bytes = j.to_bytes(); - let json_bytes_len = max(json_bytes.len(), 1) as MemoryInt; // always allocate at least 1 byte - if MemoryBits::from(json_bytes_len) > WasmStack::max() { - return Err(AllocationError::OutOfBounds); - } - self.write_in_wasm_memory(&json_bytes, Length::from(json_bytes_len)) - } -} diff --git a/crates/wasm_utils/tests/integration-test.rs b/crates/wasm_utils/tests/integration-test.rs deleted file mode 100755 index 682a95e886..0000000000 --- a/crates/wasm_utils/tests/integration-test.rs +++ /dev/null @@ -1,228 +0,0 @@ -extern crate holochain_conductor_lib; -extern crate holochain_core; -extern crate holochain_core_types; -#[macro_use] -extern crate serde_derive; -#[macro_use] -extern crate holochain_json_derive; -extern crate holochain_json_api; -extern crate holochain_persistence_api; -extern crate holochain_wasm_utils; -extern crate serde_json; -extern crate tempfile; -extern crate test_utils; - -use holochain_conductor_lib::error::{HolochainInstanceError, HolochainResult}; -use holochain_core_types::{ - bits_n_pieces::U16_MAX, - error::{CoreError, HolochainError}, -}; - -use holochain_json_api::{ - error::JsonError, - json::{JsonString, RawString}, -}; - -use holochain_wasm_utils::{memory::MemoryInt, wasm_target_dir}; -use std::{convert::TryFrom, path::PathBuf}; -use test_utils::hc_setup_and_call_zome_fn; - -fn call_zome_function_with_hc>( - fn_name: &str, - params: J, -) -> HolochainResult { - let mut wasm_path = PathBuf::new(); - let wasm_path_component: PathBuf = - [String::from("wasm-test"), String::from("integration-test")] - .iter() - .collect(); - wasm_path.push(wasm_target_dir( - &String::from("wasm_utils").into(), - &wasm_path_component, - )); - let wasm_file_path: PathBuf = [ - String::from("wasm32-unknown-unknown"), - String::from("release"), - String::from("wasm_integration_test.wasm"), - ] - .iter() - .collect(); - wasm_path.push(wasm_file_path); - hc_setup_and_call_zome_fn(&wasm_path, fn_name, params) -} - -#[derive(Serialize, Default, Clone, PartialEq, Deserialize, Debug, DefaultJson)] -struct TestStruct { - value: String, - list: Vec, -} - -fn fake_test_struct() -> TestStruct { - TestStruct { - value: "first".to_string(), - list: vec!["hello".to_string(), "world!".to_string()], - } -} - -// =============================================================================================== -// START MEMORY -// ----------------------------------------------------------------------------------------------- - -// =============================================================================================== -// STRINGS -// ----------------------------------------------------------------------------------------------- - -#[test] -fn store_string_test() { - assert_eq!( - Ok(JsonString::from_json("fish")), - call_zome_function_with_hc("store_string", RawString::from("")), - ); -} - -#[test] -fn store_string_err_test() { - assert_eq!( - Err(HolochainInstanceError::from( - HolochainError::RibosomeFailed("Zome function failure: Out of memory".into()) - )), - call_zome_function_with_hc("store_string_err", RawString::from("")), - ); -} - -#[test] -fn load_string_test() { - assert_eq!( - Ok(JsonString::from_json("fish")), - call_zome_function_with_hc("load_string", RawString::from("")), - ); -} - -#[test] -fn stacked_strings_test() { - assert_eq!( - Ok(JsonString::from_json("first")), - call_zome_function_with_hc("stacked_strings", RawString::from("")), - ); -} - -#[test] -fn big_string_input_static_test() { - let s = "foobarbazbing".repeat(U16_MAX as usize); - assert_eq!( - JsonString::from( - String::from(JsonString::from(RawString::from(s.clone()))).len() as MemoryInt - ), - call_zome_function_with_hc("big_string_input", RawString::from(s)).unwrap(), - ); -} - -#[test] -/// test that we can send a big string as input to a zome function -/// at this point it is fine to preinitialize multiple wasm pages (not testing dynamic) -fn big_string_process_static_test() { - // assert happens inside the zome because this test shows internal processing - call_zome_function_with_hc("big_string_process_static", RawString::from("")).unwrap(); -} - -#[test] -/// test that we can send a big string as input to a zome function -/// at this point it is fine to preinitialize multiple wasm pages (not testing dynamic) -fn big_string_output_static_test() { - let s = call_zome_function_with_hc("big_string_output_static", RawString::from("")).unwrap(); - let expected = "(ಥ⌣ಥ)".repeat(U16_MAX as usize); - assert_eq!(String::from(s).len(), expected.len()); - assert_eq!( - Ok(JsonString::from_json(&expected)), - call_zome_function_with_hc("big_string_output_static", RawString::from("")), - ); -} - -#[test] -pub fn round_trip_foo_test() { - assert_eq!( - Ok(JsonString::from_json("foo")), - call_zome_function_with_hc("round_trip_foo", RawString::from("")), - ); -} - -#[test] -fn error_report_test() { - let call_result = call_zome_function_with_hc("error_report", RawString::from("")).unwrap(); - let core_err = CoreError::try_from(call_result).unwrap(); - assert!(core_err - .to_string() - .contains("Holochain Core error: Zome assertion failed: `false`")); -} - -#[test] -fn store_as_json_test() { - assert_eq!( - Ok(JsonString::from(RawString::from("fish"))), - call_zome_function_with_hc("store_as_json", RawString::from("")), - ); -} - -#[test] -fn store_load_struct_as_json_test() { - assert_eq!( - Ok(JsonString::from(fake_test_struct())), - call_zome_function_with_hc("store_struct_as_json", RawString::from("")), - ); -} - -#[test] -fn load_json_struct_test() { - assert_eq!( - Ok(JsonString::from(fake_test_struct())), - call_zome_function_with_hc("load_json_struct", RawString::from("")), - ); -} - -#[test] -fn stacked_json_struct_test() { - assert_eq!( - Ok(JsonString::from(fake_test_struct())), - call_zome_function_with_hc("stacked_json_struct", RawString::from("")), - ); -} - -#[test] -fn stacked_json_test() { - assert_eq!( - Ok(JsonString::from(RawString::from("first"))), - call_zome_function_with_hc("stacked_json", RawString::from("")) - ); -} - -#[test] -fn call_store_as_json_err() { - assert_eq!( - Err(HolochainInstanceError::from( - HolochainError::RibosomeFailed("Zome function failure: Out of memory".into()) - )), - call_zome_function_with_hc("store_json_err", RawString::from("")), - ); -} - -#[test] -fn load_json_err_test() { - assert_eq!( - Err(HolochainInstanceError::from( - HolochainError::RibosomeFailed("Zome function failure: Unspecified".into()) - )), - call_zome_function_with_hc("load_json_err", RawString::from("")), - ); -} - -#[test] -fn stacked_mix_test() { - assert_eq!( - Ok(JsonString::from(RawString::from("third"))), - call_zome_function_with_hc("stacked_mix", RawString::from("")), - ); -} - -// =============================================================================================== -// END MEMORY -// ----------------------------------------------------------------------------------------------- diff --git a/crates/wasm_utils/wasm-test/integration-test/.gitignore b/crates/wasm_utils/wasm-test/integration-test/.gitignore deleted file mode 100644 index eb5a316cbd..0000000000 --- a/crates/wasm_utils/wasm-test/integration-test/.gitignore +++ /dev/null @@ -1 +0,0 @@ -target diff --git a/crates/wasm_utils/wasm-test/integration-test/Cargo.toml b/crates/wasm_utils/wasm-test/integration-test/Cargo.toml deleted file mode 100644 index 75217aa90b..0000000000 --- a/crates/wasm_utils/wasm-test/integration-test/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "wasm-integration-test" -version = "0.0.43-alpha3" -authors = ["Holochain Core Dev Team "] - -[lib] -crate-type = ["cdylib"] - -[profile.release] -panic = "abort" - -[workspace] -members = [] - -[dependencies] -serde = "=1.0.104" -wasmi = "=0.4.4" -serde_derive = "=1.0.104" -serde_json = { version = "=1.0.47", features = ["preserve_order"] } -holochain_wasm_utils = { path = "../../"} -holochain_json_derive = "=0.0.23" diff --git a/crates/wasm_utils/wasm-test/integration-test/src/lib.rs b/crates/wasm_utils/wasm-test/integration-test/src/lib.rs deleted file mode 100644 index 165f513c80..0000000000 --- a/crates/wasm_utils/wasm-test/integration-test/src/lib.rs +++ /dev/null @@ -1,490 +0,0 @@ -#[macro_use] -extern crate holochain_wasm_utils; -#[macro_use] -extern crate serde_derive; -extern crate serde_json; -#[macro_use] -extern crate holochain_json_derive; -extern crate wasmi; - -use holochain_wasm_utils::holochain_json_api::{ - json::{JsonString, RawString}, error::JsonError -}; - -use holochain_wasm_utils::memory::stack::WasmStack; -use holochain_wasm_utils::memory::allocation::AllocationError; - -use holochain_wasm_utils::{ - holochain_core_types::error::HolochainError, -}; -use holochain_wasm_utils::holochain_core_types::error::RibosomeEncodingBits; -use holochain_wasm_utils::holochain_core_types::error::RibosomeEncodedValue; -use std::convert::TryFrom; -use holochain_wasm_utils::memory::ribosome::return_code_for_allocation_result; -use holochain_wasm_utils::memory::MemoryInt; -use holochain_wasm_utils::memory::ribosome::load_ribosome_encoded_json; -use holochain_wasm_utils::memory::allocation::WasmAllocation; -use holochain_wasm_utils::holochain_core_types::bits_n_pieces::U16_MAX; -use wasmi::MemoryInstance; -use wasmi::memory_units::Pages; -use holochain_wasm_utils::holochain_core_types::error::RibosomeEncodedAllocation; - -#[derive(Serialize, Default, Clone, PartialEq, Deserialize, Debug, DefaultJson)] -struct TestStruct { - value: String, - list: Vec, -} - -#[derive(Serialize, Default, Clone, PartialEq, Deserialize, Debug, DefaultJson)] -struct OtherTestStruct { - other: String, - list: Vec, -} - -// =============================================================================================== -// START MEMORY -// ----------------------------------------------------------------------------------------------- - -#[no_mangle] -/// store string in wasm memory and return encoding -/// TODO #486 -//// Can't do zome_assert!() while testing write_json() since it internally uses write_json() ! -//// so using normal assert! even if we get unhelpful Trap::Unreachable error message. -pub extern "C" fn store_string(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - - // start with an empty stack - let mut stack = WasmStack::default(); - assert_eq!( - 0 as MemoryInt, - MemoryInt::from(stack.top()), - ); - - // successfully allocate a written string - let s = "fish"; - let allocation = match stack.write_string(s) { - Ok(allocation) => allocation, - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - }; - - assert_eq!( - 4 as MemoryInt, - MemoryInt::from(stack.top()), - ); - - allocation.as_ribosome_encoding() - -} - -#[no_mangle] -pub extern "C" fn store_string_err(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - let allmost_full_alloc = 0b11111111111111111111111111111101_00000000000000000000000000000010; - - let allocation = match WasmAllocation::try_from_ribosome_encoding(allmost_full_alloc) { - Ok(allocation) => allocation, - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - }; - - let mut stack = match WasmStack::try_from(allocation) { - Ok(stack) => stack, - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - }; - - return_code_for_allocation_result( - stack.write_string("fish") - ).into() -} - -#[no_mangle] -// load the string from a previously stored string -pub extern "C" fn load_string(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - let encoded = store_string(0); - - let allocation = match WasmAllocation::try_from_ribosome_encoding(encoded) { - Ok(allocation) => allocation, - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - }; - - let mut stack = match WasmStack::try_from(allocation) { - Ok(allocation) => allocation, - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - }; - - return_code_for_allocation_result( - stack.write_string( - &allocation.read_to_string() - ) - ) - .into() - -} - -#[no_mangle] -pub extern "C" fn stacked_strings(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - - let mut stack = WasmStack::default(); - - let first = match stack.write_string("first") { - Ok(first) => first, - Err(first_error) => return first_error.as_ribosome_encoding(), - }; - if let Err(second_error) = stack.write_string("second") { - return second_error.as_ribosome_encoding(); - }; - - first.as_ribosome_encoding() -} - -#[no_mangle] -// returns the length of the input string so we can verify externally how much data was sent in -pub extern "C" fn big_string_input(big_string: RibosomeEncodingBits) -> RibosomeEncodingBits { - let input_allocation = match WasmAllocation::try_from(RibosomeEncodedAllocation::from(big_string)) { - Ok(allocation) => allocation, - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - }; - - let mut stack = WasmStack::default(); - - let allocation = match stack.write_string(&format!("{:?}", input_allocation.read_to_string().len())) { - Ok(allocation) => allocation, - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - }; - - allocation.as_ribosome_encoding() -} - -#[no_mangle] -pub extern "C" fn big_string_process_static(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - - let mut stack = WasmStack::default(); - - let memory = match MemoryInstance::alloc(Pages(1), None) { - Ok(memory) => memory, - Err(_) => return AllocationError::OutOfBounds.as_ribosome_encoding(), - }; - - if memory.grow(Pages(3)).is_err() { - return AllocationError::OutOfBounds.as_ribosome_encoding(); - } - - // @TODO we can't handle UTF-8 in wasm?? - // @see https://github.com/holochain/holochain-rust/issues/933 - // let input = "╰▐ ✖ 〜 ✖ ▐╯".repeat((U16_MAX * 1) as usize); - let input = "foo".repeat((U16_MAX * 1) as usize); - - let allocation = match stack.write_string(&input) { - Ok(allocation) => allocation, - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - }; - - assert_eq!(input, allocation.read_to_string()); - - allocation.as_ribosome_encoding() - -} - -#[no_mangle] -pub extern "C" fn big_string_output_static(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - - let mut stack = WasmStack::default(); - - let memory = match MemoryInstance::alloc(Pages(1), None) { - Ok(memory) => memory, - Err(_) => return AllocationError::OutOfBounds.as_ribosome_encoding(), - }; - - // face emoji is 11 bytes so we need 1 pages to hold U16_MAX faces - if memory.grow(Pages(11)).is_err() { - return AllocationError::OutOfBounds.as_ribosome_encoding(); - }; - - match stack.write_string(&"(ಥ⌣ಥ)".repeat(U16_MAX as usize)) { - Ok(allocation) => allocation.as_ribosome_encoding(), - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - } - -} - -#[no_mangle] -/// thrash the allocation/deallocation logic a bit -pub extern "C" fn round_trip_foo(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - let mut stack = WasmStack::default(); - - // stack should start at zero top - assert_eq!( - 0 as MemoryInt, - MemoryInt::from(stack.top()), - ); - - // should be able to retrieve a valid allocation from writing "foo" to the stack - let s = "foo"; - let allocation = stack.write_string(s).unwrap(); - - // the allocation should be offset 0 and length 3, i.e. starting at "foo" - assert_eq!( - 0 as MemoryInt, - MemoryInt::from(allocation.offset()), - ); - assert_eq!( - 3 as MemoryInt, - MemoryInt::from(allocation.length()), - ); - assert_eq!( - "foo".to_string(), - allocation.read_to_string(), - ); - - // top of the stack should be end of "foo" - assert_eq!( - 3 as MemoryInt, - MemoryInt::from(stack.top()), - ); - - // should be able to retrieve a new valid allocation from writing "bar" to the stack - let s2 = "barz"; - let allocation2 = stack.write_string(s2).unwrap(); - - // allocation 1 should be unchanged by this - assert_eq!( - 0 as MemoryInt, - MemoryInt::from(allocation.offset()), - ); - assert_eq!( - 3 as MemoryInt, - MemoryInt::from(allocation.length()), - ); - - // allocation 2 starts at the end of "foo" for "barz" so is offset 3 and length 4 - assert_eq!( - 3 as MemoryInt, - MemoryInt::from(allocation2.offset()), - ); - assert_eq!( - 4 as MemoryInt, - MemoryInt::from(allocation2.length()), - ); - assert_eq!( - "barz".to_string(), - allocation2.read_to_string(), - ); - - // stack top should now be "foo" + "barz" = 7 - assert_eq!( - 7 as MemoryInt, - MemoryInt::from(stack.top()), - ); - - // should NOT be able to deallocate "foo" - assert!(stack.deallocate(allocation).is_err()); - - // should be able to deallocate "barz" - stack.deallocate(allocation2).unwrap(); - assert_eq!( - 3 as MemoryInt, - MemoryInt::from(stack.top()), - ); - - // should be able to allocate/deallocate something else - let allocation3 = stack.write_string("a").unwrap(); - assert_eq!( - 4 as MemoryInt, - MemoryInt::from(stack.top()), - ); - stack.deallocate(allocation3).unwrap(); - assert_eq!( - 3 as MemoryInt, - MemoryInt::from(stack.top()), - ); - - // returning allocation as ribosome encoding should make "foo" visible outside wasm - allocation.as_ribosome_encoding() -} - -#[no_mangle] -pub extern "C" fn error_report(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - let mut stack = WasmStack::default(); - zome_assert!(stack, false); - RibosomeEncodedValue::Success.into() -} - -#[no_mangle] -pub extern "C" fn store_as_json(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - let mut stack = WasmStack::default(); - assert_eq!(0, MemoryInt::from(stack.top())); - - let s = "fish"; - match stack.write_json(RawString::from(s)) { - Ok(allocation) => { - assert_eq!( - // "\"fish\"" - 6 as MemoryInt, - MemoryInt::from(stack.top()), - ); - allocation.as_ribosome_encoding() - }, - Err(allocation_error) => allocation_error.as_ribosome_encoding(), - } -} - -#[no_mangle] -pub extern "C" fn store_struct_as_json(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - let mut stack = WasmStack::default(); - assert_eq!(0, MemoryInt::from(stack.top())); - - let obj = TestStruct { - value: "first".to_string(), - list: vec!["hello".to_string(), "world!".to_string()], - }; - match stack.write_json(obj.clone()) { - Ok(allocation) => { - assert_eq!( - JsonString::from(obj).to_string().len() as MemoryInt, - MemoryInt::from(stack.top()), - ); - allocation.as_ribosome_encoding() - }, - Err(allocation_error) => allocation_error.as_ribosome_encoding(), - } -} - -#[no_mangle] -pub extern "C" fn load_json_struct(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - let encoded = store_struct_as_json(0); - - let allocation = match WasmAllocation::try_from_ribosome_encoding(encoded) { - Ok(allocation) => allocation, - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - }; - - let mut stack = match WasmStack::try_from(allocation) { - Ok(stack) => stack, - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - }; - - let maybe_test_struct: Result = load_ribosome_encoded_json(encoded); - match maybe_test_struct { - Ok(test_struct) => { - return_code_for_allocation_result( - stack.write_json(test_struct) - ) - .into() - }, - Err(holochain_err) => RibosomeEncodedValue::from(holochain_err).into(), - } -} - -#[no_mangle] -pub extern "C" fn stacked_json(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - let mut stack = WasmStack::default(); - - let first = match stack.write_json(RawString::from("first")) { - Ok(first) => first, - Err(first_error) => return first_error.as_ribosome_encoding(), - }; - if let Err(second_error) = stack.write_json(RawString::from("second")) { - return second_error.as_ribosome_encoding(); - } - - first.as_ribosome_encoding() -} - -#[no_mangle] -pub extern "C" fn stacked_json_struct(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - let mut stack = WasmStack::default(); - - let first = match stack.write_json(TestStruct { - value: "first".to_string(), - list: vec!["hello".to_string(), "world!".to_string()], - }) { - Ok(first) => first, - Err(first_error) => return first_error.as_ribosome_encoding(), - }; - - if let Err(second_error) = stack.write_json(TestStruct { - value: "second".to_string(), - list: vec!["hello".to_string(), "world!".to_string()], - }) { - return second_error.as_ribosome_encoding(); - } - - first.as_ribosome_encoding() -} - -#[no_mangle] -pub extern "C" fn store_json_err(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - let allmost_full_alloc = 0b11111111111111111111111111111101_00000000000000000000000000000010; - - let allocation = match WasmAllocation::try_from_ribosome_encoding(allmost_full_alloc) { - Ok(allocation) => allocation, - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - }; - - let mut stack = match WasmStack::try_from(allocation) { - Ok(stack) => stack, - Err(allocation_error) => return allocation_error.as_ribosome_encoding(), - }; - - let obj = TestStruct { - value: "first".to_string(), - list: vec!["hello".to_string(), "world!".to_string()], - }; - - match stack.write_json(obj.clone()) { - Ok(allocation) => allocation.as_ribosome_encoding(), - Err(allocation_error) => allocation_error.as_ribosome_encoding(), - } -} - -#[no_mangle] -pub extern "C" fn load_json_err(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - let mut stack = WasmStack::default(); - - let encoded = 1 << 32; - let maybe_test_struct: Result = load_ribosome_encoded_json(encoded); - let test_struct = match maybe_test_struct { - Ok(test_struct) => test_struct, - Err(holochain_error) => return RibosomeEncodedValue::from(holochain_error).into(), - }; - - match stack.write_json(test_struct) { - Ok(allocation) => allocation.as_ribosome_encoding(), - Err(allocation_error) => allocation_error.as_ribosome_encoding(), - } -} - -#[no_mangle] -pub extern "C" fn stacked_mix(_: RibosomeEncodingBits) -> RibosomeEncodingBits { - let mut stack = WasmStack::default(); - - if let Err(first_error) = stack.write_json(TestStruct { - value: "first".to_string(), - list: vec!["hello".to_string(), "world!".to_string()], - }) { - return first_error.as_ribosome_encoding(); - } - - if let Err(second_error) = stack.write_json(RawString::from("second")) { - return second_error.as_ribosome_encoding(); - } - - let third = match stack.write_json(RawString::from("third")) { - Ok(third) => third, - Err(third_error) => return third_error.as_ribosome_encoding(), - }; - - if let Err(fourth_error) = stack.write_json(RawString::from("fourth")) { - return fourth_error.as_ribosome_encoding(); - } - - if let Err(fifth_error) = stack.write_json(TestStruct { - value: "fifth".to_string(), - list: vec!["fifthlist".to_string()], - }) { - return fifth_error.as_ribosome_encoding(); - } - - third.as_ribosome_encoding() -} - -// =============================================================================================== -// END MEMORY -// ----------------------------------------------------------------------------------------------- diff --git a/doc/architecture/README.md b/doc/architecture/README.md index 1ff57d59fb..77323cc45d 100644 --- a/doc/architecture/README.md +++ b/doc/architecture/README.md @@ -18,7 +18,7 @@ Holochain applications have been designed to consist at the low-level of WebAsse [`hdk-rust`](/hdk-rust) is a solid reference implementation of this, that enables Zomes to be written in the Rust language (the same, somewhat confusingly, as Holochain Core). -Within this repository, some aspects cross over between `core` and `hdk-rust`, such as [core_types](/core_types), since they get stored into WASM memory in `core`, and then loaded from WASM memory, within `hdk-rust`. Related, [wasm_utils](/wasm_utils) is used on both sides to actually perform the storing, and loading, of values into and from WASM memory. +Within this repository, some aspects cross over between `core` and `hdk-rust`, such as [core_types](/core_types), since they get stored into WASM memory in `core`, and then loaded from WASM memory, within `hdk-rust`. Related, [wasm_engine](/wasm_engine) is used on both sides to actually perform the storing, and loading, of values into and from WASM memory. ### Other HDKs and language options Any language that compiles to WASM and can serialize/deserialize JSON data can be available as an option for programmers to write Holochain applications. diff --git a/doc/holochain_101/src/json_string.md b/doc/holochain_101/src/json_string.md index 65b99d30f9..5a7c60d6d6 100644 --- a/doc/holochain_101/src/json_string.md +++ b/doc/holochain_101/src/json_string.md @@ -828,15 +828,15 @@ for all zome funtions: pub fn store_as_json>( stack: &mut WasmStack, jsonable: J, -) -> Result { +) -> Result { let j: JsonString = jsonable .try_into() - .map_err(|_| RibosomeErrorCode::ArgumentDeserializationFailed)?; + .map_err(|_| WasmErrorCode::ArgumentDeserializationFailed)?; let json_bytes = j.into_bytes(); let json_bytes_len = json_bytes.len() as u32; if json_bytes_len > U16_MAX { - return Err(RibosomeErrorCode::OutOfMemory); + return Err(WasmErrorCode::OutOfMemory); } write_in_wasm_memory(stack, &json_bytes, json_bytes_len as u16) } diff --git a/doc/holochain_101/src/writing_development_kit.md b/doc/holochain_101/src/writing_development_kit.md index 331b2a7473..77e6f0625a 100644 --- a/doc/holochain_101/src/writing_development_kit.md +++ b/doc/holochain_101/src/writing_development_kit.md @@ -19,7 +19,7 @@ Holochain sends and receives allocated bytes of memory to zomes by treating the If no bytes of memory are allocated (i.e. the 32 bit length is 0) the high bits map to an internal enum. This enum is contextual to the zome but typically represents errors: ```rust -pub enum RibosomeErrorCode { +pub enum WasmErrorCode { Unspecified = 1 << 32, ArgumentDeserializationFailed = 2 << 32, OutOfMemory = 3 << 32, @@ -72,7 +72,7 @@ The development kit: - Exposes convenience functions for the Holochain API to handle relevant allocation/deallocations - Maps `u64` values to/from encoded error values and `u32` offset/length values for memory allocations -For more details review the unit/integration test suites in `hdk-rust` and `wasm_utils`. +For more details review the unit/integration test suites in `hdk-rust` and `wasm_engine`. ### Crafting the API @@ -100,7 +100,7 @@ The Development Kit should implement and export one function per each native fun In order to call these "external" functions, you will need to import them and provide their signature, but in a WASM import compatible way. In Rust, for example, this is simply: ```rust extern { - fn hc_commit_entry(encoded_allocation_of_input: RibosomeEncodingBits) -> RibosomeEncodingBits; + fn hc_commit_entry(encoded_allocation_of_input: WasmAllocationInt) -> WasmAllocationInt; } ``` diff --git a/doc/holochain_101/src/zome/implementation.md b/doc/holochain_101/src/zome/implementation.md index 4b1dc4aac9..af047d7e72 100644 --- a/doc/holochain_101/src/zome/implementation.md +++ b/doc/holochain_101/src/zome/implementation.md @@ -53,7 +53,7 @@ This function will be called by the invocation dispatch (see above). The `wasmi::RuntimeArgs` passed to the Zome API function contains only a single `u64` value. This is an encoded representation of a single page of memory supported by the memory manager. The 16 high bits are the memory offset and the -16 low bits are the memory length. See the `wasm_utils` crate for more +16 low bits are the memory length. See the `wasm_engine` crate for more implementation details. You don't have to work with the memory manager directly, simply pass the runtime diff --git a/doc/holochain_101/src/zome/system_constants.md b/doc/holochain_101/src/zome/system_constants.md index 26533d4b60..e98218abff 100644 --- a/doc/holochain_101/src/zome/system_constants.md +++ b/doc/holochain_101/src/zome/system_constants.md @@ -3,10 +3,9 @@ Note: Full reference is available in language-specific API Reference documentation. (TODO add links) -| Name | Purpose | -| ------------- |:-------------| -| VERSION | Version of the Holochain software running the zome | -| HashNotFound | Value returned when a hash provided could not be found. | +| Name | Purpose | +| ------------- |:-------------| +| VERSION | Version of the Holochain software running the zome | | Status | Enum holding all possible state of an entry. | | GetEntryMask | Mask values used for calling the `get_entry` Zome API Function. | | LinkAction | Constants used for calling the `link_entries` Zome API Function. | diff --git a/release/publish/default.nix b/release/publish/default.nix index fb18e9073e..404cc71251 100644 --- a/release/publish/default.nix +++ b/release/publish/default.nix @@ -67,7 +67,7 @@ for crate in \ common \ metrics \ core_types \ - wasm_utils \ + wasm_engine \ conductor_api \ dpki \ sim2h \ diff --git a/release/version/default.nix b/release/version/default.nix index 0a01948212..3139dbd731 100644 --- a/release/version/default.nix +++ b/release/version/default.nix @@ -7,7 +7,7 @@ for dep in \ holochain_metrics \ holochain_core_types \ holochain_core \ - holochain_wasm_utils \ + holochain_wasm_engine \ holochain_common \ holochain_conductor_lib \ holochain_dpki \ diff --git a/rust/wasm/compile/default.nix b/rust/wasm/compile/default.nix index 34f02bef71..e6e8def5ea 100644 --- a/rust/wasm/compile/default.nix +++ b/rust/wasm/compile/default.nix @@ -4,7 +4,6 @@ let paths = [ "crates/hdk/wasm-test" - "crates/wasm_utils/wasm-test/integration-test" "crates/conductor_lib/wasm-test" "crates/conductor_lib/test-bridge-caller" "crates/core/src/nucleus/actions/wasm-test" diff --git a/test_utils/Cargo.toml b/test_utils/Cargo.toml index 921c46aca7..eec5d8fd39 100644 --- a/test_utils/Cargo.toml +++ b/test_utils/Cargo.toml @@ -14,8 +14,8 @@ holochain_net = { version = "=0.0.43-alpha3", path = "../crates/net" } holochain_core = { version = "=0.0.43-alpha3", path = "../crates/core" } holochain_conductor_lib = { version = "=0.0.43-alpha3", path = "../crates/conductor_lib" } holochain_core_types = { version = "=0.0.43-alpha3", path = "../crates/core_types" } +holochain_wasm_types = { version = "=0.0.43-alpha3", path = "../crates/wasm_types" } holochain_dpki = { version = "=0.0.43-alpha3", path = "../crates/dpki" } -holochain_wasm_utils = { version = "=0.0.43-alpha3", path = "../crates/wasm_utils" } holochain_locksmith = { version = "=0.0.43-alpha3", path = "../crates/locksmith" } holochain_persistence_api = "=0.0.17" holochain_json_api = "=0.0.23" diff --git a/test_utils/src/lib.rs b/test_utils/src/lib.rs index a9c888facd..88b1238923 100755 --- a/test_utils/src/lib.rs +++ b/test_utils/src/lib.rs @@ -40,8 +40,8 @@ use holochain_persistence_api::cas::content::{Address, AddressableContent}; use holochain_net::p2p_config::P2pConfig; -use holochain_wasm_utils::{ - api_serialization::get_entry::{GetEntryResult, StatusRequestKind}, +use holochain_wasm_types::get_entry::{GetEntryResult, StatusRequestKind}; +use holochain_core::wasm_engine::io::{ wasm_target_dir, }; @@ -405,6 +405,7 @@ pub fn start_holochain_instance>( "check_query", "check_app_entry_address", "check_sys_entry_address", + "check_call_inner", "check_call", "check_call_with_args", "send_message", @@ -539,16 +540,6 @@ pub fn example_valid_entry() -> Entry { ) } -pub fn empty_string_validation_fail_entry() -> Entry { - Entry::App( - "empty_validation_response_tester".into(), - TestEntry { - stuff: "should fail with empty string".into(), - } - .into(), - ) -} - pub fn example_valid_entry_result() -> GetEntryResult { let entry = example_valid_entry(); let entry_with_meta = &EntryWithMeta {