From bbd68d7b23c3538bddc2948da79545eee3768885 Mon Sep 17 00:00:00 2001 From: Daniel Gushchyan <39884512+dangush@users.noreply.github.com> Date: Tue, 6 Aug 2024 13:50:11 -0700 Subject: [PATCH] feat: quartz cli handshake, contract deploy (#126) --- .cargo/config.toml | 2 +- Cargo.lock | 347 ++++++++++-------- .../contracts/cw-tee-mtcs/.cargo/config.toml | 7 + apps/mtcs/contracts/cw-tee-mtcs/Cargo.lock | 34 +- apps/mtcs/contracts/cw-tee-mtcs/Cargo.toml | 5 + .../cw-tee-mtcs/{src => }/bin/schema.rs | 0 .../contracts/cw-tee-mtcs/src/contract.rs | 2 +- apps/mtcs/contracts/cw-tee-mtcs/src/msg.rs | 84 +++-- apps/mtcs/enclave/src/lib.rs | 1 + apps/mtcs/enclave/src/main.rs | 2 +- apps/mtcs/enclave/src/mtcs_server.rs | 37 +- apps/mtcs/enclave/src/types.rs | 9 + apps/mtcs/scripts/src/bin/deploy.rs | 10 +- apps/mtcs/scripts/src/bin/handshake.rs | 4 +- apps/mtcs/scripts/src/bin/listen.rs | 39 +- apps/mtcs/scripts/start.sh | 17 +- apps/transfers/contracts/Cargo.lock | 94 +++++ apps/transfers/contracts/Cargo.toml | 1 + apps/transfers/scripts/start.sh | 5 +- cli/Cargo.toml | 26 ++ cli/src/cli.rs | 70 +++- cli/src/error.rs | 4 +- cli/src/handler.rs | 18 +- cli/src/handler/contract_deploy.rs | 111 ++++++ cli/src/handler/enclave_build.rs | 8 +- cli/src/handler/handshake.rs | 197 ++++++++++ cli/src/handler/init.rs | 13 +- cli/src/handler/utils/helpers.rs | 87 +++++ cli/src/handler/utils/mod.rs | 2 + cli/src/handler/utils/types.rs | 57 +++ cli/src/main.rs | 25 +- cli/src/request.rs | 95 ++++- cli/src/request/contract_deploy.rs | 39 ++ cli/src/request/handshake.rs | 22 ++ cli/src/response.rs | 9 +- cli/src/response/contract_deploy.rs | 15 + cli/src/response/handshake.rs | 14 + core/quartz-common/Cargo.toml | 2 +- cosmwasm/packages/quartz-cw/Cargo.toml | 1 + .../quartz-cw/src/handler/execute/attested.rs | 9 +- .../quartz-cw/src/msg/execute/attested.rs | 2 +- relayer/scripts/relay.sh | 8 +- relayer/src/main.rs | 6 +- utils/cycles-sync/src/bin/submit.rs | 2 +- utils/cycles-sync/src/main.rs | 2 +- utils/cycles-sync/src/wasmd_client.rs | 43 ++- utils/tm-prover/src/config.rs | 8 +- utils/tm-prover/src/main.rs | 11 + utils/tm-prover/src/prover.rs | 13 +- 49 files changed, 1282 insertions(+), 337 deletions(-) create mode 100644 apps/mtcs/contracts/cw-tee-mtcs/.cargo/config.toml rename apps/mtcs/contracts/cw-tee-mtcs/{src => }/bin/schema.rs (100%) create mode 100644 cli/src/handler/contract_deploy.rs create mode 100644 cli/src/handler/handshake.rs create mode 100644 cli/src/handler/utils/helpers.rs create mode 100644 cli/src/handler/utils/mod.rs create mode 100644 cli/src/handler/utils/types.rs create mode 100644 cli/src/request/contract_deploy.rs create mode 100644 cli/src/request/handshake.rs create mode 100644 cli/src/response/contract_deploy.rs create mode 100644 cli/src/response/handshake.rs diff --git a/.cargo/config.toml b/.cargo/config.toml index 671364f..87b6f73 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,5 +1,5 @@ [alias] -wasm = "build --release --lib --target wasm32-unknown-unknown" +wasm = "build --release --target wasm32-unknown-unknown --lib" unit-test = "test --lib" schema = "run --bin schema" diff --git a/Cargo.lock b/Cargo.lock index 71d725f..02d6859 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -72,7 +72,7 @@ dependencies = [ "cfg-if", "once_cell", "version_check", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -92,9 +92,9 @@ checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" [[package]] name = "anstyle" -version = "1.0.7" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b" +checksum = "1bec1de6f59aedf83baf9ff929c98f2ad654b97c9510f4e70cf6f661d49fd5b1" [[package]] name = "anyhow" @@ -225,9 +225,9 @@ dependencies = [ [[package]] name = "arrayref" -version = "0.3.7" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545" +checksum = "9d151e35f61089500b617991b791fc8bfd237ae50cd5950803758a179b41e67a" [[package]] name = "arrayvec" @@ -237,9 +237,9 @@ checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" [[package]] name = "asn1-rs" -version = "0.6.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22ad1373757efa0f70ec53939aabc7152e1591cb485208052993070ac8d2429d" +checksum = "5493c3bedbacf7fd7382c6346bbd66687d12bbaad3a89a2d2c303ee6cf20b048" dependencies = [ "asn1-rs-derive", "asn1-rs-impl", @@ -253,13 +253,13 @@ dependencies = [ [[package]] name = "asn1-rs-derive" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7378575ff571966e99a744addeff0bff98b8ada0dedf1956d59e634db95eaac1" +checksum = "965c2d33e53cb6b267e148a4cb0760bc01f4904c1cd4bb4002a085bb016d1490" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", "synstructure", ] @@ -271,7 +271,7 @@ checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -293,7 +293,7 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -304,7 +304,7 @@ checksum = "6e0c28dcc82d7c8ead5cb13beb15405b57b8546e93215673ff8ca0349a028107" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -537,18 +537,18 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.6.1" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a12916984aab3fa6e39d655a33e09c0071eb36d6ab3aea5c2d78551f1df6d952" +checksum = "fca2be1d5c43812bae364ee3f30b3afcb7877cf59f4aeb94c66f313a41d2fac9" dependencies = [ "serde", ] [[package]] name = "cc" -version = "1.1.5" +version = "1.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "324c74f2155653c90b04f25b2a47a8a631360cb908f92a772695f430c7e31052" +checksum = "26a5c3fd7bfa1ce3897a3a3501d362b2d87b7f2583ebcb4a949ec25911025cbc" [[package]] name = "cfg-if" @@ -578,9 +578,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.11" +version = "4.5.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35723e6a11662c2afb578bcf0b88bf6ea8e21282a953428f240574fcc3a2b5b3" +checksum = "c53aa12ec67affac065e7c7dd20a42fa2a4094921b655711d5d3107bb3d52bed" dependencies = [ "clap_builder", "clap_derive", @@ -588,9 +588,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.11" +version = "4.5.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49eb96cbfa7cfa35017b7cd548c75b14c3118c98b423041d70562665e07fb0fa" +checksum = "efbdf2dd5fe10889e0c61942ff5d948aaf12fd0b4504408ab0cbb1916c2cffa9" dependencies = [ "anstyle", "clap_lex", @@ -605,14 +605,14 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] name = "clap_lex" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b82cf0babdbd58558212896d1a4272303a57bdb245c2bf1147185fb45640e70" +checksum = "1462739cb27611015575c0c11df5df7601141071f07518d56fcc1be504cbec97" [[package]] name = "color-eyre" @@ -699,9 +699,9 @@ dependencies = [ [[package]] name = "cosmwasm-core" -version = "2.1.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d075f6bb1483a6ce83b5cbc73a3a1207e0316ac1e34ed1f2a4d9fc3a0f07bf6" +checksum = "367fc87c43759098a476ef90f915aadc66c300480ad9c155b512081fbf327bc1" [[package]] name = "cosmwasm-crypto" @@ -719,9 +719,9 @@ dependencies = [ [[package]] name = "cosmwasm-crypto" -version = "2.1.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88ced5a6dd2801a383d3e14e5ae5caa7fdfeff1bd9f22b30e810e0aded8a5869" +checksum = "9b7c41f3e371ea457d3b98bb592c38858b46efcf614e0e988ec2ebbdb973954f" dependencies = [ "ark-bls12-381", "ark-ec", @@ -751,13 +751,13 @@ dependencies = [ [[package]] name = "cosmwasm-derive" -version = "2.1.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35bd1873f84d9b17edf8a90ffe10a89a649b82feacc00e36788b81d2c3cbf03c" +checksum = "c10510e8eb66cf7e109741b1e2c76ad18f30b5a1daa064f5f7115c1f733aaea0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -775,11 +775,11 @@ dependencies = [ [[package]] name = "cosmwasm-schema" -version = "2.1.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27984b137eb2ac561f97f6bdb02004a98eb6f2ba263062c140b8e231ee1826b7" +checksum = "f79879b6b7ef6a331b05030ce91ce46a7c4b0baf1ed6b382cce2e9a168109380" dependencies = [ - "cosmwasm-schema-derive 2.1.0", + "cosmwasm-schema-derive 2.1.1", "schemars", "serde", "serde_json", @@ -799,13 +799,13 @@ dependencies = [ [[package]] name = "cosmwasm-schema-derive" -version = "2.1.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4ef0d201f611bdb6c9124207032423eb956f1fc8ab3e3ee7253a9c08a5f5809" +checksum = "82b53e33c0e97170c7ac9cb440f4bc599a07f9cbb9b7e87916cca37b1239d57b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -832,16 +832,16 @@ dependencies = [ [[package]] name = "cosmwasm-std" -version = "2.1.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2522fb5c9a0409712bb1d036128bccf3564e6b2ac82f942ae4cf3c8df3e26fa8" +checksum = "92011c39570876f340d5f9defa68bf92797b1c44421f1b9ea9b04a31d6defd33" dependencies = [ "base64 0.22.1", "bech32 0.11.0", "bnum 0.11.0", "cosmwasm-core", - "cosmwasm-crypto 2.1.0", - "cosmwasm-derive 2.1.0", + "cosmwasm-crypto 2.1.1", + "cosmwasm-derive 2.1.1", "derive_more 1.0.0-beta.6", "hex", "rand_core 0.6.4", @@ -970,7 +970,7 @@ checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1013,7 +1013,7 @@ checksum = "e0034bfb4c06dfc8b50f0b1a06c3fc0f2312a1bae568a97db65930de071288ba" dependencies = [ "anyhow", "bech32 0.11.0", - "cosmwasm-std 2.1.0", + "cosmwasm-std 2.1.1", "cw-storage-plus 2.0.0", "cw-utils 2.0.0", "derivative", @@ -1072,7 +1072,7 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f13360e9007f51998d42b1bc6b7fa0141f74feae61ed5fd1e5b0a89eec7b5de1" dependencies = [ - "cosmwasm-std 2.1.0", + "cosmwasm-std 2.1.1", "schemars", "serde", ] @@ -1081,8 +1081,8 @@ dependencies = [ name = "cw-tee-mtcs" version = "0.1.0" dependencies = [ - "cosmwasm-schema 2.1.0", - "cosmwasm-std 2.1.0", + "cosmwasm-schema 2.1.1", + "cosmwasm-std 2.1.1", "cw-storage-plus 2.0.0", "cw2 2.0.0", "cw20", @@ -1118,8 +1118,8 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07dfee7f12f802431a856984a32bce1cb7da1e6c006b5409e3981035ce562dec" dependencies = [ - "cosmwasm-schema 2.1.0", - "cosmwasm-std 2.1.0", + "cosmwasm-schema 2.1.1", + "cosmwasm-std 2.1.1", "schemars", "serde", "thiserror", @@ -1146,8 +1146,8 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b04852cd38f044c0751259d5f78255d07590d136b8a86d4e09efdd7666bd6d27" dependencies = [ - "cosmwasm-schema 2.1.0", - "cosmwasm-std 2.1.0", + "cosmwasm-schema 2.1.1", + "cosmwasm-std 2.1.1", "cw-storage-plus 2.0.0", "schemars", "semver", @@ -1161,8 +1161,8 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a42212b6bf29bbdda693743697c621894723f35d3db0d5df930be22903d0e27c" dependencies = [ - "cosmwasm-schema 2.1.0", - "cosmwasm-std 2.1.0", + "cosmwasm-schema 2.1.1", + "cosmwasm-std 2.1.1", "cw-utils 2.0.0", "schemars", "serde", @@ -1174,8 +1174,8 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6de8c32e100f1fca306972d86b617234a5e6b00594ea2b48716fd6804d4d95d" dependencies = [ - "cosmwasm-schema 2.1.0", - "cosmwasm-std 2.1.0", + "cosmwasm-schema 2.1.1", + "cosmwasm-std 2.1.1", "cw-storage-plus 2.0.0", "cw2 2.0.0", "cw20", @@ -1194,7 +1194,7 @@ dependencies = [ "bip32", "clap", "cosmrs", - "cosmwasm-std 2.1.0", + "cosmwasm-std 2.1.1", "cw-tee-mtcs", "displaydoc", "ecies", @@ -1232,7 +1232,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1243,7 +1243,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1287,7 +1287,7 @@ checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1318,7 +1318,7 @@ checksum = "5f33878137e4dafd7fa914ad4e259e18a4e8e532b9617a2d0150262bf53abfce" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1338,7 +1338,7 @@ checksum = "2bba3e9872d7c58ce7ef0fcf1844fcc3e23ef2a58377b50df35dd98e42a5726e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", "unicode-xid", ] @@ -1371,7 +1371,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1634,7 +1634,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1727,7 +1727,7 @@ dependencies = [ "futures-sink", "futures-util", "http 0.2.12", - "indexmap 2.2.6", + "indexmap 2.3.0", "slab", "tokio", "tokio-util", @@ -1948,7 +1948,7 @@ dependencies = [ "http 1.1.0", "hyper 1.4.1", "hyper-util", - "rustls 0.23.11", + "rustls 0.23.12", "rustls-pki-types", "tokio", "tokio-rustls 0.26.0", @@ -2039,9 +2039,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.2.6" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" +checksum = "de3fc2e30ba82dd1b3911c8de1ffc143c74a914a14e99514d7637e3099df5ea0" dependencies = [ "equivalent", "hashbrown 0.14.5", @@ -2344,13 +2344,14 @@ dependencies = [ [[package]] name = "mio" -version = "0.8.11" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" +checksum = "4569e456d394deccd22ce1c1913e6ea0e54519f577285001215d33557431afe4" dependencies = [ + "hermit-abi", "libc", "wasi", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -2374,7 +2375,7 @@ dependencies = [ "clap", "color-eyre", "cosmrs", - "cosmwasm-std 2.1.0", + "cosmwasm-std 2.1.1", "cw-multi-test 2.1.0", "cw-tee-mtcs", "ecies", @@ -2400,7 +2401,7 @@ dependencies = [ "bip32", "clap", "cosmrs", - "cosmwasm-std 2.1.0", + "cosmwasm-std 2.1.1", "ecies", "hex", "k256", @@ -2473,7 +2474,7 @@ checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -2516,16 +2517,6 @@ dependencies = [ "autocfg", ] -[[package]] -name = "num_cpus" -version = "1.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" -dependencies = [ - "hermit-abi", - "libc", -] - [[package]] name = "object" version = "0.32.2" @@ -2621,9 +2612,9 @@ dependencies = [ [[package]] name = "peg" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a625d12ad770914cbf7eff6f9314c3ef803bfe364a1b20bc36ddf56673e71e5" +checksum = "295283b02df346d1ef66052a757869b2876ac29a6bb0ac3f5f7cd44aebe40e8f" dependencies = [ "peg-macros", "peg-runtime", @@ -2631,9 +2622,9 @@ dependencies = [ [[package]] name = "peg-macros" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f241d42067ed3ab6a4fece1db720838e1418f36d868585a27931f95d6bc03582" +checksum = "bdad6a1d9cf116a059582ce415d5f5566aabcd4008646779dab7fdc2a9a9d426" dependencies = [ "peg-runtime", "proc-macro2", @@ -2678,7 +2669,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" dependencies = [ "fixedbitset", - "indexmap 2.2.6", + "indexmap 2.3.0", ] [[package]] @@ -2698,7 +2689,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -2743,9 +2734,12 @@ checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" [[package]] name = "ppv-lite86" -version = "0.2.17" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" +checksum = "dee4364d9f3b902ef14fab8a1ddffb783a1cb6b4bba3bfc1fa3922732c7de97f" +dependencies = [ + "zerocopy 0.6.6", +] [[package]] name = "prettyplease" @@ -2754,7 +2748,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e" dependencies = [ "proc-macro2", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -2802,7 +2796,7 @@ dependencies = [ "prost", "prost-types", "regex", - "syn 2.0.71", + "syn 2.0.72", "tempfile", ] @@ -2816,7 +2810,7 @@ dependencies = [ "itertools 0.12.1", "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -2832,12 +2826,35 @@ dependencies = [ name = "quartz" version = "0.1.0" dependencies = [ + "anyhow", + "async-trait", + "base64 0.22.1", "clap", "color-eyre", + "cosmrs", + "cosmwasm-std 2.1.1", + "cycles-sync", "displaydoc", + "futures-util", + "hex", + "k256", + "mtcs-enclave", + "once_cell", + "prost", + "quartz-common", + "quartz-tee-ra", + "regex", + "reqwest 0.12.5", "serde", "serde_json", + "subtle-encoding", + "tendermint 0.36.0", + "tendermint-light-client", + "tendermint-rpc", "thiserror", + "tm-prover", + "tokio", + "tonic", "tracing", "tracing-subscriber", ] @@ -2850,7 +2867,7 @@ dependencies = [ "clap", "color-eyre", "cosmrs", - "cosmwasm-std 2.1.0", + "cosmwasm-std 2.1.1", "cw-multi-test 0.17.0", "cycles-sync", "ecies", @@ -2883,13 +2900,14 @@ dependencies = [ name = "quartz-cw" version = "0.1.0" dependencies = [ - "cosmwasm-schema 2.1.0", - "cosmwasm-std 2.1.0", + "cosmwasm-schema 2.1.1", + "cosmwasm-std 2.1.1", "cw-storage-plus 2.0.0", "k256", "quartz-tee-ra", "serde", "serde_json", + "serde_with", "sha2 0.10.8", "thiserror", ] @@ -2901,7 +2919,7 @@ dependencies = [ "clap", "color-eyre", "cosmrs", - "cosmwasm-std 2.1.0", + "cosmwasm-std 2.1.1", "cw-proof", "ecies", "hex", @@ -2937,7 +2955,7 @@ dependencies = [ "clap", "cosmos-sdk-proto", "cosmrs", - "cosmwasm-std 2.1.0", + "cosmwasm-std 2.1.1", "displaydoc", "ecies", "k256", @@ -2958,8 +2976,8 @@ dependencies = [ name = "quartz-tee-ra" version = "0.1.0" dependencies = [ - "cosmwasm-schema 2.1.0", - "cosmwasm-std 2.1.0", + "cosmwasm-schema 2.1.1", + "cosmwasm-std 2.1.1", "der", "displaydoc", "hex", @@ -2989,7 +3007,7 @@ dependencies = [ "quinn-proto", "quinn-udp", "rustc-hash", - "rustls 0.23.11", + "rustls 0.23.12", "thiserror", "tokio", "tracing", @@ -3005,7 +3023,7 @@ dependencies = [ "rand", "ring", "rustc-hash", - "rustls 0.23.11", + "rustls 0.23.12", "slab", "thiserror", "tinyvec", @@ -3014,14 +3032,13 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.2" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9096629c45860fc7fb143e125eb826b5e721e10be3263160c7d60ca832cf8c46" +checksum = "8bffec3605b73c6f1754535084a85229fa8a30f86014e6c81aeec4abb68b0285" dependencies = [ "libc", "once_cell", "socket2", - "tracing", "windows-sys 0.52.0", ] @@ -3208,7 +3225,7 @@ dependencies = [ "percent-encoding", "pin-project-lite", "quinn", - "rustls 0.23.11", + "rustls 0.23.12", "rustls-pemfile 2.1.2", "rustls-pki-types", "serde", @@ -3324,21 +3341,21 @@ dependencies = [ "log", "ring", "rustls-pki-types", - "rustls-webpki 0.102.5", + "rustls-webpki 0.102.6", "subtle", "zeroize", ] [[package]] name = "rustls" -version = "0.23.11" +version = "0.23.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4828ea528154ae444e5a642dbb7d5623354030dc9822b83fd9bb79683c7399d0" +checksum = "c58f8c84392efc0a126acce10fa59ff7b3d2ac06ab451a33f2741989b806b044" dependencies = [ "once_cell", "ring", "rustls-pki-types", - "rustls-webpki 0.102.5", + "rustls-webpki 0.102.6", "subtle", "zeroize", ] @@ -3405,9 +3422,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.102.5" +version = "0.102.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9a6fccd794a42c2c105b513a2f62bc3fd8f3ba57a4593677ceb0bd035164d78" +checksum = "8e6b52d4fda176fd835fdc55a835d4a89b8499cad995885a21149d5ad62f852e" dependencies = [ "ring", "rustls-pki-types", @@ -3465,7 +3482,7 @@ dependencies = [ "proc-macro2", "quote", "serde_derive_internals", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -3483,7 +3500,7 @@ dependencies = [ "clap", "color-eyre", "cosmrs", - "cosmwasm-std 2.1.0", + "cosmwasm-std 2.1.1", "cw-proof", "cw-tee-mtcs", "cycles-sync", @@ -3619,7 +3636,7 @@ checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -3630,16 +3647,17 @@ checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] name = "serde_json" -version = "1.0.120" +version = "1.0.121" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e0d21c9a8cae1235ad58a00c11cb40d4b1e5c784f1ef2c537876ed6ffd8b7c5" +checksum = "4ab380d7d9f22ef3f21ad3e6c1ebe8e4fc7a2000ccba2e4d71fc96f15b2cb609" dependencies = [ "itoa", + "memchr", "ryu", "serde", ] @@ -3652,14 +3670,14 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] name = "serde_spanned" -version = "0.6.6" +version = "0.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79e674e01f999af37c49f70a6ede167a8a60b2503e56c5599532a65baa5969a0" +checksum = "eb5b1b31579f3811bf615c144393417496f152e12ac8b7663bf664f4a815306d" dependencies = [ "serde", ] @@ -3701,7 +3719,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -3855,9 +3873,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.71" +version = "2.0.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b146dcf730474b4bcd16c311627b31ede9ab149045db4d6088b3becaea046462" +checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" dependencies = [ "proc-macro2", "quote", @@ -3884,7 +3902,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -4142,7 +4160,7 @@ checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -4232,19 +4250,18 @@ dependencies = [ [[package]] name = "tokio" -version = "1.38.1" +version = "1.39.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb2caba9f80616f438e09748d5acda951967e1ea58508ef53d9c6402485a46df" +checksum = "daa4fb1bc778bd6f04cbfc4bb2d06a7396a8f299dc33ea1900cedaa316f467b1" dependencies = [ "backtrace", "bytes", "libc", "mio", - "num_cpus", "pin-project-lite", "socket2", "tokio-macros", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -4259,13 +4276,13 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a" +checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -4295,7 +4312,7 @@ version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" dependencies = [ - "rustls 0.23.11", + "rustls 0.23.12", "rustls-pki-types", "tokio", ] @@ -4338,9 +4355,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.15" +version = "0.8.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac2caab0bf757388c6c0ae23b3293fdb463fee59434529014f85e3263b995c28" +checksum = "a1ed1f98e3fdc28d6d910e6737ae6ab1a93bf1985935a1193e68f93eeb68d24e" dependencies = [ "serde", "serde_spanned", @@ -4350,20 +4367,20 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "0.6.6" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4badfd56924ae69bcc9039335b2e017639ce3f9b001c393c1b2d1ef846ce2cbf" +checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41" dependencies = [ "serde", ] [[package]] name = "toml_edit" -version = "0.22.16" +version = "0.22.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "278f3d518e152219c994ce877758516bca5e118eaed6996192a774fb9fbf0788" +checksum = "583c44c02ad26b0c3f3066fe629275e50627026c51ac2e595cca4c230ce1ce1d" dependencies = [ - "indexmap 2.2.6", + "indexmap 2.3.0", "serde", "serde_spanned", "toml_datetime", @@ -4407,7 +4424,7 @@ dependencies = [ "proc-macro2", "prost-build", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -4461,7 +4478,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -4492,12 +4509,13 @@ dependencies = [ name = "transfers-contract" version = "0.1.0" dependencies = [ - "cosmwasm-schema 2.1.0", - "cosmwasm-std 2.1.0", + "cosmwasm-schema 2.1.1", + "cosmwasm-std 2.1.1", "cw-storage-plus 2.0.0", "cw-utils 2.0.0", "cw2 2.0.0", "cw20-base", + "getrandom", "quartz-common", "serde", "serde_json", @@ -4627,9 +4645,9 @@ dependencies = [ [[package]] name = "version_check" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "walkdir" @@ -4677,7 +4695,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", "wasm-bindgen-shared", ] @@ -4711,7 +4729,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4891,9 +4909,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" -version = "0.6.13" +version = "0.6.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59b5e5f6c299a3c7890b876a2a587f3115162487e704907d9b6cd29473052ba1" +checksum = "68a9bda4691f099d435ad181000724da8e5899daa10713c2d432552b9ccd3a6f" dependencies = [ "memchr", ] @@ -4947,13 +4965,34 @@ dependencies = [ "time", ] +[[package]] +name = "zerocopy" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "854e949ac82d619ee9a14c66a1b674ac730422372ccb759ce0c39cabcf2bf8e6" +dependencies = [ + "byteorder", + "zerocopy-derive 0.6.6", +] + [[package]] name = "zerocopy" version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" dependencies = [ - "zerocopy-derive", + "zerocopy-derive 0.7.35", +] + +[[package]] +name = "zerocopy-derive" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "125139de3f6b9d625c39e2efdd73d41bdac468ccd556556440e322be0e1bbd91" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.72", ] [[package]] @@ -4964,7 +5003,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -4984,5 +5023,5 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] diff --git a/apps/mtcs/contracts/cw-tee-mtcs/.cargo/config.toml b/apps/mtcs/contracts/cw-tee-mtcs/.cargo/config.toml new file mode 100644 index 0000000..314edee --- /dev/null +++ b/apps/mtcs/contracts/cw-tee-mtcs/.cargo/config.toml @@ -0,0 +1,7 @@ +[alias] +wasm = "build --target wasm32-unknown-unknown --release --lib" +wasm-debug = "build --target wasm32-unknown-unknown --lib" +schema = "run schema" + +[net] +git-fetch-with-cli = true \ No newline at end of file diff --git a/apps/mtcs/contracts/cw-tee-mtcs/Cargo.lock b/apps/mtcs/contracts/cw-tee-mtcs/Cargo.lock index f0a4ea1..181508d 100644 --- a/apps/mtcs/contracts/cw-tee-mtcs/Cargo.lock +++ b/apps/mtcs/contracts/cw-tee-mtcs/Cargo.lock @@ -76,6 +76,12 @@ version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "base64ct" version = "1.6.0" @@ -154,6 +160,16 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "chrono" +version = "0.4.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" +dependencies = [ + "num-traits", + "serde", +] + [[package]] name = "const-oid" version = "0.9.6" @@ -184,9 +200,9 @@ dependencies = [ [[package]] name = "cosmwasm-schema" -version = "2.0.4" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "101d0739564bd34cba9b84bf73665f0822487ae3b29b2dd59930608ed3aafd43" +checksum = "f79879b6b7ef6a331b05030ce91ce46a7c4b0baf1ed6b382cce2e9a168109380" dependencies = [ "cosmwasm-schema-derive", "schemars", @@ -197,13 +213,13 @@ dependencies = [ [[package]] name = "cosmwasm-schema-derive" -version = "2.0.4" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf4be75f60158478da2c5d319ed59295bca1687ad50c18215a0485aa91a995ea" +checksum = "82b53e33c0e97170c7ac9cb440f4bc599a07f9cbb9b7e87916cca37b1239d57b" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.70", ] [[package]] @@ -212,7 +228,7 @@ version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ded932165de44cd0717979c34fc3b84d8e8066b8dde4f5bd78f96a643b090f90" dependencies = [ - "base64", + "base64 0.21.7", "bech32 0.9.1", "bnum", "cosmwasm-crypto", @@ -981,6 +997,7 @@ dependencies = [ "quartz-tee-ra", "serde", "serde_json", + "serde_with", "sha2 0.10.8", "thiserror", ] @@ -1173,9 +1190,14 @@ version = "3.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e73139bc5ec2d45e6c5fd85be5a46949c1c39a4c18e56915f5eb4c12f975e377" dependencies = [ + "base64 0.22.1", + "chrono", + "hex", "serde", "serde_derive", + "serde_json", "serde_with_macros", + "time", ] [[package]] diff --git a/apps/mtcs/contracts/cw-tee-mtcs/Cargo.toml b/apps/mtcs/contracts/cw-tee-mtcs/Cargo.toml index 45935d3..821ed8d 100644 --- a/apps/mtcs/contracts/cw-tee-mtcs/Cargo.toml +++ b/apps/mtcs/contracts/cw-tee-mtcs/Cargo.toml @@ -5,6 +5,10 @@ edition = "2021" authors = ["Informal Systems "] exclude = ["contract.wasm", "hash.txt"] +[[bin]] +name = "schema" +path = "bin/schema.rs" + [lib] crate-type = ["cdylib", "rlib"] @@ -47,5 +51,6 @@ quartz-common = { path = "../../../../core/quartz-common/", features = ["contrac getrandom = { version = "0.2.15", features = ["js"] } [dev-dependencies] +cosmwasm-schema = "2.1.1" cw-multi-test = "2.0.0" serde_json = "1.0.113" \ No newline at end of file diff --git a/apps/mtcs/contracts/cw-tee-mtcs/src/bin/schema.rs b/apps/mtcs/contracts/cw-tee-mtcs/bin/schema.rs similarity index 100% rename from apps/mtcs/contracts/cw-tee-mtcs/src/bin/schema.rs rename to apps/mtcs/contracts/cw-tee-mtcs/bin/schema.rs diff --git a/apps/mtcs/contracts/cw-tee-mtcs/src/contract.rs b/apps/mtcs/contracts/cw-tee-mtcs/src/contract.rs index 549e0de..ba5ae40 100644 --- a/apps/mtcs/contracts/cw-tee-mtcs/src/contract.rs +++ b/apps/mtcs/contracts/cw-tee-mtcs/src/contract.rs @@ -33,7 +33,7 @@ pub fn instantiate( msg: InstantiateMsg, ) -> Result { // must be the handled first! - msg.0.handle_raw(deps.branch(), &env, &info)?; + msg.quartz.handle_raw(deps.branch(), &env, &info)?; let state = State { owner: info.sender.to_string(), diff --git a/apps/mtcs/contracts/cw-tee-mtcs/src/msg.rs b/apps/mtcs/contracts/cw-tee-mtcs/src/msg.rs index 9af0268..670a1b5 100644 --- a/apps/mtcs/contracts/cw-tee-mtcs/src/msg.rs +++ b/apps/mtcs/contracts/cw-tee-mtcs/src/msg.rs @@ -12,7 +12,9 @@ use crate::state::{LiquiditySource, RawHash, SettleOff}; pub type AttestedMsg = RawAttested, RA>; #[cw_serde] -pub struct InstantiateMsg(pub QuartzInstantiateMsg); +pub struct InstantiateMsg { + pub quartz: QuartzInstantiateMsg, +} #[cw_serde] #[allow(clippy::large_enum_variant)] @@ -162,47 +164,49 @@ mod tests { fn test_serde_instantiate_msg() { let _: InstantiateMsg = serde_json::from_str( r#"{ - "msg": { - "config": { - "mr_enclave": "1bfb949d235f61e5dc40f874ba3e9c36adef1e7a521b4b5f70e10fb1dc803251", - "epoch_duration": { - "secs": 43200, - "nanos": 0 - }, - "light_client_opts": { - "chain_id": "testing", - "trusted_height": 1, - "trusted_hash": "a1d115ba3a5e9fcc12ed68a9d8669159e9085f6f96ec26619f5c7ceb4ee02869", - "trust_threshold": [ - 2, - 3 - ], - "trusting_period": 1209600, - "max_clock_drift": 5, - "max_block_lag": 5 + "quartz": { + "msg": { + "config": { + "mr_enclave": "1bfb949d235f61e5dc40f874ba3e9c36adef1e7a521b4b5f70e10fb1dc803251", + "epoch_duration": { + "secs": 43200, + "nanos": 0 + }, + "light_client_opts": { + "chain_id": "testing", + "trusted_height": 1, + "trusted_hash": "a1d115ba3a5e9fcc12ed68a9d8669159e9085f6f96ec26619f5c7ceb4ee02869", + "trust_threshold": [ + 2, + 3 + ], + "trusting_period": 1209600, + "max_clock_drift": 5, + "max_block_lag": 5 + } } - } - }, - "attestation": { - "report": { + }, + "attestation": { "report": { - "id": "5246688123689513540899231107533660789", - "timestamp": "2024-02-07T17:06:23.913745", - "version": 4, - "epidPseudonym": "+CUyIi74LPqS6M0NF7YrSxLqPdX3MKs6D6LIPqRG/ZEB4WmxZVvxAJwdwg/0m9cYnUUQguLnJotthX645lAogfJgO8Xg5/91lSegwyUKvHmKgtjOHX/YTbVe/wmgWiBdaL+KmarY0Je459Px/FqGLWLsAF7egPAJRd1Xn88Znrs=", - "advisoryURL": "https://security-center.intel.com", - "advisoryIDs": [ - "INTEL-SA-00161", - "INTEL-SA-00219", - "INTEL-SA-00289", - "INTEL-SA-00334", - "INTEL-SA-00615" - ], - "isvEnclaveQuoteStatus": "CONFIGURATION_AND_SW_HARDENING_NEEDED", - "platformInfoBlob": "150200650000080000141402040180070000000000000000000D00000C000000020000000000000CB0F08115F3DE71AE97980FE5E10B042054930ACE356C79EC44603D3F890756EC6ED73927A7C58CDE9AF1E754AEC77E335E8D80294407936BEB6404F27669FF7BB1", - "isvEnclaveQuoteBody": "AgABALAMAAAPAA8AAAAAAFHK9aSLRQ1iSu/jKG0xSJQAAAAAAAAAAAAAAAAAAAAAFBQCBwGAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAHAAAAAAAAAOPC8qW4QNieBprK/8rbZRDvhmpz06nuVxAO1fhkbuS7AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAc8uUpEUEPvz8ZkFapjVh5WlWaLoAJM/f80T0EhGInHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACRE7C+d+1dDWhoDsdyBrjVh+1AZ5txMhzN1UBeTVSmggAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" - }, - "reportsig": "YcY4SPvkfR4P2E8A5huutCeS+vY/ir+xq6disalNfNtAcUyOIOqTPVXhAZgY1M5B47Hjj1oYWf2qC2w+dnj7VcZjzO9oR0pJYdA+A7jaVrNzH2eXA79yICkuU8WE/x58I0j5vjXLoHXahaKlpZkMeTphqBY8u+FTVSdP3cWPho4viPapTfQRuEWmYq4KIq2zSr6wLg3Pz+yQ+G3e9BASVkLYxdYGTDFH1pMmfas9SEI7V4I+j8DaXmL8bucSRakmcQdmDMPGiA7mvIhSAlprzCrdxM7CHeUC6MPLN1fmFFcc9kyO/ved69j/651MWC83GgxSJ15L80U+DQzmrSW8xg==" + "report": { + "id": "5246688123689513540899231107533660789", + "timestamp": "2024-02-07T17:06:23.913745", + "version": 4, + "epidPseudonym": "+CUyIi74LPqS6M0NF7YrSxLqPdX3MKs6D6LIPqRG/ZEB4WmxZVvxAJwdwg/0m9cYnUUQguLnJotthX645lAogfJgO8Xg5/91lSegwyUKvHmKgtjOHX/YTbVe/wmgWiBdaL+KmarY0Je459Px/FqGLWLsAF7egPAJRd1Xn88Znrs=", + "advisoryURL": "https://security-center.intel.com", + "advisoryIDs": [ + "INTEL-SA-00161", + "INTEL-SA-00219", + "INTEL-SA-00289", + "INTEL-SA-00334", + "INTEL-SA-00615" + ], + "isvEnclaveQuoteStatus": "CONFIGURATION_AND_SW_HARDENING_NEEDED", + "platformInfoBlob": "150200650000080000141402040180070000000000000000000D00000C000000020000000000000CB0F08115F3DE71AE97980FE5E10B042054930ACE356C79EC44603D3F890756EC6ED73927A7C58CDE9AF1E754AEC77E335E8D80294407936BEB6404F27669FF7BB1", + "isvEnclaveQuoteBody": "AgABALAMAAAPAA8AAAAAAFHK9aSLRQ1iSu/jKG0xSJQAAAAAAAAAAAAAAAAAAAAAFBQCBwGAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAHAAAAAAAAAOPC8qW4QNieBprK/8rbZRDvhmpz06nuVxAO1fhkbuS7AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAc8uUpEUEPvz8ZkFapjVh5WlWaLoAJM/f80T0EhGInHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACRE7C+d+1dDWhoDsdyBrjVh+1AZ5txMhzN1UBeTVSmggAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + }, + "reportsig": "YcY4SPvkfR4P2E8A5huutCeS+vY/ir+xq6disalNfNtAcUyOIOqTPVXhAZgY1M5B47Hjj1oYWf2qC2w+dnj7VcZjzO9oR0pJYdA+A7jaVrNzH2eXA79yICkuU8WE/x58I0j5vjXLoHXahaKlpZkMeTphqBY8u+FTVSdP3cWPho4viPapTfQRuEWmYq4KIq2zSr6wLg3Pz+yQ+G3e9BASVkLYxdYGTDFH1pMmfas9SEI7V4I+j8DaXmL8bucSRakmcQdmDMPGiA7mvIhSAlprzCrdxM7CHeUC6MPLN1fmFFcc9kyO/ved69j/651MWC83GgxSJ15L80U+DQzmrSW8xg==" + } } } }"#, diff --git a/apps/mtcs/enclave/src/lib.rs b/apps/mtcs/enclave/src/lib.rs index febacec..2265ace 100644 --- a/apps/mtcs/enclave/src/lib.rs +++ b/apps/mtcs/enclave/src/lib.rs @@ -1 +1,2 @@ pub mod proto; +pub mod types; diff --git a/apps/mtcs/enclave/src/main.rs b/apps/mtcs/enclave/src/main.rs index a2a303c..6a00641 100644 --- a/apps/mtcs/enclave/src/main.rs +++ b/apps/mtcs/enclave/src/main.rs @@ -57,7 +57,7 @@ async fn main() -> Result<(), Box> { let attestor = DefaultAttestor::default(); - let config = Config::new( + let config: Config = Config::new( attestor.mr_enclave()?, Duration::from_secs(30 * 24 * 60), light_client_opts, diff --git a/apps/mtcs/enclave/src/mtcs_server.rs b/apps/mtcs/enclave/src/mtcs_server.rs index ec1e23b..08225f8 100644 --- a/apps/mtcs/enclave/src/mtcs_server.rs +++ b/apps/mtcs/enclave/src/mtcs_server.rs @@ -1,5 +1,5 @@ use std::{ - collections::{BTreeMap, BTreeSet}, + collections::BTreeMap, sync::{Arc, Mutex}, }; @@ -19,12 +19,11 @@ use quartz_common::{ contract::{msg::execute::attested::RawAttested, state::Config}, enclave::{attestor::Attestor, server::ProofOfPublication}, }; -use serde::{Deserialize, Serialize}; use tonic::{Request, Response, Result as TonicResult, Status}; use crate::{ proto::{clearing_server::Clearing, RunClearingRequest, RunClearingResponse}, - types::ContractObligation, + types::{ContractObligation, RunClearingMessage}, }; pub type RawCipherText = HexBinary; @@ -36,12 +35,6 @@ pub struct MtcsService { attestor: A, } -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct RunClearingMessage { - intents: BTreeMap, - liquidity_sources: BTreeSet, -} - impl MtcsService where A: Attestor, @@ -122,34 +115,22 @@ fn into_settle_offs( println!("\nsetoff: {:?}", so); println!("\nliq sources: {:?}", liquidity_sources); - // TODO: temporary patch, fix issue with liquidity sources becoming type External - if liquidity_sources + // TODO: temporary patch, fix issue with liquidity sources becoming type External so that .contains() can be called directly + let liquidity_sources_addrs = liquidity_sources .iter() .map(|lqs| lqs.address.clone()) - .collect::>() - .contains(&so.debtor.address) + .collect::>(); + + // In tenders and acceptances, the creditor's balance decreases + if liquidity_sources_addrs.contains(&so.debtor.address) + || liquidity_sources_addrs.contains(&so.creditor.address) { - // A setoff on a tender should result in the creditor's (i.e. the tender receiver) balance - // decreasing by the setoff amount SettleOff::Transfer(Transfer { payer: so.creditor.address.clone(), payee: so.debtor.address.clone(), // TODO: Include denominations amount: ("peppicoin".to_owned(), Uint128::from(so.set_off as u128)), }) - } else if liquidity_sources - .iter() - .map(|lqs| lqs.address.clone()) - .collect::>() - .contains(&so.creditor.address) - { - // A setoff on an acceptance should result in the debtor's (i.e. the acceptance initiator) - // balance increasing by the setoff amount - SettleOff::Transfer(Transfer { - payer: so.creditor.address.clone(), - payee: so.debtor.address.clone(), - amount: ("peppicoin".to_owned(), Uint128::from(so.set_off as u128)), - }) } else { // TODO: Tracked by issue #22 diff --git a/apps/mtcs/enclave/src/types.rs b/apps/mtcs/enclave/src/types.rs index 6f48f4f..9c2f068 100644 --- a/apps/mtcs/enclave/src/types.rs +++ b/apps/mtcs/enclave/src/types.rs @@ -1,6 +1,15 @@ +use std::collections::{BTreeMap, BTreeSet}; + use cosmwasm_std::{Addr, HexBinary}; +use cw_tee_mtcs::state::{LiquiditySource, RawCipherText, RawHash}; use serde::{Deserialize, Serialize}; +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct RunClearingMessage { + pub intents: BTreeMap, + pub liquidity_sources: BTreeSet, +} + #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ContractObligation { pub debtor: Addr, diff --git a/apps/mtcs/scripts/src/bin/deploy.rs b/apps/mtcs/scripts/src/bin/deploy.rs index afde55b..f4ab043 100644 --- a/apps/mtcs/scripts/src/bin/deploy.rs +++ b/apps/mtcs/scripts/src/bin/deploy.rs @@ -29,7 +29,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("\nšŸš€ Communicating with Relay to Instantiate...\n"); let init_msg: RawInstantiateMsg = run_relay(base_path.as_path(), "Instantiate", None)?; // need to define the return type - let init_msg: MtcsInstantiateMsg = MtcsInstantiateMsg(init_msg); + let init_msg: MtcsInstantiateMsg = MtcsInstantiateMsg { quartz: init_msg }; let httpurl = Url::parse(&format!("http://{}", cli.node_url))?; let tmrpc_client = HttpClient::new(httpurl.as_str()).unwrap(); @@ -42,8 +42,8 @@ async fn main() -> Result<(), anyhow::Error> { // TODO: uncertain about the path -> string conversion let deploy_output: WasmdTxResponse = serde_json::from_str(&wasmd_client.deploy( &ChainId::from_str("testing")?, - String::from("wasm14qdftsfk6fwn40l0xmruga08xlczl4g05npy70"), - contract_path.as_path().to_string_lossy(), + &String::from("wasm14qdftsfk6fwn40l0xmruga08xlczl4g05npy70"), + contract_path.display().to_string(), )?)?; let tx_hash = @@ -57,10 +57,10 @@ async fn main() -> Result<(), anyhow::Error> { let deploy_output: WasmdTxResponse = serde_json::from_str(&wasmd_client.init( &ChainId::from_str("testing")?, - String::from("wasm14qdftsfk6fwn40l0xmruga08xlczl4g05npy70"), + &String::from("wasm14qdftsfk6fwn40l0xmruga08xlczl4g05npy70"), code_id, json!(init_msg), - format!("MTCS Contract V{}", code_id), + &format!("MTCS Contract V{}", code_id), )?)?; let tx_hash = diff --git a/apps/mtcs/scripts/src/bin/handshake.rs b/apps/mtcs/scripts/src/bin/handshake.rs index 14feb39..3707687 100644 --- a/apps/mtcs/scripts/src/bin/handshake.rs +++ b/apps/mtcs/scripts/src/bin/handshake.rs @@ -88,7 +88,7 @@ async fn main() -> Result<(), anyhow::Error> { &cli.contract.clone(), &ChainId::from_str("testing")?, 2000000, - cli.sender.clone(), + &cli.sender, json!(res), )? .as_str(), @@ -149,7 +149,7 @@ async fn main() -> Result<(), anyhow::Error> { &cli.contract.clone(), &ChainId::from_str("testing")?, 2000000, - cli.sender.clone(), + &cli.sender, json!(res), )? .as_str(), diff --git a/apps/mtcs/scripts/src/bin/listen.rs b/apps/mtcs/scripts/src/bin/listen.rs index e7d32f2..85aaaea 100644 --- a/apps/mtcs/scripts/src/bin/listen.rs +++ b/apps/mtcs/scripts/src/bin/listen.rs @@ -1,32 +1,26 @@ -use std::{ - collections::{BTreeMap, BTreeSet}, - env, - process::Command, - str::FromStr, -}; +use std::{collections::BTreeMap, env, process::Command, str::FromStr}; use anyhow::anyhow; use base64::prelude::*; use clap::Parser; use cosmrs::{tendermint::chain::Id as ChainId, AccountId}; use cosmwasm_std::{Binary, HexBinary, Uint64}; -use cw_tee_mtcs::{ - msg::{ - execute::SubmitSetoffsMsg, AttestedMsg, ExecuteMsg, GetLiquiditySourcesResponse, - QueryMsg::GetLiquiditySources, - }, - state::LiquiditySource, +use cw_tee_mtcs::msg::{ + execute::SubmitSetoffsMsg, AttestedMsg, ExecuteMsg, GetLiquiditySourcesResponse, + QueryMsg::GetLiquiditySources, }; use cycles_sync::wasmd_client::{CliWasmdClient, QueryResult, WasmdClient}; use futures_util::stream::StreamExt; -use mtcs_enclave::proto::{clearing_client::ClearingClient, RunClearingRequest}; +use mtcs_enclave::{ + proto::{clearing_client::ClearingClient, RunClearingRequest}, + types::RunClearingMessage, +}; use quartz_common::contract::msg::execute::attested::{ - EpidAttestation, RawAttested, RawAttestedMsgSansHandler, + EpidAttestation, RawAttested, RawAttestedMsgSansHandler, RawEpidAttestation, }; use quartz_tee_ra::{intel_sgx::epid::types::ReportBody, IASReport}; use reqwest::Url; use scripts::utils::wasmaddr_to_id; -use serde::{Deserialize, Serialize}; use serde_json::json; use tendermint_rpc::{ query::{EventType, Query}, @@ -38,13 +32,6 @@ use tokio::{ }; use tonic::Request; -// TODO: import this from enclave or somewhere shared -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct RunClearingMessage { - intents: BTreeMap, - liquidity_sources: BTreeSet, -} - #[derive(Clone, Debug, Parser)] #[command(version, about, long_about = None)] struct Cli { @@ -148,12 +135,14 @@ async fn handler( let attestation = gramine_ias_request(quote.attestation, user).await?; let msg = RawAttestedMsgSansHandler(quote.msg); - let setoffs_msg = - ExecuteMsg::SubmitSetoffs::(AttestedMsg { msg, attestation }); + let setoffs_msg = ExecuteMsg::SubmitSetoffs::(AttestedMsg { + msg, + attestation: attestation.into(), + }); // Send setoffs to mtcs contract on chain let output = - wasmd_client.tx_execute(contract, chain_id, 2000000, sender, json!(setoffs_msg))?; + wasmd_client.tx_execute(contract, chain_id, 2000000, &sender, json!(setoffs_msg))?; println!("output: {}", output); Ok(()) diff --git a/apps/mtcs/scripts/start.sh b/apps/mtcs/scripts/start.sh index 641def6..ac526ce 100755 --- a/apps/mtcs/scripts/start.sh +++ b/apps/mtcs/scripts/start.sh @@ -2,11 +2,10 @@ #set -eo pipefail -ROOT=${ROOT:-$HOME} -DIR_QUARTZ="$ROOT/cycles-protocol" -DIR_QUARTZ_APP="$DIR_QUARTZ/quartz-app/" -DIR_QUARTZ_ENCLAVE="$DIR_QUARTZ/quartz-app/enclave" -DIR_QUARTZ_TM_PROVER="$DIR_QUARTZ/packages/tm-prover" +DIR_QUARTZ=${ROOT:-$(git rev-parse --show-toplevel)} +DIR_QUARTZ_APP="$DIR_QUARTZ/apps/mtcs" +DIR_QUARTZ_ENCLAVE="$DIR_QUARTZ_APP/enclave" +DIR_QUARTZ_TM_PROVER="$DIR_QUARTZ/utils/tm-prover" NODE_URL=${NODE_URL:-143.244.186.205:26657} CMD="wasmd --node http://$NODE_URL" @@ -52,6 +51,14 @@ cd "$DIR_QUARTZ_APP" echo "$TRUSTED_HASH" > trusted.hash echo "$TRUSTED_HEIGHT" > trusted.height +if [ -n "$MOCK_SGX" ]; then + echo "MOCK_SGX is set. Running enclave without gramine..." + cd $DIR_QUARTZ + + RUST_BACKTRACE=full ./target/release/mtcs-enclave --chain-id "testing" --trusted-height "$TRUSTED_HEIGHT" --trusted-hash "$TRUSTED_HASH" + exit +fi + echo "--------------------------------------------------------" echo "configure gramine" cd "$DIR_QUARTZ_ENCLAVE" diff --git a/apps/transfers/contracts/Cargo.lock b/apps/transfers/contracts/Cargo.lock index 705e09c..9e1e389 100644 --- a/apps/transfers/contracts/Cargo.lock +++ b/apps/transfers/contracts/Cargo.lock @@ -231,6 +231,12 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e31ea183f6ee62ac8b8a8cf7feddd766317adfb13ff469de57ce033efd6a790" +[[package]] +name = "bumpalo" +version = "3.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" + [[package]] name = "cc" version = "1.1.6" @@ -243,6 +249,16 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "chrono" +version = "0.4.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" +dependencies = [ + "num-traits", + "serde", +] + [[package]] name = "const-oid" version = "0.9.6" @@ -746,8 +762,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", ] [[package]] @@ -825,6 +843,15 @@ version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" +[[package]] +name = "js-sys" +version = "0.3.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" +dependencies = [ + "wasm-bindgen", +] + [[package]] name = "k256" version = "0.13.3" @@ -849,6 +876,12 @@ version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" +[[package]] +name = "log" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" + [[package]] name = "mc-attestation-verifier" version = "0.4.3" @@ -1082,6 +1115,7 @@ dependencies = [ "quartz-tee-ra", "serde", "serde_json", + "serde_with", "sha2", "thiserror", ] @@ -1317,9 +1351,14 @@ version = "3.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cecfa94848272156ea67b2b1a53f20fc7bc638c4a46d2f8abde08f05f4b857" dependencies = [ + "base64", + "chrono", + "hex", "serde", "serde_derive", + "serde_json", "serde_with_macros", + "time", ] [[package]] @@ -1483,6 +1522,7 @@ dependencies = [ "cw-utils", "cw2", "cw20-base", + "getrandom", "quartz-common", "serde", "serde_json", @@ -1526,6 +1566,60 @@ version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +[[package]] +name = "wasm-bindgen" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.72", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.72", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" + [[package]] name = "windows-sys" version = "0.52.0" diff --git a/apps/transfers/contracts/Cargo.toml b/apps/transfers/contracts/Cargo.toml index ed004af..e104cc3 100644 --- a/apps/transfers/contracts/Cargo.toml +++ b/apps/transfers/contracts/Cargo.toml @@ -33,6 +33,7 @@ sha2 = "0.10.8" serde_json = "1.0.117" serde = { version = "1.0.137", default-features = false, features = ["derive"] } thiserror = { version = "1.0.49" } +getrandom = { version = "0.2.15", features = ["js"] } # cosmwasm cosmwasm-schema = { version = "2.0.0", default-features = false } diff --git a/apps/transfers/scripts/start.sh b/apps/transfers/scripts/start.sh index a863ee6..1b4e7d0 100755 --- a/apps/transfers/scripts/start.sh +++ b/apps/transfers/scripts/start.sh @@ -2,8 +2,7 @@ #set -eo pipefail -ROOT=${ROOT:-$HOME} -DIR_QUARTZ="$ROOT/cycles-quartz" +DIR_QUARTZ=${ROOT:-$(git rev-parse --show-toplevel)} DIR_QUARTZ_APP="$DIR_QUARTZ/apps/transfers" DIR_QUARTZ_ENCLAVE="$DIR_QUARTZ_APP/enclave" DIR_QUARTZ_TM_PROVER="$DIR_QUARTZ/utils/tm-prover" @@ -30,7 +29,7 @@ echo "$TRUSTED_HEIGHT" > trusted.height if [ -n "$MOCK_SGX" ]; then echo "MOCK_SGX is set. Running enclave without gramine..." - cd $DIR_QUARTZ_ENCLAVE + cd $DIR_QUARTZ ./target/release/quartz-app-transfers-enclave --chain-id "testing" --trusted-height "$TRUSTED_HEIGHT" --trusted-hash "$TRUSTED_HASH" exit fi diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 9fb11fd..66f59fd 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -10,6 +10,7 @@ keywords = ["blockchain", "cosmos", "tendermint", "cycles", "quartz"] readme = "README.md" [dependencies] +async-trait.workspace = true clap = { workspace = true, features=["env"] } color-eyre.workspace = true displaydoc.workspace = true @@ -18,3 +19,28 @@ serde_json.workspace = true thiserror.workspace = true tracing.workspace = true tracing-subscriber = { workspace = true, features = ["env-filter"] } +hex.workspace = true +k256.workspace = true +prost.workspace = true +tokio.workspace = true +tonic.workspace = true +once_cell = "1.19.0" +reqwest = { version = "0.12.2", default-features = false, features = ["json", "rustls-tls"] } +anyhow = "1.0.86" +base64 = "0.22.1" +subtle-encoding = "0.5.1" +futures-util = "0.3.30" + +# cosmos +cosmrs.workspace = true +cosmwasm-std.workspace = true +tendermint.workspace = true +tendermint-light-client.workspace = true +tendermint-rpc = { workspace = true, features=["websocket-client", "http-client"]} + +cycles-sync = { workspace = true} +tm-prover = { workspace = true} +quartz-common = { workspace = true, features=["contract"]} +quartz-tee-ra = { workspace = true} +mtcs-enclave = { workspace = true, optional = false} +regex = "1.10.5" diff --git a/cli/src/cli.rs b/cli/src/cli.rs index 315c286..3f4f508 100644 --- a/cli/src/cli.rs +++ b/cli/src/cli.rs @@ -1,8 +1,11 @@ -use std::path::PathBuf; +use std::{env, path::PathBuf}; use clap::{Parser, Subcommand}; +use cosmrs::{tendermint::chain::Id as ChainId, AccountId}; use tracing::metadata::LevelFilter; +use crate::handler::utils::helpers::wasmaddr_to_id; + #[derive(clap::Args, Debug, Clone)] pub struct Verbosity { /// Increase verbosity, can be repeated up to 2 times @@ -45,6 +48,35 @@ pub enum Command { #[clap(long)] path: Option, }, + Handshake { + /// path to create & init a quartz app, defaults to current path if unspecified + #[arg(short, long, value_parser = wasmaddr_to_id)] + contract: AccountId, + /// Port enclave is listening on + #[arg(short, long, default_value = "11090")] + port: u16, + /// Name or address of private key with which to sign + #[arg(short, long, default_value = "admin")] + sender: String, + /// The network chain ID + #[arg(long, default_value = "testing")] + chain_id: ChainId, + /// : to tendermint rpc interface for this chain + #[clap(long, default_value_t = default_node_url())] + node_url: String, + /// RPC interface for the quartz enclave + #[clap(long, default_value_t = default_rpc_addr())] + enclave_rpc_addr: String, + /// Path to quartz app directory + /// Defaults to current working dir + #[clap(long)] + app_dir: Option, + }, + /// Create an empty Quartz app from a template + Contract { + #[command(subcommand)] + contract_command: ContractCommand, + }, /// Subcommands for handling the Quartz app enclave Enclave { #[command(subcommand)] @@ -52,6 +84,34 @@ pub enum Command { }, } +#[derive(Debug, Clone, Subcommand)] +pub enum ContractCommand { + Build { + #[clap(long)] + path: Option, + }, + Deploy { + /// Json-formatted cosmwasm contract initialization message + #[clap(long, default_value = "{}")] + init_msg: String, + /// : to tendermint rpc interface for this chain + #[clap(long, default_value_t = default_node_url())] + node_url: String, + /// Name or address of private key with which to sign + #[arg(short, long, default_value = "admin")] + sender: String, + /// The network chain ID + #[arg(long, default_value = "testing")] + chain_id: ChainId, + /// A human-readable name for this contract in lists + #[arg(long, default_value = "Quartz App Contract")] + label: String, + /// Path to contract wasm binary for deployment + #[clap(long)] + wasm_bin_path: PathBuf, + }, +} + #[derive(Debug, Clone, Subcommand)] pub enum EnclaveCommand { /// Build the Quartz app's enclave @@ -66,3 +126,11 @@ pub enum EnclaveCommand { path: Option, }, } + +fn default_rpc_addr() -> String { + env::var("RPC_URL").unwrap_or_else(|_| "http://127.0.0.1".to_string()) +} + +fn default_node_url() -> String { + env::var("NODE_URL").unwrap_or_else(|_| "http://127.0.0.1:26657".to_string()) +} diff --git a/cli/src/error.rs b/cli/src/error.rs index c43012e..ffe45ba 100644 --- a/cli/src/error.rs +++ b/cli/src/error.rs @@ -3,8 +3,10 @@ use thiserror::Error; #[derive(Debug, Display, Error)] pub enum Error { - /// specified path `{0}` is not a directory + /// Specified path `{0}` is not a directory PathNotDir(String), + /// Specified file `{0}` does not exist + PathNotFile(String), /// {0} GenericErr(String), } diff --git a/cli/src/handler.rs b/cli/src/handler.rs index 85916c7..ed47a73 100644 --- a/cli/src/handler.rs +++ b/cli/src/handler.rs @@ -1,23 +1,33 @@ +use async_trait::async_trait; + use crate::{error::Error, request::Request, response::Response, Config}; +pub mod utils; +// commands +pub mod contract_deploy; pub mod enclave_build; +pub mod handshake; pub mod init; +#[async_trait] pub trait Handler { type Error; type Response; - fn handle(self, config: Config) -> Result; + async fn handle(self, config: Config) -> Result; } +#[async_trait] impl Handler for Request { type Error = Error; type Response = Response; - fn handle(self, config: Config) -> Result { + async fn handle(self, config: Config) -> Result { match self { - Request::Init(request) => request.handle(config), - Request::EnclaveBuild(request) => request.handle(config), + Request::Init(request) => request.handle(config).await, + Request::Handshake(request) => request.handle(config).await, + Request::ContractDeploy(request) => request.handle(config).await, + Request::EnclaveBuild(request) => request.handle(config).await, } .map(Into::into) } diff --git a/cli/src/handler/contract_deploy.rs b/cli/src/handler/contract_deploy.rs new file mode 100644 index 0000000..ba1f29b --- /dev/null +++ b/cli/src/handler/contract_deploy.rs @@ -0,0 +1,111 @@ +use std::env::current_dir; + +use async_trait::async_trait; +use cycles_sync::wasmd_client::{CliWasmdClient, WasmdClient}; +use quartz_common::contract::{ + msg::execute::attested::{RawEpidAttestation, RawMockAttestation}, + prelude::QuartzInstantiateMsg, +}; +use reqwest::Url; +use serde::{de::DeserializeOwned, Serialize}; +use serde_json::json; +use tendermint_rpc::HttpClient; +use tracing::{debug, info, trace}; + +use super::utils::{ + helpers::{block_tx_commit, run_relay}, + types::{Log, WasmdTxResponse}, +}; +use crate::{ + error::Error, + handler::{utils::types::RelayMessage, Handler}, + request::contract_deploy::ContractDeployRequest, + response::{contract_deploy::ContractDeployResponse, Response}, + Config, +}; + +#[async_trait] +impl Handler for ContractDeployRequest { + type Error = Error; + type Response = Response; + + async fn handle(self, config: Config) -> Result { + trace!("initializing directory structure..."); + + let (code_id, contract_addr) = if config.mock_sgx { + deploy::(self, config.mock_sgx) + .await + .map_err(|e| Error::GenericErr(e.to_string()))? + } else { + deploy::(self, config.mock_sgx) + .await + .map_err(|e| Error::GenericErr(e.to_string()))? + }; + + Ok(ContractDeployResponse { + code_id, + contract_addr, + } + .into()) + } +} + +async fn deploy( + args: ContractDeployRequest, + mock_sgx: bool, +) -> Result<(u64, String), anyhow::Error> { + // TODO: Replace with call to Rust package + let relay_path = current_dir()?.join("../"); + + let httpurl = Url::parse(&format!("http://{}", args.node_url))?; + let tmrpc_client = HttpClient::new(httpurl.as_str())?; + let wasmd_client = CliWasmdClient::new(Url::parse(httpurl.as_str())?); + + info!("\nšŸš€ Deploying {} Contract\n", args.label); + let contract_path = args.wasm_bin_path; + // .join("contracts/cw-tee-mtcs/target/wasm32-unknown-unknown/release/cw_tee_mtcs.wasm"); + + // TODO: uncertain about the path -> string conversion + let deploy_output: WasmdTxResponse = serde_json::from_str(&wasmd_client.deploy( + &args.chain_id, + &args.sender, + contract_path.display().to_string(), + )?)?; + let res = block_tx_commit(&tmrpc_client, deploy_output.txhash).await?; + + let log: Vec = serde_json::from_str(&res.tx_result.log)?; + let code_id: usize = log[0].events[1].attributes[1].value.parse()?; + + info!("\nšŸš€ Communicating with Relay to Instantiate...\n"); + let raw_init_msg = run_relay::>( + relay_path.as_path(), + mock_sgx, + RelayMessage::Instantiate, + )?; + + info!("\nšŸš€ Instantiating {} Contract\n", args.label); + let mut init_msg = args.init_msg; + init_msg["quartz"] = json!(raw_init_msg); + + let init_output: WasmdTxResponse = serde_json::from_str(&wasmd_client.init( + &args.chain_id, + &args.sender, + code_id, + json!(init_msg), + &format!("{} Contract #{}", args.label, code_id), + )?)?; + let res = block_tx_commit(&tmrpc_client, init_output.txhash).await?; + + let log: Vec = serde_json::from_str(&res.tx_result.log)?; + let contract_addr: &String = &log[0].events[1].attributes[0].value; + + info!("\nšŸš€ Successfully deployed and instantiated contract!"); + info!("\nšŸ†” Code ID: {}", code_id); + info!("\nšŸ“Œ Contract Address: {}", contract_addr); + + debug!("{contract_addr}"); + + Ok((code_id as u64, contract_addr.to_owned())) +} + +//RES=$($CMD tx wasm instantiate "$CODE_ID" "$INSTANTIATE_MSG" --from "$USER_ADDR" --label $LABEL $TXFLAG -y --no-admin --output json) diff --git a/cli/src/handler/enclave_build.rs b/cli/src/handler/enclave_build.rs index aa7eb74..cd888e0 100644 --- a/cli/src/handler/enclave_build.rs +++ b/cli/src/handler/enclave_build.rs @@ -1,6 +1,7 @@ use std::process::Command; -use tracing::{debug, trace}; +use async_trait::async_trait; +use tracing::{debug, info}; use crate::{ error::Error, @@ -10,11 +11,12 @@ use crate::{ Config, }; +#[async_trait] impl Handler for EnclaveBuildRequest { type Error = Error; type Response = Response; - fn handle(self, config: Config) -> Result { + async fn handle(self, config: Config) -> Result { let mut cargo = Command::new("cargo"); let command = cargo .args(["build", "--release"]) @@ -25,7 +27,7 @@ impl Handler for EnclaveBuildRequest { command.arg("--features=mock-sgx"); } - trace!("šŸš§ Building enclave ..."); + info!("šŸš§ Building enclave ..."); let status = command .status() .map_err(|e| Error::GenericErr(e.to_string()))?; diff --git a/cli/src/handler/handshake.rs b/cli/src/handler/handshake.rs new file mode 100644 index 0000000..a6d8b02 --- /dev/null +++ b/cli/src/handler/handshake.rs @@ -0,0 +1,197 @@ +use std::{env::current_dir, fs, path::Path, str::FromStr}; + +use anyhow::anyhow; +use async_trait::async_trait; +use cosmrs::tendermint::chain::Id as ChainId; // TODO see if this redundancy in dependencies can be decreased +use cycles_sync::wasmd_client::{CliWasmdClient, WasmdClient}; +use futures_util::stream::StreamExt; +use reqwest::Url; +use serde::Serialize; +use serde_json::json; +use tendermint::{block::Height, Hash}; +use tendermint_rpc::{query::EventType, HttpClient, SubscriptionClient, WebSocketClient}; +use tm_prover::{config::Config as TmProverConfig, prover::prove}; +use tracing::{debug, info, trace}; + +use super::utils::{ + helpers::{block_tx_commit, run_relay}, + types::WasmdTxResponse, +}; +use crate::{ + error::Error, + handler::{utils::types::RelayMessage, Handler}, + request::handshake::HandshakeRequest, + response::{handshake::HandshakeResponse, Response}, + Config, +}; + +#[async_trait] +impl Handler for HandshakeRequest { + type Error = Error; + type Response = Response; + + async fn handle(self, config: Config) -> Result { + trace!("starting handshake..."); + + // TODO: may need to import verbosity here + let pub_key = handshake(self, config.mock_sgx) + .await + .map_err(|e| Error::GenericErr(e.to_string()))?; + + Ok(HandshakeResponse { pub_key }.into()) + } +} + +#[derive(Serialize)] +struct Message<'a> { + message: &'a str, +} + +async fn handshake(args: HandshakeRequest, mock_sgx: bool) -> Result { + let httpurl = Url::parse(&format!("http://{}", args.node_url))?; + let wsurl = format!("ws://{}/websocket", args.node_url); + + let tmrpc_client = HttpClient::new(httpurl.as_str())?; + let wasmd_client = CliWasmdClient::new(Url::parse(httpurl.as_str())?); + + // TODO: dir logic issue #125 + // Read trusted hash and height from files + let base_path = current_dir()?.join("../"); + let trusted_files_path = args.app_dir; + let (trusted_height, trusted_hash) = read_hash_height(trusted_files_path.as_path()).await?; + + info!("Running SessionCreate"); + let res: serde_json::Value = + run_relay(base_path.as_path(), mock_sgx, RelayMessage::SessionCreate)?; + + let output: WasmdTxResponse = serde_json::from_str( + wasmd_client + .tx_execute( + &args.contract.clone(), + &args.chain_id, + 2000000, + &args.sender, + json!(res), + )? + .as_str(), + )?; + debug!("\n\n SessionCreate tx output: {:?}", output); + + // Wait for tx to commit + block_tx_commit(&tmrpc_client, output.txhash).await?; + info!("SessionCreate tx committed"); + + // Wait 2 blocks + info!("Waiting 2 blocks for light client proof"); + two_block_waitoor(&wsurl).await?; + + // TODO: dir logic issue #125 + let proof_path = current_dir()?.join("../utils/tm-prover/light-client-proof.json"); + debug!("Proof path: {:?}", proof_path.to_str()); + + // Call tm prover with trusted hash and height + let config = TmProverConfig { + primary: httpurl.as_str().parse()?, + witnesses: httpurl.as_str().parse()?, + trusted_height, + trusted_hash, + trace_file: Some(proof_path.clone()), + verbose: "1".parse()?, // TODO: both tm-prover and cli define the same Verbosity struct. Need to define this once and import + contract_address: args.contract.clone(), + storage_key: "quartz_session".to_string(), + chain_id: args.chain_id.to_string(), + ..Default::default() + }; + debug!("config: {:?}", config); + if let Err(report) = prove(config).await { + return Err(anyhow!("Tendermint prover failed. Report: {}", report)); + } + + // Read proof file + let proof = fs::read_to_string(proof_path.as_path())?; + let proof_json = serde_json::to_string(&Message { + message: proof.trim(), + })?; + + // Execute SessionSetPubKey on enclave + info!("Running SessionSetPubKey"); + let res: serde_json::Value = run_relay( + base_path.as_path(), + mock_sgx, + RelayMessage::SessionSetPubKey(proof_json), + )?; + + // Submit SessionSetPubKey to contract + let output: WasmdTxResponse = serde_json::from_str( + wasmd_client + .tx_execute( + &args.contract.clone(), + &ChainId::from_str("testing")?, + 2000000, + &args.sender, + json!(res), + )? + .as_str(), + )?; + + // Wait for tx to commit + block_tx_commit(&tmrpc_client, output.txhash).await?; + info!("SessionSetPubKey tx committed"); + + let output: WasmdTxResponse = wasmd_client.query_tx(&output.txhash.to_string())?; + + let wasm_event = output + .events + .iter() + .find(|e| e.kind == "wasm") + .expect("Wasm transactions are guaranteed to contain a 'wasm' event"); + + if let Some(pubkey) = wasm_event.attributes.iter().find(|a| { + a.key_str() + .expect("SessionSetPubKey tx is expected to have 'pub_key' attribute") + == "pub_key" + }) { + Ok(pubkey.value_str()?.to_string()) + } else { + Err(anyhow!("Failed to find pubkey from SetPubKey message")) + } +} + +async fn two_block_waitoor(wsurl: &str) -> Result<(), anyhow::Error> { + let (client, driver) = WebSocketClient::new(wsurl).await?; + + let driver_handle = tokio::spawn(async move { driver.run().await }); + + // Subscription functionality + let mut subs = client.subscribe(EventType::NewBlock.into()).await?; + + // Wait 2 NewBlock events + let mut ev_count = 2_i32; + debug!("Blocks left: {ev_count} ..."); + + while let Some(res) = subs.next().await { + let _ev = res?; + ev_count -= 1; + debug!("Blocks left: {ev_count} ..."); + if ev_count == 0 { + break; + } + } + + // Signal to the driver to terminate. + client.close()?; + // Await the driver's termination to ensure proper connection closure. + let _ = driver_handle.await?; + + Ok(()) +} + +async fn read_hash_height(base_path: &Path) -> Result<(Height, Hash), anyhow::Error> { + let height_path = base_path.join("trusted.height"); + let trusted_height: Height = fs::read_to_string(height_path.as_path())?.trim().parse()?; + + let hash_path = base_path.join("trusted.hash"); + let trusted_hash: Hash = fs::read_to_string(hash_path.as_path())?.trim().parse()?; + + Ok((trusted_height, trusted_hash)) +} diff --git a/cli/src/handler/init.rs b/cli/src/handler/init.rs index cd672b9..d3ef866 100644 --- a/cli/src/handler/init.rs +++ b/cli/src/handler/init.rs @@ -1,15 +1,22 @@ +use async_trait::async_trait; use tracing::trace; use crate::{ - error::Error, handler::Handler, request::init::InitRequest, response::Response, Config, + error::Error, + handler::Handler, + request::init::InitRequest, + response::{init::InitResponse, Response}, + Config, }; +#[async_trait] impl Handler for InitRequest { type Error = Error; type Response = Response; - fn handle(self, _config: Config) -> Result { + async fn handle(self, _config: Config) -> Result { trace!("initializing directory structure..."); - todo!() + + Ok(InitResponse.into()) } } diff --git a/cli/src/handler/utils/helpers.rs b/cli/src/handler/utils/helpers.rs new file mode 100644 index 0000000..91d176c --- /dev/null +++ b/cli/src/handler/utils/helpers.rs @@ -0,0 +1,87 @@ +use std::{path::Path, process::Command, time::Duration}; + +use anyhow::anyhow; +use cosmrs::{AccountId, ErrorReport}; +use regex::Regex; +use serde::de::DeserializeOwned; +use subtle_encoding::bech32::decode as bech32_decode; +use tendermint::Hash; +use tendermint_rpc::{ + endpoint::tx::Response as TmTxResponse, error::ErrorDetail, Client, HttpClient, +}; +use tracing::debug; + +use super::types::RelayMessage; + +pub fn wasmaddr_to_id(address_str: &str) -> Result { + let (hr, _) = bech32_decode(address_str).map_err(|e| anyhow!(e))?; + if hr != "wasm" { + return Err(anyhow!(hr)); + } + + address_str.parse().map_err(|e: ErrorReport| anyhow!(e)) +} + +// TODO: move wrapping result with "quartz:" struct into here +pub fn run_relay( + base_path: &Path, + mock_sgx: bool, + msg: RelayMessage, +) -> Result { + let relayer_path = base_path.join("relayer/scripts/relay.sh"); + + let mut bash = Command::new("bash"); + let command = bash + .arg(relayer_path) + .arg(msg.to_string()) + .env("MOCK_SGX", mock_sgx.to_string()); + + if let RelayMessage::SessionSetPubKey(proof) = msg { + command.arg(proof); + } + + let output = command.output()?; + + if !output.status.success() { + return Err(anyhow!("{:?}", output)); + } + + let query_result: R = serde_json::from_slice(&output.stdout) + .map_err(|e| anyhow!("Error deserializing: {}", e))?; + + Ok(query_result) +} + +// Note: time until tx commit is empiraclly 800ms on DO wasmd chain. +pub async fn block_tx_commit(client: &HttpClient, tx: Hash) -> Result { + let re = Regex::new(r"tx \([A-F0-9]{64}\) not found")?; + + tokio::time::sleep(Duration::from_millis(400)).await; + loop { + match client.tx(tx, false).await { + Ok(resp) => { + return Ok(resp); + } + Err(e) => { + // If error, make sure it is only because of a not yet committed tx + match e.0 { + ErrorDetail::Response(subdetail) => { + if !re.is_match(subdetail.source.data().unwrap_or_default()) { + return Err(anyhow!( + "Error querying for tx: {}", + ErrorDetail::Response(subdetail) + )); + } else { + debug!("šŸ”— Waiting for tx commit... (+400ms)"); + tokio::time::sleep(Duration::from_millis(400)).await; + continue; + } + } + _ => { + return Err(anyhow!("Error querying for tx: {}", e.0)); + } + } + } + } + } +} diff --git a/cli/src/handler/utils/mod.rs b/cli/src/handler/utils/mod.rs new file mode 100644 index 0000000..52af0f9 --- /dev/null +++ b/cli/src/handler/utils/mod.rs @@ -0,0 +1,2 @@ +pub mod helpers; +pub mod types; diff --git a/cli/src/handler/utils/types.rs b/cli/src/handler/utils/types.rs new file mode 100644 index 0000000..14e2104 --- /dev/null +++ b/cli/src/handler/utils/types.rs @@ -0,0 +1,57 @@ +use serde::{Deserialize, Serialize}; +use tendermint::{abci::Event as TmEvent, Hash}; + +// Rust libraries don't seem to implement this type from the wasmd go implementation +// TODO: Replace String with types from Rust libraries +// TODO: Move this into WasmdClient +#[derive(Deserialize, Debug, Default)] +pub struct WasmdTxResponse { + pub height: String, + pub txhash: Hash, + pub codespace: String, + pub code: u32, + pub data: String, + pub raw_log: String, + pub logs: Vec, + pub info: String, + pub gas_wanted: String, + pub gas_used: String, + pub tx: Option, + pub timestamp: String, + pub events: Vec, +} + +#[derive(Serialize, Deserialize, Debug)] +pub struct Attribute { + pub key: String, + pub value: String, +} + +#[derive(Serialize, Deserialize, Debug)] +pub struct Event { + pub attributes: Vec, + pub r#type: String, +} + +#[derive(Serialize, Deserialize, Debug)] +pub struct Log { + pub events: Vec, + pub msg_index: u32, +} + +#[derive(Debug, PartialEq, PartialOrd)] +pub enum RelayMessage { + Instantiate, + SessionCreate, + SessionSetPubKey(String), +} + +impl std::fmt::Display for RelayMessage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + RelayMessage::Instantiate => write!(f, "Instantiate"), + RelayMessage::SessionCreate => write!(f, "SessionCreate"), + RelayMessage::SessionSetPubKey(_) => write!(f, "SessionSetPubKey"), + } + } +} diff --git a/cli/src/main.rs b/cli/src/main.rs index 4a0889b..265c502 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -25,13 +25,28 @@ use tracing_subscriber::{util::SubscriberInitExt, EnvFilter}; use crate::{cli::Cli, handler::Handler, request::Request}; +const BANNER: &str = r" + ________ ___ ___ ________ ________ _________ ________ +|\ __ \ |\ \|\ \ |\ __ \ |\ __ \ |\___ ___\ |\_____ \ +\ \ \|\ \ \ \ \\\ \ \ \ \|\ \ \ \ \|\ \ \|___ \ \_| \|___/ /| + \ \ \\\ \ \ \ \\\ \ \ \ __ \ \ \ _ _\ \ \ \ / / / + \ \ \\\ \ \ \ \\\ \ \ \ \ \ \ \ \ \\ \| \ \ \ / /_/__ + \ \_____ \ \ \_______\ \ \__\ \__\ \ \__\\ _\ \ \__\ |\________\ + \|___| \__\ \|_______| \|__|\|__| \|__|\|__| \|__| \|_______| + \|__| + +"; + pub struct Config { pub mock_sgx: bool, } -fn main() -> Result<()> { +#[tokio::main] +async fn main() -> Result<()> { color_eyre::install()?; + println!("{BANNER}"); + let args = Cli::parse(); let env_filter = EnvFilter::builder() @@ -52,9 +67,11 @@ fn main() -> Result<()> { // Each `Request` defines an associated `Handler` (i.e. logic) and `Response`. All handlers are // free to log to the terminal and these logs are sent to `stderr`. - let response = request.handle(Config { - mock_sgx: args.mock_sgx, - })?; + let response = request + .handle(Config { + mock_sgx: args.mock_sgx, + }) + .await?; // `Handlers` must use `Responses` to output to `stdout`. println!( diff --git a/cli/src/request.rs b/cli/src/request.rs index b698d0c..3bb104f 100644 --- a/cli/src/request.rs +++ b/cli/src/request.rs @@ -1,15 +1,24 @@ +use std::{env::current_dir, path::PathBuf}; + use crate::{ - cli::{Command, EnclaveCommand}, + cli::{Command, ContractCommand, EnclaveCommand}, error::Error, - request::{enclave_build::EnclaveBuildRequest, init::InitRequest}, + request::{ + contract_deploy::ContractDeployRequest, enclave_build::EnclaveBuildRequest, + handshake::HandshakeRequest, init::InitRequest, + }, }; +pub mod contract_deploy; pub mod enclave_build; +pub mod handshake; pub mod init; #[derive(Clone, Debug)] pub enum Request { Init(InitRequest), + Handshake(HandshakeRequest), + ContractDeploy(ContractDeployRequest), EnclaveBuild(EnclaveBuildRequest), } @@ -19,12 +28,82 @@ impl TryFrom for Request { fn try_from(cmd: Command) -> Result { match cmd { Command::Init { path } => InitRequest::try_from(path).map(Into::into), - Command::Enclave { enclave_command } => match enclave_command { - EnclaveCommand::Build { manifest_path } => { - Ok(EnclaveBuildRequest { manifest_path }.into()) - } - _ => todo!(), - }, + Command::Handshake { + contract, + port, + sender, + chain_id, + node_url, + enclave_rpc_addr, + app_dir, + } => Ok(HandshakeRequest { + contract, + port, + sender, + chain_id, + node_url, + enclave_rpc_addr, + app_dir: Self::path_checked(app_dir)?, + } + .into()), + Command::Contract { contract_command } => contract_command.try_into(), + Command::Enclave { enclave_command } => Ok(enclave_command.into()), + } + } +} + +impl Request { + fn path_checked(path: Option) -> Result { + if let Some(path) = path { + if !path.is_dir() { + return Err(Error::PathNotDir(format!("{}", path.display()))); + } + + Ok(path) + } else { + Ok(current_dir().map_err(|e| Error::GenericErr(e.to_string()))?) + } + } +} + +impl TryFrom for Request { + type Error = Error; + + fn try_from(cmd: ContractCommand) -> Result { + match cmd { + ContractCommand::Deploy { + init_msg, + node_url, + chain_id, + sender, + label, + wasm_bin_path, + } => { + if !wasm_bin_path.exists() { + return Err(Error::PathNotFile(wasm_bin_path.display().to_string())); + } + + Ok(ContractDeployRequest { + init_msg: serde_json::from_str(&init_msg) + .map_err(|e| Error::GenericErr(e.to_string()))?, + node_url, + chain_id, + sender, + label, + wasm_bin_path, + } + .into()) + } + ContractCommand::Build { path: _ } => todo!(), + } + } +} + +impl From for Request { + fn from(cmd: EnclaveCommand) -> Request { + match cmd { + EnclaveCommand::Build { manifest_path } => EnclaveBuildRequest { manifest_path }.into(), + EnclaveCommand::Start { path: _ } => todo!(), } } } diff --git a/cli/src/request/contract_deploy.rs b/cli/src/request/contract_deploy.rs new file mode 100644 index 0000000..35e294f --- /dev/null +++ b/cli/src/request/contract_deploy.rs @@ -0,0 +1,39 @@ +use std::{collections::HashMap, path::PathBuf}; + +use cosmrs::tendermint::chain::Id as ChainId; +use serde::{Deserialize, Serialize}; + +use crate::{error::Error, request::Request}; + +#[derive(Clone, Debug)] +pub struct ContractDeployRequest { + pub init_msg: serde_json::Value, + pub node_url: String, + pub chain_id: ChainId, + pub sender: String, + pub label: String, + pub wasm_bin_path: PathBuf, +} + +impl From for Request { + fn from(request: ContractDeployRequest) -> Self { + Self::ContractDeploy(request) + } +} + +impl ContractDeployRequest { + pub fn checked_init(init_msg: String) -> Result { + let parsed: GenericQuartzInit = serde_json::from_str(&init_msg).map_err(|_| { + Error::GenericErr("Init message doesn't contain mandatory quartz field.".to_string()) + })?; + + Ok(parsed) + } +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct GenericQuartzInit { + pub quartz: serde_json::Value, + #[serde(flatten)] + extra: HashMap, +} diff --git a/cli/src/request/handshake.rs b/cli/src/request/handshake.rs new file mode 100644 index 0000000..2b3a321 --- /dev/null +++ b/cli/src/request/handshake.rs @@ -0,0 +1,22 @@ +use std::path::PathBuf; + +use cosmrs::{tendermint::chain::Id as ChainId, AccountId}; + +use crate::request::Request; + +#[derive(Clone, Debug)] +pub struct HandshakeRequest { + pub contract: AccountId, + pub port: u16, + pub sender: String, + pub chain_id: ChainId, + pub node_url: String, + pub enclave_rpc_addr: String, + pub app_dir: PathBuf, +} + +impl From for Request { + fn from(request: HandshakeRequest) -> Self { + Self::Handshake(request) + } +} diff --git a/cli/src/response.rs b/cli/src/response.rs index 2509121..69ded11 100644 --- a/cli/src/response.rs +++ b/cli/src/response.rs @@ -1,12 +1,19 @@ use serde::Serialize; -use crate::response::{enclave_build::EnclaveBuildResponse, init::InitResponse}; +use crate::response::{ + contract_deploy::ContractDeployResponse, enclave_build::EnclaveBuildResponse, + handshake::HandshakeResponse, init::InitResponse, +}; +pub mod contract_deploy; pub mod enclave_build; +pub mod handshake; pub mod init; #[derive(Clone, Debug, Serialize)] pub enum Response { Init(InitResponse), + Handshake(HandshakeResponse), + ContractDeploy(ContractDeployResponse), EnclaveBuild(EnclaveBuildResponse), } diff --git a/cli/src/response/contract_deploy.rs b/cli/src/response/contract_deploy.rs new file mode 100644 index 0000000..c4da3df --- /dev/null +++ b/cli/src/response/contract_deploy.rs @@ -0,0 +1,15 @@ +use serde::Serialize; + +use crate::response::Response; + +#[derive(Clone, Debug, Serialize)] +pub struct ContractDeployResponse { + pub code_id: u64, + pub contract_addr: String, +} + +impl From for Response { + fn from(response: ContractDeployResponse) -> Self { + Self::ContractDeploy(response) + } +} diff --git a/cli/src/response/handshake.rs b/cli/src/response/handshake.rs new file mode 100644 index 0000000..d6a7d87 --- /dev/null +++ b/cli/src/response/handshake.rs @@ -0,0 +1,14 @@ +use serde::Serialize; + +use crate::response::Response; + +#[derive(Clone, Debug, Serialize, Default)] +pub struct HandshakeResponse { + pub pub_key: String, +} + +impl From for Response { + fn from(response: HandshakeResponse) -> Self { + Self::Handshake(response) + } +} diff --git a/core/quartz-common/Cargo.toml b/core/quartz-common/Cargo.toml index b039afb..2c6373a 100644 --- a/core/quartz-common/Cargo.toml +++ b/core/quartz-common/Cargo.toml @@ -19,4 +19,4 @@ mock-sgx-enclave = ["quartz-enclave/mock-sgx"] [dependencies] quartz-cw = { workspace = true, optional = true } quartz-proto = { workspace = true, optional = true } -quartz-enclave = { workspace = true, optional = true } \ No newline at end of file +quartz-enclave = { workspace = true, optional = true } diff --git a/cosmwasm/packages/quartz-cw/Cargo.toml b/cosmwasm/packages/quartz-cw/Cargo.toml index 6694e9c..822b336 100644 --- a/cosmwasm/packages/quartz-cw/Cargo.toml +++ b/cosmwasm/packages/quartz-cw/Cargo.toml @@ -17,6 +17,7 @@ mock-sgx = [] k256.workspace = true serde.workspace = true serde_json.workspace = true +serde_with.workspace = true sha2.workspace = true thiserror.workspace = true diff --git a/cosmwasm/packages/quartz-cw/src/handler/execute/attested.rs b/cosmwasm/packages/quartz-cw/src/handler/execute/attested.rs index 101e125..61cf8be 100644 --- a/cosmwasm/packages/quartz-cw/src/handler/execute/attested.rs +++ b/cosmwasm/packages/quartz-cw/src/handler/execute/attested.rs @@ -93,8 +93,13 @@ where // 1. we avoid (the more expensive) attestation verification if the message handler fails // 2. we allow the message handler to make changes to the config so that the attestation // handler can use those changes, e.g. InstantiateMsg - Handler::handle(msg, deps.branch(), env, info)?; - Handler::handle(attestation, deps, env, info) + // return response from msg handle to include pub_key attribute + let res_msg = Handler::handle(msg, deps.branch(), env, info)?; + let res_attest = Handler::handle(attestation, deps, env, info)?; + + Ok(res_msg + .add_events(res_attest.events) + .add_attributes(res_attest.attributes)) } } diff --git a/cosmwasm/packages/quartz-cw/src/msg/execute/attested.rs b/cosmwasm/packages/quartz-cw/src/msg/execute/attested.rs index e77a0d9..41ea583 100644 --- a/cosmwasm/packages/quartz-cw/src/msg/execute/attested.rs +++ b/cosmwasm/packages/quartz-cw/src/msg/execute/attested.rs @@ -101,7 +101,7 @@ pub trait HasUserData { } /// A verifiable EPID attestation report generated by an enclave. -#[derive(Clone, Debug, PartialEq, Serialize)] +#[derive(Clone, Debug, PartialEq)] pub struct EpidAttestation { report: IASReport, } diff --git a/relayer/scripts/relay.sh b/relayer/scripts/relay.sh index af036b5..41db94d 100755 --- a/relayer/scripts/relay.sh +++ b/relayer/scripts/relay.sh @@ -9,7 +9,7 @@ usage() { } ROOT=${ROOT:-$HOME} -DIR_QUARTZ="$ROOT/cycles-quartz" +DIR_QUARTZ=$(git rev-parse --show-toplevel) DIR_PROTO="$DIR_QUARTZ/core/quartz-proto/proto" IAS_API_KEY="669244b3e6364b5888289a11d2a1726d" RA_CLIENT_SPID="51CAF5A48B450D624AEFE3286D314894" @@ -33,7 +33,9 @@ ATTESTED_MSG=$(grpcurl -plaintext -import-path "$DIR_PROTO" -proto quartz.proto QUOTE=$(echo "$ATTESTED_MSG" | jq -c '.quote') MSG=$(echo "$ATTESTED_MSG" | jq 'del(.quote)') -if [ -n "$MOCK_SGX" ]; then + +if [ "$MOCK_SGX" = "true" ]; then + case "$REQUEST" in "Instantiate") jq -nc --argjson msg "$MSG" --argjson "attestation" "$QUOTE" '$ARGS.named' @@ -48,7 +50,7 @@ if [ -n "$MOCK_SGX" ]; then usage ;; esac - exit + exit 0 fi # clear tmp files from previous runs diff --git a/relayer/src/main.rs b/relayer/src/main.rs index 0e7fcd7..259b805 100644 --- a/relayer/src/main.rs +++ b/relayer/src/main.rs @@ -163,11 +163,7 @@ pub async fn send_tx(node: impl ToString, tx_bytes: Vec) -> Result<(), Box Result> { - use std::{ - fs::{read_to_string, File}, - io::Write, - process::Command, - }; + use std::{fs::read_to_string, io::Write, process::Command}; let dir = tempfile::tempdir()?; let quote_file_path = dir.path().join("test.quote"); diff --git a/utils/cycles-sync/src/bin/submit.rs b/utils/cycles-sync/src/bin/submit.rs index f321e11..a5f3d85 100644 --- a/utils/cycles-sync/src/bin/submit.rs +++ b/utils/cycles-sync/src/bin/submit.rs @@ -105,7 +105,7 @@ async fn main() -> Result<(), anyhow::Error> { let wasmd_client = CliWasmdClient::new(node_url); - wasmd_client.tx_execute(&cli.mtcs, &chain_id, 3000000, cli.admin.to_string(), msg)?; + wasmd_client.tx_execute(&cli.mtcs, &chain_id, 3000000, &cli.admin.to_string(), msg)?; Ok(()) } diff --git a/utils/cycles-sync/src/main.rs b/utils/cycles-sync/src/main.rs index 9d82a76..d886a25 100644 --- a/utils/cycles-sync/src/main.rs +++ b/utils/cycles-sync/src/main.rs @@ -177,7 +177,7 @@ async fn sync_obligations( let msg = create_wasm_msg(intents_enc, liquidity_sources)?; let wasmd_client = CliWasmdClient::new(cli.node); - wasmd_client.tx_execute(&cli.contract, &cli.chain_id, 3000000, cli.user, msg)?; + wasmd_client.tx_execute(&cli.contract, &cli.chain_id, 3000000, &cli.user, msg)?; Ok(()) } diff --git a/utils/cycles-sync/src/wasmd_client.rs b/utils/cycles-sync/src/wasmd_client.rs index f93457b..d1c8b11 100644 --- a/utils/cycles-sync/src/wasmd_client.rs +++ b/utils/cycles-sync/src/wasmd_client.rs @@ -25,29 +25,31 @@ pub trait WasmdClient { query: Self::RawQuery, ) -> Result; + fn query_tx(&self, txhash: &str) -> Result; + fn tx_execute( &self, contract: &Self::Address, chain_id: &Id, gas: u64, - sender: String, + sender: &str, msg: M, ) -> Result; fn deploy( &self, chain_id: &Id, - sender: String, // what should this type be + sender: &str, // what should this type be wasm_path: M, ) -> Result; fn init( &self, chain_id: &Id, - sender: String, + sender: &str, code_id: usize, init_msg: M, - label: String, + label: &str, ) -> Result; } @@ -119,12 +121,29 @@ impl WasmdClient for CliWasmdClient { Ok(query_result) } + fn query_tx(&self, txhash: &str) -> Result { + let mut wasmd = Command::new("wasmd"); + let command = wasmd + .args(["--node", self.url.as_str()]) + .args(["query", "tx"]) + .arg(txhash) + .args(["--output", "json"]); + + let output = command.output()?; + if !output.status.success() { + return Err(anyhow!("{:?}", output)); + } + + let query_result: R = serde_json::from_slice(&output.stdout).unwrap_or_default(); + Ok(query_result) + } + fn tx_execute( &self, contract: &Self::Address, chain_id: &Id, gas: u64, - sender: String, + sender: &str, msg: M, ) -> Result { let mut wasmd = Command::new("wasmd"); @@ -134,7 +153,7 @@ impl WasmdClient for CliWasmdClient { .args(["tx", "wasm"]) .args(["execute", contract.as_ref(), &msg.to_string()]) .args(["--gas", &gas.to_string()]) - .args(["--from", sender.as_ref()]) + .args(["--from", sender]) .args(["--output", "json"]) .arg("-y"); @@ -151,14 +170,14 @@ impl WasmdClient for CliWasmdClient { fn deploy( &self, chain_id: &Id, - sender: String, + sender: &str, wasm_path: M, ) -> Result { let mut wasmd = Command::new("wasmd"); let command = wasmd .args(["--node", self.url.as_str()]) .args(["tx", "wasm", "store", &wasm_path.to_string()]) - .args(["--from", sender.as_ref()]) + .args(["--from", sender]) .args(["--chain-id", chain_id.as_ref()]) .args(["--gas-prices", "0.0025ucosm"]) .args(["--gas", "auto"]) @@ -179,18 +198,18 @@ impl WasmdClient for CliWasmdClient { fn init( &self, chain_id: &Id, - sender: String, + sender: &str, code_id: usize, init_msg: M, - label: String, + label: &str, ) -> Result { let mut wasmd = Command::new("wasmd"); let command = wasmd .args(["--node", self.url.as_str()]) .args(["tx", "wasm", "instantiate"]) .args([&code_id.to_string(), &init_msg.to_string()]) - .args(["--label", label.as_ref()]) - .args(["--from", sender.as_ref()]) + .args(["--label", label]) + .args(["--from", sender]) .arg("--no-admin") .args(["--chain-id", chain_id.as_ref()]) .args(["--gas-prices", "0.0025ucosm"]) diff --git a/utils/tm-prover/src/config.rs b/utils/tm-prover/src/config.rs index 60b80fa..5d7dcdd 100644 --- a/utils/tm-prover/src/config.rs +++ b/utils/tm-prover/src/config.rs @@ -69,13 +69,13 @@ pub struct ProofOutput { pub merkle_proof: RawCwProof, } -// TODO: Investigate if it's possible to derive default using Clap's default values +// TODO: Investigate if it's possible to derive default using Clap's default values, or otherwise find better default values impl Default for Config { fn default() -> Self { Config { chain_id: String::default(), primary: "http://127.0.0.1:26657".parse().unwrap(), - witnesses: "[]".parse().unwrap(), + witnesses: "http://127.0.0.1:26657".parse().unwrap(), trusted_height: Height::default(), trusted_hash: Hash::default(), trust_threshold: TrustThreshold::TWO_THIRDS, @@ -84,7 +84,9 @@ impl Default for Config { max_block_lag: 5u64, trace_file: None, verbose: Verbosity::default(), - contract_address: "".parse().unwrap(), + contract_address: "wasm14qdftsfk6fwn40l0xmruga08xlczl4g05npy70" + .parse() + .unwrap(), storage_key: String::default(), } } diff --git a/utils/tm-prover/src/main.rs b/utils/tm-prover/src/main.rs index e36333a..2f2b3f0 100644 --- a/utils/tm-prover/src/main.rs +++ b/utils/tm-prover/src/main.rs @@ -1,6 +1,7 @@ use clap::Parser; use color_eyre::eyre::Result; use tm_prover::{config::Config, prover::prove}; +use tracing_subscriber::{util::SubscriberInitExt, EnvFilter}; #[tokio::main] async fn main() -> Result<()> { @@ -8,5 +9,15 @@ async fn main() -> Result<()> { let args = Config::parse(); + let env_filter = EnvFilter::builder() + .with_default_directive(args.verbose.to_level_filter().into()) + .from_env_lossy(); + + tracing_subscriber::fmt() + .with_target(false) + .with_env_filter(env_filter) + .finish() + .init(); + prove(args).await } diff --git a/utils/tm-prover/src/prover.rs b/utils/tm-prover/src/prover.rs index 7a7f252..f3baec1 100644 --- a/utils/tm-prover/src/prover.rs +++ b/utils/tm-prover/src/prover.rs @@ -33,7 +33,6 @@ use tendermint_light_client::{ use tendermint_light_client_detector::{detect_divergence, Error, Provider, Trace}; use tendermint_rpc::{client::HttpClient, Client, HttpClientUrl}; use tracing::{error, info}; -use tracing_subscriber::{util::SubscriberInitExt, EnvFilter}; const WASM_STORE_KEY: &str = "/store/wasm/key"; @@ -51,21 +50,11 @@ pub async fn prove( max_clock_drift, max_block_lag, trace_file, - verbose, + verbose: _, contract_address, storage_key, }: TmProverConfig, ) -> Result<()> { - let env_filter = EnvFilter::builder() - .with_default_directive(verbose.to_level_filter().into()) - .from_env_lossy(); - - tracing_subscriber::fmt() - .with_target(false) - .with_env_filter(env_filter) - .finish() - .init(); - let options = Options { trust_threshold, trusting_period: Duration::from_secs(trusting_period),