diff --git a/.circleci/config.yml b/.circleci/config.yml index 09e0a4b9b5c..61b9c2f04b3 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -31,9 +31,6 @@ commands: - run: name: Build miner command: cargo build --release --bin tari_miner - - run: - name: Build validator node - command: cargo build --release --bin tari_validator_node - run: name: Run cucumber scenarios no_output_timeout: 20m @@ -64,9 +61,6 @@ commands: - run: name: Build base node command: cargo build --release --bin tari_base_node - - run: - name: Build validator node - command: cargo build --release --bin tari_validator_node - run: name: Build wallet command: cargo build --release --bin tari_console_wallet @@ -79,9 +73,6 @@ commands: - run: name: Build miner command: cargo build --release --bin tari_miner - - run: - name: Build validator node - command: cargo build --release --bin tari_validator_node # Below step requires NodeJS v12 to run correctly, see explanation in WalletFFI.feature - run: name: Run FFI wallet library cucumber scenarios diff --git a/.github/workflows/dan_layer_integration_tests.yml b/.github/workflows/dan_layer_integration_tests.yml deleted file mode 100644 index 7cdfecc2059..00000000000 --- a/.github/workflows/dan_layer_integration_tests.yml +++ /dev/null @@ -1,102 +0,0 @@ ---- -name: DAN - -on: - push: - pull_request: - types: - - opened - - reopened - - synchronize - -env: - toolchain: nightly-2022-05-01 - -jobs: - dan-layer-integration-tests: - name: integration tests - runs-on: [ self-hosted, ubuntu18.04-high-cpu ] - steps: - - name: checkout - uses: actions/checkout@v2 - - name: toolchain - uses: actions-rs/toolchain@v1 - with: - toolchain: ${{ env.toolchain }} - profile: minimal - override: true - - uses: Swatinem/rust-cache@v1 - - name: ubuntu dependencies - run: | - sudo apt-get update && \ - sudo apt-get -y install \ - openssl \ - libssl-dev \ - pkg-config \ - libsqlite3-dev \ - clang-10 \ - git \ - cmake \ - libc++-dev \ - libc++abi-dev \ - libprotobuf-dev \ - protobuf-compiler \ - libncurses5-dev \ - libncursesw5-dev \ - zip \ - build-essential \ - libgtk-3-dev \ - libwebkit2gtk-4.0-dev \ - libsoup2.4-dev \ - curl \ - wget \ - libappindicator3-dev \ - patchelf \ - librsvg2-dev - - name: node -v - run: node -v - - name: build base node - uses: actions-rs/cargo@v1 - with: - command: build - args: --release --bin tari_base_node -Z unstable-options - - name: build console wallet - uses: actions-rs/cargo@v1 - with: - command: build - args: --release --bin tari_console_wallet -Z unstable-options - - name: build merge mining proxy - uses: actions-rs/cargo@v1 - with: - command: build - args: --release --bin tari_merge_mining_proxy -Z unstable-options - - name: build miner - uses: actions-rs/cargo@v1 - with: - command: build - args: --release --bin tari_miner -Z unstable-options - - name: build wallet-ffi - uses: actions-rs/cargo@v1 - with: - command: build - args: --release --package tari_wallet_ffi -Z unstable-options - - name: build validator node - uses: actions-rs/cargo@v1 - with: - command: build - args: --release --bin tari_validator_node -Z unstable-options - - name: npm ci - run: cd integration_tests && npm ci && cd node_modules/wallet-grpc-client && npm install - - name: Run integration tests - run: cd integration_tests && mkdir -p cucumber_output && node_modules/.bin/cucumber-js --profile "non-critical" --tags "@dan and not @broken" --format json:cucumber_output/tests.cucumber --exit --retry 2 --retry-tag-filter "@flaky and not @broken" - - name: Generate report - if: always() - run: cd integration_tests && node ./generate_report.js - - name: Store test results - uses: actions/upload-artifact@v3 - if: always() - with: - name: test results - path: | - integration_tests/cucumber_output - integration_tests/temp/reports diff --git a/.license.ignore b/.license.ignore index 5080f746f1e..6551ee1d099 100644 --- a/.license.ignore +++ b/.license.ignore @@ -12,6 +12,7 @@ ./applications/tari_base_node/osx-pkg/scripts/preinstall ./applications/tari_console_wallet/linux/start_tari_console_wallet ./base_layer/key_manager/Makefile +./base_layer/p2p/src/dns/roots/tls.rs ./buildtools/docker/torrc ./docs/src/theme/book.js ./docs/src/theme/highlight.js diff --git a/Cargo.lock b/Cargo.lock index 940957c713c..a5d7d41dcb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,15 +2,6 @@ # It is not intended for manual editing. version = 3 -[[package]] -name = "addr2line" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b" -dependencies = [ - "gimli", -] - [[package]] name = "adler" version = "1.0.2" @@ -236,21 +227,6 @@ dependencies = [ "cc", ] -[[package]] -name = "backtrace" -version = "0.3.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11a17d453482a265fd5f8479f2a3f405566e6ca627837aaddb85af8b1ab8ef61" -dependencies = [ - "addr2line", - "cc", - "cfg-if 1.0.0", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", -] - [[package]] name = "base58-monero" version = "0.3.2" @@ -440,51 +416,6 @@ dependencies = [ "opaque-debug 0.3.0", ] -[[package]] -name = "borsh" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15bf3650200d8bffa99015595e10f1fbd17de07abbc25bb067da79e769939bfa" -dependencies = [ - "borsh-derive", - "hashbrown 0.11.2", -] - -[[package]] -name = "borsh-derive" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6441c552f230375d18e3cc377677914d2ca2b0d36e52129fe15450a2dce46775" -dependencies = [ - "borsh-derive-internal", - "borsh-schema-derive-internal", - "proc-macro-crate 0.1.5", - "proc-macro2", - "syn", -] - -[[package]] -name = "borsh-derive-internal" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5449c28a7b352f2d1e592a8a28bf139bc71afb0764a14f3c02500935d8c44065" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "borsh-schema-derive-internal" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdbd5696d8bfa21d53d9fe39a714a18538bad11492a42d066dbbc395fb1951c0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "bs58" version = "0.4.0" @@ -531,39 +462,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" -[[package]] -name = "bytecheck" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a31f923c2db9513e4298b72df143e6e655a759b3d6a0966df18f81223fff54f" -dependencies = [ - "bytecheck_derive", - "ptr_meta", -] - -[[package]] -name = "bytecheck_derive" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edb17c862a905d912174daa27ae002326fff56dc8b8ada50a0a5f0976cb174f0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "bytecodec" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adf4c9d0bbf32eea58d7c0f812058138ee8edaf0f2802b6d03561b504729a325" -dependencies = [ - "bincode", - "byteorder", - "serde", - "trackable 0.2.24", -] - [[package]] name = "bytemuck" version = "1.9.1" @@ -591,17 +489,6 @@ dependencies = [ "serde", ] -[[package]] -name = "cargo_toml" -version = "0.11.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5809dd3e6444651fd1cdd3dbec71eca438c439a0fcc8081674a14da0afe50185" -dependencies = [ - "serde", - "serde_derive", - "toml", -] - [[package]] name = "cassowary" version = "0.3.0" @@ -972,19 +859,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "corosensei" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9847f90f32a50b0dcbd68bc23ff242798b13080b97b0569f6ed96a45ce4cf2cd" -dependencies = [ - "autocfg", - "cfg-if 1.0.0", - "libc", - "scopeguard", - "windows-sys 0.33.0", -] - [[package]] name = "cpufeatures" version = "0.1.5" @@ -1009,65 +883,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dcb25d077389e53838a8158c8e99174c5a9d902dee4904320db714f3c653ffba" -[[package]] -name = "cranelift-bforest" -version = "0.82.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38faa2a16616c8e78a18d37b4726b98bfd2de192f2fdc8a39ddf568a408a0f75" -dependencies = [ - "cranelift-entity", -] - -[[package]] -name = "cranelift-codegen" -version = "0.82.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26f192472a3ba23860afd07d2b0217dc628f21fcc72617aa1336d98e1671f33b" -dependencies = [ - "cranelift-bforest", - "cranelift-codegen-meta", - "cranelift-codegen-shared", - "cranelift-entity", - "gimli", - "log", - "regalloc", - "smallvec", - "target-lexicon", -] - -[[package]] -name = "cranelift-codegen-meta" -version = "0.82.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f32ddb89e9b89d3d9b36a5b7d7ea3261c98235a76ac95ba46826b8ec40b1a24" -dependencies = [ - "cranelift-codegen-shared", -] - -[[package]] -name = "cranelift-codegen-shared" -version = "0.82.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01fd0d9f288cc1b42d9333b7a776b17e278fc888c28e6a0f09b5573d45a150bc" - -[[package]] -name = "cranelift-entity" -version = "0.82.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e3bfe172b83167604601faf9dc60453e0d0a93415b57a9c4d1a7ae6849185cf" - -[[package]] -name = "cranelift-frontend" -version = "0.82.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a006e3e32d80ce0e4ba7f1f9ddf66066d052a8c884a110b91d05404d6ce26dce" -dependencies = [ - "cranelift-codegen", - "log", - "smallvec", - "target-lexicon", -] - [[package]] name = "crc24" version = "0.1.6" @@ -1444,35 +1259,14 @@ dependencies = [ "zeroize", ] -[[package]] -name = "d3ne" -version = "0.7.4" -source = "git+https://github.com/stringhandler/d3ne-rs.git?branch=st-fixes2#ad2b0dfca267c9466251780aecb78bab139846e5" -dependencies = [ - "anyhow", - "serde", - "serde_json", - "thiserror", -] - [[package]] name = "darling" version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d706e75d87e35569db781a9b5e2416cff1236a47ed380831f959382ccd5f858" dependencies = [ - "darling_core 0.10.2", - "darling_macro 0.10.2", -] - -[[package]] -name = "darling" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a01d95850c592940db9b8194bc39f4bc0e89dee5c4265e4b1807c34a9aba453c" -dependencies = [ - "darling_core 0.13.4", - "darling_macro 0.13.4", + "darling_core", + "darling_macro", ] [[package]] @@ -1489,37 +1283,13 @@ dependencies = [ "syn", ] -[[package]] -name = "darling_core" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "859d65a907b6852c9361e3185c862aae7fafd2887876799fa55f5f99dc40d610" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "darling_macro" version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9b5a2f4ac4969822c62224815d069952656cadc7084fdca9751e6d959189b72" dependencies = [ - "darling_core 0.10.2", - "quote", - "syn", -] - -[[package]] -name = "darling_macro" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835" -dependencies = [ - "darling_core 0.13.4", + "darling_core", "quote", "syn", ] @@ -1577,7 +1347,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2658621297f2cf68762a6f7dc0bb7e1ff2cfd6583daef8ee0fed6f7ec468ec0" dependencies = [ - "darling 0.10.2", + "darling", "derive_builder_core", "proc-macro2", "quote", @@ -1590,7 +1360,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2791ea3e372c8495c0bc2033991d76b512cd799d07491fbd6890124db9458bef" dependencies = [ - "darling 0.10.2", + "darling", "proc-macro2", "quote", "syn", @@ -1781,47 +1551,6 @@ dependencies = [ "syn", ] -[[package]] -name = "enum-iterator" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eeac5c5edb79e4e39fe8439ef35207780a11f69c52cbe424ce3dfad4cb78de6" -dependencies = [ - "enum-iterator-derive", -] - -[[package]] -name = "enum-iterator-derive" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c134c37760b27a871ba422106eedbb8247da973a09e82558bf26d619c882b159" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "enumset" -version = "1.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4799cdb24d48f1f8a7a98d06b7fde65a85a2d1e42b25a889f5406aa1fbefe074" -dependencies = [ - "enumset_derive", -] - -[[package]] -name = "enumset_derive" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea83a3fbdc1d999ccfbcbee717eab36f8edf2d71693a23ce0d7cca19e085304c" -dependencies = [ - "darling 0.13.4", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "env_logger" version = "0.7.1" @@ -1878,12 +1607,6 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" -[[package]] -name = "fallible-iterator" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" - [[package]] name = "fast-float" version = "0.2.0" @@ -2173,17 +1896,6 @@ dependencies = [ "polyval 0.5.3", ] -[[package]] -name = "gimli" -version = "0.26.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78cc372d058dcf6d5ecd98510e7fbc9e5aec4d21de70f65fea8fecebcd881bd4" -dependencies = [ - "fallible-iterator", - "indexmap", - "stable_deref_trait", -] - [[package]] name = "git2" version = "0.8.0" @@ -2235,9 +1947,6 @@ name = "hashbrown" version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" -dependencies = [ - "ahash", -] [[package]] name = "hashbrown" @@ -2471,15 +2180,8 @@ checksum = "e6012d540c5baa3589337a98ce73408de9b5a25ec9fc2c6fd6be8f0d39e0ca5a" dependencies = [ "autocfg", "hashbrown 0.11.2", - "serde", ] -[[package]] -name = "indoc" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05a0bd019339e5d968b37855180087b7b9d512c5046fbd244cf8c95687927d6e" - [[package]] name = "instant" version = "0.1.12" @@ -2607,12 +2309,6 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" -[[package]] -name = "leb128" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67" - [[package]] name = "libc" version = "0.2.126" @@ -2824,36 +2520,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "loupe" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b6a72dfa44fe15b5e76b94307eeb2ff995a8c5b283b55008940c02e0c5b634d" -dependencies = [ - "indexmap", - "loupe-derive", - "rustversion", -] - -[[package]] -name = "loupe-derive" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0fbfc88337168279f2e9ae06e157cfed4efd3316e14dc96ed074d4f2e6c5952" -dependencies = [ - "quote", - "syn", -] - -[[package]] -name = "mach" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b823e83b2affd8f40a9ee8c29dbc56404c1e34cd2710921f2801e2cf29527afa" -dependencies = [ - "libc", -] - [[package]] name = "maplit" version = "1.0.2" @@ -2892,15 +2558,6 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" -[[package]] -name = "memmap2" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5172b50c23043ff43dd53e51392f36519d9b35a8f3a410d30ece5d1aedd58ae" -dependencies = [ - "libc", -] - [[package]] name = "memoffset" version = "0.6.5" @@ -3025,12 +2682,6 @@ dependencies = [ "tiny-keccak", ] -[[package]] -name = "more-asserts" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7843ec2de400bcbc6a6328c958dc38e5359da6e93e72e37bc5246bf1ae776389" - [[package]] name = "multiaddr" version = "0.14.0" @@ -3066,7 +2717,7 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc076939022111618a5026d3be019fd8b366e76314538ff9a1b59ffbcbf98bcd" dependencies = [ - "proc-macro-crate 1.1.3", + "proc-macro-crate", "proc-macro-error", "proc-macro2", "quote", @@ -3288,18 +2939,6 @@ dependencies = [ "libc", ] -[[package]] -name = "object" -version = "0.28.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e42c982f2d955fac81dd7e1d0e1426a7d702acd9c98d19ab01083a6a0328c424" -dependencies = [ - "crc32fast", - "hashbrown 0.11.2", - "indexmap", - "memchr", -] - [[package]] name = "once_cell" version = "1.12.0" @@ -3579,17 +3218,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" -[[package]] -name = "patricia_tree" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52c4b8ef84caee22395fa083b7d8ee9351e71cdf69a46c832528acdcac402117" -dependencies = [ - "bitflags 1.3.2", - "bytecodec", - "trackable 0.2.24", -] - [[package]] name = "peeking_take_while" version = "0.1.2" @@ -3879,20 +3507,11 @@ checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" [[package]] name = "proc-macro-crate" -version = "0.1.5" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d6ea3c4595b96363c13943497db34af4460fb474a95c43f4446ad341b8c9785" +checksum = "e17d47ce914bf4de440332250b0edd23ce48c005f59fab39d3335866b114f11a" dependencies = [ - "toml", -] - -[[package]] -name = "proc-macro-crate" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17d47ce914bf4de440332250b0edd23ce48c005f59fab39d3335866b114f11a" -dependencies = [ - "thiserror", + "thiserror", "toml", ] @@ -4003,26 +3622,6 @@ version = "2.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf7e6d18738ecd0902d30d1ad232c9125985a3422929b16c65517b38adc14f96" -[[package]] -name = "ptr_meta" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0738ccf7ea06b608c10564b31debd4f5bc5e197fc8bfe088f68ae5ce81e7a4f1" -dependencies = [ - "ptr_meta_derive", -] - -[[package]] -name = "ptr_meta_derive" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "qrcode" version = "0.12.0" @@ -4248,17 +3847,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "regalloc" -version = "0.0.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62446b1d3ebf980bdc68837700af1d77b37bc430e524bf95319c6eada2a4cc02" -dependencies = [ - "log", - "rustc-hash", - "smallvec", -] - [[package]] name = "regex" version = "1.5.6" @@ -4285,18 +3873,6 @@ version = "0.6.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49b3de9ec5dc0a3417da371aab17d729997c15010e7fd24ff707773a33bddb64" -[[package]] -name = "region" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76e189c2369884dce920945e2ddf79b3dff49e071a167dd1817fa9c4c00d512e" -dependencies = [ - "bitflags 1.3.2", - "libc", - "mach", - "winapi", -] - [[package]] name = "remove_dir_all" version = "0.5.3" @@ -4306,15 +3882,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "rend" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79af64b4b6362ffba04eef3a4e10829718a4896dac19daa741851c86781edf95" -dependencies = [ - "bytecheck", -] - [[package]] name = "reqwest" version = "0.11.11" @@ -4378,31 +3945,6 @@ dependencies = [ "opaque-debug 0.3.0", ] -[[package]] -name = "rkyv" -version = "0.7.39" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cec2b3485b07d96ddfd3134767b8a447b45ea4eb91448d0a35180ec0ffd5ed15" -dependencies = [ - "bytecheck", - "hashbrown 0.12.1", - "ptr_meta", - "rend", - "rkyv_derive", - "seahash", -] - -[[package]] -name = "rkyv_derive" -version = "0.7.39" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6eaedadc88b53e36dd32d940ed21ae4d850d5916f2581526921f553a72ac34c4" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "ron" version = "0.7.0" @@ -4454,12 +3996,6 @@ dependencies = [ "ordered-multimap", ] -[[package]] -name = "rustc-demangle" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342" - [[package]] name = "rustc-hash" version = "1.1.0" @@ -4525,12 +4061,6 @@ dependencies = [ "base64 0.13.0", ] -[[package]] -name = "rustversion" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2cc38e8fa666e2de3c4aba7edeb5ffc5246c1c2ed0e3d17e560aeeba736b23f" - [[package]] name = "rustyline" version = "9.1.2" @@ -4627,12 +4157,6 @@ dependencies = [ "untrusted", ] -[[package]] -name = "seahash" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" - [[package]] name = "security-framework" version = "2.6.1" @@ -4708,15 +4232,6 @@ dependencies = [ "serde", ] -[[package]] -name = "serde_bytes" -version = "0.11.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "212e73464ebcde48d723aa02eb270ba62eff38a9b732df31f33f1b4e145f3a54" -dependencies = [ - "serde", -] - [[package]] name = "serde_cbor" version = "0.11.2" @@ -4969,12 +4484,6 @@ dependencies = [ "der", ] -[[package]] -name = "stable_deref_trait" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" - [[package]] name = "stack-buf" version = "0.1.6" @@ -5097,12 +4606,6 @@ dependencies = [ "unicode-xid", ] -[[package]] -name = "target-lexicon" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c02424087780c9b71cc96799eaeddff35af2bc513278cda5c99fc1f5d026d3c1" - [[package]] name = "tari_app_grpc" version = "0.35.0" @@ -5537,113 +5040,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "tari_dan_common_types" -version = "0.1.0" -dependencies = [ - "borsh", - "prost", - "prost-types", - "tari_common", - "tari_common_types", -] - -[[package]] -name = "tari_dan_core" -version = "0.1.0" -dependencies = [ - "anyhow", - "async-trait", - "blake2 0.9.2", - "clap 3.2.15", - "digest 0.9.0", - "futures 0.3.21", - "lmdb-zero", - "log", - "num-derive", - "num-traits", - "prost", - "prost-types", - "rand 0.8.5", - "serde", - "serde_json", - "tari_common", - "tari_common_types", - "tari_comms", - "tari_comms_dht", - "tari_comms_rpc_macros", - "tari_core", - "tari_crypto", - "tari_dan_common_types", - "tari_dan_engine", - "tari_mmr", - "tari_p2p", - "tari_service_framework", - "tari_shutdown", - "tari_storage", - "tari_test_utils", - "tari_utilities", - "thiserror", - "tokio", - "tokio-stream", - "tonic", -] - -[[package]] -name = "tari_dan_engine" -version = "0.1.0" -dependencies = [ - "anyhow", - "borsh", - "cargo_toml", - "d3ne", - "digest 0.9.0", - "log", - "rand 0.8.5", - "serde", - "serde_json", - "tari_common", - "tari_common_types", - "tari_crypto", - "tari_dan_common_types", - "tari_mmr", - "tari_template_abi", - "tari_template_lib", - "tari_utilities", - "thiserror", - "wasmer", -] - -[[package]] -name = "tari_dan_storage_lmdb" -version = "0.1.0" -dependencies = [ - "borsh", - "lmdb-zero", - "tari_dan_engine", - "tari_storage", - "tempfile", -] - -[[package]] -name = "tari_dan_storage_sqlite" -version = "0.1.0" -dependencies = [ - "async-trait", - "borsh", - "diesel", - "diesel_migrations", - "log", - "tari_common", - "tari_common_types", - "tari_dan_core", - "tari_dan_engine", - "tari_utilities", - "thiserror", - "tokio", - "tokio-stream", -] - [[package]] name = "tari_key_manager" version = "0.35.0" @@ -5911,32 +5307,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "tari_template_abi" -version = "0.1.0" -dependencies = [ - "borsh", -] - -[[package]] -name = "tari_template_lib" -version = "0.1.0" -dependencies = [ - "borsh", - "serde", - "tari_template_abi", -] - -[[package]] -name = "tari_template_macros" -version = "0.1.0" -dependencies = [ - "indoc", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "tari_test_utils" version = "0.35.0" @@ -5964,51 +5334,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "tari_validator_node" -version = "0.35.0" -dependencies = [ - "anyhow", - "async-trait", - "blake2 0.9.2", - "bytecodec", - "clap 3.2.15", - "config", - "digest 0.9.0", - "futures 0.3.21", - "lmdb-zero", - "log", - "patricia_tree", - "prost", - "prost-types", - "rand 0.8.5", - "serde", - "serde_json", - "tari_app_grpc", - "tari_app_utilities", - "tari_common", - "tari_common_types", - "tari_comms", - "tari_comms_dht", - "tari_comms_rpc_macros", - "tari_core", - "tari_crypto", - "tari_dan_common_types", - "tari_dan_core", - "tari_dan_engine", - "tari_dan_storage_sqlite", - "tari_mmr", - "tari_p2p", - "tari_service_framework", - "tari_shutdown", - "tari_storage", - "tari_test_utils", - "thiserror", - "tokio", - "tokio-stream", - "tonic", -] - [[package]] name = "tari_wallet" version = "0.35.0" @@ -6552,35 +5877,6 @@ dependencies = [ "tracing-serde", ] -[[package]] -name = "trackable" -version = "0.2.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b98abb9e7300b9ac902cc04920945a874c1973e08c310627cc4458c04b70dd32" -dependencies = [ - "trackable 1.2.0", - "trackable_derive", -] - -[[package]] -name = "trackable" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "017e2a1a93718e4e8386d037cfb8add78f1d690467f4350fb582f55af1203167" -dependencies = [ - "trackable_derive", -] - -[[package]] -name = "trackable_derive" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebeb235c5847e2f82cfe0f07eb971d1e5f6804b18dac2ae16349cc604380f82f" -dependencies = [ - "quote", - "syn", -] - [[package]] name = "traitobject" version = "0.1.0" @@ -7000,273 +6296,6 @@ dependencies = [ "quote", ] -[[package]] -name = "wasm-encoder" -version = "0.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8905fd25fdadeb0e7e8bf43a9f46f9f972d6291ad0c7a32573b88dd13a6cfa6b" -dependencies = [ - "leb128", -] - -[[package]] -name = "wasmer" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea8d8361c9d006ea3d7797de7bd6b1492ffd0f91a22430cfda6c1658ad57bedf" -dependencies = [ - "cfg-if 1.0.0", - "indexmap", - "js-sys", - "loupe", - "more-asserts", - "target-lexicon", - "thiserror", - "wasm-bindgen", - "wasmer-artifact", - "wasmer-compiler", - "wasmer-compiler-cranelift", - "wasmer-derive", - "wasmer-engine", - "wasmer-engine-dylib", - "wasmer-engine-universal", - "wasmer-types", - "wasmer-vm", - "wat", - "winapi", -] - -[[package]] -name = "wasmer-artifact" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7aaf9428c29c1d8ad2ac0e45889ba8a568a835e33fd058964e5e500f2f7ce325" -dependencies = [ - "enumset", - "loupe", - "thiserror", - "wasmer-compiler", - "wasmer-types", -] - -[[package]] -name = "wasmer-compiler" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e67a6cd866aed456656db2cfea96c18baabbd33f676578482b85c51e1ee19d2c" -dependencies = [ - "enumset", - "loupe", - "rkyv", - "serde", - "serde_bytes", - "smallvec", - "target-lexicon", - "thiserror", - "wasmer-types", - "wasmparser", -] - -[[package]] -name = "wasmer-compiler-cranelift" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48be2f9f6495f08649e4f8b946a2cbbe119faf5a654aa1457f9504a99d23dae0" -dependencies = [ - "cranelift-codegen", - "cranelift-entity", - "cranelift-frontend", - "gimli", - "loupe", - "more-asserts", - "rayon", - "smallvec", - "target-lexicon", - "tracing", - "wasmer-compiler", - "wasmer-types", -] - -[[package]] -name = "wasmer-derive" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00e50405cc2a2f74ff574584710a5f2c1d5c93744acce2ca0866084739284b51" -dependencies = [ - "proc-macro-error", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "wasmer-engine" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f98f010978c244db431b392aeab0661df7ea0822343334f8f2a920763548e45" -dependencies = [ - "backtrace", - "enumset", - "lazy_static", - "loupe", - "memmap2", - "more-asserts", - "rustc-demangle", - "serde", - "serde_bytes", - "target-lexicon", - "thiserror", - "wasmer-artifact", - "wasmer-compiler", - "wasmer-types", - "wasmer-vm", -] - -[[package]] -name = "wasmer-engine-dylib" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad0358af9c154724587731175553805648d9acb8f6657880d165e378672b7e53" -dependencies = [ - "cfg-if 1.0.0", - "enum-iterator", - "enumset", - "leb128", - "libloading", - "loupe", - "object", - "rkyv", - "serde", - "tempfile", - "tracing", - "wasmer-artifact", - "wasmer-compiler", - "wasmer-engine", - "wasmer-object", - "wasmer-types", - "wasmer-vm", - "which", -] - -[[package]] -name = "wasmer-engine-universal" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "440dc3d93c9ca47865a4f4edd037ea81bf983b5796b59b3d712d844b32dbef15" -dependencies = [ - "cfg-if 1.0.0", - "enumset", - "leb128", - "loupe", - "region", - "rkyv", - "wasmer-compiler", - "wasmer-engine", - "wasmer-engine-universal-artifact", - "wasmer-types", - "wasmer-vm", - "winapi", -] - -[[package]] -name = "wasmer-engine-universal-artifact" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68f1db3f54152657eb6e86c44b66525ff7801dad8328fe677da48dd06af9ad41" -dependencies = [ - "enum-iterator", - "enumset", - "loupe", - "rkyv", - "thiserror", - "wasmer-artifact", - "wasmer-compiler", - "wasmer-types", -] - -[[package]] -name = "wasmer-object" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d831335ff3a44ecf451303f6f891175c642488036b92ceceb24ac8623a8fa8b" -dependencies = [ - "object", - "thiserror", - "wasmer-compiler", - "wasmer-types", -] - -[[package]] -name = "wasmer-types" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39df01ea05dc0a9bab67e054c7cb01521e53b35a7bb90bd02eca564ed0b2667f" -dependencies = [ - "backtrace", - "enum-iterator", - "indexmap", - "loupe", - "more-asserts", - "rkyv", - "serde", - "thiserror", -] - -[[package]] -name = "wasmer-vm" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30d965fa61f4dc4cdb35a54daaf7ecec3563fbb94154a6c35433f879466247dd" -dependencies = [ - "backtrace", - "cc", - "cfg-if 1.0.0", - "corosensei", - "enum-iterator", - "indexmap", - "lazy_static", - "libc", - "loupe", - "mach", - "memoffset", - "more-asserts", - "region", - "rkyv", - "scopeguard", - "serde", - "thiserror", - "wasmer-artifact", - "wasmer-types", - "winapi", -] - -[[package]] -name = "wasmparser" -version = "0.83.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "718ed7c55c2add6548cca3ddd6383d738cd73b892df400e96b9aa876f0141d7a" - -[[package]] -name = "wast" -version = "45.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "186c474c4f9bb92756b566d592a16591b4526b1a4841171caa3f31d7fe330d96" -dependencies = [ - "leb128", - "memchr", - "unicode-width", - "wasm-encoder", -] - -[[package]] -name = "wat" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2d4bc4724b4f02a482c8cab053dac5ef26410f264c06ce914958f9a42813556" -dependencies = [ - "wast", -] - [[package]] name = "web-sys" version = "0.3.57" @@ -7352,19 +6381,6 @@ dependencies = [ "windows_x86_64_msvc 0.30.0", ] -[[package]] -name = "windows-sys" -version = "0.33.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43dbb096663629518eb1dfa72d80243ca5a6aca764cae62a2df70af760a9be75" -dependencies = [ - "windows_aarch64_msvc 0.33.0", - "windows_i686_gnu 0.33.0", - "windows_i686_msvc 0.33.0", - "windows_x86_64_gnu 0.33.0", - "windows_x86_64_msvc 0.33.0", -] - [[package]] name = "windows-sys" version = "0.36.1" @@ -7384,12 +6400,6 @@ version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29277a4435d642f775f63c7d1faeb927adba532886ce0287bd985bffb16b6bca" -[[package]] -name = "windows_aarch64_msvc" -version = "0.33.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd761fd3eb9ab8cc1ed81e56e567f02dd82c4c837e48ac3b2181b9ffc5060807" - [[package]] name = "windows_aarch64_msvc" version = "0.36.1" @@ -7402,12 +6412,6 @@ version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1145e1989da93956c68d1864f32fb97c8f561a8f89a5125f6a2b7ea75524e4b8" -[[package]] -name = "windows_i686_gnu" -version = "0.33.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cab0cf703a96bab2dc0c02c0fa748491294bf9b7feb27e1f4f96340f208ada0e" - [[package]] name = "windows_i686_gnu" version = "0.36.1" @@ -7420,12 +6424,6 @@ version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4a09e3a0d4753b73019db171c1339cd4362c8c44baf1bcea336235e955954a6" -[[package]] -name = "windows_i686_msvc" -version = "0.33.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cfdbe89cc9ad7ce618ba34abc34bbb6c36d99e96cae2245b7943cd75ee773d0" - [[package]] name = "windows_i686_msvc" version = "0.36.1" @@ -7438,12 +6436,6 @@ version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ca64fcb0220d58db4c119e050e7af03c69e6f4f415ef69ec1773d9aab422d5a" -[[package]] -name = "windows_x86_64_gnu" -version = "0.33.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4dd9b0c0e9ece7bb22e84d70d01b71c6d6248b81a3c60d11869451b4cb24784" - [[package]] name = "windows_x86_64_gnu" version = "0.36.1" @@ -7456,12 +6448,6 @@ version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08cabc9f0066848fef4bc6a1c1668e6efce38b661d2aeec75d18d8617eebb5f1" -[[package]] -name = "windows_x86_64_msvc" -version = "0.33.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff1e4aa646495048ec7f3ffddc411e1d829c026a2ec62b39da15c1055e406eaa" - [[package]] name = "windows_x86_64_msvc" version = "0.36.1" diff --git a/Cargo.toml b/Cargo.toml index b5c14ec1c1f..50bf4fc94a5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,12 +13,6 @@ members = [ "comms/core", "comms/dht", "comms/rpc_macros", - "dan_layer/core", - "dan_layer/storage_lmdb", - "dan_layer/storage_sqlite", - "dan_layer/template_abi", - "dan_layer/template_lib", - "dan_layer/template_macros", "common_sqlite", "infrastructure/libtor", "infrastructure/metrics", @@ -32,7 +26,6 @@ members = [ "applications/tari_app_utilities", "applications/tari_merge_mining_proxy", "applications/tari_miner", - "applications/tari_validator_node", ] # diff --git a/applications/tari_validator_node/Cargo.toml b/applications/tari_validator_node/Cargo.toml deleted file mode 100644 index bba356e0c3c..00000000000 --- a/applications/tari_validator_node/Cargo.toml +++ /dev/null @@ -1,57 +0,0 @@ -[package] -name = "tari_validator_node" -authors = ["The Tari Development Community"] -description = "The Tari validator node implementation" -repository = "https://github.com/tari-project/tari" -license = "BSD-3-Clause" -version = "0.35.0" -edition = "2018" - -[dependencies] -tari_app_utilities = { path = "../tari_app_utilities" } -tari_app_grpc = { path = "../tari_app_grpc" } -tari_common = { path = "../../common" } -tari_comms = { path = "../../comms/core" } -tari_comms_dht = { path = "../../comms/dht" } -tari_comms_rpc_macros = { path = "../../comms/rpc_macros" } -tari_crypto = { git = "https://github.com/tari-project/tari-crypto.git", tag = "v0.15.4" } -tari_mmr = { path = "../../base_layer/mmr" } -tari_p2p = { path = "../../base_layer/p2p" } -tari_service_framework = { path = "../../base_layer/service_framework" } -tari_shutdown = { path = "../../infrastructure/shutdown" } -tari_storage = { path = "../../infrastructure/storage" } -tari_core = { path = "../../base_layer/core" } -tari_dan_core = { path = "../../dan_layer/core" } -tari_dan_storage_sqlite = { path = "../../dan_layer/storage_sqlite" } -tari_dan_common_types = { path = "../../dan_layer/common_types" } -tari_common_types = { path = "../../base_layer/common_types" } -tari_dan_engine = { path = "../../dan_layer/engine"} - -anyhow = "1.0.53" -async-trait = "0.1.50" -blake2 = "0.9.2" -clap = { version = "3.2.5", features = ["env"] } -config = "0.13.0" -digest = "0.9.0" -futures = { version = "^0.3.1" } -log = { version = "0.4.8", features = ["std"] } -lmdb-zero = "0.4.4" -prost = "0.9" -prost-types = "0.9" -rand = "0.8" -serde = "1.0.126" -thiserror = "^1.0.20" -tokio = { version = "1.10", features = ["macros", "time", "sync", "rt-multi-thread"] } -tokio-stream = { version = "0.1.7", features = ["sync"] } -tonic = "0.6.2" - -# saving of patricia tree -patricia_tree = { version = "0.3.0", features = ["binary-format"] } -bytecodec = { version = "0.4.14", features = ["bincode_codec"] } -serde_json = "1.0.64" - -[dev-dependencies] -tari_test_utils = { path = "../../infrastructure/test_utils" } - -[build-dependencies] -tari_common = { path = "../../common", features = ["build"] } diff --git a/applications/tari_validator_node/build.rs b/applications/tari_validator_node/build.rs deleted file mode 100644 index dece9cfad9b..00000000000 --- a/applications/tari_validator_node/build.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -fn main() -> Result<(), Box> { - tari_common::build::ProtobufCompiler::new() - .proto_paths(&["proto/dan"]) - .include_paths(&["proto/dan"]) - .emit_rerun_if_changed_directives() - .compile() - .unwrap(); - Ok(()) -} diff --git a/applications/tari_validator_node/log4rs_sample.yml b/applications/tari_validator_node/log4rs_sample.yml deleted file mode 100644 index d19656abcc0..00000000000 --- a/applications/tari_validator_node/log4rs_sample.yml +++ /dev/null @@ -1,194 +0,0 @@ -# A sample log configuration file for running in release mode. By default, this configuration splits up log messages to -# three destinations: -# * Console: For log messages with level INFO and higher -# * log/validator-node/network.log: INFO-level logs related to the comms crate. This file will be quite busy since there -# are lots of P2P debug messages, and so this traffic is segregated from the application log messages -# * log/validator-node/base_layer.log: Non-comms related INFO-level messages and higher are logged into this file -# * log/validator-node/other.log: Third-party crates' messages will be logged here at an ERROR level -# -# See https://docs.rs/log4rs/0.8.3/log4rs/encode/pattern/index.html for deciphering the log pattern. The log format -# used in this sample configuration prints messages as: -# timestamp [target] LEVEL message -refresh_rate: 30 seconds -appenders: - # An appender named "stdout" that writes to stdout - stdout: - kind: console - - encoder: - pattern: "{d(%H:%M)} {h({l}):5} {m}{n}" - filters: - - kind: threshold - level: info - - # An appender named "network" that writes to a file with a custom pattern encoder - network: - kind: rolling_file - path: "log/validator-node/network.log" - policy: - kind: compound - trigger: - kind: size - limit: 10mb - roller: - kind: fixed_window - base: 1 - count: 5 - pattern: "log/validator-node/network.{}.log" - encoder: - pattern: "{d(%Y-%m-%d %H:%M:%S.%f)} [{t}] [Thread:{I}] {l:5} {m}{n} // {f}:{L}" - - # An appender named "base_layer" that writes to a file with a custom pattern encoder - base_layer: - kind: rolling_file - path: "log/validator-node/base_layer.log" - policy: - kind: compound - trigger: - kind: size - limit: 10mb - roller: - kind: fixed_window - base: 1 - count: 5 - pattern: "log/validator-node/base_layer.{}.log" - encoder: - pattern: "{d(%Y-%m-%d %H:%M:%S.%f)} [{t}] [{X(node-public-key)},{X(node-id)}] {l:5} {m}{n} // {f}:{L} " - - # An appender named "base_layer" that writes to a file with a custom pattern encoder - dan_layer: - kind: rolling_file - path: "log/validator-node/dan_layer.log" - policy: - kind: compound - trigger: - kind: size - limit: 10mb - roller: - kind: fixed_window - base: 1 - count: 5 - pattern: "log/validator-node/dan_layer.{}.log" - encoder: - pattern: "{d(%Y-%m-%d %H:%M:%S.%f)} [{t}] [{X(node-public-key)},{X(node-id)}] {l:5} {m}{n} // {f}:{L} " - - - # An appender named "other" that writes to a file with a custom pattern encoder - other: - kind: rolling_file - path: "log/validator-node/other.log" - policy: - kind: compound - trigger: - kind: size - limit: 10mb - roller: - kind: fixed_window - base: 1 - count: 5 - pattern: "log/validator-node/other.{}.log" - encoder: - pattern: "{d(%Y-%m-%d %H:%M:%S.%f)} [{t}] [Thread:{I}] {l:5} {m}{n} // {f}:{L} " - -# Set the default logging level to "info" -root: - level: warn - appenders: - - stdout - -loggers: - # Route log events common to every application to all appenders - - tari::application: - level: info - appenders: - - dan_layer - - other - - stdout - additive: false - - tari::validator_node: - level: info - appenders: - - dan_layer - - stdout - additive: false - - tari::dan: - level: info - appenders: - - dan_layer - - stdout - additive: false - - tari::dan_layer: - level: info - appenders: - - dan_layer - - stdout - additive: false - - # Route log events sent to the "core" logger to the "base_layer" appender - c: - level: info - appenders: - - base_layer - tari: - level: info - appenders: - - base_layer - - # Route log events sent to the "wallet" logger to the "base_layer" appender - wallet: - level: info - appenders: - - base_layer - # Route log events sent to the "comms" logger to the "network" appender - comms: - level: debug - appenders: - - network - # Route log events sent to the "p2p" logger to the "network" appender - p2p: - level: debug - appenders: - - network - - # Route log events sent to the "yamux" logger to the "network" appender - yamux: - level: info - appenders: - - network - # Route log events sent to the "mio" logger to the "network" appender - mio: - level: error - appenders: - - network - # Route log events sent to the "rustyline" logger to the "other" appender - rustyline: - level: error - appenders: - - other - additive: false - - # Route log events sent to the "tokio_util" logger to the "other" appender - tokio_util: - level: error - appenders: - - other - # Route PGP log events - pgp: - level: warn - appenders: - - other - # Route log events sent to the "tari_mm_proxy" logger to the "base_layer" appender - tari_mm_proxy: - level: info - appenders: - - base_layer - # Route R2D2 log events - r2d2: - level: warn - appenders: - - other - additive: false diff --git a/applications/tari_validator_node/proto/dan/common.proto b/applications/tari_validator_node/proto/dan/common.proto deleted file mode 100644 index 1fe3120754c..00000000000 --- a/applications/tari_validator_node/proto/dan/common.proto +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -syntax = "proto3"; - -package tari.dan.common; - -message SideChainBlock { - Node node = 1; - InstructionSet instructions = 2; -} - -message Node { - bytes hash = 1; - bytes parent = 2; - uint32 height = 3; - bool is_committed = 4; -} - -message Instruction { - uint32 template_id = 1; - string method = 2; - bytes args = 3; - bytes sender = 4; -} - -message InstructionSet{ - repeated Instruction instructions = 1; -} - -message SignerSignature { - bytes signer = 1; - Signature signature = 2; -} - -message Signature { - bytes public_nonce = 1; - bytes signature = 2; -} diff --git a/applications/tari_validator_node/proto/dan/consensus.proto b/applications/tari_validator_node/proto/dan/consensus.proto deleted file mode 100644 index 80f243e4df8..00000000000 --- a/applications/tari_validator_node/proto/dan/consensus.proto +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -syntax = "proto3"; - -package tari.dan.consensus; - -import "common.proto"; - -enum HotStuffMessageType { - HOT_STUFF_MESSAGE_TYPE_UNKNOWN = 0; - HOT_STUFF_MESSAGE_TYPE_NEW_VIEW = 1; - HOT_STUFF_MESSAGE_TYPE_PREPARE = 2; - HOT_STUFF_MESSAGE_TYPE_PRE_COMMIT = 3; - HOT_STUFF_MESSAGE_TYPE_COMMIT = 4; - HOT_STUFF_MESSAGE_TYPE_GENESIS = 255; - -} - -message HotStuffMessage { - uint64 view_number = 1; - HotStuffMessageType message_type = 2; - QuorumCertificate justify = 3; - HotStuffTreeNode node= 4; - ValidatorSignature partial_sig = 5; - bytes node_hash = 6; - bytes contract_id = 7; - tari.dan.common.SignerSignature checkpoint_signature = 8; -} - -message QuorumCertificate { - HotStuffMessageType message_type = 1; - bytes node_hash = 2; - uint64 view_number = 3; - ValidatorSignature signature = 4; -} - -message HotStuffTreeNode { - bytes parent = 1; - TariDanPayload payload = 2; - uint32 height = 3; - bytes state_root =4; -} - -message ValidatorSignature{ - -} - -message TariDanPayload { - tari.dan.common.InstructionSet instruction_set = 1; - CheckpointData checkpoint = 2; -} - -message CheckpointData { - // todo: fill this in -} diff --git a/applications/tari_validator_node/proto/dan/validator_node.proto b/applications/tari_validator_node/proto/dan/validator_node.proto deleted file mode 100644 index c0386d6ff1b..00000000000 --- a/applications/tari_validator_node/proto/dan/validator_node.proto +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -syntax = "proto3"; - -package tari.dan.validator_node; - -import "common.proto"; - -service ValidatorNode { - rpc GetTokenData(GetTokenDataRequest) returns (GetTokenDataResponse); - rpc InvokeReadMethod(InvokeReadMethodRequest) returns (InvokeReadMethodResponse); - rpc InvokeMethod(InvokeMethodRequest) returns (InvokeMethodResponse); -} - -message GetTokenDataRequest { - bytes asset_pub_key = 1; - bytes unique_id = 2; -} - -message GetTokenDataResponse {} - -enum Status { - Accepted = 0; - Errored = 1; -} - - -message InvokeReadMethodRequest{ - bytes contract_id = 1; - uint32 template_id = 2; - string method = 3; - bytes args = 4; - bytes sender = 5; -} - -message InvokeReadMethodResponse { - bytes result = 1; -} - - -message InvokeMethodRequest{ - bytes contract_id = 1; - uint32 template_id = 2; - string method = 3; - bytes args = 4; - bytes sender = 5; -} - -message InvokeMethodResponse { - bytes result = 1; - Status status = 2; -} - -message GetSidechainBlocksRequest { - bytes contract_id = 1; - bytes start_hash = 2; - bytes end_hash = 3; -} - -message GetSidechainBlocksResponse { - tari.dan.common.SideChainBlock block = 1; -} - -message GetSidechainStateRequest { - bytes contract_id = 1; -} - -message GetSidechainStateResponse { - oneof state { - string schema = 1; - KeyValue key_value = 2; - } -} - -message KeyValue { - bytes key = 1; - bytes value = 2; -} - -message GetStateOpLogsRequest { - bytes contract_id = 1; - uint64 height = 2; -} - -message GetStateOpLogsResponse { - repeated StateOpLog op_logs = 1; -} - -message StateOpLog { - uint64 height = 1; - string operation = 2; - string schema = 3; - bytes key = 4; - bytes value = 5; - bytes merkle_root = 6; -} - -message GetTipNodeRequest{ - bytes contract_id = 1; -} - -message GetTipNodeResponse { - tari.dan.common.Node tip_node = 1; -} diff --git a/applications/tari_validator_node/src/asset.rs b/applications/tari_validator_node/src/asset.rs deleted file mode 100644 index fcd5bd8e13b..00000000000 --- a/applications/tari_validator_node/src/asset.rs +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - collections::HashMap, - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, - }, -}; - -use tari_dan_core::models::AssetDefinition; - -#[derive(Debug)] -#[allow(dead_code)] -pub struct Asset { - definition: AssetDefinition, - current_state: bool, - // Changes in the committee for this asset. - // Mined height of the change TXs, and the involvement in the committee (true = part of committee) - next_states: HashMap, - kill_signal: Option>, -} - -#[allow(dead_code)] -impl Asset { - pub fn new(definition: AssetDefinition) -> Self { - Self { - definition, - current_state: false, - next_states: HashMap::new(), - kill_signal: None, - } - } - - pub fn update_height(&mut self, height: u64, start: Fstart) - where Fstart: Fn(AssetDefinition) -> Arc { - if let Some((&height, &involvement)) = self - .next_states - .iter() - .find(|(&mined_height, _)| mined_height <= height) - { - // State change - if self.current_state != involvement { - if involvement { - self.kill_signal = Some(start(self.definition.clone())); - } else { - // Switch on the kill signal for the asset to end processing - let stop = self.kill_signal.clone().unwrap(); - stop.as_ref().store(true, Ordering::Relaxed); - self.kill_signal = None; - } - } - self.current_state = involvement; - // We have the current state set and we will keep only future updates - self.next_states - .retain(|&effective_height, _| effective_height > height); - // Monitor this asset if we are part of committee or there is a next state - } - } - - // If we are part of committee or there is a next state then monitor this asset - pub fn should_monitor(&self) -> bool { - self.current_state || !self.next_states.is_empty() - } - - pub fn add_state(&mut self, height: u64, involvement: bool) { - self.next_states.insert(height, involvement); - } - - pub fn is_committee_member(&self) -> bool { - self.current_state - } -} diff --git a/applications/tari_validator_node/src/cli.rs b/applications/tari_validator_node/src/cli.rs deleted file mode 100644 index d9d86ae85b2..00000000000 --- a/applications/tari_validator_node/src/cli.rs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use clap::Parser; -use tari_app_utilities::common_cli_args::CommonCliArgs; -use tari_common::configuration::{ConfigOverrideProvider, Network}; - -#[derive(Parser, Debug)] -#[clap(author, version, about, long_about = None)] -#[clap(propagate_version = true)] -pub(crate) struct Cli { - #[clap(flatten)] - pub common: CommonCliArgs, - /// Enable tracing - #[clap(long, aliases = &["tracing", "enable-tracing"])] - pub tracing_enabled: bool, - /// Supply a network (overrides existing configuration) - #[clap(long, env = "TARI_NETWORK")] - pub network: Option, -} - -impl ConfigOverrideProvider for Cli { - fn get_config_property_overrides(&self, default_network: Network) -> Vec<(String, String)> { - let mut overrides = self.common.get_config_property_overrides(default_network); - let network = self.network.clone().unwrap_or_else(|| default_network.to_string()); - overrides.push(("network".to_string(), network.clone())); - overrides.push(("validator_node.override_from".to_string(), network.clone())); - overrides.push(("p2p.seeds.override_from".to_string(), network)); - overrides - } -} diff --git a/applications/tari_validator_node/src/cmd_args.rs b/applications/tari_validator_node/src/cmd_args.rs deleted file mode 100644 index 2cb53c35c65..00000000000 --- a/applications/tari_validator_node/src/cmd_args.rs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// use clap::App; - -// pub fn _get_operation_mode() -> OperationMode { -// let _matches = App::new("Tari DAN node").version("1.0").get_matches(); -// OperationMode::Run -// } - -// pub enum OperationMode { -// Run, -// } - -// pub struct DanNodeConfig {} diff --git a/applications/tari_validator_node/src/comms.rs b/applications/tari_validator_node/src/comms.rs deleted file mode 100644 index 6db8580d339..00000000000 --- a/applications/tari_validator_node/src/comms.rs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::sync::Arc; - -use tari_app_utilities::{identity_management, identity_management::load_from_json}; -use tari_common::exit_codes::{ExitCode, ExitError}; -use tari_comms::{protocol::rpc::RpcServer, NodeIdentity, UnspawnedCommsNode}; -use tari_comms_dht::Dht; -use tari_dan_core::services::{ConcreteAssetProcessor, MempoolServiceHandle}; -use tari_dan_storage_sqlite::SqliteDbFactory; -use tari_p2p::{ - comms_connector::{pubsub_connector, SubscriptionFactory}, - initialization::{spawn_comms_using_transport, P2pInitializer}, -}; -use tari_service_framework::{ServiceHandles, StackBuilder}; -use tari_shutdown::ShutdownSignal; - -use crate::{config::ApplicationConfig, p2p::create_validator_node_rpc_service}; - -pub async fn build_service_and_comms_stack( - config: &ApplicationConfig, - shutdown: ShutdownSignal, - node_identity: Arc, - mempool: MempoolServiceHandle, - db_factory: SqliteDbFactory, - asset_processor: ConcreteAssetProcessor, -) -> Result<(ServiceHandles, SubscriptionFactory), ExitError> { - let (publisher, peer_message_subscriptions) = pubsub_connector(100, 50); - - let mut p2p_config = config.validator_node.p2p.clone(); - p2p_config.transport.tor.identity = load_from_json(&config.validator_node.tor_identity_file) - .map_err(|e| ExitError::new(ExitCode::ConfigError, e))?; - - let mut handles = StackBuilder::new(shutdown.clone()) - .add_initializer(P2pInitializer::new( - p2p_config.clone(), - config.peer_seeds.clone(), - config.network, - node_identity.clone(), - publisher, - )) - .build() - .await - .map_err(|err| ExitError::new(ExitCode::ConfigError, err.to_string()))?; - - let comms = handles - .take_handle::() - .expect("P2pInitializer was not added to the stack or did not add UnspawnedCommsNode"); - - let comms = setup_p2p_rpc(config, comms, &handles, mempool, db_factory, asset_processor); - - let comms = spawn_comms_using_transport(comms, p2p_config.transport.clone()) - .await - .map_err(|e| ExitError::new(ExitCode::ConfigError, format!("Could not spawn using transport: {}", e)))?; - - // Save final node identity after comms has initialized. This is required because the public_address can be - // changed by comms during initialization when using tor. - identity_management::save_as_json(&config.validator_node.identity_file, &*comms.node_identity()) - .map_err(|e| ExitError::new(ExitCode::ConfigError, format!("Failed to save node identity: {}", e)))?; - if let Some(hs) = comms.hidden_service() { - identity_management::save_as_json(&config.validator_node.tor_identity_file, hs.tor_identity()) - .map_err(|e| ExitError::new(ExitCode::ConfigError, format!("Failed to save tor identity: {}", e)))?; - } - - handles.register(comms); - Ok((handles, peer_message_subscriptions)) -} - -fn setup_p2p_rpc( - config: &ApplicationConfig, - comms: UnspawnedCommsNode, - handles: &ServiceHandles, - mempool: MempoolServiceHandle, - db_factory: SqliteDbFactory, - asset_processor: ConcreteAssetProcessor, -) -> UnspawnedCommsNode { - let dht = handles.expect_handle::(); - let rpc_server = RpcServer::builder() - - .with_maximum_simultaneous_sessions( -config.validator_node.p2p.rpc_max_simultaneous_sessions - ) - .finish() - - // Add your RPC services here ‍🏴‍☠️️☮️🌊 - .add_service(dht.rpc_service()) - .add_service(create_validator_node_rpc_service(mempool, db_factory, asset_processor)); - - comms.add_protocol_extension(rpc_server) -} diff --git a/applications/tari_validator_node/src/config.rs b/applications/tari_validator_node/src/config.rs deleted file mode 100644 index 21bc0d5f836..00000000000 --- a/applications/tari_validator_node/src/config.rs +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - net::{IpAddr, Ipv4Addr, SocketAddr}, - path::{Path, PathBuf}, -}; - -use config::Config; -use serde::{Deserialize, Serialize}; -use tari_common::{ - configuration::{CommonConfig, Network}, - ConfigurationError, - DefaultConfigLoader, - SubConfigPath, -}; -use tari_comms::multiaddr::Multiaddr; -use tari_p2p::{P2pConfig, PeerSeedsConfig}; - -#[derive(Debug, Clone)] -pub struct ApplicationConfig { - pub common: CommonConfig, - pub validator_node: ValidatorNodeConfig, - pub peer_seeds: PeerSeedsConfig, - pub network: Network, -} - -impl ApplicationConfig { - pub fn load_from(cfg: &Config) -> Result { - let mut config = Self { - common: CommonConfig::load_from(cfg)?, - validator_node: ValidatorNodeConfig::load_from(cfg)?, - peer_seeds: PeerSeedsConfig::load_from(cfg)?, - network: cfg.get("network")?, - }; - config.validator_node.set_base_path(config.common.base_path()); - Ok(config) - } -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -#[serde(deny_unknown_fields)] -pub struct ValidatorNodeConfig { - override_from: Option, - /// A path to the file that stores your node identity and secret key - pub identity_file: PathBuf, - /// A path to the file that stores the tor hidden service private key, if using the tor transport - pub tor_identity_file: PathBuf, - /// The node's publicly-accessible hostname - pub public_address: Option, - /// The asset worker will adhere to this phased timeout for the asset - pub phase_timeout: u64, - /// The Tari base node's GRPC address - pub base_node_grpc_address: SocketAddr, - /// The Tari console wallet's GRPC address - pub wallet_grpc_address: SocketAddr, - /// If set to false, there will be no scanning at all - pub scan_for_assets: bool, - /// How often do we want to scan the base layer for changes - pub new_asset_scanning_interval: u64, - /// If set then only the specific assets will be checked - pub assets_allow_list: Option>, - /// The relative path to store persistent data - pub data_dir: PathBuf, - /// The p2p configuration settings - pub p2p: P2pConfig, - /// The constitution will auto accept contracts if true - pub constitution_auto_accept: bool, - /// Constitution confirmation time in block height - pub constitution_management_confirmation_time: u64, - /// Constitution polling interval in block height - pub constitution_management_polling_interval: u64, - /// Constitution polling interval in time (seconds) - pub constitution_management_polling_interval_in_seconds: u64, - /// GRPC address of the validator node application - pub grpc_address: Option, -} - -impl ValidatorNodeConfig { - pub fn set_base_path>(&mut self, base_path: P) { - if !self.identity_file.is_absolute() { - self.identity_file = base_path.as_ref().join(&self.identity_file); - } - if !self.tor_identity_file.is_absolute() { - self.tor_identity_file = base_path.as_ref().join(&self.tor_identity_file); - } - if !self.data_dir.is_absolute() { - self.data_dir = base_path.as_ref().join(&self.data_dir); - } - self.p2p.set_base_path(base_path); - } -} - -impl Default for ValidatorNodeConfig { - fn default() -> Self { - let p2p = P2pConfig { - datastore_path: PathBuf::from("peer_db/validator_node"), - ..Default::default() - }; - - Self { - override_from: None, - identity_file: PathBuf::from("validator_node_id.json"), - tor_identity_file: PathBuf::from("validator_node_tor_id.json"), - public_address: None, - phase_timeout: 30, - base_node_grpc_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 18142), - wallet_grpc_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 18143), - scan_for_assets: true, - new_asset_scanning_interval: 10, - assets_allow_list: None, - data_dir: PathBuf::from("data/validator_node"), - constitution_auto_accept: false, - constitution_management_confirmation_time: 20, - constitution_management_polling_interval: 120, - constitution_management_polling_interval_in_seconds: 60, - p2p, - grpc_address: Some("/ip4/127.0.0.1/tcp/18144".parse().unwrap()), - } - } -} - -impl SubConfigPath for ValidatorNodeConfig { - fn main_key_prefix() -> &'static str { - "validator_node" - } -} diff --git a/applications/tari_validator_node/src/contract_worker_manager.rs b/applications/tari_validator_node/src/contract_worker_manager.rs deleted file mode 100644 index 5fa2c59a877..00000000000 --- a/applications/tari_validator_node/src/contract_worker_manager.rs +++ /dev/null @@ -1,606 +0,0 @@ -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - collections::HashMap, - convert::{TryFrom, TryInto}, - sync::{atomic::AtomicBool, Arc}, - time::Duration, -}; - -use log::*; -use tari_common_types::types::{FixedHash, FixedHashSizeError}; -use tari_comms::{types::CommsPublicKey, NodeIdentity}; -use tari_comms_dht::Dht; -use tari_core::transactions::transaction_components::{ContractConstitution, OutputType}; -use tari_crypto::tari_utilities::{hex::Hex, message_format::MessageFormat, ByteArray}; -use tari_dan_core::{ - models::{AssetDefinition, BaseLayerMetadata, Committee}, - services::{ - AcceptanceManager, - BaseNodeClient, - ConcreteAcceptanceManager, - ConcreteAssetProcessor, - ConcreteCheckpointManager, - ConcreteCommitteeManager, - LoggingEventsPublisher, - MempoolServiceHandle, - NodeIdentitySigningService, - TariDanPayloadProcessor, - TariDanPayloadProvider, - }, - storage::{ - global::{ContractState, GlobalDb, GlobalDbMetadataKey}, - StorageError, - }, - workers::ConsensusWorker, - DigitalAssetError, -}; -use tari_dan_storage_sqlite::{ - global::{models::contract::NewContract, SqliteGlobalDbBackendAdapter}, - SqliteDbFactory, - SqliteStorageService, -}; -use tari_p2p::{comms_connector::SubscriptionFactory, tari_message::TariMessageType}; -use tari_service_framework::ServiceHandles; -use tari_shutdown::ShutdownSignal; -use tokio::{task, time}; - -use crate::{ - p2p::services::{ - inbound_connection_service::TariCommsInboundConnectionService, - outbound_connection_service::TariCommsOutboundService, - }, - DefaultServiceSpecification, - GrpcBaseNodeClient, - GrpcWalletClient, - TariCommsValidatorNodeClientFactory, - ValidatorNodeConfig, -}; - -const LOG_TARGET: &str = "tari::validator_node::asset_worker_manager"; - -pub struct ContractWorkerManager { - config: ValidatorNodeConfig, - global_db: GlobalDb, - last_scanned_height: u64, - last_scanned_hash: Option, - base_node_client: GrpcBaseNodeClient, - acceptance_manager: ConcreteAcceptanceManager, - identity: Arc, - active_workers: HashMap>, - mempool: MempoolServiceHandle, - handles: ServiceHandles, - subscription_factory: SubscriptionFactory, - db_factory: SqliteDbFactory, - shutdown: ShutdownSignal, -} - -macro_rules! some_or_continue { - ($expr:expr) => { - match $expr { - Some(x) => x, - None => continue, - } - }; -} - -impl ContractWorkerManager { - pub fn new( - config: ValidatorNodeConfig, - identity: Arc, - global_db: GlobalDb, - base_node_client: GrpcBaseNodeClient, - acceptance_manager: ConcreteAcceptanceManager, - mempool: MempoolServiceHandle, - handles: ServiceHandles, - subscription_factory: SubscriptionFactory, - db_factory: SqliteDbFactory, - shutdown: ShutdownSignal, - ) -> Self { - Self { - config, - global_db, - last_scanned_height: 0, - last_scanned_hash: None, - base_node_client, - acceptance_manager, - identity, - mempool, - handles, - subscription_factory, - db_factory, - active_workers: HashMap::new(), - shutdown, - } - } - - pub async fn start(mut self) -> Result<(), WorkerManagerError> { - self.load_initial_state()?; - - info!( - target: LOG_TARGET, - "ℹ️ constitution_auto_accept is {}", self.config.constitution_auto_accept - ); - - if !self.config.scan_for_assets { - info!( - target: LOG_TARGET, - "⚠️ scan_for_assets turned OFF. Contract scanner is shutting down." - ); - self.shutdown.await; - return Ok(()); - } - - self.start_active_contracts().await?; - - loop { - // TODO: Get statuses of Accepted contracts to see if quorum is met if quorum is met, start the chain and - // create a checkpoint - - let tip = self.base_node_client.get_tip_info().await?; - let new_contracts = self.scan_for_new_contracts(&tip).await?; - - if !new_contracts.is_empty() { - if self.config.constitution_auto_accept { - info!( - target: LOG_TARGET, - "ℹ️ Auto accepting {} new contract(s).", - new_contracts.len() - ); - self.accept_contracts(new_contracts).await?; - } else { - info!( - target: LOG_TARGET, - "ℹ️ Auto accept is OFF. {} new contract(s) will require manual acceptance.", - new_contracts.len() - ); - } - } - - self.validate_contract_activity(&tip).await?; - - self.set_last_scanned_block(&tip)?; - tokio::select! { - _ = time::sleep(Duration::from_secs(self.config.constitution_management_polling_interval_in_seconds)) => {}, - _ = &mut self.shutdown => break - } - } - - Ok(()) - } - - async fn validate_contract_activity(&mut self, tip: &BaseLayerMetadata) -> Result<(), WorkerManagerError> { - let active_contracts = self.global_db.get_contracts_with_state(ContractState::Active)?; - - for contract in active_contracts { - let contract_id = FixedHash::try_from(contract.contract_id)?; - info!("Validating contract={} activity", contract_id.to_hex()); - - if let Some(checkpoint) = self.scan_for_last_checkpoint(tip, &contract_id).await? { - let constitution = ContractConstitution::from_binary(&*contract.constitution).map_err(|error| { - WorkerManagerError::DataCorruption { - details: error.to_string(), - } - })?; - - if tip.height_of_longest_chain > - checkpoint.mined_height + constitution.checkpoint_params.abandoned_interval - { - self.global_db - .update_contract_state(contract_id, ContractState::Abandoned)?; - - info!( - target: LOG_TARGET, - "Contract={} has missed checkpoints and has been marked Abandoned", - contract_id.to_hex() - ); - } - } - } - - Ok(()) - } - - async fn start_active_contracts(&mut self) -> Result<(), WorkerManagerError> { - // Abandoned contracts can be revived by the VNC so they should continue to monitor them - let mut active_contracts = self.global_db.get_contracts_with_state(ContractState::Active)?; - active_contracts.append(&mut self.global_db.get_contracts_with_state(ContractState::Abandoned)?); - info!( - target: LOG_TARGET, - "ℹ️ ready to work on {} active contract(s)", - active_contracts.len() - ); - - for contract in active_contracts { - let contract_id = FixedHash::try_from(contract.contract_id)?; - - let constitution = ContractConstitution::from_binary(&*contract.constitution).map_err(|error| { - WorkerManagerError::DataCorruption { - details: error.to_string(), - } - })?; - - let kill = self.spawn_asset_worker(contract_id, &constitution); - self.active_workers.insert(contract_id, kill); - } - - Ok(()) - } - - async fn accept_contracts(&mut self, new_contracts: Vec) -> Result<(), WorkerManagerError> { - for contract in new_contracts { - info!( - target: LOG_TARGET, - "ℹ️ Posting acceptance transaction for contract {}", contract.contract_id - ); - self.post_contract_acceptance(&contract).await?; - - // TODO: This should only be set to Accepted but we don't have steps for checking quorums yet. - self.global_db - .update_contract_state(contract.contract_id, ContractState::Active)?; - - // TODO: Scan for acceptances and once enough are present, start working on the contract - // for now, we start working immediately. - let kill = self.spawn_asset_worker(contract.contract_id, &contract.constitution); - self.active_workers.insert(contract.contract_id, kill); - } - - Ok(()) - } - - fn load_initial_state(&mut self) -> Result<(), WorkerManagerError> { - self.last_scanned_hash = self - .global_db - .get_data(GlobalDbMetadataKey::LastScannedConstitutionHash)? - .map(TryInto::try_into) - .transpose()?; - self.last_scanned_height = self - .global_db - .get_data(GlobalDbMetadataKey::LastScannedConstitutionHeight)? - .map(|data| { - if data.len() == 8 { - let mut buf = [0u8; 8]; - buf.copy_from_slice(&data); - Ok(u64::from_le_bytes(buf)) - } else { - Err(WorkerManagerError::DataCorruption { - details: "LastScannedConstitutionHeight did not contain little-endian u64 data".to_string(), - }) - } - }) - .transpose()? - .unwrap_or(0); - Ok(()) - } - - async fn scan_for_last_checkpoint( - &mut self, - tip: &BaseLayerMetadata, - contract_id: &FixedHash, - ) -> Result, WorkerManagerError> { - info!( - target: LOG_TARGET, - "Scanning base layer (tip: {}) for last checkpoint of contract={}", - tip.height_of_longest_chain, - contract_id - ); - - let outputs = self - .base_node_client - .get_current_contract_outputs( - tip.height_of_longest_chain, - *contract_id, - OutputType::ContractCheckpoint, - ) - .await?; - - let mut outputs = outputs - .iter() - .map({ - |output| Checkpoint { - mined_height: output.mined_height, - } - }) - .collect::>(); - outputs.sort_by(|l, r| l.mined_height.partial_cmp(&r.mined_height).unwrap()); - - Ok(outputs.pop()) - } - - async fn scan_for_new_contracts( - &mut self, - tip: &BaseLayerMetadata, - ) -> Result, WorkerManagerError> { - info!( - target: LOG_TARGET, - "🔍 Scanning base layer (tip: {}) for new assets", tip.height_of_longest_chain - ); - - let outputs = self - .base_node_client - .get_constitutions(self.last_scanned_hash, self.identity.public_key()) - .await?; - - let mut new_contracts = vec![]; - for utxo in outputs { - let output = some_or_continue!(utxo.output.into_unpruned_output()); - let mined_height = utxo.mined_height; - let sidechain_features = some_or_continue!(output.features.sidechain_features); - let contract_id = sidechain_features.contract_id; - let constitution = some_or_continue!(sidechain_features.constitution); - if !constitution.validator_committee.contains(self.identity.public_key()) { - warn!( - target: LOG_TARGET, - "Base node returned constitution for contract {} that this node is not part of", contract_id - ); - continue; - } - - if self.active_workers.contains_key(&contract_id) { - warn!(target: LOG_TARGET, "Contract {} is already in active list", contract_id); - continue; - } - - if constitution.acceptance_requirements.acceptance_period_expiry < tip.height_of_longest_chain { - warn!( - target: LOG_TARGET, - "Constitution acceptance period for contract {} has expired. Expires at {} but tip is {}", - contract_id, - constitution.acceptance_requirements.acceptance_period_expiry, - tip.height_of_longest_chain - ); - - let contract = ActiveContract { - constitution, - contract_id, - mined_height, - }; - - match self.global_db.save_contract(contract.into(), ContractState::Expired) { - Ok(_) => info!( - target: LOG_TARGET, - "Saving expired contract data id={}", - contract_id.to_hex() - ), - Err(error) => error!( - target: LOG_TARGET, - "Couldn't save expired contract data id={} received error={}", - contract_id.to_hex(), - error.to_string() - ), - } - - continue; - } - - let contract = ActiveContract { - constitution, - contract_id, - mined_height, - }; - - match self - .global_db - .save_contract(contract.clone().into(), ContractState::Pending) - { - Ok(_) => info!( - target: LOG_TARGET, - "Saving contract data id={}", - contract.contract_id.to_hex() - ), - Err(error) => error!( - target: LOG_TARGET, - "Couldn't save contract data id={} received error={}", - contract.contract_id.to_hex(), - error.to_string() - ), - } - - new_contracts.push(contract); - } - - info!(target: LOG_TARGET, "{} new contract(s) found", new_contracts.len()); - - Ok(new_contracts) - } - - fn spawn_asset_worker(&self, contract_id: FixedHash, constitution: &ContractConstitution) -> Arc { - info!(target: LOG_TARGET, "🚀 starting work on contract {}", contract_id); - let node_identity = self.identity.clone(); - let mempool = self.mempool.clone(); - let handles = self.handles.clone(); - let subscription_factory = self.subscription_factory.clone(); - let db_factory = self.db_factory.clone(); - let shutdown = self.shutdown.clone(); - // Create a kill signal for each asset - let kill = Arc::new(AtomicBool::new(false)); - let dan_config = self.config.clone(); - task::spawn(Self::start_asset_worker( - AssetDefinition { - contract_id, - committee: constitution - .validator_committee - .members() - .iter() - .map(|pk| pk.to_hex()) - .collect(), - phase_timeout: self.config.phase_timeout, - base_layer_confirmation_time: 0, - checkpoint_unique_id: vec![], - initial_state: Default::default(), - template_parameters: vec![], - wasm_modules: vec![], - wasm_functions: vec![], - flow_functions: vec![], - }, - node_identity, - mempool, - handles, - subscription_factory, - shutdown, - dan_config, - db_factory, - kill.clone(), - )); - kill - } - - async fn start_asset_worker( - asset_definition: AssetDefinition, - node_identity: Arc, - mempool_service: MempoolServiceHandle, - handles: ServiceHandles, - subscription_factory: SubscriptionFactory, - shutdown: ShutdownSignal, - config: ValidatorNodeConfig, - db_factory: SqliteDbFactory, - kill: Arc, - ) -> Result<(), DigitalAssetError> { - let timeout = Duration::from_secs(asset_definition.phase_timeout); - let committee = asset_definition - .committee - .iter() - .map(|s| CommsPublicKey::from_hex(s).map_err(|_| DigitalAssetError::InvalidCommitteePublicKeyHex)) - .collect::, _>>()?; - - let committee = Committee::new(committee); - let committee_service = ConcreteCommitteeManager::new(committee); - - let payload_provider = TariDanPayloadProvider::new(mempool_service.clone()); - - let events_publisher = LoggingEventsPublisher::default(); - let signing_service = NodeIdentitySigningService::new(node_identity.clone()); - - // let _backend = LmdbAssetStore::initialize(data_dir.join("asset_data"), Default::default()) - // .map_err(|err| ExitCodes::DatabaseError(err.to_string()))?; - // let data_store = AssetDataStore::new(backend); - let asset_processor = ConcreteAssetProcessor::default(); - - let payload_processor = TariDanPayloadProcessor::new(asset_processor); - let mut inbound = TariCommsInboundConnectionService::new(asset_definition.contract_id); - let receiver = inbound.get_receiver(); - - let loopback = inbound.clone_sender(); - let shutdown_2 = shutdown.clone(); - task::spawn(async move { - let topic_subscription = - subscription_factory.get_subscription(TariMessageType::DanConsensusMessage, "HotStuffMessages"); - inbound.run(shutdown_2, topic_subscription).await - }); - let dht = handles.expect_handle::(); - let outbound = TariCommsOutboundService::new(dht.outbound_requester(), loopback, asset_definition.contract_id); - let base_node_client = GrpcBaseNodeClient::new(config.base_node_grpc_address); - let chain_storage = SqliteStorageService {}; - let wallet_client = GrpcWalletClient::new(config.wallet_grpc_address); - let checkpoint_manager = ConcreteCheckpointManager::new(asset_definition.clone(), wallet_client); - let validator_node_client_factory = TariCommsValidatorNodeClientFactory::new(dht.dht_requester()); - let mut consensus_worker = ConsensusWorker::::new( - receiver, - outbound, - committee_service, - node_identity.public_key().clone(), - payload_provider, - events_publisher, - signing_service, - payload_processor, - asset_definition, - base_node_client, - timeout, - db_factory, - chain_storage, - checkpoint_manager, - validator_node_client_factory, - ); - - if let Err(err) = consensus_worker.run(shutdown, None, kill).await { - error!(target: LOG_TARGET, "Consensus worker failed with error: {}", err); - return Err(err); - } - - Ok(()) - } - - async fn post_contract_acceptance(&mut self, contract: &ActiveContract) -> Result<(), WorkerManagerError> { - let mut acceptance_manager = self.acceptance_manager.clone(); - - let tx_id = acceptance_manager - .publish_constitution_acceptance(&self.identity, &contract.contract_id) - .await?; - info!( - target: LOG_TARGET, - "Contract {} acceptance submitted with id={}", contract.contract_id, tx_id - ); - Ok(()) - } - - fn set_last_scanned_block(&mut self, tip: &BaseLayerMetadata) -> Result<(), WorkerManagerError> { - self.global_db.set_data( - GlobalDbMetadataKey::LastScannedConstitutionHash, - tip.tip_hash.as_bytes(), - )?; - self.global_db.set_data( - GlobalDbMetadataKey::LastScannedConstitutionHeight, - &tip.height_of_longest_chain.to_le_bytes(), - )?; - self.last_scanned_hash = Some(tip.tip_hash); - self.last_scanned_height = tip.height_of_longest_chain; - Ok(()) - } -} - -#[derive(Debug, thiserror::Error)] -pub enum WorkerManagerError { - #[error(transparent)] - FixedHashSizeError(#[from] FixedHashSizeError), - #[error("Storage error: {0}")] - StorageError(#[from] StorageError), - #[error("DigitalAsset error: {0}")] - DigitalAssetError(#[from] DigitalAssetError), - // TODO: remove dead_code - #[allow(dead_code)] - #[error("Data corruption: {details}")] - DataCorruption { details: String }, -} - -#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)] -struct Checkpoint { - pub mined_height: u64, -} - -#[derive(Debug, Clone)] -struct ActiveContract { - pub constitution: ContractConstitution, - pub contract_id: FixedHash, - pub mined_height: u64, -} - -impl From for NewContract { - fn from(value: ActiveContract) -> Self { - Self { - height: value.mined_height as i64, - contract_id: value.contract_id.to_vec(), - constitution: value.constitution.to_binary().unwrap(), - state: 0, - } - } -} diff --git a/applications/tari_validator_node/src/dan_node.rs b/applications/tari_validator_node/src/dan_node.rs deleted file mode 100644 index ed156da7992..00000000000 --- a/applications/tari_validator_node/src/dan_node.rs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::sync::Arc; - -use tari_common::exit_codes::{ExitCode, ExitError}; -use tari_comms::NodeIdentity; -use tari_dan_core::{ - services::{ConcreteAcceptanceManager, MempoolServiceHandle}, - storage::global::GlobalDb, -}; -use tari_dan_storage_sqlite::{global::SqliteGlobalDbBackendAdapter, SqliteDbFactory}; -use tari_p2p::comms_connector::SubscriptionFactory; -use tari_service_framework::ServiceHandles; -use tari_shutdown::ShutdownSignal; - -use crate::{ - config::ValidatorNodeConfig, - contract_worker_manager::ContractWorkerManager, - grpc::services::{base_node_client::GrpcBaseNodeClient, wallet_client::GrpcWalletClient}, -}; - -const _LOG_TARGET: &str = "tari::validator_node::app"; - -#[derive(Clone)] -pub struct DanNode { - config: ValidatorNodeConfig, - identity: Arc, - global_db: GlobalDb, -} - -impl DanNode { - pub fn new( - config: ValidatorNodeConfig, - identity: Arc, - global_db: GlobalDb, - ) -> Self { - Self { - config, - identity, - global_db, - } - } - - pub async fn start( - &self, - shutdown: ShutdownSignal, - mempool_service: MempoolServiceHandle, - db_factory: SqliteDbFactory, - handles: ServiceHandles, - subscription_factory: SubscriptionFactory, - ) -> Result<(), ExitError> { - let base_node_client = GrpcBaseNodeClient::new(self.config.base_node_grpc_address); - let wallet_client = GrpcWalletClient::new(self.config.wallet_grpc_address); - let acceptance_manager = ConcreteAcceptanceManager::new(wallet_client, base_node_client.clone()); - let workers = ContractWorkerManager::new( - self.config.clone(), - self.identity.clone(), - self.global_db.clone(), - base_node_client, - acceptance_manager, - mempool_service, - handles, - subscription_factory, - db_factory, - shutdown.clone(), - ); - - workers - .start() - .await - .map_err(|err| ExitError::new(ExitCode::DigitalAssetError, err))?; - - Ok(()) - } -} diff --git a/applications/tari_validator_node/src/default_service_specification.rs b/applications/tari_validator_node/src/default_service_specification.rs deleted file mode 100644 index 76caf5f94eb..00000000000 --- a/applications/tari_validator_node/src/default_service_specification.rs +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_common_types::types::PublicKey; -use tari_dan_core::{ - models::{domain_events::ConsensusWorkerDomainEvent, TariDanPayload}, - services::{ - ConcreteAcceptanceManager, - ConcreteAssetProcessor, - ConcreteAssetProxy, - ConcreteCheckpointManager, - ConcreteCommitteeManager, - LoggingEventsPublisher, - MempoolServiceHandle, - NodeIdentitySigningService, - ServiceSpecification, - TariDanPayloadProcessor, - TariDanPayloadProvider, - }, -}; -use tari_dan_storage_sqlite::{ - global::SqliteGlobalDbBackendAdapter, - SqliteChainBackendAdapter, - SqliteDbFactory, - SqliteStateDbBackendAdapter, - SqliteStorageService, -}; - -use crate::{ - grpc::services::{base_node_client::GrpcBaseNodeClient, wallet_client::GrpcWalletClient}, - p2p::services::{ - inbound_connection_service::TariCommsInboundReceiverHandle, - outbound_connection_service::TariCommsOutboundService, - rpc_client::TariCommsValidatorNodeClientFactory, - }, -}; - -#[derive(Default, Clone)] -pub struct DefaultServiceSpecification; - -impl ServiceSpecification for DefaultServiceSpecification { - type AcceptanceManager = ConcreteAcceptanceManager; - type Addr = PublicKey; - type AssetProcessor = ConcreteAssetProcessor; - type AssetProxy = ConcreteAssetProxy; - type BaseNodeClient = GrpcBaseNodeClient; - type ChainDbBackendAdapter = SqliteChainBackendAdapter; - type ChainStorageService = SqliteStorageService; - type CheckpointManager = ConcreteCheckpointManager; - type CommitteeManager = ConcreteCommitteeManager; - type DbFactory = SqliteDbFactory; - type EventsPublisher = LoggingEventsPublisher; - type GlobalDbAdapter = SqliteGlobalDbBackendAdapter; - type InboundConnectionService = TariCommsInboundReceiverHandle; - type MempoolService = MempoolServiceHandle; - type OutboundService = TariCommsOutboundService; - type Payload = TariDanPayload; - type PayloadProcessor = TariDanPayloadProcessor; - type PayloadProvider = TariDanPayloadProvider; - type SigningService = NodeIdentitySigningService; - type StateDbBackendAdapter = SqliteStateDbBackendAdapter; - type ValidatorNodeClientFactory = TariCommsValidatorNodeClientFactory; - type WalletClient = GrpcWalletClient; -} diff --git a/applications/tari_validator_node/src/grpc/conversions.rs b/applications/tari_validator_node/src/grpc/conversions.rs deleted file mode 100644 index 1f24e37b961..00000000000 --- a/applications/tari_validator_node/src/grpc/conversions.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -use tari_app_grpc::tari_rpc; -use tari_crypto::tari_utilities::ByteArray; -use tari_dan_core::models::SidechainMetadata; - -pub struct St(tari_rpc::SidechainMetadata); - -impl From for St { - fn from(source: SidechainMetadata) -> Self { - Self(tari_rpc::SidechainMetadata { - asset_public_key: source.asset_public_key().as_bytes().to_vec(), - committed_height: source.committed_height().into(), - committed_hash: source.committed_hash().as_bytes().to_vec(), - }) - } -} diff --git a/applications/tari_validator_node/src/grpc/mod.rs b/applications/tari_validator_node/src/grpc/mod.rs deleted file mode 100644 index 10ea203ea1e..00000000000 --- a/applications/tari_validator_node/src/grpc/mod.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -mod conversions; -pub mod services; -pub(crate) mod validator_node_grpc_server; diff --git a/applications/tari_validator_node/src/grpc/services/base_node_client.rs b/applications/tari_validator_node/src/grpc/services/base_node_client.rs deleted file mode 100644 index 62c437bb7e0..00000000000 --- a/applications/tari_validator_node/src/grpc/services/base_node_client.rs +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{convert::TryInto, net::SocketAddr}; - -use async_trait::async_trait; -use log::*; -use tari_app_grpc::tari_rpc as grpc; -use tari_common_types::types::{FixedHash, PublicKey}; -use tari_core::{ - chain_storage::{PrunedOutput, UtxoMinedInfo}, - transactions::transaction_components::OutputType, -}; -use tari_crypto::tari_utilities::ByteArray; -use tari_dan_core::{ - models::{BaseLayerMetadata, BaseLayerOutput}, - services::BaseNodeClient, - DigitalAssetError, -}; - -const LOG_TARGET: &str = "tari::validator_node::app"; - -type Client = grpc::base_node_client::BaseNodeClient; - -#[derive(Clone)] -pub struct GrpcBaseNodeClient { - endpoint: SocketAddr, - client: Option, -} - -impl GrpcBaseNodeClient { - pub fn new(endpoint: SocketAddr) -> GrpcBaseNodeClient { - Self { endpoint, client: None } - } - - pub async fn connection(&mut self) -> Result<&mut Client, DigitalAssetError> { - if self.client.is_none() { - let url = format!("http://{}", self.endpoint); - let inner = Client::connect(url).await?; - self.client = Some(inner); - } - self.client - .as_mut() - .ok_or_else(|| DigitalAssetError::FatalError("no connection".into())) - } -} -#[async_trait] -impl BaseNodeClient for GrpcBaseNodeClient { - async fn get_tip_info(&mut self) -> Result { - let inner = self.connection().await?; - let request = grpc::Empty {}; - let result = inner.get_tip_info(request).await?.into_inner(); - let metadata = result - .metadata - .ok_or_else(|| DigitalAssetError::InvalidPeerMessage("Base node returned no metadata".to_string()))?; - Ok(BaseLayerMetadata { - height_of_longest_chain: metadata.height_of_longest_chain, - tip_hash: metadata.best_block.try_into().map_err(|_| { - DigitalAssetError::InvalidPeerMessage("best_block was not a valid fixed hash".to_string()) - })?, - }) - } - - async fn get_current_contract_outputs( - &mut self, - _height: u64, - contract_id: FixedHash, - output_type: OutputType, - ) -> Result, DigitalAssetError> { - let inner = self.connection().await?; - let request = grpc::GetCurrentContractOutputsRequest { - contract_id: contract_id.to_vec(), - output_type: u32::from(output_type.as_byte()), - }; - let resp = match inner.get_current_contract_outputs(request).await { - Ok(resp) => { - debug!( - target: LOG_TARGET, - "get_current_contract_outputs: {} output(s) found for contract {}: {:?}", - resp.get_ref().outputs.len(), - contract_id, - resp - ); - resp.into_inner() - }, - Err(err) => return Err(err.into()), - }; - - let mut outputs = vec![]; - for mined_info in resp.outputs { - let output = mined_info - .output - .map(TryInto::try_into) - .transpose() - .map_err(DigitalAssetError::ConversionError)? - .ok_or_else(|| DigitalAssetError::InvalidPeerMessage("Mined info contained no output".to_string()))?; - - outputs.push(UtxoMinedInfo { - output: PrunedOutput::NotPruned { output }, - mmr_position: mined_info.mmr_position, - mined_height: mined_info.mined_height, - header_hash: mined_info.header_hash, - mined_timestamp: mined_info.mined_timestamp, - }); - } - Ok(outputs) - } - - async fn get_constitutions( - &mut self, - start_block_hash: Option, - dan_node_public_key: &PublicKey, - ) -> Result, DigitalAssetError> { - let conn = self.connection().await?; - let request = grpc::GetConstitutionsRequest { - start_block_hash: start_block_hash.map(|h| h.to_vec()).unwrap_or_else(Vec::new), - dan_node_public_key: dan_node_public_key.as_bytes().to_vec(), - }; - let mut result = conn.get_constitutions(request).await?.into_inner(); - let mut outputs = vec![]; - while let Some(resp) = result.message().await? { - let output = resp - .output - .map(TryInto::try_into) - .transpose() - .map_err(DigitalAssetError::ConversionError)? - .ok_or_else(|| DigitalAssetError::InvalidPeerMessage("Mined info contained no output".to_string()))?; - - outputs.push(UtxoMinedInfo { - output: PrunedOutput::NotPruned { output }, - mmr_position: resp.mmr_position, - mined_height: resp.mined_height, - header_hash: resp.header_hash, - mined_timestamp: resp.mined_timestamp, - }); - } - Ok(outputs) - } - - async fn check_if_in_committee( - &mut self, - _asset_public_key: PublicKey, - _dan_node_public_key: PublicKey, - ) -> Result<(bool, u64), DigitalAssetError> { - unimplemented!() - // let tip = self.get_tip_info().await?; - // if let Some(checkpoint) = self - // .get_current_checkpoint( - // tip.height_of_longest_chain, - // asset_public_key, - // COMMITTEE_DEFINITION_ID.into(), - // ) - // .await? - // { - // if let Some(committee) = checkpoint.get_side_chain_committee() { - // if committee.contains(&dan_node_public_key) { - // // We know it's part of the committee at this height - // // TODO: there could be a scenario where it was not part of the committee for one block (or more, - // // depends on the config) - // Ok((true, checkpoint.height)) - // } else { - // // We know it's no longer part of the committee at this height - // // TODO: if the committee changes twice in short period of time, this will cause some glitches - // Ok((false, checkpoint.height)) - // } - // } else { - // Ok((false, 0)) - // } - // } else { - // Ok((false, 0)) - // } - } - - async fn get_asset_registration( - &mut self, - asset_public_key: PublicKey, - ) -> Result, DigitalAssetError> { - let inner = self.connection().await?; - - let req = grpc::GetAssetMetadataRequest { - asset_public_key: asset_public_key.to_vec(), - }; - let output = inner.get_asset_metadata(req).await.unwrap().into_inner(); - - let mined_height = output.mined_height; - let output = output - .features - .map(|features| match features.try_into() { - Ok(f) => Ok(BaseLayerOutput { - features: f, - height: mined_height, - }), - Err(e) => Err(DigitalAssetError::ConversionError(e)), - }) - .transpose()?; - - Ok(output) - } -} diff --git a/applications/tari_validator_node/src/grpc/services/mod.rs b/applications/tari_validator_node/src/grpc/services/mod.rs deleted file mode 100644 index c1e3cc3b037..00000000000 --- a/applications/tari_validator_node/src/grpc/services/mod.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub mod base_node_client; -pub mod wallet_client; diff --git a/applications/tari_validator_node/src/grpc/services/wallet_client.rs b/applications/tari_validator_node/src/grpc/services/wallet_client.rs deleted file mode 100644 index 7fac77d4452..00000000000 --- a/applications/tari_validator_node/src/grpc/services/wallet_client.rs +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::net::SocketAddr; - -use async_trait::async_trait; -use tari_app_grpc::{ - tari_rpc as grpc, - tari_rpc::{ - CreateFollowOnAssetCheckpointRequest, - CreateInitialAssetCheckpointRequest, - SubmitContractAcceptanceRequest, - SubmitContractUpdateProposalAcceptanceRequest, - }, -}; -use tari_common_types::types::{FixedHash, PublicKey, Signature}; -use tari_core::transactions::transaction_components::SignerSignature; -use tari_crypto::tari_utilities::ByteArray; -use tari_dan_core::{services::WalletClient, DigitalAssetError}; -use tari_dan_engine::state::models::StateRoot; - -const _LOG_TARGET: &str = "tari::dan::wallet_grpc"; - -type Inner = grpc::wallet_client::WalletClient; - -#[derive(Clone)] -pub struct GrpcWalletClient { - endpoint: SocketAddr, - inner: Option, -} - -impl GrpcWalletClient { - pub fn new(endpoint: SocketAddr) -> GrpcWalletClient { - Self { endpoint, inner: None } - } - - pub async fn connection(&mut self) -> Result<&mut Inner, DigitalAssetError> { - if self.inner.is_none() { - let url = format!("http://{}", self.endpoint); - let inner = Inner::connect(url).await?; - self.inner = Some(inner); - } - self.inner - .as_mut() - .ok_or_else(|| DigitalAssetError::FatalError("no connection".into())) - } -} - -#[async_trait] -impl WalletClient for GrpcWalletClient { - async fn create_new_checkpoint( - &mut self, - contract_id: &FixedHash, - state_root: &StateRoot, - checkpoint_number: u64, - checkpoint_signatures: &[SignerSignature], - ) -> Result<(), DigitalAssetError> { - let inner = self.connection().await?; - let committee_signatures = grpc::CommitteeSignatures { - signatures: checkpoint_signatures.iter().map(Into::into).collect(), - }; - - if checkpoint_number == 0 { - let request = CreateInitialAssetCheckpointRequest { - contract_id: contract_id.to_vec(), - merkle_root: state_root.as_bytes().to_vec(), - committee_signatures: Some(committee_signatures), - }; - - let _res = inner - .create_initial_asset_checkpoint(request) - .await - .map_err(|e| DigitalAssetError::FatalError(format!("Could not create checkpoint:{}", e)))?; - } else { - let request = CreateFollowOnAssetCheckpointRequest { - checkpoint_number, - contract_id: contract_id.to_vec(), - merkle_root: state_root.as_bytes().to_vec(), - committee_signatures: Some(committee_signatures), - }; - - let _res = inner - .create_follow_on_asset_checkpoint(request) - .await - .map_err(|e| DigitalAssetError::FatalError(format!("Could not create checkpoint:{}", e)))?; - } - - Ok(()) - } - - async fn submit_contract_acceptance( - &mut self, - contract_id: &FixedHash, - validator_node_public_key: &PublicKey, - signature: &Signature, - ) -> Result { - let inner = self.connection().await?; - - let request = SubmitContractAcceptanceRequest { - contract_id: contract_id.as_bytes().to_vec(), - validator_node_public_key: validator_node_public_key.as_bytes().to_vec(), - signature: Some((*signature).clone().into()), - }; - - let res = inner - .submit_contract_acceptance(request) - .await - .map_err(|e| DigitalAssetError::FatalError(format!("Could not submit contract acceptance: {}", e)))?; - - Ok(res.into_inner().tx_id) - } - - async fn submit_contract_update_proposal_acceptance( - &mut self, - contract_id: &FixedHash, - proposal_id: u64, - validator_node_public_key: &PublicKey, - signature: &Signature, - ) -> Result { - let inner = self.connection().await?; - - let request = SubmitContractUpdateProposalAcceptanceRequest { - contract_id: contract_id.as_bytes().to_vec(), - proposal_id, - validator_node_public_key: validator_node_public_key.as_bytes().to_vec(), - signature: Some((*signature).clone().into()), - }; - - let res = inner - .submit_contract_update_proposal_acceptance(request) - .await - .map_err(|e| { - DigitalAssetError::FatalError(format!("Could not submit contract update proposal acceptance: {}", e)) - })?; - - Ok(res.into_inner().tx_id) - } -} diff --git a/applications/tari_validator_node/src/grpc/validator_node_grpc_server.rs b/applications/tari_validator_node/src/grpc/validator_node_grpc_server.rs deleted file mode 100644 index dcb8d805e27..00000000000 --- a/applications/tari_validator_node/src/grpc/validator_node_grpc_server.rs +++ /dev/null @@ -1,276 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -use std::{ - convert::{TryFrom, TryInto}, - time::Duration, -}; - -use futures::channel::mpsc; -use tari_app_grpc::tari_rpc::{self as rpc, TransactionOutput}; -use tari_common_types::types::{FixedHash, PublicKey}; -use tari_comms::NodeIdentity; -use tari_crypto::tari_utilities::ByteArray; -use tari_dan_core::{ - services::{AcceptanceManager, AssetProcessor, AssetProxy, ServiceSpecification}, - storage::DbFactory, -}; -use tari_dan_engine::instructions::Instruction; -use tokio::{task, time}; -use tonic::{Request, Response, Status}; - -const LOG_TARGET: &str = "tari::validator_node::grpc"; - -pub struct ValidatorNodeGrpcServer { - node_identity: NodeIdentity, - db_factory: TServiceSpecification::DbFactory, - asset_processor: TServiceSpecification::AssetProcessor, - asset_proxy: TServiceSpecification::AssetProxy, - acceptance_manager: TServiceSpecification::AcceptanceManager, -} - -impl ValidatorNodeGrpcServer { - pub fn new( - node_identity: NodeIdentity, - db_factory: TServiceSpecification::DbFactory, - asset_processor: TServiceSpecification::AssetProcessor, - asset_proxy: TServiceSpecification::AssetProxy, - acceptance_manager: TServiceSpecification::AcceptanceManager, - ) -> Self { - Self { - node_identity, - db_factory, - asset_processor, - asset_proxy, - acceptance_manager, - } - } -} - -#[tonic::async_trait] -impl rpc::validator_node_server::ValidatorNode - for ValidatorNodeGrpcServer -{ - type GetConstitutionRequestsStream = mpsc::Receiver>; - - async fn publish_contract_acceptance( - &self, - request: tonic::Request, - ) -> Result, tonic::Status> { - let mut acceptance_manager = self.acceptance_manager.clone(); - let request = request.into_inner(); - let contract_id = - FixedHash::try_from(request.contract_id).map_err(|err| tonic::Status::invalid_argument(err.to_string()))?; - - match acceptance_manager - .publish_constitution_acceptance(&self.node_identity, &contract_id) - .await - { - Ok(tx_id) => Ok(Response::new(rpc::PublishContractAcceptanceResponse { - tx_id, - status: "Accepted".to_string(), - })), - Err(err) => { - log::error!(target: LOG_TARGET, "publish_contract_acceptance: {}", err); - Ok(Response::new(rpc::PublishContractAcceptanceResponse { - status: "Errored".to_string(), - tx_id: 0_u64, - })) - }, - } - } - - async fn publish_contract_update_proposal_acceptance( - &self, - request: tonic::Request, - ) -> Result, tonic::Status> { - let mut acceptance_manager = self.acceptance_manager.clone(); - let request = request.into_inner(); - let contract_id = FixedHash::try_from(request.contract_id).unwrap_or_default(); - let proposal_id = request.proposal_id; - - match acceptance_manager - .publish_proposal_acceptance(&self.node_identity, &contract_id, proposal_id) - .await - { - Ok(tx_id) => Ok(Response::new(rpc::PublishContractUpdateProposalAcceptanceResponse { - tx_id, - status: "Accepted".to_string(), - })), - Err(_) => Ok(Response::new(rpc::PublishContractUpdateProposalAcceptanceResponse { - status: "Errored".to_string(), - tx_id: 0_u64, - })), - } - } - - async fn get_constitution_requests( - &self, - _request: tonic::Request, - ) -> Result, tonic::Status> { - let (mut _sender, receiver) = mpsc::channel(100); - task::spawn(async move { - let mut _test = 1u64; - loop { - let _ = time::sleep(Duration::from_secs(1)).await; - // if let Err(err) = sender.send(Ok(ContractConstitution { test })).await { - // info!(target: LOG_TARGET, "The request was aborted, {}", err); - // break; - // } - _test += 1; - } - }); - Ok(Response::new(receiver)) - } - - async fn get_identity( - &self, - _request: tonic::Request, - ) -> Result, tonic::Status> { - let response = rpc::GetIdentityResponse { - public_key: self.node_identity.public_key().to_vec(), - public_address: self.node_identity.public_address().to_string(), - node_id: self.node_identity.node_id().to_vec(), - }; - Ok(Response::new(response)) - } - - async fn get_token_data( - &self, - _request: tonic::Request, - ) -> Result, tonic::Status> { - Err(Status::internal("Oh noes")) - } - - async fn invoke_method( - &self, - request: Request, - ) -> Result, Status> { - let request = request.into_inner(); - let contract_id = request - .contract_id - .try_into() - .map_err(|_err| Status::invalid_argument("contract_id was not valid"))?; - - match self - .asset_proxy - .invoke_method( - &contract_id, - request - .template_id - .try_into() - .map_err(|_| Status::invalid_argument("invalid template_id"))?, - request.method.clone(), - request.args.clone(), - PublicKey::from_bytes(&request.sender).map_err(|_| Status::invalid_argument("invalid sender"))?, - ) - .await - { - Ok(_) => Ok(Response::new(rpc::InvokeMethodResponse { - status: "Accepted".to_string(), - result: vec![], - })), - Err(_) => Ok(Response::new(rpc::InvokeMethodResponse { - status: "Errored".to_string(), - result: vec![], - })), - } - } - - async fn get_metadata( - &self, - request: Request, - ) -> Result, Status> { - println!("{:?}", request); - // let db = self.db_factory.create(); - todo!() - // let mut tx = db.new_unit_of_work(); - // let metadata = db.metadata.read(&mut tx); - // // .map_err(|e| Status::internal(format!("Could not read metadata from storage:{}", e)))?; - // Ok(Response::new(rpc::GetMetadataResponse { - // sidechains: vec![metadata.into()], - // })) - } - - async fn invoke_read_method( - &self, - request: Request, - ) -> Result, Status> { - println!("invoke_read_method grpc call"); - println!("{:?}", request); - let request = request.into_inner(); - let contract_id = request - .contract_id - .try_into() - .map_err(|err| Status::invalid_argument(format!("Contract ID was not valid: {}", err)))?; - let template_id = request - .template_id - .try_into() - .map_err(|_| Status::invalid_argument("Invalid template_id"))?; - if let Some(state) = self - .db_factory - .get_state_db(&contract_id) - .map_err(|e| Status::internal(format!("Could not create state db: {}", e)))? - { - let state_db_reader = state.reader(); - let instruction = Instruction::new( - template_id, - request.method, - request.args, - PublicKey::from_bytes(&request.sender).map_err(|_| Status::invalid_argument("invalid sender"))?, - ); - let response_bytes = self - .asset_processor - .invoke_read_method(&instruction, &state_db_reader) - .map_err(|e| Status::internal(format!("Could not invoke read method: {}", e)))?; - Ok(Response::new(rpc::InvokeReadMethodResponse { - result: response_bytes.unwrap_or_default(), - authority: Some(rpc::Authority { - node_public_key: vec![], - signature: vec![], - proxied_by: vec![], - }), - })) - } else { - // Forward to proxy - let response_bytes = self - .asset_proxy - .invoke_read_method( - &contract_id, - template_id, - request.method, - request.args, - PublicKey::from_bytes(&request.sender).map_err(|_| Status::invalid_argument("invalid sender"))?, - ) - .await - .map_err(|err| Status::internal(format!("Error calling proxied method:{}", err)))?; - // TODO: Populate authority - Ok(Response::new(rpc::InvokeReadMethodResponse { - result: response_bytes.unwrap_or_default(), - authority: Some(rpc::Authority { - node_public_key: vec![], - signature: vec![], - proxied_by: vec![], - }), - })) - } - } -} diff --git a/applications/tari_validator_node/src/main.rs b/applications/tari_validator_node/src/main.rs deleted file mode 100644 index 4a9770e4ffe..00000000000 --- a/applications/tari_validator_node/src/main.rs +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -mod asset; -mod cli; -mod cmd_args; -mod comms; -mod config; -mod contract_worker_manager; -mod dan_node; -mod default_service_specification; -mod grpc; -mod p2p; - -use std::{process, sync::Arc}; - -use clap::Parser; -use futures::FutureExt; -use log::*; -use tari_app_grpc::tari_rpc::validator_node_server::ValidatorNodeServer; -use tari_app_utilities::identity_management::setup_node_identity; -use tari_common::{ - exit_codes::{ExitCode, ExitError}, - initialize_logging, - load_configuration, -}; -use tari_comms::{ - multiaddr::Multiaddr, - peer_manager::PeerFeatures, - utils::multiaddr::multiaddr_to_socketaddr, - NodeIdentity, -}; -use tari_comms_dht::Dht; -use tari_dan_core::{ - services::{ - ConcreteAcceptanceManager, - ConcreteAssetProcessor, - ConcreteAssetProxy, - MempoolServiceHandle, - ServiceSpecification, - }, - storage::{global::GlobalDb, DbFactory}, -}; -use tari_dan_storage_sqlite::{global::SqliteGlobalDbBackendAdapter, SqliteDbFactory}; -use tari_p2p::comms_connector::SubscriptionFactory; -use tari_service_framework::ServiceHandles; -use tari_shutdown::{Shutdown, ShutdownSignal}; -use tokio::{runtime, runtime::Runtime, task}; -use tonic::transport::Server; - -use crate::{ - cli::Cli, - config::{ApplicationConfig, ValidatorNodeConfig}, - dan_node::DanNode, - default_service_specification::DefaultServiceSpecification, - grpc::{ - services::{base_node_client::GrpcBaseNodeClient, wallet_client::GrpcWalletClient}, - validator_node_grpc_server::ValidatorNodeGrpcServer, - }, - p2p::services::rpc_client::TariCommsValidatorNodeClientFactory, -}; - -const LOG_TARGET: &str = "tari::validator_node::app"; - -fn main() { - // Uncomment to enable tokio tracing via tokio-console - // console_subscriber::init(); - - if let Err(err) = main_inner() { - let exit_code = err.exit_code; - eprintln!("{:?}", err); - error!( - target: LOG_TARGET, - "Exiting with code ({}): {:?}", exit_code as i32, exit_code - ); - process::exit(exit_code as i32); - } -} - -fn main_inner() -> Result<(), ExitError> { - let cli = Cli::parse(); - let config_path = cli.common.config_path(); - let cfg = load_configuration(config_path, true, &cli)?; - initialize_logging( - &cli.common.log_config_path("validator"), - include_str!("../log4rs_sample.yml"), - )?; - let config = ApplicationConfig::load_from(&cfg)?; - println!("Starting validator node on network {}", config.network); - let runtime = build_runtime()?; - runtime.block_on(run_node(&config))?; - - Ok(()) -} - -async fn run_node(config: &ApplicationConfig) -> Result<(), ExitError> { - let shutdown = Shutdown::new(); - - let node_identity = setup_node_identity( - &config.validator_node.identity_file, - config.validator_node.public_address.as_ref(), - true, - PeerFeatures::NONE, - )?; - let db_factory = SqliteDbFactory::new(config.validator_node.data_dir.clone()); - let global_db = db_factory - .get_or_create_global_db() - .map_err(|e| ExitError::new(ExitCode::DatabaseError, e))?; - let mempool_service = MempoolServiceHandle::default(); - - info!( - target: LOG_TARGET, - "Node starting with pub key: {}, node_id: {}", - node_identity.public_key(), - node_identity.node_id() - ); - // fs::create_dir_all(&global.peer_db_path).map_err(|err| ExitError::new(ExitCode::ConfigError, err))?; - let (handles, subscription_factory) = comms::build_service_and_comms_stack( - config, - shutdown.to_signal(), - node_identity.clone(), - mempool_service.clone(), - db_factory.clone(), - ConcreteAssetProcessor::default(), - ) - .await?; - - let asset_processor = ConcreteAssetProcessor::default(); - let validator_node_client_factory = - TariCommsValidatorNodeClientFactory::new(handles.expect_handle::().dht_requester()); - let base_node_client = GrpcBaseNodeClient::new(config.validator_node.base_node_grpc_address); - let asset_proxy: ConcreteAssetProxy = ConcreteAssetProxy::new( - base_node_client.clone(), - validator_node_client_factory, - 5, - mempool_service.clone(), - db_factory.clone(), - ); - let wallet_client = GrpcWalletClient::new(config.validator_node.wallet_grpc_address); - let acceptance_manager = ConcreteAcceptanceManager::new(wallet_client.clone(), base_node_client); - let grpc_server: ValidatorNodeGrpcServer = ValidatorNodeGrpcServer::new( - node_identity.as_ref().clone(), - db_factory.clone(), - asset_processor, - asset_proxy, - acceptance_manager, - ); - - if let Some(address) = config.validator_node.grpc_address.clone() { - println!("Started GRPC server on {}", address); - task::spawn(run_grpc(grpc_server, address, shutdown.to_signal())); - } - - println!("🚀 Validator node started!"); - println!("{}", node_identity); - - run_dan_node( - shutdown.to_signal(), - config.validator_node.clone(), - mempool_service, - db_factory, - handles, - subscription_factory, - node_identity, - global_db, - ) - .await?; - - Ok(()) -} - -fn build_runtime() -> Result { - let mut builder = runtime::Builder::new_multi_thread(); - builder - .enable_all() - .build() - .map_err(|e| ExitError::new(ExitCode::UnknownError, e)) -} - -async fn run_dan_node( - shutdown_signal: ShutdownSignal, - config: ValidatorNodeConfig, - mempool_service: MempoolServiceHandle, - db_factory: SqliteDbFactory, - handles: ServiceHandles, - subscription_factory: SubscriptionFactory, - node_identity: Arc, - global_db: GlobalDb, -) -> Result<(), ExitError> { - let node = DanNode::new(config, node_identity, global_db); - node.start( - shutdown_signal, - mempool_service, - db_factory, - handles, - subscription_factory, - ) - .await -} - -async fn run_grpc( - grpc_server: ValidatorNodeGrpcServer, - grpc_address: Multiaddr, - shutdown_signal: ShutdownSignal, -) -> Result<(), anyhow::Error> { - println!("Starting GRPC on {}", grpc_address); - info!(target: LOG_TARGET, "Starting GRPC on {}", grpc_address); - - let grpc_address = multiaddr_to_socketaddr(&grpc_address)?; - - Server::builder() - .add_service(ValidatorNodeServer::new(grpc_server)) - .serve_with_shutdown(grpc_address, shutdown_signal.map(|_| ())) - .await - .map_err(|err| { - error!(target: LOG_TARGET, "GRPC encountered an error: {}", err); - err - })?; - - info!("Stopping GRPC"); - info!(target: LOG_TARGET, "Stopping GRPC"); - Ok(()) -} diff --git a/applications/tari_validator_node/src/monitoring.rs b/applications/tari_validator_node/src/monitoring.rs deleted file mode 100644 index fc7eb793e74..00000000000 --- a/applications/tari_validator_node/src/monitoring.rs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - collections::HashMap, - sync::{atomic::AtomicBool, Arc}, -}; - -use tari_common_types::types::PublicKey; -use tari_dan_core::models::AssetDefinition; - -use crate::asset::Asset; - -#[derive(Debug)] -#[allow(dead_code)] -pub struct Monitoring { - committee_management_confirmation_time: u64, - assets: HashMap, -} - -#[allow(dead_code)] -impl Monitoring { - pub fn new(committee_management_confirmation_time: u64) -> Self { - Self { - committee_management_confirmation_time, - assets: HashMap::new(), - } - } - - pub fn add_if_unmonitored(&mut self, asset: AssetDefinition) { - if !self.assets.contains_key(&asset.contract_id) { - self.assets.insert(asset.contract_id.clone(), Asset::new(asset)); - } - } - - pub fn add_state(&mut self, asset_public_key: PublicKey, height: u64, involvement: bool) { - // Add committee_management_confirmation_time to the mined height = effective height - self.assets - .get_mut(&asset_public_key) - .unwrap() - .add_state(height + self.committee_management_confirmation_time, involvement); - } - - pub fn update_height(&mut self, height: u64, start: Fstart) - where Fstart: Fn(AssetDefinition) -> Arc { - for proc in self.assets.values_mut() { - proc.update_height(height, start.clone()); - } - self.assets.retain(|_, proc| proc.should_monitor()) - } - - // Get active public keys, so we can check if we are still part of the committee - pub fn get_active_public_keys(&self) -> Vec<&PublicKey> { - self.assets - .keys() - .filter(|&a| self.assets.get(a).unwrap().is_committee_member()) - .collect() - } -} diff --git a/applications/tari_validator_node/src/p2p/mod.rs b/applications/tari_validator_node/src/p2p/mod.rs deleted file mode 100644 index ebe7216d3c6..00000000000 --- a/applications/tari_validator_node/src/p2p/mod.rs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub mod proto; - -mod rpc; -pub use rpc::create_validator_node_rpc_service; -pub mod services; diff --git a/applications/tari_validator_node/src/p2p/proto/conversions.rs b/applications/tari_validator_node/src/p2p/proto/conversions.rs deleted file mode 100644 index b966cbf80bc..00000000000 --- a/applications/tari_validator_node/src/p2p/proto/conversions.rs +++ /dev/null @@ -1,419 +0,0 @@ -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - borrow::Borrow, - convert::{TryFrom, TryInto}, -}; - -use tari_common_types::types::{PrivateKey, PublicKey, Signature}; -use tari_core::transactions::transaction_components::SignerSignature; -use tari_crypto::tari_utilities::ByteArray; -use tari_dan_common_types::TemplateId; -use tari_dan_core::models::{ - CheckpointData, - HotStuffMessage, - HotStuffMessageType, - HotStuffTreeNode, - InstructionSet, - Node, - QuorumCertificate, - SideChainBlock, - TariDanPayload, - TreeNodeHash, - ValidatorSignature, - ViewId, -}; -use tari_dan_engine::{ - instructions::Instruction, - state::{ - models::{KeyValue, StateOpLogEntry, StateRoot}, - DbStateOpLogEntry, - }, -}; - -use crate::p2p::proto; - -impl From> for proto::consensus::HotStuffMessage { - fn from(source: HotStuffMessage) -> Self { - Self { - message_type: i32::from(source.message_type().as_u8()), - node: source.node().map(|n| n.clone().into()), - justify: source.justify().map(|j| j.clone().into()), - partial_sig: source.partial_sig().map(|s| s.clone().into()), - view_number: source.view_number().as_u64(), - node_hash: source - .node_hash() - .copied() - .unwrap_or_else(TreeNodeHash::zero) - .as_bytes() - .to_vec(), - checkpoint_signature: source.checkpoint_signature().map(Into::into), - contract_id: source.contract_id().to_vec(), - } - } -} - -impl From> for proto::consensus::HotStuffTreeNode { - fn from(source: HotStuffTreeNode) -> Self { - Self { - parent: Vec::from(source.parent().as_bytes()), - payload: Some(source.payload().clone().into()), - height: source.height(), - state_root: Vec::from(source.state_root().as_bytes()), - } - } -} - -impl From for proto::consensus::QuorumCertificate { - fn from(source: QuorumCertificate) -> Self { - Self { - message_type: i32::from(source.message_type().as_u8()), - node_hash: Vec::from(source.node_hash().as_bytes()), - view_number: source.view_number().as_u64(), - signature: source.signature().map(|s| s.clone().into()), - } - } -} - -impl From for proto::consensus::ValidatorSignature { - fn from(_s: ValidatorSignature) -> Self { - Self {} - } -} - -impl From for proto::consensus::TariDanPayload { - fn from(source: TariDanPayload) -> Self { - let (instruction_set, checkpoint) = source.destruct(); - Self { - checkpoint: checkpoint.map(|c| c.into()), - instruction_set: Some(instruction_set.into()), - } - } -} - -impl From for proto::consensus::CheckpointData { - fn from(_source: CheckpointData) -> Self { - Self {} - } -} - -impl From<&Instruction> for proto::common::Instruction { - fn from(source: &Instruction) -> Self { - Self { - template_id: source.template_id() as u32, - method: source.method().to_string(), - args: Vec::from(source.args()), - sender: source.sender().to_vec(), - } - } -} - -impl TryFrom for HotStuffMessage { - type Error = String; - - fn try_from(value: proto::consensus::HotStuffMessage) -> Result { - let node_hash = if value.node_hash.is_empty() { - None - } else { - Some(TreeNodeHash::try_from(value.node_hash).map_err(|err| err.to_string())?) - }; - Ok(Self::new( - ViewId(value.view_number), - HotStuffMessageType::try_from(u8::try_from(value.message_type).unwrap())?, - value.justify.map(|j| j.try_into()).transpose()?, - value.node.map(|n| n.try_into()).transpose()?, - node_hash, - value.partial_sig.map(|p| p.try_into()).transpose()?, - value.checkpoint_signature.map(|p| p.try_into()).transpose()?, - value - .contract_id - .try_into() - .map_err(|err| format!("Not a valid contract ID:{}", err))?, - )) - } -} - -impl TryFrom for QuorumCertificate { - type Error = String; - - fn try_from(value: proto::consensus::QuorumCertificate) -> Result { - Ok(Self::new( - HotStuffMessageType::try_from(u8::try_from(value.message_type).unwrap())?, - ViewId(value.view_number), - TreeNodeHash::try_from(value.node_hash).map_err(|err| err.to_string())?, - value.signature.map(|s| s.try_into()).transpose()?, - )) - } -} - -impl TryFrom for HotStuffTreeNode { - type Error = String; - - fn try_from(value: proto::consensus::HotStuffTreeNode) -> Result { - if value.parent.is_empty() { - return Err("parent not provided".to_string()); - } - let state_root = value - .state_root - .try_into() - .map(StateRoot::new) - .map_err(|_| "Incorrect length for state_root")?; - Ok(Self::new( - TreeNodeHash::try_from(value.parent).map_err(|_| "Incorrect length for parent")?, - value - .payload - .map(|p| p.try_into()) - .transpose()? - .ok_or("payload not provided")?, - state_root, - value.height, - )) - } -} - -impl TryFrom for ValidatorSignature { - type Error = String; - - fn try_from(_value: proto::consensus::ValidatorSignature) -> Result { - Ok(Self {}) - } -} - -impl TryFrom for InstructionSet { - type Error = String; - - fn try_from(value: proto::common::InstructionSet) -> Result { - let instructions: Vec = value - .instructions - .into_iter() - .map(|i| i.try_into()) - .collect::>()?; - Ok(Self::from_vec(instructions)) - } -} - -impl From for proto::common::InstructionSet { - fn from(value: InstructionSet) -> Self { - Self { - instructions: value.instructions().iter().map(Into::into).collect(), - } - } -} - -impl TryFrom for Instruction { - type Error = String; - - fn try_from(value: proto::common::Instruction) -> Result { - let template_id = TemplateId::try_from(value.template_id)?; - Ok(Self::new( - template_id, - value.method, - value.args, - PublicKey::from_bytes(&value.sender).map_err(|e| format!("Invalid public key:{}", e))?, - )) - } -} - -impl TryFrom for TariDanPayload { - type Error = String; - - fn try_from(value: proto::consensus::TariDanPayload) -> Result { - let instruction_set = value - .instruction_set - .ok_or_else(|| "Instructions were not present".to_string())? - .try_into()?; - let checkpoint = value.checkpoint.map(|c| c.try_into()).transpose()?; - - Ok(Self::new(instruction_set, checkpoint)) - } -} - -impl TryFrom for CheckpointData { - type Error = String; - - fn try_from(_value: proto::consensus::CheckpointData) -> Result { - Ok(Self::default()) - } -} - -impl From for proto::common::SideChainBlock { - fn from(block: SideChainBlock) -> Self { - let (node, instructions) = block.destruct(); - Self { - node: Some(node.into()), - instructions: Some(instructions.into()), - } - } -} - -impl TryFrom for SideChainBlock { - type Error = String; - - fn try_from(block: proto::common::SideChainBlock) -> Result { - let node = block - .node - .map(TryInto::try_into) - .ok_or_else(|| "No node provided in sidechain block".to_string())??; - let instructions = block - .instructions - .map(TryInto::try_into) - .ok_or_else(|| "No InstructionSet provided in sidechain block".to_string())??; - Ok(Self::new(node, instructions)) - } -} - -impl From for proto::common::Node { - fn from(node: Node) -> Self { - Self { - hash: node.hash().as_bytes().to_vec(), - parent: node.parent().as_bytes().to_vec(), - height: node.height(), - is_committed: node.is_committed(), - } - } -} - -impl TryFrom for Node { - type Error = String; - - fn try_from(node: proto::common::Node) -> Result { - let hash = TreeNodeHash::try_from(node.hash).map_err(|err| err.to_string())?; - let parent = TreeNodeHash::try_from(node.parent).map_err(|err| err.to_string())?; - let height = node.height; - let is_committed = node.is_committed; - - Ok(Self::new(hash, parent, height, is_committed)) - } -} - -impl From for proto::validator_node::KeyValue { - fn from(kv: KeyValue) -> Self { - Self { - key: kv.key, - value: kv.value, - } - } -} - -impl TryFrom for KeyValue { - type Error = String; - - fn try_from(kv: proto::validator_node::KeyValue) -> Result { - if kv.key.is_empty() { - return Err("KeyValue: key cannot be empty".to_string()); - } - - Ok(Self { - key: kv.key, - value: kv.value, - }) - } -} - -impl From for proto::validator_node::StateOpLog { - fn from(entry: StateOpLogEntry) -> Self { - let DbStateOpLogEntry { - height, - merkle_root, - operation, - schema, - key, - value, - } = entry.into_inner(); - Self { - height, - merkle_root: merkle_root.map(|r| r.as_bytes().to_vec()).unwrap_or_default(), - operation: operation.as_op_str().to_string(), - schema, - key, - value: value.unwrap_or_default(), - } - } -} -impl TryFrom for StateOpLogEntry { - type Error = String; - - fn try_from(value: proto::validator_node::StateOpLog) -> Result { - Ok(DbStateOpLogEntry { - height: value.height, - merkle_root: Some(value.merkle_root) - .filter(|r| !r.is_empty()) - .map(TryInto::try_into) - .transpose() - .map_err(|_| "Invalid merkle root value".to_string())?, - operation: value - .operation - .parse() - .map_err(|_| "Invalid oplog operation string".to_string())?, - schema: value.schema, - key: value.key, - value: Some(value.value).filter(|v| !v.is_empty()), - } - .into()) - } -} - -//---------------------------------- SignerSignature --------------------------------------------// -impl> From for proto::common::SignerSignature { - fn from(signature: B) -> Self { - Self { - signer: signature.borrow().signer().to_vec(), - signature: Some(signature.borrow().signature().into()), - } - } -} - -impl TryFrom for SignerSignature { - type Error = String; - - fn try_from(value: proto::common::SignerSignature) -> Result { - Ok(Self::new( - PublicKey::from_bytes(&value.signer).map_err(|err| err.to_string())?, - value - .signature - .map(TryInto::try_into) - .ok_or("signature not provided")??, - )) - } -} - -//---------------------------------- Signature --------------------------------------------// -impl TryFrom for Signature { - type Error = String; - - fn try_from(sig: proto::common::Signature) -> Result { - let public_nonce = PublicKey::from_bytes(&sig.public_nonce).map_err(|e| e.to_string())?; - let signature = PrivateKey::from_bytes(&sig.signature).map_err(|e| e.to_string())?; - - Ok(Self::new(public_nonce, signature)) - } -} - -impl> From for proto::common::Signature { - fn from(sig: T) -> Self { - Self { - public_nonce: sig.borrow().get_public_nonce().to_vec(), - signature: sig.borrow().get_signature().to_vec(), - } - } -} diff --git a/applications/tari_validator_node/src/p2p/proto/mod.rs b/applications/tari_validator_node/src/p2p/proto/mod.rs deleted file mode 100644 index 185d9ba540b..00000000000 --- a/applications/tari_validator_node/src/p2p/proto/mod.rs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -mod conversions; - -pub mod common { - include!(concat!(env!("OUT_DIR"), "/tari.dan.common.rs")); -} - -pub mod consensus { - include!(concat!(env!("OUT_DIR"), "/tari.dan.consensus.rs")); -} - -pub mod validator_node { - include!(concat!(env!("OUT_DIR"), "/tari.dan.validator_node.rs")); -} diff --git a/applications/tari_validator_node/src/p2p/rpc/mod.rs b/applications/tari_validator_node/src/p2p/rpc/mod.rs deleted file mode 100644 index 771b777e803..00000000000 --- a/applications/tari_validator_node/src/p2p/rpc/mod.rs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2021, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -mod service_impl; - -#[cfg(test)] -mod test; - -pub use service_impl::ValidatorNodeRpcServiceImpl; -use tari_comms::protocol::rpc::{Request, Response, RpcStatus, Streaming}; -use tari_comms_rpc_macros::tari_rpc; -use tari_dan_core::{ - services::{AssetProcessor, MempoolService}, - storage::DbFactory, -}; - -use crate::p2p::proto::validator_node as proto; - -#[tari_rpc(protocol_name = b"t/vn/1", server_struct = ValidatorNodeRpcServer, client_struct = ValidatorNodeRpcClient)] -pub trait ValidatorNodeRpcService: Send + Sync + 'static { - #[rpc(method = 1)] - async fn get_token_data( - &self, - request: Request, - ) -> Result, RpcStatus>; - - #[rpc(method = 2)] - async fn invoke_read_method( - &self, - request: Request, - ) -> Result, RpcStatus>; - - #[rpc(method = 3)] - async fn invoke_method( - &self, - request: Request, - ) -> Result, RpcStatus>; - - #[rpc(method = 4)] - async fn get_sidechain_blocks( - &self, - request: Request, - ) -> Result, RpcStatus>; - - #[rpc(method = 5)] - async fn get_sidechain_state( - &self, - request: Request, - ) -> Result, RpcStatus>; - - #[rpc(method = 6)] - async fn get_op_logs( - &self, - request: Request, - ) -> Result, RpcStatus>; - - #[rpc(method = 7)] - async fn get_tip_node( - &self, - request: Request, - ) -> Result, RpcStatus>; -} - -pub fn create_validator_node_rpc_service< - TMempoolService: MempoolService + Clone, - TDbFactory: DbFactory + Clone, - TAssetProcessor: AssetProcessor + Clone, ->( - mempool_service: TMempoolService, - db_factory: TDbFactory, - asset_processor: TAssetProcessor, -) -> ValidatorNodeRpcServer> { - ValidatorNodeRpcServer::new(ValidatorNodeRpcServiceImpl::new( - mempool_service, - db_factory, - asset_processor, - )) -} diff --git a/applications/tari_validator_node/src/p2p/rpc/service_impl.rs b/applications/tari_validator_node/src/p2p/rpc/service_impl.rs deleted file mode 100644 index 4eb0561fad1..00000000000 --- a/applications/tari_validator_node/src/p2p/rpc/service_impl.rs +++ /dev/null @@ -1,346 +0,0 @@ -// Copyright 2021, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that -// the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the -// following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -use std::convert::{TryFrom, TryInto}; - -use log::*; -use tari_comms::{ - protocol::rpc::{Request, Response, RpcStatus, Streaming}, - utils, -}; -use tari_dan_core::{ - models::TreeNodeHash, - services::{AssetProcessor, MempoolService}, - storage::DbFactory, -}; -use tari_dan_engine::state::StateDbUnitOfWorkReader; -use tokio::{sync::mpsc, task}; - -const LOG_TARGET: &str = "vn::p2p::rpc"; - -use tari_common_types::types::PublicKey; -use tari_crypto::tari_utilities::ByteArray; -use tari_dan_engine::instructions::Instruction; - -use crate::p2p::{proto::validator_node as proto, rpc::ValidatorNodeRpcService}; - -pub struct ValidatorNodeRpcServiceImpl { - mempool_service: TMempoolService, - db_factory: TDbFactory, - asset_processor: TAssetProcessor, -} - -impl< - TMempoolService: MempoolService + Clone, - TDbFactory: DbFactory + Clone, - TAssetProcessor: AssetProcessor + Clone, - > ValidatorNodeRpcServiceImpl -{ - pub fn new(mempool_service: TMempoolService, db_factory: TDbFactory, asset_processor: TAssetProcessor) -> Self { - Self { - mempool_service, - db_factory, - asset_processor, - } - } -} - -#[tari_comms::async_trait] -impl ValidatorNodeRpcService - for ValidatorNodeRpcServiceImpl -where - TMempoolService: MempoolService + Clone, - TDbFactory: DbFactory + Clone, - TAssetProcessor: AssetProcessor + Clone, -{ - async fn get_token_data( - &self, - _request: Request, - ) -> Result, RpcStatus> { - Err(RpcStatus::general("Not implemented")) - } - - async fn invoke_read_method( - &self, - request: Request, - ) -> Result, RpcStatus> { - println!("{:?}", request); - let request = request.into_message(); - let contract_id = request - .contract_id - .try_into() - .map_err(|err| RpcStatus::bad_request(&format!("Asset public key was not a valid public key:{}", err)))?; - - let state = self - .db_factory - .get_state_db(&contract_id) - .map_err(|e| RpcStatus::general(&format!("Could not create state db: {}", e)))? - .ok_or_else(|| RpcStatus::not_found(&"This node does not process this asset".to_string()))?; - - let unit_of_work = state.reader(); - - let instruction = Instruction::new( - request - .template_id - .try_into() - .map_err(|_| RpcStatus::bad_request("Invalid template_id"))?, - request.method, - request.args, - PublicKey::from_bytes(&request.sender) - .map_err(|_| RpcStatus::bad_request("Invalid public key for sender"))?, - ); - let response_bytes = self - .asset_processor - .invoke_read_method(&instruction, &unit_of_work) - .map_err(|e| RpcStatus::general(&format!("Could not invoke read method: {}", e)))?; - - Ok(Response::new(proto::InvokeReadMethodResponse { - result: response_bytes.unwrap_or_default(), - })) - } - - async fn invoke_method( - &self, - request: Request, - ) -> Result, RpcStatus> { - println!("{:?}", request); - let request = request.into_message(); - let instruction = Instruction::new( - request - .template_id - .try_into() - .map_err(|_| RpcStatus::bad_request("Invalid template_id"))?, - request.method.clone(), - request.args.clone(), - PublicKey::from_bytes(&request.sender).map_err(|_| RpcStatus::bad_request("invalid sender"))?, /* TokenId(request.token_id.clone()), - * TODO: put signature in here - * ComSig::default() - * create_com_sig_from_bytes(&request.signature) - * .map_err(|err| Status::invalid_argument("signature was not a valid comsig"))?, */ - ); - debug!(target: LOG_TARGET, "Submitting instruction {} to mempool", instruction); - let mut mempool_service = self.mempool_service.clone(); - match mempool_service.submit_instruction(instruction).await { - Ok(_) => { - debug!(target: LOG_TARGET, "Accepted instruction into mempool"); - return Ok(Response::new(proto::InvokeMethodResponse { - result: vec![], - status: proto::Status::Accepted as i32, - })); - }, - Err(err) => { - debug!(target: LOG_TARGET, "Mempool rejected instruction: {}", err); - return Ok(Response::new(proto::InvokeMethodResponse { - result: vec![], - status: proto::Status::Errored as i32, - })); - }, - } - } - - async fn get_sidechain_blocks( - &self, - request: Request, - ) -> Result, RpcStatus> { - let msg = request.into_message(); - - let contract_id = msg - .contract_id - .try_into() - .map_err(|_| RpcStatus::bad_request("Invalid contract_id"))?; - let start_hash = - TreeNodeHash::try_from(msg.start_hash).map_err(|_| RpcStatus::bad_request("Invalid start hash"))?; - - let end_hash = Some(msg.end_hash) - .filter(|h| !h.is_empty()) - .map(TreeNodeHash::try_from) - .transpose() - .map_err(|_| RpcStatus::bad_request("Invalid end_hash"))?; - - let db = self - .db_factory - .get_chain_db(&contract_id) - .map_err(RpcStatus::log_internal_error(LOG_TARGET))? - .ok_or_else(|| RpcStatus::not_found("Asset not found"))?; - - let start_block = db - .find_sidechain_block_by_node_hash(&start_hash) - .map_err(RpcStatus::log_internal_error(LOG_TARGET))? - .ok_or_else(|| RpcStatus::not_found(&format!("Block not found with start_hash '{}'", start_hash)))?; - - let end_block_exists = end_hash - .as_ref() - .map(|end_hash| db.sidechain_block_exists(end_hash)) - .transpose() - .map_err(RpcStatus::log_internal_error(LOG_TARGET))?; - - if !end_block_exists.unwrap_or(true) { - return Err(RpcStatus::not_found(&format!( - "Block not found with end_hash '{}'", - end_hash.unwrap_or_else(TreeNodeHash::zero) - ))); - } - - let (tx, rx) = mpsc::channel(2); - - task::spawn(async move { - let mut current_block_hash = *start_block.node().hash(); - if tx - .send(Ok(proto::GetSidechainBlocksResponse { - block: Some(start_block.into()), - })) - .await - .is_err() - { - return; - } - loop { - match db.find_sidechain_block_by_parent_node_hash(¤t_block_hash) { - Ok(Some(block)) => { - current_block_hash = *block.node().hash(); - if tx - .send(Ok(proto::GetSidechainBlocksResponse { - block: Some(block.into()), - })) - .await - .is_err() - { - return; - } - if end_hash.map(|h| h == current_block_hash).unwrap_or(false) { - return; - } - }, - Ok(None) => return, - Err(err) => { - error!(target: LOG_TARGET, "Failure while streaming blocks: {}", err); - let _result = tx.send(Err(RpcStatus::general("Internal database failure"))).await; - return; - }, - } - } - }); - - Ok(Streaming::new(rx)) - } - - async fn get_sidechain_state( - &self, - request: Request, - ) -> Result, RpcStatus> { - let msg = request.into_message(); - - let contract_id = msg - .contract_id - .try_into() - .map_err(|_| RpcStatus::bad_request("Invalid contract_id"))?; - - let db = self - .db_factory - .get_state_db(&contract_id) - .map_err(RpcStatus::log_internal_error(LOG_TARGET))? - .ok_or_else(|| RpcStatus::not_found("Asset not found"))?; - - let uow = db.reader(); - let data = uow.get_all_state().map_err(RpcStatus::log_internal_error(LOG_TARGET))?; - let (tx, rx) = mpsc::channel(10); - - task::spawn(async move { - for state in data { - let schema = proto::GetSidechainStateResponse { - state: Some(proto::get_sidechain_state_response::State::Schema(state.name)), - }; - - if tx.send(Ok(schema)).await.is_err() { - return; - } - - let key_values = state - .items - .into_iter() - .map(|kv| proto::get_sidechain_state_response::State::KeyValue(kv.into())) - .map(|state| Ok(proto::GetSidechainStateResponse { state: Some(state) })); - - if utils::mpsc::send_all(&tx, key_values).await.is_err() { - return; - } - } - }); - - Ok(Streaming::new(rx)) - } - - async fn get_op_logs( - &self, - request: Request, - ) -> Result, RpcStatus> { - let msg = request.into_message(); - - let contract_id = msg - .contract_id - .try_into() - .map_err(|_| RpcStatus::bad_request("Invalid contract_id"))?; - - let db = self - .db_factory - .get_state_db(&contract_id) - .map_err(RpcStatus::log_internal_error(LOG_TARGET))? - .ok_or_else(|| RpcStatus::not_found("Asset not found"))?; - - let reader = db.reader(); - let op_logs = reader - .get_op_logs_for_height(msg.height) - .map_err(RpcStatus::log_internal_error(LOG_TARGET))?; - - let resp = proto::GetStateOpLogsResponse { - op_logs: op_logs.into_iter().map(Into::into).collect(), - }; - - Ok(Response::new(resp)) - } - - async fn get_tip_node( - &self, - request: Request, - ) -> Result, RpcStatus> { - let msg = request.into_message(); - - let contract_id = msg - .contract_id - .try_into() - .map_err(|_| RpcStatus::bad_request("Invalid contract_id"))?; - - let db = self - .db_factory - .get_chain_db(&contract_id) - .map_err(RpcStatus::log_internal_error(LOG_TARGET))? - .ok_or_else(|| RpcStatus::not_found("Asset not found"))?; - - let tip_node = db.get_tip_node().map_err(RpcStatus::log_internal_error(LOG_TARGET))?; - - let resp = proto::GetTipNodeResponse { - tip_node: tip_node.map(Into::into), - }; - - Ok(Response::new(resp)) - } -} diff --git a/applications/tari_validator_node/src/p2p/rpc/test.rs b/applications/tari_validator_node/src/p2p/rpc/test.rs deleted file mode 100644 index 0bddc115138..00000000000 --- a/applications/tari_validator_node/src/p2p/rpc/test.rs +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::convert::TryFrom; - -use tari_common_types::types::FixedHash; -use tari_comms::{protocol::rpc::mock::RpcRequestMock, test_utils}; -use tari_crypto::tari_utilities::{hex::Hex, ByteArray}; -use tari_dan_core::{ - models::{Node, TreeNodeHash}, - services::mocks::{MockAssetProcessor, MockMempoolService}, - storage::{chain::ChainDbUnitOfWork, mocks::MockDbFactory, DbFactory}, -}; -use tari_test_utils::{paths::tempdir, streams::convert_mpsc_to_stream}; -use tokio_stream::StreamExt; - -use crate::p2p::{ - proto, - rpc::{ValidatorNodeRpcService, ValidatorNodeRpcServiceImpl}, -}; - -fn setup() -> ( - ValidatorNodeRpcServiceImpl, - RpcRequestMock, - MockDbFactory, -) { - let tmp = tempdir().unwrap(); - let peer_manager = test_utils::build_peer_manager(&tmp); - let mock = RpcRequestMock::new(peer_manager); - let mempool = MockMempoolService; - let db_factory = MockDbFactory::default(); - let asset_processor = MockAssetProcessor; - let service = ValidatorNodeRpcServiceImpl::new(mempool, db_factory.clone(), asset_processor); - - (service, mock, db_factory) -} - -mod get_sidechain_blocks { - - use super::*; - - #[tokio::test] - async fn it_fetches_matching_block() { - let (service, mock, db_factory) = setup(); - let contract_id = FixedHash::zero(); - let db = db_factory.get_or_create_chain_db(&contract_id).unwrap(); - let mut uow = db.new_unit_of_work(); - - // Some random parent hash to ensure stream does not last forever - let parent = - TreeNodeHash::from_hex("972209d3622c1227a499fd2cfcfa75fdde547d1a21fa805522d3a1a315ebd1a3").unwrap(); - uow.add_node(TreeNodeHash::zero(), parent, 1).unwrap(); - uow.commit().unwrap(); - - let req = proto::validator_node::GetSidechainBlocksRequest { - contract_id: contract_id.to_vec(), - start_hash: TreeNodeHash::zero().as_bytes().to_vec(), - end_hash: vec![], - }; - let req = mock.request_with_context(Default::default(), req); - let mut resp = service.get_sidechain_blocks(req).await.unwrap().into_inner(); - let stream = convert_mpsc_to_stream(&mut resp).map(|r| r.unwrap()); - - let responses = stream - .collect::>() - .await; - assert_eq!(responses.len(), 1); - let node = Node::new(TreeNodeHash::zero(), parent, 1, false); - let block = responses[0].block.clone(); - assert_eq!( - Node::try_from(block.as_ref().unwrap().node.clone().unwrap()).unwrap(), - node - ); - assert_eq!( - block.as_ref().unwrap().instructions.clone().unwrap().instructions.len(), - 0 - ); - } - - #[tokio::test] - async fn it_errors_if_asset_not_found() { - let (service, mock, _) = setup(); - - let req = proto::validator_node::GetSidechainBlocksRequest { - contract_id: FixedHash::zero().to_vec(), - start_hash: FixedHash::zero().as_bytes().to_vec(), - end_hash: vec![], - }; - let req = mock.request_with_context(Default::default(), req); - let err = service.get_sidechain_blocks(req).await.unwrap_err(); - assert!(err.as_status_code().is_not_found()); - assert_eq!(err.details(), "Asset not found"); - } - - #[tokio::test] - async fn it_errors_if_block_not_found() { - let (service, mock, db_factory) = setup(); - let contract_id = FixedHash::zero(); - let db = db_factory.get_or_create_chain_db(&contract_id).unwrap(); - db.new_unit_of_work().commit().unwrap(); - - let req = proto::validator_node::GetSidechainBlocksRequest { - contract_id: contract_id.to_vec(), - start_hash: FixedHash::zero().as_bytes().to_vec(), - end_hash: vec![], - }; - let req = mock.request_with_context(Default::default(), req); - let err = service.get_sidechain_blocks(req).await.unwrap_err(); - assert!(err.as_status_code().is_not_found()); - assert!(err.details().starts_with("Block not found")); - } -} diff --git a/applications/tari_validator_node/src/p2p/services/inbound_connection_service.rs b/applications/tari_validator_node/src/p2p/services/inbound_connection_service.rs deleted file mode 100644 index 4d6f15abc9b..00000000000 --- a/applications/tari_validator_node/src/p2p/services/inbound_connection_service.rs +++ /dev/null @@ -1,341 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -use std::{ - collections::VecDeque, - convert::TryInto, - sync::Arc, - time::{Duration, Instant}, -}; - -use async_trait::async_trait; -use futures::{self, pin_mut, Stream, StreamExt}; -use log::*; -use tari_common_types::types::FixedHash; -use tari_comms::types::CommsPublicKey; -use tari_dan_core::{ - models::{HotStuffMessage, HotStuffMessageType, TariDanPayload, ViewId}, - services::infrastructure_services::InboundConnectionService, - DigitalAssetError, -}; -use tari_p2p::comms_connector::PeerMessage; -use tari_shutdown::ShutdownSignal; -use tokio::sync::{ - mpsc::{channel, Receiver, Sender}, - oneshot, -}; - -use crate::p2p::proto; - -const LOG_TARGET: &str = "tari::validator_node::p2p::services::inbound_connection_service"; - -#[derive(Debug)] -enum WaitForMessageType { - Message, - QuorumCertificate, -} - -#[derive(Debug)] -#[allow(dead_code)] -enum TariCommsInboundRequest { - WaitForMessage { - wait_for_type: WaitForMessageType, - message_type: HotStuffMessageType, - view_number: ViewId, - reply_channel: oneshot::Sender<(CommsPublicKey, HotStuffMessage)>, - }, -} - -#[allow(dead_code)] -pub struct TariCommsInboundConnectionService { - receiver: TariCommsInboundReceiverHandle, - // sender: Sender<(CommsPublicKey, HotStuffMessage)>, - request_channel: Receiver, - contract_id: FixedHash, - buffered_messages: VecDeque<(CommsPublicKey, HotStuffMessage, Instant)>, - expiry_time: Duration, - #[allow(clippy::type_complexity)] - waiters: VecDeque<( - HotStuffMessageType, - ViewId, - WaitForMessageType, - oneshot::Sender<(CommsPublicKey, HotStuffMessage)>, - )>, - loopback_sender: Sender<(CommsPublicKey, HotStuffMessage)>, - loopback_receiver: Receiver<(CommsPublicKey, HotStuffMessage)>, -} - -#[allow(dead_code)] -impl TariCommsInboundConnectionService { - pub fn new(contract_id: FixedHash) -> Self { - let (sender, receiver) = channel(1000); - let (loopback_sender, loopback_receiver) = channel(1); - Self { - receiver: TariCommsInboundReceiverHandle::new(sender), - request_channel: receiver, - contract_id, - buffered_messages: VecDeque::with_capacity(1000), - expiry_time: Duration::new(90, 0), - waiters: VecDeque::new(), - loopback_receiver, - loopback_sender, - } - } - - pub fn clone_sender(&self) -> Sender<(CommsPublicKey, HotStuffMessage)> { - self.loopback_sender.clone() - } - - pub fn get_receiver(&self) -> TariCommsInboundReceiverHandle { - self.receiver.clone() - } - - pub async fn run( - &mut self, - _shutdown_signal: ShutdownSignal, - inbound_stream: impl Stream>, - ) -> Result<(), DigitalAssetError> { - let inbound_stream = inbound_stream.fuse(); - pin_mut!(inbound_stream); - loop { - tokio::select! { - request = self.request_channel.recv() => { - if let Some(request) = request { - self.handle_request(request).await?; - } else { - debug!(target: LOG_TARGET, "All requesters have dropped, stopping."); - return Ok(()) - } - }, - message = self.loopback_receiver.recv() => { - if let Some((from, message)) = message { - self.process_message(from, message).await?; - } else { - debug!(target: LOG_TARGET, "Loopback senders have all dropped, stopping"); - return Ok(()) - } - }, - message = inbound_stream.select_next_some() => { - self.forward_message(message).await?; - }, - // complete => { - // return Ok(()); - // } - // _ = shutdown_signal => { - // return Ok(()) - // } - } - } - } - - async fn handle_request(&mut self, request: TariCommsInboundRequest) -> Result<(), DigitalAssetError> { - debug!(target: LOG_TARGET, "Received request: {:?}", request); - match request { - TariCommsInboundRequest::WaitForMessage { - wait_for_type, - message_type, - view_number, - reply_channel, - } => { - // Check for already received messages - let mut indexes_to_remove = vec![]; - let mut result_message = None; - for (index, (from_pk, message, msg_time)) in self.buffered_messages.iter().enumerate() { - if msg_time.elapsed() > self.expiry_time { - warn!( - target: LOG_TARGET, - "Message has expired: ({:.2?}) {:?}", - msg_time.elapsed(), - message - ); - indexes_to_remove.push(index); - } else { - match wait_for_type { - WaitForMessageType::Message => { - if message.message_type() == message_type && message.view_number() == view_number { - result_message = Some((from_pk.clone(), message.clone())); - indexes_to_remove.push(index); - break; - } - }, - WaitForMessageType::QuorumCertificate => { - if let Some(qc) = message.justify() { - if qc.message_type() == message_type && qc.view_number() == view_number { - result_message = Some((from_pk.clone(), message.clone())); - indexes_to_remove.push(index); - break; - } - } - }, - } - } - } - for i in indexes_to_remove.iter().rev() { - self.buffered_messages.remove(*i); - } - match result_message { - Some(m) => { - if let Err(m) = reply_channel.send(m) { - error!(target: LOG_TARGET, "Failed to send result message! {:?}", m); - } - }, - None => { - self.waiters - .push_back((message_type, view_number, wait_for_type, reply_channel)); - }, - } - }, - } - Ok(()) - } - - async fn forward_message(&mut self, message: Arc) -> Result<(), DigitalAssetError> { - // let from = message.authenticated_origin.as_ref().unwrap().clone(); - let from = message.source_peer.public_key.clone(); - let proto_message: proto::consensus::HotStuffMessage = message.decode_message()?; - let hot_stuff_message: HotStuffMessage = proto_message - .try_into() - .map_err(DigitalAssetError::InvalidPeerMessage)?; - if *hot_stuff_message.contract_id() == self.contract_id { - println!("{:?}", hot_stuff_message); - // self.sender.send((from, hot_stuff_message)).await.unwrap(); - self.process_message(from, hot_stuff_message).await?; - } else { - println!("filtered"); - } - Ok(()) - } - - async fn process_message( - &mut self, - from: CommsPublicKey, - message: HotStuffMessage, - ) -> Result<(), DigitalAssetError> { - debug!(target: "messages::inbound::validator_node", "Inbound message received:{} {:?}", from, message); - debug!(target: LOG_TARGET, "Inbound message received:{} {:?}", from, message); - - // Loop until we have sent to a waiting call, or buffer the message - loop { - // Check for waiters - let mut waiter_index = None; - for (index, waiter) in self.waiters.iter().enumerate() { - let (message_type, view_number, wait_for_type, _) = waiter; - match wait_for_type { - WaitForMessageType::Message => { - if message.message_type() == *message_type && message.view_number() == *view_number { - waiter_index = Some(index); - break; - } - }, - WaitForMessageType::QuorumCertificate => { - if let Some(qc) = message.justify() { - if qc.message_type() == *message_type && qc.view_number() == *view_number { - waiter_index = Some(index); - break; - } - } - }, - } - } - - if let Some(index) = waiter_index { - debug!( - target: LOG_TARGET, - "Found waiter for this message, waking task... {:?}", - message.message_type() - ); - if let Some((_, _, _, reply)) = self.waiters.swap_remove_back(index) { - // The receiver on the other end of this channel may have dropped naturally - // as it moves out of scope and is not longer interested in receiving the message - if reply.send((from.clone(), message.clone())).is_ok() { - return Ok(()); - } - } - } else { - break; - } - } - - debug!( - target: LOG_TARGET, - "No waiters for this message, buffering message: {:?}", - message.message_type() - ); - // Otherwise, buffer it - self.buffered_messages.push_back((from, message, Instant::now())); - Ok(()) - } -} - -#[derive(Clone)] -pub struct TariCommsInboundReceiverHandle { - sender: Sender, -} - -impl TariCommsInboundReceiverHandle { - fn new(sender: Sender) -> Self { - Self { sender } - } -} - -#[async_trait] -impl InboundConnectionService for TariCommsInboundReceiverHandle { - type Addr = CommsPublicKey; - type Payload = TariDanPayload; - - async fn wait_for_message( - &self, - message_type: HotStuffMessageType, - view_number: ViewId, - ) -> Result<(CommsPublicKey, HotStuffMessage), DigitalAssetError> { - let (tx, rx) = oneshot::channel(); - self.sender - .send(TariCommsInboundRequest::WaitForMessage { - wait_for_type: WaitForMessageType::Message, - message_type, - view_number, - reply_channel: tx, - }) - .await - .map_err(|e| DigitalAssetError::FatalError(format!("Error sending request to channel:{}", e)))?; - rx.await - .map_err(|e| DigitalAssetError::FatalError(format!("Error receiving from wait_for oneshot channel:{}", e))) - } - - async fn wait_for_qc( - &self, - message_type: HotStuffMessageType, - view_number: ViewId, - ) -> Result<(CommsPublicKey, HotStuffMessage), DigitalAssetError> { - let (tx, rx) = oneshot::channel(); - self.sender - .send(TariCommsInboundRequest::WaitForMessage { - wait_for_type: WaitForMessageType::QuorumCertificate, - message_type, - view_number, - reply_channel: tx, - }) - .await - .map_err(|e| DigitalAssetError::FatalError(format!("Error sending request to channel:{}", e)))?; - rx.await - .map_err(|e| DigitalAssetError::FatalError(format!("Error receiving from qc oneshot channel:{}", e))) - } -} diff --git a/applications/tari_validator_node/src/p2p/services/mod.rs b/applications/tari_validator_node/src/p2p/services/mod.rs deleted file mode 100644 index 60f57c5e48a..00000000000 --- a/applications/tari_validator_node/src/p2p/services/mod.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub mod inbound_connection_service; -pub mod outbound_connection_service; -pub mod rpc_client; diff --git a/applications/tari_validator_node/src/p2p/services/outbound_connection_service.rs b/applications/tari_validator_node/src/p2p/services/outbound_connection_service.rs deleted file mode 100644 index 9190ecbe142..00000000000 --- a/applications/tari_validator_node/src/p2p/services/outbound_connection_service.rs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::marker::PhantomData; - -use async_trait::async_trait; -use log::*; -use tari_common_types::types::FixedHash; -use tari_comms::types::CommsPublicKey; -use tari_comms_dht::{domain_message::OutboundDomainMessage, outbound::OutboundMessageRequester}; -use tari_dan_core::{ - models::{HotStuffMessage, Payload, TariDanPayload}, - services::infrastructure_services::OutboundService, - DigitalAssetError, -}; -use tari_p2p::tari_message::TariMessageType; -use tokio::sync::mpsc::Sender; - -use crate::p2p::proto; - -const LOG_TARGET: &str = "tari::validator_node::messages::outbound::validator_node"; - -pub struct TariCommsOutboundService { - outbound_message_requester: OutboundMessageRequester, - loopback_service: Sender<(CommsPublicKey, HotStuffMessage)>, - contract_id: FixedHash, - // TODO: Remove - phantom: PhantomData, -} - -impl TariCommsOutboundService { - #[allow(dead_code)] - pub fn new( - outbound_message_requester: OutboundMessageRequester, - loopback_service: Sender<(CommsPublicKey, HotStuffMessage)>, - contract_id: FixedHash, - ) -> Self { - Self { - outbound_message_requester, - loopback_service, - contract_id, - phantom: PhantomData, - } - } -} - -#[async_trait] -impl OutboundService for TariCommsOutboundService { - type Addr = CommsPublicKey; - type Payload = TariDanPayload; - - async fn send( - &mut self, - from: CommsPublicKey, - to: CommsPublicKey, - message: HotStuffMessage, - ) -> Result<(), DigitalAssetError> { - debug!(target: LOG_TARGET, "Outbound message to be sent:{} {:?}", to, message); - // Tari comms does allow sending to itself - if from == to && *message.contract_id() == self.contract_id { - debug!( - target: LOG_TARGET, - "Sending {:?} to self for contract {}", - message.message_type(), - message.contract_id() - ); - self.loopback_service.send((from, message)).await.map_err(Box::new)?; - return Ok(()); - } - - let inner = proto::consensus::HotStuffMessage::from(message); - let tari_message = OutboundDomainMessage::new(&TariMessageType::DanConsensusMessage, inner); - - self.outbound_message_requester.send_direct(to, tari_message).await?; - Ok(()) - } - - async fn broadcast( - &mut self, - from: CommsPublicKey, - committee: &[CommsPublicKey], - message: HotStuffMessage, - ) -> Result<(), DigitalAssetError> { - for committee_member in committee { - // TODO: send in parallel - self.send(from.clone(), committee_member.clone(), message.clone()) - .await?; - } - Ok(()) - } -} diff --git a/applications/tari_validator_node/src/p2p/services/rpc_client.rs b/applications/tari_validator_node/src/p2p/services/rpc_client.rs deleted file mode 100644 index ca99d058736..00000000000 --- a/applications/tari_validator_node/src/p2p/services/rpc_client.rs +++ /dev/null @@ -1,269 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::convert::TryInto; - -use async_trait::async_trait; -use log::*; -use tari_common_types::types::{FixedHash, PublicKey}; -use tari_comms::PeerConnection; -use tari_comms_dht::DhtRequester; -use tari_crypto::tari_utilities::ByteArray; -use tari_dan_common_types::TemplateId; -use tari_dan_core::{ - models::{Node, SideChainBlock, TreeNodeHash}, - services::{ValidatorNodeClientError, ValidatorNodeClientFactory, ValidatorNodeRpcClient}, -}; -use tari_dan_engine::state::models::{SchemaState, StateOpLogEntry}; -use tokio_stream::StreamExt; - -use crate::p2p::{proto::validator_node as proto, rpc}; - -const LOG_TARGET: &str = "tari::validator_node::p2p::services::rpc_client"; - -pub struct TariCommsValidatorNodeRpcClient { - dht: DhtRequester, - address: PublicKey, -} - -impl TariCommsValidatorNodeRpcClient { - async fn create_connection(&mut self) -> Result { - let conn = self.dht.dial_or_discover_peer(self.address.clone()).await?; - Ok(conn) - } -} - -#[async_trait] -impl ValidatorNodeRpcClient for TariCommsValidatorNodeRpcClient { - async fn invoke_read_method( - &mut self, - contract_id: &FixedHash, - template_id: TemplateId, - method: String, - args: Vec, - sender: PublicKey, - ) -> Result>, ValidatorNodeClientError> { - debug!( - target: LOG_TARGET, - r#"Invoking read method "{}" for asset '{}'"#, method, contract_id - ); - let mut connection = self.create_connection().await?; - let mut client = connection.connect_rpc::().await?; - let request = proto::InvokeReadMethodRequest { - contract_id: contract_id.to_vec(), - template_id: template_id as u32, - method, - args, - sender: sender.to_vec(), - }; - let response = client.invoke_read_method(request).await?; - - Ok(if response.result.is_empty() { - None - } else { - Some(response.result) - }) - } - - async fn invoke_method( - &mut self, - contract_id: &FixedHash, - template_id: TemplateId, - method: String, - args: Vec, - sender: PublicKey, - ) -> Result>, ValidatorNodeClientError> { - debug!( - target: LOG_TARGET, - r#"Invoking method "{}" for asset '{}'"#, method, contract_id - ); - let mut connection = self.create_connection().await?; - let mut client = connection.connect_rpc::().await?; - let request = proto::InvokeMethodRequest { - contract_id: contract_id.to_vec(), - template_id: template_id as u32, - method, - args, - sender: sender.to_vec(), - }; - let response = client.invoke_method(request).await?; - - debug!( - target: LOG_TARGET, - "Validator node '{}' returned status '{}' for asset '{}'", self.address, response.status, contract_id - ); - if response.result.is_empty() { - Ok(None) - } else { - Ok(Some(response.result)) - } - } - - async fn get_sidechain_blocks( - &mut self, - contract_id: &FixedHash, - start_hash: TreeNodeHash, - end_hash: Option, - ) -> Result, ValidatorNodeClientError> { - let mut connection = self.create_connection().await?; - let mut client = connection.connect_rpc::().await?; - let request = proto::GetSidechainBlocksRequest { - contract_id: contract_id.to_vec(), - start_hash: start_hash.as_bytes().to_vec(), - end_hash: end_hash.map(|h| h.as_bytes().to_vec()).unwrap_or_default(), - }; - - let stream = client.get_sidechain_blocks(request).await?; - // TODO: By first collecting all the blocks, we lose the advantage of streaming. Since you cannot return - // `Result, _>`, and the Map type is private in tokio-stream, its a little tricky to - // return the stream and not leak the RPC response type out of the client. - // Copying the tokio_stream::Map stream into our code / creating a custom conversion stream wrapper would - // solve this. - let blocks = stream - .map(|result| { - let resp = result?; - let block: SideChainBlock = resp - .block - .ok_or_else(|| { - ValidatorNodeClientError::InvalidPeerMessage("Node returned empty block".to_string()) - })? - .try_into() - .map_err(ValidatorNodeClientError::InvalidPeerMessage)?; - Ok(block) - }) - .collect::>() - .await?; - - Ok(blocks) - } - - async fn get_sidechain_state( - &mut self, - contract_id: &FixedHash, - ) -> Result, ValidatorNodeClientError> { - let mut connection = self.create_connection().await?; - let mut client = connection.connect_rpc::().await?; - let request = proto::GetSidechainStateRequest { - contract_id: contract_id.to_vec(), - }; - - let mut stream = client.get_sidechain_state(request).await?; - // TODO: Same issue as get_sidechain_blocks - let mut schemas = Vec::new(); - let mut current_schema = None; - while let Some(resp) = stream.next().await { - let resp = resp?; - - match resp.state { - Some(proto::get_sidechain_state_response::State::Schema(name)) => { - if let Some(schema) = current_schema.take() { - schemas.push(schema); - } - current_schema = Some(SchemaState::new(name, vec![])); - }, - Some(proto::get_sidechain_state_response::State::KeyValue(kv)) => match current_schema.as_mut() { - Some(schema) => { - let kv = kv.try_into().map_err(ValidatorNodeClientError::InvalidPeerMessage)?; - schema.push_key_value(kv); - }, - None => { - return Err(ValidatorNodeClientError::InvalidPeerMessage(format!( - "Peer {} sent a key value response without first defining the schema", - self.address - ))) - }, - }, - None => { - return Err(ValidatorNodeClientError::ProtocolViolation { - peer: self.address.clone(), - details: "get_sidechain_state: Peer sent response without state".to_string(), - }) - }, - } - } - - if let Some(schema) = current_schema { - schemas.push(schema); - } - - Ok(schemas) - } - - async fn get_op_logs( - &mut self, - contract_id: &FixedHash, - height: u64, - ) -> Result, ValidatorNodeClientError> { - let mut connection = self.create_connection().await?; - let mut client = connection.connect_rpc::().await?; - let request = proto::GetStateOpLogsRequest { - contract_id: contract_id.as_bytes().to_vec(), - height, - }; - - let resp = client.get_op_logs(request).await?; - let op_logs = resp - .op_logs - .into_iter() - .map(TryInto::try_into) - .collect::, _>>() - .map_err(ValidatorNodeClientError::InvalidPeerMessage)?; - - Ok(op_logs) - } - - async fn get_tip_node(&mut self, contract_id: &FixedHash) -> Result, ValidatorNodeClientError> { - let mut connection = self.create_connection().await?; - let mut client = connection.connect_rpc::().await?; - let request = proto::GetTipNodeRequest { - contract_id: contract_id.to_vec(), - }; - let resp = client.get_tip_node(request).await?; - resp.tip_node - .map(TryInto::try_into) - .transpose() - .map_err(ValidatorNodeClientError::InvalidPeerMessage) - } -} - -#[derive(Clone)] -pub struct TariCommsValidatorNodeClientFactory { - dht: DhtRequester, -} - -impl TariCommsValidatorNodeClientFactory { - pub fn new(dht: DhtRequester) -> Self { - Self { dht } - } -} - -impl ValidatorNodeClientFactory for TariCommsValidatorNodeClientFactory { - type Addr = PublicKey; - type Client = TariCommsValidatorNodeRpcClient; - - fn create_client(&self, address: &Self::Addr) -> Self::Client { - TariCommsValidatorNodeRpcClient { - dht: self.dht.clone(), - address: address.clone(), - } - } -} diff --git a/base_layer/core/src/proof_of_work/lwma_diff.rs b/base_layer/core/src/proof_of_work/lwma_diff.rs index f5de6dcaf2e..e422f06045f 100644 --- a/base_layer/core/src/proof_of_work/lwma_diff.rs +++ b/base_layer/core/src/proof_of_work/lwma_diff.rs @@ -1,3 +1,8 @@ +// Copyright 2022 The Tari Project +// SPDX-License-Identifier: BSD-3-Clause + +// Portions of the code: + // LWMA-1 for BTC & Zcash clones // Copyright (c) 2017-2019 The Bitcoin Gold developers, Zawy, iamstenman (Microbitcoin) // MIT License diff --git a/clients/validator_node_grpc_client/README.md b/clients/validator_node_grpc_client/README.md deleted file mode 100644 index f009164c64f..00000000000 --- a/clients/validator_node_grpc_client/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# Tari Validator Node GRPC client - -Async GRPC client library for the Tari Validator Node. - -## Usage - -```javascript -const { Client } = require("@tari/validator-node-grpc-client"); -const client = Client.connect("127.0.0.1:18144"); -``` - -## Development - -- `npm install` -- hack hack hack - -## Tests - -- `npm test` diff --git a/clients/validator_node_grpc_client/package.json b/clients/validator_node_grpc_client/package.json deleted file mode 100644 index b22c8810dee..00000000000 --- a/clients/validator_node_grpc_client/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "@tari/validator-node-grpc-client", - "version": "0.0.1", - "description": "GRPC client for Tari Base Node", - "main": "./src/index.js", - "scripts": { - "test": "jest" - }, - "author": "Tari development community", - "dependencies": { - "@grpc/grpc-js": "^1.2.3", - "@grpc/proto-loader": "^0.5.5", - "grpc-promise": "^1.4.0" - }, - "devDependencies": { - "jest": "^27.1.1" - } -} diff --git a/clients/validator_node_grpc_client/src/index.js b/clients/validator_node_grpc_client/src/index.js deleted file mode 100644 index f30542d9987..00000000000 --- a/clients/validator_node_grpc_client/src/index.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -const grpc = require("@grpc/grpc-js"); -const protoLoader = require("@grpc/proto-loader"); -const {promisifyAll} = require("grpc-promise"); -const path = require("path"); - -const packageDefinition = protoLoader.loadSync( - path.resolve( - __dirname, - "../../../applications/tari_app_grpc/proto/validator_node.proto" - ), - { - keepCase: true, - longs: String, - enums: String, - defaults: true, - oneofs: true, - } -); -const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); -const tariGrpc = protoDescriptor.tari.rpc; - -function connect(address) { - const client = new tariGrpc.ValidatorNode( - address, - grpc.credentials.createInsecure() - ); - promisifyAll(client, {metadata: new grpc.Metadata()}); - return client; -} - -function Client(address = "127.0.0.1:18144") { - this.inner = connect(address); - - const methods = [ - "getMetadata", - "getTokenData", - "executeInstruction", - ]; - methods.forEach((method) => { - this[method] = (arg) => this.inner[method]().sendMessage(arg); - }); -} - -Client.connect = (address) => new Client(address); - -module.exports = { - Client, - types: tariGrpc, -}; diff --git a/dan_layer/common_types/Cargo.toml b/dan_layer/common_types/Cargo.toml deleted file mode 100644 index fc12b0ae164..00000000000 --- a/dan_layer/common_types/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "tari_dan_common_types" -version = "0.1.0" -edition = "2021" -license = "BSD-3-Clause" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -tari_common = { path = "../../common", features = ["build"] } -tari_common_types = { path = "../../base_layer/common_types" } - -borsh = "0.9.3" -prost = "0.9" -prost-types = "0.9" - -[build-dependencies] -tari_common = { path = "../../common", features = ["build"] } diff --git a/dan_layer/common_types/build.rs b/dan_layer/common_types/build.rs deleted file mode 100644 index dc1a880c0b1..00000000000 --- a/dan_layer/common_types/build.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -fn main() -> Result<(), Box> { - tari_common::build::ProtobufCompiler::new() - .proto_paths(&["proto/tips"]) - .include_paths(&["proto/tips"]) - .emit_rerun_if_changed_directives() - .compile() - .unwrap(); - Ok(()) -} diff --git a/dan_layer/common_types/proto/tips/tip002.proto b/dan_layer/common_types/proto/tips/tip002.proto deleted file mode 100644 index 9386b5ea70b..00000000000 --- a/dan_layer/common_types/proto/tips/tip002.proto +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - - -syntax = "proto3"; -package tari.dan.tips.tip002; - -// ERC20 copy - Should be renamed to TIP020 -service Tip002 { - rpc Init(InitRequest) returns (Empty); - // rpc Info(InfoRequest) returns (InfoResponse); - rpc BalanceOf(BalanceOfRequest) returns (BalanceOfResponse); - rpc Transfer(TransferRequest) returns (TransferResponse); -} - - -message InitRequest { - string symbol = 1; - uint32 decimals = 2; - uint64 total_supply = 3; -} -message Empty{ - -} - -message TransferRequest { - bytes to = 1; - uint64 amount = 2; - bytes from = 3; - bytes caller = 4; -} - -message TransferResponse { - // TODO? maybe errors? -} - -//message InfoRequest { -// -//} -// -//message InfoResponse { -// string symbol = 1; -// byte decimals = 2; -// uint256 total_supply = 3; -//} - -message BalanceOfRequest { - bytes owner = 1; -} - -message BalanceOfResponse { - uint64 balance = 1; -} diff --git a/dan_layer/common_types/proto/tips/tip003.proto b/dan_layer/common_types/proto/tips/tip003.proto deleted file mode 100644 index aeab96e3a03..00000000000 --- a/dan_layer/common_types/proto/tips/tip003.proto +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - - -syntax = "proto3"; -package tari.dan.tips.tip003; - -// Empty TIP for sidechains using base layer checkpoints -service Tip003 { - rpc Init(InitRequest) returns (Empty); -} - -message InitRequest { - -} - -message Empty { - -} diff --git a/dan_layer/common_types/proto/tips/tip004.proto b/dan_layer/common_types/proto/tips/tip004.proto deleted file mode 100644 index 2f60de177f4..00000000000 --- a/dan_layer/common_types/proto/tips/tip004.proto +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -syntax = "proto3"; -package tari.dan.tips.tip004; - -// Template for mintable NFTs (721) that are not created when the contract is created later -service Tip003 { - rpc Init(InitRequest) returns (Empty); - rpc Mint(MintRequest) returns (MintResponse); - rpc BalanceOf(BalanceOfRequest) returns (BalanceOfResponse); - rpc TokenOfOwnerByIndex(TokenOfOwnerByIndexRequest) returns (TokenOfOwnerByIndexResponse); -} - -message InitRequest { - -} - -message Empty { - -} - -message MintRequest { - string token =1; - bytes owner = 2; -} - -message MintResponse { - -} - -message BalanceOfRequest { - bytes owner = 1; -} - -message BalanceOfResponse { - uint64 num_tokens = 1; -} - -message TokenOfOwnerByIndexRequest { - bytes owner = 1; - uint64 index = 2; -} - -message TokenOfOwnerByIndexResponse { - bytes token_id = 1; - string token = 2; -} diff --git a/dan_layer/common_types/proto/tips/tip721.proto b/dan_layer/common_types/proto/tips/tip721.proto deleted file mode 100644 index c95f0f65a79..00000000000 --- a/dan_layer/common_types/proto/tips/tip721.proto +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -syntax = "proto3"; -package tari.dan.tips.tip721; - - -// ERC 721 copy -service Tip721 { - rpc Init(InitRequest) returns (Empty); - rpc TransferFrom(TransferFromRequest) returns (TransferFromResponse); - rpc OwnerOf(OwnerOfRequest) returns (OwnerOfResponse); -} - -message InitRequest{ - -} - -message Empty { - -} - -message TransferFromRequest { - bytes from =1; - bytes to=2; - bytes token_id = 3; -} - -message TransferFromResponse { - -} - -message OwnerOfRequest { - bytes token_id = 1; -} - -message OwnerOfResponse { - bytes owner =1; -} diff --git a/dan_layer/common_types/src/lib.rs b/dan_layer/common_types/src/lib.rs deleted file mode 100644 index 80f36717655..00000000000 --- a/dan_layer/common_types/src/lib.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -pub mod proto; -pub mod storage; - -mod template_id; - -pub use template_id::TemplateId; diff --git a/dan_layer/common_types/src/proto/mod.rs b/dan_layer/common_types/src/proto/mod.rs deleted file mode 100644 index 5573437383c..00000000000 --- a/dan_layer/common_types/src/proto/mod.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub mod tips { - pub mod tip002 { - include!(concat!(env!("OUT_DIR"), "/tari.dan.tips.tip002.rs")); - } - pub mod tip003 { - include!(concat!(env!("OUT_DIR"), "/tari.dan.tips.tip003.rs")); - } - pub mod tip004 { - include!(concat!(env!("OUT_DIR"), "/tari.dan.tips.tip004.rs")); - } - pub mod tip721 { - include!(concat!(env!("OUT_DIR"), "/tari.dan.tips.tip721.rs")); - } -} diff --git a/dan_layer/common_types/src/storage/mod.rs b/dan_layer/common_types/src/storage/mod.rs deleted file mode 100644 index 4d542cd2503..00000000000 --- a/dan_layer/common_types/src/storage/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -mod unit_of_work_tracker; - -pub use unit_of_work_tracker::UnitOfWorkTracker; diff --git a/dan_layer/common_types/src/storage/unit_of_work_tracker.rs b/dan_layer/common_types/src/storage/unit_of_work_tracker.rs deleted file mode 100644 index acdd3238db6..00000000000 --- a/dan_layer/common_types/src/storage/unit_of_work_tracker.rs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::sync::{ - atomic::{AtomicBool, Ordering}, - Arc, - RwLock, - RwLockReadGuard, - RwLockWriteGuard, -}; - -#[derive(Debug)] -pub struct UnitOfWorkTracker { - item: Arc>, - is_dirty: Arc, -} - -impl Clone for UnitOfWorkTracker { - fn clone(&self) -> Self { - Self { - item: self.item.clone(), - is_dirty: self.is_dirty.clone(), - } - } -} - -impl UnitOfWorkTracker { - pub fn new(item: TItem, is_dirty: bool) -> Self { - Self { - item: Arc::new(RwLock::new(item)), - is_dirty: Arc::new(AtomicBool::new(is_dirty)), - } - } - - pub fn get(&self) -> RwLockReadGuard { - self.item.read().unwrap() - } - - pub fn get_mut(&self) -> RwLockWriteGuard { - self.is_dirty.store(true, Ordering::SeqCst); - self.item.write().unwrap() - } - - pub fn is_dirty(&self) -> bool { - self.is_dirty.load(Ordering::SeqCst) - } -} diff --git a/dan_layer/common_types/src/template_id.rs b/dan_layer/common_types/src/template_id.rs deleted file mode 100644 index 8c2aedab86e..00000000000 --- a/dan_layer/common_types/src/template_id.rs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::{ - convert::TryFrom, - fmt::{Display, Formatter}, - str::FromStr, -}; - -#[derive(Copy, Clone, Debug)] -pub enum TemplateId { - Tip002 = 2, - Tip003 = 3, - Tip004 = 4, - Tip721 = 721, - EditableMetadata = 20, -} - -impl FromStr for TemplateId { - type Err = String; - - fn from_str(s: &str) -> Result { - match s { - "Tip002" => Ok(TemplateId::Tip002), - "Tip003" => Ok(TemplateId::Tip003), - "Tip004" => Ok(TemplateId::Tip004), - "Tip721" => Ok(TemplateId::Tip721), - "EditableMetadata" => Ok(TemplateId::EditableMetadata), - _ => { - println!("Unrecognised template"); - Err(format!("Unrecognised template ID '{}'", s)) - }, - } - } -} - -impl TryFrom for TemplateId { - type Error = String; - - fn try_from(value: u32) -> Result { - match value { - 2 => Ok(TemplateId::Tip002), - 3 => Ok(TemplateId::Tip003), - 4 => Ok(TemplateId::Tip004), - 721 => Ok(TemplateId::Tip721), - _ => Err(format!("Unknown value: {}", value)), - } - } -} - -impl TryFrom for TemplateId { - type Error = String; - - fn try_from(value: i32) -> Result { - u32::try_from(value) - .map_err(|_| { - format!( - "Could not convert to TemplateId because it was not a valid u32:{}", - value - ) - })? - .try_into() - } -} - -impl Display for TemplateId { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} diff --git a/dan_layer/core/Cargo.toml b/dan_layer/core/Cargo.toml deleted file mode 100644 index 0fa17ee9920..00000000000 --- a/dan_layer/core/Cargo.toml +++ /dev/null @@ -1,51 +0,0 @@ -[package] -name = "tari_dan_core" -version = "0.1.0" -edition = "2018" -license = "BSD-3-Clause" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -tari_common = { path = "../../common" } -tari_comms = { path = "../../comms/core" } -tari_comms_dht = { path = "../../comms/dht" } -tari_comms_rpc_macros = { path = "../../comms/rpc_macros" } -tari_crypto = { git = "https://github.com/tari-project/tari-crypto.git", tag = "v0.15.4" } -tari_mmr = { path = "../../base_layer/mmr" } -tari_p2p = { path = "../../base_layer/p2p" } -tari_service_framework = { path = "../../base_layer/service_framework" } -tari_shutdown = { path = "../../infrastructure/shutdown" } -tari_storage = { path = "../../infrastructure/storage" } -tari_core = {path = "../../base_layer/core"} -tari_dan_common_types = {path = "../common_types"} -tari_common_types = {path = "../../base_layer/common_types"} -tari_utilities = { git = "https://github.com/tari-project/tari_utilities.git", tag = "v0.4.5" } -tari_dan_engine = { path = "../engine"} - -anyhow = "1.0.53" -async-trait = "0.1.50" -blake2 = "0.9.2" -clap = "3.1.8" -digest = "0.9.0" -futures = { version = "^0.3.1" } -lmdb-zero = "0.4.4" -log = { version = "0.4.8", features = ["std"] } -num-derive = "0.3.3" -num-traits = "0.2.15" -prost = "0.9" -prost-types = "0.9" -rand = "0.8.4" -serde = "1.0.126" -thiserror = "^1.0.20" -tokio = { version="1.10", features = ["macros", "time"]} -tokio-stream = { version = "0.1.7", features = ["sync"] } -tonic = "0.6.2" - -serde_json = "1.0.64" - -[dev-dependencies] -tari_test_utils = { path="../../infrastructure/test_utils" } - -[build-dependencies] -tari_common = { path = "../../common", features = ["build"] } diff --git a/dan_layer/core/src/digital_assets_error.rs b/dan_layer/core/src/digital_assets_error.rs deleted file mode 100644 index bdd9bb435d6..00000000000 --- a/dan_layer/core/src/digital_assets_error.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use prost::DecodeError; -use tari_comms_dht::outbound::DhtOutboundError; -use tari_crypto::ristretto::RistrettoPublicKey; -use tari_dan_engine::state::error::StateStorageError; -use thiserror::Error; -use tokio::sync::mpsc::error::SendError; - -use crate::{ - models::{HotStuffMessage, ModelError, TariDanPayload}, - services::ValidatorNodeClientError, - storage::StorageError, - workers::StateSyncError, -}; - -#[derive(Debug, Error)] -pub enum DigitalAssetError { - #[error("Unknown method: {method_name}")] - _UnknownMethod { method_name: String }, - #[error("Missing argument at position {position} (name: {argument_name}")] - _MissingArgument { argument_name: String, position: usize }, - #[error("Invalid sig, TODO: fill in deets")] - InvalidSignature, - #[error("Peer sent an invalid message: {0}")] - InvalidPeerMessage(String), - #[error("Storage error: {0}")] - StorageError(#[from] StorageError), - #[error("Metadata was malformed: {0}")] - MalformedMetadata(String), - #[error("Could not convert between types:{0}")] - ConversionError(String), - #[error("Branched to an unexpected logic path, this is most likely due to a bug:{reason}")] - InvalidLogicPath { reason: String }, - #[error("Could not decode protobuf message for {message_type}:{source}")] - ProtoBufDecodeError { - source: prost::DecodeError, - message_type: String, - }, - #[error("Could not encode protobuf message for {message_type}:{source}")] - ProtoBufEncodeError { - source: prost::EncodeError, - message_type: String, - }, - #[error("Arithmetic overflow")] - Overflow, - #[error("Not enough funds")] - NotEnoughFunds, - #[error("Entity {entity}:{id} was not found")] - NotFound { entity: &'static str, id: String }, - #[error("Not authorised: {0}")] - NotAuthorised(String), - #[error("Database is missing or has not be created")] - MissingDatabase, - #[error("There was no committee for the asset")] - NoCommitteeForAsset, - #[error("None of the committee responded")] - NoResponsesFromCommittee, - #[error("Fatal error: {0}")] - FatalError(String), - #[error(transparent)] - ModelError(#[from] ModelError), - #[error("UTXO missing checkpoint data")] - UtxoNoCheckpointData, - #[error("Failed to synchronize state: {0}")] - StateSyncError(#[from] StateSyncError), - #[error("Validator node client error: {0}")] - ValidatorNodeClientError(#[from] ValidatorNodeClientError), - #[error("Peer did not send a quorum certificate in prepare phase")] - PreparePhaseNoQuorumCertificate, - #[error("Quorum certificate does not extend node")] - PreparePhaseCertificateDoesNotExtendNode, - #[error("Node not safe")] - PreparePhaseNodeNotSafe, - #[error("Unsupported template method {name}")] - TemplateUnsupportedMethod { name: String }, - #[error("Connection error: {0}")] - GrpcConnection(#[from] tonic::transport::Error), - #[error("GRPC error: {0}")] - GrpcStatus(#[from] tonic::Status), - #[error("DHT outbound error: `{0}`")] - DhtOutboundError(#[from] DhtOutboundError), - #[error("Failed to decode message: {0}")] - DecodeError(#[from] DecodeError), - #[error("Failed to send message: {0}")] - SendError(#[from] Box)>>), - #[error("Invalid committee public key hex")] - InvalidCommitteePublicKeyHex, - #[error("State storage error:{0}")] - StateStorageError(#[from] StateStorageError), -} - -impl From for DigitalAssetError { - fn from(err: lmdb_zero::Error) -> Self { - Self::StorageError(err.into()) - } -} diff --git a/dan_layer/core/src/helpers.rs b/dan_layer/core/src/helpers.rs deleted file mode 100644 index 6a318bb6f9a..00000000000 --- a/dan_layer/core/src/helpers.rs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{fmt, marker::PhantomData}; - -use serde::{de, Deserializer}; -use tari_utilities::hex::Hex; - -pub fn deserialize_from_hex<'de, D, T>(des: D) -> Result -where - D: Deserializer<'de>, - T: Hex, -{ - struct HexStringVisitor { - marker: PhantomData, - } - - impl<'de, K: Hex> de::Visitor<'de> for HexStringVisitor { - type Value = K; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a type in hex format") - } - - fn visit_str(self, v: &str) -> Result - where E: de::Error { - K::from_hex(v).map_err(E::custom) - } - } - - des.deserialize_str(HexStringVisitor { marker: PhantomData }) -} diff --git a/dan_layer/core/src/lib.rs b/dan_layer/core/src/lib.rs deleted file mode 100644 index d8cd0857d21..00000000000 --- a/dan_layer/core/src/lib.rs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#![allow(clippy::too_many_arguments)] -mod digital_assets_error; -pub use digital_assets_error::DigitalAssetError; - -mod helpers; -pub mod models; -pub mod services; -pub mod storage; -pub mod template_command; -pub mod templates; -pub mod types; -pub mod workers; diff --git a/dan_layer/core/src/models/asset_definition.rs b/dan_layer/core/src/models/asset_definition.rs deleted file mode 100644 index 990668b6cdb..00000000000 --- a/dan_layer/core/src/models/asset_definition.rs +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use serde::{self, Deserialize, Serialize}; -use tari_common_types::types::FixedHash; -use tari_core::transactions::transaction_components::TemplateParameter; -use tari_dan_engine::{ - function_definitions::{FlowFunctionDefinition, WasmFunctionDefinition}, - state::models::SchemaState, - wasm::WasmModuleDefinition, -}; - -use crate::helpers::deserialize_from_hex; - -#[derive(Deserialize, Clone, Debug)] -#[serde(default)] -pub struct AssetDefinition { - #[serde(deserialize_with = "deserialize_from_hex")] - pub contract_id: FixedHash, - // TODO: remove and read from base layer - pub committee: Vec, - pub phase_timeout: u64, - // TODO: Better name? lock time/peg time? (in number of blocks) - pub base_layer_confirmation_time: u64, - // TODO: remove - pub checkpoint_unique_id: Vec, - pub initial_state: InitialState, - pub template_parameters: Vec, - pub wasm_modules: Vec, - pub wasm_functions: Vec, - pub flow_functions: Vec, -} - -impl Default for AssetDefinition { - fn default() -> Self { - Self { - base_layer_confirmation_time: 5, - checkpoint_unique_id: vec![], - contract_id: Default::default(), - committee: vec![], - phase_timeout: 30, - initial_state: Default::default(), - template_parameters: vec![], - wasm_modules: vec![], - wasm_functions: vec![], - flow_functions: vec![], - } - } -} - -impl AssetDefinition { - pub fn initial_state(&self) -> &InitialState { - &self.initial_state - } -} - -#[derive(Serialize, Deserialize, Default, Clone, Debug)] -pub struct InitialState { - pub schemas: Vec, -} diff --git a/dan_layer/core/src/models/base_layer_metadata.rs b/dan_layer/core/src/models/base_layer_metadata.rs deleted file mode 100644 index ecbd4db3b88..00000000000 --- a/dan_layer/core/src/models/base_layer_metadata.rs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_common_types::types::FixedHash; - -pub struct BaseLayerMetadata { - pub height_of_longest_chain: u64, - pub tip_hash: FixedHash, -} diff --git a/dan_layer/core/src/models/base_layer_output.rs b/dan_layer/core/src/models/base_layer_output.rs deleted file mode 100644 index 6606f1eb627..00000000000 --- a/dan_layer/core/src/models/base_layer_output.rs +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -//! A trait to allow abstraction from a specific base layer output -use std::convert::TryFrom; - -use tari_common_types::types::{FixedHash, PublicKey}; -use tari_core::{ - chain_storage::UtxoMinedInfo, - transactions::transaction_components::{OutputFeatures, OutputType}, -}; - -use crate::{models::ModelError, DigitalAssetError}; - -#[derive(Debug)] -pub struct BaseLayerOutput { - pub features: OutputFeatures, - pub height: u64, -} - -impl BaseLayerOutput { - pub fn get_side_chain_committee(&self) -> Option<&[PublicKey]> { - self.features - .constitution_committee() - .map(|committee| committee.members()) - } - - pub fn get_backup_keys(&self) -> Option<&[PublicKey]> { - self.features.backup_keys().map(|keys| keys.members()) - } - - pub fn get_checkpoint_merkle_root(&self) -> Option { - self.features - .sidechain_features - .as_ref() - .and_then(|cp| cp.checkpoint.as_ref()) - .map(|cp| cp.merkle_root) - } - - pub fn get_parent_public_key(&self) -> Option<&PublicKey> { - self.features.parent_public_key.as_ref() - } - - pub fn contract_id(&self) -> Option { - self.features.contract_id() - } -} - -#[derive(Debug, Clone)] -pub struct CheckpointOutput { - pub output_type: OutputType, - pub contract_id: FixedHash, - pub merkle_root: FixedHash, -} - -impl TryFrom for CheckpointOutput { - type Error = ModelError; - - fn try_from(output: BaseLayerOutput) -> Result { - if output.features.output_type != OutputType::ContractCheckpoint { - return Err(ModelError::NotCheckpointOutput); - } - - let contract_id = output.contract_id().ok_or(ModelError::OutputMissingParentPublicKey)?; - - let merkle_root = output - .get_checkpoint_merkle_root() - .ok_or(ModelError::CheckpointOutputMissingCheckpointMerkleRoot)?; - - Ok(Self { - output_type: output.features.output_type, - contract_id, - merkle_root, - }) - } -} - -impl TryFrom for BaseLayerOutput { - type Error = DigitalAssetError; - - fn try_from(utxo: UtxoMinedInfo) -> Result { - let mined_height = utxo.mined_height; - let features = match utxo.output.as_transaction_output() { - Some(o) => o.features.clone(), - None => { - return Err(DigitalAssetError::ConversionError( - "Output was none/pruned or did not contain features".to_string(), - )) - }, - }; - - Ok(BaseLayerOutput { - features, - height: mined_height, - }) - } -} - -#[derive(Debug, Clone)] -pub struct CommitteeOutput { - pub flags: OutputType, - pub parent_public_key: PublicKey, - pub committee: Vec, -} - -impl TryFrom for CommitteeOutput { - type Error = ModelError; - - fn try_from(output: BaseLayerOutput) -> Result { - if output.features.output_type != OutputType::CommitteeDefinition { - return Err(ModelError::NotCommitteeDefinitionOutput); - } - - let parent_public_key = output - .get_parent_public_key() - .cloned() - .ok_or(ModelError::OutputMissingParentPublicKey)?; - - let committee = output - .get_side_chain_committee() - .ok_or(ModelError::CommitteeOutputMissingDefinition)?; - - Ok(Self { - flags: output.features.output_type, - parent_public_key, - committee: committee.into(), - }) - } -} diff --git a/dan_layer/core/src/models/committee.rs b/dan_layer/core/src/models/committee.rs deleted file mode 100644 index b65c68429a3..00000000000 --- a/dan_layer/core/src/models/committee.rs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::{models::ViewId, services::infrastructure_services::NodeAddressable}; - -#[derive(Clone)] -pub struct Committee { - // TODO: encapsulate - pub members: Vec, -} - -impl Committee { - pub fn new(members: Vec) -> Self { - Self { members } - } - - pub fn leader_for_view(&self, view_id: ViewId) -> &TAddr { - let pos = view_id.current_leader(self.members.len()); - &self.members[pos] - } - - pub fn consensus_threshold(&self) -> usize { - let len = self.members.len(); - let max_failures = (len - 1) / 3; - len - max_failures - } - - pub fn is_empty(&self) -> bool { - self.members.is_empty() - } - - pub fn len(&self) -> usize { - self.members.len() - } - - pub fn contains(&self, member: &TAddr) -> bool { - self.members.contains(member) - } -} - -impl IntoIterator for Committee { - type IntoIter = std::vec::IntoIter; - type Item = TAddr; - - fn into_iter(self) -> Self::IntoIter { - self.members.into_iter() - } -} diff --git a/dan_layer/core/src/models/domain_events/consensus_worker_domain_event.rs b/dan_layer/core/src/models/domain_events/consensus_worker_domain_event.rs deleted file mode 100644 index abeb9def29f..00000000000 --- a/dan_layer/core/src/models/domain_events/consensus_worker_domain_event.rs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{fmt, fmt::Formatter}; - -use crate::models::{ConsensusWorkerState, Event}; - -#[derive(Debug, Clone, PartialEq)] -pub enum ConsensusWorkerDomainEvent { - StateChanged { - from: ConsensusWorkerState, - to: ConsensusWorkerState, - }, -} - -impl Event for ConsensusWorkerDomainEvent {} - -impl fmt::Display for ConsensusWorkerDomainEvent { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - match self { - ConsensusWorkerDomainEvent::StateChanged { from: old, to: new } => { - write!(f, "State changed from {:?} to {:?}", old, new) - }, - } - } -} diff --git a/dan_layer/core/src/models/domain_events/mod.rs b/dan_layer/core/src/models/domain_events/mod.rs deleted file mode 100644 index dc47246b27c..00000000000 --- a/dan_layer/core/src/models/domain_events/mod.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -mod consensus_worker_domain_event; - -pub use consensus_worker_domain_event::ConsensusWorkerDomainEvent; diff --git a/dan_layer/core/src/models/error.rs b/dan_layer/core/src/models/error.rs deleted file mode 100644 index dfe99036aa2..00000000000 --- a/dan_layer/core/src/models/error.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#[derive(Debug, thiserror::Error)] -pub enum ModelError { - #[error("Invalid template id Number {value}")] - InvalidTemplateIdNumber { value: i64 }, - #[error("Failed to parse string: {details}")] - StringParseError { details: String }, - #[error("Output is missing parent public key")] - OutputMissingParentPublicKey, - #[error("Checkpoint output is missing checkpoint merkle root")] - CheckpointOutputMissingCheckpointMerkleRoot, - #[error("Checkpoint output is missing side chain committee")] - CheckpointOutputMissingSidechainCommittee, - #[error("Output is not flagged as a checkpoint output")] - NotCheckpointOutput, - #[error("Output is not flagged as a committee definition output")] - NotCommitteeDefinitionOutput, - #[error("Committee output is missing committee of public keys")] - CommitteeOutputMissingDefinition, -} diff --git a/dan_layer/core/src/models/hashing.rs b/dan_layer/core/src/models/hashing.rs deleted file mode 100644 index 7b30efefdd5..00000000000 --- a/dan_layer/core/src/models/hashing.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use digest::Digest; -use tari_crypto::{ - hash_domain, - hashing::{DomainSeparatedHasher, LengthExtensionAttackResistant}, -}; - -hash_domain!( - DanLayerCoreModelsDomain, - "com.tari.tari_project.dan_layer.core.models", - 1 -); - -pub(crate) const HOT_STUFF_MESSAGE_LABEL: &str = "hot_stuff_message"; -pub(crate) const TARI_DAN_PAYLOAD_LABEL: &str = "tari_dan_payload"; - -pub(crate) fn dan_layer_models_hasher( - label: &'static str, -) -> DomainSeparatedHasher { - DomainSeparatedHasher::::new_with_label(label) -} diff --git a/dan_layer/core/src/models/hot_stuff_message.rs b/dan_layer/core/src/models/hot_stuff_message.rs deleted file mode 100644 index 5ee81adce82..00000000000 --- a/dan_layer/core/src/models/hot_stuff_message.rs +++ /dev/null @@ -1,256 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_common_types::types::FixedHash; -use tari_core::transactions::transaction_components::SignerSignature; -use tari_crypto::hash::blake2::Blake256; - -use super::HOT_STUFF_MESSAGE_LABEL; -use crate::models::{ - dan_layer_models_hasher, - HotStuffMessageType, - HotStuffTreeNode, - Payload, - QuorumCertificate, - TreeNodeHash, - ValidatorSignature, - ViewId, -}; - -#[derive(Debug, Clone)] -pub struct HotStuffMessage { - view_number: ViewId, - message_type: HotStuffMessageType, - justify: Option, - node: Option>, - node_hash: Option, - partial_sig: Option, - checkpoint_signature: Option, - contract_id: FixedHash, -} - -impl HotStuffMessage { - pub fn new( - view_number: ViewId, - message_type: HotStuffMessageType, - justify: Option, - node: Option>, - node_hash: Option, - partial_sig: Option, - checkpoint_signature: Option, - contract_id: FixedHash, - ) -> Self { - Self { - view_number, - message_type, - justify, - node, - node_hash, - partial_sig, - checkpoint_signature, - contract_id, - } - } - - pub fn new_view(prepare_qc: QuorumCertificate, view_number: ViewId, contract_id: FixedHash) -> Self { - Self { - message_type: HotStuffMessageType::NewView, - view_number, - justify: Some(prepare_qc), - node: None, - partial_sig: None, - checkpoint_signature: None, - node_hash: None, - contract_id, - } - } - - pub fn prepare( - proposal: HotStuffTreeNode, - high_qc: Option, - view_number: ViewId, - contract_id: FixedHash, - ) -> Self { - Self { - message_type: HotStuffMessageType::Prepare, - node: Some(proposal), - justify: high_qc, - view_number, - partial_sig: None, - checkpoint_signature: None, - node_hash: None, - contract_id, - } - } - - pub fn vote_prepare(node_hash: TreeNodeHash, view_number: ViewId, contract_id: FixedHash) -> Self { - Self { - message_type: HotStuffMessageType::Prepare, - node_hash: Some(node_hash), - view_number, - node: None, - partial_sig: None, - checkpoint_signature: None, - justify: None, - contract_id, - } - } - - pub fn pre_commit( - node: Option>, - prepare_qc: Option, - view_number: ViewId, - contract_id: FixedHash, - ) -> Self { - Self { - message_type: HotStuffMessageType::PreCommit, - node, - justify: prepare_qc, - view_number, - node_hash: None, - checkpoint_signature: None, - partial_sig: None, - contract_id, - } - } - - pub fn vote_pre_commit(node_hash: TreeNodeHash, view_number: ViewId, contract_id: FixedHash) -> Self { - Self { - message_type: HotStuffMessageType::PreCommit, - node_hash: Some(node_hash), - view_number, - node: None, - partial_sig: None, - checkpoint_signature: None, - justify: None, - contract_id, - } - } - - pub fn commit( - node: Option>, - pre_commit_qc: Option, - view_number: ViewId, - contract_id: FixedHash, - ) -> Self { - Self { - message_type: HotStuffMessageType::Commit, - node, - justify: pre_commit_qc, - view_number, - partial_sig: None, - checkpoint_signature: None, - node_hash: None, - contract_id, - } - } - - pub fn vote_commit( - node_hash: TreeNodeHash, - view_number: ViewId, - contract_id: FixedHash, - checkpoint_signature: SignerSignature, - ) -> Self { - Self { - message_type: HotStuffMessageType::Commit, - node_hash: Some(node_hash), - view_number, - node: None, - partial_sig: None, - checkpoint_signature: Some(checkpoint_signature), - justify: None, - contract_id, - } - } - - pub fn decide( - node: Option>, - commit_qc: Option, - view_number: ViewId, - contract_id: FixedHash, - ) -> Self { - Self { - message_type: HotStuffMessageType::Decide, - node, - justify: commit_qc, - view_number, - partial_sig: None, - checkpoint_signature: None, - node_hash: None, - contract_id, - } - } - - pub fn create_signature_challenge(&self) -> Vec { - let mut b = dan_layer_models_hasher::(HOT_STUFF_MESSAGE_LABEL) - .chain(&[self.message_type.as_u8()]) - .chain(self.view_number.as_u64().to_le_bytes()); - if let Some(ref node) = self.node { - b = b.chain(node.calculate_hash().as_bytes()); - } else if let Some(ref node_hash) = self.node_hash { - b = b.chain(node_hash.as_bytes()); - } else { - } - b.finalize().as_ref().to_vec() - } - - pub fn view_number(&self) -> ViewId { - self.view_number - } - - pub fn contract_id(&self) -> &FixedHash { - &self.contract_id - } - - pub fn node(&self) -> Option<&HotStuffTreeNode> { - self.node.as_ref() - } - - pub fn node_hash(&self) -> Option<&TreeNodeHash> { - self.node_hash.as_ref() - } - - pub fn message_type(&self) -> HotStuffMessageType { - self.message_type - } - - pub fn justify(&self) -> Option<&QuorumCertificate> { - self.justify.as_ref() - } - - pub fn matches(&self, message_type: HotStuffMessageType, view_id: ViewId) -> bool { - // from hotstuf spec - self.message_type() == message_type && view_id == self.view_number() - } - - pub fn add_partial_sig(&mut self, signature: ValidatorSignature) { - self.partial_sig = Some(signature) - } - - pub fn partial_sig(&self) -> Option<&ValidatorSignature> { - self.partial_sig.as_ref() - } - - pub fn checkpoint_signature(&self) -> Option<&SignerSignature> { - self.checkpoint_signature.as_ref() - } -} diff --git a/dan_layer/core/src/models/hot_stuff_tree_node.rs b/dan_layer/core/src/models/hot_stuff_tree_node.rs deleted file mode 100644 index 2c0bdc08fb0..00000000000 --- a/dan_layer/core/src/models/hot_stuff_tree_node.rs +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use digest::{Digest, FixedOutput}; -use tari_crypto::hash::blake2::Blake256; -use tari_dan_engine::state::models::StateRoot; - -use crate::models::{Payload, TreeNodeHash}; - -#[derive(Debug, Clone)] -pub struct HotStuffTreeNode { - parent: TreeNodeHash, - payload: TPayload, - state_root: StateRoot, - hash: TreeNodeHash, - height: u32, -} - -impl HotStuffTreeNode { - pub fn new(parent: TreeNodeHash, payload: TPayload, state_root: StateRoot, height: u32) -> Self { - let mut s = HotStuffTreeNode { - parent, - payload, - state_root, - hash: TreeNodeHash::zero(), - height, - }; - s.hash = s.calculate_hash(); - s - } - - pub fn genesis(payload: TPayload, state_root: StateRoot) -> HotStuffTreeNode { - let mut s = Self { - parent: TreeNodeHash::zero(), - payload, - hash: TreeNodeHash::zero(), - state_root, - height: 0, - }; - s.hash = s.calculate_hash(); - s - } - - pub fn from_parent( - parent: TreeNodeHash, - payload: TPayload, - state_root: StateRoot, - height: u32, - ) -> HotStuffTreeNode { - Self::new(parent, payload, state_root, height) - } - - pub fn calculate_hash(&self) -> TreeNodeHash { - let result = Blake256::new() - .chain(self.parent.as_bytes()) - .chain(self.payload.consensus_hash()) - .chain(self.height.to_le_bytes()) - .chain(self.state_root.as_bytes()) - .finalize_fixed(); - result.into() - } - - pub fn hash(&self) -> &TreeNodeHash { - &self.hash - } - - pub fn parent(&self) -> &TreeNodeHash { - &self.parent - } - - pub fn payload(&self) -> &TPayload { - &self.payload - } - - pub fn state_root(&self) -> &StateRoot { - &self.state_root - } - - pub fn height(&self) -> u32 { - self.height - } -} - -impl PartialEq for HotStuffTreeNode { - fn eq(&self, other: &Self) -> bool { - self.hash.eq(&other.hash) - } -} diff --git a/dan_layer/core/src/models/instruction_id.rs b/dan_layer/core/src/models/instruction_id.rs deleted file mode 100644 index da48e51c534..00000000000 --- a/dan_layer/core/src/models/instruction_id.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// TODO: encapsulate -pub struct InstructionId(pub u64); diff --git a/dan_layer/core/src/models/instruction_set.rs b/dan_layer/core/src/models/instruction_set.rs deleted file mode 100644 index 1b0cab130f0..00000000000 --- a/dan_layer/core/src/models/instruction_set.rs +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{convert::TryFrom, hash::Hash, iter::FromIterator}; - -use tari_common_types::types::FixedHash; -use tari_crypto::hash::blake2::Blake256; -use tari_dan_engine::instructions::Instruction; -use tari_mmr::MerkleMountainRange; - -use crate::models::ConsensusHash; - -#[derive(PartialEq, Eq, Clone, Debug, Hash)] -pub struct InstructionSetHash(FixedHash); - -impl InstructionSetHash { - pub fn zero() -> InstructionSetHash { - Self(FixedHash::zero()) - } -} - -impl InstructionSetHash { - pub fn as_bytes(&self) -> &[u8] { - self.0.as_slice() - } -} - -impl From for InstructionSetHash { - fn from(hash: FixedHash) -> Self { - Self(hash) - } -} - -// TODO: Implement hash properly -#[allow(clippy::derive_hash_xor_eq)] -#[derive(Clone, Debug)] -pub struct InstructionSet { - hash: InstructionSetHash, - instructions: Vec, -} - -impl InstructionSet { - pub fn empty() -> Self { - Self::from_vec(vec![]) - } - - pub fn from_vec(instructions: Vec) -> Self { - let mut result = Self { - instructions, - hash: InstructionSetHash::zero(), - }; - result.hash = result.calculate_hash(); - result - } - - pub fn calculate_hash(&self) -> InstructionSetHash { - let mut mmr = MerkleMountainRange::::new(Vec::default()); - // assume instructions are sorted - for instruction in &self.instructions { - mmr.push(instruction.calculate_hash().to_vec()).unwrap(); - } - - FixedHash::try_from(mmr.get_merkle_root().unwrap()).unwrap().into() - } - - pub fn instructions(&self) -> &[Instruction] { - self.instructions.as_slice() - } -} - -impl FromIterator for InstructionSet { - fn from_iter>(iter: T) -> Self { - let instructions = iter.into_iter().collect(); - Self::from_vec(instructions) - } -} - -impl From> for InstructionSet { - fn from(instructions: Vec) -> Self { - Self::from_vec(instructions) - } -} - -impl ConsensusHash for InstructionSet { - fn consensus_hash(&self) -> &[u8] { - self.hash.as_bytes() - } -} - -impl IntoIterator for InstructionSet { - type IntoIter = as IntoIterator>::IntoIter; - type Item = Instruction; - - fn into_iter(self) -> Self::IntoIter { - self.instructions.into_iter() - } -} - -impl Extend for InstructionSet { - fn extend>(&mut self, iter: T) { - self.instructions.extend(iter); - self.hash = self.calculate_hash(); - } -} diff --git a/dan_layer/core/src/models/mod.rs b/dan_layer/core/src/models/mod.rs deleted file mode 100644 index 852a81b949b..00000000000 --- a/dan_layer/core/src/models/mod.rs +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{convert::TryFrom, fmt::Debug, hash::Hash}; - -mod asset_definition; -mod base_layer_metadata; -mod base_layer_output; -mod committee; -pub mod domain_events; -mod error; -mod hashing; -mod hot_stuff_message; -mod hot_stuff_tree_node; -mod instruction_set; -mod node; -mod payload; -mod quorum_certificate; -mod sidechain_block; -mod sidechain_metadata; -mod tari_dan_payload; -mod tree_node_hash; -mod view; -mod view_id; - -pub use asset_definition::{AssetDefinition, InitialState}; -pub use base_layer_metadata::BaseLayerMetadata; -pub use base_layer_output::{BaseLayerOutput, CheckpointOutput, CommitteeOutput}; -pub use committee::Committee; -pub use error::ModelError; -pub(crate) use hashing::{dan_layer_models_hasher, HOT_STUFF_MESSAGE_LABEL}; -pub use hot_stuff_message::HotStuffMessage; -pub use hot_stuff_tree_node::HotStuffTreeNode; -pub use instruction_set::InstructionSet; -pub use node::Node; -pub use payload::Payload; -pub use quorum_certificate::QuorumCertificate; -pub use sidechain_block::SideChainBlock; -pub use sidechain_metadata::SidechainMetadata; -pub use tari_dan_payload::{CheckpointData, TariDanPayload}; -pub use tree_node_hash::TreeNodeHash; -pub use view::View; -pub use view_id::ViewId; - -// TODO: encapsulate -pub struct InstructionCaller { - pub owner_token_id: TokenId, -} - -impl InstructionCaller { - pub fn _owner_token_id(&self) -> &TokenId { - &self.owner_token_id - } -} - -#[derive(Clone, Debug, Hash)] -pub struct TokenId(pub Vec); - -impl TokenId { - pub fn as_bytes(&self) -> &[u8] { - self.0.as_slice() - } -} - -impl AsRef<[u8]> for TokenId { - fn as_ref(&self) -> &[u8] { - self.as_bytes() - } -} - -#[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub enum HotStuffMessageType { - NewView, - Prepare, - PreCommit, - Commit, - Decide, - // Special type - Genesis, -} - -impl HotStuffMessageType { - pub fn as_u8(&self) -> u8 { - match self { - HotStuffMessageType::NewView => 1, - HotStuffMessageType::Prepare => 2, - HotStuffMessageType::PreCommit => 3, - HotStuffMessageType::Commit => 4, - HotStuffMessageType::Decide => 5, - HotStuffMessageType::Genesis => 255, - } - } -} - -impl TryFrom for HotStuffMessageType { - type Error = String; - - fn try_from(value: u8) -> Result { - match value { - 1 => Ok(HotStuffMessageType::NewView), - 2 => Ok(HotStuffMessageType::Prepare), - 3 => Ok(HotStuffMessageType::PreCommit), - 4 => Ok(HotStuffMessageType::Commit), - 5 => Ok(HotStuffMessageType::Decide), - 255 => Ok(HotStuffMessageType::Genesis), - _ => Err("Not a value message type".to_string()), - } - } -} - -pub trait ConsensusHash { - fn consensus_hash(&self) -> &[u8]; -} - -impl ConsensusHash for &str { - fn consensus_hash(&self) -> &[u8] { - self.as_bytes() - } -} - -impl ConsensusHash for String { - fn consensus_hash(&self) -> &[u8] { - self.as_bytes() - } -} - -pub trait Event: Clone + Send + Sync {} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ConsensusWorkerState { - Starting, - Synchronizing, - Prepare, - PreCommit, - Commit, - Decide, - NextView, - Idle, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ValidatorSignature {} - -impl ValidatorSignature { - pub fn from_bytes(_source: &[u8]) -> Self { - Self {} - } - - pub fn combine(&self, other: &ValidatorSignature) -> ValidatorSignature { - other.clone() - } - - pub fn to_bytes(&self) -> Vec { - vec![] - } -} - -#[derive(Copy, Clone, Debug)] -pub struct ChainHeight(u64); - -impl From for u64 { - fn from(c: ChainHeight) -> Self { - c.0 - } -} - -impl From for ChainHeight { - fn from(v: u64) -> Self { - ChainHeight(v) - } -} diff --git a/dan_layer/core/src/models/node.rs b/dan_layer/core/src/models/node.rs deleted file mode 100644 index 9d3767bcdef..00000000000 --- a/dan_layer/core/src/models/node.rs +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::{models::TreeNodeHash, storage::chain::DbNode}; - -#[derive(Debug, Clone, PartialEq)] -pub struct Node { - hash: TreeNodeHash, - parent: TreeNodeHash, - height: u32, - is_committed: bool, -} - -impl Node { - pub fn new(hash: TreeNodeHash, parent: TreeNodeHash, height: u32, is_committed: bool) -> Node { - Self { - hash, - parent, - height, - is_committed, - } - } - - pub fn hash(&self) -> &TreeNodeHash { - &self.hash - } - - pub fn parent(&self) -> &TreeNodeHash { - &self.parent - } - - pub fn height(&self) -> u32 { - self.height - } - - pub fn is_committed(&self) -> bool { - self.is_committed - } -} - -impl From for Node { - fn from(db_node: DbNode) -> Self { - Node::new(db_node.hash, db_node.parent, db_node.height, db_node.is_committed) - } -} diff --git a/dan_layer/core/src/models/payload.rs b/dan_layer/core/src/models/payload.rs deleted file mode 100644 index b0c4037ff42..00000000000 --- a/dan_layer/core/src/models/payload.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::fmt::Debug; - -use crate::models::ConsensusHash; - -pub trait Payload: Debug + Clone + Send + Sync + ConsensusHash {} - -impl Payload for &str {} - -impl Payload for String {} diff --git a/dan_layer/core/src/models/quorum_certificate.rs b/dan_layer/core/src/models/quorum_certificate.rs deleted file mode 100644 index ee929b00e5a..00000000000 --- a/dan_layer/core/src/models/quorum_certificate.rs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::{ - models::{HotStuffMessageType, TreeNodeHash, ValidatorSignature, ViewId}, - storage::chain::DbQc, -}; - -#[derive(Debug, Clone)] -pub struct QuorumCertificate { - message_type: HotStuffMessageType, - node_hash: TreeNodeHash, - view_number: ViewId, - signatures: Option, -} - -impl QuorumCertificate { - pub fn new( - message_type: HotStuffMessageType, - view_number: ViewId, - node_hash: TreeNodeHash, - signature: Option, - ) -> Self { - Self { - message_type, - node_hash, - view_number, - signatures: signature, - } - } - - pub fn genesis(node_hash: TreeNodeHash) -> Self { - Self { - message_type: HotStuffMessageType::Genesis, - node_hash, - view_number: 0.into(), - signatures: None, - } - } - - pub fn node_hash(&self) -> &TreeNodeHash { - &self.node_hash - } - - pub fn view_number(&self) -> ViewId { - self.view_number - } - - pub fn message_type(&self) -> HotStuffMessageType { - self.message_type - } - - pub fn signature(&self) -> Option<&ValidatorSignature> { - self.signatures.as_ref() - } - - pub fn combine_sig(&mut self, partial_sig: &ValidatorSignature) { - self.signatures = match &self.signatures { - None => Some(partial_sig.clone()), - Some(s) => Some(s.combine(partial_sig)), - }; - } - - pub fn matches(&self, message_type: HotStuffMessageType, view_id: ViewId) -> bool { - // from hotstuf spec - self.message_type() == message_type && view_id == self.view_number() - } -} - -impl From for QuorumCertificate { - fn from(rec: DbQc) -> Self { - Self { - message_type: rec.message_type, - node_hash: rec.node_hash, - view_number: rec.view_number, - signatures: rec.signature, - } - } -} diff --git a/dan_layer/core/src/models/replica_info.rs b/dan_layer/core/src/models/replica_info.rs deleted file mode 100644 index 3d09e1fc85f..00000000000 --- a/dan_layer/core/src/models/replica_info.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub struct ReplicaInfo {} diff --git a/dan_layer/core/src/models/sidechain_block.rs b/dan_layer/core/src/models/sidechain_block.rs deleted file mode 100644 index 8dca014b8c5..00000000000 --- a/dan_layer/core/src/models/sidechain_block.rs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::models::{InstructionSet, Node}; - -#[derive(Debug)] -pub struct SideChainBlock { - node: Node, - instructions: InstructionSet, -} - -impl SideChainBlock { - pub fn new(node: Node, instructions: InstructionSet) -> Self { - Self { node, instructions } - } - - pub fn node(&self) -> &Node { - &self.node - } - - pub fn instructions(&self) -> &InstructionSet { - &self.instructions - } - - pub fn destruct(self) -> (Node, InstructionSet) { - (self.node, self.instructions) - } -} diff --git a/dan_layer/core/src/models/sidechain_metadata.rs b/dan_layer/core/src/models/sidechain_metadata.rs deleted file mode 100644 index 3ba1b895f43..00000000000 --- a/dan_layer/core/src/models/sidechain_metadata.rs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_common_types::types::PublicKey; - -use crate::models::{ChainHeight, TreeNodeHash}; - -pub struct SidechainMetadata { - asset_public_key: PublicKey, - committed_height: ChainHeight, - committed_hash: TreeNodeHash, -} - -impl SidechainMetadata { - pub fn new(asset_public_key: PublicKey, committed_height: ChainHeight, committed_hash: TreeNodeHash) -> Self { - Self { - asset_public_key, - committed_hash, - committed_height, - } - } - - pub fn asset_public_key(&self) -> &PublicKey { - &self.asset_public_key - } - - pub fn committed_height(&self) -> ChainHeight { - self.committed_height - } - - pub fn committed_hash(&self) -> &TreeNodeHash { - &self.committed_hash - } -} diff --git a/dan_layer/core/src/models/tari_dan_payload.rs b/dan_layer/core/src/models/tari_dan_payload.rs deleted file mode 100644 index c4567c47022..00000000000 --- a/dan_layer/core/src/models/tari_dan_payload.rs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::fmt::Debug; - -use tari_common_types::types::FixedHash; -use tari_crypto::hash::blake2::Blake256; -use tari_dan_engine::instructions::Instruction; - -use super::{dan_layer_models_hasher, hashing::TARI_DAN_PAYLOAD_LABEL}; -use crate::models::{ConsensusHash, InstructionSet, Payload}; - -#[derive(Debug, Clone)] -pub struct TariDanPayload { - hash: FixedHash, - instruction_set: InstructionSet, - checkpoint: Option, -} - -impl TariDanPayload { - pub fn new(instruction_set: InstructionSet, checkpoint: Option) -> Self { - let mut result = Self { - hash: FixedHash::zero(), - instruction_set, - checkpoint, - }; - result.hash = result.calculate_hash(); - result - } - - pub fn destruct(self) -> (InstructionSet, Option) { - (self.instruction_set, self.checkpoint) - } - - pub fn instructions(&self) -> &[Instruction] { - self.instruction_set.instructions() - } - - fn calculate_hash(&self) -> FixedHash { - let result = - dan_layer_models_hasher::(TARI_DAN_PAYLOAD_LABEL).chain(self.instruction_set.consensus_hash()); - - let mut out = [0u8; 32]; - - let result = if let Some(ref ck) = self.checkpoint { - result.chain(ck.consensus_hash()).finalize() - } else { - result.finalize() - }; - - out.copy_from_slice(result.as_ref()); - out.into() - } -} - -impl ConsensusHash for TariDanPayload { - fn consensus_hash(&self) -> &[u8] { - self.hash.as_slice() - } -} - -impl Payload for TariDanPayload {} - -#[derive(Debug, Clone, Default)] -pub struct CheckpointData { - hash: FixedHash, -} - -impl ConsensusHash for CheckpointData { - fn consensus_hash(&self) -> &[u8] { - self.hash.as_slice() - } -} diff --git a/dan_layer/core/src/models/tree_node_hash.rs b/dan_layer/core/src/models/tree_node_hash.rs deleted file mode 100644 index ae3aa15088c..00000000000 --- a/dan_layer/core/src/models/tree_node_hash.rs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - convert::TryFrom, - fmt::{Display, Formatter}, -}; - -use digest::{consts::U32, generic_array}; -use tari_common_types::types::{FixedHash, FixedHashSizeError}; -use tari_utilities::hex::{Hex, HexError}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct TreeNodeHash(FixedHash); - -impl TreeNodeHash { - pub fn zero() -> Self { - Self(FixedHash::zero()) - } - - pub fn as_bytes(&self) -> &[u8] { - self.0.as_slice() - } -} - -impl From<[u8; FixedHash::byte_size()]> for TreeNodeHash { - fn from(hash: [u8; FixedHash::byte_size()]) -> Self { - Self(hash.into()) - } -} - -impl From> for TreeNodeHash { - fn from(hash: digest::generic_array::GenericArray) -> Self { - Self(hash.into()) - } -} - -impl TryFrom> for TreeNodeHash { - type Error = FixedHashSizeError; - - fn try_from(value: Vec) -> Result { - let hash = FixedHash::try_from(value)?; - Ok(Self(hash)) - } -} - -impl Hex for TreeNodeHash { - fn from_hex(hex: &str) -> Result - where Self: Sized { - let hash = FixedHash::from_hex(hex)?; - Ok(Self(hash)) - } - - fn to_hex(&self) -> String { - self.0.to_hex() - } -} - -impl Display for TreeNodeHash { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.to_hex()) - } -} diff --git a/dan_layer/core/src/models/view.rs b/dan_layer/core/src/models/view.rs deleted file mode 100644 index c57c85e9b12..00000000000 --- a/dan_layer/core/src/models/view.rs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::fmt::{Display, Formatter}; - -use crate::models::ViewId; - -// TODO: Encapsulate -#[derive(Clone)] -pub struct View { - pub view_id: ViewId, - pub is_leader: bool, -} - -impl View { - pub fn is_leader(&self) -> bool { - self.is_leader - } - - pub fn view_id(&self) -> ViewId { - self.view_id - } -} - -impl Display for View { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "View(Id: {}, leader: {})", self.view_id.as_u64(), self.is_leader) - } -} diff --git a/dan_layer/core/src/models/view_id.rs b/dan_layer/core/src/models/view_id.rs deleted file mode 100644 index 234990c7779..00000000000 --- a/dan_layer/core/src/models/view_id.rs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - cmp::Ordering, - fmt::{self, Display}, - ops::{Add, Sub}, -}; - -#[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub struct ViewId(pub u64); - -impl ViewId { - pub fn current_leader(&self, committee_size: usize) -> usize { - #[allow(clippy::cast_possible_truncation)] - let view_id = self.0 as usize; - if committee_size == 0 { - 0 - } else { - view_id % committee_size - } - } - - pub fn is_genesis(&self) -> bool { - self.0 == 0 - } - - pub fn next(&self) -> ViewId { - ViewId(self.0.wrapping_add(1)) - } - - pub fn as_u64(&self) -> u64 { - self.0 - } - - pub fn saturating_sub(self, other: ViewId) -> ViewId { - self.0.saturating_sub(other.0).into() - } -} - -impl PartialOrd for ViewId { - fn partial_cmp(&self, other: &Self) -> Option { - self.0.partial_cmp(&other.0) - } -} - -impl From for ViewId { - fn from(v: u64) -> Self { - Self(v) - } -} - -impl Display for ViewId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "View({})", self.0) - } -} - -impl Add for ViewId { - type Output = ViewId; - - fn add(self, rhs: Self) -> Self::Output { - ViewId(self.0 + rhs.0) - } -} - -impl Sub for ViewId { - type Output = ViewId; - - fn sub(self, rhs: Self) -> Self::Output { - ViewId(self.0 - rhs.0) - } -} diff --git a/dan_layer/core/src/services/acceptance_manager.rs b/dan_layer/core/src/services/acceptance_manager.rs deleted file mode 100644 index f534515c777..00000000000 --- a/dan_layer/core/src/services/acceptance_manager.rs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use async_trait::async_trait; -use tari_common_types::types::{Commitment, FixedHash}; -use tari_comms::NodeIdentity; -use tari_core::{ - chain_storage::UtxoMinedInfo, - transactions::transaction_components::{ - ContractAcceptanceChallenge, - ContractUpdateProposalAcceptanceChallenge, - OutputType, - SignerSignature, - TransactionOutput, - }, -}; -use tari_utilities::hex::Hex; - -use super::BaseNodeClient; -use crate::{services::wallet_client::WalletClient, DigitalAssetError}; - -#[async_trait] -pub trait AcceptanceManager: Send + Sync { - async fn publish_constitution_acceptance( - &mut self, - node_identity: &NodeIdentity, - contract_id: &FixedHash, - ) -> Result; - - async fn publish_proposal_acceptance( - &mut self, - node_identity: &NodeIdentity, - contract_id: &FixedHash, - proposal_id: u64, - ) -> Result; -} - -#[derive(Clone)] -pub struct ConcreteAcceptanceManager { - wallet: TWallet, - base_node: TBaseNode, -} - -impl ConcreteAcceptanceManager { - pub fn new(wallet: TWallet, base_node: TBaseNode) -> Self { - Self { wallet, base_node } - } -} - -#[async_trait] -impl AcceptanceManager - for ConcreteAcceptanceManager -{ - async fn publish_constitution_acceptance( - &mut self, - node_identity: &NodeIdentity, - contract_id: &FixedHash, - ) -> Result { - let public_key = node_identity.public_key(); - - // build the acceptance signature - let secret_key = node_identity.secret_key(); - let constitution_commitment = self.fetch_constitution_commitment(contract_id).await?; - let challenge = ContractAcceptanceChallenge::new(&constitution_commitment, contract_id); - let signer_signature = SignerSignature::sign(secret_key, challenge); - - // publish the acceptance - self.wallet - .submit_contract_acceptance(contract_id, public_key, signer_signature.signature()) - .await - } - - async fn publish_proposal_acceptance( - &mut self, - node_identity: &NodeIdentity, - contract_id: &FixedHash, - proposal_id: u64, - ) -> Result { - let public_key = node_identity.public_key(); - - // build the acceptance signature - let secret_key = node_identity.secret_key(); - let proposal_commitment = self.fetch_proposal_commitment(contract_id, proposal_id).await?; - let challenge = ContractUpdateProposalAcceptanceChallenge::new(&proposal_commitment, contract_id, proposal_id); - let signer_signature = SignerSignature::sign(secret_key, challenge); - - // publish the acceptance - self.wallet - .submit_contract_update_proposal_acceptance( - contract_id, - proposal_id, - public_key, - signer_signature.signature(), - ) - .await - } -} - -impl - ConcreteAcceptanceManager -{ - async fn fetch_constitution_commitment( - &mut self, - contract_id: &FixedHash, - ) -> Result { - let outputs: Vec = self - .base_node - .get_current_contract_outputs(0, *contract_id, OutputType::ContractConstitution) - .await?; - let transaction_outputs: Vec = outputs - .into_iter() - .filter_map(|utxo| utxo.output.into_unpruned_output()) - .collect(); - - if transaction_outputs.is_empty() { - return Err(DigitalAssetError::NotFound { - entity: "constitution", - id: contract_id.to_hex(), - }); - } - let constitution_commitment = transaction_outputs[0].commitment(); - - Ok(constitution_commitment.clone()) - } - - async fn fetch_proposal_commitment( - &mut self, - contract_id: &FixedHash, - proposal_id: u64, - ) -> Result { - let outputs: Vec = self - .base_node - .get_current_contract_outputs(0, *contract_id, OutputType::ContractConstitutionProposal) - .await?; - let transaction_outputs: Vec = outputs - .into_iter() - .filter_map(|utxo| utxo.output.into_unpruned_output()) - .filter(|output| output.features.contains_sidechain_proposal(contract_id, proposal_id)) - .collect(); - - if transaction_outputs.is_empty() { - return Err(DigitalAssetError::NotFound { - entity: "update proposal", - id: contract_id.to_hex(), - }); - } - let proposal_commitment = transaction_outputs[0].commitment(); - - Ok(proposal_commitment.clone()) - } -} diff --git a/dan_layer/core/src/services/asset_processor.rs b/dan_layer/core/src/services/asset_processor.rs deleted file mode 100644 index 918c7e28a11..00000000000 --- a/dan_layer/core/src/services/asset_processor.rs +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::convert::TryInto; - -use tari_core::transactions::transaction_components::TemplateParameter; -use tari_dan_engine::{ - flow::FlowFactory, - instructions::Instruction, - state::{StateDbUnitOfWork, StateDbUnitOfWorkReader}, - wasm::WasmModuleFactory, -}; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::{AssetDefinition, InstructionSet}, - template_command::ExecutionResult, - templates::{tip002_template, tip004_template, tip721_template}, -}; - -pub trait AssetProcessor: Sync + Send + 'static { - // purposefully made sync, because instructions should be run in order, and complete before the - // next one starts. There may be a better way to enforce this though... - fn execute_instruction( - &self, - instruction: &Instruction, - db: &mut TUnitOfWork, - ) -> Result<(), DigitalAssetError>; - - fn invoke_read_method( - &self, - instruction: &Instruction, - state_db: &TUnitOfWorkReader, - ) -> Result>, DigitalAssetError>; -} - -#[derive(Default, Clone)] -pub struct ConcreteAssetProcessor { - _asset_definition: AssetDefinition, - template_factory: TemplateFactory, - _wasm_factory: WasmModuleFactory, - _function_interface: FunctionInterface, - _flow_factory: FlowFactory, -} - -impl ConcreteAssetProcessor { - pub fn new(asset_definition: AssetDefinition) -> Self { - Self { - _wasm_factory: WasmModuleFactory::new(&asset_definition.wasm_modules, &asset_definition.wasm_functions), - _flow_factory: FlowFactory::new(&asset_definition.flow_functions), - _asset_definition: asset_definition, - template_factory: Default::default(), - _function_interface: FunctionInterface {}, - } - } -} - -impl AssetProcessor for ConcreteAssetProcessor { - fn execute_instruction( - &self, - instruction: &Instruction, - state_db: &mut TUnitOfWork, - ) -> Result<(), DigitalAssetError> { - self.template_factory.invoke_write_method(instruction, state_db) - } - - fn invoke_read_method( - &self, - instruction: &Instruction, - state_db: &TUnitOfWork, - ) -> Result>, DigitalAssetError> { - self.template_factory.invoke_read_method(instruction, state_db) - } -} - -#[derive(Clone, Default)] -pub struct FunctionInterface {} - -// impl FunctionInterface { -// #[allow(dead_code)] -// fn find_executor(&self, instruction: &Instruction) -> Result { -// match instruction.template_id() { -// // TODO: Put these back -// // TemplateId::Tip6000 => Ok(InstructionExecutor::WasmModule { -// // name: instruction.method().to_string(), -// // }), -// // TemplateId::Tip7000 => Ok(InstructionExecutor::Flow { -// // name: instruction.method().to_string(), -// // }), -// _ => Ok(InstructionExecutor::Template { -// template_id: instruction.template_id(), -// }), -// } -// } -// } -// -// pub enum InstructionExecutor { -// WasmModule { name: String }, -// Template { template_id: TemplateId }, -// Flow { name: String }, -// } - -#[derive(Default, Clone)] -pub struct TemplateFactory {} - -impl TemplateFactory { - pub fn initial_instructions(&self, template_param: &TemplateParameter) -> InstructionSet { - use tari_dan_common_types::TemplateId::{EditableMetadata, Tip002, Tip003, Tip004, Tip721}; - // TODO: We may want to use the TemplateId type, so that we know it is known/valid - let template_id = template_param.template_id.try_into().unwrap(); - match template_id { - Tip002 => tip002_template::initial_instructions(template_param), - Tip003 => todo!(), - Tip004 => tip004_template::initial_instructions(template_param), - Tip721 => tip721_template::initial_instructions(template_param), - EditableMetadata => { - todo!() - }, - } - } - - pub fn invoke_read_method( - &self, - instruction: &Instruction, - state_db: &TUnitOfWork, - ) -> Result>, DigitalAssetError> { - use tari_dan_common_types::TemplateId::{EditableMetadata, Tip002, Tip003, Tip004, Tip721}; - match instruction.template_id() { - Tip002 => tip002_template::invoke_read_method(instruction.method(), instruction.args(), state_db), - Tip003 => todo!(), - Tip004 => tip004_template::invoke_read_method(instruction.method(), instruction.args(), state_db), - Tip721 => tip721_template::invoke_read_method(instruction.method(), instruction.args(), state_db), - EditableMetadata => { - todo!() - }, - } - } - - pub fn invoke_write_method( - &self, - instruction: &Instruction, - state_db: &mut TUnitOfWork, - ) -> Result<(), DigitalAssetError> { - use tari_dan_common_types::TemplateId::{EditableMetadata, Tip002, Tip003, Tip004, Tip721}; - match instruction.template_id() { - Tip002 => tip002_template::invoke_write_method(instruction.method(), instruction.args(), state_db), - Tip003 => todo!(), - Tip004 => tip004_template::invoke_write_method(instruction.method(), instruction.args(), state_db), - Tip721 => tip721_template::invoke_write_method(instruction.method(), instruction.args(), state_db), - EditableMetadata => { - todo!() - }, - } - } -} - -pub trait InstructionLog { - fn store(&mut self, hash: Vec, result: ExecutionResult); -} - -#[derive(Default)] -pub struct MemoryInstructionLog { - log: Vec<(Vec, ExecutionResult)>, -} - -impl InstructionLog for MemoryInstructionLog { - fn store(&mut self, hash: Vec, result: ExecutionResult) { - self.log.push((hash, result)) - } -} diff --git a/dan_layer/core/src/services/asset_proxy.rs b/dan_layer/core/src/services/asset_proxy.rs deleted file mode 100644 index 3065ff3b5c3..00000000000 --- a/dan_layer/core/src/services/asset_proxy.rs +++ /dev/null @@ -1,287 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::convert::TryFrom; - -use async_trait::async_trait; -use futures::stream::FuturesUnordered; -use log::*; -use tari_common_types::types::{FixedHash, PublicKey}; -use tari_core::transactions::transaction_components::OutputType; -use tari_dan_common_types::TemplateId; -use tari_dan_engine::instructions::Instruction; -use tari_utilities::hex::Hex; -use tokio_stream::StreamExt; - -use crate::{ - models::BaseLayerOutput, - services::{ - validator_node_rpc_client::ValidatorNodeRpcClient, - BaseNodeClient, - MempoolService, - ServiceSpecification, - ValidatorNodeClientFactory, - }, - storage::DbFactory, - DigitalAssetError, -}; - -const LOG_TARGET: &str = "tari::dan_layer::core::services::asset_proxy"; - -#[async_trait] -pub trait AssetProxy: Send + Sync { - async fn invoke_method( - &self, - contract_id: &FixedHash, - template_id: TemplateId, - method: String, - args: Vec, - sender: PublicKey, - ) -> Result<(), DigitalAssetError>; - - async fn invoke_read_method( - &self, - contract_id: &FixedHash, - template_id: TemplateId, - method: String, - args: Vec, - sender: PublicKey, - ) -> Result>, DigitalAssetError>; -} - -enum InvokeType { - InvokeReadMethod, - InvokeMethod, -} - -#[derive(Clone)] -pub struct ConcreteAssetProxy { - base_node_client: TServiceSpecification::BaseNodeClient, - validator_node_client_factory: TServiceSpecification::ValidatorNodeClientFactory, - max_clients_to_ask: usize, - mempool: TServiceSpecification::MempoolService, - db_factory: TServiceSpecification::DbFactory, -} - -impl> ConcreteAssetProxy { - pub fn new( - base_node_client: TServiceSpecification::BaseNodeClient, - validator_node_client_factory: TServiceSpecification::ValidatorNodeClientFactory, - max_clients_to_ask: usize, - mempool: TServiceSpecification::MempoolService, - db_factory: TServiceSpecification::DbFactory, - ) -> Self { - Self { - base_node_client, - validator_node_client_factory, - max_clients_to_ask, - mempool, - db_factory, - } - } - - async fn forward_invoke_read_to_node( - &self, - member: &TServiceSpecification::Addr, - contract_id: FixedHash, - template_id: TemplateId, - method: String, - args: Vec, - sender: PublicKey, - ) -> Result>, DigitalAssetError> { - let mut client = self.validator_node_client_factory.create_client(member); - let resp = client - .invoke_read_method(&contract_id, template_id, method, args, sender) - .await?; - Ok(resp) - } - - async fn forward_invoke_to_node( - &self, - member: &TServiceSpecification::Addr, - contract_id: FixedHash, - template_id: TemplateId, - method: String, - args: Vec, - sender: PublicKey, - ) -> Result>, DigitalAssetError> { - debug!(target: LOG_TARGET, "Forwarding '{}' instruction to {}", member, method); - let mut client = self.validator_node_client_factory.create_client(member); - let resp = client - .invoke_method(&contract_id, template_id, method, args, sender) - .await?; - Ok(resp) - } - - #[allow(clippy::for_loops_over_fallibles)] - async fn forward_to_committee( - &self, - contract_id: FixedHash, - invoke_type: InvokeType, - template_id: TemplateId, - method: String, - args: Vec, - sender: PublicKey, - ) -> Result>, DigitalAssetError> { - let mut base_node_client = self.base_node_client.clone(); - let tip = base_node_client.get_tip_info().await?; - let mut outputs = base_node_client - .get_current_contract_outputs( - tip.height_of_longest_chain, - contract_id, - OutputType::ContractConstitution, - ) - .await?; - - let constitution = match outputs.pop() { - Some(chk) => BaseLayerOutput::try_from(chk)?, - None => { - return Err(DigitalAssetError::NotFound { - entity: "checkpoint", - id: contract_id.to_hex(), - }) - }, - }; - - let committee = constitution - .get_side_chain_committee() - .ok_or(DigitalAssetError::NoCommitteeForAsset)?; - - debug!( - target: LOG_TARGET, - "Found {} committee member(s): {}", - committee.len(), - committee.iter().map(ToString::to_string).collect::>().join(", ") - ); - - match invoke_type { - InvokeType::InvokeReadMethod => { - let mut tasks = FuturesUnordered::new(); - for member in committee.iter().take(self.max_clients_to_ask) { - tasks.push(self.forward_invoke_read_to_node( - member, - contract_id, - template_id, - method.clone(), - args.clone(), - sender.clone(), - )); - } - - for result in tasks.next().await { - match result { - Ok(data) => return Ok(data), - Err(err) => { - error!(target: LOG_TARGET, "Committee member responded with error:{}", err); - }, - } - } - }, - InvokeType::InvokeMethod => { - let mut tasks = FuturesUnordered::new(); - for member in committee.iter().take(self.max_clients_to_ask) { - tasks.push(self.forward_invoke_to_node( - member, - contract_id, - template_id, - method.clone(), - args.clone(), - sender.clone(), - )); - } - - for result in tasks.next().await { - match result { - Ok(data) => return Ok(data), - Err(err) => { - error!(target: LOG_TARGET, "Committee member responded with error:{}", err); - }, - } - } - }, - }; - - Err(DigitalAssetError::NoResponsesFromCommittee) - } -} - -#[async_trait] -impl> AssetProxy - for ConcreteAssetProxy -{ - async fn invoke_method( - &self, - contract_id: &FixedHash, - template_id: TemplateId, - method: String, - args: Vec, - sender: PublicKey, - ) -> Result<(), DigitalAssetError> { - // check if we are processing this asset - if self.db_factory.get_state_db(contract_id)?.is_some() { - let instruction = Instruction::new( - template_id, - method.clone(), - args.clone(), - sender.clone(), /* TokenId(request.token_id.clone()), - * TODO: put signature in here - * ComSig::default() - * create_com_sig_from_bytes(&request.signature) - * .map_err(|err| Status::invalid_argument("signature was not a valid - * comsig"))?, */ - ); - let mut mempool = self.mempool.clone(); - mempool.submit_instruction(instruction).await - } else { - let _result = self - .forward_to_committee( - *contract_id, - InvokeType::InvokeMethod, - template_id, - method, - args, - sender, - ) - .await?; - Ok(()) - } - } - - async fn invoke_read_method( - &self, - contract_id: &FixedHash, - template_id: TemplateId, - method: String, - args: Vec, - sender: PublicKey, - ) -> Result>, DigitalAssetError> { - self.forward_to_committee( - *contract_id, - InvokeType::InvokeReadMethod, - template_id, - method, - args, - sender, - ) - .await - } -} diff --git a/dan_layer/core/src/services/base_node_client.rs b/dan_layer/core/src/services/base_node_client.rs deleted file mode 100644 index 0b6caeb92db..00000000000 --- a/dan_layer/core/src/services/base_node_client.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use async_trait::async_trait; -use tari_common_types::types::{FixedHash, PublicKey}; -use tari_core::{chain_storage::UtxoMinedInfo, transactions::transaction_components::OutputType}; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::{BaseLayerMetadata, BaseLayerOutput}, -}; - -#[async_trait] -pub trait BaseNodeClient: Send + Sync { - async fn get_tip_info(&mut self) -> Result; - - async fn get_current_contract_outputs( - &mut self, - height: u64, - contract_id: FixedHash, - output_type: OutputType, - ) -> Result, DigitalAssetError>; - - async fn get_constitutions( - &mut self, - start_block_hash: Option, - dan_node_public_key: &PublicKey, - ) -> Result, DigitalAssetError>; - - async fn check_if_in_committee( - &mut self, - asset_public_key: PublicKey, - dan_node_public_key: PublicKey, - ) -> Result<(bool, u64), DigitalAssetError>; - - async fn get_asset_registration( - &mut self, - asset_public_key: PublicKey, - ) -> Result, DigitalAssetError>; -} diff --git a/dan_layer/core/src/services/checkpoint_manager.rs b/dan_layer/core/src/services/checkpoint_manager.rs deleted file mode 100644 index 854672e9fec..00000000000 --- a/dan_layer/core/src/services/checkpoint_manager.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use async_trait::async_trait; -use log::*; -use tari_core::transactions::transaction_components::SignerSignature; -use tari_dan_engine::state::models::StateRoot; - -use crate::{models::AssetDefinition, services::wallet_client::WalletClient, DigitalAssetError}; - -const LOG_TARGET: &str = "tari::dan::checkpoint_manager"; - -#[async_trait] -pub trait CheckpointManager { - async fn create_checkpoint( - &mut self, - checkpoint_number: u64, - state_root: StateRoot, - signature: &[SignerSignature], - ) -> Result<(), DigitalAssetError>; -} - -#[derive(Default)] -pub struct ConcreteCheckpointManager { - asset_definition: AssetDefinition, - wallet: TWallet, -} - -impl ConcreteCheckpointManager { - pub fn new(asset_definition: AssetDefinition, wallet: TWallet) -> Self { - Self { - asset_definition, - wallet, - } - } -} - -#[async_trait] -impl CheckpointManager for ConcreteCheckpointManager { - async fn create_checkpoint( - &mut self, - checkpoint_number: u64, - state_root: StateRoot, - signatures: &[SignerSignature], - ) -> Result<(), DigitalAssetError> { - info!( - target: LOG_TARGET, - "✅ Creating checkpoint #{} for contract {}", checkpoint_number, self.asset_definition.contract_id - ); - - self.wallet - .create_new_checkpoint( - &self.asset_definition.contract_id, - &state_root, - checkpoint_number, - signatures, - ) - .await?; - Ok(()) - } -} diff --git a/dan_layer/core/src/services/committee_manager.rs b/dan_layer/core/src/services/committee_manager.rs deleted file mode 100644 index 129b345343b..00000000000 --- a/dan_layer/core/src/services/committee_manager.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_common_types::types::PublicKey; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::{BaseLayerOutput, Committee}, - services::infrastructure_services::NodeAddressable, -}; - -pub trait CommitteeManager { - fn current_committee(&self) -> Result<&Committee, DigitalAssetError>; - - fn read_from_constitution(&mut self, output: BaseLayerOutput) -> Result<(), DigitalAssetError>; -} - -pub struct ConcreteCommitteeManager { - committee: Committee, -} - -impl ConcreteCommitteeManager { - pub fn new(committee: Committee) -> Self { - Self { committee } - } -} - -impl CommitteeManager for ConcreteCommitteeManager { - fn current_committee(&self) -> Result<&Committee, DigitalAssetError> { - Ok(&self.committee) - } - - fn read_from_constitution(&mut self, output: BaseLayerOutput) -> Result<(), DigitalAssetError> { - // TODO: better error - let committee = output.get_side_chain_committee().unwrap(); - self.committee = Committee::new(committee.to_vec()); - Ok(()) - } -} diff --git a/dan_layer/core/src/services/events_publisher.rs b/dan_layer/core/src/services/events_publisher.rs deleted file mode 100644 index 866a5af2cbb..00000000000 --- a/dan_layer/core/src/services/events_publisher.rs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - fmt::{Debug, Display}, - marker::PhantomData, -}; - -use log::*; - -use crate::models::Event; - -const LOG_TARGET: &str = "tari::dan::services::events_publisher"; - -pub trait EventsPublisher { - fn publish(&mut self, event: TEvent); -} - -pub struct LoggingEventsPublisher { - // TODO: remove - phantom: PhantomData, -} - -impl Default for LoggingEventsPublisher { - fn default() -> Self { - Self { phantom: PhantomData } - } -} - -impl EventsPublisher for LoggingEventsPublisher { - fn publish(&mut self, event: TEvent) { - debug!(target: LOG_TARGET, "[Event] Event received: {}", event); - } -} diff --git a/dan_layer/core/src/services/infrastructure_services/inbound_connection_service.rs b/dan_layer/core/src/services/infrastructure_services/inbound_connection_service.rs deleted file mode 100644 index 99461f5be81..00000000000 --- a/dan_layer/core/src/services/infrastructure_services/inbound_connection_service.rs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use async_trait::async_trait; - -use crate::{ - models::{HotStuffMessage, HotStuffMessageType, Payload, ViewId}, - services::infrastructure_services::NodeAddressable, - DigitalAssetError, -}; - -#[async_trait] -pub trait InboundConnectionService { - type Addr: NodeAddressable; - type Payload: Payload; - - async fn wait_for_message( - &self, - message_type: HotStuffMessageType, - for_view: ViewId, - ) -> Result<(Self::Addr, HotStuffMessage), DigitalAssetError>; - - async fn wait_for_qc( - &self, - message_type: HotStuffMessageType, - for_view: ViewId, - ) -> Result<(Self::Addr, HotStuffMessage), DigitalAssetError>; -} diff --git a/dan_layer/core/src/services/infrastructure_services/mocks/mod.rs b/dan_layer/core/src/services/infrastructure_services/mocks/mod.rs deleted file mode 100644 index 8df09712b6d..00000000000 --- a/dan_layer/core/src/services/infrastructure_services/mocks/mod.rs +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::collections::HashMap; - -use async_trait::async_trait; -use tokio::sync::mpsc::{channel, Receiver, Sender}; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::HotStuffMessage, - services::infrastructure_services::{InboundConnectionService, NodeAddressable, OutboundService}, -}; - -pub fn mock_inbound() -> MockInboundConnectionService { - MockInboundConnectionService::default() -} - -type Messages = ( - Sender<(TAddr, HotStuffMessage)>, - Receiver<(TAddr, HotStuffMessage)>, -); - -#[derive()] -pub struct MockInboundConnectionService { - messages: Messages, -} - -#[async_trait] -impl InboundConnectionService - for MockInboundConnectionService -{ - type Addr = TAddr; - type Payload = TPayload; - - async fn wait_for_message( - &self, - _message_type: HotStuffMessageType, - _for_view: ViewId, - ) -> Result<(TAddr, HotStuffMessage), DigitalAssetError> { - todo!() - } - - async fn wait_for_qc( - &self, - _message_type: HotStuffMessageType, - _for_view: ViewId, - ) -> Result<(TAddr, HotStuffMessage), DigitalAssetError> { - todo!() - } -} -impl Default for MockInboundConnectionService { - fn default() -> Self { - Self { messages: channel(10) } - } -} - -impl MockInboundConnectionService { - pub fn _push(&mut self, from: TAddr, message: HotStuffMessage) { - self.messages.0.try_send((from, message)).unwrap() - } - - pub fn _create_sender(&self) -> Sender<(TAddr, HotStuffMessage)> { - self.messages.0.clone() - } -} - -pub fn mock_outbound( - committee: Vec, -) -> MockOutboundService { - MockOutboundService::new(committee) -} - -pub struct MockOutboundService { - inbound_senders: HashMap)>>, - inbounds: HashMap>, -} - -impl Clone for MockOutboundService { - fn clone(&self) -> Self { - MockOutboundService { - inbound_senders: self.inbound_senders.clone(), - inbounds: HashMap::new(), - } - } -} -impl MockOutboundService { - pub fn new(committee: Vec) -> Self { - let mut inbounds = HashMap::new(); - let mut inbound_senders = HashMap::new(); - for member in committee { - let inbound = mock_inbound(); - inbound_senders.insert(member.clone(), inbound.messages.0.clone()); - inbounds.insert(member.clone(), inbound); - } - Self { - inbounds, - inbound_senders, - } - } - - pub fn take_inbound(&mut self, member: &TAddr) -> Option> { - self.inbounds.remove(member) - } -} - -use std::fmt::Debug; - -use crate::models::{HotStuffMessageType, Payload, ViewId}; - -#[async_trait] -impl OutboundService - for MockOutboundService -{ - type Addr = TAddr; - type Payload = TPayload; - - async fn send( - &mut self, - from: TAddr, - to: TAddr, - message: HotStuffMessage, - ) -> Result<(), DigitalAssetError> { - let t = &to; - println!( - "[mock] Sending message: {:?} {:?} sig:{:?}", - &to, - &message.message_type(), - &message.partial_sig() - ); - // intentionally swallow error here because the other end can die in tests - let _result = self.inbound_senders.get_mut(t).unwrap().send((from, message)).await; - Ok(()) - } - - async fn broadcast( - &mut self, - from: TAddr, - _committee: &[TAddr], - message: HotStuffMessage, - ) -> Result<(), DigitalAssetError> { - let receivers: Vec = self.inbound_senders.keys().cloned().collect(); - for receiver in receivers { - self.send(from.clone(), receiver.clone(), message.clone()).await? - } - Ok(()) - } -} diff --git a/dan_layer/core/src/services/infrastructure_services/mod.rs b/dan_layer/core/src/services/infrastructure_services/mod.rs deleted file mode 100644 index 638e3dc94c7..00000000000 --- a/dan_layer/core/src/services/infrastructure_services/mod.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -mod inbound_connection_service; -mod node_addressable; -mod outbound_service; - -pub use inbound_connection_service::InboundConnectionService; -pub use node_addressable::NodeAddressable; -pub use outbound_service::OutboundService; - -#[cfg(test)] -pub mod mocks; diff --git a/dan_layer/core/src/services/infrastructure_services/node_addressable.rs b/dan_layer/core/src/services/infrastructure_services/node_addressable.rs deleted file mode 100644 index d9afd670ef9..00000000000 --- a/dan_layer/core/src/services/infrastructure_services/node_addressable.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - fmt::{Debug, Display}, - hash::Hash, -}; - -use tari_comms::types::CommsPublicKey; - -pub trait NodeAddressable: Eq + Hash + Clone + Debug + Send + Sync + Display {} - -impl NodeAddressable for String {} - -impl NodeAddressable for &str {} - -impl NodeAddressable for CommsPublicKey {} diff --git a/dan_layer/core/src/services/infrastructure_services/outbound_service.rs b/dan_layer/core/src/services/infrastructure_services/outbound_service.rs deleted file mode 100644 index 3702ab246a7..00000000000 --- a/dan_layer/core/src/services/infrastructure_services/outbound_service.rs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use async_trait::async_trait; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::{HotStuffMessage, Payload}, - services::infrastructure_services::NodeAddressable, -}; - -#[async_trait] -pub trait OutboundService { - type Addr: NodeAddressable + Send; - type Payload: Payload; - - async fn send( - &mut self, - from: Self::Addr, - to: Self::Addr, - message: HotStuffMessage, - ) -> Result<(), DigitalAssetError>; - - async fn broadcast( - &mut self, - from: Self::Addr, - committee: &[Self::Addr], - message: HotStuffMessage, - ) -> Result<(), DigitalAssetError>; -} diff --git a/dan_layer/core/src/services/mempool_service.rs b/dan_layer/core/src/services/mempool_service.rs deleted file mode 100644 index dfa1376d8fe..00000000000 --- a/dan_layer/core/src/services/mempool_service.rs +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::sync::Arc; - -use async_trait::async_trait; -use tari_common_types::types::FixedHash; -use tari_dan_engine::instructions::Instruction; -use tokio::sync::Mutex; - -use crate::{digital_assets_error::DigitalAssetError, models::TreeNodeHash}; - -#[async_trait] -pub trait MempoolService: Sync + Send + 'static { - async fn submit_instruction(&mut self, instruction: Instruction) -> Result<(), DigitalAssetError>; - async fn read_block(&self, limit: usize) -> Result, DigitalAssetError>; - async fn reserve_instruction_in_block( - &mut self, - instruction_hash: &FixedHash, - block_hash: TreeNodeHash, - ) -> Result<(), DigitalAssetError>; - async fn remove_all_in_block(&mut self, block_hash: &TreeNodeHash) -> Result<(), DigitalAssetError>; - async fn release_reservations(&mut self, block_hash: &TreeNodeHash) -> Result<(), DigitalAssetError>; - async fn size(&self) -> usize; -} - -#[derive(Default)] -pub struct ConcreteMempoolService { - instructions: Vec<(Instruction, Option)>, -} - -#[async_trait] -impl MempoolService for ConcreteMempoolService { - async fn submit_instruction(&mut self, instruction: Instruction) -> Result<(), DigitalAssetError> { - self.instructions.push((instruction, None)); - Ok(()) - } - - async fn read_block(&self, limit: usize) -> Result, DigitalAssetError> { - let mut result = vec![]; - for (i, (instruction, block_hash)) in self.instructions.iter().enumerate() { - if i > limit { - break; - } - if block_hash.is_none() { - result.push(instruction.clone()); - } - } - Ok(result) - } - - async fn reserve_instruction_in_block( - &mut self, - instruction_hash: &FixedHash, - node_hash: TreeNodeHash, - ) -> Result<(), DigitalAssetError> { - for (instruction, node_hash_mut) in &mut self.instructions { - if instruction.hash() == instruction_hash { - *node_hash_mut = Some(node_hash); - break; - } - } - - Ok(()) - } - - async fn remove_all_in_block(&mut self, block_hash: &TreeNodeHash) -> Result<(), DigitalAssetError> { - self.instructions = self - .instructions - .drain(..) - .filter(|(_, node_hash)| node_hash.as_ref() != Some(block_hash)) - .collect(); - Ok(()) - } - - async fn release_reservations(&mut self, block_hash: &TreeNodeHash) -> Result<(), DigitalAssetError> { - for (_, block_hash_mut) in &mut self.instructions { - if block_hash_mut.as_ref() == Some(block_hash) { - *block_hash_mut = None; - } - } - Ok(()) - } - - // async fn remove_instructions(&mut self, instructions: &[Instruction]) -> Result<(), DigitalAssetError> { - // let mut result = self.instructions.clone(); - // for i in instructions { - // if let Some(position) = result.iter().position(|r| r == i) { - // result.remove(position); - // } - // } - // self.instructions = result; - // Ok(()) - // } - - async fn size(&self) -> usize { - self.instructions - .iter() - .fold(0, |a, b| if b.1.is_none() { a + 1 } else { a }) - } -} - -#[derive(Clone)] -pub struct MempoolServiceHandle { - mempool: Arc>, -} - -impl Default for MempoolServiceHandle { - fn default() -> Self { - Self { - mempool: Arc::new(Mutex::new(ConcreteMempoolService::default())), - } - } -} - -#[async_trait] -impl MempoolService for MempoolServiceHandle { - async fn submit_instruction(&mut self, instruction: Instruction) -> Result<(), DigitalAssetError> { - self.mempool.lock().await.submit_instruction(instruction).await - } - - async fn read_block(&self, limit: usize) -> Result, DigitalAssetError> { - self.mempool.lock().await.read_block(limit).await - } - - async fn reserve_instruction_in_block( - &mut self, - instruction_hash: &FixedHash, - node_hash: TreeNodeHash, - ) -> Result<(), DigitalAssetError> { - self.mempool - .lock() - .await - .reserve_instruction_in_block(instruction_hash, node_hash) - .await - } - - async fn remove_all_in_block(&mut self, block_hash: &TreeNodeHash) -> Result<(), DigitalAssetError> { - self.mempool.lock().await.remove_all_in_block(block_hash).await - } - - async fn release_reservations(&mut self, block_hash: &TreeNodeHash) -> Result<(), DigitalAssetError> { - self.mempool.lock().await.release_reservations(block_hash).await - } - - async fn size(&self) -> usize { - self.mempool.lock().await.size().await - } -} diff --git a/dan_layer/core/src/services/mocks/mod.rs b/dan_layer/core/src/services/mocks/mod.rs deleted file mode 100644 index 0ec28387e1a..00000000000 --- a/dan_layer/core/src/services/mocks/mod.rs +++ /dev/null @@ -1,501 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - collections::VecDeque, - sync::{Arc, Mutex}, -}; - -use async_trait::async_trait; -use tari_common_types::types::{FixedHash, PublicKey}; -use tari_core::{ - chain_storage::UtxoMinedInfo, - transactions::transaction_components::{CheckpointChallenge, OutputType, SignerSignature}, -}; -use tari_crypto::ristretto::RistrettoPublicKey; -use tari_dan_common_types::TemplateId; -#[cfg(test)] -use tari_dan_engine::state::mocks::state_db::MockStateDbBackupAdapter; -use tari_dan_engine::{ - instructions::Instruction, - state::{ - models::{SchemaState, StateOpLogEntry, StateRoot}, - StateDbUnitOfWork, - StateDbUnitOfWorkReader, - }, -}; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::{ - AssetDefinition, - BaseLayerMetadata, - BaseLayerOutput, - Committee, - Event, - HotStuffTreeNode, - InstructionSet, - Node, - Payload, - SideChainBlock, - SidechainMetadata, - TariDanPayload, - TreeNodeHash, - ValidatorSignature, - }, - services::{ - base_node_client::BaseNodeClient, - infrastructure_services::NodeAddressable, - AssetProcessor, - CommitteeManager, - ConcreteCheckpointManager, - EventsPublisher, - MempoolService, - PayloadProcessor, - PayloadProvider, - SigningService, - ValidatorNodeClientError, - ValidatorNodeClientFactory, - ValidatorNodeRpcClient, - WalletClient, - }, - storage::{chain::ChainDbUnitOfWork, ChainStorageService, StorageError}, -}; -#[cfg(test)] -use crate::{ - models::domain_events::ConsensusWorkerDomainEvent, - services::infrastructure_services::mocks::{MockInboundConnectionService, MockOutboundService}, - services::{ConcreteAssetProxy, ServiceSpecification}, - storage::mocks::{chain_db::MockChainDbBackupAdapter, MockDbFactory}, -}; - -#[derive(Debug, Clone)] -pub struct MockMempoolService; - -#[async_trait] -impl MempoolService for MockMempoolService { - async fn submit_instruction(&mut self, _instruction: Instruction) -> Result<(), DigitalAssetError> { - Ok(()) - } - - async fn read_block(&self, _limit: usize) -> Result, DigitalAssetError> { - Ok(vec![]) - } - - async fn reserve_instruction_in_block( - &mut self, - _instruction_hash: &FixedHash, - _block_hash: TreeNodeHash, - ) -> Result<(), DigitalAssetError> { - todo!() - } - - async fn remove_all_in_block(&mut self, _block_hash: &TreeNodeHash) -> Result<(), DigitalAssetError> { - todo!() - } - - async fn release_reservations(&mut self, _block_hash: &TreeNodeHash) -> Result<(), DigitalAssetError> { - todo!() - } - - async fn size(&self) -> usize { - 0 - } -} - -pub fn create_mempool_mock() -> MockMempoolService { - MockMempoolService -} - -pub fn mock_static_payload_provider() -> MockStaticPayloadProvider { - let instruction_set = InstructionSet::empty(); - let payload = TariDanPayload::new(instruction_set, None); - MockStaticPayloadProvider { - static_payload: payload, - } -} - -pub struct MockStaticPayloadProvider { - static_payload: TPayload, -} - -#[async_trait] -impl PayloadProvider for MockStaticPayloadProvider { - async fn create_payload(&self) -> Result { - Ok(self.static_payload.clone()) - } - - fn create_genesis_payload(&self, _: &AssetDefinition) -> TPayload { - self.static_payload.clone() - } - - async fn get_payload_queue(&self) -> usize { - 1 - } - - async fn reserve_payload( - &mut self, - _payload: &TPayload, - _reservation_key: &TreeNodeHash, - ) -> Result<(), DigitalAssetError> { - todo!() - } - - async fn remove_payload(&mut self, _reservation_key: &TreeNodeHash) -> Result<(), DigitalAssetError> { - todo!() - } -} - -pub fn mock_payload_provider() -> MockStaticPayloadProvider<&'static str> { - MockStaticPayloadProvider { - static_payload: "", - } -} - -pub fn mock_events_publisher() -> MockEventsPublisher { - MockEventsPublisher::default() -} - -#[derive(Clone)] -pub struct MockEventsPublisher { - events: Arc>>, -} - -impl Default for MockEventsPublisher { - fn default() -> Self { - Self { - events: Arc::new(Mutex::new(VecDeque::new())), - } - } -} - -impl MockEventsPublisher { - pub fn to_vec(&self) -> Vec { - self.events.lock().unwrap().iter().cloned().collect() - } -} - -impl EventsPublisher for MockEventsPublisher { - fn publish(&mut self, event: TEvent) { - self.events.lock().unwrap().push_back(event) - } -} - -pub fn mock_signing_service() -> MockSigningService { - MockSigningService -} - -pub struct MockSigningService; - -impl SigningService for MockSigningService { - fn sign(&self, _challenge: &[u8]) -> Result { - Ok(ValidatorSignature {}) - } - - fn sign_checkpoint(&self, _challenge: &CheckpointChallenge) -> Result { - todo!() - } -} - -#[derive(Clone)] -pub struct MockBaseNodeClient {} - -#[async_trait] -impl BaseNodeClient for MockBaseNodeClient { - async fn get_tip_info(&mut self) -> Result { - todo!(); - } - - async fn get_constitutions( - &mut self, - _start_block_hash: Option, - _dan_node_public_key: &PublicKey, - ) -> Result, DigitalAssetError> { - todo!() - } - - async fn check_if_in_committee( - &mut self, - _asset_public_key: PublicKey, - _dan_node_public_key: PublicKey, - ) -> Result<(bool, u64), DigitalAssetError> { - todo!(); - } - - // async fn get_assets_for_dan_node( - // &mut self, - // _dan_node_public_key: PublicKey, - // ) -> Result, DigitalAssetError> { - // todo!(); - // } - - async fn get_asset_registration( - &mut self, - _asset_public_key: PublicKey, - ) -> Result, DigitalAssetError> { - todo!() - } - - async fn get_current_contract_outputs( - &mut self, - _height: u64, - _contract_id: FixedHash, - _output_type: OutputType, - ) -> Result, DigitalAssetError> { - todo!() - } -} - -pub fn mock_base_node_client() -> MockBaseNodeClient { - MockBaseNodeClient {} -} - -#[derive(Clone)] -pub struct MockCommitteeManager { - pub committee: Committee, -} - -impl CommitteeManager for MockCommitteeManager { - fn current_committee(&self) -> Result<&Committee, DigitalAssetError> { - todo!(); - } - - fn read_from_constitution(&mut self, _output: BaseLayerOutput) -> Result<(), DigitalAssetError> { - todo!(); - } -} - -// pub fn _mock_template_service() -> MockTemplateService { -// MockTemplateService {} -// } -// -// pub struct MockTemplateService {} -// -// #[async_trait] -// impl TemplateService for MockTemplateService { -// async fn execute_instruction(&mut self, _instruction: &Instruction) -> Result<(), DigitalAssetError> { -// dbg!("Executing instruction as mock"); -// Ok(()) -// } -// } - -pub fn mock_payload_processor() -> MockPayloadProcessor { - MockPayloadProcessor {} -} - -pub struct MockPayloadProcessor {} - -#[async_trait] -impl PayloadProcessor for MockPayloadProcessor { - async fn process_payload( - &self, - _payload: &TPayload, - _unit_of_work: TUnitOfWork, - ) -> Result { - todo!() - } -} - -#[derive(Debug, Clone)] -pub struct MockAssetProcessor; - -impl AssetProcessor for MockAssetProcessor { - fn execute_instruction( - &self, - _instruction: &Instruction, - _db: &mut TUnitOfWork, - ) -> Result<(), DigitalAssetError> { - todo!() - } - - fn invoke_read_method( - &self, - _instruction: &Instruction, - _state_db: &TUnifOfWork, - ) -> Result>, DigitalAssetError> { - todo!() - } -} - -#[derive(Default, Clone)] -pub struct MockWalletClient; - -#[async_trait] -impl WalletClient for MockWalletClient { - async fn create_new_checkpoint( - &mut self, - _contract_id: &FixedHash, - _state_root: &StateRoot, - _checkpoint_number: u64, - _checkpoint_signatures: &[SignerSignature], - ) -> Result<(), DigitalAssetError> { - Ok(()) - } - - async fn submit_contract_acceptance( - &mut self, - _contract_id: &FixedHash, - _validator_node_public_key: &PublicKey, - _signature: &tari_common_types::types::Signature, - ) -> Result { - Ok(0_u64) - } - - async fn submit_contract_update_proposal_acceptance( - &mut self, - _contract_id: &FixedHash, - _proposal_id: u64, - _validator_node_public_key: &PublicKey, - _signature: &tari_common_types::types::Signature, - ) -> Result { - Ok(0_u64) - } -} - -pub fn mock_wallet_client() -> MockWalletClient { - MockWalletClient {} -} - -#[derive(Default, Clone)] -pub struct MockValidatorNodeClientFactory; - -#[derive(Default, Clone)] -pub struct MockValidatorNodeClient; - -#[async_trait] -impl ValidatorNodeRpcClient for MockValidatorNodeClient { - async fn invoke_read_method( - &mut self, - _contract_id: &FixedHash, - _template_id: TemplateId, - _method: String, - _args: Vec, - _sender: PublicKey, - ) -> Result>, ValidatorNodeClientError> { - Ok(None) - } - - async fn invoke_method( - &mut self, - _contract_id: &FixedHash, - _template_id: TemplateId, - _method: String, - _args: Vec, - _sender: PublicKey, - ) -> Result>, ValidatorNodeClientError> { - Ok(None) - } - - async fn get_sidechain_blocks( - &mut self, - _contract_id: &FixedHash, - _start_hash: TreeNodeHash, - _end_hash: Option, - ) -> Result, ValidatorNodeClientError> { - Ok(vec![]) - } - - async fn get_sidechain_state( - &mut self, - _contract_id: &FixedHash, - ) -> Result, ValidatorNodeClientError> { - Ok(vec![]) - } - - async fn get_op_logs( - &mut self, - _contract_id: &FixedHash, - _height: u64, - ) -> Result, ValidatorNodeClientError> { - Ok(vec![]) - } - - async fn get_tip_node(&mut self, _contract_id: &FixedHash) -> Result, ValidatorNodeClientError> { - Ok(None) - } -} - -impl ValidatorNodeClientFactory for MockValidatorNodeClientFactory { - type Addr = PublicKey; - type Client = MockValidatorNodeClient; - - fn create_client(&self, _address: &Self::Addr) -> Self::Client { - MockValidatorNodeClient::default() - } -} - -#[derive(Default, Clone)] -pub struct MockChainStorageService; - -#[async_trait] -impl ChainStorageService for MockChainStorageService { - async fn get_metadata(&self) -> Result { - todo!() - } - - async fn add_node( - &self, - _node: &HotStuffTreeNode, - _db: TUnitOfWork, - ) -> Result<(), StorageError> { - Ok(()) - } -} - -pub fn mock_checkpoint_manager() -> ConcreteCheckpointManager { - ConcreteCheckpointManager::::new(AssetDefinition::default(), MockWalletClient::default()) -} - -pub fn create_public_key() -> RistrettoPublicKey { - let mut rng = rand::thread_rng(); - let (_, address) = ::random_keypair(&mut rng); - address -} - -#[derive(Default, Clone)] -pub struct MockServiceSpecification; - -#[cfg(test)] -impl ServiceSpecification for MockServiceSpecification { - type AcceptanceManager = super::ConcreteAcceptanceManager; - type Addr = RistrettoPublicKey; - type AssetProcessor = MockAssetProcessor; - type AssetProxy = ConcreteAssetProxy; - type BaseNodeClient = MockBaseNodeClient; - type ChainDbBackendAdapter = MockChainDbBackupAdapter; - type ChainStorageService = MockChainStorageService; - type CheckpointManager = ConcreteCheckpointManager; - type CommitteeManager = MockCommitteeManager; - type DbFactory = MockDbFactory; - type EventsPublisher = MockEventsPublisher; - type GlobalDbAdapter = crate::storage::mocks::global_db::MockGlobalDbBackupAdapter; - type InboundConnectionService = MockInboundConnectionService; - type MempoolService = MockMempoolService; - type OutboundService = MockOutboundService; - type Payload = TariDanPayload; - type PayloadProcessor = MockPayloadProcessor; - type PayloadProvider = MockStaticPayloadProvider; - type SigningService = MockSigningService; - type StateDbBackendAdapter = MockStateDbBackupAdapter; - type ValidatorNodeClientFactory = MockValidatorNodeClientFactory; - type WalletClient = MockWalletClient; -} diff --git a/dan_layer/core/src/services/mod.rs b/dan_layer/core/src/services/mod.rs deleted file mode 100644 index d239a6567ed..00000000000 --- a/dan_layer/core/src/services/mod.rs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -mod acceptance_manager; -mod asset_processor; -mod base_node_client; -mod committee_manager; -mod events_publisher; -pub mod infrastructure_services; -mod mempool_service; -mod payload_processor; -mod payload_provider; -mod signing_service; - -pub use acceptance_manager::{AcceptanceManager, ConcreteAcceptanceManager}; -pub use asset_processor::{AssetProcessor, ConcreteAssetProcessor, MemoryInstructionLog}; -pub use asset_proxy::{AssetProxy, ConcreteAssetProxy}; -pub use base_node_client::BaseNodeClient; -pub use committee_manager::{CommitteeManager, ConcreteCommitteeManager}; -pub use events_publisher::{EventsPublisher, LoggingEventsPublisher}; -pub use mempool_service::{ConcreteMempoolService, MempoolService, MempoolServiceHandle}; -pub use payload_processor::{PayloadProcessor, TariDanPayloadProcessor}; -pub use payload_provider::{PayloadProvider, TariDanPayloadProvider}; -pub use signing_service::{NodeIdentitySigningService, SigningService}; -mod asset_proxy; -mod checkpoint_manager; -pub mod mocks; -mod service_specification; -mod validator_node_rpc_client; -mod wallet_client; -pub use checkpoint_manager::{CheckpointManager, ConcreteCheckpointManager}; -pub use service_specification::ServiceSpecification; -pub use validator_node_rpc_client::{ValidatorNodeClientError, ValidatorNodeClientFactory, ValidatorNodeRpcClient}; -pub use wallet_client::WalletClient; diff --git a/dan_layer/core/src/services/payload_processor.rs b/dan_layer/core/src/services/payload_processor.rs deleted file mode 100644 index 448d2ca2baa..00000000000 --- a/dan_layer/core/src/services/payload_processor.rs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use async_trait::async_trait; -use tari_dan_engine::state::{models::StateRoot, StateDbUnitOfWork}; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::{Payload, TariDanPayload}, - services::AssetProcessor, -}; - -#[async_trait] -pub trait PayloadProcessor { - async fn process_payload( - &self, - payload: &TPayload, - unit_of_work: TUnitOfWork, - ) -> Result; -} - -pub struct TariDanPayloadProcessor -where TAssetProcessor: AssetProcessor -{ - asset_processor: TAssetProcessor, -} - -impl TariDanPayloadProcessor { - pub fn new(asset_processor: TAssetProcessor) -> Self { - Self { asset_processor } - } -} - -#[async_trait] -impl PayloadProcessor - for TariDanPayloadProcessor -{ - async fn process_payload( - &self, - payload: &TariDanPayload, - state_tx: TUnitOfWork, - ) -> Result { - let mut state_tx = state_tx; - for instruction in payload.instructions() { - println!("Executing instruction"); - println!("{:?}", instruction); - // TODO: Should we swallow + log the error instead of propagating it? - self.asset_processor.execute_instruction(instruction, &mut state_tx)?; - } - - Ok(state_tx.calculate_root()?) - } -} diff --git a/dan_layer/core/src/services/payload_provider.rs b/dan_layer/core/src/services/payload_provider.rs deleted file mode 100644 index 7a6d6c9344e..00000000000 --- a/dan_layer/core/src/services/payload_provider.rs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use async_trait::async_trait; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::{AssetDefinition, InstructionSet, Payload, TariDanPayload, TreeNodeHash}, - services::{asset_processor::TemplateFactory, MempoolService}, -}; - -#[async_trait] -pub trait PayloadProvider { - async fn create_payload(&self) -> Result; - fn create_genesis_payload(&self, asset_definition: &AssetDefinition) -> TPayload; - async fn get_payload_queue(&self) -> usize; - async fn reserve_payload( - &mut self, - payload: &TPayload, - reservation_key: &TreeNodeHash, - ) -> Result<(), DigitalAssetError>; - async fn remove_payload(&mut self, reservation_key: &TreeNodeHash) -> Result<(), DigitalAssetError>; -} - -pub struct TariDanPayloadProvider { - mempool: TMempoolService, - template_factory: TemplateFactory, -} - -impl TariDanPayloadProvider { - pub fn new(mempool: TMempoolService) -> Self { - Self { - mempool, - template_factory: TemplateFactory {}, - } - } -} - -#[async_trait] -impl PayloadProvider for TariDanPayloadProvider { - async fn create_payload(&self) -> Result { - let instructions = self.mempool.read_block(100).await?; - let instruction_set = InstructionSet::from_vec(instructions); - - Ok(TariDanPayload::new(instruction_set, None)) - } - - fn create_genesis_payload(&self, asset_definition: &AssetDefinition) -> TariDanPayload { - let mut instruction_set = InstructionSet::empty(); - for params in &asset_definition.template_parameters { - let instructions = self.template_factory.initial_instructions(params); - instruction_set.extend(instructions); - } - TariDanPayload::new(instruction_set, None) - } - - async fn get_payload_queue(&self) -> usize { - self.mempool.size().await - } - - async fn reserve_payload( - &mut self, - payload: &TariDanPayload, - reservation_key: &TreeNodeHash, - ) -> Result<(), DigitalAssetError> { - // Reserve all instructions if they succeeded - for instruction in payload.instructions() { - self.mempool - .reserve_instruction_in_block(instruction.hash(), *reservation_key) - .await?; - } - Ok(()) - } - - async fn remove_payload(&mut self, reservation_key: &TreeNodeHash) -> Result<(), DigitalAssetError> { - self.mempool.remove_all_in_block(reservation_key).await - } -} diff --git a/dan_layer/core/src/services/service_specification.rs b/dan_layer/core/src/services/service_specification.rs deleted file mode 100644 index 5322c19f839..00000000000 --- a/dan_layer/core/src/services/service_specification.rs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_dan_engine::state::StateDbBackendAdapter; - -use super::acceptance_manager::AcceptanceManager; -use crate::{ - models::{domain_events::ConsensusWorkerDomainEvent, Payload}, - services::{ - infrastructure_services::{InboundConnectionService, NodeAddressable, OutboundService}, - wallet_client::WalletClient, - AssetProcessor, - AssetProxy, - BaseNodeClient, - CheckpointManager, - CommitteeManager, - EventsPublisher, - MempoolService, - PayloadProcessor, - PayloadProvider, - SigningService, - ValidatorNodeClientFactory, - }, - storage::{ - chain::{ChainDbBackendAdapter, ChainDbMetadataKey}, - global::GlobalDbBackendAdapter, - ChainStorageService, - DbFactory, - MetadataBackendAdapter, - }, -}; - -/// A trait to describe a specific configuration of services. This type allows other services to -/// simply reference types. -/// This trait is intended to only include `types` and no methods. -pub trait ServiceSpecification: Default + Clone { - type AcceptanceManager: AcceptanceManager + Clone; - type Addr: NodeAddressable; - type AssetProcessor: AssetProcessor + Clone; - type AssetProxy: AssetProxy + Clone; - type BaseNodeClient: BaseNodeClient + Clone; - type ChainDbBackendAdapter: ChainDbBackendAdapter + MetadataBackendAdapter; - type ChainStorageService: ChainStorageService; - type CheckpointManager: CheckpointManager; - type CommitteeManager: CommitteeManager; - type DbFactory: DbFactory< - StateDbBackendAdapter = Self::StateDbBackendAdapter, - ChainDbBackendAdapter = Self::ChainDbBackendAdapter, - GlobalDbBackendAdapter = Self::GlobalDbAdapter, - > + Clone; - type EventsPublisher: EventsPublisher; - type GlobalDbAdapter: GlobalDbBackendAdapter; - type InboundConnectionService: InboundConnectionService; - type MempoolService: MempoolService + Clone; - type OutboundService: OutboundService; - type Payload: Payload; - type PayloadProcessor: PayloadProcessor; - type PayloadProvider: PayloadProvider; - type SigningService: SigningService; - type StateDbBackendAdapter: StateDbBackendAdapter; - type ValidatorNodeClientFactory: ValidatorNodeClientFactory + Clone; - type WalletClient: WalletClient + Clone; -} diff --git a/dan_layer/core/src/services/signing_service.rs b/dan_layer/core/src/services/signing_service.rs deleted file mode 100644 index 244cbc8a2c8..00000000000 --- a/dan_layer/core/src/services/signing_service.rs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::sync::Arc; - -use tari_comms::NodeIdentity; -use tari_core::transactions::transaction_components::{CheckpointChallenge, SignerSignature}; - -use crate::{digital_assets_error::DigitalAssetError, models::ValidatorSignature}; - -pub trait SigningService { - fn sign(&self, challenge: &[u8]) -> Result; - - fn sign_checkpoint(&self, challenge: &CheckpointChallenge) -> Result; -} - -pub struct NodeIdentitySigningService { - node_identity: Arc, -} - -impl NodeIdentitySigningService { - pub fn new(node_identity: Arc) -> Self { - Self { node_identity } - } -} - -impl SigningService for NodeIdentitySigningService { - fn sign(&self, _challenge: &[u8]) -> Result { - // TODO better sig - Ok(ValidatorSignature {}) - } - - fn sign_checkpoint(&self, challenge: &CheckpointChallenge) -> Result { - Ok(SignerSignature::sign(self.node_identity.secret_key(), challenge)) - } -} diff --git a/dan_layer/core/src/services/validator_node_rpc_client.rs b/dan_layer/core/src/services/validator_node_rpc_client.rs deleted file mode 100644 index 5fbcd7360c4..00000000000 --- a/dan_layer/core/src/services/validator_node_rpc_client.rs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use async_trait::async_trait; -use tari_common_types::types::{FixedHash, PublicKey}; -use tari_comms::{ - connectivity::ConnectivityError, - protocol::rpc::{RpcError, RpcStatus}, - types::CommsPublicKey, -}; -use tari_comms_dht::DhtActorError; -use tari_dan_common_types::TemplateId; -use tari_dan_engine::state::models::{SchemaState, StateOpLogEntry}; - -use crate::{ - models::{Node, SideChainBlock, TreeNodeHash}, - services::infrastructure_services::NodeAddressable, -}; - -pub trait ValidatorNodeClientFactory: Send + Sync { - type Addr: NodeAddressable; - type Client: ValidatorNodeRpcClient; - fn create_client(&self, address: &Self::Addr) -> Self::Client; -} - -#[async_trait] -pub trait ValidatorNodeRpcClient: Send + Sync { - async fn invoke_read_method( - &mut self, - contract_id: &FixedHash, - template_id: TemplateId, - method: String, - args: Vec, - sender: PublicKey, - ) -> Result>, ValidatorNodeClientError>; - - async fn invoke_method( - &mut self, - contract_id: &FixedHash, - template_id: TemplateId, - method: String, - args: Vec, - sender: PublicKey, - ) -> Result>, ValidatorNodeClientError>; - - async fn get_sidechain_blocks( - &mut self, - contract_id: &FixedHash, - start_hash: TreeNodeHash, - end_hash: Option, - ) -> Result, ValidatorNodeClientError>; - - async fn get_sidechain_state( - &mut self, - contract_id: &FixedHash, - ) -> Result, ValidatorNodeClientError>; - - async fn get_op_logs( - &mut self, - contract_id: &FixedHash, - height: u64, - ) -> Result, ValidatorNodeClientError>; - - async fn get_tip_node(&mut self, contract_id: &FixedHash) -> Result, ValidatorNodeClientError>; -} - -#[derive(Debug, thiserror::Error)] -pub enum ValidatorNodeClientError { - #[error("Protocol violations for peer {peer}: {details}")] - ProtocolViolation { peer: CommsPublicKey, details: String }, - #[error("Peer sent an invalid message: {0}")] - InvalidPeerMessage(String), - #[error("Connectivity error:{0}")] - ConnectivityError(#[from] ConnectivityError), - #[error("RpcError: {0}")] - RpcError(#[from] RpcError), - #[error("Remote node returned error: {0}")] - RpcStatusError(#[from] RpcStatus), - #[error("Dht error: {0}")] - DhtError(#[from] DhtActorError), -} diff --git a/dan_layer/core/src/services/wallet_client.rs b/dan_layer/core/src/services/wallet_client.rs deleted file mode 100644 index 6ebc5a949bb..00000000000 --- a/dan_layer/core/src/services/wallet_client.rs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use async_trait::async_trait; -use tari_common_types::types::{FixedHash, PublicKey, Signature}; -use tari_core::transactions::transaction_components::SignerSignature; -use tari_dan_engine::state::models::StateRoot; - -use crate::DigitalAssetError; - -#[async_trait] -pub trait WalletClient: Send + Sync { - async fn create_new_checkpoint( - &mut self, - contract_id: &FixedHash, - state_root: &StateRoot, - checkpoint_number: u64, - checkpoint_signatures: &[SignerSignature], - ) -> Result<(), DigitalAssetError>; - - async fn submit_contract_acceptance( - &mut self, - contract_id: &FixedHash, - validator_node_public_key: &PublicKey, - signature: &Signature, - ) -> Result; - - async fn submit_contract_update_proposal_acceptance( - &mut self, - contract_id: &FixedHash, - proposal_id: u64, - validator_node_public_key: &PublicKey, - signature: &Signature, - ) -> Result; -} diff --git a/dan_layer/core/src/storage/atomic_db.rs b/dan_layer/core/src/storage/atomic_db.rs deleted file mode 100644 index 3e1023956b0..00000000000 --- a/dan_layer/core/src/storage/atomic_db.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::storage::StorageError; - -pub trait AtomicDb { - type Error: Into; - type DbTransaction; - - fn create_transaction(&self) -> Result; - - fn commit(&self, transaction: &Self::DbTransaction) -> Result<(), Self::Error>; -} diff --git a/dan_layer/core/src/storage/chain/chain_db.rs b/dan_layer/core/src/storage/chain/chain_db.rs deleted file mode 100644 index fc239faa82d..00000000000 --- a/dan_layer/core/src/storage/chain/chain_db.rs +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::{ - models::{Node, QuorumCertificate, SideChainBlock, TreeNodeHash}, - storage::{ - chain::{chain_db_unit_of_work::ChainDbUnitOfWorkImpl, ChainDbBackendAdapter, ChainDbMetadataKey}, - MetadataBackendAdapter, - StorageError, - }, -}; - -pub struct ChainDb { - adapter: TBackendAdapter, -} - -impl ChainDb { - pub fn new(adapter: TBackendAdapter) -> ChainDb { - ChainDb { adapter } - } - - pub fn find_highest_prepared_qc(&self) -> Result { - self.adapter - .find_highest_prepared_qc() - .map_err(TBackendAdapter::Error::into) - } - - pub fn get_locked_qc(&self) -> Result { - self.adapter.get_locked_qc().map_err(TBackendAdapter::Error::into) - } - - pub fn is_empty(&self) -> Result { - self.adapter.is_empty().map_err(TBackendAdapter::Error::into) - } - - pub fn sidechain_block_exists(&self, hash: &TreeNodeHash) -> Result { - self.adapter.node_exists(hash).map_err(TBackendAdapter::Error::into) - } - - pub fn find_sidechain_block_by_node_hash( - &self, - hash: &TreeNodeHash, - ) -> Result, StorageError> { - let maybe_block = self - .adapter - .find_node_by_hash(hash) - .map_err(TBackendAdapter::Error::into)?; - - let (block_id, node) = match maybe_block { - Some(v) => v, - None => return Ok(None), - }; - - let instructions = self - .adapter - .find_all_instructions_by_node(block_id) - .map_err(TBackendAdapter::Error::into)?; - let instructions = instructions.into_iter().map(|i| i.instruction).collect(); - - Ok(Some(SideChainBlock::new(node.into(), instructions))) - } - - pub fn find_sidechain_block_by_parent_node_hash( - &self, - parent_hash: &TreeNodeHash, - ) -> Result, StorageError> { - let maybe_block = self - .adapter - .find_node_by_parent_hash(parent_hash) - .map_err(TBackendAdapter::Error::into)?; - let (block_id, node) = match maybe_block { - Some(v) => v, - None => return Ok(None), - }; - - let instructions = self - .adapter - .find_all_instructions_by_node(block_id) - .map_err(TBackendAdapter::Error::into)?; - let instructions = instructions.into_iter().map(|i| i.instruction).collect(); - - Ok(Some(SideChainBlock::new(node.into(), instructions))) - } - - pub fn get_tip_node(&self) -> Result, StorageError> { - let db_node = self.adapter.get_tip_node().map_err(TBackendAdapter::Error::into)?; - Ok(db_node.map(Into::into)) - } -} - -impl ChainDb -where TBackendAdapter: MetadataBackendAdapter -{ - pub fn get_current_checkpoint_number(&self) -> Result { - let tx = self - .adapter - .create_transaction() - .map_err(TBackendAdapter::Error::into)?; - let number = self - .adapter - .get_metadata(&ChainDbMetadataKey::CheckpointNumber, &tx) - .map_err(TBackendAdapter::Error::into)? - .unwrap_or(0); - Ok(number) - } - - /// Increments checkpoint number and returns the incremented value. If the key did not previously exist, it - /// is created and set to 1. - pub fn increment_checkpoint_number(&self) -> Result { - let tx = self - .adapter - .create_transaction() - .map_err(TBackendAdapter::Error::into)?; - const KEY: ChainDbMetadataKey = ChainDbMetadataKey::CheckpointNumber; - let n = self - .adapter - .get_metadata::(&KEY, &tx) - .map_err(TBackendAdapter::Error::into)? - .unwrap_or(0); - let next = n + 1; - self.adapter - .set_metadata(KEY, next, &tx) - .map_err(TBackendAdapter::Error::into)?; - self.adapter.commit(&tx).map_err(TBackendAdapter::Error::into)?; - Ok(next) - } -} - -impl ChainDb { - pub fn new_unit_of_work(&self) -> ChainDbUnitOfWorkImpl { - ChainDbUnitOfWorkImpl::new(self.adapter.clone()) - } -} diff --git a/dan_layer/core/src/storage/chain/chain_db_backend_adapter.rs b/dan_layer/core/src/storage/chain/chain_db_backend_adapter.rs deleted file mode 100644 index 6b0104a1fdf..00000000000 --- a/dan_layer/core/src/storage/chain/chain_db_backend_adapter.rs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::fmt::Debug; - -use crate::{ - models::{Payload, QuorumCertificate, TreeNodeHash}, - storage::{ - chain::{DbInstruction, DbNode, DbQc}, - AtomicDb, - }, -}; - -pub trait ChainDbBackendAdapter: AtomicDb + Send + Sync + Clone { - type Id: Copy + Send + Sync + Debug + PartialEq; - type Payload: Payload; - - fn is_empty(&self) -> Result; - fn node_exists(&self, node_hash: &TreeNodeHash) -> Result; - fn get_tip_node(&self) -> Result, Self::Error>; - fn insert_node(&self, item: &DbNode, transaction: &Self::DbTransaction) -> Result<(), Self::Error>; - fn update_node(&self, id: &Self::Id, item: &DbNode, transaction: &Self::DbTransaction) -> Result<(), Self::Error>; - fn insert_instruction(&self, item: &DbInstruction, transaction: &Self::DbTransaction) -> Result<(), Self::Error>; - fn locked_qc_id(&self) -> Self::Id; - fn prepare_qc_id(&self) -> Self::Id; - fn find_highest_prepared_qc(&self) -> Result; - fn get_locked_qc(&self) -> Result; - fn get_prepare_qc(&self) -> Result, Self::Error>; - fn find_node_by_hash(&self, node_hash: &TreeNodeHash) -> Result, Self::Error>; - fn find_node_by_parent_hash(&self, parent_hash: &TreeNodeHash) -> Result, Self::Error>; - fn find_all_instructions_by_node(&self, node_id: Self::Id) -> Result, Self::Error>; - fn update_prepare_qc(&self, item: &DbQc, transaction: &Self::DbTransaction) -> Result<(), Self::Error>; - fn update_locked_qc(&self, locked_qc: &DbQc, transaction: &Self::DbTransaction) -> Result<(), Self::Error>; -} diff --git a/dan_layer/core/src/storage/chain/chain_db_unit_of_work.rs b/dan_layer/core/src/storage/chain/chain_db_unit_of_work.rs deleted file mode 100644 index 81deb6e1dc2..00000000000 --- a/dan_layer/core/src/storage/chain/chain_db_unit_of_work.rs +++ /dev/null @@ -1,359 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - fmt::{Debug, Formatter}, - ops::DerefMut, - sync::{Arc, RwLock}, -}; - -use log::*; -use tari_dan_common_types::storage::UnitOfWorkTracker; -use tari_dan_engine::instructions::Instruction; - -use crate::{ - models::{Node, QuorumCertificate, TreeNodeHash}, - storage::{ - chain::{db_node::DbNode, ChainDbBackendAdapter, DbInstruction, DbQc}, - StorageError, - }, -}; - -const LOG_TARGET: &str = "tari::dan::chain_db::unit_of_work"; - -pub trait ChainDbUnitOfWork: Clone + Send + Sync { - fn commit(&mut self) -> Result<(), StorageError>; - fn add_node(&mut self, hash: TreeNodeHash, parent: TreeNodeHash, height: u32) -> Result<(), StorageError>; - fn add_instruction(&mut self, node_hash: TreeNodeHash, instruction: Instruction) -> Result<(), StorageError>; - fn get_locked_qc(&mut self) -> Result; - fn set_locked_qc(&mut self, qc: &QuorumCertificate) -> Result<(), StorageError>; - fn get_prepare_qc(&mut self) -> Result, StorageError>; - fn set_prepare_qc(&mut self, qc: &QuorumCertificate) -> Result<(), StorageError>; - fn commit_node(&mut self, node_hash: &TreeNodeHash) -> Result<(), StorageError>; - // fn find_proposed_node(&mut self, node_hash: TreeNodeHash) -> Result<(Self::Id, UnitOfWorkTracker), StorageError>; - fn get_tip_node(&self) -> Result, StorageError>; -} - -// Cloneable, Send, Sync wrapper -pub struct ChainDbUnitOfWorkImpl { - inner: Arc>>, -} - -impl ChainDbUnitOfWorkImpl { - pub fn new(adapter: TBackendAdapter) -> Self { - Self { - inner: Arc::new(RwLock::new(ChainDbUnitOfWorkInner::new(adapter))), - } - } -} - -impl Clone for ChainDbUnitOfWorkImpl { - fn clone(&self) -> Self { - Self { - inner: self.inner.clone(), - } - } -} - -impl ChainDbUnitOfWork for ChainDbUnitOfWorkImpl { - // pub fn register_clean(&mut self, item: UnitOfWorkTracker) { - // self.clean.push(item); - // } - - fn commit(&mut self) -> Result<(), StorageError> { - let mut inner = self.inner.write()?; - let tx = inner - .backend_adapter - .create_transaction() - .map_err(TBackendAdapter::Error::into)?; - - for (id, item) in &inner.nodes { - if item.is_dirty() { - match id { - Some(i) => inner - .backend_adapter - .update_node(i, &*item.get(), &tx) - .map_err(TBackendAdapter::Error::into)?, - None => inner - .backend_adapter - .insert_node(&*item.get(), &tx) - .map_err(TBackendAdapter::Error::into)?, - } - } - } - - for (id, item) in &inner.instructions { - if item.is_dirty() { - match id { - Some(_i) => { - unimplemented!("Cannot update instructions"); - }, - None => inner - .backend_adapter - .insert_instruction(&*item.get(), &tx) - .map_err(TBackendAdapter::Error::into)?, - } - } - } - - if let Some(ref locked_qc) = inner.locked_qc { - if locked_qc.is_dirty() { - inner - .backend_adapter - .update_locked_qc(&*locked_qc.get(), &tx) - .map_err(TBackendAdapter::Error::into)?; - } - } - - if let Some(ref prepare_qc) = inner.prepare_qc { - if prepare_qc.is_dirty() { - inner - .backend_adapter - .update_prepare_qc(&*prepare_qc.get(), &tx) - .map_err(TBackendAdapter::Error::into)?; - } - } - - inner - .backend_adapter - .commit(&tx) - .map_err(TBackendAdapter::Error::into)?; - - inner.nodes = vec![]; - inner.instructions = vec![]; - Ok(()) - } - - fn add_node(&mut self, hash: TreeNodeHash, parent: TreeNodeHash, height: u32) -> Result<(), StorageError> { - self.inner.write()?.nodes.push(( - None, - UnitOfWorkTracker::new( - DbNode { - hash, - parent, - height, - is_committed: false, - }, - true, - ), - )); - Ok(()) - } - - fn add_instruction(&mut self, node_hash: TreeNodeHash, instruction: Instruction) -> Result<(), StorageError> { - self.inner.write()?.instructions.push(( - None, - UnitOfWorkTracker::new(DbInstruction { node_hash, instruction }, true), - )); - Ok(()) - } - - fn get_locked_qc(&mut self) -> Result { - let mut inner = self.inner.write()?; - - if let Some(locked_qc) = &inner.locked_qc { - let locked_qc = locked_qc.get(); - return Ok(QuorumCertificate::new( - locked_qc.message_type, - locked_qc.view_number, - locked_qc.node_hash, - locked_qc.signature.clone(), - )); - } - - // finally hit the db - let qc = inner - .backend_adapter - .get_locked_qc() - .map_err(TBackendAdapter::Error::into)?; - inner.locked_qc = Some(UnitOfWorkTracker::new( - DbQc { - message_type: qc.message_type(), - view_number: qc.view_number(), - node_hash: *qc.node_hash(), - signature: qc.signature().cloned(), - }, - false, - )); - Ok(qc) - } - - fn set_locked_qc(&mut self, qc: &QuorumCertificate) -> Result<(), StorageError> { - let mut inner = self.inner.write()?; - - if let Some(locked_qc) = &inner.locked_qc.as_ref() { - let mut locked_qc = locked_qc.get_mut(); - locked_qc.message_type = qc.message_type(); - locked_qc.view_number = qc.view_number(); - locked_qc.node_hash = *qc.node_hash(); - locked_qc.signature = qc.signature().cloned(); - } else { - inner.locked_qc = Some(UnitOfWorkTracker::new( - DbQc { - message_type: qc.message_type(), - view_number: qc.view_number(), - node_hash: *qc.node_hash(), - signature: qc.signature().cloned(), - }, - true, - )); - } - - debug!( - target: LOG_TARGET, - "Marking proposed node '{}' as committed", - qc.node_hash() - ); - let found_node = inner.find_proposed_node(qc.node_hash())?; - let mut node = found_node.1.get_mut(); - let mut n = node.deref_mut(); - n.is_committed = true; - Ok(()) - } - - fn get_prepare_qc(&mut self) -> Result, StorageError> { - let mut inner = self.inner.write()?; - - if let Some(prepare_qc) = &inner.prepare_qc { - let prepare_qc = prepare_qc.get(); - return Ok(Some(QuorumCertificate::new( - prepare_qc.message_type, - prepare_qc.view_number, - prepare_qc.node_hash, - prepare_qc.signature.clone(), - ))); - } - - // finally hit the db - let qc = inner - .backend_adapter - .get_prepare_qc() - .map_err(TBackendAdapter::Error::into)?; - - inner.prepare_qc = qc.as_ref().map(|qc| { - UnitOfWorkTracker::new( - DbQc { - message_type: qc.message_type(), - view_number: qc.view_number(), - node_hash: *qc.node_hash(), - signature: qc.signature().cloned(), - }, - false, - ) - }); - Ok(qc) - } - - fn set_prepare_qc(&mut self, qc: &QuorumCertificate) -> Result<(), StorageError> { - // put it in the tracker - let _ = self.get_prepare_qc()?; - let mut inner = self.inner.write()?; - match inner.prepare_qc.as_mut() { - None => { - inner.prepare_qc = Some(UnitOfWorkTracker::new( - DbQc { - message_type: qc.message_type(), - view_number: qc.view_number(), - node_hash: *qc.node_hash(), - signature: qc.signature().cloned(), - }, - true, - )); - }, - Some(db_qc) => { - let mut db_qc = db_qc.get_mut(); - db_qc.message_type = qc.message_type(); - db_qc.view_number = qc.view_number(); - db_qc.node_hash = *qc.node_hash(); - db_qc.signature = qc.signature().cloned(); - }, - } - - Ok(()) - } - - fn commit_node(&mut self, node_hash: &TreeNodeHash) -> Result<(), StorageError> { - let mut inner = self.inner.write()?; - let found_node = inner.find_proposed_node(node_hash)?; - let mut node = found_node.1.get_mut(); - node.is_committed = true; - Ok(()) - } - - fn get_tip_node(&self) -> Result, StorageError> { - let inner = self.inner.read()?; - inner.get_tip_node() - } -} - -pub struct ChainDbUnitOfWorkInner { - backend_adapter: TBackendAdapter, - nodes: Vec<(Option, UnitOfWorkTracker)>, - instructions: Vec<(Option, UnitOfWorkTracker)>, - locked_qc: Option>, - prepare_qc: Option>, -} - -impl Debug for ChainDbUnitOfWorkInner { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - writeln!(f, "Nodes:{:?}", self.nodes) - } -} -impl ChainDbUnitOfWorkInner { - pub fn new(backend_adapter: TBackendAdapter) -> Self { - Self { - backend_adapter, - nodes: vec![], - instructions: vec![], - locked_qc: None, - prepare_qc: None, - } - } - - pub fn find_proposed_node( - &mut self, - node_hash: &TreeNodeHash, - ) -> Result<(Option, UnitOfWorkTracker), StorageError> { - for (id, item) in &self.nodes { - if &item.get().hash == node_hash { - return Ok((*id, item.clone())); - } - } - // finally hit the db - let (id, item) = self - .backend_adapter - .find_node_by_hash(node_hash) - .map_err(TBackendAdapter::Error::into)? - .ok_or(StorageError::NotFound)?; - let tracker = UnitOfWorkTracker::new(item, false); - self.nodes.push((Some(id), tracker.clone())); - Ok((Some(id), tracker)) - } - - pub fn get_tip_node(&self) -> Result, StorageError> { - let node = self - .backend_adapter - .get_tip_node() - .map_err(TBackendAdapter::Error::into)?; - Ok(node.map(Into::into)) - } -} diff --git a/dan_layer/core/src/storage/chain/db_instruction.rs b/dan_layer/core/src/storage/chain/db_instruction.rs deleted file mode 100644 index d8756cb2e2b..00000000000 --- a/dan_layer/core/src/storage/chain/db_instruction.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_dan_engine::instructions::Instruction; - -use crate::models::TreeNodeHash; - -#[derive(Debug, Clone)] -pub struct DbInstruction { - pub instruction: Instruction, - pub node_hash: TreeNodeHash, -} diff --git a/dan_layer/core/src/storage/chain/db_node.rs b/dan_layer/core/src/storage/chain/db_node.rs deleted file mode 100644 index 84acf2186fd..00000000000 --- a/dan_layer/core/src/storage/chain/db_node.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::models::TreeNodeHash; - -#[derive(Debug, Clone)] -pub struct DbNode { - pub hash: TreeNodeHash, - pub parent: TreeNodeHash, - pub height: u32, - pub is_committed: bool, -} diff --git a/dan_layer/core/src/storage/chain/db_qc.rs b/dan_layer/core/src/storage/chain/db_qc.rs deleted file mode 100644 index 8763ad30b06..00000000000 --- a/dan_layer/core/src/storage/chain/db_qc.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::models::{HotStuffMessageType, TreeNodeHash, ValidatorSignature, ViewId}; - -#[derive(Debug, Clone)] -pub struct DbQc { - pub message_type: HotStuffMessageType, - pub view_number: ViewId, - pub node_hash: TreeNodeHash, - pub signature: Option, -} diff --git a/dan_layer/core/src/storage/chain/metadata_key.rs b/dan_layer/core/src/storage/chain/metadata_key.rs deleted file mode 100644 index 2bc40fba255..00000000000 --- a/dan_layer/core/src/storage/chain/metadata_key.rs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::fmt::{Display, Formatter}; - -use crate::storage::metadata_backend_adapter::AsKeyBytes; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ChainDbMetadataKey { - CheckpointNumber, -} - -impl AsKeyBytes for ChainDbMetadataKey { - fn as_key_bytes(&self) -> &[u8] { - match self { - ChainDbMetadataKey::CheckpointNumber => b"checkpoint-number", - } - } -} - -impl Display for ChainDbMetadataKey { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", String::from_utf8_lossy(self.as_key_bytes())) - } -} diff --git a/dan_layer/core/src/storage/chain/mod.rs b/dan_layer/core/src/storage/chain/mod.rs deleted file mode 100644 index c7eb62aca69..00000000000 --- a/dan_layer/core/src/storage/chain/mod.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -mod chain_db; -mod chain_db_backend_adapter; -mod chain_db_unit_of_work; -mod db_instruction; -mod db_node; -mod db_qc; -mod metadata_key; - -pub use chain_db::ChainDb; -pub use chain_db_backend_adapter::ChainDbBackendAdapter; -pub use chain_db_unit_of_work::ChainDbUnitOfWork; -pub use db_instruction::DbInstruction; -pub use db_node::DbNode; -pub use db_qc::DbQc; -pub use metadata_key::ChainDbMetadataKey; diff --git a/dan_layer/core/src/storage/chain_storage_service.rs b/dan_layer/core/src/storage/chain_storage_service.rs deleted file mode 100644 index 956472b6911..00000000000 --- a/dan_layer/core/src/storage/chain_storage_service.rs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use async_trait::async_trait; - -use crate::{ - models::{HotStuffTreeNode, Payload, SidechainMetadata}, - storage::{chain::ChainDbUnitOfWork, StorageError}, -}; - -// TODO: perhaps rename to ChainBusinessLogic -// One per asset, per network -#[async_trait] -pub trait ChainStorageService { - async fn get_metadata(&self) -> Result; - async fn add_node( - &self, - node: &HotStuffTreeNode, - db: TUnitOfWork, - ) -> Result<(), StorageError>; -} diff --git a/dan_layer/core/src/storage/db_factory.rs b/dan_layer/core/src/storage/db_factory.rs deleted file mode 100644 index 543ae4c8929..00000000000 --- a/dan_layer/core/src/storage/db_factory.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_common_types::types::FixedHash; -use tari_dan_engine::state::{StateDb, StateDbBackendAdapter}; - -use crate::storage::{ - chain::{ChainDb, ChainDbBackendAdapter}, - global::{GlobalDb, GlobalDbBackendAdapter}, - StorageError, -}; - -pub trait DbFactory: Sync + Send + 'static { - type ChainDbBackendAdapter: ChainDbBackendAdapter; - type StateDbBackendAdapter: StateDbBackendAdapter; - type GlobalDbBackendAdapter: GlobalDbBackendAdapter; - - fn get_chain_db( - &self, - contract_id: &FixedHash, - ) -> Result>, StorageError>; - - fn get_or_create_chain_db( - &self, - contract_id: &FixedHash, - ) -> Result, StorageError>; - - fn get_state_db( - &self, - contract_id: &FixedHash, - ) -> Result>, StorageError>; - - fn get_or_create_state_db( - &self, - contract_id: &FixedHash, - ) -> Result, StorageError>; - - fn get_or_create_global_db(&self) -> Result, StorageError>; -} diff --git a/dan_layer/core/src/storage/error.rs b/dan_layer/core/src/storage/error.rs deleted file mode 100644 index 8733a78a366..00000000000 --- a/dan_layer/core/src/storage/error.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2021, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{io, sync::PoisonError}; - -use lmdb_zero as lmdb; -use tari_storage::lmdb_store::LMDBError; - -#[derive(Debug, thiserror::Error)] -pub enum StorageError { - #[error("Could not connect to storage:{reason}")] - ConnectionError { reason: String }, - #[error("IO Error: {0}")] - Io(#[from] io::Error), - #[error("LMDB: {0}")] - LmdbError(#[from] lmdb::Error), - #[error("LMDB Error: {0}")] - LMDBError(#[from] LMDBError), - #[error("Query error:{reason}")] - QueryError { reason: String }, - #[error("Migration error: {reason}")] - MigrationError { reason: String }, - #[error("Invalid unit of work tracker type")] - InvalidUnitOfWorkTrackerType, - #[error("Item does not exist")] - NotFound, - #[error("File system path does not exist")] - FileSystemPathDoesNotExist, - - #[error("General storage error: {details}")] - General { details: String }, - #[error("Lock error")] - LockError, -} - -impl From> for StorageError { - fn from(_err: PoisonError) -> Self { - Self::LockError - } -} diff --git a/dan_layer/core/src/storage/global/global_db.rs b/dan_layer/core/src/storage/global/global_db.rs deleted file mode 100644 index d630c107f44..00000000000 --- a/dan_layer/core/src/storage/global/global_db.rs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::sync::Arc; - -use tari_common_types::types::FixedHash; - -use crate::storage::{ - global::{ContractState, GlobalDbBackendAdapter, GlobalDbMetadataKey}, - StorageError, -}; - -#[derive(Debug, Clone)] -pub struct GlobalDb { - adapter: Arc, -} - -impl GlobalDb { - pub fn new(adapter: TGlobalDbBackendAdapter) -> Self { - Self { - adapter: Arc::new(adapter), - } - } - - pub fn set_data(&self, key: GlobalDbMetadataKey, value: &[u8]) -> Result<(), StorageError> { - self.adapter - .set_data(key, value) - .map_err(TGlobalDbBackendAdapter::Error::into) - } - - pub fn get_data(&self, key: GlobalDbMetadataKey) -> Result>, StorageError> { - self.adapter.get_data(key).map_err(TGlobalDbBackendAdapter::Error::into) - } - - pub fn save_contract( - &self, - contract: TGlobalDbBackendAdapter::NewModel, - state: ContractState, - ) -> Result<(), StorageError> { - self.adapter - .save_contract(contract, state) - .map_err(TGlobalDbBackendAdapter::Error::into) - } - - pub fn update_contract_state(&self, contract_id: FixedHash, state: ContractState) -> Result<(), StorageError> { - self.adapter - .update_contract_state(contract_id, state) - .map_err(TGlobalDbBackendAdapter::Error::into) - } - - pub fn get_contracts_with_state( - &self, - state: ContractState, - ) -> Result, StorageError> { - self.adapter - .get_contracts_with_state(state) - .map_err(TGlobalDbBackendAdapter::Error::into) - } -} diff --git a/dan_layer/core/src/storage/global/global_db_backend_adapter.rs b/dan_layer/core/src/storage/global/global_db_backend_adapter.rs deleted file mode 100644 index 1993e4ec15e..00000000000 --- a/dan_layer/core/src/storage/global/global_db_backend_adapter.rs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use num_derive::FromPrimitive; -use num_traits::FromPrimitive; -use tari_common_types::types::FixedHash; - -use crate::storage::StorageError; - -pub trait GlobalDbBackendAdapter: Send + Sync + Clone { - type BackendTransaction; - type Error: Into; - type Model; - type NewModel; - - fn create_transaction(&self) -> Result; - fn commit(&self, tx: &Self::BackendTransaction) -> Result<(), Self::Error>; - fn get_data(&self, key: GlobalDbMetadataKey) -> Result>, Self::Error>; - fn set_data(&self, key: GlobalDbMetadataKey, value: &[u8]) -> Result<(), Self::Error>; - fn get_data_with_connection( - &self, - key: &GlobalDbMetadataKey, - connection: &Self::BackendTransaction, - ) -> Result>, Self::Error>; - fn save_contract(&self, contract: Self::NewModel, state: ContractState) -> Result<(), Self::Error>; - fn update_contract_state(&self, contract_id: FixedHash, state: ContractState) -> Result<(), Self::Error>; - fn get_contracts_with_state(&self, state: ContractState) -> Result, Self::Error>; -} - -#[derive(Debug, Clone, Copy)] -pub enum GlobalDbMetadataKey { - LastScannedConstitutionHash, - LastScannedConstitutionHeight, -} - -impl GlobalDbMetadataKey { - pub fn as_key_bytes(self) -> &'static [u8] { - match self { - GlobalDbMetadataKey::LastScannedConstitutionHash => b"last_scanned_constitution_hash", - GlobalDbMetadataKey::LastScannedConstitutionHeight => b"last_scanned_constitution_height", - } - } -} - -#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, FromPrimitive)] -#[repr(u8)] -pub enum ContractState { - Pending = 0, - Accepted = 1, - Expired = 2, - QuorumMet = 3, - Active = 4, - Abandoned = 5, - Quarantined = 6, - Shutdown = 7, -} - -impl ContractState { - pub fn as_byte(self) -> u8 { - self as u8 - } - - /// Returns the Status that corresponds to the byte. None is returned if the byte does not correspond - pub fn from_byte(value: u8) -> Option { - FromPrimitive::from_u8(value) - } -} diff --git a/dan_layer/core/src/storage/global/mod.rs b/dan_layer/core/src/storage/global/mod.rs deleted file mode 100644 index 8ee36752bdb..00000000000 --- a/dan_layer/core/src/storage/global/mod.rs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -mod global_db; -pub use global_db::GlobalDb; - -mod global_db_backend_adapter; -pub use global_db_backend_adapter::{ContractState, GlobalDbBackendAdapter, GlobalDbMetadataKey}; diff --git a/dan_layer/core/src/storage/metadata_backend_adapter.rs b/dan_layer/core/src/storage/metadata_backend_adapter.rs deleted file mode 100644 index 8b883d1810b..00000000000 --- a/dan_layer/core/src/storage/metadata_backend_adapter.rs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_utilities::message_format::MessageFormat; - -use crate::storage::AtomicDb; - -pub trait MetadataBackendAdapter: AtomicDb + Send + Sync + Clone { - fn get_metadata( - &self, - key: &K, - transaction: &Self::DbTransaction, - ) -> Result, Self::Error>; - - fn set_metadata( - &self, - key: K, - value: T, - transaction: &Self::DbTransaction, - ) -> Result<(), Self::Error>; - - fn metadata_key_exists(&self, key: &K, transaction: &Self::DbTransaction) -> Result; -} - -pub trait AsKeyBytes { - fn as_key_bytes(&self) -> &[u8]; -} diff --git a/dan_layer/core/src/storage/mocks/chain_db.rs b/dan_layer/core/src/storage/mocks/chain_db.rs deleted file mode 100644 index b6d648afe7c..00000000000 --- a/dan_layer/core/src/storage/mocks/chain_db.rs +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::sync::{Arc, RwLock}; - -use tari_utilities::message_format::MessageFormat; - -use super::MemoryChainDb; -use crate::{ - models::{QuorumCertificate, TreeNodeHash}, - storage::{ - chain::{ChainDbBackendAdapter, ChainDbMetadataKey, DbInstruction, DbNode, DbQc}, - AtomicDb, - MetadataBackendAdapter, - StorageError, - }, -}; - -#[derive(Debug, Clone, Default)] -pub struct MockChainDbBackupAdapter { - db: Arc>, -} - -impl MockChainDbBackupAdapter { - pub fn new() -> Self { - Self { db: Default::default() } - } -} - -impl AtomicDb for MockChainDbBackupAdapter { - type DbTransaction = (); - type Error = StorageError; - - fn create_transaction(&self) -> Result { - Ok(()) - } - - fn commit(&self, _: &Self::DbTransaction) -> Result<(), Self::Error> { - Ok(()) - } -} - -impl ChainDbBackendAdapter for MockChainDbBackupAdapter { - type Id = usize; - type Payload = String; - - fn is_empty(&self) -> Result { - let lock = self.db.read()?; - Ok(lock.nodes.is_empty()) - } - - fn node_exists(&self, node_hash: &TreeNodeHash) -> Result { - let lock = self.db.read()?; - let exists = lock.nodes.rows().any(|rec| rec.hash == *node_hash); - Ok(exists) - } - - fn insert_node(&self, node: &DbNode, _: &Self::DbTransaction) -> Result<(), Self::Error> { - let mut lock = self.db.write()?; - lock.nodes.insert(node.clone()); - Ok(()) - } - - fn update_node(&self, id: &Self::Id, item: &DbNode, _: &Self::DbTransaction) -> Result<(), Self::Error> { - let mut lock = self.db.write()?; - if lock.nodes.update(*id, item.clone()) { - Ok(()) - } else { - Err(StorageError::NotFound) - } - } - - fn insert_instruction(&self, item: &DbInstruction, _: &Self::DbTransaction) -> Result<(), Self::Error> { - let mut lock = self.db.write()?; - lock.instructions.insert(item.clone()); - Ok(()) - } - - fn locked_qc_id(&self) -> Self::Id { - 1 - } - - fn prepare_qc_id(&self) -> Self::Id { - 1 - } - - fn find_highest_prepared_qc(&self) -> Result { - let lock = self.db.read()?; - let highest = lock - .prepare_qc - .rows() - .fold(None, |found: Option<&DbQc>, rec| match found { - Some(r) if rec.view_number > r.view_number => Some(rec), - Some(r) => Some(r), - None => Some(rec), - }) - .ok_or(StorageError::NotFound)?; - - Ok(highest.clone().into()) - } - - fn get_locked_qc(&self) -> Result { - let lock = self.db.read()?; - // FIXME: when this implementation is finalized in sqlite/lmdb impl - let rec = lock.locked_qc.rows().next().cloned().map(Into::into).unwrap(); - Ok(rec) - } - - fn get_prepare_qc(&self) -> Result, Self::Error> { - let lock = self.db.read()?; - // FIXME: when this implementation is finalized in sqlite/lmdb impl - let rec = lock.prepare_qc.rows().next().cloned().map(Into::into); - Ok(rec) - } - - fn find_node_by_hash(&self, node_hash: &TreeNodeHash) -> Result, Self::Error> { - let lock = self.db.read()?; - let recs = lock - .nodes - .records() - .find(|(_, rec)| rec.hash == *node_hash) - .map(|(id, node)| (id, node.clone())); - Ok(recs) - } - - fn find_node_by_parent_hash(&self, parent_hash: &TreeNodeHash) -> Result, Self::Error> { - let lock = self.db.read()?; - let rec = lock - .nodes - .records() - .find(|(_, rec)| rec.parent == *parent_hash) - .map(|(id, node)| (id, node.clone())); - Ok(rec) - } - - fn find_all_instructions_by_node(&self, node_id: Self::Id) -> Result, Self::Error> { - let lock = self.db.read()?; - let node = lock.nodes.get(node_id).ok_or(StorageError::NotFound)?; - let recs = lock - .instructions - .rows() - .filter(|rec| rec.node_hash == node.hash) - .cloned() - .collect(); - Ok(recs) - } - - fn update_prepare_qc(&self, item: &DbQc, _transaction: &Self::DbTransaction) -> Result<(), Self::Error> { - let mut lock = self.db.write()?; - let id = lock - .prepare_qc - .records() - .next() - .map(|(id, _)| id) - .ok_or(StorageError::NotFound)?; - lock.prepare_qc.update(id, item.clone()); - Ok(()) - } - - fn update_locked_qc(&self, locked_qc: &DbQc, _transaction: &Self::DbTransaction) -> Result<(), Self::Error> { - let mut lock = self.db.write()?; - let id = lock - .locked_qc - .records() - .next() - .map(|(id, _)| id) - .ok_or(StorageError::NotFound)?; - lock.locked_qc.update(id, locked_qc.clone()); - Ok(()) - } - - fn get_tip_node(&self) -> Result, Self::Error> { - let lock = self.db.read()?; - let found = lock - .nodes - .rows() - .fold(None, |val: Option<&DbNode>, row| match val { - Some(v) if v.height < row.height => Some(row), - Some(v) => Some(v), - None => Some(row), - }) - .cloned(); - - Ok(found) - } -} - -impl MetadataBackendAdapter for MockChainDbBackupAdapter { - fn get_metadata( - &self, - key: &ChainDbMetadataKey, - _transaction: &Self::DbTransaction, - ) -> Result, Self::Error> { - let lock = self.db.read()?; - let v = lock - .metadata - .rows() - .find(|(k, _)| k == key) - .map(|(_, v)| v) - .map(|v| T::from_binary(v).unwrap()); - Ok(v) - } - - fn set_metadata( - &self, - key: ChainDbMetadataKey, - value: T, - _transaction: &Self::DbTransaction, - ) -> Result<(), Self::Error> { - let mut lock = self.db.write()?; - let value = value.to_binary().unwrap(); - let id = lock.metadata.records().find(|(_, (k, _))| *k == key).map(|(id, _)| id); - match id { - Some(id) => { - lock.metadata.update(id, (key, value)); - }, - None => { - lock.metadata.insert((key, value)); - }, - } - - Ok(()) - } - - fn metadata_key_exists( - &self, - _key: &ChainDbMetadataKey, - _transaction: &Self::DbTransaction, - ) -> Result { - todo!() - } -} diff --git a/dan_layer/core/src/storage/mocks/global_db.rs b/dan_layer/core/src/storage/mocks/global_db.rs deleted file mode 100644 index eff7a7702e9..00000000000 --- a/dan_layer/core/src/storage/mocks/global_db.rs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_common_types::types::FixedHash; - -use crate::storage::{ - global::{ContractState, GlobalDbBackendAdapter, GlobalDbMetadataKey}, - StorageError, -}; - -#[derive(Debug, Clone, Default)] -pub struct MockGlobalDbBackupAdapter; - -impl GlobalDbBackendAdapter for MockGlobalDbBackupAdapter { - type BackendTransaction = (); - type Error = StorageError; - type Model = (); - type NewModel = (); - - fn create_transaction(&self) -> Result { - todo!() - } - - fn get_data(&self, _key: GlobalDbMetadataKey) -> Result>, Self::Error> { - todo!() - } - - fn set_data(&self, _key: GlobalDbMetadataKey, _value: &[u8]) -> Result<(), Self::Error> { - todo!() - } - - fn commit(&self, _tx: &Self::BackendTransaction) -> Result<(), Self::Error> { - todo!() - } - - fn get_data_with_connection( - &self, - _key: &GlobalDbMetadataKey, - _tx: &Self::BackendTransaction, - ) -> Result>, Self::Error> { - todo!() - } - - fn save_contract(&self, _contract: Self::Model, _status: ContractState) -> Result<(), Self::Error> { - todo!() - } - - fn update_contract_state(&self, _contract_id: FixedHash, _state: ContractState) -> Result<(), Self::Error> { - todo!() - } - - fn get_contracts_with_state(&self, _state: ContractState) -> Result, Self::Error> { - todo!() - } -} diff --git a/dan_layer/core/src/storage/mocks/mod.rs b/dan_layer/core/src/storage/mocks/mod.rs deleted file mode 100644 index e5af0da55c5..00000000000 --- a/dan_layer/core/src/storage/mocks/mod.rs +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub mod chain_db; -pub mod global_db; - -use std::{ - collections::HashMap, - sync::{Arc, RwLock}, -}; - -use tari_common_types::types::FixedHash; -use tari_dan_engine::state::{mocks::state_db::MockStateDbBackupAdapter, StateDb}; - -use crate::storage::{ - chain::{ChainDb, ChainDbMetadataKey, DbInstruction, DbNode, DbQc}, - global::GlobalDb, - mocks::{chain_db::MockChainDbBackupAdapter, global_db::MockGlobalDbBackupAdapter}, - DbFactory, - StorageError, -}; - -#[derive(Clone, Default)] -pub struct MockDbFactory { - chain_db: Arc>>, - state_db: Arc>>, - _global_db: Arc>, -} - -impl DbFactory for MockDbFactory { - type ChainDbBackendAdapter = MockChainDbBackupAdapter; - type GlobalDbBackendAdapter = MockGlobalDbBackupAdapter; - type StateDbBackendAdapter = MockStateDbBackupAdapter; - - fn get_chain_db( - &self, - contract_id: &FixedHash, - ) -> Result>, StorageError> { - Ok(self - .chain_db - .read() - .unwrap() - .get(contract_id) - .cloned() - .map(ChainDb::new)) - } - - fn get_or_create_chain_db( - &self, - contract_id: &FixedHash, - ) -> Result, StorageError> { - let entry = self.chain_db.write().unwrap().entry(*contract_id).or_default().clone(); - Ok(ChainDb::new(entry)) - } - - fn get_state_db( - &self, - contract_id: &FixedHash, - ) -> Result>, StorageError> { - Ok(self - .state_db - .read() - .unwrap() - .get(contract_id) - .cloned() - .map(|db| StateDb::new(*contract_id, db))) - } - - fn get_or_create_state_db( - &self, - contract_id: &FixedHash, - ) -> Result, StorageError> { - let entry = self.state_db.write().unwrap().entry(*contract_id).or_default().clone(); - Ok(StateDb::new(*contract_id, entry)) - } - - fn get_or_create_global_db(&self) -> Result, StorageError> { - // let entry = self.global_db.write().unwrap().clone(); - // Ok(GlobalDb::new(entry)) - todo!() - } -} - -#[derive(Debug, Default)] -pub(self) struct MemoryChainDb { - pub nodes: MemoryDbTable, - pub instructions: MemoryDbTable, - pub prepare_qc: MemoryDbTable, - pub locked_qc: MemoryDbTable, - pub metadata: MemoryDbTable<(ChainDbMetadataKey, Vec)>, -} - -#[derive(Debug)] -struct MemoryDbTable { - records: HashMap, - id_counter: usize, -} - -// We don't need/want the V: Default bound -impl Default for MemoryDbTable { - fn default() -> Self { - Self { - records: Default::default(), - id_counter: 0, - } - } -} - -impl MemoryDbTable { - pub fn next_id(&mut self) -> usize { - let id = self.id_counter; - self.id_counter = self.id_counter.wrapping_add(1); - id - } - - pub fn records(&self) -> impl Iterator { - self.records.iter().map(|(k, v)| (*k, v)) - } - - pub fn rows(&self) -> impl Iterator { - self.records.values() - } - - pub fn is_empty(&self) -> bool { - self.records.is_empty() - } - - pub fn get(&self, id: usize) -> Option<&V> { - self.records.get(&id) - } - - pub fn insert(&mut self, v: V) { - let id = self.next_id(); - self.records.insert(id, v); - } - - pub fn update(&mut self, id: usize, v: V) -> bool { - match self.records.get_mut(&id) { - Some(rec) => { - *rec = v; - true - }, - None => false, - } - } -} diff --git a/dan_layer/core/src/storage/mod.rs b/dan_layer/core/src/storage/mod.rs deleted file mode 100644 index 82e2ba4369b..00000000000 --- a/dan_layer/core/src/storage/mod.rs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub use chain_storage_service::ChainStorageService; -pub use error::StorageError; -pub use store::{AssetDataStore, AssetStore}; -pub mod chain; -mod chain_storage_service; -mod db_factory; -mod error; -pub mod global; -mod metadata_backend_adapter; -mod store; - -pub use atomic_db::AtomicDb; -pub use db_factory::DbFactory; -pub use metadata_backend_adapter::{AsKeyBytes, MetadataBackendAdapter}; - -mod atomic_db; -pub mod mocks; diff --git a/dan_layer/core/src/storage/store.rs b/dan_layer/core/src/storage/store.rs deleted file mode 100644 index d5619f7154e..00000000000 --- a/dan_layer/core/src/storage/store.rs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2021, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::{digital_assets_error::DigitalAssetError, models::TokenId}; - -// const PATRICIA_MAP_KEY: u64 = 1u64; - -pub trait AssetStore { - fn get_metadata(&mut self, token_id: &TokenId) -> Result>, DigitalAssetError>; - - fn replace_metadata(&mut self, token_id: &TokenId, value: &[u8]) -> Result<(), DigitalAssetError>; -} - -pub struct AssetDataStore { - backend: TBackend, -} - -impl AssetDataStore -where TBackend: AssetStore -{ - pub fn new(backend: TBackend) -> Self { - Self { backend } - } -} - -impl AssetStore for AssetDataStore -where TBackend: AssetStore -{ - fn get_metadata(&mut self, token_id: &TokenId) -> Result>, DigitalAssetError> { - let val = self.backend.get_metadata(token_id)?; - Ok(val) - } - - fn replace_metadata(&mut self, token_id: &TokenId, value: &[u8]) -> Result<(), DigitalAssetError> { - self.backend.replace_metadata(token_id, value)?; - Ok(()) - } -} diff --git a/dan_layer/core/src/template_command.rs b/dan_layer/core/src/template_command.rs deleted file mode 100644 index 2f1b1431d39..00000000000 --- a/dan_layer/core/src/template_command.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_dan_engine::state::StateDbUnitOfWork; - -use crate::digital_assets_error::DigitalAssetError; - -pub trait TemplateCommand { - fn try_execute( - &self, - db: TUnitOfWork, - ) -> Result; -} - -pub enum ExecutionResult { - Ok, - // Error, -} diff --git a/dan_layer/core/src/templates/hashing.rs b/dan_layer/core/src/templates/hashing.rs deleted file mode 100644 index abe1b7a535b..00000000000 --- a/dan_layer/core/src/templates/hashing.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use digest::Digest; -use tari_crypto::{ - hash_domain, - hashing::{DomainSeparatedHasher, LengthExtensionAttackResistant}, -}; - -hash_domain!( - DanLayerCoreTemplatesDomain, - "com.tari.tari_project.dan_layer.core.templates", - 1 -); - -pub(crate) const TIP004_TEMPLATE_LABEL: &str = "tip004_template"; - -pub(crate) fn dan_layer_templates_hasher( - label: &'static str, -) -> DomainSeparatedHasher { - DomainSeparatedHasher::::new_with_label(label) -} diff --git a/dan_layer/core/src/templates/mod.rs b/dan_layer/core/src/templates/mod.rs deleted file mode 100644 index 66b350a3e1a..00000000000 --- a/dan_layer/core/src/templates/mod.rs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub mod hashing; -pub mod tip002_template; -pub mod tip004_template; -pub mod tip721_template; diff --git a/dan_layer/core/src/templates/tip002_template.rs b/dan_layer/core/src/templates/tip002_template.rs deleted file mode 100644 index 26146720daa..00000000000 --- a/dan_layer/core/src/templates/tip002_template.rs +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use prost::Message; -use tari_common_types::types::PublicKey; -use tari_core::transactions::transaction_components::TemplateParameter; -use tari_dan_common_types::{proto::tips::tip002, TemplateId}; -use tari_dan_engine::{ - instructions::Instruction, - state::{StateDbUnitOfWork, StateDbUnitOfWorkReader}, -}; -use tari_utilities::{hex::Hex, ByteArray}; - -use crate::{models::InstructionSet, DigitalAssetError}; - -pub fn initial_instructions(template_param: &TemplateParameter) -> InstructionSet { - InstructionSet::from_vec(vec![Instruction::new( - TemplateId::Tip002, - "init".to_string(), - template_param.template_data.clone(), - PublicKey::default(), - )]) -} - -pub fn invoke_read_method( - method: &str, - args: &[u8], - state_db: &TUnitOfWork, -) -> Result>, DigitalAssetError> { - match method.to_lowercase().replace('_', "").as_str() { - "balanceof" => balance_of(args, state_db), - name => Err(DigitalAssetError::TemplateUnsupportedMethod { name: name.to_string() }), - } -} - -pub fn invoke_write_method( - method: &str, - args: &[u8], - state_db: &mut TUnitOfWork, -) -> Result<(), DigitalAssetError> { - match method.to_lowercase().replace('_', "").as_str() { - "init" => init(args, state_db), - "transfer" => transfer(args, state_db), - name => Err(DigitalAssetError::TemplateUnsupportedMethod { name: name.to_string() }), - } -} - -fn init(args: &[u8], state_db: &mut TUnitOfWork) -> Result<(), DigitalAssetError> { - let params = tip002::InitRequest::decode(args).map_err(|e| DigitalAssetError::ProtoBufDecodeError { - source: e, - message_type: "tip002::InitRequest".to_string(), - })?; - println!("{:?}", params); - state_db.set_value( - "owners".to_string(), - state_db.context().contract_id().to_vec(), - // TODO: Encode full owner data - Vec::from(params.total_supply.to_le_bytes()), - )?; - Ok(()) -} - -fn balance_of( - args: &[u8], - state_db: &TUnitOfWork, -) -> Result>, DigitalAssetError> { - let request = tip002::BalanceOfRequest::decode(&*args).map_err(|e| DigitalAssetError::ProtoBufDecodeError { - source: e, - message_type: "tip002::BalanceOfRequest".to_string(), - })?; - - let data = state_db.get_value("owners", &request.owner)?; - match data { - Some(data) => { - let mut data2: [u8; 8] = [0; 8]; - data2.copy_from_slice(&data); - - let balance = u64::from_le_bytes(data2); - let response = tip002::BalanceOfResponse { balance }; - let mut output_buffer = vec![]; - response - .encode(&mut output_buffer) - .map_err(|e| DigitalAssetError::ProtoBufEncodeError { - source: e, - message_type: "tip002::BalanceOfResponse".to_string(), - })?; - - Ok(Some(output_buffer)) - }, - None => Ok(None), - } -} - -fn transfer(args: &[u8], state_db: &mut TUnitOfWork) -> Result<(), DigitalAssetError> { - let request = tip002::TransferRequest::decode(&*args).map_err(|e| DigitalAssetError::ProtoBufDecodeError { - source: e, - message_type: "tip002::TransferRequest".to_string(), - })?; - - println!("{:?}", request); - let data = state_db.get_value("owners", &request.from)?; - match data { - Some(data) => { - let mut data2: [u8; 8] = [0; 8]; - data2.copy_from_slice(&data); - let balance = u64::from_le_bytes(data2); - if balance < request.amount { - return Err(DigitalAssetError::NotEnoughFunds); - } - let new_balance = balance - request.amount; - println!("{:?}", new_balance); - state_db.set_value( - "owners".to_string(), - request.from.clone(), - Vec::from(new_balance.to_le_bytes()), - )?; - let receiver_data = state_db.get_value("owners", &request.to)?; - let mut receiver_balance = match receiver_data { - Some(d) => { - let mut data2: [u8; 8] = [0; 8]; - data2.copy_from_slice(&d); - - u64::from_le_bytes(data2) - }, - None => 0, - }; - println!("{:?}", receiver_balance); - receiver_balance = receiver_balance - .checked_add(request.amount) - .ok_or(DigitalAssetError::Overflow)?; - println!("{:?}", receiver_balance); - state_db.set_value( - "owners".to_string(), - request.to, - Vec::from(receiver_balance.to_le_bytes()), - )?; - Ok(()) - }, - None => Err(DigitalAssetError::NotFound { - entity: "address", - id: request.from.to_hex(), - }), - } -} diff --git a/dan_layer/core/src/templates/tip004_template.rs b/dan_layer/core/src/templates/tip004_template.rs deleted file mode 100644 index 4f14661fa22..00000000000 --- a/dan_layer/core/src/templates/tip004_template.rs +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use log::*; -use prost::Message; -use tari_core::transactions::transaction_components::TemplateParameter; -use tari_crypto::hash::blake2::Blake256; -use tari_dan_common_types::proto::tips::tip004; -use tari_dan_engine::state::{StateDbUnitOfWork, StateDbUnitOfWorkReader}; -use tari_utilities::hex::Hex; - -use super::hashing::{dan_layer_templates_hasher, TIP004_TEMPLATE_LABEL}; -use crate::{models::InstructionSet, DigitalAssetError}; - -const LOG_TARGET: &str = "tari::dan_layer::core::templates::tip004_template"; - -pub fn initial_instructions(_: &TemplateParameter) -> InstructionSet { - InstructionSet::empty() -} - -pub fn invoke_read_method( - method: &str, - args: &[u8], - state_db: &TUnitOfWork, -) -> Result>, DigitalAssetError> { - match method.to_lowercase().replace('_', "").as_str() { - "balanceof" => balance_of(args, state_db), - "tokenofownerbyindex" => token_of_owner_by_index(args, state_db), - name => Err(DigitalAssetError::TemplateUnsupportedMethod { name: name.to_string() }), - } -} - -pub fn invoke_write_method( - method: &str, - args: &[u8], - state_db: &mut TUnitOfWork, -) -> Result<(), DigitalAssetError> { - match method.to_lowercase().replace('_', "").as_str() { - "mint" => mint(args, state_db), - name => Err(DigitalAssetError::TemplateUnsupportedMethod { name: name.to_string() }), - } -} - -fn mint(args: &[u8], state_db: &mut TUnitOfWork) -> Result<(), DigitalAssetError> { - let request = tip004::MintRequest::decode(&*args).map_err(|e| DigitalAssetError::ProtoBufDecodeError { - source: e, - message_type: "tip004::MintRequest".to_string(), - })?; - - let token: String = request.token.clone(); - let owner: Vec = request.owner; - - let hash = hash_of(&token); - - match state_db.get_u64("id_of", &hash)? { - Some(_id) => { - // unimplemented!("Token has already been minted"); - error!(target: LOG_TARGET, "Token has already been minted"); - }, - None => { - let total_supply = state_db.get_u64("info", "total_supply".as_bytes())?.unwrap_or_default(); - state_db.set_u64("id_of", &hash, total_supply)?; - state_db.set_u64("info", "total_supply".as_bytes(), total_supply + 1)?; - - state_db.set_value("owners".to_string(), total_supply.to_le_bytes().to_vec(), owner)?; - // TODO: this might be too specific - state_db.set_value( - "tokens".to_string(), - total_supply.to_le_bytes().to_vec(), - Vec::from(token.as_bytes()), - )?; - }, - } - - Ok(()) -} - -fn hash_of(s: &str) -> Vec { - dan_layer_templates_hasher::(TIP004_TEMPLATE_LABEL) - .chain(s) - .finalize() - .as_ref() - .to_vec() -} - -fn balance_of( - args: &[u8], - state_db: &TUnitOfWork, -) -> Result>, DigitalAssetError> { - // TODO: move this to the invoke_read_method method - let request = tip004::BalanceOfRequest::decode(&*args).map_err(|e| DigitalAssetError::ProtoBufDecodeError { - source: e, - message_type: "tip004::BalanceOfRequest".to_string(), - })?; - - let owner = request.owner; - let owner_records = state_db.find_keys_by_value("owners", &owner)?; - let num_tokens = owner_records.len(); - let response = tip004::BalanceOfResponse { - num_tokens: num_tokens as u64, - }; - let response_bytes = response.encode_to_vec(); - Ok(Some(response_bytes)) -} - -fn token_of_owner_by_index( - args: &[u8], - state_db: &TUnitOfWork, -) -> Result>, DigitalAssetError> { - // TODO: move this to the invoke_read_method method - let request = - tip004::TokenOfOwnerByIndexRequest::decode(&*args).map_err(|e| DigitalAssetError::ProtoBufDecodeError { - source: e, - message_type: "tip004::TokenOfOwnerByIndex".to_string(), - })?; - - let owner = request.owner.clone(); - let index = request.index; - let owner_records = state_db.find_keys_by_value("owners", &owner)?; - #[allow(clippy::cast_possible_truncation)] - if let Some(token_id) = owner_records.into_iter().nth(index as usize) { - let token = state_db - .get_value("tokens", &token_id)? - .ok_or_else(|| DigitalAssetError::NotFound { - entity: "state_keys", - id: format!("tokens.{}", token_id.to_hex()), - })?; - let response = tip004::TokenOfOwnerByIndexResponse { - token_id, - token: String::from_utf8(token).expect("should fix this"), - }; - let response_bytes = response.encode_to_vec(); - Ok(Some(response_bytes)) - } else { - Ok(None) - } -} diff --git a/dan_layer/core/src/templates/tip721_template.rs b/dan_layer/core/src/templates/tip721_template.rs deleted file mode 100644 index 8ab09bf29e6..00000000000 --- a/dan_layer/core/src/templates/tip721_template.rs +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use log::*; -use prost::Message; -use tari_core::transactions::transaction_components::TemplateParameter; -use tari_dan_common_types::proto::tips::tip721; -use tari_dan_engine::state::{StateDbUnitOfWork, StateDbUnitOfWorkReader}; -use tari_utilities::{hex::Hex, ByteArray}; - -use crate::{models::InstructionSet, DigitalAssetError}; - -const LOG_TARGET: &str = "tari::dan_layer::core::templates::tip721_template"; - -pub fn initial_instructions(_: &TemplateParameter) -> InstructionSet { - InstructionSet::empty() -} - -pub fn invoke_read_method( - method: &str, - args: &[u8], - state_db: &TUnitOfWork, -) -> Result>, DigitalAssetError> { - match method.to_lowercase().replace('_', "").as_str() { - "ownerof" => { - let request = - tip721::OwnerOfRequest::decode(&*args).map_err(|e| DigitalAssetError::ProtoBufDecodeError { - source: e, - message_type: "tip721::OwnerOfRequest".to_string(), - })?; - let response = tip721::OwnerOfResponse { - owner: owner_of(request.token_id, state_db)?, - }; - Ok(Some(response.encode_to_vec())) - }, - name => Err(DigitalAssetError::TemplateUnsupportedMethod { name: name.to_string() }), - } -} - -pub fn invoke_write_method( - method: &str, - args: &[u8], - state_db: &mut TUnitOfWork, -) -> Result<(), DigitalAssetError> { - match method.to_lowercase().replace('_', "").as_str() { - "transferfrom" => transfer_from(args, state_db), - name => Err(DigitalAssetError::TemplateUnsupportedMethod { name: name.to_string() }), - } -} - -fn owner_of( - token_id: Vec, - state_db: &TUnitOfWork, -) -> Result, DigitalAssetError> { - state_db - .get_value("owners", &token_id)? - .ok_or_else(|| DigitalAssetError::NotFound { - entity: "owner", - id: token_id.to_hex(), - }) -} - -fn transfer_from( - args: &[u8], - state_db: &mut TUnitOfWork, -) -> Result<(), DigitalAssetError> { - let request = tip721::TransferFromRequest::decode(&*args).map_err(|e| DigitalAssetError::ProtoBufDecodeError { - source: e, - message_type: "tip721::TransferFromRequest".to_string(), - })?; - - debug!(target: LOG_TARGET, "transfer_from called"); - let from = request.from.clone(); - let to = request.to.clone(); - let token_id = request.token_id; - - let owner = state_db - .get_value("owners", &token_id)? - .ok_or_else(|| DigitalAssetError::NotFound { - entity: "owner", - id: token_id.to_hex(), - })?; - if owner != from { - return Err(DigitalAssetError::NotAuthorised( - "Not authorized to send this address".to_string(), - )); - } - // TODO: check signature - - state_db.set_value("owners".to_string(), token_id, to.to_vec())?; - Ok(()) -} diff --git a/dan_layer/core/src/types.rs b/dan_layer/core/src/types.rs deleted file mode 100644 index e3f43d1c3db..00000000000 --- a/dan_layer/core/src/types.rs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_crypto::{ - ristretto::{RistrettoPublicKey, RistrettoSecretKey}, - signatures::CommitmentSignature, - tari_utilities::{ByteArray, ByteArrayError}, -}; - -pub type ComSig = CommitmentSignature; - -pub fn create_com_sig_from_bytes(_bytes: &[u8]) -> Result { - Ok(ComSig::default()) - // Ok(ComSig::new( - // HomomorphicCommitment::from_bytes(&bytes[0..32])?, - // RistrettoSecretKey::from_bytes(&bytes[33..64])?, - // RistrettoSecretKey::from_bytes(&bytes[64..96])?, - // )) -} - -pub fn com_sig_to_bytes(comsig: &ComSig) -> Vec { - let mut v = Vec::from(comsig.public_nonce().as_bytes()); - v.extend_from_slice(comsig.u().as_bytes()); - v.extend_from_slice(comsig.v().as_bytes()); - v -} diff --git a/dan_layer/core/src/workers/consensus_worker.rs b/dan_layer/core/src/workers/consensus_worker.rs deleted file mode 100644 index eeff43679f0..00000000000 --- a/dan_layer/core/src/workers/consensus_worker.rs +++ /dev/null @@ -1,587 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::sync::{ - atomic::{AtomicBool, Ordering}, - Arc, -}; - -use log::*; -use tari_common_types::types::PublicKey; -use tari_dan_engine::state::{models::StateRoot, StateDbUnitOfWork, StateDbUnitOfWorkImpl, StateDbUnitOfWorkReader}; -use tari_shutdown::ShutdownSignal; -use tokio::time::Duration; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::{domain_events::ConsensusWorkerDomainEvent, AssetDefinition, ConsensusWorkerState, View, ViewId}, - services::{CheckpointManager, CommitteeManager, EventsPublisher, PayloadProvider, ServiceSpecification}, - storage::{ - chain::{ChainDb, ChainDbUnitOfWork}, - DbFactory, - }, - workers::{states, states::ConsensusWorkerStateEvent}, -}; - -const LOG_TARGET: &str = "tari::dan::consensus_worker"; - -pub struct ConsensusWorker { - inbound_connections: TSpecification::InboundConnectionService, - outbound_service: TSpecification::OutboundService, - state: ConsensusWorkerState, - current_view_id: ViewId, - committee_manager: TSpecification::CommitteeManager, - timeout: Duration, - node_address: TSpecification::Addr, - payload_provider: TSpecification::PayloadProvider, - events_publisher: TSpecification::EventsPublisher, - signing_service: TSpecification::SigningService, - payload_processor: TSpecification::PayloadProcessor, - asset_definition: AssetDefinition, - base_node_client: TSpecification::BaseNodeClient, - db_factory: TSpecification::DbFactory, - chain_storage_service: TSpecification::ChainStorageService, - state_db_unit_of_work: Option>, - state_db_state_root: Option, - checkpoint_manager: TSpecification::CheckpointManager, - validator_node_client_factory: TSpecification::ValidatorNodeClientFactory, -} - -impl> ConsensusWorker { - pub fn new( - inbound_connections: TSpecification::InboundConnectionService, - outbound_service: TSpecification::OutboundService, - committee_manager: TSpecification::CommitteeManager, - node_id: TSpecification::Addr, - payload_provider: TSpecification::PayloadProvider, - events_publisher: TSpecification::EventsPublisher, - signing_service: TSpecification::SigningService, - payload_processor: TSpecification::PayloadProcessor, - asset_definition: AssetDefinition, - base_node_client: TSpecification::BaseNodeClient, - timeout: Duration, - db_factory: TSpecification::DbFactory, - chain_storage_service: TSpecification::ChainStorageService, - checkpoint_manager: TSpecification::CheckpointManager, - validator_node_client_factory: TSpecification::ValidatorNodeClientFactory, - ) -> Self { - Self { - inbound_connections, - state: ConsensusWorkerState::Starting, - current_view_id: ViewId(0), - timeout, - outbound_service, - committee_manager, - node_address: node_id, - payload_provider, - events_publisher, - signing_service, - payload_processor, - asset_definition, - base_node_client, - db_factory, - chain_storage_service, - state_db_state_root: None, - state_db_unit_of_work: None, - checkpoint_manager, - validator_node_client_factory, - } - } - - fn get_current_view(&self) -> Result { - Ok(View { - view_id: self.current_view_id, - is_leader: self - .committee_manager - .current_committee()? - .leader_for_view(self.current_view_id) == - &self.node_address, - }) - } - - pub async fn run( - &mut self, - shutdown: ShutdownSignal, - max_views_to_process: Option, - stop: Arc, - ) -> Result<(), DigitalAssetError> { - let chain_db = self - .db_factory - .get_or_create_chain_db(&self.asset_definition.contract_id)?; - self.current_view_id = chain_db - .get_tip_node()? - .map(|n| ViewId(u64::from(n.height()))) - .unwrap_or_else(|| ViewId(0)); - info!( - target: LOG_TARGET, - "🚀 Consensus worker started for asset '{}'. Tip: {}", - self.asset_definition.contract_id, - self.current_view_id - ); - let starting_view = self.current_view_id; - while !stop.load(Ordering::Relaxed) { - if let Some(max) = max_views_to_process { - if max <= self.current_view_id.0 - starting_view.0 { - break; - } - } - let mut processor = ConsensusWorkerProcessor { - worker: self, - chain_db: &chain_db, - shutdown: &shutdown, - }; - let next_event = processor.next_state_event().await?; - if next_event.must_shutdown() { - info!( - target: LOG_TARGET, - "Consensus worker is shutting down because {}", - next_event.shutdown_reason().unwrap_or_default() - ); - break; - } - let (from, to) = self.transition(next_event)?; - debug!( - target: LOG_TARGET, - "Transitioning from {:?} to {:?} ({})", from, to, self.current_view_id - ); - - self.events_publisher - .publish(ConsensusWorkerDomainEvent::StateChanged { from, to }); - } - - Ok(()) - } -} - -struct ConsensusWorkerProcessor<'a, T: ServiceSpecification> { - worker: &'a mut ConsensusWorker, - chain_db: &'a ChainDb, - shutdown: &'a ShutdownSignal, -} - -impl<'a, T: ServiceSpecification> ConsensusWorkerProcessor<'a, T> { - async fn next_state_event(&mut self) -> Result { - use ConsensusWorkerState::{Commit, Decide, Idle, NextView, PreCommit, Prepare, Starting, Synchronizing}; - match &mut self.worker.state { - Starting => self.starting().await, - Synchronizing => self.synchronizing().await, - Prepare => self.prepare().await, - PreCommit => self.pre_commit().await, - Commit => self.commit().await, - Decide => self.decide().await, - NextView => self.next_view().await, - Idle => self.idle().await, - } - } - - async fn starting(&mut self) -> Result { - states::Starting::::new() - .next_event( - &mut self.worker.base_node_client, - &self.worker.asset_definition, - &mut self.worker.committee_manager, - &self.worker.db_factory, - &self.worker.node_address, - ) - .await - } - - async fn synchronizing(&mut self) -> Result { - states::Synchronizing::::new() - .next_event( - &mut self.worker.base_node_client, - &self.worker.asset_definition, - &self.worker.db_factory, - &self.worker.validator_node_client_factory, - &self.worker.node_address, - ) - .await - } - - async fn prepare(&mut self) -> Result { - let mut unit_of_work = self.chain_db.new_unit_of_work(); - let mut state_tx = self - .worker - .db_factory - .get_state_db(&self.worker.asset_definition.contract_id)? - .ok_or(DigitalAssetError::MissingDatabase)? - .new_unit_of_work(self.worker.current_view_id.as_u64()); - - let mut prepare = states::Prepare::::new( - self.worker.node_address.clone(), - self.worker.asset_definition.contract_id, - ); - let res = prepare - .next_event( - &self.worker.get_current_view()?, - self.worker.timeout, - &self.worker.asset_definition, - self.worker.committee_manager.current_committee()?, - &self.worker.inbound_connections, - &mut self.worker.outbound_service, - &mut self.worker.payload_provider, - &self.worker.signing_service, - &mut self.worker.payload_processor, - &self.worker.chain_storage_service, - unit_of_work.clone(), - &mut state_tx, - &self.worker.db_factory, - ) - .await?; - // Will only be committed in DECIDE - self.worker.state_db_state_root = Some(state_tx.calculate_root()?); - self.worker.state_db_unit_of_work = Some(state_tx); - unit_of_work.commit()?; - Ok(res) - } - - async fn pre_commit(&mut self) -> Result { - let mut unit_of_work = self.chain_db.new_unit_of_work(); - let mut state = states::PreCommitState::::new( - self.worker.node_address.clone(), - self.worker.committee_manager.current_committee()?.clone(), - self.worker.asset_definition.contract_id, - ); - let res = state - .next_event( - self.worker.timeout, - &self.worker.get_current_view()?, - &self.worker.inbound_connections, - &mut self.worker.outbound_service, - &self.worker.signing_service, - unit_of_work.clone(), - ) - .await?; - unit_of_work.commit()?; - Ok(res) - } - - async fn commit(&mut self) -> Result { - let current_checkpoint_num = self.chain_db.get_current_checkpoint_number()?; - let mut unit_of_work = self.chain_db.new_unit_of_work(); - let mut state = states::CommitState::::new( - self.worker.node_address.clone(), - self.worker.asset_definition.contract_id, - self.worker.committee_manager.current_committee()?.clone(), - ); - let proposed_state_root = - self.worker - .state_db_state_root - .as_ref() - .copied() - .ok_or_else(|| DigitalAssetError::InvalidLogicPath { - reason: "state_db_state_root is None in commit phase".to_string(), - })?; - let res = state - .next_event( - self.worker.timeout, - &self.worker.get_current_view()?, - &mut self.worker.inbound_connections, - &mut self.worker.outbound_service, - &self.worker.signing_service, - unit_of_work.clone(), - proposed_state_root, - current_checkpoint_num, - ) - .await?; - unit_of_work.commit()?; - Ok(res) - } - - async fn decide(&mut self) -> Result { - let mut unit_of_work = self.chain_db.new_unit_of_work(); - let mut state = states::DecideState::::new( - self.worker.node_address.clone(), - self.worker.asset_definition.contract_id, - self.worker.committee_manager.current_committee()?.clone(), - ); - let current_view = self.worker.get_current_view()?; - let res = state - .next_event( - self.worker.timeout, - ¤t_view, - &mut self.worker.inbound_connections, - &mut self.worker.outbound_service, - unit_of_work.clone(), - &mut self.worker.payload_provider, - ) - .await?; - - unit_of_work.commit()?; - if let Some(mut state_tx) = self.worker.state_db_unit_of_work.take() { - state_tx.commit()?; - // TODO: Read checkpoint interval from constitution - if current_view.is_leader() && current_view.view_id().as_u64() % 50 == 0 { - let signatures = state.collected_checkpoint_signatures(); - let checkpoint_number = self.chain_db.get_current_checkpoint_number()?; - self.worker - .checkpoint_manager - .create_checkpoint(checkpoint_number, state_tx.calculate_root()?, &signatures) - .await?; - self.chain_db.increment_checkpoint_number()?; - } - Ok(res) - } else { - // technically impossible - error!(target: LOG_TARGET, "No state unit of work was present"); - Err(DigitalAssetError::InvalidLogicPath { - reason: "Tried to commit state after DECIDE, but no state tx was present".to_string(), - }) - } - } - - async fn next_view(&mut self) -> Result { - info!( - target: LOG_TARGET, - "Status: {} in mempool ", - self.worker.payload_provider.get_payload_queue().await, - ); - self.worker.state_db_state_root = None; - self.worker.state_db_unit_of_work = None; - let mut state = states::NextViewState::::new(); - state - .next_event( - &self.worker.get_current_view()?, - &self.worker.db_factory, - &mut self.worker.outbound_service, - self.worker.committee_manager.current_committee()?, - self.worker.node_address.clone(), - &self.worker.asset_definition, - &self.worker.payload_provider, - self.shutdown, - ) - .await - } - - async fn idle(&mut self) -> Result { - info!(target: LOG_TARGET, "No work to do, idling"); - let state = states::IdleState::default(); - state.next_event().await - } -} - -impl> ConsensusWorker { - fn transition( - &mut self, - event: ConsensusWorkerStateEvent, - ) -> Result<(ConsensusWorkerState, ConsensusWorkerState), DigitalAssetError> { - use ConsensusWorkerState::{Commit, Decide, Idle, NextView, PreCommit, Prepare, Starting, Synchronizing}; - #[allow(clippy::enum_glob_use)] - use ConsensusWorkerStateEvent::*; - let from = self.state; - self.state = match (&self.state, event) { - (Starting, Initialized) => Synchronizing, - (Synchronizing, Synchronized) => NextView, - (_, NotPartOfCommittee) => Idle, - (Idle, TimedOut) => Starting, - (_, TimedOut) => { - warn!(target: LOG_TARGET, "State timed out for {}", self.current_view_id); - NextView - }, - (NextView, NewView { new_view }) => { - self.current_view_id = new_view; - Prepare - }, - (Prepare, Prepared) => PreCommit, - (PreCommit, PreCommitted) => Commit, - (Commit, Committed) => Decide, - (Decide, Decided) => NextView, - (Synchronizing, BaseLayerCheckpointNotFound | BaseLayerAssetRegistrationNotFound) => { - info!(target: LOG_TARGET, "No initial checkpoint."); - NextView - }, - (_, BaseLayerCheckpointNotFound | BaseLayerAssetRegistrationNotFound) => { - unimplemented!("Base layer checkpoint not found!") - }, - (s, e) => { - println!("{:?}", s); - println!("{:?}", e); - unimplemented!("State machine transition not implemented") - }, - }; - Ok((from, self.state)) - } -} - -#[cfg(test)] -mod test { - use tari_crypto::ristretto::RistrettoPublicKey; - use tari_shutdown::Shutdown; - use tokio::task::JoinHandle; - - use super::*; - use crate::{ - models::{ - Committee, - ConsensusWorkerState::{Commit, Decide, NextView, PreCommit, Prepare}, - TariDanPayload, - }, - services::{ - infrastructure_services::mocks::{mock_outbound, MockInboundConnectionService, MockOutboundService}, - mocks::{ - create_public_key, - mock_base_node_client, - mock_checkpoint_manager, - mock_events_publisher, - mock_payload_processor, - mock_signing_service, - mock_static_payload_provider, - MockChainStorageService, - MockCommitteeManager, - MockEventsPublisher, - MockServiceSpecification, - MockValidatorNodeClientFactory, - }, - }, - storage::mocks::MockDbFactory, - }; - - fn start_replica( - inbound: MockInboundConnectionService, - outbound: MockOutboundService, - committee_manager: MockCommitteeManager, - node_id: RistrettoPublicKey, - shutdown_signal: ShutdownSignal, - events_publisher: MockEventsPublisher, - ) -> JoinHandle<()> { - let payload_provider = mock_static_payload_provider(); - let signing_service = mock_signing_service(); - let payload_processor = mock_payload_processor(); - let asset_definition = AssetDefinition::default(); - let base_node_client = mock_base_node_client(); - let timeout = Duration::from_secs(5); - let db_factory = MockDbFactory::default(); - let chain_storage_service = MockChainStorageService::default(); - let checkpoint_manager = mock_checkpoint_manager(); - let validator_node_client_factory = MockValidatorNodeClientFactory::default(); - let mut replica_a = ConsensusWorker::::new( - inbound, - outbound, - committee_manager, - node_id, - payload_provider, - events_publisher, - signing_service, - payload_processor, - asset_definition, - base_node_client, - timeout, - db_factory, - chain_storage_service, - checkpoint_manager, - validator_node_client_factory, - ); - tokio::spawn(async move { - let max_views_to_process = Some(2); - let stop = Arc::new(AtomicBool::default()); - let _res = replica_a.run(shutdown_signal, max_views_to_process, stop).await; - }) - } - - #[tokio::test] - #[ignore] - async fn test_simple_case() { - let mut shutdown = Shutdown::new(); - let signal = shutdown.to_signal(); - - let address_a = create_public_key(); - let address_b = create_public_key(); - - let committee = Committee::new(vec![address_a.clone(), address_b.clone()]); - let mut outbound = mock_outbound(committee.members.clone()); - let committee_manager = MockCommitteeManager { committee }; - - let inbound_a = outbound.take_inbound(&address_a.clone()).unwrap(); - let inbound_b = outbound.take_inbound(&address_b.clone()).unwrap(); - // let inbound_c = outbound.take_inbound(&"C").unwrap(); - // let inbound_d = outbound.take_inbound(&"D").unwrap(); - - let events = [ - mock_events_publisher(), - mock_events_publisher(), - mock_events_publisher(), - mock_events_publisher(), - ]; - - let task_a = start_replica( - inbound_a, - outbound.clone(), - committee_manager.clone(), - address_a, - signal.clone(), - events[0].clone(), - ); - let task_b = start_replica( - inbound_b, - outbound.clone(), - committee_manager, - address_b, - signal.clone(), - events[1].clone(), - ); - // let task_c = start_replica( - // inbound_c, - // outbound.clone(), - // committee.clone(), - // "C", - // signal.clone(), - // events[2].clone(), - // ); - // let task_d = start_replica( - // inbound_d, - // outbound.clone(), - // committee.clone(), - // "D", - // signal.clone(), - // events[3].clone(), - // ); - shutdown.trigger(); - task_a.await.unwrap(); - task_b.await.unwrap(); - // task_c.await.unwrap(); - // task_d.await.unwrap(); - - // assert_eq!(events[0].to_vec(), vec![ConsensusWorkerDomainEvent::StateChanged { - // old: Starting, - // new: Prepare - // }]); - - assert_state_change(&events[0].to_vec(), vec![ - Prepare, NextView, Prepare, PreCommit, Commit, Decide, NextView, Prepare, PreCommit, Commit, Decide, - NextView, - ]); - assert_state_change(&events[1].to_vec(), vec![ - Prepare, NextView, Prepare, PreCommit, Commit, Decide, NextView, Prepare, PreCommit, Commit, Decide, - NextView, - ]); - } - - fn assert_state_change(events: &[ConsensusWorkerDomainEvent], states: Vec) { - println!("{:?}", events); - let mapped_events = events.iter().map(|e| match e { - ConsensusWorkerDomainEvent::StateChanged { from: _, to: new } => Some(new), - }); - for (state, event) in states.iter().zip(mapped_events) { - assert_eq!(state, event.unwrap()) - } - } -} diff --git a/dan_layer/core/src/workers/mod.rs b/dan_layer/core/src/workers/mod.rs deleted file mode 100644 index e1afe1c1a6a..00000000000 --- a/dan_layer/core/src/workers/mod.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -mod consensus_worker; -pub mod states; - -pub use consensus_worker::ConsensusWorker; - -mod state_sync; -pub use state_sync::StateSyncError; diff --git a/dan_layer/core/src/workers/state_sync/error.rs b/dan_layer/core/src/workers/state_sync/error.rs deleted file mode 100644 index c336e17fe1c..00000000000 --- a/dan_layer/core/src/workers/state_sync/error.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_dan_engine::state::error::StateStorageError; - -use crate::{services::ValidatorNodeClientError, storage::StorageError}; - -#[derive(Debug, thiserror::Error)] -pub enum StateSyncError { - #[error( - "This validator node is the only committee member but its state is not synchronized. Unable to recover state." - )] - NoOtherCommitteeMembersToSync, - #[error("Storage error: {0}")] - StorageError(#[from] StorageError), - #[error("State storage error: {0}")] - StateStorageError(#[from] StateStorageError), - #[error("Invalid state Merkle root")] - InvalidStateMerkleRoot, - #[error("Remote peer does not have tip node")] - RemotePeerDoesNotHaveTipNode, - #[error("Validator node client call failed: {0}")] - ValidatorNodeClientError(#[from] ValidatorNodeClientError), -} diff --git a/dan_layer/core/src/workers/state_sync/mod.rs b/dan_layer/core/src/workers/state_sync/mod.rs deleted file mode 100644 index 9aba7e7b54b..00000000000 --- a/dan_layer/core/src/workers/state_sync/mod.rs +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -mod error; -pub use error::StateSyncError; -use log::*; -use rand::{rngs::OsRng, seq::SliceRandom}; -use tari_common_types::types::PublicKey; -use tari_dan_engine::state::{ - error::StateStorageError, - StateDb, - StateDbBackendAdapter, - StateDbUnitOfWork, - StateDbUnitOfWorkReader, -}; -use tari_utilities::hex::Hex; - -use crate::{ - models::CheckpointOutput, - services::{ValidatorNodeClientFactory, ValidatorNodeRpcClient}, -}; - -const LOG_TARGET: &str = "tari::dan::workers::state_sync"; - -pub struct StateSynchronizer<'a, TStateDbBackendAdapter, TValidatorNodeClientFactory: ValidatorNodeClientFactory> { - last_checkpoint: &'a CheckpointOutput, - state_db: &'a mut StateDb, - validator_node_client_factory: &'a TValidatorNodeClientFactory, - our_address: &'a TValidatorNodeClientFactory::Addr, - committee: &'a [TValidatorNodeClientFactory::Addr], -} - -impl<'a, TStateDbBackendAdapter, TValidatorNodeClientFactory> - StateSynchronizer<'a, TStateDbBackendAdapter, TValidatorNodeClientFactory> -where - TStateDbBackendAdapter: StateDbBackendAdapter, - TValidatorNodeClientFactory: ValidatorNodeClientFactory, -{ - pub fn new( - last_checkpoint: &'a CheckpointOutput, - state_db: &'a mut StateDb, - validator_node_client_factory: &'a TValidatorNodeClientFactory, - our_address: &'a TValidatorNodeClientFactory::Addr, - committee: &'a [TValidatorNodeClientFactory::Addr], - ) -> Self { - Self { - last_checkpoint, - state_db, - validator_node_client_factory, - our_address, - committee, - } - } - - pub async fn sync(&self) -> Result<(), StateSyncError> { - let mut committee = self - .committee - .iter() - .filter(|address| *self.our_address != **address) - .collect::>(); - - if committee.is_empty() { - return Err(StateSyncError::NoOtherCommitteeMembersToSync); - } - - committee.shuffle(&mut OsRng); - - for member in committee { - match self.try_sync_from(member).await { - Ok(_) => { - info!(target: LOG_TARGET, "Sync complete from committee member {}", member); - break; - }, - Err(err) => { - error!(target: LOG_TARGET, "Error syncing from {}: {}", member, err); - continue; - }, - } - } - - Ok(()) - } - - async fn try_sync_from(&self, member: &TValidatorNodeClientFactory::Addr) -> Result<(), StateSyncError> { - info!( - target: LOG_TARGET, - "Attempting to sync asset '{}' from peer '{}'", self.last_checkpoint.contract_id, member - ); - let mut client = self.validator_node_client_factory.create_client(member); - let tip_node = client - .get_tip_node(&self.last_checkpoint.contract_id) - .await? - .ok_or(StateSyncError::RemotePeerDoesNotHaveTipNode)?; - - // TODO: should rather download the op logs for a checkpoint and reply over initial/current state - let state_schemas = client.get_sidechain_state(&self.last_checkpoint.contract_id).await?; - - let mut uow = self.state_db.new_unit_of_work(u64::from(tip_node.height())); - - for schema in state_schemas { - let name = schema.name; - for item in schema.items { - debug!( - target: LOG_TARGET, - "Adding schema={}, key={}, value={}", - name, - item.key.to_hex(), - item.value.to_hex() - ); - uow.set_value(name.clone(), item.key, item.value)?; - } - } - // TODO: Check merkle root before commit - - uow.clear_all_state().map_err(StateStorageError::from)?; - uow.commit().map_err(StateStorageError::from)?; - - let merkle_root = uow.calculate_root()?; - if self.last_checkpoint.merkle_root.as_slice() != merkle_root.as_bytes() { - return Err(StateSyncError::InvalidStateMerkleRoot); - } - - Ok(()) - } -} diff --git a/dan_layer/core/src/workers/states/commit_state.rs b/dan_layer/core/src/workers/states/commit_state.rs deleted file mode 100644 index e57931a8635..00000000000 --- a/dan_layer/core/src/workers/states/commit_state.rs +++ /dev/null @@ -1,273 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::collections::HashMap; - -use log::*; -use tari_common_types::types::{Commitment, FixedHash}; -use tari_core::transactions::transaction_components::CheckpointChallenge; -use tari_dan_engine::state::models::StateRoot; -use tokio::time::{sleep, Duration}; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::{Committee, HotStuffMessage, HotStuffMessageType, QuorumCertificate, TreeNodeHash, View, ViewId}, - services::{ - infrastructure_services::{InboundConnectionService, OutboundService}, - ServiceSpecification, - SigningService, - }, - storage::chain::ChainDbUnitOfWork, - workers::states::ConsensusWorkerStateEvent, -}; - -const LOG_TARGET: &str = "tari::dan::workers::states::commit"; - -// TODO: This is very similar to pre-commit state -pub struct CommitState { - node_id: TSpecification::Addr, - contract_id: FixedHash, - committee: Committee, - received_new_view_messages: HashMap>, -} - -impl CommitState { - pub fn new( - node_id: TSpecification::Addr, - contract_id: FixedHash, - committee: Committee, - ) -> Self { - Self { - node_id, - contract_id, - committee, - received_new_view_messages: HashMap::new(), - } - } - - pub async fn next_event( - &mut self, - timeout: Duration, - current_view: &View, - inbound_services: &mut TSpecification::InboundConnectionService, - outbound_service: &mut TSpecification::OutboundService, - signing_service: &TSpecification::SigningService, - mut unit_of_work: TUnitOfWork, - proposed_state_root: StateRoot, - checkpoint_number: u64, - ) -> Result { - self.received_new_view_messages.clear(); - let timeout = sleep(timeout); - futures::pin_mut!(timeout); - loop { - tokio::select! { - r = inbound_services.wait_for_message(HotStuffMessageType::PreCommit, current_view.view_id()) => { - let (from, message) = r?; - if current_view.is_leader() { - if let Some(result) = self.process_leader_message(current_view, message.clone(), &from, outbound_service).await?{ - break Ok(result); - } - } - }, - r = inbound_services.wait_for_qc(HotStuffMessageType::PreCommit, current_view.view_id()) => { - let (from, message) = r?; - let leader = self.committee.leader_for_view(current_view.view_id).clone(); - if let Some(result) = self.process_replica_message( - &message, - current_view, - &from, - &leader, - outbound_service, - signing_service, - &mut unit_of_work, - proposed_state_root, - checkpoint_number, - ).await? { - break Ok(result); - } - } - _ = &mut timeout => { - break Ok(ConsensusWorkerStateEvent::TimedOut); - } - } - } - } - - async fn process_leader_message( - &mut self, - current_view: &View, - message: HotStuffMessage, - sender: &TSpecification::Addr, - outbound: &mut TSpecification::OutboundService, - ) -> Result, DigitalAssetError> { - if !message.matches(HotStuffMessageType::PreCommit, current_view.view_id) { - return Ok(None); - } - - // TODO: This might need to be checked in the QC rather - if self.received_new_view_messages.contains_key(sender) { - warn!(target: LOG_TARGET, "Already received message from {:?}", &sender); - return Ok(None); - } - - self.received_new_view_messages.insert(sender.clone(), message); - - if self.received_new_view_messages.len() >= self.committee.consensus_threshold() { - debug!( - target: LOG_TARGET, - "[COMMIT] Consensus has been reached with {:?} out of {} votes", - self.received_new_view_messages.len(), - self.committee.len(), - ); - - if let Some(qc) = self.create_qc(current_view) { - self.broadcast(outbound, qc, current_view.view_id).await?; - return Ok(None); // Replica will move this on - } - warn!(target: LOG_TARGET, "committee did not agree on node"); - Ok(None) - } else { - debug!( - target: LOG_TARGET, - "[COMMIT] Consensus has NOT YET been reached with {:?} out of {} votes", - self.received_new_view_messages.len(), - self.committee.len() - ); - Ok(None) - } - } - - async fn broadcast( - &self, - outbound: &mut TSpecification::OutboundService, - pre_commit_qc: QuorumCertificate, - view_number: ViewId, - ) -> Result<(), DigitalAssetError> { - let message = HotStuffMessage::commit(None, Some(pre_commit_qc), view_number, self.contract_id); - outbound - .broadcast(self.node_id.clone(), self.committee.members.as_slice(), message) - .await - } - - fn create_qc(&self, current_view: &View) -> Option { - // TODO: This can be done in one loop instead of two - let mut node_hash = None; - for message in self.received_new_view_messages.values() { - node_hash = match node_hash { - None => message.node_hash().copied(), - Some(n) => { - if let Some(m_node) = message.node_hash() { - if &n != m_node { - unimplemented!("Nodes did not match"); - } - Some(*m_node) - } else { - Some(n) - } - }, - }; - } - - let node_hash = node_hash.unwrap(); - let mut qc = QuorumCertificate::new(HotStuffMessageType::PreCommit, current_view.view_id, node_hash, None); - for message in self.received_new_view_messages.values() { - qc.combine_sig(message.partial_sig().unwrap()) - } - Some(qc) - } - - async fn process_replica_message( - &mut self, - message: &HotStuffMessage, - current_view: &View, - from: &TSpecification::Addr, - view_leader: &TSpecification::Addr, - outbound: &mut TSpecification::OutboundService, - signing_service: &TSpecification::SigningService, - unit_of_work: &mut TUnitOfWork, - proposed_state_root: StateRoot, - checkpoint_number: u64, - ) -> Result, DigitalAssetError> { - if let Some(justify) = message.justify() { - if !justify.matches(HotStuffMessageType::PreCommit, current_view.view_id) { - warn!( - target: LOG_TARGET, - "Wrong justify message type received, log: {} {:?} {}", - &self.node_id, - &justify.message_type(), - current_view.view_id - ); - return Ok(None); - } - // if message.node().is_none() { - // unimplemented!("Empty message"); - // } - - if from != view_leader { - warn!(target: LOG_TARGET, "Message not from leader"); - return Ok(None); - } - - unit_of_work.set_locked_qc(justify)?; - self.send_vote_to_leader( - *justify.node_hash(), - outbound, - view_leader, - current_view.view_id, - signing_service, - proposed_state_root, - checkpoint_number, - ) - .await?; - Ok(Some(ConsensusWorkerStateEvent::Committed)) - } else { - warn!(target: LOG_TARGET, "received non justify message"); - Ok(None) - } - } - - async fn send_vote_to_leader( - &self, - node: TreeNodeHash, - outbound: &mut TSpecification::OutboundService, - view_leader: &TSpecification::Addr, - view_number: ViewId, - signing_service: &TSpecification::SigningService, - proposed_state_root: StateRoot, - checkpoint_number: u64, - ) -> Result<(), DigitalAssetError> { - // TODO: Validators should have agreed on a checkpoint commitment and included this in the signature for base - // layer validation - let commitment = Commitment::default(); - - let challenge = CheckpointChallenge::new( - &self.contract_id, - &commitment, - &proposed_state_root.into(), - checkpoint_number, - ); - let checkpoint_signature = signing_service.sign_checkpoint(&challenge)?; - let mut message = HotStuffMessage::vote_commit(node, view_number, self.contract_id, checkpoint_signature); - message.add_partial_sig(signing_service.sign(&message.create_signature_challenge())?); - outbound.send(self.node_id.clone(), view_leader.clone(), message).await - } -} diff --git a/dan_layer/core/src/workers/states/decide_state.rs b/dan_layer/core/src/workers/states/decide_state.rs deleted file mode 100644 index c3486f953c7..00000000000 --- a/dan_layer/core/src/workers/states/decide_state.rs +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::collections::HashMap; - -use log::*; -use tari_common_types::types::FixedHash; -use tari_core::transactions::transaction_components::SignerSignature; -use tari_utilities::hex::Hex; -use tokio::time::{sleep, Duration}; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::{Committee, HotStuffMessage, HotStuffMessageType, QuorumCertificate, View, ViewId}, - services::{ - infrastructure_services::{InboundConnectionService, OutboundService}, - PayloadProvider, - ServiceSpecification, - }, - storage::chain::ChainDbUnitOfWork, - workers::states::ConsensusWorkerStateEvent, -}; - -const LOG_TARGET: &str = "tari::dan::workers::states::decide"; - -// TODO: This is very similar to pre-commit, and commit state -pub struct DecideState { - node_id: TSpecification::Addr, - contract_id: FixedHash, - committee: Committee, - received_new_view_messages: HashMap>, -} - -impl DecideState { - pub fn new( - node_id: TSpecification::Addr, - contract_id: FixedHash, - committee: Committee, - ) -> Self { - Self { - node_id, - contract_id, - committee, - received_new_view_messages: HashMap::new(), - } - } - - pub async fn next_event( - &mut self, - timeout: Duration, - current_view: &View, - inbound_services: &mut TSpecification::InboundConnectionService, - outbound_service: &mut TSpecification::OutboundService, - mut unit_of_work: TUnitOfWork, - payload_provider: &mut TSpecification::PayloadProvider, - ) -> Result { - self.received_new_view_messages.clear(); - let timeout = sleep(timeout); - futures::pin_mut!(timeout); - loop { - tokio::select! { - r = inbound_services.wait_for_message(HotStuffMessageType::Commit, current_view.view_id()) => { - let (from, message) = r?; - if current_view.is_leader() { - if let Some(event) = self.process_leader_message(current_view, message.clone(), &from, outbound_service).await?{ - break Ok(event); - } - } - }, - r = inbound_services.wait_for_qc(HotStuffMessageType::Commit, current_view.view_id()) => { - let (from, message) = r?; - let leader= self.committee.leader_for_view(current_view.view_id).clone(); - if let Some(event) = self.process_replica_message(&message, current_view, &from, &leader, &mut unit_of_work, payload_provider).await? { - break Ok(event); - } - }, - _ = &mut timeout => { - break Ok( ConsensusWorkerStateEvent::TimedOut); - } - } - } - } - - async fn process_leader_message( - &mut self, - current_view: &View, - message: HotStuffMessage, - sender: &TSpecification::Addr, - outbound: &mut TSpecification::OutboundService, - ) -> Result, DigitalAssetError> { - if !message.matches(HotStuffMessageType::Commit, current_view.view_id) { - return Ok(None); - } - - if self.received_new_view_messages.contains_key(sender) { - warn!(target: LOG_TARGET, "Already received message from {:?}", &sender); - return Ok(None); - } - debug!(target: LOG_TARGET, "MSG={:?}", message); - - self.received_new_view_messages.insert(sender.clone(), message); - - if self.received_new_view_messages.len() >= self.committee.consensus_threshold() { - debug!( - target: LOG_TARGET, - "[DECIDE] Consensus has been reached with {:?} out of {} votes", - self.received_new_view_messages.len(), - self.committee.len() - ); - - if let Some(qc) = self.create_qc(current_view) { - self.broadcast(outbound, qc, current_view.view_id).await?; - return Ok(None); // Replica will move this on - } - warn!(target: LOG_TARGET, "committee did not agree on node"); - Ok(None) - } else { - debug!( - target: LOG_TARGET, - "[DECIDE] Consensus has NOT YET been reached with {:?} out of {} votes", - self.received_new_view_messages.len(), - self.committee.len() - ); - Ok(None) - } - } - - async fn broadcast( - &self, - outbound: &mut TSpecification::OutboundService, - commit_qc: QuorumCertificate, - view_number: ViewId, - ) -> Result<(), DigitalAssetError> { - let message = HotStuffMessage::decide(None, Some(commit_qc), view_number, self.contract_id); - outbound - .broadcast(self.node_id.clone(), self.committee.members.as_slice(), message) - .await - } - - fn create_qc(&self, current_view: &View) -> Option { - let mut node_hash = None; - for message in self.received_new_view_messages.values() { - node_hash = match node_hash { - None => message.node_hash().copied(), - Some(n) => { - if let Some(m_node) = message.node_hash() { - if &n != m_node { - unimplemented!("Nodes did not match"); - } - Some(*m_node) - } else { - Some(n) - } - }, - }; - } - - let node_hash = node_hash.unwrap(); - let mut qc = QuorumCertificate::new(HotStuffMessageType::Commit, current_view.view_id, node_hash, None); - for message in self.received_new_view_messages.values() { - qc.combine_sig(message.partial_sig().unwrap()) - } - Some(qc) - } - - async fn process_replica_message( - &mut self, - message: &HotStuffMessage, - current_view: &View, - from: &TSpecification::Addr, - view_leader: &TSpecification::Addr, - unit_of_work: &mut TUnitOfWork, - payload_provider: &mut TSpecification::PayloadProvider, - ) -> Result, DigitalAssetError> { - debug!(target: LOG_TARGET, "[DECIDE] replica message: {:?}", message); - if let Some(justify) = message.justify() { - if !justify.matches(HotStuffMessageType::Commit, current_view.view_id) { - warn!( - target: LOG_TARGET, - "Wrong justify message type received, log. {}, {:?}, {}", - &self.node_id, - &justify.message_type(), - current_view.view_id - ); - return Ok(None); - } - // if message.node().is_none() { - // unimplemented!("Empty message"); - // } - - if from != view_leader { - warn!(target: LOG_TARGET, "Message not from leader"); - return Ok(None); - } - - payload_provider.remove_payload(justify.node_hash()).await?; - unit_of_work.commit_node(justify.node_hash())?; - info!(target: LOG_TARGET, "Committed node: {}", justify.node_hash().to_hex()); - Ok(Some(ConsensusWorkerStateEvent::Decided)) - } else { - warn!(target: LOG_TARGET, "received non justify message"); - Ok(None) - } - } - - pub fn collected_checkpoint_signatures(&self) -> Vec { - self.received_new_view_messages - .values() - .filter_map(|msg| msg.checkpoint_signature().cloned()) - .collect() - } -} diff --git a/dan_layer/core/src/workers/states/helpers.rs b/dan_layer/core/src/workers/states/helpers.rs deleted file mode 100644 index 5af4df3a431..00000000000 --- a/dan_layer/core/src/workers/states/helpers.rs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub async fn wait_for_message( - inbound_connection: &TInboundConnectionService, - message_type: HotStuffMessageType, - view: ViewId, -) -> (TAddr, HotStuffMessage) { -} diff --git a/dan_layer/core/src/workers/states/idle_state.rs b/dan_layer/core/src/workers/states/idle_state.rs deleted file mode 100644 index 2a32f1b26fe..00000000000 --- a/dan_layer/core/src/workers/states/idle_state.rs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tokio::time::{sleep, Duration}; - -use crate::{digital_assets_error::DigitalAssetError, workers::states::ConsensusWorkerStateEvent}; - -#[derive(Default)] -pub struct IdleState {} - -impl IdleState { - pub async fn next_event(&self) -> Result { - sleep(Duration::from_secs(10)).await; - Ok(ConsensusWorkerStateEvent::TimedOut) - } -} diff --git a/dan_layer/core/src/workers/states/mod.rs b/dan_layer/core/src/workers/states/mod.rs deleted file mode 100644 index 236a2a466bf..00000000000 --- a/dan_layer/core/src/workers/states/mod.rs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::models::ViewId; - -// #[async_trait] -// pub trait State { -// async fn next_event( -// &mut self, -// current_view: &View, -// shutdown: &ShutdownSignal, -// ) -> Result; -// } - -mod commit_state; -mod decide_state; -mod idle_state; -mod next_view; -mod pre_commit_state; -mod prepare; -mod starting; -mod synchronizing; - -pub use commit_state::CommitState; -pub use decide_state::DecideState; -pub use idle_state::IdleState; -pub use next_view::NextViewState; -pub use pre_commit_state::PreCommitState; -pub use prepare::Prepare; -pub use starting::Starting; -pub use synchronizing::Synchronizing; - -#[derive(Debug, PartialEq, Eq)] -pub enum ConsensusWorkerStateEvent { - Initialized, - Synchronized, - BaseLayerCheckpointNotFound, - BaseLayerAssetRegistrationNotFound, - BaseLayerCheckopintNotFound, - NotPartOfCommittee, - Errored { reason: String }, - Prepared, - PreCommitted, - Committed, - Decided, - TimedOut, - NewView { new_view: ViewId }, -} - -impl ConsensusWorkerStateEvent { - pub fn must_shutdown(&self) -> bool { - matches!(self, ConsensusWorkerStateEvent::Errored { .. }) - } - - pub fn shutdown_reason(&self) -> Option<&str> { - match self { - ConsensusWorkerStateEvent::Errored { reason } => Some(reason.as_str()), - _ => None, - } - } -} diff --git a/dan_layer/core/src/workers/states/next_view.rs b/dan_layer/core/src/workers/states/next_view.rs deleted file mode 100644 index 6f07ab3beed..00000000000 --- a/dan_layer/core/src/workers/states/next_view.rs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::marker::PhantomData; - -use log::*; -use tari_dan_engine::state::models::StateRoot; -use tari_shutdown::ShutdownSignal; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::{AssetDefinition, Committee, HotStuffMessage, HotStuffTreeNode, QuorumCertificate, View}, - services::{infrastructure_services::OutboundService, PayloadProvider, ServiceSpecification}, - storage::DbFactory, - workers::states::ConsensusWorkerStateEvent, -}; - -const LOG_TARGET: &str = "tari::dan::workers::states::next_view"; - -#[derive(Default)] -pub struct NextViewState { - _spec: PhantomData, -} - -impl NextViewState { - pub fn new() -> Self { - Default::default() - } - - pub async fn next_event( - &mut self, - current_view: &View, - db_factory: &TSpecification::DbFactory, - broadcast: &mut TSpecification::OutboundService, - committee: &Committee, - node_id: TSpecification::Addr, - asset_definition: &AssetDefinition, - payload_provider: &TSpecification::PayloadProvider, - _shutdown: &ShutdownSignal, - ) -> Result { - let chain_db = db_factory.get_or_create_chain_db(&asset_definition.contract_id)?; - if chain_db.is_empty()? { - info!(target: LOG_TARGET, "Database is empty. Proposing genesis block"); - let node = HotStuffTreeNode::genesis( - payload_provider.create_genesis_payload(asset_definition), - StateRoot::initial(), - ); - let genesis_qc = QuorumCertificate::genesis(*node.hash()); - let genesis_view_no = genesis_qc.view_number(); - let leader = committee.leader_for_view(genesis_view_no); - let message = HotStuffMessage::new_view(genesis_qc, genesis_view_no, asset_definition.contract_id); - broadcast.send(node_id, leader.clone(), message).await?; - Ok(ConsensusWorkerStateEvent::NewView { - new_view: genesis_view_no, - }) - } else { - info!(target: LOG_TARGET, "End of view: {}", current_view.view_id); - debug!(target: LOG_TARGET, "--------------------------------"); - let prepare_qc = chain_db.find_highest_prepared_qc()?; - let next_view = current_view.view_id.next(); - let message = HotStuffMessage::new_view(prepare_qc, next_view, asset_definition.contract_id); - let leader = committee.leader_for_view(next_view); - broadcast.send(node_id, leader.clone(), message).await?; - Ok(ConsensusWorkerStateEvent::NewView { new_view: next_view }) - } - } -} diff --git a/dan_layer/core/src/workers/states/pre_commit_state.rs b/dan_layer/core/src/workers/states/pre_commit_state.rs deleted file mode 100644 index efde5447cfe..00000000000 --- a/dan_layer/core/src/workers/states/pre_commit_state.rs +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::collections::HashMap; - -use log::*; -use tari_common_types::types::FixedHash; -use tokio::time::{sleep, Duration}; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::{Committee, HotStuffMessage, HotStuffMessageType, QuorumCertificate, TreeNodeHash, View, ViewId}, - services::{ - infrastructure_services::{InboundConnectionService, OutboundService}, - ServiceSpecification, - SigningService, - }, - storage::chain::ChainDbUnitOfWork, - workers::states::ConsensusWorkerStateEvent, -}; - -const LOG_TARGET: &str = "tari::dan::workers::states::precommit"; - -pub struct PreCommitState { - node_id: TSpecification::Addr, - contract_id: FixedHash, - committee: Committee, - received_prepare_messages: HashMap>, -} - -impl PreCommitState { - pub fn new( - node_id: TSpecification::Addr, - committee: Committee, - contract_id: FixedHash, - ) -> Self { - Self { - node_id, - contract_id, - committee, - received_prepare_messages: HashMap::new(), - } - } - - pub async fn next_event( - &mut self, - timeout: Duration, - current_view: &View, - inbound_services: &TSpecification::InboundConnectionService, - outbound_service: &mut TSpecification::OutboundService, - signing_service: &TSpecification::SigningService, - unit_of_work: TUnitOfWork, - ) -> Result { - self.received_prepare_messages.clear(); - let mut unit_of_work = unit_of_work; - let timeout = sleep(timeout); - futures::pin_mut!(timeout); - loop { - tokio::select! { - r = inbound_services.wait_for_message(HotStuffMessageType::Prepare, current_view.view_id()) => { - let (from, message) = r?; - debug!(target: LOG_TARGET, "Received message: {:?} view:{}", message.message_type(), message.view_number()); - if current_view.is_leader() { - if let Some(event) = self.process_leader_message(current_view, message.clone(), &from, outbound_service).await? { - break Ok(event); - } - } - }, - r = inbound_services.wait_for_qc(HotStuffMessageType::Prepare, current_view.view_id()) => { - let (from, message) = r?; - let leader = self.committee.leader_for_view(current_view.view_id).clone(); - if let Some(event) = self.process_replica_message(&message, current_view, &from, &leader, outbound_service, signing_service, &mut unit_of_work).await? { - break Ok(event); - } - }, - _ = &mut timeout => { - break Ok(ConsensusWorkerStateEvent::TimedOut); - } - } - } - } - - async fn process_leader_message( - &mut self, - current_view: &View, - message: HotStuffMessage, - sender: &TSpecification::Addr, - outbound: &mut TSpecification::OutboundService, - ) -> Result, DigitalAssetError> { - debug!( - target: LOG_TARGET, - "Received message as leader:{:?} for view:{}", - message.message_type(), - message.view_number() - ); - if !message.matches(HotStuffMessageType::Prepare, current_view.view_id) { - return Ok(None); - } - - if self.received_prepare_messages.contains_key(sender) { - return Ok(None); - } - - self.received_prepare_messages.insert(sender.clone(), message); - - if self.received_prepare_messages.len() >= self.committee.consensus_threshold() { - debug!( - target: LOG_TARGET, - "[PRECOMMIT] Consensus has been reached with {:?} out of {} votes", - self.received_prepare_messages.len(), - self.committee.len() - ); - - if let Some(qc) = self.create_qc(current_view) { - self.broadcast(outbound, &self.committee, qc, current_view.view_id) - .await?; - // return Ok(Some(ConsensusWorkerStateEvent::PreCommitted)); - return Ok(None); - } - warn!(target: LOG_TARGET, "committee did not agree on node"); - Ok(None) - } else { - debug!( - target: LOG_TARGET, - "[PRECOMMIT] Consensus has NOT YET been reached with {:?} out of {} votes", - self.received_prepare_messages.len(), - self.committee.len() - ); - Ok(None) - } - } - - async fn broadcast( - &self, - outbound: &mut TSpecification::OutboundService, - committee: &Committee, - prepare_qc: QuorumCertificate, - view_number: ViewId, - ) -> Result<(), DigitalAssetError> { - let message = HotStuffMessage::pre_commit(None, Some(prepare_qc), view_number, self.contract_id); - outbound - .broadcast(self.node_id.clone(), committee.members.as_slice(), message) - .await - } - - fn create_qc(&self, current_view: &View) -> Option { - let mut node_hash = None; - for message in self.received_prepare_messages.values() { - node_hash = match node_hash { - None => message.node_hash().copied(), - Some(n) => { - if let Some(m_node) = message.node_hash() { - if &n != m_node { - unimplemented!("Nodes did not match"); - } - Some(*m_node) - } else { - Some(n) - } - }, - }; - } - - let node_hash = node_hash.unwrap(); - let mut qc = QuorumCertificate::new(HotStuffMessageType::Prepare, current_view.view_id, node_hash, None); - for message in self.received_prepare_messages.values() { - qc.combine_sig(message.partial_sig().unwrap()) - } - Some(qc) - } - - async fn process_replica_message( - &mut self, - message: &HotStuffMessage, - current_view: &View, - from: &TSpecification::Addr, - view_leader: &TSpecification::Addr, - outbound: &mut TSpecification::OutboundService, - signing_service: &TSpecification::SigningService, - unit_of_work: &mut TUnitOfWork, - ) -> Result, DigitalAssetError> { - debug!( - target: LOG_TARGET, - "Received message as replica:{:?} for view:{}", - message.message_type(), - message.view_number() - ); - if let Some(justify) = message.justify() { - if !justify.matches(HotStuffMessageType::Prepare, current_view.view_id) { - warn!( - target: LOG_TARGET, - "Wrong justify message type received, log. {}, {:?}, {}", - &self.node_id, - &justify.message_type(), - current_view.view_id - ); - return Ok(None); - } - - if from != view_leader { - warn!(target: LOG_TARGET, "Message not from leader"); - return Ok(None); - } - - unit_of_work.set_prepare_qc(justify)?; - self.send_vote_to_leader( - *justify.node_hash(), - outbound, - view_leader, - current_view.view_id, - signing_service, - ) - .await?; - Ok(Some(ConsensusWorkerStateEvent::PreCommitted)) - } else { - // dbg!("received non justify message"); - Ok(None) - } - } - - async fn send_vote_to_leader( - &self, - node: TreeNodeHash, - outbound: &mut TSpecification::OutboundService, - view_leader: &TSpecification::Addr, - view_number: ViewId, - signing_service: &TSpecification::SigningService, - ) -> Result<(), DigitalAssetError> { - let mut message = HotStuffMessage::vote_pre_commit(node, view_number, self.contract_id); - message.add_partial_sig(signing_service.sign(&message.create_signature_challenge())?); - outbound.send(self.node_id.clone(), view_leader.clone(), message).await - } -} diff --git a/dan_layer/core/src/workers/states/prepare.rs b/dan_layer/core/src/workers/states/prepare.rs deleted file mode 100644 index e3a33426b74..00000000000 --- a/dan_layer/core/src/workers/states/prepare.rs +++ /dev/null @@ -1,505 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{collections::HashMap, time::Duration}; - -use log::*; -use tari_common_types::types::FixedHash; -use tari_dan_engine::state::StateDbUnitOfWork; -use tokio::time::sleep; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::{ - AssetDefinition, - Committee, - HotStuffMessage, - HotStuffMessageType, - HotStuffTreeNode, - QuorumCertificate, - TreeNodeHash, - View, - ViewId, - }, - services::{ - infrastructure_services::{InboundConnectionService, OutboundService}, - PayloadProcessor, - PayloadProvider, - ServiceSpecification, - SigningService, - }, - storage::{chain::ChainDbUnitOfWork, ChainStorageService, DbFactory, StorageError}, - workers::states::ConsensusWorkerStateEvent, -}; - -const LOG_TARGET: &str = "tari::dan::workers::states::prepare"; - -pub struct Prepare { - node_id: TSpecification::Addr, - contract_id: FixedHash, - received_new_view_messages: HashMap>, -} - -impl Prepare { - pub fn new(node_id: TSpecification::Addr, contract_id: FixedHash) -> Self { - Self { - node_id, - contract_id, - received_new_view_messages: HashMap::new(), - } - } - - pub async fn next_event( - &mut self, - current_view: &View, - timeout: Duration, - asset_definition: &AssetDefinition, - committee: &Committee, - inbound_services: &TSpecification::InboundConnectionService, - outbound_service: &mut TSpecification::OutboundService, - payload_provider: &mut TSpecification::PayloadProvider, - signing_service: &TSpecification::SigningService, - payload_processor: &mut TSpecification::PayloadProcessor, - chain_storage_service: &TSpecification::ChainStorageService, - mut chain_tx: TChainDbUnitOfWork, - state_tx: &mut TStateDbUnitOfWork, - db_factory: &TSpecification::DbFactory, - ) -> Result { - self.received_new_view_messages.clear(); - let timeout = sleep(timeout); - futures::pin_mut!(timeout); - debug!(target: LOG_TARGET, "[PREPARE] Current view: {}", current_view); - - if current_view.is_leader() { - debug!( - target: LOG_TARGET, - "Waiting for NewView (view_id = {}) messages", - current_view.view_id() - ); - } else { - debug!( - target: LOG_TARGET, - "Waiting for Prepare (view_id = {}) messages", - current_view.view_id() - ); - } - loop { - tokio::select! { - r = inbound_services.wait_for_message(HotStuffMessageType::NewView, current_view.view_id()) => { - let (from, message) = r?; - debug!(target: LOG_TARGET, "Received leader message (is_leader = {:?})", current_view.is_leader()); - if current_view.is_leader() { - if let Some(event) = self.process_leader_message( - current_view, - message.clone(), - &from, - asset_definition, - committee, - payload_provider, - payload_processor, - outbound_service, - db_factory, - ).await? { - break Ok(event) - } - } - }, - r = inbound_services.wait_for_message(HotStuffMessageType::Prepare, current_view.view_id()) => { - let (from, message) = r?; - debug!(target: LOG_TARGET, "Received replica message"); - if let Some(event) = self.process_replica_message( - &message, - current_view, - &from, - committee.leader_for_view(current_view.view_id), - outbound_service, - signing_service, - payload_processor, - payload_provider, - &mut chain_tx, - chain_storage_service, - state_tx, - ).await? { - break Ok(event); - } - - }, - _ = &mut timeout => { - break Ok( ConsensusWorkerStateEvent::TimedOut); - } - } - } - } - - async fn process_leader_message( - &mut self, - current_view: &View, - message: HotStuffMessage, - sender: &TSpecification::Addr, - asset_definition: &AssetDefinition, - committee: &Committee, - payload_provider: &TSpecification::PayloadProvider, - payload_processor: &mut TSpecification::PayloadProcessor, - outbound: &mut TSpecification::OutboundService, - db_factory: &TSpecification::DbFactory, - ) -> Result, DigitalAssetError> { - debug!( - target: LOG_TARGET, - "Received message as leader:{:?} for view:{}", - message.message_type(), - message.view_number() - ); - - // TODO: This might need to be checked in the QC rather - if self.received_new_view_messages.contains_key(sender) { - warn!("Already received message from {:?}", sender); - return Ok(None); - } - - self.received_new_view_messages.insert(sender.clone(), message); - - if self.received_new_view_messages.len() >= committee.consensus_threshold() { - debug!( - target: LOG_TARGET, - "[PREPARE] Consensus has been reached with {:?} out of {} votes", - self.received_new_view_messages.len(), - committee.len() - ); - let high_qc = self.find_highest_qc(); - - let temp_state_tx = db_factory - .get_or_create_state_db(&self.contract_id)? - .new_unit_of_work(current_view.view_id.as_u64()); - let proposal = self - .create_proposal( - *high_qc.node_hash(), - asset_definition, - payload_provider, - payload_processor, - current_view.view_id, - temp_state_tx, - ) - .await?; - self.broadcast_proposal(outbound, committee, proposal, high_qc, current_view.view_id) - .await?; - Ok(None) // Will move to pre-commit when it receives the message as a replica - } else { - debug!( - target: LOG_TARGET, - "[PREPARE] Consensus has NOT YET been reached with {} out of {} votes", - self.received_new_view_messages.len(), - committee.len() - ); - Ok(None) - } - } - - async fn process_replica_message( - &self, - message: &HotStuffMessage, - current_view: &View, - from: &TSpecification::Addr, - view_leader: &TSpecification::Addr, - outbound: &mut TSpecification::OutboundService, - signing_service: &TSpecification::SigningService, - payload_processor: &mut TSpecification::PayloadProcessor, - payload_provider: &mut TSpecification::PayloadProvider, - chain_tx: &mut TChainDbUnitOfWork, - chain_storage_service: &TSpecification::ChainStorageService, - state_tx: &mut TStateDbUnitOfWork, - ) -> Result, DigitalAssetError> { - debug!( - target: LOG_TARGET, - "Received message as replica:{:?} for view:{}", - message.message_type(), - message.view_number() - ); - if message.node().is_none() { - unimplemented!("Empty message"); - } - if from != view_leader { - warn!("Message not from leader"); - return Ok(None); - } - let node = message.node().unwrap(); - let justify = message - .justify() - .ok_or(DigitalAssetError::PreparePhaseNoQuorumCertificate)?; - - // The genesis does not extend any node - if !current_view.view_id().is_genesis() { - if !self.does_extend(node, justify.node_hash()) { - return Err(DigitalAssetError::PreparePhaseCertificateDoesNotExtendNode); - } - - if !self.is_safe_node(node, justify, chain_tx)? { - return Err(DigitalAssetError::PreparePhaseNodeNotSafe); - } - } - - debug!( - target: LOG_TARGET, - "[PREPARE] Processing prepared payload for view {}", - current_view.view_id() - ); - - let state_root = payload_processor - .process_payload(node.payload(), state_tx.clone()) - .await?; - - if state_root != *node.state_root() { - warn!( - target: LOG_TARGET, - "Calculated state root did not match the state root provided by the leader: Expected: {:?} Leader \ - provided:{:?}", - state_root, - node.state_root() - ); - return Ok(None); - } - - debug!( - target: LOG_TARGET, - "[PREPARE] Merkle root matches payload for view {}. Adding node '{}'", - current_view.view_id(), - node.hash() - ); - - chain_storage_service - .add_node::(node, chain_tx.clone()) - .await?; - - payload_provider.reserve_payload(node.payload(), node.hash()).await?; - self.send_vote_to_leader( - *node.hash(), - outbound, - view_leader, - current_view.view_id, - signing_service, - ) - .await?; - Ok(Some(ConsensusWorkerStateEvent::Prepared)) - } - - fn find_highest_qc(&self) -> QuorumCertificate { - let mut max_qc = None; - for message in self.received_new_view_messages.values() { - match &max_qc { - None => max_qc = message.justify().cloned(), - Some(qc) => { - if let Some(justify) = message.justify() { - if qc.view_number() < justify.view_number() { - max_qc = Some(justify.clone()) - } - } - }, - } - } - // TODO: this will panic if nothing found - max_qc.unwrap() - } - - #[allow(clippy::cast_possible_truncation)] - async fn create_proposal( - &self, - parent: TreeNodeHash, - asset_definition: &AssetDefinition, - payload_provider: &TSpecification::PayloadProvider, - payload_processor: &mut TSpecification::PayloadProcessor, - view_id: ViewId, - state_db: TStateDbUnitOfWork, - ) -> Result, DigitalAssetError> { - debug!(target: LOG_TARGET, "Creating new proposal for {}", view_id); - - // TODO: Artificial delay here to set the block time - sleep(Duration::from_secs(10)).await; - - if view_id.is_genesis() { - let payload = payload_provider.create_genesis_payload(asset_definition); - let state_root = payload_processor.process_payload(&payload, state_db).await?; - Ok(HotStuffTreeNode::genesis(payload, state_root)) - } else { - let payload = payload_provider.create_payload().await?; - - let state_root = payload_processor.process_payload(&payload, state_db).await?; - Ok(HotStuffTreeNode::from_parent( - parent, - payload, - state_root, - view_id.as_u64() as u32, - )) - } - } - - async fn broadcast_proposal( - &self, - outbound: &mut TSpecification::OutboundService, - committee: &Committee, - proposal: HotStuffTreeNode, - high_qc: QuorumCertificate, - view_number: ViewId, - ) -> Result<(), DigitalAssetError> { - let message = HotStuffMessage::prepare(proposal, Some(high_qc), view_number, self.contract_id); - outbound - .broadcast(self.node_id.clone(), committee.members.as_slice(), message) - .await - } - - fn does_extend(&self, node: &HotStuffTreeNode, from: &TreeNodeHash) -> bool { - from == node.parent() - } - - fn is_safe_node( - &self, - node: &HotStuffTreeNode, - quorum_certificate: &QuorumCertificate, - chain_tx: &mut TUnitOfWork, - ) -> Result { - let locked_qc = chain_tx.get_locked_qc()?; - Ok(self.does_extend(node, locked_qc.node_hash()) || quorum_certificate.view_number() > locked_qc.view_number()) - } - - async fn send_vote_to_leader( - &self, - node: TreeNodeHash, - outbound: &mut TSpecification::OutboundService, - view_leader: &TSpecification::Addr, - view_number: ViewId, - signing_service: &TSpecification::SigningService, - ) -> Result<(), DigitalAssetError> { - // TODO: Only send node hash, not the full node - let mut message = HotStuffMessage::vote_prepare(node, view_number, self.contract_id); - message.add_partial_sig(signing_service.sign(&message.create_signature_challenge())?); - outbound.send(self.node_id.clone(), view_leader.clone(), message).await - } -} - -#[cfg(test)] -mod test { - use std::time::Duration; - - use tari_common_types::types::FixedHash; - - use crate::{ - models::{AssetDefinition, Committee, HotStuffMessage, QuorumCertificate, TreeNodeHash, View, ViewId}, - services::{ - infrastructure_services::{mocks::mock_outbound, OutboundService}, - mocks::{ - create_public_key, - mock_payload_processor, - mock_signing_service, - mock_static_payload_provider, - MockChainStorageService, - MockServiceSpecification, - }, - }, - storage::{mocks::MockDbFactory, DbFactory}, - workers::states::{ConsensusWorkerStateEvent, Prepare}, - }; - - #[tokio::test(flavor = "multi_thread")] - #[ignore] - async fn basic_test_as_leader() { - // let mut inbound = mock_inbound(); - // let mut sender = inbound.create_sender(); - let locked_qc = QuorumCertificate::genesis(TreeNodeHash::zero()); - let contract_id = FixedHash::default(); - let address_a = create_public_key(); - let address_b = create_public_key(); - let address_c = create_public_key(); - let address_d = create_public_key(); - - let mut state = Prepare::::new(address_b.clone(), contract_id); - let current_view = View { - view_id: ViewId(1), - is_leader: true, - }; - let timeout = Duration::from_secs(10); - let asset_definition = AssetDefinition::default(); - let committee = Committee::new(vec![ - address_a.clone(), - address_b.clone(), - address_c.clone(), - address_d.clone(), - ]); - let mut outbound = mock_outbound(committee.members.clone()); - let mut outbound2 = outbound.clone(); - let inbound = outbound.take_inbound(&address_b).unwrap(); - let mut payload_provider = mock_static_payload_provider(); - let signing_service = mock_signing_service(); - let mut payload_processor = mock_payload_processor(); - let chain_storage_service = MockChainStorageService::default(); - let db_factory = MockDbFactory::default(); - let chain_db = db_factory.get_or_create_chain_db(&contract_id.clone()).unwrap(); - let chain_tx = chain_db.new_unit_of_work(); - let mut state_tx = db_factory - .get_or_create_state_db(&contract_id) - .unwrap() - .new_unit_of_work(current_view.view_id.as_u64()); - - let task = state.next_event( - ¤t_view, - timeout, - &asset_definition, - &committee, - &inbound, - &mut outbound, - &mut payload_provider, - &signing_service, - &mut payload_processor, - &chain_storage_service, - chain_tx, - &mut state_tx, - &db_factory, - ); - - outbound2 - .send( - address_a.clone(), - address_b.clone(), - HotStuffMessage::new_view(locked_qc.clone(), ViewId(0), contract_id), - ) - .await - .unwrap(); - - outbound2 - .send( - address_c.clone(), - address_b.clone(), - HotStuffMessage::new_view(locked_qc.clone(), ViewId(0), contract_id), - ) - .await - .unwrap(); - - outbound2 - .send( - address_d.clone(), - address_b.clone(), - HotStuffMessage::new_view(locked_qc.clone(), ViewId(0), contract_id), - ) - .await - .unwrap(); - - let event = task.await.unwrap(); - assert_eq!(event, ConsensusWorkerStateEvent::Prepared); - } -} diff --git a/dan_layer/core/src/workers/states/starting.rs b/dan_layer/core/src/workers/states/starting.rs deleted file mode 100644 index 5fd702baf3e..00000000000 --- a/dan_layer/core/src/workers/states/starting.rs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{convert::TryInto, marker::PhantomData}; - -use log::*; -use tari_core::transactions::transaction_components::OutputType; - -use crate::{ - digital_assets_error::DigitalAssetError, - models::AssetDefinition, - services::{BaseNodeClient, CommitteeManager, ServiceSpecification}, - storage::DbFactory, - workers::states::ConsensusWorkerStateEvent, -}; - -const LOG_TARGET: &str = "tari::dan::workers::states::starting"; - -#[derive(Default)] -pub struct Starting { - _spec: PhantomData, -} - -impl Starting { - pub fn new() -> Self { - Default::default() - } - - pub async fn next_event( - &self, - base_node_client: &mut TSpecification::BaseNodeClient, - asset_definition: &AssetDefinition, - committee_manager: &mut TSpecification::CommitteeManager, - db_factory: &TSpecification::DbFactory, - node_id: &TSpecification::Addr, - ) -> Result - where - TSpecification: ServiceSpecification, - { - info!( - target: LOG_TARGET, - "Checking base layer to see if we are part of the committee" - ); - let tip = base_node_client.get_tip_info().await?; - // get latest checkpoint on the base layer - let mut outputs = base_node_client - .get_current_contract_outputs( - tip.height_of_longest_chain - .saturating_sub(asset_definition.base_layer_confirmation_time), - asset_definition.contract_id, - OutputType::ContractConstitution, - ) - .await?; - - let output = match outputs.pop() { - Some(chk) => chk.try_into()?, - None => return Ok(ConsensusWorkerStateEvent::BaseLayerCheckopintNotFound), - }; - - committee_manager.read_from_constitution(output)?; - - if !committee_manager.current_committee()?.contains(node_id) { - info!( - target: LOG_TARGET, - "Validator node not part of committee for asset public key '{}'", asset_definition.contract_id - ); - return Ok(ConsensusWorkerStateEvent::NotPartOfCommittee); - } - - info!( - target: LOG_TARGET, - "Validator node is a committee member for asset public key '{}'", asset_definition.contract_id - ); - // read and create the genesis block - info!(target: LOG_TARGET, "Creating DB"); - let _chain_db = db_factory.get_or_create_chain_db(&asset_definition.contract_id)?; - - Ok(ConsensusWorkerStateEvent::Initialized) - } -} diff --git a/dan_layer/core/src/workers/states/synchronizing.rs b/dan_layer/core/src/workers/states/synchronizing.rs deleted file mode 100644 index 4a7331a508e..00000000000 --- a/dan_layer/core/src/workers/states/synchronizing.rs +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{convert::TryFrom, marker::PhantomData}; - -use log::*; -use tari_comms::types::CommsPublicKey; -use tari_core::transactions::transaction_components::OutputType; -use tari_dan_engine::state::StateDbUnitOfWorkReader; - -use crate::{ - models::{AssetDefinition, BaseLayerOutput, CheckpointOutput}, - services::{BaseNodeClient, ServiceSpecification}, - storage::DbFactory, - workers::{state_sync::StateSynchronizer, states::ConsensusWorkerStateEvent}, - DigitalAssetError, -}; - -const LOG_TARGET: &str = "tari::dan::workers::states::starting"; - -#[derive(Debug, Default, Clone)] -pub struct Synchronizing { - _spec: PhantomData, -} - -impl> Synchronizing { - pub fn new() -> Self { - Default::default() - } - - #[allow(unreachable_code, unused_variables)] - pub async fn next_event( - &mut self, - base_node_client: &mut TSpecification::BaseNodeClient, - asset_definition: &AssetDefinition, - db_factory: &TSpecification::DbFactory, - validator_node_client_factory: &TSpecification::ValidatorNodeClientFactory, - our_address: &TSpecification::Addr, - ) -> Result { - // TODO: The collectibles app does not post a valid initial merkle root for the initial asset checkpoint. So - // this is always out-of-sync. - // return Ok(ConsensusWorkerStateEvent::Synchronized); - - let tip = base_node_client.get_tip_info().await?; - let mut last_checkpoint = base_node_client - .get_current_contract_outputs( - tip.height_of_longest_chain - .saturating_sub(asset_definition.base_layer_confirmation_time), - asset_definition.contract_id, - OutputType::ContractCheckpoint, - ) - .await?; - - let last_checkpoint = match last_checkpoint.pop() { - Some(utxo) => { - let output = BaseLayerOutput::try_from(utxo)?; - CheckpointOutput::try_from(output)? - }, - None => return Ok(ConsensusWorkerStateEvent::BaseLayerCheckpointNotFound), - }; - - let mut constitution = base_node_client - .get_current_contract_outputs( - tip.height_of_longest_chain - .saturating_sub(asset_definition.base_layer_confirmation_time), - asset_definition.contract_id, - OutputType::ContractConstitution, - ) - .await?; - - let current_constitution = match constitution.pop() { - Some(o) => BaseLayerOutput::try_from(o)?, - None => return Ok(ConsensusWorkerStateEvent::BaseLayerCheckopintNotFound), - }; - - let mut state_db = db_factory.get_or_create_state_db(&asset_definition.contract_id)?; - { - let state_reader = state_db.reader(); - let our_merkle_root = state_reader.calculate_root()?; - if our_merkle_root.as_bytes() == last_checkpoint.merkle_root.as_slice() { - info!(target: LOG_TARGET, "Our state database is up-to-date."); - return Ok(ConsensusWorkerStateEvent::Synchronized); - } - } - - let committee = current_constitution - .features - .constitution_committee() - .map(|committee| committee.members().to_vec()) - .unwrap_or_default(); - - info!( - target: LOG_TARGET, - "Our state database for asset '{}' is out of sync. Attempting to contact a committee member to synchronize", - asset_definition.contract_id - ); - - let synchronizer = StateSynchronizer::new( - &last_checkpoint, - &mut state_db, - validator_node_client_factory, - our_address, - &committee, - ); - synchronizer.sync().await?; - - Ok(ConsensusWorkerStateEvent::Synchronized) - } -} diff --git a/dan_layer/engine/Cargo.toml b/dan_layer/engine/Cargo.toml deleted file mode 100644 index 9b7edf0d985..00000000000 --- a/dan_layer/engine/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "tari_dan_engine" -version = "0.1.0" -edition = "2018" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -tari_common = { path = "../../common" } -tari_common_types = { path = "../../base_layer/common_types" } -tari_crypto = { git = "https://github.com/tari-project/tari-crypto.git", tag = "v0.15.4" } -tari_dan_common_types = { path = "../common_types" } -tari_mmr = { path = "../../base_layer/mmr" } -tari_template_abi = { path = "../template_abi", features = ["std"] } -tari_template_lib = { path = "../template_lib", features = ["serde"] } -tari_utilities = { git = "https://github.com/tari-project/tari_utilities.git", tag = "v0.4.5" } - -anyhow = "1.0.53" -borsh = "0.9.3" -cargo_toml = "0.11.5" -d3ne = { git = "https://github.com/stringhandler/d3ne-rs.git", branch = "st-fixes2" } -digest = "0.9.0" -log = { version = "0.4.8", features = ["std"] } -rand = "0.8.1" -serde = "1.0.126" -serde_json = "1.0.81" -thiserror = "^1.0.20" -wasmer = "2.3.0" diff --git a/dan_layer/engine/src/crypto.rs b/dan_layer/engine/src/crypto.rs deleted file mode 100644 index fd62bdc06c6..00000000000 --- a/dan_layer/engine/src/crypto.rs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use digest::Digest; -use rand::rngs::OsRng; -use tari_common_types::types::{PrivateKey, PublicKey}; -use tari_crypto::{hash::blake2::Blake256, hash_domain, hashing::DomainSeparatedHasher, keys::PublicKey as PublicKeyT}; - -hash_domain!(TariEngineHashDomain, "tari.dan.engine", 0); - -pub type TariEngineHasher = DomainSeparatedHasher; - -pub fn hasher(label: &'static str) -> impl Digest { - TariEngineHasher::new_with_label(label) -} - -pub fn create_key_pair() -> (PrivateKey, PublicKey) { - PublicKey::random_keypair(&mut OsRng) -} diff --git a/dan_layer/engine/src/flow/error.rs b/dan_layer/engine/src/flow/error.rs deleted file mode 100644 index 60d9eec06e9..00000000000 --- a/dan_layer/engine/src/flow/error.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use thiserror::Error; -#[derive(Debug, Error)] -pub enum FlowEngineError { - #[error("The instruction execution failed: Inner error:{inner}")] - InstructionFailed { inner: String }, -} diff --git a/dan_layer/engine/src/flow/flow_factory.rs b/dan_layer/engine/src/flow/flow_factory.rs deleted file mode 100644 index 02ba0fffd2f..00000000000 --- a/dan_layer/engine/src/flow/flow_factory.rs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::collections::HashMap; - -use d3ne::WorkersBuilder; - -use crate::{ - flow::{FlowEngineError, FlowInstance}, - function_definitions::{FlowFunctionDefinition, FunctionArgDefinition}, - instructions::Instruction, - state::StateDbUnitOfWork, -}; - -#[derive(Clone, Default)] -pub struct FlowFactory { - flows: HashMap, FlowInstance)>, -} -impl FlowFactory { - pub fn new(flow_functions: &[FlowFunctionDefinition]) -> Self { - let mut flows = HashMap::new(); - for func_def in flow_functions { - // build_instance(&mut instance, &func_def); - flows.insert( - func_def.name.clone(), - ( - func_def.args.clone(), - FlowInstance::try_build(func_def.flow.clone(), WorkersBuilder::new().build()) - .expect("Could not build flow"), - ), - ); - } - Self { flows } - } - - pub fn invoke_write_method( - &self, - name: String, - instruction: &Instruction, - state_db: TUnitOfWork, - ) -> Result { - if let Some((args, engine)) = self.flows.get(&name) { - engine.process(instruction.args(), args, instruction.sender(), state_db) - } else { - todo!("could not find engine") - } - } -} diff --git a/dan_layer/engine/src/flow/flow_instance.rs b/dan_layer/engine/src/flow/flow_instance.rs deleted file mode 100644 index 8c89ebbae86..00000000000 --- a/dan_layer/engine/src/flow/flow_instance.rs +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::{ - collections::HashMap, - ops::Deref, - sync::{Arc, RwLock}, -}; - -use d3ne::{Engine, Node, Workers, WorkersBuilder}; -use serde_json::Value as JsValue; -use tari_common_types::types::PublicKey; -use tari_utilities::ByteArray; - -use crate::{ - flow::{ - workers::{ - ArgWorker, - CreateBucketWorker, - HasRoleWorker, - MintBucketWorker, - SenderWorker, - StartWorker, - StoreBucketWorker, - TextWorker, - }, - ArgValue, - FlowEngineError, - }, - function_definitions::{ArgType, FunctionArgDefinition}, - state::StateDbUnitOfWork, -}; - -#[derive(Clone, Debug)] -pub struct FlowInstance { - // engine: Engine, - // TODO: engine is not Send so can't be added here - // process: JsValue, - start_node: i64, - nodes: HashMap, -} - -impl FlowInstance { - pub fn try_build(value: JsValue, workers: Workers) -> Result { - let engine = Engine::new("tari@0.1.0", workers); - // dbg!(&value); - let nodes = engine.parse_value(value).expect("could not create engine"); - Ok(FlowInstance { - // process: value, - nodes, - start_node: 1, - }) - } - - pub fn process( - &self, - args: &[u8], - arg_defs: &[FunctionArgDefinition], - sender: PublicKey, - state_db: TUnitOfWork, - ) -> Result { - let mut engine_args = HashMap::new(); - - let mut remaining_args = Vec::from(args); - for ad in arg_defs { - let value = match ad.arg_type { - ArgType::String => { - let length = remaining_args.pop().expect("no more args: len") as usize; - let s_bytes: Vec = remaining_args.drain(0..length).collect(); - let s = String::from_utf8(s_bytes).expect("could not convert string"); - ArgValue::String(s) - }, - ArgType::Byte => ArgValue::Byte(remaining_args.pop().expect("No byte to read")), - ArgType::PublicKey => { - let bytes: Vec = remaining_args.drain(0..32).collect(); - let pk = PublicKey::from_bytes(&bytes).expect("Not a valid public key"); - ArgValue::PublicKey(pk) - }, - ArgType::Uint => { - let bytes: Vec = remaining_args.drain(0..8).collect(); - let mut fixed: [u8; 8] = [0u8; 8]; - fixed.copy_from_slice(&bytes); - let value = u64::from_le_bytes(fixed); - ArgValue::Uint(value) - }, - }; - engine_args.insert(ad.name.clone(), value); - } - - let state_db = Arc::new(RwLock::new(state_db)); - let engine = Engine::new("tari@0.1.0", load_workers(engine_args, sender, state_db.clone())); - let output = engine.process(&self.nodes, self.start_node); - let _od = output.expect("engine process failed"); - // if let Some(err) = od.get("error") { - // match err { - // Ok(_) => todo!("Unexpected Ok result returned from error"), - // Err(e) => { - // return Err(FlowEngineError::InstructionFailed { inner: e.to_string() }); - // }, - // } - // } - let inner = state_db.read().map(|s| s.deref().clone()).unwrap(); - Ok(inner) - } -} - -fn load_workers( - args: HashMap, - sender: PublicKey, - state_db: Arc>, -) -> Workers { - let mut workers = WorkersBuilder::new(); - workers.add(StartWorker {}); - workers.add(CreateBucketWorker { - state_db: state_db.clone(), - }); - workers.add(StoreBucketWorker { - state_db: state_db.clone(), - }); - workers.add(ArgWorker { args: args.clone() }); - workers.add(ArgWorker { args }); - workers.add(SenderWorker { sender }); - workers.add(TextWorker {}); - workers.add(HasRoleWorker { state_db }); - workers.add(MintBucketWorker {}); - workers.build() -} diff --git a/dan_layer/engine/src/flow/mod.rs b/dan_layer/engine/src/flow/mod.rs deleted file mode 100644 index 96a826171a4..00000000000 --- a/dan_layer/engine/src/flow/mod.rs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -pub mod error; -mod flow_factory; -mod flow_instance; -pub mod workers; - -use std::any::Any; - -pub use error::FlowEngineError; -pub use flow_factory::FlowFactory; -pub use flow_instance::FlowInstance; -use tari_common_types::types::PublicKey; - -#[derive(Clone, Debug)] -pub enum ArgValue { - String(String), - Byte(u8), - PublicKey(PublicKey), - Uint(u64), -} - -impl ArgValue { - pub fn into_any(self) -> Box { - match self { - ArgValue::String(s) => Box::new(s), - ArgValue::Byte(b) => Box::new(b), - ArgValue::PublicKey(k) => Box::new(k), - ArgValue::Uint(u) => Box::new(u), - } - } -} diff --git a/dan_layer/engine/src/flow/workers/arg_worker.rs b/dan_layer/engine/src/flow/workers/arg_worker.rs deleted file mode 100644 index 2d9e8964936..00000000000 --- a/dan_layer/engine/src/flow/workers/arg_worker.rs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::collections::HashMap; - -use d3ne::{InputData, Node, OutputData, OutputDataBuilder, Worker}; -use tari_utilities::hex::Hex; - -use crate::flow::ArgValue; - -pub struct ArgWorker { - pub args: HashMap, -} - -impl Worker for ArgWorker { - // fn call(&self, node: Node, inputs: InputData) -> OutputData { - // let name = node.get_string_field("name", &inputs).unwrap(); - // let mut map = HashMap::new(); - // let value = self.args.get(&name).cloned().expect("could not find arg"); - // match value { - // ArgValue::Uint(x) => map.insert( - // "default".to_string(), - // Ok(IOData { - // data: Box::new(x as i64), - // }), - // ), - // ArgValue::PublicKey(pk) => map.insert( - // "default".to_string(), - // Ok(IOData { - // data: Box::new(pk.to_hex()), - // }), - // ), - // _ => todo!(), - // }; - // - // Rc::new(map) - // } - - fn name(&self) -> &str { - "tari::arg" - } - - fn work(&self, node: &Node, input_data: InputData) -> anyhow::Result { - let name = node.get_string_field("name", &input_data)?; - let value = self.args.get(&name).cloned().expect("could not find arg"); - let output = match value { - ArgValue::Uint(x) => OutputDataBuilder::new().data("default", Box::new(x as i64)), - ArgValue::PublicKey(pk) => OutputDataBuilder::new().data("default", Box::new(pk.to_hex())), - _ => todo!(), - }; - Ok(output.build()) - } -} diff --git a/dan_layer/engine/src/flow/workers/create_bucket_worker.rs b/dan_layer/engine/src/flow/workers/create_bucket_worker.rs deleted file mode 100644 index f4368842e57..00000000000 --- a/dan_layer/engine/src/flow/workers/create_bucket_worker.rs +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::{ - convert::TryFrom, - sync::{Arc, RwLock}, -}; - -use d3ne::{InputData, Node, OutputData, OutputDataBuilder, Worker}; -use tari_common_types::types::PublicKey; -use tari_utilities::{hex::Hex, ByteArray}; - -use crate::{ - models::{Bucket, ResourceAddress}, - state::StateDbUnitOfWork, -}; - -pub struct CreateBucketWorker { - pub state_db: Arc>, -} - -impl Worker for CreateBucketWorker { - fn name(&self) -> &str { - "tari::create_bucket" - } - - fn work(&self, node: &Node, input_data: InputData) -> anyhow::Result { - // TODO: return proper errors.... - let amount = u64::try_from(node.get_number_field("amount", &input_data)?)?; - let vault_id = ResourceAddress::from_hex(&node.get_string_field("vault_id", &input_data)?)?; - let token_id = u64::try_from(node.get_number_field("token_id", &input_data)?)?; - let from = PublicKey::from_hex(&node.get_string_field("from", &input_data)?).expect("Not a valid pub key"); - let mut state = self.state_db.write().unwrap(); - let balance_key = format!("token_id-{}-{}", vault_id, token_id); - let balance = state.get_u64(&balance_key, from.as_bytes())?.unwrap_or(0); - let new_balance = balance.checked_sub(amount).expect("Not enough funds to create bucket"); - state - .set_u64(&balance_key, from.as_bytes(), new_balance) - .expect("Could not save state"); - let output = OutputDataBuilder::new() - .data("default", Box::new(())) - .data("bucket", Box::new(Bucket::for_token(vault_id, vec![token_id]))) - .build(); - Ok(output) - } - // let mut map = HashMap::new(); - // let amount = match node.get_number_field("amount", &inputs) { - // Ok(a) => a as u64, - // Err(err) => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(err)); - // return Rc::new(err_map); - // }, - // }; - // let token_id = match node.get_number_field("token_id", &inputs) { - // Ok(a) => a as u64, - // Err(err) => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(err)); - // return Rc::new(err_map); - // }, - // }; - // let asset_id = match node.get_number_field("asset_id", &inputs) { - // Ok(a) => a as u64, - // Err(err) => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(err)); - // return Rc::new(err_map); - // }, - // }; - // let from = match node.get_string_field("from", &inputs) { - // Ok(a) => PublicKey::from_hex(&a).expect("Not a valid pub key"), - // Err(err) => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(err)); - // return Rc::new(err_map); - // }, - // }; - // - // let mut state = self.state_db.write().unwrap(); - // let balance_key = format!("token_id-{}-{}", asset_id, token_id); - // let balance = match state.get_u64(&balance_key, from.as_bytes()) { - // Ok(b) => b.unwrap_or(0), - // Err(err) => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(err.into())); - // return Rc::new(err_map); - // }, - // }; - // - // let new_balance = match balance.checked_sub(amount) { - // Some(x) => x, - // None => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(anyhow!("Not enough funds to create bucket"))); - // return Rc::new(err_map); - // }, - // }; - // match state.set_u64(&balance_key, from.as_bytes(), new_balance) { - // Ok(_) => (), - // Err(err) => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(err.into())); - // return Rc::new(err_map); - // }, - // } - // - // let bucket = Bucket::new(amount, token_id, asset_id); - // map.insert("default".to_string(), Ok(IOData { data: Box::new(()) })); - // map.insert("bucket".to_string(), Ok(IOData { data: Box::new(bucket) })); - // Rc::new(map) - // } -} diff --git a/dan_layer/engine/src/flow/workers/has_role_worker.rs b/dan_layer/engine/src/flow/workers/has_role_worker.rs deleted file mode 100644 index df9bc9641e3..00000000000 --- a/dan_layer/engine/src/flow/workers/has_role_worker.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::sync::{Arc, RwLock}; - -use d3ne::{InputData, Node, OutputData, OutputDataBuilder, Worker}; - -use crate::state::StateDbUnitOfWork; - -pub struct HasRoleWorker { - pub state_db: Arc>, -} -impl Worker for HasRoleWorker { - // fn call(&self, node: Node, inputs: InputData) -> OutputData { - // let _role = node.get_string_field("role", &inputs).unwrap(); - // - // let _pubkey = match node.get_string_field("pubkey", &inputs) { - // Ok(a) => PublicKey::from_hex(&a).expect("Not a valid pub key"), - // Err(err) => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(err)); - // return Rc::new(err_map); - // }, - // }; - // - // // let state = self.state_db.read().expect("Could not get lock on data"); - // // state.get_value() - // // TODO: read roles from db - // let mut map = HashMap::new(); - // map.insert("default".to_string(), Ok(IOData { data: Box::new(()) })); - // Rc::new(map) - // } - - fn name(&self) -> &str { - "tari::has_role" - } - - fn work(&self, node: &Node, input_data: InputData) -> anyhow::Result { - let _role = node.get_string_field("role", &input_data)?; - Ok(OutputDataBuilder::new().data("default", Box::new(())).build()) - } -} diff --git a/dan_layer/engine/src/flow/workers/mint_bucket_worker.rs b/dan_layer/engine/src/flow/workers/mint_bucket_worker.rs deleted file mode 100644 index af5386330d7..00000000000 --- a/dan_layer/engine/src/flow/workers/mint_bucket_worker.rs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::convert::TryFrom; - -use d3ne::{InputData, Node, OutputData, OutputDataBuilder, Worker}; - -use crate::models::{Bucket, ResourceAddress}; - -pub struct MintBucketWorker {} - -impl Worker for MintBucketWorker { - // fn call(&self, node: Node, inputs: InputData) -> OutputData { - // let mut map = HashMap::new(); - // let amount = match node.get_number_field("amount", &inputs) { - // Ok(a) => a as u64, - // Err(err) => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(err)); - // return Rc::new(err_map); - // }, - // }; - // let token_id = match node.get_number_field("token_id", &inputs) { - // Ok(a) => a as u64, - // Err(err) => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(err)); - // return Rc::new(err_map); - // }, - // }; - // - // let asset_id = match node.get_number_field("asset_id", &inputs) { - // Ok(a) => a as u64, - // Err(err) => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(err)); - // return Rc::new(err_map); - // }, - // }; - // let bucket = Bucket::new(amount, token_id, asset_id); - // map.insert("default".to_string(), Ok(IOData { data: Box::new(()) })); - // map.insert("bucket".to_string(), Ok(IOData { data: Box::new(bucket) })); - // Rc::new(map) - // } - - fn name(&self) -> &str { - "tari::mint_bucket" - } - - fn work(&self, node: &Node, inputs: InputData) -> anyhow::Result { - let _amount = u64::try_from(node.get_number_field("amount", &inputs)?)?; - let token_id = u64::try_from(node.get_number_field("token_id", &inputs)?)?; - let vault_id = ResourceAddress::from_hex(&node.get_string_field("vault_id", &inputs)?)?; - let bucket = Bucket::for_token(vault_id, vec![token_id]); - let output = OutputDataBuilder::new() - .data("default", Box::new(())) - .data("bucket", Box::new(bucket)) - .build(); - Ok(output) - } -} diff --git a/dan_layer/engine/src/flow/workers/mod.rs b/dan_layer/engine/src/flow/workers/mod.rs deleted file mode 100644 index c44e88c458e..00000000000 --- a/dan_layer/engine/src/flow/workers/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause -mod arg_worker; -mod create_bucket_worker; -mod has_role_worker; -mod mint_bucket_worker; -mod sender_worker; -mod start_worker; -mod store_bucket_worker; -mod text_worker; - -pub use arg_worker::ArgWorker; -pub use create_bucket_worker::CreateBucketWorker; -pub use has_role_worker::HasRoleWorker; -pub use mint_bucket_worker::MintBucketWorker; -pub use sender_worker::SenderWorker; -pub use start_worker::StartWorker; -pub use store_bucket_worker::StoreBucketWorker; -pub use text_worker::TextWorker; diff --git a/dan_layer/engine/src/flow/workers/sender_worker.rs b/dan_layer/engine/src/flow/workers/sender_worker.rs deleted file mode 100644 index 16f47b2745d..00000000000 --- a/dan_layer/engine/src/flow/workers/sender_worker.rs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use d3ne::{InputData, Node, OutputData, OutputDataBuilder, Worker}; -use tari_common_types::types::PublicKey; -use tari_utilities::hex::Hex; - -pub struct SenderWorker { - pub sender: PublicKey, -} - -impl Worker for SenderWorker { - // fn call(&self, _node: Node, _input: InputData) -> OutputData { - // let mut map = HashMap::new(); - // map.insert( - // "default".to_string(), - // Ok(IOData { - // data: Box::new(self.sender.to_hex()), - // }), - // ); - // Rc::new(map) - // } - - fn name(&self) -> &str { - "core::sender" - } - - fn work(&self, _node: &Node, _input_data: InputData) -> anyhow::Result { - Ok(OutputDataBuilder::new() - .data("default", Box::new(self.sender.to_hex())) - .build()) - } -} diff --git a/dan_layer/engine/src/flow/workers/start_worker.rs b/dan_layer/engine/src/flow/workers/start_worker.rs deleted file mode 100644 index 3bb2fd2d936..00000000000 --- a/dan_layer/engine/src/flow/workers/start_worker.rs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use d3ne::{InputData, Node, OutputData, OutputDataBuilder, Worker}; - -pub struct StartWorker {} - -impl Worker for StartWorker { - // fn call(&self, _node: Node, _inputs: InputData) -> OutputData { - // let mut map = HashMap::new(); - // map.insert("default".to_string(), Ok(IOData { data: Box::new(()) })); - // Rc::new(map) - // } - - fn name(&self) -> &str { - "core::start" - } - - fn work(&self, _node: &Node, _input_data: InputData) -> anyhow::Result { - Ok(OutputDataBuilder::new().data("default", Box::new(())).build()) - } -} diff --git a/dan_layer/engine/src/flow/workers/store_bucket_worker.rs b/dan_layer/engine/src/flow/workers/store_bucket_worker.rs deleted file mode 100644 index 3286f32132c..00000000000 --- a/dan_layer/engine/src/flow/workers/store_bucket_worker.rs +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::sync::{Arc, RwLock}; - -use d3ne::{InputData, Node, OutputData, OutputDataBuilder, Worker}; -use tari_common_types::types::PublicKey; -use tari_utilities::{hex::Hex, ByteArray}; - -use crate::{models::Bucket, state::StateDbUnitOfWork}; - -pub struct StoreBucketWorker { - pub state_db: Arc>, -} - -impl Worker for StoreBucketWorker { - // fn call(&self, node: Node, inputs: InputData) -> OutputData { - // let mut map = HashMap::new(); - // let bucket: Bucket = match node.get_field_t("bucket", &inputs) { - // Ok(a) => a, - // Err(err) => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(err)); - // return Rc::new(err_map); - // }, - // }; - // - // let to = match node.get_string_field("to", &inputs) { - // Ok(a) => PublicKey::from_hex(&a).expect("Not a valid pub key"), - // Err(err) => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(err)); - // return Rc::new(err_map); - // }, - // }; - // - // let mut state = self.state_db.write().unwrap(); - // let balance_key = format!("token_id-{}-{}", bucket.asset_id(), bucket.token_id()); - // let balance = match state.get_u64(&balance_key, to.as_bytes()) { - // Ok(b) => b.unwrap_or(0), - // Err(err) => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(err.into())); - // return Rc::new(err_map); - // }, - // }; - // match state.set_u64( - // &balance_key, - // to.as_bytes(), - // bucket.amount().checked_add(balance).expect("overflowed"), - // ) { - // Ok(_) => (), - // Err(err) => { - // let mut err_map = HashMap::new(); - // err_map.insert("error".to_string(), Err(err.into())); - // return Rc::new(err_map); - // }, - // } - // - // map.insert("default".to_string(), Ok(IOData { data: Box::new(()) })); - // // map.insert("bucket".to_string(), Ok(IOData { data: Box::new(bucket) })); - // Rc::new(map) - // } - - fn name(&self) -> &str { - "tari::store_bucket" - } - - fn work(&self, node: &Node, inputs: InputData) -> anyhow::Result { - let bucket: Bucket = serde_json::from_str(&node.get_string_field("bucket", &inputs)?)?; - let to = PublicKey::from_hex(&node.get_string_field("to", &inputs)?)?; - let mut state = self.state_db.write().unwrap(); - // TODO: handle panics - let balance_key = format!( - "token_id-{}-{}", - bucket.resource_address(), - bucket.token_ids().unwrap()[0] - ); - let balance = state.get_u64(&balance_key, to.as_bytes())?.unwrap_or(0); - state.set_u64( - &balance_key, - to.as_bytes(), - bucket.amount().checked_add(balance).expect("overflowed"), - )?; - - let output = OutputDataBuilder::new().data("default", Box::new(())).build(); - Ok(output) - } -} diff --git a/dan_layer/engine/src/flow/workers/text_worker.rs b/dan_layer/engine/src/flow/workers/text_worker.rs deleted file mode 100644 index 24e90379d0a..00000000000 --- a/dan_layer/engine/src/flow/workers/text_worker.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use d3ne::{InputData, Node, OutputData, OutputDataBuilder, Worker}; - -pub struct TextWorker {} - -impl Worker for TextWorker { - // fn call(&self, node: Node, inputs: InputData) -> OutputData { - // let txt = node.get_string_field("txt", &inputs).unwrap(); - // let mut map = HashMap::new(); - // map.insert("txt".to_string(), Ok(IOData { data: Box::new(txt) })); - // Rc::new(map) - // } - - fn name(&self) -> &str { - "core::text" - } - - fn work(&self, node: &Node, input_data: InputData) -> anyhow::Result { - let txt = node.get_string_field("txt", &input_data)?; - Ok(OutputDataBuilder::new().data("txt", Box::new(txt)).build()) - } -} diff --git a/dan_layer/engine/src/function_definitions/flow_function_definition.rs b/dan_layer/engine/src/function_definitions/flow_function_definition.rs deleted file mode 100644 index 0ac03e7fa96..00000000000 --- a/dan_layer/engine/src/function_definitions/flow_function_definition.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause -use serde::{Deserialize, Serialize}; -use serde_json::Value as JsValue; - -use crate::function_definitions::FunctionArgDefinition; - -#[derive(Serialize, Deserialize, Clone, Debug)] -pub struct FlowFunctionDefinition { - pub name: String, - pub args: Vec, - pub flow: JsValue, -} diff --git a/dan_layer/engine/src/function_definitions/function_arg_definition.rs b/dan_layer/engine/src/function_definitions/function_arg_definition.rs deleted file mode 100644 index 5d55835c018..00000000000 --- a/dan_layer/engine/src/function_definitions/function_arg_definition.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Clone, Debug)] -pub struct FunctionArgDefinition { - pub name: String, - #[serde(rename = "type")] - pub arg_type: ArgType, -} - -#[derive(Serialize, Deserialize, Clone, Debug)] -#[serde(rename_all = "snake_case")] -pub enum ArgType { - String, - Byte, - PublicKey, - Uint, -} diff --git a/dan_layer/engine/src/function_definitions/mod.rs b/dan_layer/engine/src/function_definitions/mod.rs deleted file mode 100644 index d0998b05287..00000000000 --- a/dan_layer/engine/src/function_definitions/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -mod function_arg_definition; - -mod flow_function_definition; -mod wasm_function_definition; - -pub use flow_function_definition::FlowFunctionDefinition; -pub use function_arg_definition::{ArgType, FunctionArgDefinition}; -pub use wasm_function_definition::WasmFunctionDefinition; diff --git a/dan_layer/engine/src/function_definitions/wasm_function_definition.rs b/dan_layer/engine/src/function_definitions/wasm_function_definition.rs deleted file mode 100644 index c68f44a0038..00000000000 --- a/dan_layer/engine/src/function_definitions/wasm_function_definition.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use serde::{Deserialize, Serialize}; - -use crate::function_definitions::FunctionArgDefinition; - -#[derive(Serialize, Deserialize, Default, Clone, Debug)] -pub struct WasmFunctionDefinition { - pub name: String, - pub args: Vec, - pub in_module: String, -} diff --git a/dan_layer/engine/src/instruction/builder.rs b/dan_layer/engine/src/instruction/builder.rs deleted file mode 100644 index a5321753482..00000000000 --- a/dan_layer/engine/src/instruction/builder.rs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_common_types::types::PrivateKey; - -use super::{Instruction, InstructionSet}; -use crate::instruction::signature::InstructionSignature; - -#[derive(Debug, Clone, Default)] -pub struct InstructionBuilder { - instructions: Vec, - signature: Option, -} - -impl InstructionBuilder { - pub fn new() -> Self { - Self { - instructions: Vec::new(), - signature: None, - } - } - - pub fn add_instruction(&mut self, instruction: Instruction) -> &mut Self { - self.instructions.push(instruction); - // Reset the signature as it is no longer valid - self.signature = None; - self - } - - pub fn sign(&mut self, secret_key: &PrivateKey) -> &mut Self { - self.signature = Some(InstructionSignature::sign(secret_key, &self.instructions)); - self - } - - pub fn build(&mut self) -> InstructionSet { - InstructionSet { - instructions: self.instructions.drain(..).collect(), - signature: self.signature.take().expect("not signed"), - } - } -} diff --git a/dan_layer/engine/src/instruction/error.rs b/dan_layer/engine/src/instruction/error.rs deleted file mode 100644 index 9d4e9bb1963..00000000000 --- a/dan_layer/engine/src/instruction/error.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_template_lib::models::PackageId; - -use crate::{runtime::RuntimeError, wasm::WasmExecutionError}; - -#[derive(Debug, thiserror::Error)] -pub enum InstructionError { - #[error(transparent)] - WasmExecutionError(#[from] WasmExecutionError), - #[error("Package {package_id} not found")] - PackageNotFound { package_id: PackageId }, - #[error("Invalid template")] - TemplateNameNotFound { name: String }, - #[error(transparent)] - RuntimeError(#[from] RuntimeError), -} diff --git a/dan_layer/engine/src/instruction/mod.rs b/dan_layer/engine/src/instruction/mod.rs deleted file mode 100644 index f2ac91f665c..00000000000 --- a/dan_layer/engine/src/instruction/mod.rs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -mod builder; -pub use builder::InstructionBuilder; - -mod error; - -mod processor; -pub use processor::InstructionProcessor; - -mod signature; -pub use signature::InstructionSignature; -use tari_template_lib::models::{ComponentId, PackageId}; - -#[derive(Debug, Clone)] -pub enum Instruction { - CallFunction { - package_id: PackageId, - template: String, - function: String, - args: Vec>, - }, - CallMethod { - package_id: PackageId, - component_id: ComponentId, - method: String, - args: Vec>, - }, -} - -#[derive(Debug, Clone)] -pub struct InstructionSet { - pub instructions: Vec, - pub signature: InstructionSignature, -} diff --git a/dan_layer/engine/src/instruction/processor.rs b/dan_layer/engine/src/instruction/processor.rs deleted file mode 100644 index 37b8408f6b1..00000000000 --- a/dan_layer/engine/src/instruction/processor.rs +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::sync::Arc; - -use tari_template_abi::encode; - -use crate::{ - instruction::{error::InstructionError, Instruction, InstructionSet}, - packager::Package, - runtime::{Runtime, RuntimeInterface}, - traits::Invokable, - wasm::{ExecutionResult, Process}, -}; - -#[derive(Debug, Clone)] -pub struct InstructionProcessor { - package: Package, - runtime_interface: TRuntimeInterface, -} - -impl InstructionProcessor -where TRuntimeInterface: RuntimeInterface + Clone + 'static -{ - pub fn new(runtime_interface: TRuntimeInterface, package: Package) -> Self { - Self { - package, - runtime_interface, - } - } - - pub fn execute(&self, instruction_set: InstructionSet) -> Result, InstructionError> { - let mut results = Vec::with_capacity(instruction_set.instructions.len()); - - // TODO: implement engine - let state = Runtime::new(Arc::new(self.runtime_interface.clone())); - for instruction in instruction_set.instructions { - let result = match instruction { - Instruction::CallFunction { - package_id, - template, - function, - args, - } => { - if package_id != self.package.id() { - return Err(InstructionError::PackageNotFound { package_id }); - } - - let module = self - .package - .get_module_by_name(&template) - .ok_or(InstructionError::TemplateNameNotFound { name: template })?; - - // TODO: implement intelligent instance caching - let process = Process::start(module.clone(), state.clone(), package_id)?; - process.invoke_by_name(&function, args)? - }, - Instruction::CallMethod { - package_id, - component_id, - method, - args, - } => { - if package_id != self.package.id() { - return Err(InstructionError::PackageNotFound { package_id }); - } - let component = self.runtime_interface.get_component(&component_id)?; - let module = self.package.get_module_by_name(&component.module_name).ok_or_else(|| { - InstructionError::TemplateNameNotFound { - name: component.module_name.clone(), - } - })?; - - let mut final_args = Vec::with_capacity(args.len() + 1); - final_args.push(encode(&component).unwrap()); - final_args.extend(args); - - // TODO: implement intelligent instance caching - let process = Process::start(module.clone(), state.clone(), package_id)?; - process.invoke_by_name(&method, final_args)? - }, - }; - - results.push(result); - } - - Ok(results) - } -} diff --git a/dan_layer/engine/src/instruction/signature.rs b/dan_layer/engine/src/instruction/signature.rs deleted file mode 100644 index e6a4cbd6be1..00000000000 --- a/dan_layer/engine/src/instruction/signature.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_common_types::types::{PrivateKey, Signature}; - -use crate::{crypto::create_key_pair, instruction::Instruction}; - -#[derive(Debug, Clone)] -pub struct InstructionSignature(Signature); - -impl InstructionSignature { - pub fn sign(secret_key: &PrivateKey, _instructions: &[Instruction]) -> Self { - let (nonce, _) = create_key_pair(); - // TODO: create proper challenge - let challenge = [0u8; 32]; - Self(Signature::sign(secret_key.clone(), nonce, &challenge).unwrap()) - } -} diff --git a/dan_layer/engine/src/instructions/hashing.rs b/dan_layer/engine/src/instructions/hashing.rs deleted file mode 100644 index 2602d3ddc57..00000000000 --- a/dan_layer/engine/src/instructions/hashing.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use digest::Digest; -use tari_crypto::{ - hash_domain, - hashing::{DomainSeparatedHasher, LengthExtensionAttackResistant}, -}; - -hash_domain!( - DanLayerEngineInstructionsDomain, - "com.tari.tari_project.dan_layer.engine.instructions", - 1 -); - -pub(crate) const INSTRUCTION_LABEL: &str = "instruction"; - -pub(crate) fn dan_layer_engine_instructions( - label: &'static str, -) -> DomainSeparatedHasher { - DomainSeparatedHasher::::new_with_label(label) -} diff --git a/dan_layer/engine/src/instructions/instruction.rs b/dan_layer/engine/src/instructions/instruction.rs deleted file mode 100644 index 4e71c7f2cd5..00000000000 --- a/dan_layer/engine/src/instructions/instruction.rs +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::fmt::{Display, Formatter}; - -use tari_common_types::types::{FixedHash, PublicKey}; -use tari_crypto::hash::blake2::Blake256; -use tari_dan_common_types::TemplateId; -use tari_utilities::hex::Hex; - -use super::hashing::{dan_layer_engine_instructions, INSTRUCTION_LABEL}; - -#[derive(Clone, Debug)] -pub struct Instruction { - template_id: TemplateId, - method: String, - args: Vec, - sender: PublicKey, - // from: TokenId, - // signature: ComSig, - hash: FixedHash, -} - -impl PartialEq for Instruction { - fn eq(&self, other: &Self) -> bool { - self.hash.eq(&other.hash) - } -} - -impl Instruction { - pub fn new( - template_id: TemplateId, - method: String, - args: Vec, - sender: PublicKey, - // from: TokenId, - // _signature: ComSig, - ) -> Self { - let mut s = Self { - template_id, - method, - args, - sender, - // from, - // TODO: this is obviously wrong - // signature: ComSig::default(), - hash: FixedHash::zero(), - }; - s.hash = s.calculate_hash(); - s - } - - pub fn template_id(&self) -> TemplateId { - self.template_id - } - - pub fn method(&self) -> &str { - &self.method - } - - pub fn args(&self) -> &[u8] { - &self.args - } - - pub fn sender(&self) -> PublicKey { - self.sender.clone() - } - - // // TODO: rename to avoid use of from - // pub fn from_owner(&self) -> &TokenId { - // &self.from - // } - - // pub fn _signature(&self) -> &ComSig { - // &self.signature - // } - - pub fn hash(&self) -> &FixedHash { - &self.hash - } - - pub fn calculate_hash(&self) -> FixedHash { - // Blake256 has 32-byte output - let b = dan_layer_engine_instructions::(INSTRUCTION_LABEL) - .chain(self.method.as_bytes()) - .chain(&self.args) - .finalize(); - - let mut out = [0u8; 32]; - out.copy_from_slice(b.as_ref()); - - out.into() - } -} - -impl Display for Instruction { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!( - f, - "Method: {}, Hash: {}, Args: {} bytes, Template: {}", - self.method, - self.hash.to_hex(), - self.args.len(), - self.template_id - ) - } -} diff --git a/dan_layer/engine/src/instructions/mod.rs b/dan_layer/engine/src/instructions/mod.rs deleted file mode 100644 index 614a8ed58bf..00000000000 --- a/dan_layer/engine/src/instructions/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -mod hashing; -mod instruction; - -pub use instruction::Instruction; diff --git a/dan_layer/engine/src/lib.rs b/dan_layer/engine/src/lib.rs deleted file mode 100644 index 7026a48d92c..00000000000 --- a/dan_layer/engine/src/lib.rs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -pub mod flow; -pub mod function_definitions; -pub mod instructions; -pub mod models; -pub mod state; -pub mod wasm; - -pub mod crypto; -pub mod instruction; -pub mod packager; -pub mod runtime; -pub mod state_store; -pub mod traits; diff --git a/dan_layer/engine/src/models/bucket.rs b/dan_layer/engine/src/models/bucket.rs deleted file mode 100644 index ee6a5900f5f..00000000000 --- a/dan_layer/engine/src/models/bucket.rs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use serde::Deserialize; -use tari_template_abi::{Decode, Encode}; - -use crate::models::resource::{Resource, ResourceAddress}; - -#[derive(Debug, Clone, Encode, Decode, Deserialize)] -pub struct Bucket { - resource: Resource, -} - -impl Bucket { - pub fn for_coin(address: ResourceAddress, amount: u64) -> Self { - Self { - resource: Resource::Coin { address, amount }, - } - } - - pub fn for_token(address: ResourceAddress, token_ids: Vec) -> Self { - Self { - resource: Resource::Token { address, token_ids }, - } - } - - pub fn amount(&self) -> u64 { - match self.resource { - Resource::Coin { ref amount, .. } => *amount, - Resource::Token { ref token_ids, .. } => token_ids.len() as u64, - } - } - - pub fn resource_address(&self) -> ResourceAddress { - match self.resource { - Resource::Coin { address, .. } => address, - Resource::Token { address, .. } => address, - } - } - - pub fn token_ids(&self) -> Option<&[u64]> { - match self.resource { - Resource::Coin { .. } => None, - Resource::Token { ref token_ids, .. } => Some(token_ids), - } - } -} diff --git a/dan_layer/engine/src/models/component.rs b/dan_layer/engine/src/models/component.rs deleted file mode 100644 index 97bc30dc6b6..00000000000 --- a/dan_layer/engine/src/models/component.rs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_template_abi::{CreateComponentArg, Decode, Encode}; -use tari_template_lib::{ - models::{ContractAddress, PackageId}, - Hash, -}; - -pub type ComponentId = Hash; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct Component { - pub contract_address: ContractAddress, - pub package_id: PackageId, - pub module_name: String, - pub state: Vec, -} - -impl From for Component { - fn from(arg: CreateComponentArg) -> Self { - Self { - contract_address: arg.contract_address, - package_id: arg.package_id, - module_name: arg.component_name, - state: arg.state, - } - } -} diff --git a/dan_layer/engine/src/models/mod.rs b/dan_layer/engine/src/models/mod.rs deleted file mode 100644 index 5b7a99f1488..00000000000 --- a/dan_layer/engine/src/models/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -mod bucket; -pub use bucket::Bucket; - -mod resource; -pub use resource::{Resource, ResourceAddress}; - -mod vault; -pub use vault::Vault; diff --git a/dan_layer/engine/src/models/resource.rs b/dan_layer/engine/src/models/resource.rs deleted file mode 100644 index ba2b078d687..00000000000 --- a/dan_layer/engine/src/models/resource.rs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_template_abi::{Decode, Encode}; -use tari_template_lib::Hash; - -pub type ResourceAddress = Hash; - -#[derive(Debug, Clone, Encode, Decode, serde::Deserialize)] -pub enum Resource { - Coin { - address: ResourceAddress, - // type_descriptor: TypeDescriptor, - amount: u64, - }, - Token { - address: ResourceAddress, - // type_descriptor: TypeDescriptor, - token_ids: Vec, - }, -} - -pub trait ResourceTypeDescriptor { - fn type_descriptor(&self) -> TypeDescriptor; -} - -// The thinking here, that a resource address + a "local" type id together can used to validate type safety of the -// resources at runtime. The local type id can be defined as a unique id within the scope of the contract. We'll have to -// get further to see if this can work or is even needed. -#[derive(Debug, Clone, Encode, Decode, serde::Deserialize)] -pub struct TypeDescriptor { - type_id: u16, -} diff --git a/dan_layer/engine/src/models/vault.rs b/dan_layer/engine/src/models/vault.rs deleted file mode 100755 index a9ba3cd9415..00000000000 --- a/dan_layer/engine/src/models/vault.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_template_abi::{Decode, Encode}; - -use crate::models::Resource; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct Vault { - resource: Resource, -} - -impl Vault { - pub fn new(resource: Resource) -> Self { - Self { resource } - } -} diff --git a/dan_layer/engine/src/packager/error.rs b/dan_layer/engine/src/packager/error.rs deleted file mode 100644 index 9d69ed4e851..00000000000 --- a/dan_layer/engine/src/packager/error.rs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::wasm::WasmExecutionError; - -#[derive(Debug, thiserror::Error)] -pub enum PackageError { - #[error(transparent)] - WasmModuleError(#[from] WasmExecutionError), - #[error("Template called engine during initialization")] - TemplateCalledEngineDuringInitialization, - #[error(transparent)] - CompileError(#[from] wasmer::CompileError), - #[error(transparent)] - InstantiationError(#[from] wasmer::InstantiationError), - #[error(transparent)] - HostEnvInitError(#[from] wasmer::HostEnvInitError), - #[error("Runtime error: {0}")] - RuntimeError(#[from] wasmer::RuntimeError), -} diff --git a/dan_layer/engine/src/packager/mod.rs b/dan_layer/engine/src/packager/mod.rs deleted file mode 100644 index f671e0e2db2..00000000000 --- a/dan_layer/engine/src/packager/mod.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -mod error; -pub use error::PackageError; - -mod package; -pub use package::{Package, PackageBuilder}; - -mod module_loader; -pub use module_loader::PackageModuleLoader; diff --git a/dan_layer/engine/src/packager/module_loader.rs b/dan_layer/engine/src/packager/module_loader.rs deleted file mode 100644 index 871d9558b64..00000000000 --- a/dan_layer/engine/src/packager/module_loader.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::packager::PackageError; - -pub trait PackageModuleLoader { - type Loaded; - type Error: Into; - - fn load_module(&self) -> Result; -} diff --git a/dan_layer/engine/src/packager/package.rs b/dan_layer/engine/src/packager/package.rs deleted file mode 100644 index e0fc3e8c832..00000000000 --- a/dan_layer/engine/src/packager/package.rs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::collections::HashMap; - -use digest::Digest; -use rand::{rngs::OsRng, RngCore}; -use tari_template_lib::models::PackageId; - -use crate::{ - crypto, - packager::{error::PackageError, PackageModuleLoader}, - wasm::{LoadedWasmModule, WasmModule}, -}; - -#[derive(Debug, Clone)] -pub struct Package { - id: PackageId, - wasm_modules: HashMap, -} - -impl Package { - pub fn builder() -> PackageBuilder { - PackageBuilder::new() - } - - pub fn get_module_by_name(&self, name: &str) -> Option<&LoadedWasmModule> { - self.wasm_modules.get(name) - } - - pub fn id(&self) -> PackageId { - self.id - } -} - -#[derive(Debug, Clone, Default)] -pub struct PackageBuilder { - wasm_modules: Vec, -} - -impl PackageBuilder { - pub fn new() -> Self { - Self { - wasm_modules: Vec::new(), - } - } - - pub fn add_wasm_module(&mut self, wasm_module: WasmModule) -> &mut Self { - self.wasm_modules.push(wasm_module); - self - } - - pub fn build(&self) -> Result { - let mut wasm_modules = HashMap::with_capacity(self.wasm_modules.len()); - let id = new_package_id(); - for wasm in &self.wasm_modules { - let loaded = wasm.load_module()?; - wasm_modules.insert(loaded.template_name().to_string(), loaded); - } - - Ok(Package { id, wasm_modules }) - } -} - -fn new_package_id() -> PackageId { - let v = OsRng.next_u32(); - let hash: [u8; 32] = crypto::hasher("package") - // TODO: Proper package id - .chain(&v.to_le_bytes()) - .finalize().into(); - hash.into() -} diff --git a/dan_layer/engine/src/runtime.rs b/dan_layer/engine/src/runtime.rs deleted file mode 100644 index 9681464a0bf..00000000000 --- a/dan_layer/engine/src/runtime.rs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - collections::HashMap, - fmt::Debug, - sync::{Arc, RwLock}, -}; - -use tari_common_types::types::FixedHash; -use tari_template_lib::{ - args::LogLevel, - models::{Component, ComponentId, ComponentInstance}, -}; - -use crate::{models::Bucket, state_store::StateStoreError}; - -#[derive(Clone)] -pub struct Runtime { - tracker: Arc>, - interface: Arc, -} - -impl Runtime { - pub fn new(engine: Arc) -> Self { - Self { - tracker: Arc::new(RwLock::new(ChangeTracker::default())), - interface: engine, - } - } - - pub fn interface(&self) -> &dyn RuntimeInterface { - &*self.interface - } -} - -impl Debug for Runtime { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Runtime") - .field("tracker", &self.tracker) - .field("engine", &"dyn RuntimeEngine") - .finish() - } -} - -#[derive(Debug, Clone, Default)] -pub struct ChangeTracker { - pub buckets: HashMap, -} - -#[derive(Debug, thiserror::Error)] -pub enum RuntimeError { - #[error("State DB error: {0}")] - StateDbError(#[from] anyhow::Error), - #[error("State storage error: {0}")] - StateStoreError(#[from] StateStoreError), - #[error("Component not found with id '{id}'")] - ComponentNotFound { id: ComponentId }, -} - -pub trait RuntimeInterface: Send + Sync { - fn emit_log(&self, level: LogLevel, message: &str); - fn create_component(&self, component: Component) -> Result; - fn get_component(&self, component_id: &ComponentId) -> Result; - fn set_component_state(&self, component_id: &ComponentId, state: Vec) -> Result<(), RuntimeError>; -} diff --git a/dan_layer/engine/src/state/db_key_value.rs b/dan_layer/engine/src/state/db_key_value.rs deleted file mode 100644 index 7e639270ca9..00000000000 --- a/dan_layer/engine/src/state/db_key_value.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -#[derive(Debug, Clone)] -pub struct DbKeyValue { - pub schema: String, - pub key: Vec, - pub value: Vec, -} diff --git a/dan_layer/engine/src/state/error.rs b/dan_layer/engine/src/state/error.rs deleted file mode 100644 index e6e840d0fcd..00000000000 --- a/dan_layer/engine/src/state/error.rs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause -use std::sync::PoisonError; - -use tari_mmr::error::MerkleMountainRangeError; -use thiserror::Error; - -#[derive(Debug, Error)] -pub enum StateStorageError { - #[error("Lock error")] - LockError, - #[error("Merkle error:{0}")] - MerkleMountainRangeError(#[from] MerkleMountainRangeError), - #[error("Could not connect to storage:{reason}")] - ConnectionError { reason: String }, - #[error("Query error:{reason}")] - QueryError { reason: String }, - #[error("Migration error: {reason}")] - MigrationError { reason: String }, - #[error("General storage error: {details}")] - General { details: String }, -} - -impl From> for StateStorageError { - fn from(_err: PoisonError) -> Self { - Self::LockError - } -} diff --git a/dan_layer/engine/src/state/mocks/mod.rs b/dan_layer/engine/src/state/mocks/mod.rs deleted file mode 100644 index 06eb2c9285f..00000000000 --- a/dan_layer/engine/src/state/mocks/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -pub mod state_db; diff --git a/dan_layer/engine/src/state/mocks/state_db.rs b/dan_layer/engine/src/state/mocks/state_db.rs deleted file mode 100644 index db968a6899c..00000000000 --- a/dan_layer/engine/src/state/mocks/state_db.rs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use crate::state::{error::StateStorageError, DbKeyValue, DbStateOpLogEntry, StateDbBackendAdapter}; - -#[derive(Debug, Clone, Default)] -pub struct MockStateDbBackupAdapter; - -impl StateDbBackendAdapter for MockStateDbBackupAdapter { - type BackendTransaction = (); - type Error = StateStorageError; - - fn create_transaction(&self) -> Result { - todo!() - } - - fn update_key_value( - &self, - _schema: &str, - _key: &[u8], - _value: &[u8], - _tx: &Self::BackendTransaction, - ) -> Result<(), Self::Error> { - todo!() - } - - fn get(&self, _schema: &str, _key: &[u8]) -> Result>, Self::Error> { - todo!() - } - - fn find_keys_by_value(&self, _schema: &str, _value: &[u8]) -> Result>, Self::Error> { - todo!() - } - - fn commit(&self, _tx: &Self::BackendTransaction) -> Result<(), Self::Error> { - todo!() - } - - fn get_all_schemas(&self, _tx: &Self::BackendTransaction) -> Result, Self::Error> { - todo!() - } - - fn get_all_values_for_schema( - &self, - _schema: &str, - _tx: &Self::BackendTransaction, - ) -> Result, Self::Error> { - todo!() - } - - fn get_state_op_logs_by_height( - &self, - _height: u64, - _tx: &Self::BackendTransaction, - ) -> Result, Self::Error> { - todo!() - } - - fn add_state_oplog_entry( - &self, - _entry: DbStateOpLogEntry, - _tx: &Self::BackendTransaction, - ) -> Result<(), Self::Error> { - todo!() - } - - fn clear_all_state(&self, _tx: &Self::BackendTransaction) -> Result<(), Self::Error> { - todo!() - } -} diff --git a/dan_layer/engine/src/state/mod.rs b/dan_layer/engine/src/state/mod.rs deleted file mode 100644 index f1823575433..00000000000 --- a/dan_layer/engine/src/state/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -mod state_db_unit_of_work; -pub use state_db_unit_of_work::{StateDbUnitOfWork, StateDbUnitOfWorkImpl, StateDbUnitOfWorkReader, UnitOfWorkContext}; - -mod db_key_value; -pub use db_key_value::DbKeyValue; - -mod state_db; -pub use state_db::StateDb; - -mod state_db_backend_adapter; -pub use state_db_backend_adapter::StateDbBackendAdapter; - -mod state_op_log; -pub use state_op_log::{DbStateOpLogEntry, DbStateOperation}; - -pub mod models; - -pub mod error; -pub mod mocks; diff --git a/dan_layer/engine/src/state/models/key_value.rs b/dan_layer/engine/src/state/models/key_value.rs deleted file mode 100644 index 98271aa6c9d..00000000000 --- a/dan_layer/engine/src/state/models/key_value.rs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Default, Clone, Debug)] -pub struct KeyValue { - pub key: Vec, - pub value: Vec, -} diff --git a/dan_layer/engine/src/state/models/mod.rs b/dan_layer/engine/src/state/models/mod.rs deleted file mode 100644 index 72e01e6142c..00000000000 --- a/dan_layer/engine/src/state/models/mod.rs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -mod key_value; -pub use key_value::KeyValue; - -mod schema_state; -pub use schema_state::SchemaState; - -mod state_root; -pub use state_root::StateRoot; - -mod op_log; -pub use op_log::{StateOpLogEntry, StateOperation}; diff --git a/dan_layer/engine/src/state/models/op_log.rs b/dan_layer/engine/src/state/models/op_log.rs deleted file mode 100644 index 8ccea65eb72..00000000000 --- a/dan_layer/engine/src/state/models/op_log.rs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use crate::state::{DbStateOpLogEntry, DbStateOperation}; - -#[derive(Debug)] -pub struct StateOpLogEntry { - inner: DbStateOpLogEntry, -} - -impl StateOpLogEntry { - pub fn operation(&self) -> StateOperation { - self.inner.operation.into() - } - - pub fn into_inner(self) -> DbStateOpLogEntry { - self.inner - } -} - -impl From for StateOpLogEntry { - fn from(inner: DbStateOpLogEntry) -> Self { - Self { inner } - } -} - -#[derive(Debug, Clone, Copy)] -pub enum StateOperation { - Set, - Delete, -} - -impl StateOperation { - pub fn as_op_str(&self) -> &str { - use StateOperation::{Delete, Set}; - match self { - Set => "S", - Delete => "D", - } - } -} - -impl From for StateOperation { - fn from(op: DbStateOperation) -> Self { - match op { - DbStateOperation::Set => StateOperation::Set, - DbStateOperation::Delete => StateOperation::Delete, - } - } -} diff --git a/dan_layer/engine/src/state/models/schema_state.rs b/dan_layer/engine/src/state/models/schema_state.rs deleted file mode 100644 index b5ed83d11cc..00000000000 --- a/dan_layer/engine/src/state/models/schema_state.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use serde::{Deserialize, Serialize}; - -use crate::state::models::KeyValue; - -#[derive(Serialize, Deserialize, Default, Clone, Debug)] -pub struct SchemaState { - pub name: String, - pub items: Vec, -} - -impl SchemaState { - pub fn new(name: String, items: Vec) -> Self { - Self { name, items } - } - - pub fn push_key_value(&mut self, key_value: KeyValue) -> &mut Self { - self.items.push(key_value); - self - } -} diff --git a/dan_layer/engine/src/state/models/state_root.rs b/dan_layer/engine/src/state/models/state_root.rs deleted file mode 100644 index f5102e5fca7..00000000000 --- a/dan_layer/engine/src/state/models/state_root.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use tari_common_types::types::FixedHash; - -#[derive(PartialEq, Eq, Debug, Clone, Copy)] -pub struct StateRoot { - root: FixedHash, -} - -impl StateRoot { - pub fn new(root: FixedHash) -> Self { - Self { root } - } - - pub fn as_bytes(&self) -> &[u8] { - self.root.as_slice() - } - - pub fn initial() -> Self { - Self { - root: FixedHash::zero(), - } - } -} - -impl From for FixedHash { - fn from(state_root: StateRoot) -> Self { - state_root.root - } -} diff --git a/dan_layer/engine/src/state/state_db.rs b/dan_layer/engine/src/state/state_db.rs deleted file mode 100644 index 7fa683888a4..00000000000 --- a/dan_layer/engine/src/state/state_db.rs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use tari_common_types::types::FixedHash; - -use crate::state::{ - state_db_unit_of_work::{StateDbUnitOfWorkImpl, StateDbUnitOfWorkReader, UnitOfWorkContext}, - StateDbBackendAdapter, -}; - -pub struct StateDb { - backend_adapter: TStateDbBackendAdapter, - contract_id: FixedHash, -} - -impl StateDb { - pub fn new(contract_id: FixedHash, backend_adapter: TStateDbBackendAdapter) -> Self { - Self { - backend_adapter, - contract_id, - } - } - - pub fn new_unit_of_work(&self, height: u64) -> StateDbUnitOfWorkImpl { - StateDbUnitOfWorkImpl::new( - UnitOfWorkContext::new(height, self.contract_id), - self.backend_adapter.clone(), - ) - } - - pub fn reader(&self) -> impl StateDbUnitOfWorkReader { - // TODO: A reader doesnt need the current context, should perhaps make a read-only implementation that the - // writable implementation also uses - StateDbUnitOfWorkImpl::new( - UnitOfWorkContext::new(0, self.contract_id), - self.backend_adapter.clone(), - ) - } -} diff --git a/dan_layer/engine/src/state/state_db_backend_adapter.rs b/dan_layer/engine/src/state/state_db_backend_adapter.rs deleted file mode 100644 index c25eea837dd..00000000000 --- a/dan_layer/engine/src/state/state_db_backend_adapter.rs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use crate::state::{db_key_value::DbKeyValue, error::StateStorageError, DbStateOpLogEntry}; - -pub trait StateDbBackendAdapter: Send + Sync + Clone { - type BackendTransaction; - type Error: Into; - - fn create_transaction(&self) -> Result; - fn update_key_value( - &self, - schema: &str, - key: &[u8], - value: &[u8], - tx: &Self::BackendTransaction, - ) -> Result<(), Self::Error>; - fn get(&self, schema: &str, key: &[u8]) -> Result>, Self::Error>; - fn find_keys_by_value(&self, schema: &str, value: &[u8]) -> Result>, Self::Error>; - fn commit(&self, tx: &Self::BackendTransaction) -> Result<(), Self::Error>; - fn get_all_schemas(&self, tx: &Self::BackendTransaction) -> Result, Self::Error>; - fn get_all_values_for_schema( - &self, - schema: &str, - tx: &Self::BackendTransaction, - ) -> Result, Self::Error>; - fn get_state_op_logs_by_height( - &self, - height: u64, - tx: &Self::BackendTransaction, - ) -> Result, Self::Error>; - fn add_state_oplog_entry(&self, entry: DbStateOpLogEntry, tx: &Self::BackendTransaction) - -> Result<(), Self::Error>; - fn clear_all_state(&self, tx: &Self::BackendTransaction) -> Result<(), Self::Error>; -} diff --git a/dan_layer/engine/src/state/state_db_unit_of_work.rs b/dan_layer/engine/src/state/state_db_unit_of_work.rs deleted file mode 100644 index 3770656b54a..00000000000 --- a/dan_layer/engine/src/state/state_db_unit_of_work.rs +++ /dev/null @@ -1,331 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::{ - convert::TryInto, - ops::Deref, - sync::{Arc, RwLock, RwLockReadGuard}, -}; - -use digest::Digest; -use log::*; -use tari_common_types::types::FixedHash; -use tari_crypto::hash::blake2::Blake256; -use tari_dan_common_types::storage::UnitOfWorkTracker; -use tari_mmr::{MemBackendVec, MerkleMountainRange}; -use tari_utilities::hex::Hex; - -use crate::state::{ - db_key_value::DbKeyValue, - error::StateStorageError, - models::{KeyValue, SchemaState, StateOpLogEntry, StateRoot}, - DbStateOpLogEntry, - StateDbBackendAdapter, -}; - -const LOG_TARGET: &str = "tari::dan::state_db"; - -pub trait StateDbUnitOfWork: StateDbUnitOfWorkReader { - fn set_value(&mut self, schema: String, key: Vec, value: Vec) -> Result<(), StateStorageError>; - fn set_u64(&mut self, schema: &str, key: &[u8], value: u64) -> Result<(), StateStorageError>; - fn commit(&mut self) -> Result<(), StateStorageError>; - fn clear_all_state(&self) -> Result<(), StateStorageError>; -} - -pub trait StateDbUnitOfWorkReader: Clone + Send + Sync { - fn context(&self) -> &UnitOfWorkContext; - fn get_value(&self, schema: &str, key: &[u8]) -> Result>, StateStorageError>; - fn get_u64(&self, schema: &str, key: &[u8]) -> Result, StateStorageError>; - fn find_keys_by_value(&self, schema: &str, value: &[u8]) -> Result>, StateStorageError>; - fn calculate_root(&self) -> Result; - fn get_all_state(&self) -> Result, StateStorageError>; - fn get_op_logs_for_height(&self, height: u64) -> Result, StateStorageError>; -} - -#[derive(Debug, Clone)] -pub struct UnitOfWorkContext { - contract_id: FixedHash, - height: u64, -} - -impl UnitOfWorkContext { - pub fn new(height: u64, contract_id: FixedHash) -> Self { - Self { height, contract_id } - } - - pub fn height(&self) -> u64 { - self.height - } - - pub fn contract_id(&self) -> &FixedHash { - &self.contract_id - } -} - -pub struct StateDbUnitOfWorkImpl { - inner: Arc>>, - context: UnitOfWorkContext, -} - -impl StateDbUnitOfWorkImpl { - pub fn new(context: UnitOfWorkContext, backend_adapter: TBackendAdapter) -> Self { - Self { - inner: Arc::new(RwLock::new(StateDbUnitOfWorkInner::new(backend_adapter))), - context, - } - } -} - -impl Clone for StateDbUnitOfWorkImpl { - fn clone(&self) -> Self { - Self { - inner: self.inner.clone(), - context: self.context.clone(), - } - } -} - -impl StateDbUnitOfWork for StateDbUnitOfWorkImpl { - fn set_value(&mut self, schema: String, key: Vec, value: Vec) -> Result<(), StateStorageError> { - let mut inner = self.inner.write()?; - inner - .updates - .push(UnitOfWorkTracker::new(DbKeyValue { schema, key, value }, true)); - - Ok(()) - } - - fn set_u64(&mut self, schema: &str, key: &[u8], value: u64) -> Result<(), StateStorageError> { - self.set_value(schema.to_string(), Vec::from(key), Vec::from(value.to_le_bytes())) - } - - fn commit(&mut self) -> Result<(), StateStorageError> { - let mut inner = self.inner.write()?; - if !inner.is_dirty() { - return Ok(()); - } - let tx = inner - .backend_adapter - .create_transaction() - .map_err(TBackendAdapter::Error::into)?; - // let mut current_tree = inner - // .backend_adapter - // .get_current_state_tree(&tx) - // .map_err(TBackendAdapter::Error::into)?; - debug!(target: LOG_TARGET, "Committing {} state update(s)", inner.updates.len()); - for item in &inner.updates { - let i = item.get(); - inner - .backend_adapter - .update_key_value(&i.schema, &i.key, &i.value, &tx) - .map_err(TBackendAdapter::Error::into)?; - - inner - .backend_adapter - .add_state_oplog_entry( - DbStateOpLogEntry::set_operation(self.context.height, i.deref().clone()), - &tx, - ) - .map_err(TBackendAdapter::Error::into)?; - // let key = format!("{}.{}", &i.schema, bs58::encode(&i.key).into_string()); - // current_tree.insert(key, i.value.clone()); - } - - // inner - // .backend_adapter - // .set_current_state_tree(current_tree, &tx) - // .map_err(TBackendAdapter::Error::into)?; - - inner - .backend_adapter - .commit(&tx) - .map_err(TBackendAdapter::Error::into)?; - inner.updates = vec![]; - - Ok(()) - } - - /// Clears the state db immediately (before commit) - this will not be needed in future when build up the state from - /// instructions/op logs - fn clear_all_state(&self) -> Result<(), StateStorageError> { - let inner = self.inner.write()?; - let tx = inner - .backend_adapter - .create_transaction() - .map_err(TBackendAdapter::Error::into)?; - inner - .backend_adapter - .clear_all_state(&tx) - .map_err(TBackendAdapter::Error::into) - } -} - -impl StateDbUnitOfWorkReader for StateDbUnitOfWorkImpl { - fn context(&self) -> &UnitOfWorkContext { - &self.context - } - - fn get_value(&self, schema: &str, key: &[u8]) -> Result>, StateStorageError> { - let inner = self.inner.read()?; - // Hit the DB. - inner - .backend_adapter - .get(schema, key) - .map_err(TBackendAdapter::Error::into) - } - - fn get_u64(&self, schema: &str, key: &[u8]) -> Result, StateStorageError> { - let data = self.get_value(schema, key)?; - match data { - Some(data) => { - let mut data2: [u8; 8] = [0; 8]; - data2.copy_from_slice(&data); - Ok(Some(u64::from_le_bytes(data2))) - }, - None => Ok(None), - } - } - - fn find_keys_by_value(&self, schema: &str, value: &[u8]) -> Result>, StateStorageError> { - let inner = self.inner.read()?; - inner - .backend_adapter - .find_keys_by_value(schema, value) - .map_err(TBackendAdapter::Error::into) - } - - // TODO: Needs to keep a merkle proof of the latest state and append all updates onto that to get the merkle root - // TODO: This does not include _new_ keys that are to be added in the updates - fn calculate_root(&self) -> Result { - let inner = self.inner.read()?; - let tx = inner - .backend_adapter - .create_transaction() - .map_err(TBackendAdapter::Error::into)?; - // let root_node : Node> = inner.backend_adapter.get_current_state_tree(&tx).into(); - - // omg it's an MMR of MMRs - let mut top_level_mmr = MerkleMountainRange::::new(MemBackendVec::new()); - let schemas = inner - .backend_adapter - .get_all_schemas(&tx) - .map_err(TBackendAdapter::Error::into)?; - debug!( - target: LOG_TARGET, - "calculate_root: {} key value schemas loaded", - schemas.len() - ); - - for schema in schemas { - let mut mmr = MerkleMountainRange::::new(MemBackendVec::new()); - for key_value in inner - .backend_adapter - .get_all_values_for_schema(&schema, &tx) - .map_err(TBackendAdapter::Error::into)? - { - debug!( - target: LOG_TARGET, - "schema = {}, key = {}, value = {}", - schema, - key_value.key.to_hex(), - key_value.value.to_hex() - ); - if let Some(updated_value) = find_update(&inner, &schema, &key_value.key) { - let hasher = Blake256::new(); - mmr.push(hasher.chain(&key_value.key).chain(updated_value).finalize().to_vec())?; - } else { - let hasher = Blake256::new(); - mmr.push(hasher.chain(&key_value.key).chain(&key_value.value).finalize().to_vec())?; - } - } - let hasher = Blake256::new(); - top_level_mmr.push(hasher.chain(schema).chain(mmr.get_merkle_root()?).finalize().to_vec())?; - } - - Ok(StateRoot::new( - top_level_mmr - .get_merkle_root()? - .try_into() - .expect("MMR output incorrect size"), - )) - } - - fn get_all_state(&self) -> Result, StateStorageError> { - let inner = self.inner.read()?; - let tx = inner - .backend_adapter - .create_transaction() - .map_err(TBackendAdapter::Error::into)?; - - let schemas = inner - .backend_adapter - .get_all_schemas(&tx) - .map_err(TBackendAdapter::Error::into)?; - let mut schema_state = Vec::with_capacity(schemas.len()); - for schema in schemas { - let key_values = inner - .backend_adapter - .get_all_values_for_schema(&schema, &tx) - .map_err(TBackendAdapter::Error::into)?; - - let key_values = key_values - .into_iter() - .map(|kv| { - let value = find_update(&inner, &schema, &kv.key).unwrap_or(kv.value); - KeyValue { key: kv.key, value } - }) - .collect(); - - schema_state.push(SchemaState::new(schema, key_values)); - } - Ok(schema_state) - } - - fn get_op_logs_for_height(&self, height: u64) -> Result, StateStorageError> { - let inner = self.inner.read()?; - let tx = inner - .backend_adapter - .create_transaction() - .map_err(TBackendAdapter::Error::into)?; - - let op_logs = inner - .backend_adapter - .get_state_op_logs_by_height(height, &tx) - .map_err(TBackendAdapter::Error::into)?; - - let op_logs = op_logs.into_iter().map(Into::into).collect(); - Ok(op_logs) - } -} - -fn find_update( - inner: &RwLockReadGuard>, - schema: &str, - key: &[u8], -) -> Option> { - for update in &inner.updates { - let update = update.get(); - if update.schema == schema && update.key == key { - return Some(update.value.clone()); - } - } - None -} - -pub struct StateDbUnitOfWorkInner { - backend_adapter: TBackendAdapter, - updates: Vec>, -} - -impl StateDbUnitOfWorkInner { - pub fn new(backend_adapter: TBackendAdapter) -> Self { - Self { - updates: vec![], - backend_adapter, - } - } - - pub fn is_dirty(&self) -> bool { - !self.updates.is_empty() - } -} diff --git a/dan_layer/engine/src/state/state_op_log.rs b/dan_layer/engine/src/state/state_op_log.rs deleted file mode 100644 index 764fba8f417..00000000000 --- a/dan_layer/engine/src/state/state_op_log.rs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::str::FromStr; - -use tari_common_types::types::FixedHash; - -use crate::state::DbKeyValue; - -#[derive(Debug)] -pub struct DbStateOpLogEntry { - pub height: u64, - pub merkle_root: Option, - pub operation: DbStateOperation, - pub schema: String, - pub key: Vec, - pub value: Option>, -} - -impl DbStateOpLogEntry { - pub fn set_operation(height: u64, key_value: DbKeyValue) -> Self { - Self { - height, - merkle_root: None, - operation: DbStateOperation::Set, - schema: key_value.schema, - key: key_value.key, - value: Some(key_value.value), - } - } -} - -#[derive(Debug, Clone, Copy)] -pub enum DbStateOperation { - Set, - Delete, -} - -impl DbStateOperation { - pub fn as_op_str(&self) -> &str { - use DbStateOperation::{Delete, Set}; - match self { - Set => "S", - Delete => "D", - } - } -} - -impl FromStr for DbStateOperation { - type Err = (); - - fn from_str(s: &str) -> Result { - use DbStateOperation::{Delete, Set}; - match s { - "S" => Ok(Set), - "D" => Ok(Delete), - _ => Err(()), - } - } -} diff --git a/dan_layer/engine/src/state_store/memory.rs b/dan_layer/engine/src/state_store/memory.rs deleted file mode 100644 index 6e2ef15da35..00000000000 --- a/dan_layer/engine/src/state_store/memory.rs +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -use std::{ - collections::HashMap, - sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}, -}; - -use anyhow::anyhow; - -use crate::state_store::{AtomicDb, StateReader, StateStoreError, StateWriter}; - -type InnerKvMap = HashMap, Vec>; - -#[derive(Debug, Clone, Default)] -pub struct MemoryStateStore { - state: Arc>, -} - -pub struct MemoryTransaction { - pending: InnerKvMap, - guard: T, -} - -impl<'a> AtomicDb<'a> for MemoryStateStore { - type Error = anyhow::Error; - type ReadAccess = MemoryTransaction>; - type WriteAccess = MemoryTransaction>; - - fn read_access(&'a self) -> Result { - let guard = self.state.read().map_err(|_| anyhow!("Failed to read state"))?; - - Ok(MemoryTransaction { - pending: HashMap::default(), - guard, - }) - } - - fn write_access(&'a self) -> Result { - let guard = self.state.write().map_err(|_| anyhow!("Failed to write state"))?; - - Ok(MemoryTransaction { - pending: HashMap::default(), - guard, - }) - } - - fn commit(&self, mut tx: Self::WriteAccess) -> Result<(), Self::Error> { - tx.guard.extend(tx.pending.into_iter()); - Ok(()) - } -} - -impl<'a> StateReader for MemoryTransaction> { - fn get_state_raw(&self, key: &[u8]) -> Result>, StateStoreError> { - Ok(self.pending.get(key).cloned().or_else(|| self.guard.get(key).cloned())) - } - - fn exists(&self, key: &[u8]) -> Result { - Ok(self.pending.contains_key(key) || self.guard.contains_key(key)) - } -} - -impl<'a> StateReader for MemoryTransaction> { - fn get_state_raw(&self, key: &[u8]) -> Result>, StateStoreError> { - Ok(self.pending.get(key).cloned().or_else(|| self.guard.get(key).cloned())) - } - - fn exists(&self, key: &[u8]) -> Result { - Ok(self.pending.contains_key(key) || self.guard.contains_key(key)) - } -} - -impl<'a> StateWriter for MemoryTransaction> { - fn set_state_raw(&mut self, key: &[u8], value: Vec) -> Result<(), StateStoreError> { - self.pending.insert(key.to_vec(), value); - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use tari_template_abi::{Decode, Encode}; - - use super::*; - - #[test] - fn read_write() { - let store = MemoryStateStore::default(); - let mut access = store.write_access().unwrap(); - access.set_state_raw(b"abc", vec![1, 2, 3]).unwrap(); - let res = access.get_state_raw(b"abc").unwrap(); - assert_eq!(res, Some(vec![1, 2, 3])); - let res = access.get_state_raw(b"def").unwrap(); - assert_eq!(res, None); - } - - #[test] - fn read_write_rollback_commit() { - #[derive(Debug, Encode, Decode, PartialEq, Eq, Clone)] - struct UserData { - name: String, - age: u8, - } - - let user_data = UserData { - name: "Foo".to_string(), - age: 99, - }; - - let store = MemoryStateStore::default(); - { - let mut access = store.write_access().unwrap(); - access.set_state(b"abc", user_data.clone()).unwrap(); - let res = access.get_state(b"abc").unwrap(); - assert_eq!(res, Some(user_data.clone())); - let res = access.get_state::<_, UserData>(b"def").unwrap(); - assert_eq!(res, None); - // Drop without commit rolls back - } - - { - let access = store.read_access().unwrap(); - let res = access.get_state::<_, UserData>(b"abc").unwrap(); - assert_eq!(res, None); - } - - { - let mut access = store.write_access().unwrap(); - access.set_state(b"abc", user_data.clone()).unwrap(); - store.commit(access).unwrap(); - } - - let access = store.read_access().unwrap(); - let res = access.get_state(b"abc").unwrap(); - assert_eq!(res, Some(user_data)); - } -} diff --git a/dan_layer/engine/src/state_store/mod.rs b/dan_layer/engine/src/state_store/mod.rs deleted file mode 100644 index 9493aad4f15..00000000000 --- a/dan_layer/engine/src/state_store/mod.rs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub mod memory; - -use std::{error::Error, io}; - -use tari_template_abi::{encode, Decode, Encode}; - -/// Abstraction for any database that has atomic read/write semantics. -pub trait AtomicDb<'a> { - type Error; - type ReadAccess: 'a; - type WriteAccess: 'a; - - /// Obtain read access to the underlying database - fn read_access(&'a self) -> Result; - - /// Obtain write access to the underlying database - fn write_access(&'a self) -> Result; - - fn commit(&self, tx: Self::WriteAccess) -> Result<(), Self::Error>; -} - -pub trait StateReader { - fn get_state_raw(&self, key: &[u8]) -> Result>, StateStoreError>; - - fn get_state(&self, key: &K) -> Result, StateStoreError> { - let value = self.get_state_raw(&encode(key)?)?; - let value = value.map(|v| V::deserialize(&mut v.as_slice())).transpose()?; - Ok(value) - } - - fn exists(&self, key: &[u8]) -> Result; -} - -pub trait StateWriter: StateReader { - fn set_state_raw(&mut self, key: &[u8], value: Vec) -> Result<(), StateStoreError>; - fn set_state(&mut self, key: &K, value: V) -> Result<(), StateStoreError> { - self.set_state_raw(&encode(key)?, encode(&value)?) - } -} - -#[derive(Debug, thiserror::Error)] -pub enum StateStoreError { - #[error("Encoding error: {0}")] - EncodingError(#[from] io::Error), - #[error(transparent)] - Custom(anyhow::Error), - #[error("Error: {0}")] - CustomStr(String), -} - -impl StateStoreError { - pub fn custom(e: E) -> Self { - StateStoreError::Custom(e.into()) - } - - pub fn custom_str(e: &str) -> Self { - StateStoreError::CustomStr(e.to_string()) - } -} diff --git a/dan_layer/engine/src/traits.rs b/dan_layer/engine/src/traits.rs deleted file mode 100644 index 062c1452edb..00000000000 --- a/dan_layer/engine/src/traits.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::wasm::ExecutionResult; - -pub trait Invokable { - type Error; - - fn invoke_by_name(&self, name: &str, args: Vec>) -> Result; -} diff --git a/dan_layer/engine/src/wasm/compile.rs b/dan_layer/engine/src/wasm/compile.rs deleted file mode 100644 index 9ba3b152fb6..00000000000 --- a/dan_layer/engine/src/wasm/compile.rs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{fs, io, io::ErrorKind, path::Path, process::Command}; - -use cargo_toml::{Manifest, Product}; - -use super::module::WasmModule; - -pub fn compile_template>(package_dir: P, features: &[&str]) -> io::Result { - let mut args = ["build", "--target", "wasm32-unknown-unknown", "--release"] - .iter() - .map(ToString::to_string) - .collect::>(); - - if !features.is_empty() { - args.push("--features".to_string()); - args.extend(features.iter().map(ToString::to_string)); - } - - let status = Command::new("cargo") - .current_dir(package_dir.as_ref()) - .args(args) - .status()?; - if !status.success() { - return Err(io::Error::new( - ErrorKind::Other, - format!("Failed to compile package: {:?}", package_dir.as_ref()), - )); - } - - // resolve wasm name - let manifest = Manifest::from_path(&package_dir.as_ref().join("Cargo.toml")).unwrap(); - let wasm_name = if let Some(Product { name: Some(name), .. }) = manifest.lib { - // lib name - name - } else if let Some(pkg) = manifest.package { - // package name - pkg.name.replace('-', "_") - } else { - // file name - package_dir - .as_ref() - .file_name() - .unwrap() - .to_str() - .unwrap() - .to_owned() - .replace('-', "_") - }; - - // path of the wasm executable - let mut path = package_dir.as_ref().to_path_buf(); - path.push("target"); - path.push("wasm32-unknown-unknown"); - path.push("release"); - path.push(wasm_name); - path.set_extension("wasm"); - - // return - let code = fs::read(path)?; - Ok(WasmModule::from_code(code)) -} diff --git a/dan_layer/engine/src/wasm/environment.rs b/dan_layer/engine/src/wasm/environment.rs deleted file mode 100644 index 91d5454030b..00000000000 --- a/dan_layer/engine/src/wasm/environment.rs +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - cell::Cell, - fmt::{Debug, Formatter}, -}; - -use wasmer::{ - imports, - Function, - HostEnvInitError, - Instance, - LazyInit, - Memory, - NativeFunc, - Pages, - Resolver, - Store, - WasmerEnv, -}; - -use crate::wasm::WasmExecutionError; - -#[derive(Clone)] -pub struct WasmEnv { - memory: LazyInit, - mem_alloc: LazyInit>, - mem_free: LazyInit>, - state: T, -} - -impl WasmEnv { - pub fn new(state: T) -> Self { - Self { - state, - memory: LazyInit::new(), - mem_alloc: LazyInit::new(), - mem_free: LazyInit::new(), - } - } - - pub(super) fn alloc(&self, len: u32) -> Result { - let ptr = self.get_mem_alloc_func()?.call(len as i32)?; - if ptr == 0 { - return Err(WasmExecutionError::MemoryAllocationFailed); - } - - Ok(AllocPtr(ptr as u32, len)) - } - - pub(super) fn free(&self, ptr: AllocPtr) -> Result<(), WasmExecutionError> { - self.get_mem_free_func()?.call(ptr.as_i32())?; - Ok(()) - } - - pub(super) fn write_to_memory(&self, ptr: &AllocPtr, data: &[u8]) -> Result<(), WasmExecutionError> { - if data.len() != ptr.len() as usize { - return Err(WasmExecutionError::InvalidWriteLength { - allocated: ptr.len(), - requested: data.len() as u32, - }); - } - // SAFETY: The pointer has been allocated by alloc above and the runtime is single-threaded so data - // races are not possible. - unsafe { - self.get_memory()? - .uint8view() - .subarray(ptr.get(), ptr.end()) - .copy_from(data); - } - Ok(()) - } - - pub(super) fn read_memory_with_embedded_len(&self, ptr: u32) -> Result, WasmExecutionError> { - let memory = self.get_memory()?; - let view = memory.uint8view().subarray(ptr, memory.data_size() as u32 - 1); - let view_bytes = &*view; - if view_bytes.len() < 4 { - return Err(WasmExecutionError::MemoryUnderflow { - required: 4, - remaining: view_bytes.len(), - }); - } - - let mut buf = [0u8; 4]; - copy_from_cell_slice(view_bytes, &mut buf); - let len = u32::from_le_bytes(buf); - let data = self.read_from_memory(ptr + 4, len)?; - - Ok(data) - } - - pub(super) fn read_from_memory(&self, ptr: u32, len: u32) -> Result, WasmExecutionError> { - let memory = self.get_memory()?; - let size = memory.data_size(); - if u64::from(ptr) >= size || u64::from(ptr + len) >= memory.data_size() { - return Err(WasmExecutionError::MemoryPointerOutOfRange { - size: memory.data_size(), - pointer: u64::from(ptr), - len: u64::from(len), - }); - } - let view = memory.uint8view().subarray(ptr, ptr + len); - let mut data = vec![0u8; len as usize]; - copy_from_cell_slice(&*view, &mut data); - Ok(data) - } - - pub fn state(&self) -> &T { - &self.state - } - - fn get_mem_alloc_func(&self) -> Result<&NativeFunc, WasmExecutionError> { - self.mem_alloc - .get_ref() - .ok_or_else(|| WasmExecutionError::MissingAbiFunction { - function: "tari_alloc".into(), - }) - } - - fn get_mem_free_func(&self) -> Result<&NativeFunc, WasmExecutionError> { - self.mem_free - .get_ref() - .ok_or_else(|| WasmExecutionError::MissingAbiFunction { - function: "tari_free".into(), - }) - } - - fn get_memory(&self) -> Result<&Memory, WasmExecutionError> { - self.memory.get_ref().ok_or(WasmExecutionError::MemoryNotInitialized) - } - - pub fn mem_size(&self) -> Pages { - self.memory.get_ref().map(|mem| mem.size()).unwrap_or(Pages(0)) - } - - pub fn create_resolver(&self, store: &Store, tari_engine: Function) -> impl Resolver { - imports! { - "env" => { - "tari_engine" => tari_engine, - "debug" => Function::new_native_with_env(store, self.clone(), Self::debug_handler), - } - } - } - - fn debug_handler(env: &Self, arg_ptr: i32, arg_len: i32) { - const WASM_DEBUG_LOG_TARGET: &str = "tari::dan::wasm"; - match env.read_from_memory(arg_ptr as u32, arg_len as u32) { - Ok(arg) => { - eprintln!("DEBUG: {}", String::from_utf8_lossy(&arg)); - }, - Err(err) => { - log::error!(target: WASM_DEBUG_LOG_TARGET, "Failed to read from memory: {}", err); - }, - } - } -} - -impl WasmerEnv for WasmEnv { - fn init_with_instance(&mut self, instance: &Instance) -> Result<(), HostEnvInitError> { - self.memory - .initialize(instance.exports.get_with_generics_weak("memory")?); - self.mem_alloc - .initialize(instance.exports.get_with_generics_weak("tari_alloc")?); - self.mem_free - .initialize(instance.exports.get_with_generics_weak("tari_free")?); - Ok(()) - } -} - -impl Debug for WasmEnv { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - f.debug_struct("WasmEnv") - .field("memory", &"LazyInit") - .field("tari_alloc", &" LazyInit") - .field("tari_free", &"LazyInit>") - .field("State", &self.state) - .finish() - } -} - -/// Efficiently copy read-only memory into a mutable buffer. -/// Panics if the length of `dest` is more than the length of `src`. -fn copy_from_cell_slice(src: &[Cell], dest: &mut [u8]) { - assert!(dest.len() <= src.len()); - let len = dest.len(); - // SAFETY: size_of::() is equal to size_of::(), we assert this below just in case. - let (head, body, tail) = unsafe { src[..len].align_to() }; - assert_eq!(head.len(), 0); - assert_eq!(tail.len(), 0); - dest.copy_from_slice(body); -} - -#[derive(Debug)] -pub struct AllocPtr(u32, u32); - -impl AllocPtr { - pub fn get(&self) -> u32 { - self.0 - } - - pub fn len(&self) -> u32 { - self.1 - } - - pub fn end(&self) -> u32 { - self.get() + self.len() - } - - pub fn as_i32(&self) -> i32 { - // We want the 'u32 as i32' conversion to wrap - self.get() as i32 - } -} diff --git a/dan_layer/engine/src/wasm/error.rs b/dan_layer/engine/src/wasm/error.rs deleted file mode 100644 index 9dacb379b1d..00000000000 --- a/dan_layer/engine/src/wasm/error.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::io; - -use thiserror::Error; -use wasmer::{ExportError, HostEnvInitError, InstantiationError}; - -use crate::runtime::RuntimeError; - -#[derive(Debug, Error)] -pub enum WasmError { - #[error("Missing argument at position {position} (name: {argument_name}")] - MissingArgument { argument_name: String, position: usize }, -} - -#[derive(Debug, thiserror::Error)] -pub enum WasmExecutionError { - #[error(transparent)] - InstantiationError(#[from] InstantiationError), - #[error(transparent)] - ExportError(#[from] ExportError), - #[error(transparent)] - WasmRuntimeError(#[from] wasmer::RuntimeError), - #[error(transparent)] - HostEnvInitError(#[from] HostEnvInitError), - #[error("Function {name} not found")] - FunctionNotFound { name: String }, - #[error("Expected function {function} to return a pointer")] - ExpectedPointerReturn { function: String }, - #[error("Attempted to write {requested} bytes but pointer allocated {allocated}")] - InvalidWriteLength { allocated: u32, requested: u32 }, - #[error("memory underflow: {required} bytes required but {remaining} remaining")] - MemoryUnderflow { required: usize, remaining: usize }, - #[error("memory pointer out of range: memory size of {size} but pointer is {pointer}")] - MemoryPointerOutOfRange { size: u64, pointer: u64, len: u64 }, - #[error("Memory allocation failed")] - MemoryAllocationFailed, - #[error("Memory not initialized")] - MemoryNotInitialized, - #[error("Invalid operation {op}")] - InvalidOperation { op: i32 }, - #[error("Missing function {function}")] - MissingAbiFunction { function: String }, - #[error("Runtime error: {0}")] - RuntimeError(#[from] RuntimeError), - #[error("Failed to decode argument for engine call: {0}")] - EngineArgDecodeFailed(io::Error), - #[error("maximum module memory size exceeded")] - MaxMemorySizeExceeded, - #[error("Failed to decode ABI")] - AbiDecodeError, - #[error("package ABI function returned an invalid type")] - InvalidReturnTypeFromAbiFunc, - #[error("package did not contain an ABI definition")] - NoAbiDefinition, - #[error("Unexpected ABI function {name}")] - UnexpectedAbiFunction { name: String }, -} diff --git a/dan_layer/engine/src/wasm/mod.rs b/dan_layer/engine/src/wasm/mod.rs deleted file mode 100644 index 39f0d76272f..00000000000 --- a/dan_layer/engine/src/wasm/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -mod wasm_module_definition; -mod wasm_module_factory; - -pub use wasm_module_definition::WasmModuleDefinition; -pub use wasm_module_factory::WasmModuleFactory; - -pub mod compile; - -mod error; -pub use error::{WasmError, WasmExecutionError}; - -mod environment; - -mod module; -pub use module::{LoadedWasmModule, WasmModule}; - -mod process; -pub use process::{ExecutionResult, Process}; diff --git a/dan_layer/engine/src/wasm/module.rs b/dan_layer/engine/src/wasm/module.rs deleted file mode 100644 index 0a98066334c..00000000000 --- a/dan_layer/engine/src/wasm/module.rs +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::sync::{ - atomic::{AtomicBool, Ordering}, - Arc, -}; - -use tari_template_abi::{FunctionDef, TemplateDef}; -use wasmer::{Extern, Function, Instance, Module, Store, Val, WasmerEnv}; - -use crate::{ - packager::{PackageError, PackageModuleLoader}, - wasm::{environment::WasmEnv, WasmExecutionError}, -}; - -#[derive(Debug, Clone)] -pub struct WasmModule { - code: Vec, -} - -impl WasmModule { - pub fn from_code(code: Vec) -> Self { - Self { code } - } - - pub fn code(&self) -> &[u8] { - &self.code - } -} - -impl PackageModuleLoader for WasmModule { - type Error = PackageError; - type Loaded = LoadedWasmModule; - - fn load_module(&self) -> Result { - let store = Store::default(); - let module = Module::new(&store, &self.code)?; - let violation_flag = Arc::new(AtomicBool::new(false)); - let mut env = WasmEnv::new(violation_flag.clone()); - - fn stub(env: &WasmEnv>, _op: i32, _arg_ptr: i32, _arg_len: i32) -> i32 { - env.state().store(true, Ordering::Relaxed); - 0 - } - - let stub = Function::new_native_with_env(&store, env.clone(), stub); - let imports = env.create_resolver(&store, stub); - let instance = Instance::new(&module, &imports)?; - env.init_with_instance(&instance)?; - validate_instance(&instance)?; - validate_environment(&env)?; - - let template = initialize_and_load_template_abi(&instance, &env)?; - if violation_flag.load(Ordering::Relaxed) { - return Err(PackageError::TemplateCalledEngineDuringInitialization); - } - Ok(LoadedWasmModule::new(template, module)) - } -} - -fn initialize_and_load_template_abi( - instance: &Instance, - env: &WasmEnv>, -) -> Result { - let abi_func = instance - .exports - .iter() - .find_map(|(name, export)| match export { - Extern::Function(f) if name.ends_with("_abi") && f.param_arity() == 0 && f.result_arity() == 1 => Some(f), - _ => None, - }) - .ok_or(WasmExecutionError::NoAbiDefinition)?; - - // Initialize ABI memory - let ret = abi_func.call(&[])?; - let ptr = match ret.get(0) { - Some(Val::I32(ptr)) => *ptr as u32, - Some(_) | None => return Err(WasmExecutionError::InvalidReturnTypeFromAbiFunc), - }; - - // Load ABI from memory - let data = env.read_memory_with_embedded_len(ptr)?; - let decoded = tari_template_abi::decode(&data).map_err(|_| WasmExecutionError::AbiDecodeError)?; - Ok(decoded) -} - -#[derive(Debug, Clone)] -pub struct LoadedWasmModule { - template: TemplateDef, - module: wasmer::Module, -} - -impl LoadedWasmModule { - pub fn new(template: TemplateDef, module: wasmer::Module) -> Self { - Self { template, module } - } - - pub fn wasm_module(&self) -> &wasmer::Module { - &self.module - } - - pub fn template_name(&self) -> &str { - &self.template.template_name - } - - pub fn template_def(&self) -> &TemplateDef { - &self.template - } - - pub fn find_func_by_name(&self, function_name: &str) -> Option<&FunctionDef> { - self.template.functions.iter().find(|f| f.name == *function_name) - } -} - -fn validate_environment(env: &WasmEnv>) -> Result<(), WasmExecutionError> { - const MAX_MEM_SIZE: usize = 2 * 1024 * 1024; - let mem_size = env.mem_size(); - if mem_size.bytes().0 > MAX_MEM_SIZE { - return Err(WasmExecutionError::MaxMemorySizeExceeded); - } - - Ok(()) -} - -fn validate_instance(instance: &Instance) -> Result<(), WasmExecutionError> { - // Enforce that only permitted functions are allowed - let unexpected_abi_func = instance - .exports - .iter() - .functions() - .find(|(name, _)| !is_func_permitted(name)); - if let Some((name, _)) = unexpected_abi_func { - return Err(WasmExecutionError::UnexpectedAbiFunction { name: name.to_string() }); - } - - Ok(()) -} - -fn is_func_permitted(name: &str) -> bool { - name.ends_with("_abi") || name.ends_with("_main") || name == "tari_alloc" || name == "tari_free" -} diff --git a/dan_layer/engine/src/wasm/process.rs b/dan_layer/engine/src/wasm/process.rs deleted file mode 100644 index 70d3e3fbd5b..00000000000 --- a/dan_layer/engine/src/wasm/process.rs +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::io; - -use borsh::{BorshDeserialize, BorshSerialize}; -use tari_template_abi::{decode, encode, encode_into, encode_with_len, CallInfo, Type}; -use tari_template_lib::{ - abi_context::AbiContext, - args::{CreateComponentArg, EmitLogArg, GetComponentArg, SetComponentStateArg}, - models::{Component, Contract, ContractAddress, Package, PackageId}, - ops, -}; -use wasmer::{Function, Instance, Module, Store, Val, WasmerEnv}; - -use crate::{ - runtime::Runtime, - traits::Invokable, - wasm::{ - environment::{AllocPtr, WasmEnv}, - error::WasmExecutionError, - LoadedWasmModule, - }, -}; - -const LOG_TARGET: &str = "tari::dan::wasm::process"; - -#[derive(Debug)] -pub struct Process { - module: LoadedWasmModule, - env: WasmEnv, - instance: Instance, - package_id: PackageId, - contract_address: ContractAddress, -} - -impl Process { - pub fn start(module: LoadedWasmModule, state: Runtime, package_id: PackageId) -> Result { - let store = Store::default(); - let mut env = WasmEnv::new(state); - let tari_engine = Function::new_native_with_env(&store, env.clone(), Self::tari_engine_entrypoint); - let resolver = env.create_resolver(&store, tari_engine); - let instance = Instance::new(module.wasm_module(), &resolver)?; - env.init_with_instance(&instance)?; - Ok(Self { - module, - env, - instance, - package_id, - // TODO: - contract_address: ContractAddress::default(), - }) - } - - fn alloc_and_write(&self, val: &T) -> Result { - let mut buf = Vec::with_capacity(512); - encode_into(val, &mut buf).unwrap(); - let ptr = self.env.alloc(buf.len() as u32)?; - self.env.write_to_memory(&ptr, &buf)?; - - Ok(ptr) - } - - pub fn wasm_module(&self) -> &Module { - self.module.wasm_module() - } - - fn tari_engine_entrypoint(env: &WasmEnv, op: i32, arg_ptr: i32, arg_len: i32) -> i32 { - let arg = match env.read_from_memory(arg_ptr as u32, arg_len as u32) { - Ok(arg) => arg, - Err(err) => { - log::error!(target: LOG_TARGET, "Failed to read from memory: {}", err); - return 0; - }, - }; - - let result = match op { - ops::OP_EMIT_LOG => Self::handle(env, arg, |env, arg: EmitLogArg| { - env.state().interface().emit_log(arg.level, &arg.message); - Result::<_, WasmExecutionError>::Ok(()) - }), - ops::OP_CREATE_COMPONENT => Self::handle(env, arg, |env, arg: CreateComponentArg| { - env.state().interface().create_component(Component { - contract_address: arg.contract_address, - package_id: arg.package_id, - module_name: arg.module_name, - state: arg.state, - }) - }), - ops::OP_GET_COMPONENT => Self::handle(env, arg, |env, arg: GetComponentArg| { - env.state().interface().get_component(&arg.component_id) - }), - ops::OP_SET_COMPONENT_STATE => Self::handle(env, arg, |env, arg: SetComponentStateArg| { - env.state() - .interface() - .set_component_state(&arg.component_id, arg.state) - }), - _ => Err(WasmExecutionError::InvalidOperation { op }), - }; - - result.unwrap_or_else(|err| { - log::error!(target: LOG_TARGET, "{}", err); - 0 - }) - } - - pub fn handle( - env: &WasmEnv, - args: Vec, - f: fn(&WasmEnv, T) -> Result, - ) -> Result - where - T: BorshDeserialize, - U: BorshSerialize, - WasmExecutionError: From, - { - let decoded = decode(&args).map_err(WasmExecutionError::EngineArgDecodeFailed)?; - let resp = f(env, decoded)?; - let encoded = encode_with_len(&resp); - let ptr = env.alloc(encoded.len() as u32)?; - env.write_to_memory(&ptr, &encoded)?; - // TODO: It's not clear how/if this memory is freed. When I drop it on the WASM side I get an - // out-of-bounds access error. - Ok(ptr.as_i32()) - } - - fn encoded_abi_context(&self) -> Vec { - encode(&AbiContext { - package: Package { id: self.package_id }, - contract: Contract { - address: self.contract_address, - }, - }) - .unwrap() - } -} - -impl Invokable for Process { - type Error = WasmExecutionError; - - fn invoke_by_name(&self, name: &str, args: Vec>) -> Result { - let func_def = self - .module - .find_func_by_name(name) - .ok_or_else(|| WasmExecutionError::FunctionNotFound { name: name.into() })?; - - let call_info = CallInfo { - abi_context: self.encoded_abi_context(), - func_name: func_def.name.clone(), - args, - }; - - let main_name = format!("{}_main", self.module.template_name()); - let func = self.instance.exports.get_function(&main_name)?; - - let call_info_ptr = self.alloc_and_write(&call_info)?; - let res = func.call(&[call_info_ptr.as_i32().into(), Val::I32(call_info_ptr.len() as i32)])?; - self.env.free(call_info_ptr)?; - let ptr = res - .get(0) - .and_then(|v| v.i32()) - .ok_or(WasmExecutionError::ExpectedPointerReturn { function: main_name })?; - - // Read response from memory - let raw = self.env.read_memory_with_embedded_len(ptr as u32)?; - - // TODO: decode raw as per function def - Ok(ExecutionResult { - value: wasmer::Value::I32(ptr), - raw, - return_type: func_def.output.clone(), - }) - } -} - -pub struct ExecutionResult { - pub value: wasmer::Value, - pub raw: Vec, - pub return_type: Type, -} - -impl ExecutionResult { - pub fn decode(&self) -> io::Result { - tari_template_abi::decode(&self.raw) - } -} diff --git a/dan_layer/engine/src/wasm/wasm_module_definition.rs b/dan_layer/engine/src/wasm/wasm_module_definition.rs deleted file mode 100644 index 1750e88dd04..00000000000 --- a/dan_layer/engine/src/wasm/wasm_module_definition.rs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::path::PathBuf; - -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Default, Clone, Debug)] -pub struct WasmModuleDefinition { - pub name: String, - pub path: PathBuf, -} diff --git a/dan_layer/engine/src/wasm/wasm_module_factory.rs b/dan_layer/engine/src/wasm/wasm_module_factory.rs deleted file mode 100644 index 92d17745d2f..00000000000 --- a/dan_layer/engine/src/wasm/wasm_module_factory.rs +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -use std::{collections::HashMap, fs}; - -use wasmer::{imports, Instance, Module, Store, Val, Value}; - -use crate::{ - function_definitions::{ArgType, WasmFunctionDefinition}, - instructions::Instruction, - state::StateDbUnitOfWork, - wasm::{WasmError, WasmModuleDefinition}, -}; - -#[derive(Clone, Default)] -pub struct WasmModuleFactory { - modules: HashMap, - functions: HashMap, String)>, -} - -impl WasmModuleFactory { - pub fn new(wasm_modules: &[WasmModuleDefinition], wasm_functions: &[WasmFunctionDefinition]) -> Self { - let mut modules = HashMap::new(); - for mod_def in wasm_modules { - let store = Store::default(); - let file = fs::read(&mod_def.path).expect("could not read all bytes"); - let module = Module::new(&store, file).expect("Did not compile"); - let import_object = imports! {}; // <- SDK for interacting with block chain - let _declared_imps: Vec<_> = module.imports().functions().collect(); - // TODO: Does wasm code auto run at this point - let instance = Instance::new(&module, &import_object).expect("Could not create instance"); - modules.insert(mod_def.name.clone(), instance); - } - let mut functions = HashMap::new(); - for func_def in wasm_functions { - if let Some(instance) = modules.get(&func_def.in_module) { - // check that imported function is actually present in wasm - let _function = instance.exports.get_function(&func_def.name).unwrap(); - - functions.insert( - func_def.name.clone(), - ( - func_def.args.iter().map(|at| at.arg_type.clone()).collect(), - func_def.in_module.clone(), - ), - ); - } else { - panic!("module {} does not exist", func_def.in_module) - } - } - Self { modules, functions } - } - - pub fn invoke_write_method( - &self, - name: String, - instruction: &Instruction, - state_db: TUnitOfWork, - ) -> Result { - // TODO: We should probably create a new instance each time, so that - // there's no stale memory - if let Some((arg_types, module_name)) = self.functions.get(&name) { - if let Some(instance) = self.modules.get(module_name) { - let func_pointer = instance.exports.get_function(&name).expect("Could not find function"); - let _type_params = func_pointer.ty().params(); - let _remaining_args = Vec::from(instruction.args()); - // dbg!(&remaining_args); - // let memory = instance.get_memory("mem"); - let _offset = 0; - // TODO: better iteration - let mut remaining_instruction_args = Vec::from(instruction.args()); - let args: Vec> = arg_types - .iter() - .enumerate() - .map(|(position, param)| { - match param { - ArgType::String => { - // if remaining_args.len() < 3 { - // return Err(DigitalAssetError::MissingArgument { - // position, - // argument_name: "Wasm string".to_string(), - // }); - // } - // - // let len = remaining_instruction_args.pop().expect("can't take length") as usize; - // let instruction_arg = - // String::from_utf8(remaining_instruction_args.drain(len)).expect("invalid utf8"); - // let ptr = WasmPtr::::new(offset); - // let derefed = ptr.deref(&memory).expect("could not get derefed pointer"); - // derefed.set(instruction_arg); - // - // Ok(vec![Value::I32()]) - todo!() - }, - ArgType::Byte => { - if remaining_instruction_args.is_empty() { - return Err(WasmError::MissingArgument { - position, - argument_name: "Wasm byte".to_string(), - }); - } - let byte = remaining_instruction_args.pop().expect("not enough length"); - Ok(vec![Value::I32(i32::from(byte))]) - }, - ArgType::PublicKey => { - if remaining_instruction_args.len() < 32 { - return Err(WasmError::MissingArgument { - position, - argument_name: "Wasm public key".to_string(), - }); - } - let bytes: Vec = remaining_instruction_args.drain(..32).collect(); - let mut result = Vec::with_capacity(8); - for i in 0..8 { - let mut data = [0u8; 4]; - data.copy_from_slice(&bytes[i * 4..i * 4 + 4]); - result.push(Value::I32(i32::from_le_bytes(data))); - } - // write as 8 * bytes - Ok(result) - }, - // F32, - // F64, - // V128, - // ExternRef, - // FuncRef, - _ => { - todo!() - }, - } - }) - .collect::>()?; - - let args: Vec = args.into_iter().flatten().collect(); - let _result = func_pointer.call(args.as_slice()).expect("invokation error"); - Ok(state_db) - } else { - todo!("No module found") - } - } else { - todo!("function not found") - } - // let store = Store::default(); - // let module = Module::new(&store, wat_file.as_str()); - // let import_object = imports! {}; - // let instance = Instance::new(&module, &import_object)?; - } -} diff --git a/dan_layer/engine/tests/templates/buggy/Cargo.lock b/dan_layer/engine/tests/templates/buggy/Cargo.lock deleted file mode 100644 index 5887120c560..00000000000 --- a/dan_layer/engine/tests/templates/buggy/Cargo.lock +++ /dev/null @@ -1,229 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "ahash" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" -dependencies = [ - "getrandom", - "once_cell", - "version_check", -] - -[[package]] -name = "borsh" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15bf3650200d8bffa99015595e10f1fbd17de07abbc25bb067da79e769939bfa" -dependencies = [ - "borsh-derive", - "hashbrown", -] - -[[package]] -name = "borsh-derive" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6441c552f230375d18e3cc377677914d2ca2b0d36e52129fe15450a2dce46775" -dependencies = [ - "borsh-derive-internal", - "borsh-schema-derive-internal", - "proc-macro-crate", - "proc-macro2", - "syn", -] - -[[package]] -name = "borsh-derive-internal" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5449c28a7b352f2d1e592a8a28bf139bc71afb0764a14f3c02500935d8c44065" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "borsh-schema-derive-internal" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdbd5696d8bfa21d53d9fe39a714a18538bad11492a42d066dbbc395fb1951c0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "buggy" -version = "0.1.0" -dependencies = [ - "tari_template_abi", - "wee_alloc", -] - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "getrandom" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "wasi", -] - -[[package]] -name = "hashbrown" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" -dependencies = [ - "ahash", -] - -[[package]] -name = "libc" -version = "0.2.129" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64de3cc433455c14174d42e554d4027ee631c4d046d43e3ecc6efc4636cdc7a7" - -[[package]] -name = "memory_units" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8452105ba047068f40ff7093dd1d9da90898e63dd61736462e9cdda6a90ad3c3" - -[[package]] -name = "once_cell" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18a6dbe30758c9f83eb00cbea4ac95966305f5a7772f3f42ebfc7fc7eddbd8e1" - -[[package]] -name = "proc-macro-crate" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d6ea3c4595b96363c13943497db34af4460fb474a95c43f4446ad341b8c9785" -dependencies = [ - "toml", -] - -[[package]] -name = "proc-macro2" -version = "1.0.43" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a2ca2c61bc9f3d74d2886294ab7b9853abd9c1ad903a3ac7815c58989bb7bab" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "serde" -version = "1.0.143" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53e8e5d5b70924f74ff5c6d64d9a5acd91422117c60f48c4e07855238a254553" - -[[package]] -name = "syn" -version = "1.0.99" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58dbef6ec655055e20b86b15a8cc6d439cca19b667537ac6a1369572d151ab13" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "tari_template_abi" -version = "0.1.0" -dependencies = [ - "borsh", -] - -[[package]] -name = "toml" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" -dependencies = [ - "serde", -] - -[[package]] -name = "unicode-ident" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4f5b37a154999a8f3f98cc23a628d850e154479cd94decf3414696e12e31aaf" - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" - -[[package]] -name = "wee_alloc" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbb3b5a6b2bb17cb6ad44a2e68a43e8d2722c997da10e928665c72ec6c0a0b8e" -dependencies = [ - "cfg-if 0.1.10", - "libc", - "memory_units", - "winapi", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/dan_layer/engine/tests/templates/buggy/Cargo.toml b/dan_layer/engine/tests/templates/buggy/Cargo.toml deleted file mode 100644 index 839b457debc..00000000000 --- a/dan_layer/engine/tests/templates/buggy/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[workspace] -[package] -name = "buggy" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -tari_template_abi = { path = "../../../../template_abi", default-features = false } -wee_alloc = "0.4.5" - -[profile.release] -opt-level = 's' # Optimize for size. -lto = true # Enable Link Time Optimization. -codegen-units = 1 # Reduce number of codegen units to increase optimizations. -panic = 'abort' # Abort on panic. -strip = "debuginfo" # Strip debug info. - -[lib] -crate-type = ["cdylib", "lib"] - -[features] -call_engine_in_abi = [] -return_null_abi = [] -unexpected_export_function = [] \ No newline at end of file diff --git a/dan_layer/engine/tests/templates/buggy/src/lib.rs b/dan_layer/engine/tests/templates/buggy/src/lib.rs deleted file mode 100644 index 36c4ff9d024..00000000000 --- a/dan_layer/engine/tests/templates/buggy/src/lib.rs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#![allow(non_snake_case)] - -use core::ptr; - -pub use tari_template_abi::{tari_alloc, tari_free}; - -#[global_allocator] -static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; - -#[cfg(any(feature = "call_engine_in_abi", feature = "unexpected_export_function"))] -#[no_mangle] -pub extern "C" fn Buggy_abi() -> *mut u8 { - use tari_template_abi::*; - // Call the engine in the ABI code, you aren't allowed to do that *shakes head* - #[cfg(feature = "call_engine_in_abi")] - unsafe { - tari_engine(123, ptr::null_mut(), 0) - }; - wrap_ptr(encode_with_len(&TemplateDef { - template_name: "".to_string(), - functions: vec![], - })) -} - -#[cfg(feature = "return_null_abi")] -#[no_mangle] -pub extern "C" fn Buggy_abi() -> *mut u8 { - ptr::null_mut() -} - -#[no_mangle] -pub extern "C" fn Buggy_main(_call_info: *mut u8, _call_info_len: usize) -> *mut u8 { - ptr::null_mut() -} - -extern "C" { - pub fn tari_engine(op: i32, input_ptr: *const u8, input_len: usize) -> *mut u8; - pub fn debug(input_ptr: *const u8, input_len: usize); -} - -#[cfg(feature = "unexpected_export_function")] -#[no_mangle] -pub extern "C" fn i_shouldnt_be_here() -> *mut u8 { - ptr::null_mut() -} diff --git a/dan_layer/engine/tests/templates/hello_world/Cargo.lock b/dan_layer/engine/tests/templates/hello_world/Cargo.lock deleted file mode 100644 index e3375cdea0d..00000000000 --- a/dan_layer/engine/tests/templates/hello_world/Cargo.lock +++ /dev/null @@ -1,201 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "ahash" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" -dependencies = [ - "getrandom", - "once_cell", - "version_check", -] - -[[package]] -name = "borsh" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15bf3650200d8bffa99015595e10f1fbd17de07abbc25bb067da79e769939bfa" -dependencies = [ - "borsh-derive", - "hashbrown", -] - -[[package]] -name = "borsh-derive" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6441c552f230375d18e3cc377677914d2ca2b0d36e52129fe15450a2dce46775" -dependencies = [ - "borsh-derive-internal", - "borsh-schema-derive-internal", - "proc-macro-crate", - "proc-macro2", - "syn", -] - -[[package]] -name = "borsh-derive-internal" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5449c28a7b352f2d1e592a8a28bf139bc71afb0764a14f3c02500935d8c44065" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "borsh-schema-derive-internal" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdbd5696d8bfa21d53d9fe39a714a18538bad11492a42d066dbbc395fb1951c0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "getrandom" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - -[[package]] -name = "hashbrown" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" -dependencies = [ - "ahash", -] - -[[package]] -name = "hello_world" -version = "0.1.0" -dependencies = [ - "tari_template_abi", - "tari_template_lib", - "tari_template_macros", -] - -[[package]] -name = "libc" -version = "0.2.126" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836" - -[[package]] -name = "once_cell" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18a6dbe30758c9f83eb00cbea4ac95966305f5a7772f3f42ebfc7fc7eddbd8e1" - -[[package]] -name = "proc-macro-crate" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d6ea3c4595b96363c13943497db34af4460fb474a95c43f4446ad341b8c9785" -dependencies = [ - "toml", -] - -[[package]] -name = "proc-macro2" -version = "1.0.42" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c278e965f1d8cf32d6e0e96de3d3e79712178ae67986d9cf9151f51e95aac89b" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bcdf212e9776fbcb2d23ab029360416bb1706b1aea2d1a5ba002727cbcab804" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "serde" -version = "1.0.140" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc855a42c7967b7c369eb5860f7164ef1f6f81c20c7cc1141f2a604e18723b03" - -[[package]] -name = "syn" -version = "1.0.98" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c50aef8a904de4c23c788f104b7dddc7d6f79c647c7c8ce4cc8f73eb0ca773dd" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "tari_template_abi" -version = "0.1.0" -dependencies = [ - "borsh", -] - -[[package]] -name = "tari_template_lib" -version = "0.1.0" -dependencies = [ - "borsh", - "tari_template_abi", -] - -[[package]] -name = "tari_template_macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "toml" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" -dependencies = [ - "serde", -] - -[[package]] -name = "unicode-ident" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15c61ba63f9235225a22310255a29b806b907c9b8c964bcbd0a2c70f3f2deea7" - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" diff --git a/dan_layer/engine/tests/templates/hello_world/Cargo.toml b/dan_layer/engine/tests/templates/hello_world/Cargo.toml deleted file mode 100644 index 8593782b2bd..00000000000 --- a/dan_layer/engine/tests/templates/hello_world/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[workspace] -[package] -name = "hello_world" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -tari_template_abi = { path = "../../../../template_abi", default-features = false } -tari_template_lib = { path = "../../../../template_lib" } -tari_template_macros = { path = "../../../../template_macros" } - -[profile.release] -opt-level = 's' # Optimize for size. -lto = true # Enable Link Time Optimization. -codegen-units = 1 # Reduce number of codegen units to increase optimizations. -panic = 'abort' # Abort on panic. -strip = "debuginfo" # Strip debug info. - -[lib] -crate-type = ["cdylib", "lib"] \ No newline at end of file diff --git a/dan_layer/engine/tests/templates/hello_world/src/lib.rs b/dan_layer/engine/tests/templates/hello_world/src/lib.rs deleted file mode 100644 index 95d4bc8a11b..00000000000 --- a/dan_layer/engine/tests/templates/hello_world/src/lib.rs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_template_macros::template; - -#[template] -mod hello_world { - struct HelloWorld { - greeting: String, - } - - impl HelloWorld { - pub fn greet() -> String { - "Hello World!".to_string() - } - - pub fn new(greeting: String) -> Self { - Self { greeting } - } - - pub fn custom_greeting(&self, name: String) -> String { - format!("{} {}!", self.greeting, name) - } - } -} diff --git a/dan_layer/engine/tests/templates/state/Cargo.lock b/dan_layer/engine/tests/templates/state/Cargo.lock deleted file mode 100644 index 659d755fe3b..00000000000 --- a/dan_layer/engine/tests/templates/state/Cargo.lock +++ /dev/null @@ -1,201 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "ahash" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" -dependencies = [ - "getrandom", - "once_cell", - "version_check", -] - -[[package]] -name = "borsh" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15bf3650200d8bffa99015595e10f1fbd17de07abbc25bb067da79e769939bfa" -dependencies = [ - "borsh-derive", - "hashbrown", -] - -[[package]] -name = "borsh-derive" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6441c552f230375d18e3cc377677914d2ca2b0d36e52129fe15450a2dce46775" -dependencies = [ - "borsh-derive-internal", - "borsh-schema-derive-internal", - "proc-macro-crate", - "proc-macro2", - "syn", -] - -[[package]] -name = "borsh-derive-internal" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5449c28a7b352f2d1e592a8a28bf139bc71afb0764a14f3c02500935d8c44065" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "borsh-schema-derive-internal" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdbd5696d8bfa21d53d9fe39a714a18538bad11492a42d066dbbc395fb1951c0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "getrandom" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - -[[package]] -name = "hashbrown" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" -dependencies = [ - "ahash", -] - -[[package]] -name = "libc" -version = "0.2.126" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836" - -[[package]] -name = "once_cell" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18a6dbe30758c9f83eb00cbea4ac95966305f5a7772f3f42ebfc7fc7eddbd8e1" - -[[package]] -name = "proc-macro-crate" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d6ea3c4595b96363c13943497db34af4460fb474a95c43f4446ad341b8c9785" -dependencies = [ - "toml", -] - -[[package]] -name = "proc-macro2" -version = "1.0.43" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a2ca2c61bc9f3d74d2886294ab7b9853abd9c1ad903a3ac7815c58989bb7bab" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bcdf212e9776fbcb2d23ab029360416bb1706b1aea2d1a5ba002727cbcab804" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "serde" -version = "1.0.140" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc855a42c7967b7c369eb5860f7164ef1f6f81c20c7cc1141f2a604e18723b03" - -[[package]] -name = "state" -version = "0.1.0" -dependencies = [ - "tari_template_abi", - "tari_template_lib", - "tari_template_macros", -] - -[[package]] -name = "syn" -version = "1.0.98" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c50aef8a904de4c23c788f104b7dddc7d6f79c647c7c8ce4cc8f73eb0ca773dd" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "tari_template_abi" -version = "0.1.0" -dependencies = [ - "borsh", -] - -[[package]] -name = "tari_template_lib" -version = "0.1.0" -dependencies = [ - "borsh", - "tari_template_abi", -] - -[[package]] -name = "tari_template_macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "toml" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" -dependencies = [ - "serde", -] - -[[package]] -name = "unicode-ident" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15c61ba63f9235225a22310255a29b806b907c9b8c964bcbd0a2c70f3f2deea7" - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" diff --git a/dan_layer/engine/tests/templates/state/Cargo.toml b/dan_layer/engine/tests/templates/state/Cargo.toml deleted file mode 100644 index f293ba6add1..00000000000 --- a/dan_layer/engine/tests/templates/state/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[workspace] -[package] -name = "state" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -tari_template_abi = { path = "../../../../template_abi" } -tari_template_lib = { path = "../../../../template_lib" } -tari_template_macros = { path = "../../../../template_macros" } - -[profile.release] -opt-level = 's' # Optimize for size. -lto = true # Enable Link Time Optimization. -codegen-units = 1 # Reduce number of codegen units to increase optimizations. -panic = 'abort' # Abort on panic. -strip = "debuginfo" # Strip debug info. - -[lib] -crate-type = ["cdylib", "lib"] \ No newline at end of file diff --git a/dan_layer/engine/tests/templates/state/src/lib.rs b/dan_layer/engine/tests/templates/state/src/lib.rs deleted file mode 100644 index de90eee6f4d..00000000000 --- a/dan_layer/engine/tests/templates/state/src/lib.rs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_template_macros::template; - -#[template] -mod state_template { - pub struct State { - pub value: u32, - } - - impl State { - pub fn new() -> Self { - Self { value: 0 } - } - - pub fn set(&mut self, value: u32) { - debug(format!("Changing value from {} to {}", self.value, value)); - self.value = value; - } - - pub fn get(&self) -> u32 { - self.value - } - } -} diff --git a/dan_layer/engine/tests/test.rs b/dan_layer/engine/tests/test.rs deleted file mode 100644 index 637cb7dfdc5..00000000000 --- a/dan_layer/engine/tests/test.rs +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -mod tooling; - -use tari_dan_engine::{ - packager::{Package, PackageError}, - state_store::{AtomicDb, StateReader}, - wasm::{compile::compile_template, WasmExecutionError}, -}; -use tari_template_lib::{ - args, - models::{ComponentId, ComponentInstance}, -}; -use tooling::TemplateTest; - -#[test] -fn test_hello_world() { - let template_test = TemplateTest::new(vec!["tests/templates/hello_world"]); - let result: String = template_test.call_function("HelloWorld", "greet", args![]); - - assert_eq!(result, "Hello World!"); -} - -#[test] -fn test_state() { - let template_test = TemplateTest::new(vec!["tests/templates/state"]); - let store = template_test.state_store(); - - // constructor - let component_id1: ComponentId = template_test.call_function("State", "new", args![]); - template_test.assert_calls(&["emit_log", "create_component"]); - template_test.clear_calls(); - - let component_id2: ComponentId = template_test.call_function("State", "new", args![]); - assert_ne!(component_id1, component_id2); - - let component: ComponentInstance = store - .read_access() - .unwrap() - .get_state(&component_id1) - .unwrap() - .expect("component1 not found"); - assert_eq!(component.module_name, "State"); - let component: ComponentInstance = store - .read_access() - .unwrap() - .get_state(&component_id2) - .unwrap() - .expect("component2 not found"); - assert_eq!(component.module_name, "State"); - - // call the "set" method to update the instance value - let new_value = 20_u32; - template_test.call_method::<()>(component_id2, "set", args![new_value]); - - // call the "get" method to get the current value - let value: u32 = template_test.call_method(component_id2, "get", args![]); - - assert_eq!(value, new_value); -} - -#[test] -fn test_composed() { - let template_test = TemplateTest::new(vec!["tests/templates/state", "tests/templates/hello_world"]); - - let functions = template_test - .get_module("HelloWorld") - .template_def() - .functions - .iter() - .map(|f| f.name.as_str()) - .collect::>(); - assert_eq!(functions, vec!["greet", "new", "custom_greeting"]); - - let functions = template_test - .get_module("State") - .template_def() - .functions - .iter() - .map(|f| f.name.as_str()) - .collect::>(); - assert_eq!(functions, vec!["new", "set", "get"]); - - let component_state: ComponentId = template_test.call_function("State", "new", args![]); - let component_hw: ComponentId = template_test.call_function("HelloWorld", "new", args!["أهلا"]); - - let result: String = template_test.call_method(component_hw, "custom_greeting", args!["Wasm"]); - assert_eq!(result, "أهلا Wasm!"); - - // call the "set" method to update the instance value - let new_value = 20_u32; - template_test.call_method::<()>(component_state, "set", args![new_value]); - - // call the "get" method to get the current value - let value: u32 = template_test.call_method(component_state, "get", args![]); - - assert_eq!(value, new_value); -} - -#[test] -fn test_dodgy_template() { - let wasm = compile_template("tests/templates/buggy", &["call_engine_in_abi"]).unwrap(); - let err = Package::builder().add_wasm_module(wasm).build().unwrap_err(); - assert!(matches!(err, PackageError::TemplateCalledEngineDuringInitialization)); - - let wasm = compile_template("tests/templates/buggy", &["return_null_abi"]).unwrap(); - let err = Package::builder().add_wasm_module(wasm).build().unwrap_err(); - assert!(matches!( - err, - PackageError::WasmModuleError(WasmExecutionError::AbiDecodeError) - )); - - let wasm = compile_template("tests/templates/buggy", &["unexpected_export_function"]).unwrap(); - let err = Package::builder().add_wasm_module(wasm).build().unwrap_err(); - assert!(matches!( - err, - PackageError::WasmModuleError(WasmExecutionError::UnexpectedAbiFunction { .. }) - )); -} diff --git a/dan_layer/engine/tests/tooling/mock_runtime_interface.rs b/dan_layer/engine/tests/tooling/mock_runtime_interface.rs deleted file mode 100644 index 04afb47e183..00000000000 --- a/dan_layer/engine/tests/tooling/mock_runtime_interface.rs +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::sync::{atomic::AtomicU32, Arc, RwLock}; - -use digest::Digest; -use tari_dan_engine::{ - crypto, - runtime::{RuntimeError, RuntimeInterface}, - state_store::{memory::MemoryStateStore, AtomicDb, StateReader, StateWriter}, -}; -use tari_template_lib::{ - args::LogLevel, - models::{Component, ComponentId, ComponentInstance}, -}; - -#[derive(Debug, Clone, Default)] -pub struct MockRuntimeInterface { - ids: Arc, - state: MemoryStateStore, - calls: Arc>>, -} - -impl MockRuntimeInterface { - pub fn new() -> Self { - Self { - ids: Arc::new(AtomicU32::new(0)), - state: MemoryStateStore::default(), - calls: Arc::new(RwLock::new(vec![])), - } - } - - pub fn state_store(&self) -> MemoryStateStore { - self.state.clone() - } - - pub fn next_id(&self) -> u32 { - self.ids.fetch_add(1, std::sync::atomic::Ordering::Relaxed) - } - - pub fn get_calls(&self) -> Vec<&'static str> { - self.calls.read().unwrap().clone() - } - - pub fn clear_calls(&self) { - self.calls.write().unwrap().clear(); - } - - fn add_call(&self, call: &'static str) { - self.calls.write().unwrap().push(call); - } -} - -impl RuntimeInterface for MockRuntimeInterface { - fn emit_log(&self, level: LogLevel, message: &str) { - self.add_call("emit_log"); - let level = match level { - LogLevel::Error => log::Level::Error, - LogLevel::Warn => log::Level::Warn, - LogLevel::Info => log::Level::Info, - LogLevel::Debug => log::Level::Debug, - }; - eprintln!("[{:?}] {}", level, message); - log::log!(target: "tari::dan::engine::runtime", level, "{}", message); - } - - fn create_component(&self, new_component: Component) -> Result { - self.add_call("create_component"); - let component_id: [u8; 32] = crypto::hasher("component") - .chain(self.next_id().to_le_bytes()) - .finalize() - .into(); - - let component = ComponentInstance::new(component_id.into(), new_component); - let mut tx = self.state.write_access().map_err(RuntimeError::StateDbError)?; - tx.set_state(&component_id, component)?; - self.state.commit(tx).map_err(RuntimeError::StateDbError)?; - - Ok(component_id.into()) - } - - fn get_component(&self, component_id: &ComponentId) -> Result { - self.add_call("get_component"); - let component = self - .state - .read_access() - .map_err(RuntimeError::StateDbError)? - .get_state(component_id)? - .ok_or(RuntimeError::ComponentNotFound { id: *component_id })?; - Ok(component) - } - - fn set_component_state(&self, component_id: &ComponentId, state: Vec) -> Result<(), RuntimeError> { - self.add_call("set_component_state"); - let mut tx = self.state.write_access().map_err(RuntimeError::StateDbError)?; - let mut component: ComponentInstance = tx - .get_state(component_id)? - .ok_or(RuntimeError::ComponentNotFound { id: *component_id })?; - component.state = state; - tx.set_state(&component_id, component)?; - self.state.commit(tx).map_err(RuntimeError::StateDbError)?; - - Ok(()) - } -} diff --git a/dan_layer/engine/tests/tooling/mod.rs b/dan_layer/engine/tests/tooling/mod.rs deleted file mode 100644 index 6a6873c86ba..00000000000 --- a/dan_layer/engine/tests/tooling/mod.rs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -mod mock_runtime_interface; -pub use mock_runtime_interface::*; - -mod template_test; -pub use template_test::TemplateTest; diff --git a/dan_layer/engine/tests/tooling/template_test.rs b/dan_layer/engine/tests/tooling/template_test.rs deleted file mode 100644 index 9ed755af241..00000000000 --- a/dan_layer/engine/tests/tooling/template_test.rs +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::path::Path; - -use borsh::BorshDeserialize; -use tari_crypto::ristretto::RistrettoSecretKey; -use tari_dan_engine::{ - crypto::create_key_pair, - instruction::{Instruction, InstructionBuilder, InstructionProcessor}, - packager::Package, - state_store::memory::MemoryStateStore, - wasm::{compile::compile_template, LoadedWasmModule}, -}; -use tari_template_lib::models::ComponentId; - -use super::MockRuntimeInterface; - -pub struct TemplateTest { - package: Package, - processor: InstructionProcessor, - secret_key: RistrettoSecretKey, - runtime_interface: MockRuntimeInterface, -} - -impl TemplateTest { - pub fn new>(template_paths: Vec

) -> Self { - let runtime_interface = MockRuntimeInterface::new(); - let (secret_key, _pk) = create_key_pair(); - - let wasms = template_paths - .into_iter() - .map(|path| compile_template(path, &[]).unwrap()); - let mut builder = Package::builder(); - for wasm in wasms { - builder.add_wasm_module(wasm); - } - let package = builder.build().unwrap(); - let processor = InstructionProcessor::new(runtime_interface.clone(), package.clone()); - - Self { - package, - processor, - secret_key, - runtime_interface, - } - } - - pub fn state_store(&self) -> MemoryStateStore { - self.runtime_interface.state_store() - } - - pub fn assert_calls(&self, expected: &[&'static str]) { - let calls = self.runtime_interface.get_calls(); - assert_eq!(calls, expected); - } - - pub fn clear_calls(&self) { - self.runtime_interface.clear_calls(); - } - - pub fn get_module(&self, module_name: &str) -> &LoadedWasmModule { - self.package.get_module_by_name(module_name).unwrap() - } - - pub fn call_function(&self, template_name: &str, func_name: &str, args: Vec>) -> T - where T: BorshDeserialize { - let instruction = InstructionBuilder::new() - .add_instruction(Instruction::CallFunction { - package_id: self.package.id(), - template: template_name.to_owned(), - function: func_name.to_owned(), - args, - }) - .sign(&self.secret_key) - .build(); - let result = self.processor.execute(instruction).unwrap(); - - result[0].decode::().unwrap() - } - - pub fn call_method(&self, component_id: ComponentId, method_name: &str, args: Vec>) -> T - where T: BorshDeserialize { - let instruction = InstructionBuilder::new() - .add_instruction(Instruction::CallMethod { - package_id: self.package.id(), - component_id, - method: method_name.to_owned(), - args, - }) - .sign(&self.secret_key) - .build(); - let result = self.processor.execute(instruction).unwrap(); - - result[0].decode::().unwrap() - } -} diff --git a/dan_layer/storage_lmdb/Cargo.toml b/dan_layer/storage_lmdb/Cargo.toml deleted file mode 100644 index 374c75b39f8..00000000000 --- a/dan_layer/storage_lmdb/Cargo.toml +++ /dev/null @@ -1,17 +0,0 @@ -[package] -name = "tari_dan_storage_lmdb" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -tari_dan_engine = { path = "../engine" } -tari_storage = { path = "../../infrastructure/storage" } - -borsh = "0.9.3" -lmdb-zero = "0.4.4" - - -[dev-dependencies] -tempfile = "3.3.0" \ No newline at end of file diff --git a/dan_layer/storage_lmdb/src/engine_state_store.rs b/dan_layer/storage_lmdb/src/engine_state_store.rs deleted file mode 100644 index 365c17008ec..00000000000 --- a/dan_layer/storage_lmdb/src/engine_state_store.rs +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ops::Deref, path::Path, sync::Arc}; - -use lmdb_zero::{db, put, ConstTransaction, LmdbResultExt, ReadTransaction, WriteTransaction}; -use tari_dan_engine::state_store::{AtomicDb, StateReader, StateStoreError, StateWriter}; -use tari_storage::lmdb_store::{DatabaseRef, LMDBBuilder}; - -pub struct LmdbTransaction { - db: DatabaseRef, - tx: T, -} - -pub struct LmdbStateStore { - pub env: Arc, - pub db: DatabaseRef, -} - -impl LmdbStateStore { - pub fn new>(path: P) -> Self { - let flags = db::CREATE; - std::fs::create_dir_all(&path).unwrap(); - - let store = LMDBBuilder::new() - .set_path(path) - // .set_env_config(config) - .set_max_number_of_databases(1) - .add_database("test_db", flags ) - .build().unwrap(); - - let handle = store.get_handle("test_db").unwrap(); - let db = handle.db(); - Self { env: store.env(), db } - } -} - -impl<'a> AtomicDb<'a> for LmdbStateStore { - type Error = lmdb_zero::Error; - type ReadAccess = LmdbTransaction>; - type WriteAccess = LmdbTransaction>; - - fn read_access(&'a self) -> Result { - let tx = ReadTransaction::new(self.env.clone())?; - - Ok(LmdbTransaction { - db: self.db.clone(), - tx, - }) - } - - fn write_access(&'a self) -> Result { - let tx = WriteTransaction::new(self.env.clone())?; - - Ok(LmdbTransaction { - db: self.db.clone(), - tx, - }) - } - - fn commit(&self, tx: Self::WriteAccess) -> Result<(), Self::Error> { - tx.tx.commit() - } -} - -impl<'a, T: Deref>> StateReader for LmdbTransaction { - fn get_state_raw(&self, key: &[u8]) -> Result>, StateStoreError> { - let access = self.tx.access(); - access - .get::<_, [u8]>(&*self.db, key) - .map(|data| data.to_vec()) - .to_opt() - .map_err(StateStoreError::custom) - } - - fn exists(&self, key: &[u8]) -> Result { - Ok(self.get_state_raw(key)?.is_some()) - } -} - -impl<'a> StateWriter for LmdbTransaction> { - fn set_state_raw(&mut self, key: &[u8], value: Vec) -> Result<(), StateStoreError> { - let mut access = self.tx.access(); - access - .put(&*self.db, key, &value, put::Flags::empty()) - .map_err(StateStoreError::custom) - } -} - -#[cfg(test)] -mod tests { - - use borsh::{BorshDeserialize, BorshSerialize}; - use tempfile::tempdir; - - use super::*; - - #[derive(Debug, BorshSerialize, BorshDeserialize, PartialEq, Eq, Clone)] - struct UserData { - name: String, - age: u8, - } - - #[test] - fn read_write_rollback_commit() { - let user_data = UserData { - name: "Foo".to_string(), - age: 99, - }; - - let path = tempdir().unwrap(); - let store = LmdbStateStore::new(&path); - { - let mut access = store.write_access().unwrap(); - access.set_state(b"abc", user_data.clone()).unwrap(); - assert!(access.exists(b"abc").unwrap()); - let res = access.get_state(b"abc").unwrap(); - assert_eq!(res, Some(user_data.clone())); - let res = access.get_state::<_, UserData>(b"def").unwrap(); - assert_eq!(res, None); - // Drop without commit rolls back - } - - { - let access = store.read_access().unwrap(); - let res = access.get_state::<_, UserData>(b"abc").unwrap(); - assert_eq!(res, None); - assert!(!access.exists(b"abc").unwrap()); - } - - { - let mut access = store.write_access().unwrap(); - access.set_state(b"abc", user_data.clone()).unwrap(); - store.commit(access).unwrap(); - } - - let access = store.read_access().unwrap(); - let res = access.get_state(b"abc").unwrap(); - assert_eq!(res, Some(user_data)); - } -} diff --git a/dan_layer/storage_lmdb/src/lib.rs b/dan_layer/storage_lmdb/src/lib.rs deleted file mode 100644 index 25fc6bb7820..00000000000 --- a/dan_layer/storage_lmdb/src/lib.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub mod engine_state_store; diff --git a/dan_layer/storage_sqlite/Cargo.toml b/dan_layer/storage_sqlite/Cargo.toml deleted file mode 100644 index cc0034c3c2c..00000000000 --- a/dan_layer/storage_sqlite/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "tari_dan_storage_sqlite" -version = "0.1.0" -edition = "2018" -license = "BSD-3-Clause" - -[dependencies] -tari_dan_core = { path = "../core" } -tari_common = { path = "../../common" } -tari_common_types = { path = "../../base_layer/common_types" } -tari_utilities = { git = "https://github.com/tari-project/tari_utilities.git", tag = "v0.4.5" } -tari_dan_engine = { path = "../engine" } - -borsh = "0.9.3" -diesel = { version = "1.4.8", default-features = false, features = ["sqlite"] } -diesel_migrations = "1.4.0" -thiserror = "1.0.30" -async-trait = "0.1.50" -tokio = { version = "1.10", features = ["macros", "time"] } -tokio-stream = { version = "0.1.7", features = ["sync"] } -log = { version = "0.4.8", features = ["std"] } diff --git a/dan_layer/storage_sqlite/README.md b/dan_layer/storage_sqlite/README.md deleted file mode 100644 index 06c3d5f598f..00000000000 --- a/dan_layer/storage_sqlite/README.md +++ /dev/null @@ -1,12 +0,0 @@ -To run migrations: - -``` -diesel migration run --database-url temp.sqlite --config-file .\diesel.toml -``` - -To run global migrations -To run migrations: - -``` -diesel migration run --database-url temp-glob.sqlite --config-file .\diesel-global.toml --migration-dir ./global_db_migrations -``` diff --git a/dan_layer/storage_sqlite/diesel-global.toml b/dan_layer/storage_sqlite/diesel-global.toml deleted file mode 100644 index 26f6ef30b6c..00000000000 --- a/dan_layer/storage_sqlite/diesel-global.toml +++ /dev/null @@ -1,5 +0,0 @@ -# For documentation on how to configure this file, -# see diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/global/schema.rs" diff --git a/dan_layer/storage_sqlite/diesel.toml b/dan_layer/storage_sqlite/diesel.toml deleted file mode 100644 index 92267c829f2..00000000000 --- a/dan_layer/storage_sqlite/diesel.toml +++ /dev/null @@ -1,5 +0,0 @@ -# For documentation on how to configure this file, -# see diesel.rs/guides/configuring-diesel-cli - -[print_schema] -file = "src/schema.rs" diff --git a/dan_layer/storage_sqlite/global_db_migrations/2022-06-20-091532_create_metadata/down.sql b/dan_layer/storage_sqlite/global_db_migrations/2022-06-20-091532_create_metadata/down.sql deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/dan_layer/storage_sqlite/global_db_migrations/2022-06-20-091532_create_metadata/up.sql b/dan_layer/storage_sqlite/global_db_migrations/2022-06-20-091532_create_metadata/up.sql deleted file mode 100644 index e63e22eb321..00000000000 --- a/dan_layer/storage_sqlite/global_db_migrations/2022-06-20-091532_create_metadata/up.sql +++ /dev/null @@ -1,26 +0,0 @@ --- // Copyright 2021. The Tari Project --- // --- // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the --- // following conditions are met: --- // --- // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following --- // disclaimer. --- // --- // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the --- // following disclaimer in the documentation and/or other materials provided with the distribution. --- // --- // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote --- // products derived from this software without specific prior written permission. --- // --- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, --- // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --- // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR --- // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, --- // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE --- // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -create table metadata ( - key_name blob primary key not null, - value blob not null -) diff --git a/dan_layer/storage_sqlite/global_db_migrations/2022-06-28-120617_create_contracts/down.sql b/dan_layer/storage_sqlite/global_db_migrations/2022-06-28-120617_create_contracts/down.sql deleted file mode 100644 index 2c804585e01..00000000000 --- a/dan_layer/storage_sqlite/global_db_migrations/2022-06-28-120617_create_contracts/down.sql +++ /dev/null @@ -1,21 +0,0 @@ --- // Copyright 2022. The Tari Project --- // --- // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the --- // following conditions are met: --- // --- // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following --- // disclaimer. --- // --- // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the --- // following disclaimer in the documentation and/or other materials provided with the distribution. --- // --- // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote --- // products derived from this software without specific prior written permission. --- // --- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, --- // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --- // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR --- // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, --- // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE --- // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/dan_layer/storage_sqlite/global_db_migrations/2022-06-28-120617_create_contracts/up.sql b/dan_layer/storage_sqlite/global_db_migrations/2022-06-28-120617_create_contracts/up.sql deleted file mode 100644 index fe89c52ee1c..00000000000 --- a/dan_layer/storage_sqlite/global_db_migrations/2022-06-28-120617_create_contracts/up.sql +++ /dev/null @@ -1,32 +0,0 @@ --- // Copyright 2022. The Tari Project --- // --- // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the --- // following conditions are met: --- // --- // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following --- // disclaimer. --- // --- // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the --- // following disclaimer in the documentation and/or other materials provided with the distribution. --- // --- // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote --- // products derived from this software without specific prior written permission. --- // --- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, --- // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --- // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR --- // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, --- // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE --- // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -create table contracts ( - id Integer primary key autoincrement not null, - contract_id blob not null, - height bigint not null, - state integer not null, - constitution blob not null -); - -create index contracts_contract_id_index on contracts (contract_id); -create index contracts_state_index on contracts (state); diff --git a/dan_layer/storage_sqlite/migrations/.gitkeep b/dan_layer/storage_sqlite/migrations/.gitkeep deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/dan_layer/storage_sqlite/migrations/2021-11-02-185150_create_nodes/down.sql b/dan_layer/storage_sqlite/migrations/2021-11-02-185150_create_nodes/down.sql deleted file mode 100644 index 291a97c5ce1..00000000000 --- a/dan_layer/storage_sqlite/migrations/2021-11-02-185150_create_nodes/down.sql +++ /dev/null @@ -1 +0,0 @@ --- This file should undo anything in `up.sql` \ No newline at end of file diff --git a/dan_layer/storage_sqlite/migrations/2021-11-02-185150_create_nodes/up.sql b/dan_layer/storage_sqlite/migrations/2021-11-02-185150_create_nodes/up.sql deleted file mode 100644 index 93eeb6ed58c..00000000000 --- a/dan_layer/storage_sqlite/migrations/2021-11-02-185150_create_nodes/up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- Your SQL goes here -create table nodes ( - id integer primary key autoincrement not null, - hash blob not null unique, - parent blob not null, - height integer not null, - is_committed boolean not null DEFAULT FALSE -); - -create table instructions ( - id integer primary key autoincrement not null, - hash blob not null, - node_id integer not null , - template_id int not null, - method text not null, - args blob not null, - sender blob not null, - foreign key (node_id) references nodes(id) -); - - -create table locked_qc ( - id integer primary key not null, -- should always be 1 row - message_type integer not null, - view_number bigint not null, - node_hash blob not null, - signature blob null -); - -create table prepare_qc ( - id integer primary key not null, - message_type integer not null, - view_number bigint not null, - node_hash blob not null, - signature blob null -); diff --git a/dan_layer/storage_sqlite/migrations/2021-11-18-121212_create_state/down.sql b/dan_layer/storage_sqlite/migrations/2021-11-18-121212_create_state/down.sql deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/dan_layer/storage_sqlite/migrations/2021-11-18-121212_create_state/up.sql b/dan_layer/storage_sqlite/migrations/2021-11-18-121212_create_state/up.sql deleted file mode 100644 index f653327f6c6..00000000000 --- a/dan_layer/storage_sqlite/migrations/2021-11-18-121212_create_state/up.sql +++ /dev/null @@ -1,28 +0,0 @@ --- // Copyright 2021. The Tari Project --- // --- // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the --- // following conditions are met: --- // --- // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following --- // disclaimer. --- // --- // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the --- // following disclaimer in the documentation and/or other materials provided with the distribution. --- // --- // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote --- // products derived from this software without specific prior written permission. --- // --- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, --- // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --- // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR --- // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, --- // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE --- // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -create table state_keys ( - schema_name text not null, - key_name blob not null, - value blob not null, - primary key (schema_name, key_name) -) \ No newline at end of file diff --git a/dan_layer/storage_sqlite/migrations/2021-12-21-121212_create_state_tree/down.sql b/dan_layer/storage_sqlite/migrations/2021-12-21-121212_create_state_tree/down.sql deleted file mode 100644 index eaccf650e34..00000000000 --- a/dan_layer/storage_sqlite/migrations/2021-12-21-121212_create_state_tree/down.sql +++ /dev/null @@ -1,23 +0,0 @@ --- // Copyright 2021. The Tari Project --- // --- // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the --- // following conditions are met: --- // --- // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following --- // disclaimer. --- // --- // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the --- // following disclaimer in the documentation and/or other materials provided with the distribution. --- // --- // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote --- // products derived from this software without specific prior written permission. --- // --- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, --- // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --- // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR --- // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, --- // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE --- // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - --- no going back diff --git a/dan_layer/storage_sqlite/migrations/2021-12-21-121212_create_state_tree/up.sql b/dan_layer/storage_sqlite/migrations/2021-12-21-121212_create_state_tree/up.sql deleted file mode 100644 index ade982b56e2..00000000000 --- a/dan_layer/storage_sqlite/migrations/2021-12-21-121212_create_state_tree/up.sql +++ /dev/null @@ -1,29 +0,0 @@ --- // Copyright 2021. The Tari Project --- // --- // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the --- // following conditions are met: --- // --- // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following --- // disclaimer. --- // --- // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the --- // following disclaimer in the documentation and/or other materials provided with the distribution. --- // --- // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote --- // products derived from this software without specific prior written permission. --- // --- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, --- // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --- // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR --- // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, --- // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE --- // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -create table state_tree ( - id integer primary key autoincrement not null, - version integer not null, - is_current boolean not null, - data blob not null -) \ No newline at end of file diff --git a/dan_layer/storage_sqlite/migrations/2022-02-09-105823_create_state_op_log/down.sql b/dan_layer/storage_sqlite/migrations/2022-02-09-105823_create_state_op_log/down.sql deleted file mode 100644 index 291a97c5ce1..00000000000 --- a/dan_layer/storage_sqlite/migrations/2022-02-09-105823_create_state_op_log/down.sql +++ /dev/null @@ -1 +0,0 @@ --- This file should undo anything in `up.sql` \ No newline at end of file diff --git a/dan_layer/storage_sqlite/migrations/2022-02-09-105823_create_state_op_log/up.sql b/dan_layer/storage_sqlite/migrations/2022-02-09-105823_create_state_op_log/up.sql deleted file mode 100644 index e15f19bb7f0..00000000000 --- a/dan_layer/storage_sqlite/migrations/2022-02-09-105823_create_state_op_log/up.sql +++ /dev/null @@ -1,13 +0,0 @@ -create table state_op_log -( - id integer primary key autoincrement not null, - height bigint not null, - merkle_root blob(32) null, - operation varchar(30) not null, - schema varchar(255) not null, - key blob not null, - value blob null -); - -create index state_op_log_height_index on state_op_log (height); -create index state_op_log_merkle_root_index on state_op_log (merkle_root); diff --git a/dan_layer/storage_sqlite/migrations/2022-07-05-131723_create_metadata/down.sql b/dan_layer/storage_sqlite/migrations/2022-07-05-131723_create_metadata/down.sql deleted file mode 100644 index dfc0d8e01b3..00000000000 --- a/dan_layer/storage_sqlite/migrations/2022-07-05-131723_create_metadata/down.sql +++ /dev/null @@ -1 +0,0 @@ -drop table metadata; \ No newline at end of file diff --git a/dan_layer/storage_sqlite/migrations/2022-07-05-131723_create_metadata/up.sql b/dan_layer/storage_sqlite/migrations/2022-07-05-131723_create_metadata/up.sql deleted file mode 100644 index c94fb1cd2b3..00000000000 --- a/dan_layer/storage_sqlite/migrations/2022-07-05-131723_create_metadata/up.sql +++ /dev/null @@ -1,5 +0,0 @@ -create table metadata -( - key blob primary key not null, - value blob not null -) diff --git a/dan_layer/storage_sqlite/src/engine_state_store.rs b/dan_layer/storage_sqlite/src/engine_state_store.rs deleted file mode 100644 index 7477aa403e9..00000000000 --- a/dan_layer/storage_sqlite/src/engine_state_store.rs +++ /dev/null @@ -1,220 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use diesel::{connection::TransactionManager, Connection, OptionalExtension, QueryDsl, RunQueryDsl, SqliteConnection}; -use tari_dan_engine::state_store::{AtomicDb, StateReader, StateStoreError, StateWriter}; - -use crate::{diesel::ExpressionMethods, error::SqliteStorageError, schema::metadata}; -pub struct SqliteStateStore { - conn: SqliteConnection, -} - -impl SqliteStateStore { - pub fn try_connect(url: &str) -> Result { - let conn = SqliteConnection::establish(url)?; - conn.execute("PRAGMA foreign_keys = ON;") - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "set pragma".to_string(), - })?; - Ok(Self { conn }) - } - - pub fn migrate(&self) -> Result<(), SqliteStorageError> { - embed_migrations!("./migrations"); - embedded_migrations::run(&self.conn)?; - Ok(()) - } - - fn access(&self) -> Result, SqliteStorageError> { - let manager = self.conn.transaction_manager(); - manager - .begin_transaction(&self.conn) - .map_err(|err| SqliteStorageError::DieselError { - source: err, - operation: "begin transaction".to_string(), - })?; - Ok(SqliteTransaction::new(&self.conn)) - } -} - -impl<'a> AtomicDb<'a> for SqliteStateStore { - type Error = SqliteStorageError; - type ReadAccess = SqliteTransaction<'a>; - type WriteAccess = SqliteTransaction<'a>; - - fn read_access(&'a self) -> Result { - self.access() - } - - fn write_access(&'a self) -> Result { - self.access() - } - - fn commit(&self, tx: Self::WriteAccess) -> Result<(), Self::Error> { - self.conn - .transaction_manager() - .commit_transaction(tx.conn) - .map_err(|err| SqliteStorageError::DieselError { - source: err, - operation: "commit transaction".to_string(), - })?; - - Ok(()) - } -} - -pub struct SqliteTransaction<'a> { - conn: &'a SqliteConnection, -} - -impl<'a> SqliteTransaction<'a> { - fn new(conn: &'a SqliteConnection) -> Self { - Self { conn } - } -} - -impl<'a> StateReader for SqliteTransaction<'a> { - fn get_state_raw(&self, key: &[u8]) -> Result>, StateStoreError> { - use crate::schema::metadata::dsl; - let val = dsl::metadata - .select(metadata::value) - .filter(metadata::key.eq(key)) - .first::>(self.conn) - .optional() - .map_err(|source| { - StateStoreError::custom(SqliteStorageError::DieselError { - source, - operation: "get state".to_string(), - }) - })?; - - Ok(val) - } - - fn exists(&self, key: &[u8]) -> Result { - use crate::schema::metadata::dsl; - let val = dsl::metadata - .count() - .filter(metadata::key.eq(key)) - .limit(1) - .first::(self.conn) - .map_err(|source| { - StateStoreError::custom(SqliteStorageError::DieselError { - source, - operation: "get state".to_string(), - }) - })?; - - Ok(val > 0) - } -} - -impl<'a> StateWriter for SqliteTransaction<'a> { - fn set_state_raw(&mut self, key: &[u8], value: Vec) -> Result<(), StateStoreError> { - use crate::schema::metadata::dsl; - - // TODO: Check key exists without getting the data - match self.get_state_raw(key) { - Ok(Some(_)) => diesel::update(dsl::metadata.filter(metadata::key.eq(key))) - .set(metadata::value.eq(value)) - .execute(self.conn) - .map_err(|source| { - StateStoreError::custom(SqliteStorageError::DieselError { - source, - operation: "update::metadata".to_string(), - }) - })?, - Ok(None) => diesel::insert_into(metadata::table) - .values((metadata::key.eq(key), metadata::value.eq(value))) - .execute(self.conn) - .map_err(|source| { - StateStoreError::custom(SqliteStorageError::DieselError { - source, - operation: "insert::metadata".to_string(), - }) - })?, - Err(e) => return Err(e), - }; - - Ok(()) - } -} - -impl Drop for SqliteTransaction<'_> { - fn drop(&mut self) { - if let Err(err) = self.conn.transaction_manager().rollback_transaction(self.conn) { - log::error!("Error rolling back transaction: {:?}", err); - } - } -} - -#[cfg(test)] -mod tests { - use borsh::{BorshDeserialize, BorshSerialize}; - - use super::*; - - #[test] - fn read_write_rollback_commit() { - #[derive(Debug, BorshSerialize, BorshDeserialize, PartialEq, Eq, Clone)] - struct UserData { - name: String, - age: u8, - } - - let user_data = UserData { - name: "Foo".to_string(), - age: 99, - }; - - let store = SqliteStateStore::try_connect(":memory:").unwrap(); - store.migrate().unwrap(); - { - let mut access = store.write_access().unwrap(); - access.set_state(b"abc", user_data.clone()).unwrap(); - let res = access.get_state(b"abc").unwrap(); - assert_eq!(res, Some(user_data.clone())); - assert!(access.exists(b"abc").unwrap()); - let res = access.get_state::<_, UserData>(b"def").unwrap(); - assert_eq!(res, None); - // Drop without commit rolls back - } - - { - let access = store.read_access().unwrap(); - let res = access.get_state::<_, UserData>(b"abc").unwrap(); - assert_eq!(res, None); - assert!(!access.exists(b"abc").unwrap()); - } - - { - let mut access = store.write_access().unwrap(); - access.set_state(b"abc", user_data.clone()).unwrap(); - store.commit(access).unwrap(); - } - - let access = store.read_access().unwrap(); - let res = access.get_state(b"abc").unwrap(); - assert_eq!(res, Some(user_data)); - } -} diff --git a/dan_layer/storage_sqlite/src/error.rs b/dan_layer/storage_sqlite/src/error.rs deleted file mode 100644 index b8a6c8cd44e..00000000000 --- a/dan_layer/storage_sqlite/src/error.rs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -use diesel; -use tari_common_types::types::FixedHashSizeError; -use tari_dan_core::{models::ModelError, storage::StorageError}; -use tari_dan_engine::state::error::StateStorageError; -use thiserror::Error; - -#[derive(Debug, Error)] -pub enum SqliteStorageError { - #[error("Could not connect to database: {source}")] - ConnectionError { - #[from] - source: diesel::ConnectionError, - }, - #[error("General diesel error during operation {operation}: {source}")] - DieselError { - source: diesel::result::Error, - operation: String, - }, - #[error("Could not migrate the database")] - MigrationError { - #[from] - source: diesel_migrations::RunMigrationsError, - }, - #[error("Encountered malformed hash data")] - MalformedHashData, - #[error("Malformed DB data: {0}")] - MalformedDbData(String), - #[error(transparent)] - ModelError(#[from] ModelError), - #[error("Conversion error:{reason}")] - ConversionError { reason: String }, - #[error("Malformed metadata for key '{key}'")] - MalformedMetadata { key: String }, -} - -impl From for StorageError { - fn from(source: SqliteStorageError) -> Self { - match source { - SqliteStorageError::ConnectionError { .. } => StorageError::ConnectionError { - reason: source.to_string(), - }, - SqliteStorageError::DieselError { .. } => StorageError::QueryError { - reason: source.to_string(), - }, - SqliteStorageError::MigrationError { .. } => StorageError::MigrationError { - reason: source.to_string(), - }, - other => StorageError::General { - details: other.to_string(), - }, - } - } -} - -impl From for StateStorageError { - fn from(source: SqliteStorageError) -> Self { - match source { - SqliteStorageError::ConnectionError { .. } => StateStorageError::ConnectionError { - reason: source.to_string(), - }, - SqliteStorageError::DieselError { .. } => StateStorageError::QueryError { - reason: source.to_string(), - }, - SqliteStorageError::MigrationError { .. } => StateStorageError::MigrationError { - reason: source.to_string(), - }, - other => StateStorageError::General { - details: other.to_string(), - }, - } - } -} - -impl From for SqliteStorageError { - fn from(_: FixedHashSizeError) -> Self { - SqliteStorageError::MalformedHashData - } -} diff --git a/dan_layer/storage_sqlite/src/global/mod.rs b/dan_layer/storage_sqlite/src/global/mod.rs deleted file mode 100644 index f615a46d786..00000000000 --- a/dan_layer/storage_sqlite/src/global/mod.rs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub mod models; -pub mod schema; -mod sqlite_global_db_backend_adapter; -pub use sqlite_global_db_backend_adapter::SqliteGlobalDbBackendAdapter; diff --git a/dan_layer/storage_sqlite/src/global/models/contract.rs b/dan_layer/storage_sqlite/src/global/models/contract.rs deleted file mode 100644 index 622d5797d6c..00000000000 --- a/dan_layer/storage_sqlite/src/global/models/contract.rs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_dan_core::storage::global::ContractState; - -use crate::global::schema::*; - -#[derive(Queryable, Identifiable)] -pub struct Contract { - pub id: i32, - pub contract_id: Vec, - pub height: i64, - pub state: i32, - pub constitution: Vec, -} - -#[derive(Insertable)] -#[table_name = "contracts"] -pub struct NewContract { - pub contract_id: Vec, - pub height: i64, - pub state: i32, - pub constitution: Vec, -} - -impl NewContract { - pub fn with_state(&mut self, state: ContractState) -> &mut Self { - self.state = i32::from(state.as_byte()); - self - } -} diff --git a/dan_layer/storage_sqlite/src/global/models/metadata.rs b/dan_layer/storage_sqlite/src/global/models/metadata.rs deleted file mode 100644 index 4d587f7a1e2..00000000000 --- a/dan_layer/storage_sqlite/src/global/models/metadata.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::global::schema::*; - -#[derive(Queryable, Insertable, Identifiable)] -#[table_name = "metadata"] -#[primary_key(key_name)] -pub struct GlobalMetadata { - pub key_name: Vec, - pub value: Vec, -} diff --git a/dan_layer/storage_sqlite/src/global/models/mod.rs b/dan_layer/storage_sqlite/src/global/models/mod.rs deleted file mode 100644 index 030337a27cf..00000000000 --- a/dan_layer/storage_sqlite/src/global/models/mod.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub mod contract; -pub mod metadata; diff --git a/dan_layer/storage_sqlite/src/global/schema.rs b/dan_layer/storage_sqlite/src/global/schema.rs deleted file mode 100644 index 13f3cc0b683..00000000000 --- a/dan_layer/storage_sqlite/src/global/schema.rs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -table! { - contracts (id) { - id -> Integer, - contract_id -> Binary, - height -> BigInt, - state -> Integer, - constitution -> Binary, - } -} - -table! { - metadata (key_name) { - key_name -> Binary, - value -> Binary, - } -} - -allow_tables_to_appear_in_same_query!(contracts, metadata,); diff --git a/dan_layer/storage_sqlite/src/global/sqlite_global_db_backend_adapter.rs b/dan_layer/storage_sqlite/src/global/sqlite_global_db_backend_adapter.rs deleted file mode 100644 index 41a970f224a..00000000000 --- a/dan_layer/storage_sqlite/src/global/sqlite_global_db_backend_adapter.rs +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use diesel::{prelude::*, Connection, RunQueryDsl, SqliteConnection}; -use tari_common_types::types::FixedHash; -use tari_dan_core::storage::global::{ContractState, GlobalDbBackendAdapter, GlobalDbMetadataKey}; - -use crate::{ - error::SqliteStorageError, - global::models::{ - contract::{Contract, NewContract}, - metadata::GlobalMetadata, - }, - SqliteTransaction, -}; - -#[derive(Clone)] -pub struct SqliteGlobalDbBackendAdapter { - database_url: String, -} - -impl SqliteGlobalDbBackendAdapter { - pub fn new(database_url: String) -> Self { - SqliteGlobalDbBackendAdapter { database_url } - } -} - -impl GlobalDbBackendAdapter for SqliteGlobalDbBackendAdapter { - type BackendTransaction = SqliteTransaction; - type Error = SqliteStorageError; - type Model = Contract; - type NewModel = NewContract; - - fn create_transaction(&self) -> Result { - let connection = SqliteConnection::establish(self.database_url.as_str())?; - - connection - .execute("PRAGMA foreign_keys = ON;") - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "set pragma".to_string(), - })?; - connection - .execute("BEGIN EXCLUSIVE TRANSACTION;") - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "begin transaction".to_string(), - })?; - - Ok(SqliteTransaction::new(connection)) - } - - fn set_data(&self, key: GlobalDbMetadataKey, value: &[u8]) -> Result<(), Self::Error> { - use crate::global::schema::metadata; - let tx = self.create_transaction()?; - - match self.get_data_with_connection(&key, &tx) { - Ok(Some(r)) => diesel::update(&GlobalMetadata { - key_name: key.as_key_bytes().to_vec(), - value: r, - }) - .set(metadata::value.eq(value)) - .execute(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "update::metadata".to_string(), - })?, - Ok(None) => diesel::insert_into(metadata::table) - .values((metadata::key_name.eq(key.as_key_bytes()), metadata::value.eq(value))) - .execute(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "insert::metadata".to_string(), - })?, - Err(e) => return Err(e), - }; - - self.commit(&tx)?; - - Ok(()) - } - - fn get_data(&self, key: GlobalDbMetadataKey) -> Result>, Self::Error> { - use crate::global::schema::metadata::dsl; - let connection = SqliteConnection::establish(self.database_url.as_str())?; - - let row: Option = dsl::metadata - .find(key.as_key_bytes()) - .first(&connection) - .optional() - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "get::metadata_key".to_string(), - })?; - - Ok(row.map(|r| r.value)) - } - - fn get_data_with_connection( - &self, - key: &GlobalDbMetadataKey, - tx: &Self::BackendTransaction, - ) -> Result>, Self::Error> { - use crate::global::schema::metadata::dsl; - - let row: Option = dsl::metadata - .find(key.as_key_bytes()) - .first(tx.connection()) - .optional() - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "get::metadata_key".to_string(), - })?; - - Ok(row.map(|r| r.value)) - } - - fn commit(&self, tx: &Self::BackendTransaction) -> Result<(), Self::Error> { - tx.connection() - .execute("COMMIT TRANSACTION;") - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "commit::state".to_string(), - })?; - Ok(()) - } - - fn save_contract(&self, mut contract: NewContract, state: ContractState) -> Result<(), Self::Error> { - use crate::global::schema::contracts; - let tx = self.create_transaction()?; - - contract.with_state(state); - - diesel::insert_into(contracts::table) - .values(&contract) - .execute(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "insert::contract".to_string(), - })?; - - self.commit(&tx)?; - - Ok(()) - } - - fn update_contract_state(&self, contract_id: FixedHash, state: ContractState) -> Result<(), Self::Error> { - use crate::global::schema::contracts; - let tx = self.create_transaction()?; - - diesel::update(contracts::table.filter(contracts::contract_id.eq(contract_id.to_vec()))) - .set(contracts::state.eq(i32::from(state.as_byte()))) - .execute(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "update::contract_state".to_string(), - })?; - - self.commit(&tx)?; - - Ok(()) - } - - fn get_contracts_with_state(&self, state: ContractState) -> Result, Self::Error> { - use crate::global::schema::{contracts, contracts::dsl}; - let tx = self.create_transaction()?; - - dsl::contracts - .filter(contracts::state.eq(i32::from(state.as_byte()))) - .load::(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "get::contracts".to_string(), - }) - } -} diff --git a/dan_layer/storage_sqlite/src/lib.rs b/dan_layer/storage_sqlite/src/lib.rs deleted file mode 100644 index e62b629e170..00000000000 --- a/dan_layer/storage_sqlite/src/lib.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#[macro_use] -extern crate diesel; -#[macro_use] -extern crate diesel_migrations; - -pub mod error; -mod schema; -mod sqlite_chain_backend_adapter; -pub use sqlite_chain_backend_adapter::SqliteChainBackendAdapter; -mod sqlite_transaction; -pub use sqlite_transaction::SqliteTransaction; -mod sqlite_db_factory; -pub use sqlite_db_factory::SqliteDbFactory; -mod models; -mod sqlite_state_db_backend_adapter; -pub use sqlite_state_db_backend_adapter::SqliteStateDbBackendAdapter; -pub mod engine_state_store; -pub mod global; -mod sqlite_storage_service; - -pub use sqlite_storage_service::SqliteStorageService; diff --git a/dan_layer/storage_sqlite/src/models/instruction.rs b/dan_layer/storage_sqlite/src/models/instruction.rs deleted file mode 100644 index 173688e001c..00000000000 --- a/dan_layer/storage_sqlite/src/models/instruction.rs +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that -// the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the -// following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. - -use std::convert::{TryFrom, TryInto}; - -use tari_common_types::types::PublicKey; -use tari_utilities::ByteArray; - -use crate::{error::SqliteStorageError, schema::*}; - -#[derive(Debug, Identifiable, Queryable)] -pub struct Instruction { - pub id: i32, - pub hash: Vec, - pub node_id: i32, - pub template_id: i32, - pub method: String, - pub args: Vec, - pub sender: Vec, -} - -impl TryFrom for tari_dan_engine::instructions::Instruction { - type Error = SqliteStorageError; - - fn try_from(instruction: Instruction) -> Result { - let template_id = instruction - .template_id - .try_into() - .map_err(|s| SqliteStorageError::ConversionError { reason: s })?; - Ok(Self::new( - template_id, - instruction.method, - instruction.args, - PublicKey::from_bytes(&instruction.sender).expect("invalid public key"), - )) - } -} - -#[derive(Debug, Insertable)] -#[table_name = "instructions"] -pub struct NewInstruction { - pub hash: Vec, - pub node_id: i32, - pub template_id: i32, - pub method: String, - pub args: Vec, - pub sender: Vec, -} diff --git a/dan_layer/storage_sqlite/src/models/locked_qc.rs b/dan_layer/storage_sqlite/src/models/locked_qc.rs deleted file mode 100644 index 460b9fe323f..00000000000 --- a/dan_layer/storage_sqlite/src/models/locked_qc.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#[derive(Queryable)] -pub struct LockedQc { - pub id: i32, - pub message_type: i32, - pub view_number: i64, - pub node_hash: Vec, - pub signature: Option>, -} diff --git a/dan_layer/storage_sqlite/src/models/metadata.rs b/dan_layer/storage_sqlite/src/models/metadata.rs deleted file mode 100644 index f8853174a90..00000000000 --- a/dan_layer/storage_sqlite/src/models/metadata.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::schema::metadata; - -#[derive(Queryable, Insertable, Identifiable)] -#[table_name = "metadata"] -#[primary_key(key)] -pub struct Metadata { - pub key: Vec, - pub value: Vec, -} diff --git a/dan_layer/storage_sqlite/src/models/mod.rs b/dan_layer/storage_sqlite/src/models/mod.rs deleted file mode 100644 index b12e4238a04..00000000000 --- a/dan_layer/storage_sqlite/src/models/mod.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub mod instruction; -pub mod locked_qc; -pub mod metadata; -pub mod node; -pub mod prepare_qc; -pub mod state_key; -pub mod state_op_log; diff --git a/dan_layer/storage_sqlite/src/models/node.rs b/dan_layer/storage_sqlite/src/models/node.rs deleted file mode 100644 index e310ab0d2e7..00000000000 --- a/dan_layer/storage_sqlite/src/models/node.rs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::schema::*; - -#[derive(Debug, Clone, Identifiable, Queryable)] -pub struct Node { - pub id: i32, - pub hash: Vec, - pub parent: Vec, - pub height: i32, - pub is_committed: bool, -} - -#[derive(Debug, Clone, Insertable)] -#[table_name = "nodes"] -pub struct NewNode { - pub hash: Vec, - pub parent: Vec, - pub height: i32, -} diff --git a/dan_layer/storage_sqlite/src/models/prepare_qc.rs b/dan_layer/storage_sqlite/src/models/prepare_qc.rs deleted file mode 100644 index 99a39f4b2b1..00000000000 --- a/dan_layer/storage_sqlite/src/models/prepare_qc.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#[derive(Queryable)] -pub struct PrepareQc { - pub id: i32, - pub message_type: i32, - pub view_number: i64, - pub node_hash: Vec, - pub signature: Option>, -} diff --git a/dan_layer/storage_sqlite/src/models/state_key.rs b/dan_layer/storage_sqlite/src/models/state_key.rs deleted file mode 100644 index b5fcb990867..00000000000 --- a/dan_layer/storage_sqlite/src/models/state_key.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::schema::*; - -#[derive(Queryable, Insertable, Identifiable)] -#[primary_key(schema_name, key_name)] -pub struct StateKey { - pub schema_name: String, - pub key_name: Vec, - pub value: Vec, -} diff --git a/dan_layer/storage_sqlite/src/models/state_op_log.rs b/dan_layer/storage_sqlite/src/models/state_op_log.rs deleted file mode 100644 index 4ebbb358ffd..00000000000 --- a/dan_layer/storage_sqlite/src/models/state_op_log.rs +++ /dev/null @@ -1,90 +0,0 @@ -use std::convert::TryFrom; - -use tari_common_types::types::FixedHash; -use tari_dan_engine::state::DbStateOpLogEntry; - -// Copyright 2022, The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that -// the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the -// following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -use crate::{error::SqliteStorageError, schema::*}; - -#[derive(Debug, Clone, Identifiable, Queryable)] -#[table_name = "state_op_log"] -pub struct StateOpLogEntry { - pub id: i32, - pub height: i64, - pub merkle_root: Option>, - pub operation: String, - pub schema: String, - pub key: Vec, - pub value: Option>, -} - -#[derive(Debug, Clone, Insertable)] -#[table_name = "state_op_log"] -pub struct NewStateOpLogEntry { - pub height: i64, - pub merkle_root: Option>, - pub operation: String, - pub schema: String, - pub key: Vec, - pub value: Option>, -} - -impl From for NewStateOpLogEntry { - #[allow(clippy::cast_possible_wrap)] - fn from(entry: DbStateOpLogEntry) -> Self { - Self { - height: entry.height as i64, - merkle_root: entry.merkle_root.map(|r| r.to_vec()), - operation: entry.operation.as_op_str().to_string(), - schema: entry.schema, - key: entry.key, - value: entry.value, - } - } -} - -#[allow(clippy::cast_sign_loss)] -impl TryFrom for DbStateOpLogEntry { - type Error = SqliteStorageError; - - fn try_from(entry: StateOpLogEntry) -> Result { - Ok(Self { - height: entry.height as u64, - merkle_root: entry - .merkle_root - .map(FixedHash::try_from) - .transpose() - .map_err(|_| SqliteStorageError::MalformedHashData)?, - operation: entry - .operation - .parse() - .map_err(|_| SqliteStorageError::ConversionError { - reason: "Invalid OpLog operation".to_string(), - })?, - schema: entry.schema, - key: entry.key, - value: entry.value, - }) - } -} diff --git a/dan_layer/storage_sqlite/src/schema.rs b/dan_layer/storage_sqlite/src/schema.rs deleted file mode 100644 index 746f8b4efa6..00000000000 --- a/dan_layer/storage_sqlite/src/schema.rs +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -table! { - instructions (id) { - id -> Integer, - hash -> Binary, - node_id -> Integer, - template_id -> Integer, - method -> Text, - args -> Binary, - sender -> Binary, - } -} - -table! { - locked_qc (id) { - id -> Integer, - message_type -> Integer, - view_number -> BigInt, - node_hash -> Binary, - signature -> Nullable, - } -} - -table! { - metadata (key) { - key -> Binary, - value -> Binary, - } -} - -table! { - nodes (id) { - id -> Integer, - hash -> Binary, - parent -> Binary, - height -> Integer, - is_committed -> Bool, - } -} - -table! { - prepare_qc (id) { - id -> Integer, - message_type -> Integer, - view_number -> BigInt, - node_hash -> Binary, - signature -> Nullable, - } -} - -table! { - state_keys (schema_name, key_name) { - schema_name -> Text, - key_name -> Binary, - value -> Binary, - } -} - -table! { - state_op_log (id) { - id -> Integer, - height -> BigInt, - merkle_root -> Nullable, - operation -> Text, - schema -> Text, - key -> Binary, - value -> Nullable, - } -} - -table! { - state_tree (id) { - id -> Integer, - version -> Integer, - is_current -> Bool, - data -> Binary, - } -} - -joinable!(instructions -> nodes (node_id)); - -allow_tables_to_appear_in_same_query!( - instructions, - locked_qc, - metadata, - nodes, - prepare_qc, - state_keys, - state_op_log, - state_tree, -); diff --git a/dan_layer/storage_sqlite/src/sqlite_chain_backend_adapter.rs b/dan_layer/storage_sqlite/src/sqlite_chain_backend_adapter.rs deleted file mode 100644 index ec82bf75e0e..00000000000 --- a/dan_layer/storage_sqlite/src/sqlite_chain_backend_adapter.rs +++ /dev/null @@ -1,547 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - convert::{TryFrom, TryInto}, - fmt::Display, -}; - -use diesel::{prelude::*, Connection, SqliteConnection}; -use log::*; -use tari_dan_core::{ - models::{HotStuffMessageType, QuorumCertificate, TariDanPayload, TreeNodeHash, ValidatorSignature, ViewId}, - storage::{ - chain::{ChainDbBackendAdapter, DbInstruction, DbNode, DbQc}, - AsKeyBytes, - AtomicDb, - MetadataBackendAdapter, - }, -}; -use tari_utilities::{message_format::MessageFormat, ByteArray}; - -use crate::{ - error::SqliteStorageError, - models::{ - instruction::{Instruction, NewInstruction}, - locked_qc::LockedQc, - metadata::Metadata, - node::{NewNode, Node}, - prepare_qc::PrepareQc, - }, - schema::*, - SqliteTransaction, -}; - -const LOG_TARGET: &str = "tari::dan_layer::storage_sqlite::sqlite_chain_backend_adapter"; - -#[derive(Clone)] -pub struct SqliteChainBackendAdapter { - database_url: String, -} - -impl SqliteChainBackendAdapter { - pub fn new(database_url: String) -> SqliteChainBackendAdapter { - Self { database_url } - } - - pub fn get_connection(&self) -> ConnectionResult { - SqliteConnection::establish(self.database_url.as_str()) - } -} - -impl AtomicDb for SqliteChainBackendAdapter { - type DbTransaction = SqliteTransaction; - type Error = SqliteStorageError; - - fn create_transaction(&self) -> Result { - let connection = self.get_connection()?; - connection - .execute("PRAGMA foreign_keys = ON;") - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "set pragma".to_string(), - })?; - connection - .execute("BEGIN EXCLUSIVE TRANSACTION;") - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "begin transaction".to_string(), - })?; - - Ok(SqliteTransaction::new(connection)) - } - - fn commit(&self, transaction: &Self::DbTransaction) -> Result<(), Self::Error> { - debug!(target: LOG_TARGET, "Committing transaction"); - transaction - .connection() - .execute("COMMIT TRANSACTION") - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "commit::chain".to_string(), - })?; - Ok(()) - } -} - -impl ChainDbBackendAdapter for SqliteChainBackendAdapter { - type Id = i32; - type Payload = TariDanPayload; - - fn is_empty(&self) -> Result { - let connection = self.get_connection()?; - let n: Option = - nodes::table - .first(&connection) - .optional() - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "is_empty".to_string(), - })?; - Ok(n.is_none()) - } - - fn node_exists(&self, node_hash: &TreeNodeHash) -> Result { - let connection = self.get_connection()?; - use crate::schema::nodes::dsl; - let count = dsl::nodes - .filter(nodes::parent.eq(node_hash.as_bytes())) - .limit(1) - .count() - .first::(&connection) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "node_exists: count".to_string(), - })?; - - Ok(count > 0) - } - - #[allow(clippy::cast_sign_loss)] - fn get_tip_node(&self) -> Result, Self::Error> { - use crate::schema::nodes::dsl; - - let connection = self.get_connection()?; - let node = dsl::nodes - .order_by(dsl::height.desc()) - .first::(&connection) - .optional() - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "get_tip_node".to_string(), - })?; - - match node { - Some(node) => Ok(Some(DbNode { - hash: node.hash.try_into()?, - parent: node.parent.try_into()?, - height: node.height as u32, - is_committed: node.is_committed, - })), - None => Ok(None), - } - } - - fn insert_node(&self, item: &DbNode, transaction: &Self::DbTransaction) -> Result<(), Self::Error> { - debug!(target: LOG_TARGET, "Inserting {:?}", item); - #[allow(clippy::cast_possible_wrap)] - let new_node = NewNode { - hash: Vec::from(item.hash.as_bytes()), - parent: Vec::from(item.parent.as_bytes()), - height: item.height as i32, - }; - diesel::insert_into(nodes::table) - .values(&new_node) - .execute(transaction.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "insert::node".to_string(), - })?; - Ok(()) - } - - fn update_node(&self, id: &Self::Id, item: &DbNode, transaction: &Self::DbTransaction) -> Result<(), Self::Error> { - use crate::schema::nodes::dsl; - // Should not be allowed to update hash, parent and height - diesel::update(dsl::nodes.find(id)) - .set(( - // dsl::hash.eq(&hash.0), - // dsl::parent.eq(&parent.0), - // dsl::height.eq(*height as i32), - dsl::is_committed.eq(item.is_committed), - )) - .execute(transaction.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "update::nodes".to_string(), - })?; - Ok(()) - } - - #[allow(clippy::cast_possible_wrap)] - fn update_locked_qc(&self, item: &DbQc, transaction: &Self::DbTransaction) -> Result<(), Self::Error> { - use crate::schema::locked_qc::dsl; - let message_type = i32::from(item.message_type.as_u8()); - let existing: Result = dsl::locked_qc.find(1).first(transaction.connection()); - match existing { - Ok(_) => { - diesel::update(dsl::locked_qc.find(1)) - .set(( - dsl::message_type.eq(message_type), - dsl::view_number.eq(item.view_number.0 as i64), - dsl::node_hash.eq(item.node_hash.as_bytes()), - dsl::signature.eq(item.signature.as_ref().map(|s| s.to_bytes())), - )) - .execute(transaction.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "update::locked_qc".to_string(), - })?; - }, - Err(_) => { - diesel::insert_into(locked_qc::table) - .values(( - dsl::id.eq(1), - dsl::message_type.eq(message_type), - dsl::view_number.eq(item.view_number.0 as i64), - dsl::node_hash.eq(item.node_hash.as_bytes()), - dsl::signature.eq(item.signature.as_ref().map(|s| s.to_bytes())), - )) - .execute(transaction.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "insert::locked_qc".to_string(), - })?; - }, - } - Ok(()) - } - - #[allow(clippy::cast_possible_wrap)] - fn update_prepare_qc(&self, item: &DbQc, transaction: &Self::DbTransaction) -> Result<(), Self::Error> { - use crate::schema::prepare_qc::dsl; - let message_type = i32::from(item.message_type.as_u8()); - let existing: Result = dsl::prepare_qc.find(1).first(transaction.connection()); - match existing { - Ok(_) => { - diesel::update(dsl::prepare_qc.find(1)) - .set(( - dsl::message_type.eq(message_type), - dsl::view_number.eq(item.view_number.0 as i64), - dsl::node_hash.eq(item.node_hash.as_bytes()), - dsl::signature.eq(item.signature.as_ref().map(|s| s.to_bytes())), - )) - .execute(transaction.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "update::prepare_qc".to_string(), - })?; - }, - Err(_) => { - diesel::insert_into(prepare_qc::table) - .values(( - dsl::id.eq(1), - dsl::message_type.eq(message_type), - dsl::view_number.eq(item.view_number.0 as i64), - dsl::node_hash.eq(item.node_hash.as_bytes()), - dsl::signature.eq(item.signature.as_ref().map(|s| s.to_bytes())), - )) - .execute(transaction.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "insert::prepare_qc".to_string(), - })?; - }, - } - Ok(()) - } - - #[allow(clippy::cast_sign_loss)] - fn get_prepare_qc(&self) -> Result, Self::Error> { - let connection = self.get_connection()?; - use crate::schema::prepare_qc::dsl; - let qc: Option = dsl::prepare_qc - .find(1) - .first(&connection) - .optional() - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "get_prepare_qc".to_string(), - })?; - qc.map(|qc| { - Ok(QuorumCertificate::new( - HotStuffMessageType::try_from(u8::try_from(qc.message_type).unwrap()).unwrap(), - ViewId::from(qc.view_number as u64), - qc.node_hash.try_into()?, - qc.signature.map(|s| ValidatorSignature::from_bytes(s.as_slice())), - )) - }) - .transpose() - } - - fn locked_qc_id(&self) -> Self::Id { - 1 - } - - fn prepare_qc_id(&self) -> Self::Id { - 1 - } - - #[allow(clippy::cast_sign_loss)] - fn find_highest_prepared_qc(&self) -> Result { - use crate::schema::locked_qc::dsl; - let connection = self.get_connection()?; - // TODO: this should be a single row - let result: Option = prepare_qc::table - .order_by(prepare_qc::view_number.desc()) - .first(&connection) - .optional() - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "find_highest_prepared_qc".to_string(), - })?; - let qc = match result { - Some(r) => r, - None => { - let l: LockedQc = dsl::locked_qc - .find(self.locked_qc_id()) - .first(&connection) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "find_locked_qc".to_string(), - })?; - PrepareQc { - id: 1, - message_type: l.message_type, - view_number: l.view_number, - node_hash: l.node_hash.clone(), - signature: l.signature, - } - }, - }; - - Ok(QuorumCertificate::new( - HotStuffMessageType::try_from(u8::try_from(qc.message_type).unwrap()).unwrap(), - ViewId::from(qc.view_number as u64), - qc.node_hash.try_into()?, - qc.signature.map(|s| ValidatorSignature::from_bytes(s.as_slice())), - )) - } - - #[allow(clippy::cast_sign_loss)] - fn get_locked_qc(&self) -> Result { - use crate::schema::locked_qc::dsl; - let connection = self.get_connection()?; - let qc: LockedQc = dsl::locked_qc - .find(self.locked_qc_id()) - .first(&connection) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "get_locked_qc".to_string(), - })?; - Ok(QuorumCertificate::new( - HotStuffMessageType::try_from(u8::try_from(qc.message_type).unwrap()).unwrap(), - ViewId::from(qc.view_number as u64), - qc.node_hash.try_into()?, - qc.signature.map(|s| ValidatorSignature::from_bytes(s.as_slice())), - )) - } - - fn find_node_by_hash(&self, node_hash: &TreeNodeHash) -> Result, Self::Error> { - use crate::schema::nodes::dsl; - let connection = self.get_connection()?; - let node = dsl::nodes - .filter(nodes::hash.eq(node_hash.as_bytes())) - .first::(&connection) - .optional() - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "find_node_by_hash".to_string(), - })?; - - match node { - Some(node) => Ok(Some((node.id, DbNode { - hash: node.hash.try_into()?, - parent: node.parent.try_into()?, - height: u32::try_from(node.height).unwrap(), - is_committed: node.is_committed, - }))), - None => Ok(None), - } - } - - #[allow(clippy::cast_sign_loss)] - fn find_node_by_parent_hash(&self, parent_hash: &TreeNodeHash) -> Result, Self::Error> { - use crate::schema::nodes::dsl; - let connection = self.get_connection()?; - let node = dsl::nodes - .filter(nodes::parent.eq(parent_hash.as_bytes())) - .first::(&connection) - .optional() - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "find_node_by_hash".to_string(), - })?; - - match node { - Some(node) => Ok(Some((node.id, DbNode { - hash: node.hash.try_into()?, - parent: node.parent.try_into()?, - height: node.height as u32, - is_committed: node.is_committed, - }))), - None => Ok(None), - } - } - - fn insert_instruction(&self, item: &DbInstruction, transaction: &Self::DbTransaction) -> Result<(), Self::Error> { - use crate::schema::nodes::dsl; - // TODO: this could be made more efficient - let node: Node = dsl::nodes - .filter(nodes::hash.eq(&item.node_hash.as_bytes())) - .first(transaction.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "insert_instruction::find_node".to_string(), - })?; - let new_instruction = NewInstruction { - hash: item.instruction.hash().to_vec(), - node_id: node.id, - template_id: item.instruction.template_id() as i32, - method: item.instruction.method().to_string(), - args: Vec::from(item.instruction.args()), - sender: item.instruction.sender().to_vec(), - }; - diesel::insert_into(instructions::table) - .values(new_instruction) - .execute(transaction.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "insert_instruction".to_string(), - })?; - Ok(()) - } - - fn find_all_instructions_by_node(&self, node_id: Self::Id) -> Result, Self::Error> { - use crate::schema::{instructions::dsl as instructions_dsl, nodes::dsl as nodes_dsl}; - let connection = self.get_connection()?; - let node = nodes_dsl::nodes - .filter(nodes::id.eq(node_id)) - .first::(&connection) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "find_all_instructions_by_node::find_node".to_string(), - })?; - let instructions = instructions_dsl::instructions - .filter(instructions::node_id.eq(&node.id)) - .load::(&connection) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "find_all_instructions_by_node::filter_by_node_id".to_string(), - })?; - let node_hash = node.hash.try_into()?; - let instructions = instructions - .into_iter() - .map(|i| { - Ok(DbInstruction { - instruction: i.try_into()?, - node_hash, - }) - }) - .collect::>()?; - - Ok(instructions) - } -} - -impl MetadataBackendAdapter for SqliteChainBackendAdapter { - fn get_metadata( - &self, - key: &K, - transaction: &Self::DbTransaction, - ) -> Result, Self::Error> { - use crate::schema::metadata::dsl; - debug!(target: LOG_TARGET, "get_metadata: key = {}", key); - let value = dsl::metadata - .select(metadata::value) - .filter(metadata::key.eq(key.as_key_bytes())) - .first::>(transaction.connection()) - .optional() - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "chain_db::get_metadata".to_string(), - })?; - - value - .map(|v| T::from_binary(&v)) - .transpose() - .map_err(|_| SqliteStorageError::MalformedMetadata { key: key.to_string() }) - } - - fn set_metadata(&self, key: K, value: T, tx: &Self::DbTransaction) -> Result<(), Self::Error> { - use crate::schema::metadata::dsl; - debug!(target: LOG_TARGET, "set_metadata: key = {}", key); - let value = value - .to_binary() - .map_err(|_| SqliteStorageError::MalformedMetadata { key: key.to_string() })?; - - // One day we will have upsert in diesel - if self.metadata_key_exists(&key, tx)? { - debug!(target: LOG_TARGET, "update_metadata: key = {}", key); - diesel::update(metadata::table.filter(dsl::key.eq(key.as_key_bytes()))) - .set(metadata::value.eq(value)) - .execute(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "chain_db::set_metadata".to_string(), - })?; - } else { - debug!(target: LOG_TARGET, "insert_metadata: key = {}", key); - diesel::insert_into(metadata::table) - .values(Metadata { - key: key.as_key_bytes().to_vec(), - value, - }) - .execute(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "chain_db::set_metadata".to_string(), - })?; - } - - Ok(()) - } - - fn metadata_key_exists(&self, key: &K, transaction: &Self::DbTransaction) -> Result { - use crate::schema::metadata::dsl; - let v = dsl::metadata - .select(metadata::key) - .filter(metadata::key.eq(key.as_key_bytes())) - .first::>(transaction.connection()) - .optional() - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "chain_db::get_metadata".to_string(), - })?; - Ok(v.is_some()) - } -} diff --git a/dan_layer/storage_sqlite/src/sqlite_db_factory.rs b/dan_layer/storage_sqlite/src/sqlite_db_factory.rs deleted file mode 100644 index 7ede7674a67..00000000000 --- a/dan_layer/storage_sqlite/src/sqlite_db_factory.rs +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{fs::create_dir_all, path::PathBuf}; - -use diesel::{Connection, ConnectionError, SqliteConnection}; -use diesel_migrations::embed_migrations; -use log::*; -use tari_common_types::types::FixedHash; -use tari_dan_core::storage::{chain::ChainDb, global::GlobalDb, DbFactory, StorageError}; -use tari_dan_engine::state::StateDb; -use tari_utilities::hex::Hex; - -use crate::{ - error::SqliteStorageError, - global::SqliteGlobalDbBackendAdapter, - sqlite_state_db_backend_adapter::SqliteStateDbBackendAdapter, - SqliteChainBackendAdapter, -}; - -#[derive(Clone)] -pub struct SqliteDbFactory { - data_dir: PathBuf, -} - -impl SqliteDbFactory { - pub fn new(data_dir: PathBuf) -> Self { - Self { data_dir } - // let database_url = config - // .data_dir - // .join("asset_data") - // .into_os_string() - // .into_string() - // .unwrap(); - // - // Self { database_url } - } - - fn database_url_for(&self, contract_id: &FixedHash) -> String { - self.data_dir - .join("asset_data") - .join(contract_id.to_hex()) - .join("dan_storage.sqlite") - .into_os_string() - .into_string() - .expect("Should not fail") - } - - fn try_connect(&self, url: &str) -> Result, StorageError> { - match SqliteConnection::establish(url) { - Ok(connection) => { - connection - .execute("PRAGMA foreign_keys = ON;") - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "set pragma".to_string(), - })?; - Ok(Some(connection)) - }, - Err(ConnectionError::BadConnection(_)) => Ok(None), - Err(err) => Err(SqliteStorageError::from(err).into()), - } - } -} - -impl DbFactory for SqliteDbFactory { - type ChainDbBackendAdapter = SqliteChainBackendAdapter; - type GlobalDbBackendAdapter = SqliteGlobalDbBackendAdapter; - type StateDbBackendAdapter = SqliteStateDbBackendAdapter; - - fn get_chain_db( - &self, - contract_id: &FixedHash, - ) -> Result>, StorageError> { - let database_url = self.database_url_for(contract_id); - match self.try_connect(&database_url)? { - Some(_) => Ok(Some(ChainDb::new(SqliteChainBackendAdapter::new(database_url)))), - None => Ok(None), - } - } - - fn get_or_create_chain_db( - &self, - contract_id: &FixedHash, - ) -> Result, StorageError> { - let database_url = self.database_url_for(contract_id); - debug!("Loading chain database from {}", database_url); - create_dir_all(&PathBuf::from(&database_url).parent().unwrap()) - .map_err(|_| StorageError::FileSystemPathDoesNotExist)?; - let connection = SqliteConnection::establish(database_url.as_str()).map_err(SqliteStorageError::from)?; - connection - .execute("PRAGMA foreign_keys = ON;") - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "set pragma".to_string(), - })?; - embed_migrations!("./migrations"); - embedded_migrations::run(&connection).map_err(SqliteStorageError::from)?; - Ok(ChainDb::new(SqliteChainBackendAdapter::new(database_url))) - } - - fn get_state_db( - &self, - contract_id: &FixedHash, - ) -> Result>, StorageError> { - let database_url = self.database_url_for(contract_id); - match self.try_connect(&database_url)? { - Some(_) => Ok(Some(StateDb::new( - *contract_id, - SqliteStateDbBackendAdapter::new(database_url), - ))), - None => Ok(None), - } - } - - fn get_or_create_state_db( - &self, - contract_id: &FixedHash, - ) -> Result, StorageError> { - let database_url = self.database_url_for(contract_id); - - create_dir_all(&PathBuf::from(&database_url).parent().unwrap()) - .map_err(|_| StorageError::FileSystemPathDoesNotExist)?; - - let connection = SqliteConnection::establish(database_url.as_str()).map_err(SqliteStorageError::from)?; - connection - .execute("PRAGMA foreign_keys = ON;") - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "set pragma".to_string(), - })?; - embed_migrations!("./migrations"); - embedded_migrations::run(&connection).map_err(SqliteStorageError::from)?; - Ok(StateDb::new( - *contract_id, - SqliteStateDbBackendAdapter::new(database_url), - )) - } - - fn get_or_create_global_db(&self) -> Result, StorageError> { - let database_url = self - .data_dir - .join("global_storage.sqlite") - .into_os_string() - .into_string() - .expect("Should not fail"); - - create_dir_all(&PathBuf::from(&database_url).parent().unwrap()) - .map_err(|_| StorageError::FileSystemPathDoesNotExist)?; - - let connection = SqliteConnection::establish(database_url.as_str()).map_err(SqliteStorageError::from)?; - connection - .execute("PRAGMA foreign_keys = ON;") - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "set pragma".to_string(), - })?; - embed_migrations!("./global_db_migrations"); - // embedded_migrations::run(&connection).map_err(SqliteStorageError::from)?; - embedded_migrations::run_with_output(&connection, &mut std::io::stdout()).expect("Migration failed"); - Ok(GlobalDb::new(SqliteGlobalDbBackendAdapter::new(database_url))) - } -} diff --git a/dan_layer/storage_sqlite/src/sqlite_state_db_backend_adapter.rs b/dan_layer/storage_sqlite/src/sqlite_state_db_backend_adapter.rs deleted file mode 100644 index 879fc499cbd..00000000000 --- a/dan_layer/storage_sqlite/src/sqlite_state_db_backend_adapter.rs +++ /dev/null @@ -1,244 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::convert::TryInto; - -use diesel::{prelude::*, Connection, SqliteConnection}; -use log::*; -use tari_dan_engine::state::{DbKeyValue, DbStateOpLogEntry, StateDbBackendAdapter}; - -use crate::{ - error::SqliteStorageError, - models::{ - state_key::StateKey, - state_op_log::{NewStateOpLogEntry, StateOpLogEntry}, - }, - schema::*, - SqliteTransaction, -}; - -const LOG_TARGET: &str = "tari::dan_layer::storage_sqlite::sqlite_state_db_backend_adapter"; - -#[derive(Clone)] -pub struct SqliteStateDbBackendAdapter { - database_url: String, -} - -impl SqliteStateDbBackendAdapter { - pub fn new(database_url: String) -> Self { - SqliteStateDbBackendAdapter { database_url } - } -} - -impl StateDbBackendAdapter for SqliteStateDbBackendAdapter { - type BackendTransaction = SqliteTransaction; - type Error = SqliteStorageError; - - fn create_transaction(&self) -> Result { - let connection = SqliteConnection::establish(self.database_url.as_str())?; - connection - .execute("PRAGMA foreign_keys = ON;") - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "set pragma".to_string(), - })?; - connection - .execute("BEGIN EXCLUSIVE TRANSACTION;") - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "begin transaction".to_string(), - })?; - - Ok(SqliteTransaction::new(connection)) - } - - fn update_key_value( - &self, - schema: &str, - key: &[u8], - value: &[u8], - tx: &Self::BackendTransaction, - ) -> Result<(), Self::Error> { - use crate::schema::state_keys::dsl; - let upsert_data = ( - state_keys::schema_name.eq(schema), - state_keys::key_name.eq(key), - state_keys::value.eq(value), - ); - let row: Option = dsl::state_keys - .find((schema, key)) - .first(tx.connection()) - .optional() - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "find::state_key".to_string(), - })?; - - match row { - Some(r) => diesel::update(&r) - .set(state_keys::value.eq(value)) - .execute(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "update::state_key".to_string(), - })?, - None => diesel::insert_into(state_keys::table) - .values(upsert_data) - .execute(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "insert::state_key".to_string(), - })?, - }; - Ok(()) - } - - fn get(&self, schema: &str, key: &[u8]) -> Result>, Self::Error> { - use crate::schema::state_keys::dsl; - let connection = SqliteConnection::establish(self.database_url.as_str())?; - let row: Option = dsl::state_keys - .find((schema, key)) - .first(&connection) - .optional() - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "get::state_key".to_string(), - })?; - Ok(row.map(|r| r.value)) - } - - fn find_keys_by_value(&self, schema: &str, value: &[u8]) -> Result>, Self::Error> { - use crate::schema::state_keys::dsl; - let connection = SqliteConnection::establish(self.database_url.as_str())?; - let row: Vec = dsl::state_keys - .filter(state_keys::schema_name.eq(schema)) - .filter(state_keys::value.eq(value)) - .get_results(&connection) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "find_keys_by_value".to_string(), - })?; - Ok(row.into_iter().map(|r| r.key_name).collect()) - } - - fn commit(&self, tx: &Self::BackendTransaction) -> Result<(), Self::Error> { - debug!(target: LOG_TARGET, "Committing transaction"); - tx.connection() - .execute("COMMIT TRANSACTION;") - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "commit::state".to_string(), - })?; - Ok(()) - } - - fn get_all_schemas(&self, tx: &Self::BackendTransaction) -> Result, Self::Error> { - use crate::schema::state_keys::dsl; - let schemas: Vec = dsl::state_keys - .select(state_keys::schema_name) - .distinct() - .order_by(state_keys::schema_name.asc()) - .load(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "get_all_schemas".to_string(), - })?; - Ok(schemas) - } - - fn get_all_values_for_schema( - &self, - schema: &str, - tx: &Self::BackendTransaction, - ) -> Result, Self::Error> { - use crate::schema::state_keys::dsl; - let values: Vec<(String, Vec, Vec)> = dsl::state_keys - .filter(state_keys::schema_name.eq(schema)) - .select((state_keys::schema_name, state_keys::key_name, state_keys::value)) - .order_by(state_keys::key_name.asc()) - .load(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "get_all_values_for_schema".to_string(), - })?; - - Ok(values - .into_iter() - .map(|(schema, key, value)| DbKeyValue { schema, key, value }) - .collect()) - } - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_wrap)] - fn get_state_op_logs_by_height( - &self, - height: u64, - tx: &Self::BackendTransaction, - ) -> Result, Self::Error> { - use crate::schema::state_op_log::dsl; - let op_logs = dsl::state_op_log - .filter(dsl::height.eq(height as i64)) - .order_by(dsl::key.asc()) - .load::(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "get_all_values_for_schema".to_string(), - })?; - - op_logs.into_iter().map(TryInto::try_into).collect() - } - - fn add_state_oplog_entry( - &self, - entry: DbStateOpLogEntry, - tx: &Self::BackendTransaction, - ) -> Result<(), Self::Error> { - use crate::schema::state_op_log::dsl; - diesel::insert_into(dsl::state_op_log) - .values(NewStateOpLogEntry::from(entry)) - .execute(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "add_state_oplog_entry".to_string(), - })?; - - Ok(()) - } - - fn clear_all_state(&self, tx: &Self::BackendTransaction) -> Result<(), Self::Error> { - diesel::delete(state_keys::dsl::state_keys) - .execute(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "clear_all_state::state_keys".to_string(), - })?; - - diesel::delete(state_op_log::dsl::state_op_log) - .execute(tx.connection()) - .map_err(|source| SqliteStorageError::DieselError { - source, - operation: "clear_all_state::state_op_logs".to_string(), - })?; - - Ok(()) - } -} diff --git a/dan_layer/storage_sqlite/src/sqlite_storage_service.rs b/dan_layer/storage_sqlite/src/sqlite_storage_service.rs deleted file mode 100644 index 0fd9361334d..00000000000 --- a/dan_layer/storage_sqlite/src/sqlite_storage_service.rs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use async_trait::async_trait; -use tari_dan_core::{ - models::{HotStuffTreeNode, SidechainMetadata, TariDanPayload}, - storage::{chain::ChainDbUnitOfWork, ChainStorageService, StorageError}, -}; - -pub struct SqliteStorageService {} - -// TODO: this has no references to Sqlite, so may be worth moving to dan_layer.core - -#[async_trait] -impl ChainStorageService for SqliteStorageService { - async fn get_metadata(&self) -> Result { - todo!() - } - - async fn add_node( - &self, - node: &HotStuffTreeNode, - db: TUnitOfWork, - ) -> Result<(), StorageError> { - let mut db = db; - for instruction in node.payload().instructions() { - db.add_instruction(*node.hash(), instruction.clone())?; - } - db.add_node(*node.hash(), *node.parent(), node.height())?; - Ok(()) - } -} diff --git a/dan_layer/storage_sqlite/src/sqlite_transaction.rs b/dan_layer/storage_sqlite/src/sqlite_transaction.rs deleted file mode 100644 index a29f0a1c4a1..00000000000 --- a/dan_layer/storage_sqlite/src/sqlite_transaction.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use diesel::SqliteConnection; - -pub struct SqliteTransaction { - connection: SqliteConnection, -} - -impl SqliteTransaction { - pub fn new(connection: SqliteConnection) -> Self { - Self { connection } - } - - pub fn connection(&self) -> &SqliteConnection { - &self.connection - } -} diff --git a/dan_layer/template_abi/Cargo.toml b/dan_layer/template_abi/Cargo.toml deleted file mode 100644 index 81480beebad..00000000000 --- a/dan_layer/template_abi/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "tari_template_abi" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -borsh = { version ="0.9.3", default-features = false } - -[features] -default = ["std"] -std = ["borsh/std"] diff --git a/dan_layer/template_abi/src/abi.rs b/dan_layer/template_abi/src/abi.rs deleted file mode 100644 index c3e36ede193..00000000000 --- a/dan_layer/template_abi/src/abi.rs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// TODO: we should only use stdlib if the template dev needs to include it e.g. use core::mem when stdlib is not -// available -use crate::{ - decode, - decode_len, - encode_into, - rust::{fmt, mem, ptr::copy, slice, vec::Vec}, - Decode, - Encode, -}; - -extern "C" { - pub fn tari_engine(op: i32, input_ptr: *const u8, input_len: usize) -> *mut u8; - pub fn debug(input_ptr: *const u8, input_len: usize); -} - -pub fn wrap_ptr(mut v: Vec) -> *mut u8 { - let ptr = v.as_mut_ptr(); - mem::forget(v); - ptr -} - -pub fn call_engine(op: i32, input: &T) -> Option { - let mut encoded = Vec::with_capacity(512); - encode_into(input, &mut encoded).unwrap(); - let len = encoded.len(); - let input_ptr = wrap_ptr(encoded) as *const _; - let ptr = unsafe { tari_engine(op, input_ptr, len) }; - if ptr.is_null() { - return None; - } - - let slice = unsafe { slice::from_raw_parts(ptr as *const _, 4) }; - let len = decode_len(slice).unwrap(); - let slice = unsafe { slice::from_raw_parts(ptr.offset(4), len) }; - let ret = decode(slice).unwrap(); - Some(ret) -} - -pub fn call_debug>(data: T) { - let ptr = data.as_ref().as_ptr(); - let len = data.as_ref().len(); - unsafe { debug(ptr, len) } -} - -/// Allocates a block of memory of length `len` bytes. -#[no_mangle] -pub extern "C" fn tari_alloc(len: u32) -> *mut u8 { - let cap = (len + 4) as usize; - let mut buf = Vec::::with_capacity(cap); - let ptr = buf.as_mut_ptr(); - mem::forget(buf); - unsafe { - copy(len.to_le_bytes().as_ptr(), ptr, 4); - } - ptr -} - -/// Frees a block of memory allocated by `tari_alloc`. -/// -/// # Safety -/// Caller must ensure that ptr must be a valid pointer to a block of memory allocated by `tari_alloc`. -#[no_mangle] -pub unsafe extern "C" fn tari_free(ptr: *mut u8) { - let mut len = [0u8; 4]; - copy(ptr, len.as_mut_ptr(), 4); - - let cap = (u32::from_le_bytes(len) + 4) as usize; - drop(Vec::::from_raw_parts(ptr, cap, cap)); -} diff --git a/dan_layer/template_abi/src/encoding.rs b/dan_layer/template_abi/src/encoding.rs deleted file mode 100644 index 488d0124da3..00000000000 --- a/dan_layer/template_abi/src/encoding.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// TODO: Move to tari template lib crate - -use crate::{ - rust::{io, vec::Vec}, - Decode, - Encode, -}; - -pub fn encode_with_len(val: &T) -> Vec { - let mut buf = Vec::with_capacity(512); - buf.extend([0u8; 4]); - - encode_into(val, &mut buf).expect("Vec Write impl is infallible"); - - let len = ((buf.len() - 4) as u32).to_le_bytes(); - buf[..4].copy_from_slice(&len); - - buf -} - -pub fn encode_into(val: &T, buf: &mut Vec) -> io::Result<()> { - val.serialize(buf) -} - -pub fn encode(val: &T) -> io::Result> { - let mut buf = Vec::with_capacity(512); - encode_into(val, &mut buf)?; - Ok(buf) -} - -pub fn decode(mut input: &[u8]) -> io::Result { - T::deserialize(&mut input) -} - -pub fn decode_len(input: &[u8]) -> io::Result { - if input.len() < 4 { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "Not enough bytes to decode length", - )); - } - - let mut buf = [0u8; 4]; - buf.copy_from_slice(&input[..4]); - let len = u32::from_le_bytes(buf); - Ok(len as usize) -} diff --git a/dan_layer/template_abi/src/lib.rs b/dan_layer/template_abi/src/lib.rs deleted file mode 100644 index 8a0e0805b59..00000000000 --- a/dan_layer/template_abi/src/lib.rs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#![cfg_attr(not(feature = "std"), no_std)] - -//! # Tari WASM module ABI (application binary interface) -//! -//! This library provides types and encoding that allow low-level communication between the Tari WASM runtime and the -//! WASM modules. - -mod abi; -pub use abi::*; -pub use borsh::{BorshDeserialize as Decode, BorshSerialize as Encode}; - -mod encoding; -pub use encoding::{decode, decode_len, encode, encode_into, encode_with_len}; - -mod rust; - -mod types; -pub use types::*; diff --git a/dan_layer/template_abi/src/rust.rs b/dan_layer/template_abi/src/rust.rs deleted file mode 100644 index 5557a4dc895..00000000000 --- a/dan_layer/template_abi/src/rust.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#[cfg(not(feature = "std"))] -mod no_std { - extern crate alloc; - - pub use alloc::{string, vec}; - pub use core::{fmt, mem, ptr, slice}; - - pub use borsh::maybestd::io; -} - -#[cfg(not(feature = "std"))] -pub use no_std::*; - -#[cfg(feature = "std")] -mod rust_std { - pub use ::std::{fmt, io, mem, ptr, slice, string, vec}; -} - -#[cfg(feature = "std")] -pub use rust_std::*; diff --git a/dan_layer/template_abi/src/types.rs b/dan_layer/template_abi/src/types.rs deleted file mode 100644 index 3ad327f81e3..00000000000 --- a/dan_layer/template_abi/src/types.rs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::{ - rust::{string::String, vec::Vec}, - Decode, - Encode, -}; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct TemplateDef { - pub template_name: String, - pub functions: Vec, -} - -impl TemplateDef { - pub fn get_function(&self, name: &str) -> Option<&FunctionDef> { - self.functions.iter().find(|f| f.name.as_str() == name) - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct FunctionDef { - pub name: String, - pub arguments: Vec, - pub output: Type, -} - -#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] -pub enum Type { - Unit, - Bool, - I8, - I16, - I32, - I64, - I128, - U8, - U16, - U32, - U64, - U128, - String, -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct CallInfo { - pub func_name: String, - pub args: Vec>, - pub abi_context: Vec, -} diff --git a/dan_layer/template_lib/Cargo.toml b/dan_layer/template_lib/Cargo.toml deleted file mode 100644 index 950f49bc2d1..00000000000 --- a/dan_layer/template_lib/Cargo.toml +++ /dev/null @@ -1,10 +0,0 @@ -[package] -name = "tari_template_lib" -version = "0.1.0" -edition = "2021" - -[dependencies] -tari_template_abi = { path = "../template_abi" } - -borsh = "0.9.3" -serde = { version = "1.0.143", optional = true } diff --git a/dan_layer/template_lib/src/abi_context.rs b/dan_layer/template_lib/src/abi_context.rs deleted file mode 100644 index c0ec3c82cd8..00000000000 --- a/dan_layer/template_lib/src/abi_context.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_template_abi::{Decode, Encode}; - -use crate::models::{Contract, Package}; - -#[derive(Debug, Decode, Encode)] -pub struct AbiContext { - pub package: Package, - pub contract: Contract, -} diff --git a/dan_layer/template_lib/src/args.rs b/dan_layer/template_lib/src/args.rs deleted file mode 100644 index b95e5a55248..00000000000 --- a/dan_layer/template_lib/src/args.rs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -use tari_template_abi::{Decode, Encode}; - -use crate::models::{ComponentId, ContractAddress, PackageId}; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct EmitLogArg { - pub message: String, - pub level: LogLevel, -} - -#[derive(Debug, Clone, Encode, Decode)] -pub enum LogLevel { - Error, - Warn, - Info, - Debug, -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct CreateComponentArg { - pub contract_address: ContractAddress, - pub module_name: String, - pub package_id: PackageId, - pub state: Vec, -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct GetComponentArg { - pub component_id: ComponentId, -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct SetComponentStateArg { - pub component_id: ComponentId, - pub state: Vec, -} - -#[macro_export] -macro_rules! __template_lib_count { - () => (0usize); - ( $x:tt $($next:tt)* ) => (1usize + $crate::__template_lib_count!($($next)*)); -} - -#[macro_export] -macro_rules! args { - () => (Vec::new()); - - ($($args:expr),+) => {{ - let mut args = Vec::with_capacity($crate::__template_lib_count!($($args),+)); - $( - args.push(tari_template_abi::encode(&$args).unwrap()); - )+ - args - }} -} diff --git a/dan_layer/template_lib/src/context.rs b/dan_layer/template_lib/src/context.rs deleted file mode 100644 index 5553cf9e744..00000000000 --- a/dan_layer/template_lib/src/context.rs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{borrow::Borrow, cell::RefCell}; - -use tari_template_abi::{decode, CallInfo}; - -use crate::{ - abi_context::AbiContext, - models::{Contract, Package}, -}; - -thread_local! { - static CONTEXT: RefCell> = RefCell::new(None); -} - -pub fn set_context_from_call_info(call_info: &CallInfo) { - let abi_context = decode(&call_info.abi_context).expect("Failed to decode ABI context"); - with_context(|ctx| { - *ctx = Some(abi_context); - }); -} - -pub fn with_context) -> R>(f: F) -> R { - CONTEXT.borrow().with(|c| f(&mut c.borrow_mut())) -} - -pub fn get_context() -> Context { - Context -} - -#[derive(Debug, Default)] -pub struct Context; -impl Context { - pub fn package(&self) -> Package { - with_context(|ctx| ctx.as_ref().unwrap().package.clone()) - } - - pub fn contract(&self) -> Contract { - with_context(|ctx| ctx.as_ref().unwrap().contract.clone()) - } -} diff --git a/dan_layer/template_lib/src/engine.rs b/dan_layer/template_lib/src/engine.rs deleted file mode 100644 index 111c49e9460..00000000000 --- a/dan_layer/template_lib/src/engine.rs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_template_abi::{call_engine, decode, encode, Decode, Encode}; - -use crate::{ - args::{CreateComponentArg, EmitLogArg, GetComponentArg, LogLevel, SetComponentStateArg}, - context::Context, - get_context, - models::{Component, ComponentId}, - ops::*, -}; - -pub fn engine() -> TariEngine { - // TODO: I expect some thread local state to be included here - TariEngine::new(get_context()) -} - -#[derive(Debug, Default)] -pub struct TariEngine { - context: Context, -} - -impl TariEngine { - fn new(context: Context) -> Self { - Self { context } - } - - pub fn instantiate(&self, template_name: String, initial_state: T) -> ComponentId { - let encoded_state = encode(&initial_state).unwrap(); - - // Call the engine to create a new component - // TODO: proper component id - // TODO: what happens if the user wants to return multiple components/types? - let component_id = call_engine::<_, ComponentId>(OP_CREATE_COMPONENT, &CreateComponentArg { - contract_address: *self.context.contract().address(), - module_name: template_name, - state: encoded_state, - package_id: *self.context.package().id(), - }); - component_id.expect("no asset id returned") - } - - pub fn emit_log>(&self, level: LogLevel, msg: T) { - call_engine::<_, ()>(OP_EMIT_LOG, &EmitLogArg { - level, - message: msg.into(), - }); - } - - /// Get the component state - pub fn get_component_state(&self, component_id: ComponentId) -> T { - let component = call_engine::<_, Component>(OP_GET_COMPONENT, &GetComponentArg { component_id }) - .expect("Component not found"); - - decode(&component.state).expect("Failed to decode component state") - } - - pub fn set_component_state(&self, component_id: ComponentId, state: T) { - let state = encode(&state).unwrap(); - call_engine::<_, ()>(OP_SET_COMPONENT_STATE, &SetComponentStateArg { component_id, state }); - } -} diff --git a/dan_layer/template_lib/src/hash.rs b/dan_layer/template_lib/src/hash.rs deleted file mode 100644 index ddc3bbb8692..00000000000 --- a/dan_layer/template_lib/src/hash.rs +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::{ - error::Error, - fmt::{Display, Formatter}, - io, - io::Write, - ops::Deref, -}; - -use tari_template_abi::{Decode, Encode}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] -#[cfg_attr(feature = "serde", derive(serde::Deserialize))] -pub struct Hash([u8; 32]); - -impl Hash { - pub fn into_inner(self) -> [u8; 32] { - self.0 - } - - pub fn from_hex(s: &str) -> Result { - if s.len() != 64 { - return Err(HashParseError); - } - - let mut hash = [0u8; 32]; - for (i, h) in hash.iter_mut().enumerate() { - *h = u8::from_str_radix(&s[2 * i..2 * (i + 1)], 16).map_err(|_| HashParseError)?; - } - Ok(Hash(hash)) - } -} - -impl AsRef<[u8]> for Hash { - fn as_ref(&self) -> &[u8] { - self.0.as_ref() - } -} - -impl From<[u8; 32]> for Hash { - fn from(hash: [u8; 32]) -> Self { - Self(hash) - } -} - -impl Deref for Hash { - type Target = [u8]; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl Encode for Hash { - fn serialize(&self, writer: &mut W) -> io::Result<()> { - self.0.serialize(writer) - } -} - -impl Decode for Hash { - fn deserialize(buf: &mut &[u8]) -> io::Result { - let hash = <[u8; 32] as Decode>::deserialize(buf)?; - Ok(Hash(hash)) - } -} - -impl Display for Hash { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - for x in self.0 { - write!(f, "{:02x?}", x)?; - } - Ok(()) - } -} - -#[derive(Debug)] -pub struct HashParseError; - -impl Error for HashParseError {} - -impl Display for HashParseError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "Failed to parse hash") - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn serialize_deserialize() { - let hash = Hash::default(); - let mut buf = Vec::new(); - hash.serialize(&mut buf).unwrap(); - let hash2 = Hash::deserialize(&mut &buf[..]).unwrap(); - assert_eq!(hash, hash2); - } -} diff --git a/dan_layer/template_lib/src/lib.rs b/dan_layer/template_lib/src/lib.rs deleted file mode 100644 index 7da73f2e78a..00000000000 --- a/dan_layer/template_lib/src/lib.rs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -pub mod abi_context; - -mod hash; -pub use hash::Hash; - -#[macro_use] -pub mod args; -pub mod models; -pub mod ops; - -// ---------------------------------------- WASM target exports ------------------------------------------------ - -#[cfg(target_arch = "wasm32")] -pub mod template_dependencies; - -#[cfg(target_arch = "wasm32")] -mod context; -#[cfg(target_arch = "wasm32")] -pub use context::{get_context, set_context_from_call_info}; - -#[cfg(target_arch = "wasm32")] -mod engine; - -#[cfg(target_arch = "wasm32")] -pub use engine::engine; diff --git a/dan_layer/template_lib/src/models/bucket.rs b/dan_layer/template_lib/src/models/bucket.rs deleted file mode 100644 index ebd2b461809..00000000000 --- a/dan_layer/template_lib/src/models/bucket.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::marker::PhantomData; - -pub type BucketId = u32; - -pub struct Bucket { - id: BucketId, - _t: PhantomData, -} - -impl Bucket { - pub fn id(&self) -> BucketId { - self.id - } -} diff --git a/dan_layer/template_lib/src/models/component.rs b/dan_layer/template_lib/src/models/component.rs deleted file mode 100644 index 933afb56289..00000000000 --- a/dan_layer/template_lib/src/models/component.rs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_template_abi::{Decode, Encode}; - -use crate::models::{ContractAddress, PackageId}; - -pub type ComponentId = crate::Hash; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct ComponentInstance { - pub component_id: ComponentId, - pub contract_address: ContractAddress, - pub package_id: PackageId, - pub module_name: String, - pub state: Vec, -} - -impl ComponentInstance { - pub fn new(component_id: ComponentId, component: Component) -> Self { - Self { - component_id, - contract_address: component.contract_address, - package_id: component.package_id, - module_name: component.module_name, - state: component.state, - } - } - - pub fn id(&self) -> ComponentId { - self.component_id - } -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct Component { - pub contract_address: ContractAddress, - pub package_id: PackageId, - pub module_name: String, - pub state: Vec, -} diff --git a/dan_layer/template_lib/src/models/contract.rs b/dan_layer/template_lib/src/models/contract.rs deleted file mode 100644 index a03e25444ec..00000000000 --- a/dan_layer/template_lib/src/models/contract.rs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_template_abi::{Decode, Encode}; - -pub type ContractAddress = crate::Hash; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct Contract { - pub address: ContractAddress, -} - -impl Contract { - pub fn new(address: ContractAddress) -> Self { - Self { address } - } - - pub fn address(&self) -> &ContractAddress { - &self.address - } -} diff --git a/dan_layer/template_lib/src/models/mod.rs b/dan_layer/template_lib/src/models/mod.rs deleted file mode 100644 index b6aaf2bb08f..00000000000 --- a/dan_layer/template_lib/src/models/mod.rs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -mod bucket; -pub use bucket::{Bucket, BucketId}; - -mod component; -pub use component::*; - -mod contract; -pub use contract::{Contract, ContractAddress}; - -mod resource; -pub use resource::ResourceAddress; - -mod package; -pub use package::{Package, PackageId}; - -mod vault; -pub use vault::Vault; diff --git a/dan_layer/template_lib/src/models/package.rs b/dan_layer/template_lib/src/models/package.rs deleted file mode 100644 index c1761115494..00000000000 --- a/dan_layer/template_lib/src/models/package.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_template_abi::{Decode, Encode}; - -use crate::Hash; - -pub type PackageId = Hash; - -#[derive(Debug, Clone, Encode, Decode)] -pub struct Package { - pub id: PackageId, -} - -impl Package { - pub fn new(id: PackageId) -> Self { - Self { id } - } - - pub fn id(&self) -> &PackageId { - &self.id - } -} diff --git a/dan_layer/template_lib/src/models/resource.rs b/dan_layer/template_lib/src/models/resource.rs deleted file mode 100644 index 41c3730e72c..00000000000 --- a/dan_layer/template_lib/src/models/resource.rs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use std::marker::PhantomData; - -use crate::{hash::HashParseError, Hash}; - -#[derive(Debug)] -pub struct ResourceAddress { - address: Hash, - _t: PhantomData, -} - -impl ResourceAddress { - // pub fn descriptor(&self) -> (Hash, UniversalTypeId) { - // (self.address, T::universal_type_id()) - // } - - pub fn from_hex(s: &str) -> Result { - Ok(ResourceAddress { - address: Hash::from_hex(s)?, - _t: PhantomData, - }) - } -} - -impl Clone for ResourceAddress { - fn clone(&self) -> Self { - Self { - address: self.address, - _t: PhantomData, - } - } -} - -impl Copy for ResourceAddress {} diff --git a/dan_layer/template_lib/src/models/vault.rs b/dan_layer/template_lib/src/models/vault.rs deleted file mode 100644 index 172c3de4854..00000000000 --- a/dan_layer/template_lib/src/models/vault.rs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use tari_template_abi::{Decode, Encode}; - -use crate::models::{Bucket, ResourceAddress}; - -#[derive(Clone, Debug, Decode, Encode)] -pub struct Vault { - resource_address: ResourceAddress, -} - -impl Vault { - pub fn new(resource_address: ResourceAddress) -> Self { - // Call to call_engine will rather be in the ResourceBuilder/VaultBuilder, and the resulting address passed in - // here. let resource_address = call_engine(OP_RESOURCE_INVOKE, ResourceInvoke { - // resource_ref: ResourceRef::Vault, - // action: ResourceAction::Create, - // args: args![], - // }); - - Self { resource_address } - } - - pub fn put(&mut self, _bucket: Bucket) { - // let _ok: () = call_engine(OP_RESOURCE_INVOKE, ResourceInvoke { - // resource_ref: ResourceRef::VaultRef(self.resource_address()), - // action: ResourceAction::Put, - // args: args![bucket], - // }); - todo!() - } - - pub fn resource_address(&self) -> ResourceAddress { - self.resource_address - } -} diff --git a/dan_layer/template_lib/src/ops.rs b/dan_layer/template_lib/src/ops.rs deleted file mode 100644 index 67fcae63d8f..00000000000 --- a/dan_layer/template_lib/src/ops.rs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -pub const OP_EMIT_LOG: i32 = 0x00; -pub const OP_CREATE_COMPONENT: i32 = 0x01; -pub const OP_GET_COMPONENT: i32 = 0x02; -pub const OP_SET_COMPONENT_STATE: i32 = 0x03; -pub const OP_RESOURCE_INVOKE: i32 = 0x04; diff --git a/dan_layer/template_lib/src/template_dependencies.rs b/dan_layer/template_lib/src/template_dependencies.rs deleted file mode 100644 index 2057b2ec912..00000000000 --- a/dan_layer/template_lib/src/template_dependencies.rs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -//! Public types that are available to all template authors. - -pub use borsh; -pub use tari_template_abi::{call_debug as debug, Decode, Encode}; - -pub use crate::{ - args::LogLevel, - engine, - get_context as context, - models::{Bucket, BucketId, ResourceAddress, Vault}, -}; diff --git a/dan_layer/template_macros/Cargo.lock b/dan_layer/template_macros/Cargo.lock deleted file mode 100644 index 746c58c20a1..00000000000 --- a/dan_layer/template_macros/Cargo.lock +++ /dev/null @@ -1,200 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "ahash" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" -dependencies = [ - "getrandom", - "once_cell", - "version_check", -] - -[[package]] -name = "borsh" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15bf3650200d8bffa99015595e10f1fbd17de07abbc25bb067da79e769939bfa" -dependencies = [ - "borsh-derive", - "hashbrown", -] - -[[package]] -name = "borsh-derive" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6441c552f230375d18e3cc377677914d2ca2b0d36e52129fe15450a2dce46775" -dependencies = [ - "borsh-derive-internal", - "borsh-schema-derive-internal", - "proc-macro-crate", - "proc-macro2", - "syn", -] - -[[package]] -name = "borsh-derive-internal" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5449c28a7b352f2d1e592a8a28bf139bc71afb0764a14f3c02500935d8c44065" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "borsh-schema-derive-internal" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdbd5696d8bfa21d53d9fe39a714a18538bad11492a42d066dbbc395fb1951c0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "getrandom" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - -[[package]] -name = "hashbrown" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" -dependencies = [ - "ahash", -] - -[[package]] -name = "indoc" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05a0bd019339e5d968b37855180087b7b9d512c5046fbd244cf8c95687927d6e" - -[[package]] -name = "libc" -version = "0.2.126" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836" - -[[package]] -name = "once_cell" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18a6dbe30758c9f83eb00cbea4ac95966305f5a7772f3f42ebfc7fc7eddbd8e1" - -[[package]] -name = "proc-macro-crate" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d6ea3c4595b96363c13943497db34af4460fb474a95c43f4446ad341b8c9785" -dependencies = [ - "toml", -] - -[[package]] -name = "proc-macro2" -version = "1.0.42" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c278e965f1d8cf32d6e0e96de3d3e79712178ae67986d9cf9151f51e95aac89b" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bcdf212e9776fbcb2d23ab029360416bb1706b1aea2d1a5ba002727cbcab804" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "serde" -version = "1.0.140" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc855a42c7967b7c369eb5860f7164ef1f6f81c20c7cc1141f2a604e18723b03" - -[[package]] -name = "syn" -version = "1.0.98" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c50aef8a904de4c23c788f104b7dddc7d6f79c647c7c8ce4cc8f73eb0ca773dd" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "tari_template_abi" -version = "0.1.0" -dependencies = [ - "borsh", -] - -[[package]] -name = "tari_template_lib" -version = "0.1.0" -dependencies = [ - "tari_template_abi", -] - -[[package]] -name = "tari_template_macros" -version = "0.1.0" -dependencies = [ - "indoc", - "proc-macro2", - "quote", - "syn", - "tari_template_abi", - "tari_template_lib", -] - -[[package]] -name = "toml" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" -dependencies = [ - "serde", -] - -[[package]] -name = "unicode-ident" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15c61ba63f9235225a22310255a29b806b907c9b8c964bcbd0a2c70f3f2deea7" - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" diff --git a/dan_layer/template_macros/Cargo.toml b/dan_layer/template_macros/Cargo.toml deleted file mode 100644 index b7bfa3da3d9..00000000000 --- a/dan_layer/template_macros/Cargo.toml +++ /dev/null @@ -1,17 +0,0 @@ -[package] -name = "tari_template_macros" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[lib] -proc-macro = true - -[dependencies] -proc-macro2 = "1.0.42" -quote = "1.0.20" -syn = { version = "1.0.98", features = ["full"] } - -[dev-dependencies] -indoc = "1.0.6" \ No newline at end of file diff --git a/dan_layer/template_macros/src/ast.rs b/dan_layer/template_macros/src/ast.rs deleted file mode 100644 index 27079f882a3..00000000000 --- a/dan_layer/template_macros/src/ast.rs +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use syn::{ - parse::{Parse, ParseStream}, - punctuated::Punctuated, - token::Comma, - Error, - FnArg, - Ident, - ImplItem, - ImplItemMethod, - ItemImpl, - ItemMod, - ItemStruct, - Result, - ReturnType, - Signature, - Stmt, -}; - -#[allow(dead_code)] -pub struct TemplateAst { - pub template_name: Ident, - pub struct_section: ItemStruct, - pub impl_section: ItemImpl, -} - -impl Parse for TemplateAst { - fn parse(input: ParseStream) -> Result { - // parse the "mod" block - let module: ItemMod = input.parse()?; - - // get the contents of the "mod" block - let items = match module.content { - Some((_, items)) => items, - None => return Err(Error::new(module.ident.span(), "empty module")), - }; - - // there should be two items: the "struct" and the "impl" blocks - if items.len() != 2 { - return Err(Error::new(module.ident.span(), "invalid number of module sections")); - } - - // get the "struct" block - let struct_section = match &items[0] { - syn::Item::Struct(struct_item) => struct_item.clone(), - _ => return Err(Error::new(module.ident.span(), "the first section is not a 'struct'")), - }; - - // get the "impl" block - let impl_section = match &items[1] { - syn::Item::Impl(impl_item) => impl_item.clone(), - _ => return Err(Error::new(module.ident.span(), "the second section is not an 'impl'")), - }; - - let template_name = struct_section.ident.clone(); - - Ok(Self { - template_name, - struct_section, - impl_section, - }) - } -} - -impl TemplateAst { - pub fn get_functions(&self) -> Vec { - self.impl_section - .items - .iter() - .map(Self::get_function_from_item) - .collect() - } - - fn get_function_from_item(item: &ImplItem) -> FunctionAst { - match item { - ImplItem::Method(m) => FunctionAst { - name: m.sig.ident.to_string(), - input_types: Self::get_input_types(&m.sig.inputs), - output_type: Self::get_output_type_token(&m.sig.output), - statements: Self::get_statements(m), - is_constructor: Self::is_constructor(&m.sig), - }, - _ => todo!(), - } - } - - fn get_input_types(inputs: &Punctuated) -> Vec { - inputs - .iter() - .map(|arg| match arg { - // TODO: handle the "self" case - syn::FnArg::Receiver(r) => { - // TODO: validate that it's indeed a reference ("&") to self - - let mutability = r.mutability.is_some(); - TypeAst::Receiver { mutability } - }, - syn::FnArg::Typed(t) => Self::get_type_ast(&t.ty), - }) - .collect() - } - - fn get_output_type_token(ast_type: &ReturnType) -> Option { - match ast_type { - syn::ReturnType::Default => None, // the function does not return anything - syn::ReturnType::Type(_, t) => Some(Self::get_type_ast(t)), - } - } - - fn get_type_ast(syn_type: &syn::Type) -> TypeAst { - match syn_type { - syn::Type::Path(type_path) => { - // TODO: handle "Self" - // TODO: detect more complex types - TypeAst::Typed(type_path.path.segments[0].ident.clone()) - }, - _ => todo!(), - } - } - - fn get_statements(method: &ImplItemMethod) -> Vec { - method.block.stmts.clone() - } - - fn is_constructor(sig: &Signature) -> bool { - match &sig.output { - syn::ReturnType::Default => false, // the function does not return anything - syn::ReturnType::Type(_, t) => match t.as_ref() { - syn::Type::Path(type_path) => type_path.path.segments[0].ident == "Self", - _ => false, - }, - } - } -} - -pub struct FunctionAst { - pub name: String, - pub input_types: Vec, - pub output_type: Option, - pub statements: Vec, - pub is_constructor: bool, -} - -pub enum TypeAst { - Receiver { mutability: bool }, - Typed(Ident), -} diff --git a/dan_layer/template_macros/src/lib.rs b/dan_layer/template_macros/src/lib.rs deleted file mode 100644 index 689ff88c050..00000000000 --- a/dan_layer/template_macros/src/lib.rs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -mod ast; -mod template; - -use proc_macro::TokenStream; - -#[proc_macro_attribute] -pub fn template(_attr: TokenStream, item: TokenStream) -> TokenStream { - template::generate_template(proc_macro2::TokenStream::from(item)) - .unwrap_or_else(|err| err.to_compile_error()) - .into() -} diff --git a/dan_layer/template_macros/src/template/abi.rs b/dan_layer/template_macros/src/template/abi.rs deleted file mode 100644 index a9dc4aeaa21..00000000000 --- a/dan_layer/template_macros/src/template/abi.rs +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use proc_macro2::TokenStream; -use quote::{format_ident, quote}; -use syn::{parse_quote, Expr, Result}; - -use crate::ast::{FunctionAst, TemplateAst, TypeAst}; - -pub fn generate_abi(ast: &TemplateAst) -> Result { - let abi_function_name = format_ident!("{}_abi", ast.struct_section.ident); - let template_name_as_str = ast.template_name.to_string(); - let function_defs: Vec = ast.get_functions().iter().map(generate_function_def).collect(); - - let output = quote! { - #[no_mangle] - pub extern "C" fn #abi_function_name() -> *mut u8 { - use ::tari_template_abi::{encode_with_len, FunctionDef, TemplateDef, Type, wrap_ptr}; - - let template = TemplateDef { - template_name: #template_name_as_str.to_string(), - functions: vec![ #(#function_defs),* ], - }; - - let buf = encode_with_len(&template); - wrap_ptr(buf) - } - }; - - Ok(output) -} - -fn generate_function_def(f: &FunctionAst) -> Expr { - let name = f.name.clone(); - - let arguments: Vec = f.input_types.iter().map(generate_abi_type).collect(); - - let output = match &f.output_type { - Some(type_ast) => generate_abi_type(type_ast), - None => parse_quote!(Type::Unit), - }; - - parse_quote!( - FunctionDef { - name: #name.to_string(), - arguments: vec![ #(#arguments),* ], - output: #output, - } - ) -} - -fn generate_abi_type(rust_type: &TypeAst) -> Expr { - match rust_type { - // on "&self" we want to pass the component id - TypeAst::Receiver { .. } => get_component_id_type(), - // basic type - // TODO: there may be a better way of handling this - TypeAst::Typed(ident) => match ident.to_string().as_str() { - "" => parse_quote!(Type::Unit), - "bool" => parse_quote!(Type::Bool), - "i8" => parse_quote!(Type::I8), - "i16" => parse_quote!(Type::I16), - "i32" => parse_quote!(Type::I32), - "i64" => parse_quote!(Type::I64), - "i128" => parse_quote!(Type::I128), - "u8" => parse_quote!(Type::U8), - "u16" => parse_quote!(Type::U16), - "u32" => parse_quote!(Type::U32), - "u64" => parse_quote!(Type::U64), - "u128" => parse_quote!(Type::U128), - "String" => parse_quote!(Type::String), - "Self" => get_component_id_type(), - _ => todo!(), - }, - } -} - -fn get_component_id_type() -> Expr { - parse_quote!(Type::U32) -} - -#[cfg(test)] -mod tests { - use std::str::FromStr; - - use indoc::indoc; - use proc_macro2::TokenStream; - use quote::quote; - use syn::parse2; - - use super::generate_abi; - use crate::ast::TemplateAst; - - #[test] - fn test_signatures() { - let input = TokenStream::from_str(indoc! {" - mod foo { - struct Foo {} - impl Foo { - pub fn no_args_function() -> String { - \"Hello World!\".to_string() - } - pub fn some_args_function(a: i8, b: String) -> u32 { - 1_u32 - } - pub fn no_return_function() {} - pub fn constructor() -> Self {} - pub fn method(&self){} - } - } - "}) - .unwrap(); - - let ast = parse2::(input).unwrap(); - - let output = generate_abi(&ast).unwrap(); - - assert_code_eq(output, quote! { - #[no_mangle] - pub extern "C" fn Foo_abi() -> *mut u8 { - use ::tari_template_abi::{encode_with_len, FunctionDef, TemplateDef, Type, wrap_ptr}; - - let template = TemplateDef { - template_name: "Foo".to_string(), - functions: vec![ - FunctionDef { - name: "no_args_function".to_string(), - arguments: vec![], - output: Type::String, - }, - FunctionDef { - name: "some_args_function".to_string(), - arguments: vec![Type::I8, Type::String], - output: Type::U32, - }, - FunctionDef { - name: "no_return_function".to_string(), - arguments: vec![], - output: Type::Unit, - }, - FunctionDef { - name: "constructor".to_string(), - arguments: vec![], - output: Type::U32, - }, - FunctionDef { - name: "method".to_string(), - arguments: vec![Type::U32], - output: Type::Unit, - } - ], - }; - - let buf = encode_with_len(&template); - wrap_ptr(buf) - } - }); - } - - fn assert_code_eq(a: TokenStream, b: TokenStream) { - assert_eq!(a.to_string(), b.to_string()); - } -} diff --git a/dan_layer/template_macros/src/template/definition.rs b/dan_layer/template_macros/src/template/definition.rs deleted file mode 100644 index 6ca969e74b6..00000000000 --- a/dan_layer/template_macros/src/template/definition.rs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use proc_macro2::TokenStream; -use quote::{format_ident, quote}; - -use crate::ast::TemplateAst; - -pub fn generate_definition(ast: &TemplateAst) -> TokenStream { - let template_name = format_ident!("{}", ast.struct_section.ident); - let template_fields = &ast.struct_section.fields; - let semi_token = &ast.struct_section.semi_token; - let functions = &ast.impl_section.items; - - quote! { - pub mod template { - use super::*; - - #[derive(Decode, Encode)] - pub struct #template_name #template_fields #semi_token - - impl #template_name { - #(#functions)* - } - } - } -} diff --git a/dan_layer/template_macros/src/template/dependencies.rs b/dan_layer/template_macros/src/template/dependencies.rs deleted file mode 100644 index 706cc11431b..00000000000 --- a/dan_layer/template_macros/src/template/dependencies.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use proc_macro2::TokenStream; -use quote::quote; - -/// Returns code that contains global functions and types implicitly available to contract authors -pub fn generate_dependencies() -> TokenStream { - quote! { - use tari_template_lib::template_dependencies::*; - } -} diff --git a/dan_layer/template_macros/src/template/dispatcher.rs b/dan_layer/template_macros/src/template/dispatcher.rs deleted file mode 100644 index 44b57174f75..00000000000 --- a/dan_layer/template_macros/src/template/dispatcher.rs +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use proc_macro2::{Ident, Span, TokenStream}; -use quote::{format_ident, quote}; -use syn::{parse_quote, token::Brace, Block, Expr, ExprBlock, Result}; - -use crate::ast::{FunctionAst, TemplateAst, TypeAst}; - -pub fn generate_dispatcher(ast: &TemplateAst) -> Result { - let dispatcher_function_name = format_ident!("{}_main", ast.struct_section.ident); - let function_names = get_function_names(ast); - let function_blocks = get_function_blocks(ast); - - let output = quote! { - #[no_mangle] - pub extern "C" fn #dispatcher_function_name(call_info: *mut u8, call_info_len: usize) -> *mut u8 { - use ::tari_template_abi::{decode, encode_with_len, CallInfo, wrap_ptr}; - use ::tari_template_lib::set_context_from_call_info; - - if call_info.is_null() { - panic!("call_info is null"); - } - - let call_data = unsafe { Vec::from_raw_parts(call_info, call_info_len, call_info_len) }; - let call_info: CallInfo = decode(&call_data).unwrap(); - - set_context_from_call_info(&call_info); - // TODO: wrap this in a nice macro - engine().emit_log(LogLevel::Debug, format!("Dispatcher called with function {}", call_info.func_name)); - - let result; - match call_info.func_name.as_str() { - #( #function_names => #function_blocks ),*, - _ => panic!("invalid function name") - }; - - wrap_ptr(result) - } - }; - - Ok(output) -} - -fn get_function_names(ast: &TemplateAst) -> Vec { - ast.get_functions().iter().map(|f| f.name.clone()).collect() -} - -fn get_function_blocks(ast: &TemplateAst) -> Vec { - let mut blocks = vec![]; - - for function in ast.get_functions() { - let block = get_function_block(&ast.template_name, function); - blocks.push(block); - } - - blocks -} - -fn get_function_block(template_ident: &Ident, ast: FunctionAst) -> Expr { - let mut args: Vec = vec![]; - let mut stmts = vec![]; - let mut should_set_state = false; - - // encode all arguments of the functions - for (i, input_type) in ast.input_types.into_iter().enumerate() { - let arg_ident = format_ident!("arg_{}", i); - let stmt = match input_type { - // "self" argument - TypeAst::Receiver { mutability } => { - should_set_state = mutability; - args.push(parse_quote! { &mut state }); - vec![ - parse_quote! { - let component = - decode::<::tari_template_lib::models::ComponentInstance>(&call_info.args[#i]) - .unwrap(); - }, - parse_quote! { - let mut state = decode::(&component.state).unwrap(); - }, - ] - }, - // non-self argument - TypeAst::Typed(type_ident) => { - args.push(parse_quote! { #arg_ident }); - vec![parse_quote! { - let #arg_ident = - decode::<#type_ident>(&call_info.args[#i]) - .unwrap(); - }] - }, - }; - stmts.extend(stmt); - } - - // call the user defined function in the template - let function_ident = Ident::new(&ast.name, Span::call_site()); - if ast.is_constructor { - stmts.push(parse_quote! { - let state = template::#template_ident::#function_ident(#(#args),*); - }); - - let template_name_str = template_ident.to_string(); - stmts.push(parse_quote! { - let rtn = engine().instantiate(#template_name_str.to_string(), state); - }); - } else { - stmts.push(parse_quote! { - let rtn = template::#template_ident::#function_ident(#(#args),*); - }); - } - - // encode the result value - stmts.push(parse_quote! { - result = encode_with_len(&rtn); - }); - - // after user function invocation, update the component state - if should_set_state { - stmts.push(parse_quote! { - engine().set_component_state(component.id(), state); - }); - } - - // construct the code block for the function - Expr::Block(ExprBlock { - attrs: vec![], - label: None, - block: Block { - brace_token: Brace { - span: Span::call_site(), - }, - stmts, - }, - }) -} diff --git a/dan_layer/template_macros/src/template/mod.rs b/dan_layer/template_macros/src/template/mod.rs deleted file mode 100644 index 7511d343eda..00000000000 --- a/dan_layer/template_macros/src/template/mod.rs +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2022. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -mod abi; -mod definition; -mod dependencies; -mod dispatcher; - -use proc_macro2::TokenStream; -use quote::quote; -use syn::{parse2, Result}; - -use self::{ - abi::generate_abi, - definition::generate_definition, - dependencies::generate_dependencies, - dispatcher::generate_dispatcher, -}; -use crate::ast::TemplateAst; - -pub fn generate_template(input: TokenStream) -> Result { - let ast = parse2::(input).unwrap(); - - let dependencies = generate_dependencies(); - let definition = generate_definition(&ast); - let abi = generate_abi(&ast)?; - let dispatcher = generate_dispatcher(&ast)?; - - let output = quote! { - #dependencies - - #definition - - #abi - - #dispatcher - }; - - Ok(output) -} - -#[cfg(test)] -mod tests { - use std::str::FromStr; - - use indoc::indoc; - use proc_macro2::TokenStream; - use quote::quote; - - use super::generate_template; - - #[test] - #[allow(clippy::too_many_lines)] - fn test_state() { - let input = TokenStream::from_str(indoc! {" - mod test { - struct State { - value: u32 - } - impl State { - pub fn new() -> Self { - Self { value: 0 } - } - pub fn get(&self) -> u32 { - self.value - } - pub fn set(&mut self, value: u32) { - self.value = value; - } - } - } - "}) - .unwrap(); - - let output = generate_template(input).unwrap(); - - assert_code_eq(output, quote! { - use tari_template_lib::template_dependencies::*; - - pub mod template { - use super::*; - - #[derive(Decode, Encode)] - pub struct State { - value: u32 - } - - impl State { - pub fn new() -> Self { - Self { value: 0 } - } - pub fn get(&self) -> u32 { - self.value - } - pub fn set(&mut self, value: u32) { - self.value = value; - } - } - } - - #[no_mangle] - pub extern "C" fn State_abi() -> *mut u8 { - use ::tari_template_abi::{encode_with_len, FunctionDef, TemplateDef, Type, wrap_ptr}; - - let template = TemplateDef { - template_name: "State".to_string(), - functions: vec![ - FunctionDef { - name: "new".to_string(), - arguments: vec![], - output: Type::U32, - }, - FunctionDef { - name: "get".to_string(), - arguments: vec![Type::U32], - output: Type::U32, - }, - FunctionDef { - name: "set".to_string(), - arguments: vec![Type::U32, Type::U32], - output: Type::Unit, - } - ], - }; - - let buf = encode_with_len(&template); - wrap_ptr(buf) - } - - #[no_mangle] - pub extern "C" fn State_main(call_info: *mut u8, call_info_len: usize) -> *mut u8 { - use ::tari_template_abi::{decode, encode_with_len, CallInfo, wrap_ptr}; - use ::tari_template_lib::set_context_from_call_info; - - if call_info.is_null() { - panic!("call_info is null"); - } - - let call_data = unsafe { Vec::from_raw_parts(call_info, call_info_len, call_info_len) }; - let call_info: CallInfo = decode(&call_data).unwrap(); - - set_context_from_call_info(&call_info); - engine().emit_log(LogLevel::Debug, format!("Dispatcher called with function {}" , call_info.func_name)); - - let result; - match call_info.func_name.as_str() { - "new" => { - let state = template::State::new(); - let rtn = engine().instantiate("State".to_string(), state); - result = encode_with_len(&rtn); - }, - "get" => { - let component = decode::<::tari_template_lib::models::ComponentInstance>(&call_info.args[0usize]).unwrap(); - let mut state = decode::(&component.state).unwrap(); - let rtn = template::State::get(&mut state); - result = encode_with_len(&rtn); - }, - "set" => { - let component = decode::<::tari_template_lib::models::ComponentInstance>(&call_info.args[0usize]).unwrap(); - let mut state = decode::(&component.state).unwrap(); - let arg_1 = decode::(&call_info.args[1usize]).unwrap(); - let rtn = template::State::set(&mut state, arg_1); - result = encode_with_len(&rtn); - engine().set_component_state(component.id(), state); - }, - _ => panic!("invalid function name") - }; - - wrap_ptr(result) - } - }); - } - - fn assert_code_eq(a: TokenStream, b: TokenStream) { - assert_eq!(a.to_string(), b.to_string()); - } -} diff --git a/integration_tests/features/ValidatorNode.feature b/integration_tests/features/ValidatorNode.feature deleted file mode 100644 index 28776a5860b..00000000000 --- a/integration_tests/features/ValidatorNode.feature +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright 2022 The Tari Project -# SPDX-License-Identifier: BSD-3-Clause - -@dan -Feature: Validator Node - @critical - Scenario: Publish contract acceptance - Given I have a seed node NODE1 - And I have wallet WALLET1 connected to all seed nodes - And I mine 9 blocks using wallet WALLET1 on NODE1 - And I wait for wallet WALLET1 to have at least 1000000 uT - And I publish a contract definition DEF1 from file "fixtures/contract_definition.json" on wallet WALLET1 via command line - And I mine 4 blocks using wallet WALLET1 on NODE1 - And I publish a contract constitution from file "fixtures/contract_constitution.json" on wallet WALLET1 via command line - And I mine 4 blocks using wallet WALLET1 on NODE1 - And I have a validator node VN1 connected to base node NODE1 and wallet WALLET1 - When I publish a contract acceptance transaction for contract DEF1 for the validator node VN1 - And I mine 9 blocks using wallet WALLET1 on NODE1 - Then wallet WALLET1 will have a successfully mined contract acceptance transaction for contract DEF1 - - Scenario: Contract constitution auto acceptance - Given I have a seed node NODE1 - And I have wallet WALLET1 connected to all seed nodes - And I mine 9 blocks using wallet WALLET1 on NODE1 - And I wait for wallet WALLET1 to have at least 1000000 uT - And I have a validator node VN1 connected to base node NODE1 and wallet WALLET1 - And validator node VN1 has "constitution_auto_accept" set to true - And validator node VN1 has "constitution_management_polling_interval" set to 5 - And validator node VN1 has "constitution_management_polling_interval_in_seconds" set to 5 - And I publish a contract definition DEF1 from file "fixtures/contract_definition.json" on wallet WALLET1 via command line - And I mine 4 blocks using wallet WALLET1 on NODE1 - When I create a contract constitution COM1 for contract DEF1 from file "fixtures/contract_constitution.json" - And I add VN1 to the validator committee on COM1 - And I publish the contract constitution COM1 on wallet WALLET1 via command line - And I mine 9 blocks using wallet WALLET1 on NODE1 - Then wallet WALLET1 will have a successfully mined contract acceptance transaction for contract DEF1 - - @critical - Scenario: Publish contract update proposal acceptance - Given I have a seed node NODE1 - And I have wallet WALLET1 connected to all seed nodes - And I mine 9 blocks using wallet WALLET1 on NODE1 - And I wait for wallet WALLET1 to have at least 1000000 uT - And I publish a contract definition DEF1 from file "fixtures/contract_definition.json" on wallet WALLET1 via command line - And I mine 4 blocks using wallet WALLET1 on NODE1 - And I publish a contract constitution from file "fixtures/contract_constitution.json" on wallet WALLET1 via command line - And I mine 4 blocks using wallet WALLET1 on NODE1 - And I publish a contract update proposal from file "fixtures/contract_update_proposal.json" on wallet WALLET1 via command line - And I mine 4 blocks using wallet WALLET1 on NODE1 - And I have a validator node VN1 connected to base node NODE1 and wallet WALLET1 - When I publish a contract update proposal acceptance transaction for the validator node VN1 - And I mine 9 blocks using wallet WALLET1 on NODE1 - Then wallet WALLET1 will have a successfully mined contract update proposal for contract DEF1 \ No newline at end of file diff --git a/integration_tests/features/support/validator_node_steps.js b/integration_tests/features/support/validator_node_steps.js deleted file mode 100644 index 6082dfc7870..00000000000 --- a/integration_tests/features/support/validator_node_steps.js +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2021. The Tari Project -// -// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -// following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following -// disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the -// following disclaimer in the documentation and/or other materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote -// products derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -const { Given, Then } = require("@cucumber/cucumber"); -const { expect } = require("chai"); -const { findUtxoWithOutputMessage } = require("../../helpers/util"); - -Given( - "I have a validator node {word} connected to base node {word} and wallet {word}", - { timeout: 20 * 1000 }, - async function (vn_name, base_node_name, wallet_name) { - let vn = await this.createValidatorNode( - vn_name, - base_node_name, - wallet_name - ); - await this.addDanNode(vn_name, vn); - } -); - -Then( - "validator node {word} has {string} set to {word}", - { timeout: 20 * 1000 }, - async function (vn_name, option_name, option_value) { - let vn = this.getNode(vn_name); - await vn.stop(); - - vn.options["validator_node." + option_name] = option_value; - - await vn.startNew(); - } -); - -Then( - "I publish a contract acceptance transaction for contract {word} for the validator node {word}", - { timeout: 20 * 1000 }, - async function (contract_name, vn_name) { - let dan_node = this.getNode(vn_name); - let grpc_dan_node = await dan_node.createGrpcClient(); - let response = await grpc_dan_node.publishContractAcceptance( - await this.fetchContract(contract_name) - ); - expect(response.status).to.be.equal("Accepted"); - console.debug({ response }); - } -); - -Then( - "I publish a contract update proposal acceptance transaction for the validator node {word}", - { timeout: 120 * 1000 }, - async function (vn_name) { - let dan_node = this.getNode(vn_name); - let grpc_dan_node = await dan_node.createGrpcClient(); - let response = await grpc_dan_node.publishContractUpdateProposalAcceptance( - "a58fb2adefcc40242f20f2d896e14451549dd60839fee78a7bd40ba2cc0a0e91", // contract_id - 0 // proposal_id - ); - expect(response.status).to.be.equal("Accepted"); - console.debug({ response }); - } -); - -Then( - "wallet {word} will have a successfully mined contract acceptance transaction for contract {word}", - { timeout: 40 * 1000 }, - async function (wallet_name, contract_name) { - let wallet = await this.getWallet(wallet_name); - let contract_id = await this.fetchContract(contract_name); - let message = `Contract acceptance for contract with id=${contract_id}`; - - let utxos = await findUtxoWithOutputMessage(wallet, message); - expect(utxos.length).to.equal(1); - } -); - -Then( - "wallet {word} will have a successfully mined contract update proposal for contract {word}", - { timeout: 40 * 1000 }, - async function (wallet_name, contract_name) { - let wallet = await this.getWallet(wallet_name); - let contract_id = await this.fetchContract(contract_name); - let message = `Contract update proposal acceptance for contract_id=${contract_id} and proposal_id=0`; - - let utxos = await findUtxoWithOutputMessage(wallet, message); - expect(utxos.length).to.equal(1); - } -); diff --git a/integration_tests/features/support/world.js b/integration_tests/features/support/world.js index 1758d04d5e3..843509d8840 100644 --- a/integration_tests/features/support/world.js +++ b/integration_tests/features/support/world.js @@ -9,7 +9,6 @@ const { } = require("@cucumber/cucumber"); const BaseNodeProcess = require("../../helpers/baseNodeProcess"); -const ValidatorNodeProcess = require("../../helpers/validatorNodeProcess"); const MergeMiningProxyProcess = require("../../helpers/mergeMiningProxyProcess"); const WalletProcess = require("../../helpers/walletProcess"); const WalletFFIClient = require("../../helpers/walletFFIClient"); @@ -124,28 +123,6 @@ class CustomWorld { return new BaseNodeProcess(name, false, options, this.logFilePathBaseNode); } - async createValidatorNode(vn_name, base_node_name, wallet_name) { - const baseNode = this.getNode(base_node_name); - const walletNode = this.getWallet(wallet_name); - - const baseNodeGrpcAddress = `127.0.0.1:${baseNode.getGrpcPort()}`; - const walletGrpcAddress = `127.0.0.1:${walletNode.getGrpcPort()}`; - - let vn = new ValidatorNodeProcess( - vn_name, - false, - [], - this.logFilePathBaseNode, - undefined, - baseNodeGrpcAddress, - walletGrpcAddress - ); - - await vn.startNew(); - - return vn; - } - async createAndAddNode(name, addresses) { console.log(`Creating node ${name} connected to ${addresses}`); const node = this.createNode(name); @@ -752,10 +729,6 @@ BeforeAll({ timeout: 2400000 }, async function () { await baseNode.init(); await baseNode.compile(); - const danNode = new ValidatorNodeProcess("compile"); - console.log("Compiling validator node..."); - await danNode.compile(); - const wallet = new WalletProcess("compile"); console.log("Compiling wallet..."); await wallet.init(); @@ -783,19 +756,6 @@ BeforeAll({ timeout: 2400000 }, async function () { console.log("Compiling miner..."); await miningNode.init(1, 1, 1, 1, true, 1); await miningNode.compile(); - - const vn = new ValidatorNodeProcess( - "compile", - false, - {}, - null, - null, - "127.0.0.1:9999", - "127.0.0.1:9998" - ); - console.log("Compiling validator node..."); - await vn.compile(); - console.log("Compiling wallet FFI..."); await InterfaceFFI.compile(); console.log("Finished compilation."); diff --git a/integration_tests/helpers/validatorNodeClient.js b/integration_tests/helpers/validatorNodeClient.js deleted file mode 100644 index c65ac5c4db8..00000000000 --- a/integration_tests/helpers/validatorNodeClient.js +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -const grpc = require("@grpc/grpc-js"); -const protoLoader = require("@grpc/proto-loader"); -const { - tryConnect, - convertHexStringToVec, - convertStringToVec, -} = require("./util"); -const grpcPromise = require("grpc-promise"); - -class ValidatorNodeClient { - constructor() { - this.client = null; - this.blockTemplates = {}; - } - - async connect(port) { - const PROTO_PATH = - __dirname + - "/../../applications/tari_app_grpc/proto/validator_node.proto"; - const packageDefinition = protoLoader.loadSync(PROTO_PATH, { - keepCase: true, - longs: String, - enums: String, - defaults: true, - oneofs: true, - }); - const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); - const tari = protoDescriptor.tari.rpc; - this.client = await tryConnect( - () => - new tari.ValidatorNode( - "127.0.0.1:" + port, - grpc.credentials.createInsecure() - ) - ); - - grpcPromise.promisifyAll(this.client, { - metadata: new grpc.Metadata(), - }); - } - - static async create(port) { - const client = new ValidatorNodeClient(); - await client.connect(port); - return client; - } - - executeInstruction(asset_public_key, method, metadata, token, signature, id) { - console.log( - `Executing instruction for asset ${asset_public_key} / token ${token} via method ${method} with metadata ${metadata} ` - ); - return this.client.executeInstruction().sendMessage({ - asset_public_key: convertHexStringToVec(asset_public_key), - method, - args: [convertStringToVec(metadata)], - token_id: convertHexStringToVec(token), - signature, - id, - }); - } - - publishContractAcceptance(contract_id) { - console.log( - `Publishing contract acceptance for contract_id = ${contract_id} ` - ); - return this.client.publishContractAcceptance().sendMessage({ - contract_id: convertHexStringToVec(contract_id), - }); - } - - publishContractUpdateProposalAcceptance(contract_id, proposal_id) { - console.log( - `Publishing contract update proposal acceptance for contract_id = ${contract_id} ` - ); - return this.client.publishContractUpdateProposalAcceptance().sendMessage({ - contract_id: convertHexStringToVec(contract_id), - proposal_id, - }); - } -} - -module.exports = ValidatorNodeClient; diff --git a/integration_tests/helpers/validatorNodeProcess.js b/integration_tests/helpers/validatorNodeProcess.js deleted file mode 100644 index 267397a9d50..00000000000 --- a/integration_tests/helpers/validatorNodeProcess.js +++ /dev/null @@ -1,321 +0,0 @@ -// Copyright 2022 The Tari Project -// SPDX-License-Identifier: BSD-3-Clause - -const { spawn } = require("child_process"); -const { expect } = require("chai"); -const fs = require("fs"); -const path = require("path"); -const ValidatorNodeClient = require("./validatorNodeClient"); -const { getFreePort } = require("./util"); -const dateFormat = require("dateformat"); -const { createEnv } = require("./config"); -const JSON5 = require("json5"); - -let outputProcess; -class ValidatorNodeProcess { - constructor( - name, - excludeTestEnvars, - options, - logFilePath, - nodeFile, - baseNodeAddress, - walletAddress - ) { - this.name = name; - this.logFilePath = logFilePath ? path.resolve(logFilePath) : logFilePath; - this.nodeFile = nodeFile; - this.options = Object.assign( - { - baseDir: "./temp/base_nodes", - }, - options || {} - ); - this.excludeTestEnvars = excludeTestEnvars; - this.baseNodeAddress = baseNodeAddress; - this.walletAddress = walletAddress; - } - - async init() { - this.port = await getFreePort(); - this.grpcPort = await getFreePort(); - this.name = `ValidatorNode${this.port}-${this.name}`; - this.nodeFile = this.nodeFile || "validator_node_id.json"; - - let instance = 0; - do { - this.baseDir = `${this.options.baseDir}/${dateFormat( - new Date(), - "yyyymmddHHMM" - )}/${instance}/${this.name}`; - // Some tests failed during testing because the next base node process started in the previous process - // directory therefore using the previous blockchain database - if (fs.existsSync(this.baseDir)) { - instance++; - } else { - fs.mkdirSync(this.baseDir, { recursive: true }); - break; - } - } while (fs.existsSync(this.baseDir)); - const args = ["--base-path", "."]; - if (this.logFilePath) { - args.push("--log-config", this.logFilePath); - } - - await this.compile(); - // await this.run(cmd, args); - } - - async compile() { - if (!outputProcess) { - await new Promise((resolve, reject) => { - const ps = spawn( - "cargo", - [ - "build", - "--release", - "--bin", - "tari_validator_node", - "-Z", - "unstable-options", - "--out-dir", - process.cwd() + "/temp/out", - ], - { - cwd: this.baseDir, - // shell: true, - env: { ...process.env }, - } - ); - - ps.on("close", (code) => { - const ps = this.ps; - this.ps = null; - if (code) { - reject(`child process exited with code ${code}`); - } else { - resolve(ps); - } - }); - - expect(ps.error).to.be.an("undefined"); - this.ps = ps; - }); - - outputProcess = process.cwd() + "/temp/out/tari_validator_node"; - } - return outputProcess; - } - - hasAssetData() { - return fs.existsSync(this.baseDir + "/localnet/asset_data"); - } - - ensureNodeInfo() { - for (let i = 0; i < 100; i++) { - if (fs.existsSync(this.baseDir + "/" + this.nodeFile)) { - break; - } - } - if (!fs.existsSync(this.baseDir + "/" + this.nodeFile)) { - throw new Error( - `Node id file not found ${this.baseDir}/${this.nodeFile}` - ); - } - - this.nodeInfo = JSON5.parse( - fs.readFileSync(this.baseDir + "/" + this.nodeFile, "utf8") - ); - } - - peerAddress() { - this.ensureNodeInfo(); - const addr = this.nodeInfo.public_key + "::" + this.nodeInfo.public_address; - return addr; - } - - getPubKey() { - this.ensureNodeInfo(); - return this.nodeInfo.public_key; - } - - setPeerSeeds(addresses) { - this.peerSeeds = addresses.join(","); - } - - setForceSyncPeers(addresses) { - this.forceSyncPeers = addresses.join(","); - } - - setCommittee(committee) { - this.committee = committee.join(","); - } - - getGrpcAddress() { - const address = "/ip4/127.0.0.1/tcp/" + this.grpcPort; - console.log("Validator Node GRPC Address:", address); - return address; - } - - run(cmd, args) { - return new Promise((resolve, reject) => { - if (!fs.existsSync(this.baseDir + "/log")) { - fs.mkdirSync(this.baseDir + "/log", { recursive: true }); - } - - // to avoid writing permission errors, we copy the reference identity file to the temp folder - let identity_file_name = "validator_node_id.json"; - let identity_source_path = path.resolve( - `./fixtures/${identity_file_name}` - ); - let identity_destination_path = path.resolve( - `${this.baseDir}/${identity_file_name}` - ); - fs.copyFile(identity_source_path, identity_destination_path, (err) => { - if (err) { - console.log( - "Error Found while copying validator identity file to temp folder: ", - err - ); - throw err; - } - console.log("Validator identity file was copied to destination"); - fs.chmod(identity_destination_path, 0o600, (err) => { - if (err) { - console.log( - "Error Found while changing the permissions of the validator indentity file: ", - err - ); - throw err; - } - console.log( - "Validator identity file permissions successfully modified" - ); - }); - }); - - let envs = []; - if (!this.excludeTestEnvars) { - envs = this.getOverrides(); - } - - let customArgs = { - "validator_node.p2p.transport.type": "tcp", - }; - if (this.baseNodeAddress) { - customArgs["validator_node.base_node_grpc_address"] = - this.baseNodeAddress; - } - if (this.baseNodeAddress) { - customArgs["validator_node.wallet_grpc_address"] = this.walletAddress; - } - if (this.baseNodeAddress) { - customArgs["validator_node.grpc_address"] = this.getGrpcAddress(); - } - Object.keys(this.options).forEach((k) => { - if (k.startsWith("validator_node.")) { - customArgs[k] = this.options[k]; - } - }); - - Object.keys(customArgs).forEach((k) => { - args.push("-p"); - args.push(`${k}=${customArgs[k]}`); - }); - - const ps = spawn(cmd, args, { - cwd: this.baseDir, - // shell: true, - env: { ...process.env, ...envs }, - }); - - ps.stdout.on("data", (data) => { - fs.appendFileSync(`${this.baseDir}/log/stdout.log`, data.toString()); - if ( - data - .toString() - .toUpperCase() - .match(/STARTING GRPC/) - ) { - resolve(ps); - } - }); - ps.stderr.on("data", (data) => { - console.error(`stderr: ${data}`); - fs.appendFileSync(`${this.baseDir}/log/stderr.log`, data.toString()); - }); - - ps.on("close", (code) => { - const ps = this.ps; - this.ps = null; - if (code) { - if (code == 101) { - resolve(ps); // Validator node will fail, because of the missing committee section, but that's okay. - } else { - console.log(`child process exited with code ${code}`); - reject(`child process exited with code ${code}`); - } - } else { - resolve(ps); - } - }); - - expect(ps.error).to.be.an("undefined"); - this.ps = ps; - }); - } - - async startNew() { - await this.init(); - const start = await this.start(); - return start; - } - - async startAndConnect() { - await this.startNew(); - return await this.createGrpcClient(); - } - - async start(opts = []) { - const args = ["--base-path", "."]; - if (this.logFilePath) { - args.push("--log-config", this.logFilePath); - } - args.push(...opts); - return await this.run(await this.compile(), args); - } - - stop() { - return new Promise((resolve) => { - if (!this.ps) { - return resolve(); - } - this.ps.on("close", (code) => { - if (code) { - console.log(`child process exited with code ${code}`); - } - resolve(); - }); - this.ps.kill("SIGINT"); - }); - } - - async createGrpcClient() { - return await ValidatorNodeClient.create(this.grpcPort); - } - - getOverrides() { - return createEnv({ - network: "localnet", - validatorNodeGrpcAddress: this.getGrpcAddress(), - baseNodeGrpcAddress: this.baseNodeAddress, - walletGrpcAddress: this.walletAddress, - nodeFile: this.nodeFile, - options: this.options, - peerSeeds: this.peerSeeds, - forceSyncPeers: this.forceSyncPeers, - }); - } -} - -module.exports = ValidatorNodeProcess;