diff --git a/.github/workflows/crates.yml b/.github/workflows/crates.yml index 52c8b0c423..1d9ea9c018 100644 --- a/.github/workflows/crates.yml +++ b/.github/workflows/crates.yml @@ -10,7 +10,7 @@ jobs: steps: - uses: hecrj/setup-rust-action@v1 with: - rust-version: 'nightly-2020-08-20' + rust-version: 'nightly-2020-12-29' targets: 'wasm32-unknown-unknown' - name: Checkout the source code uses: actions/checkout@master diff --git a/.github/workflows/crates_frame.yml b/.github/workflows/crates_frame.yml index aa8a8bf46d..56b38afb98 100644 --- a/.github/workflows/crates_frame.yml +++ b/.github/workflows/crates_frame.yml @@ -8,7 +8,7 @@ jobs: steps: - uses: hecrj/setup-rust-action@v1 with: - rust-version: 'nightly-2020-08-20' + rust-version: 'nightly-2020-12-29' targets: 'wasm32-unknown-unknown' - name: Checkout the source code uses: actions/checkout@master diff --git a/.github/workflows/dockerpush.yml b/.github/workflows/dockerpush.yml index ed6bd9507b..d431813027 100644 --- a/.github/workflows/dockerpush.yml +++ b/.github/workflows/dockerpush.yml @@ -12,7 +12,7 @@ jobs: steps: - uses: hecrj/setup-rust-action@v1 with: - rust-version: 'nightly-2020-08-20' + rust-version: 'nightly-2020-12-29' targets: 'wasm32-unknown-unknown' - name: Checkout the source code uses: actions/checkout@master diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 08e77ece36..d141077d93 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -8,6 +8,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macOS-latest, windows-latest] + steps: - name: Install LLVM (windows only) if: runner.os == 'Windows' @@ -15,7 +16,7 @@ jobs: - uses: hecrj/setup-rust-action@v1 with: - rust-version: 'nightly-2020-08-20' + rust-version: 'nightly-2020-12-29' targets: 'wasm32-unknown-unknown' - name: Checkout the source code @@ -26,38 +27,11 @@ jobs: - name: Check targets are installed correctly run: rustup target list --installed - - name: Install build tools - run: cargo install --git https://github.com/alexcrichton/wasm-gc --force - - name: Run all tests run: cargo test --all - name: Build optimized binary - run: cargo build --release --verbose - - - name: Upload binary archive into IPFS - if: runner.os != 'Windows' - run: | - cd target/release - tar cfJ plasm-node-${{ matrix.os }}-x86_64.tar.xz plasm-node - curl "https://ipfs.infura.io:5001/api/v0/add" -F file=@plasm-node-${{ matrix.os }}-x86_64.tar.xz - - uses: actions/upload-artifact@master - if: runner.os != 'Windows' - with: - name: plasm-node-${{ matrix.os }}-x86_64.tar.xz - path: target/release/plasm-node-${{ matrix.os }}-x86_64.tar.xz - - - name: Upload binary archive into IPFS (windows only) - if: runner.os == 'Windows' - run: | - cd target/release - tar czf plasm-node-${{ matrix.os }}-x86_64.tar.gz plasm-node.exe - curl "https://ipfs.infura.io:5001/api/v0/add" -F file=@plasm-node-${{ matrix.os }}-x86_64.tar.gz - - uses: actions/upload-artifact@master - if: runner.os == 'Windows' - with: - name: plasm-node-${{ matrix.os }}-x86_64.tar.gz - path: target/release/plasm-node-${{ matrix.os }}-x86_64.tar.gz + run: cargo build --release --locked nix: runs-on: ubuntu-latest diff --git a/.gitmodules b/.gitmodules index e3f264ce80..3d2edc953d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ [submodule "vendor/frontier"] path = vendor/frontier - url = https://github.com/staketechnologies/frontier.git + url = https://github.com/PlasmNetwork/frontier.git diff --git a/Cargo.lock b/Cargo.lock index 451dad4476..2281c7f55d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -21,9 +21,9 @@ dependencies = [ [[package]] name = "adler" -version = "0.2.3" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee2a4ec343196209d6594e19543ae87a39f96d5534d7174822a3ad825dd6ed7e" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "aead" @@ -40,22 +40,11 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd2bc6d3f370b5666245ff421e231cba4353df936e26986d2918e61a8fd6aef6" dependencies = [ - "aes-soft 0.5.0", - "aesni 0.8.0", + "aes-soft", + "aesni", "block-cipher", ] -[[package]] -name = "aes" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "884391ef1066acaa41e766ba8f596341b96e93ce34f9a43e7d24bf0a0eaf0561" -dependencies = [ - "aes-soft 0.6.4", - "aesni 0.10.0", - "cipher", -] - [[package]] name = "aes-gcm" version = "0.7.0" @@ -63,26 +52,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0301c9e9c443494d970a07885e8cf3e587bae8356a1d5abd0999068413f7205f" dependencies = [ "aead", - "aes 0.5.0", + "aes", "block-cipher", "ghash", "subtle 2.4.0", ] -[[package]] -name = "aes-gcm" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5278b5fabbb9bd46e24aa69b2fdea62c99088e0a950a9be40e3e0101298f88da" -dependencies = [ - "aead", - "aes 0.6.0", - "cipher", - "ctr", - "ghash", - "subtle 2.4.0", -] - [[package]] name = "aes-soft" version = "0.5.0" @@ -90,17 +65,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63dd91889c49327ad7ef3b500fd1109dbd3c509a03db0d4a9ce413b79f575cb6" dependencies = [ "block-cipher", - "byteorder 1.4.2", - "opaque-debug 0.3.0", -] - -[[package]] -name = "aes-soft" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be14c7498ea50828a38d0e24a765ed2effe92a705885b57d029cd67d45744072" -dependencies = [ - "cipher", + "byteorder", "opaque-debug 0.3.0", ] @@ -114,31 +79,6 @@ dependencies = [ "opaque-debug 0.3.0", ] -[[package]] -name = "aesni" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea2e11f5e94c2f7d386164cc2aa1f97823fed6f259e486940a71c174dd01b0ce" -dependencies = [ - "cipher", - "opaque-debug 0.3.0", -] - -[[package]] -name = "ahash" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29661b60bec623f0586702976ff4d0c9942dcb6723161c2df0eea78455cfedfb" -dependencies = [ - "const-random", -] - -[[package]] -name = "ahash" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8fd72866655d1904d6b0997d0b07ba561047d070fbe29de039031c641b61217" - [[package]] name = "ahash" version = "0.4.7" @@ -154,17 +94,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "alga" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f823d037a7ec6ea2197046bafd4ae150e6bc36f9ca347404f46a46823fa84f2" -dependencies = [ - "approx", - "num-complex", - "num-traits", -] - [[package]] name = "ansi_term" version = "0.11.0" @@ -198,12 +127,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "arc-swap" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4d7d63395147b81a9e570bcc6243aaf71c017bd666d4909cfef0085bdda8d73" - [[package]] name = "arrayref" version = "0.3.6" @@ -240,31 +163,21 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d0864d84b8e07b145449be9a8537db86bf9de5ce03b913214694643b4743502" dependencies = [ - "quote 1.0.8", - "syn 1.0.60", + "quote", + "syn", ] [[package]] name = "async-channel" -version = "1.5.1" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59740d83946db6a5af71ae25ddf9562c2b176b2ca42cf99a455f09f4a220d6b9" +checksum = "2114d64672151c0c5eaa5e131ec84a74f06e1e559830dabba01ca30605d66319" dependencies = [ "concurrent-queue", "event-listener", "futures-core", ] -[[package]] -name = "async-dup" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7427a12b8dc09291528cfb1da2447059adb4a257388c2acd6497a79d55cf6f7c" -dependencies = [ - "futures-io", - "simple-mutex", -] - [[package]] name = "async-executor" version = "1.4.0" @@ -275,7 +188,7 @@ dependencies = [ "concurrent-queue", "fastrand", "futures-lite", - "once_cell 1.5.2", + "once_cell", "vec-arena", ] @@ -292,25 +205,7 @@ dependencies = [ "blocking", "futures-lite", "num_cpus", - "once_cell 1.5.2", -] - -[[package]] -name = "async-h1" -version = "2.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e9e2a9745d9cd0d92ed7641ce4d07568985762f92633260f0afe8ac7917d9d7" -dependencies = [ - "async-channel", - "async-dup", - "async-std", - "byte-pool", - "futures-core", - "http-types", - "httparse", - "lazy_static", - "log", - "pin-project 1.0.5", + "once_cell", ] [[package]] @@ -325,7 +220,7 @@ dependencies = [ "libc", "log", "nb-connect", - "once_cell 1.5.2", + "once_cell", "parking", "polling", "vec-arena", @@ -362,46 +257,11 @@ dependencies = [ "cfg-if 1.0.0", "event-listener", "futures-lite", - "once_cell 1.5.2", + "once_cell", "signal-hook", "winapi 0.3.9", ] -[[package]] -name = "async-session" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "345022a2eed092cd105cc1b26fd61c341e100bd5fcbbd792df4baf31c2cc631f" -dependencies = [ - "anyhow", - "async-std", - "async-trait", - "base64 0.12.3", - "bincode", - "blake3", - "chrono", - "hmac 0.8.1", - "kv-log-macro", - "rand 0.7.3", - "serde", - "serde_json", - "sha2 0.9.3", -] - -[[package]] -name = "async-sse" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53bba003996b8fd22245cd0c59b869ba764188ed435392cf2796d03b805ade10" -dependencies = [ - "async-channel", - "async-std", - "http-types", - "log", - "memchr", - "pin-project-lite 0.1.11", -] - [[package]] name = "async-std" version = "1.9.0" @@ -413,7 +273,7 @@ dependencies = [ "async-io", "async-lock", "async-process", - "crossbeam-utils 0.8.1", + "crossbeam-utils 0.8.3", "futures-channel", "futures-core", "futures-io", @@ -423,8 +283,8 @@ dependencies = [ "log", "memchr", "num_cpus", - "once_cell 1.5.2", - "pin-project-lite 0.2.4", + "once_cell", + "pin-project-lite 0.2.5", "pin-utils", "slab", "wasm-bindgen-futures", @@ -437,33 +297,50 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e91831deabf0d6d7ec49552e489aed63b7456a7a3c46cff62adad428110b0af0" [[package]] -name = "async-tls" -version = "0.8.0" +name = "async-trait" +version = "0.1.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df097e3f506bec0e1a24f06bb3c962c228f36671de841ff579cb99f371772634" +checksum = "8d3a45e77e34375a7923b1e8febb049bb011f064714a8e17a1a616fef01da13d" dependencies = [ - "futures 0.3.12", - "rustls", - "webpki", - "webpki-roots 0.19.0", + "proc-macro2", + "quote", + "syn", ] [[package]] -name = "async-trait" -version = "0.1.42" +name = "asynchronous-codec" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d3a45e77e34375a7923b1e8febb049bb011f064714a8e17a1a616fef01da13d" +checksum = "fb4401f0a3622dad2e0763fa79e0eb328bc70fb7dccfdd645341f00d671247d6" +dependencies = [ + "bytes 1.0.1", + "futures-sink", + "futures-util", + "memchr", + "pin-project-lite 0.2.5", +] + +[[package]] +name = "asynchronous-codec" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0de5164e5edbf51c45fb8c2d9664ae1c095cce1b265ecf7569093c0d66ef690" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "bytes 1.0.1", + "futures-sink", + "futures-util", + "memchr", + "pin-project-lite 0.2.5", ] [[package]] name = "atomic" -version = "0.4.6" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64f46ca51dca4837f1520754d1c8c36636356b81553d928dc9c177025369a06e" +checksum = "c3410529e8288c463bedb5930f82833bc0c90e5d2fe639a56582a4d09220b281" +dependencies = [ + "autocfg", +] [[package]] name = "atomic-waker" @@ -482,12 +359,6 @@ dependencies = [ "winapi 0.3.9", ] -[[package]] -name = "autocfg" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d49d90015b3c36167a20fe2810c5cd875ad504b39cff3d4eae7977e6b7c1cb2" - [[package]] name = "autocfg" version = "1.0.1" @@ -504,7 +375,7 @@ dependencies = [ "cfg-if 1.0.0", "libc", "miniz_oxide", - "object", + "object 0.23.0", "rustc-demangle", ] @@ -520,12 +391,6 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5024ee8015f02155eee35c711107ddd9a9bf3cb689cf2a9089c97e79b6e1ae83" -[[package]] -name = "base64" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b41b7ea54a0c9d92199de89e20e58d49f02f8e699814ef3fdf266f6f748d15c7" - [[package]] name = "base64" version = "0.12.3" @@ -540,11 +405,11 @@ checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" [[package]] name = "bincode" -version = "1.3.1" +version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f30d3a39baa26f9651f17b375061f3233dde33424a8b72b0dbe93a68a0bc896d" +checksum = "d175dfa69e619905c4c3cdb7c3c203fa3bdd5d51184e3afdb2742c0280493772" dependencies = [ - "byteorder 1.4.2", + "byteorder", "serde", ] @@ -564,27 +429,12 @@ dependencies = [ "lazycell", "log", "peeking_take_while", - "proc-macro2 1.0.24", - "quote 1.0.8", + "proc-macro2", + "quote", "regex", "rustc-hash", "shlex", - "which", -] - -[[package]] -name = "bip39" -version = "0.6.0-beta.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7059804e226b3ac116519a252d7f5fb985a5ccc0e93255e036a5f7e7283323f4" -dependencies = [ - "failure", - "hashbrown 0.1.8", - "hmac 0.7.1", - "once_cell 0.1.8", - "pbkdf2", - "rand 0.6.5", - "sha2 0.8.2", + "which 3.1.1", ] [[package]] @@ -593,20 +443,16 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" -[[package]] -name = "bitmask" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5da9b3d9f6f585199287a473f4f8dfab6566cf827d15c00c219f53c645687ead" - [[package]] name = "bitvec" -version = "0.17.4" +version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41262f11d771fd4a61aa3ce019fca363b4b6c282fca9da2a31186d3965a47a5c" +checksum = "f5011ffc90248764d7005b0e10c7294f5aa1bd87d9dd7248f4ad475b347c294d" dependencies = [ - "either", + "funty", "radium", + "tap", + "wyz", ] [[package]] @@ -675,7 +521,7 @@ checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" dependencies = [ "block-padding 0.1.5", "byte-tools", - "byteorder 1.4.2", + "byteorder", "generic-array 0.12.3", ] @@ -724,15 +570,9 @@ dependencies = [ "atomic-waker", "fastrand", "futures-lite", - "once_cell 1.5.2", + "once_cell", ] -[[package]] -name = "bs58" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "476e9cd489f9e121e02ffa6014a8ef220ecb15c05ed23fc34cca13925dc283fb" - [[package]] name = "bs58" version = "0.4.0" @@ -741,34 +581,24 @@ checksum = "771fe0050b883fcc3ea2359b1a96bcfbc090b7116eae7c3c512c7a083fdf23d3" [[package]] name = "bstr" -version = "0.2.14" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "473fc6b38233f9af7baa94fb5852dca389e3d95b8e21c8e3719301462c5d9faf" +checksum = "a40b47ad93e1a5404e6c18dec46b628214fee441c70f4ab5d6942142cc268a3d" dependencies = [ "memchr", ] [[package]] name = "bumpalo" -version = "3.6.0" +version = "3.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "099e596ef14349721d9016f6b80dd3419ea1bf289ab9b44df8e4dfd3a005d5d9" - -[[package]] -name = "byte-pool" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38e98299d518ec351ca016363e0cbfc77059dcd08dfa9700d15e405536097a" -dependencies = [ - "crossbeam-queue", - "stable_deref_trait", -] +checksum = "63396b8a4b9de3f4fdfb320ab6080762242f66a8ef174c49d8e19b674db4cdbe" [[package]] name = "byte-slice-cast" -version = "0.3.5" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0a5e3906bcbf133e33c1d4d95afc664ad37fbdb9f6568d8043e7ea8c27d93d3" +checksum = "65c1bf4a04a88c54f589125563643d773f3254b5c38571395e2b591c693bbc81" [[package]] name = "byte-tools" @@ -778,15 +608,9 @@ checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" [[package]] name = "byteorder" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fc10e8cc6b2580fda3f36eb6dc5316657f812a3df879a44a66fc9f0fdbc4855" - -[[package]] -name = "byteorder" -version = "1.4.2" +version = "1.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae44d1a3d5a19df61dd0c8beb138458ac2a53a7ac09eba97d55592540004306b" +checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" [[package]] name = "bytes" @@ -794,7 +618,7 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "206fdffcfa2df7cbe15601ef46c813fce0965eb3286db6b56c583b814b51c81c" dependencies = [ - "byteorder 1.4.2", + "byteorder", "either", "iovec", ] @@ -811,12 +635,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b700ce4376041dcd0a327fd0097c41095743c4c8af8887265942faf1100bd040" -[[package]] -name = "c_linked_list" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4964518bd3b4a8190e832886cdc0da9794f12e8e6c1613a9e90ff331c4c8724b" - [[package]] name = "cache-padded" version = "1.1.1" @@ -825,11 +643,11 @@ checksum = "631ae5198c9be5e753e5cc215e1bd73c2b466a3565173db433f52bb9d3e66dba" [[package]] name = "cc" -version = "1.0.41" +version = "1.0.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8dae9c4b8fedcae85592ba623c4fd08cfdab3e3b72d6df780c6ead964a69bfff" +checksum = "e3c69b077ad434294d3ce9f1f6143a2a4b89a8a2d54ef813d85003a4fd1137fd" dependencies = [ - "rayon", + "jobserver", ] [[package]] @@ -885,11 +703,21 @@ dependencies = [ "libc", "num-integer", "num-traits", - "serde", - "time 0.1.44", + "time", "winapi 0.3.9", ] +[[package]] +name = "cid" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff0e3bc0b6446b3f9663c1a6aba6ef06c5aeaa1bc92bd18077be337198ab9768" +dependencies = [ + "multibase", + "multihash", + "unsigned-varint 0.5.1", +] + [[package]] name = "cipher" version = "0.2.5" @@ -905,7 +733,7 @@ version = "0.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe6837df1d5cba2397b835c8530f51723267e16abbf83892e9e5af4f0e5dd10a" dependencies = [ - "glob 0.3.0", + "glob", "libc", "libloading", ] @@ -934,15 +762,6 @@ dependencies = [ "bitflags", ] -[[package]] -name = "cmake" -version = "0.1.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb6210b637171dfba4cda12e579ac6dc73f5165ad56133e5d72ef3131f320855" -dependencies = [ - "cc", -] - [[package]] name = "concurrent-queue" version = "1.2.2" @@ -952,74 +771,19 @@ dependencies = [ "cache-padded", ] -[[package]] -name = "const-random" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f590d95d011aa80b063ffe3253422ed5aa462af4e9867d43ce8337562bac77c4" -dependencies = [ - "const-random-macro", - "proc-macro-hack", -] - -[[package]] -name = "const-random-macro" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "615f6e27d000a2bffbc7f2f6a8669179378fa27ee4d0a509e985dfc0a7defb40" -dependencies = [ - "getrandom 0.2.2", - "lazy_static", - "proc-macro-hack", - "tiny-keccak 2.0.2", -] - -[[package]] -name = "const_fn" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28b9d6de7f49e22cf97ad17fc4036ece69300032f45f78f30b4a4482cdc3f4a6" - [[package]] name = "constant_time_eq" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" -[[package]] -name = "cookie" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "784ad0fbab4f3e9cef09f20e0aea6000ae08d2cb98ac4c0abc53df18803d702f" -dependencies = [ - "aes-gcm 0.8.0", - "base64 0.12.3", - "hkdf", - "hmac 0.10.1", - "percent-encoding 2.1.0", - "rand 0.7.3", - "sha2 0.9.3", - "time 0.2.25", - "version_check", -] - [[package]] name = "core-foundation" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57d24c7a13c43e870e37c1556b74555437870a04514f7685f5b354e090567171" dependencies = [ - "core-foundation-sys 0.7.0", - "libc", -] - -[[package]] -name = "core-foundation" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a89e2ae426ea83155dccf10c0fa6b1463ef6d5fcb44cee0b224a408fa640a62" -dependencies = [ - "core-foundation-sys 0.8.2", + "core-foundation-sys", "libc", ] @@ -1030,10 +794,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b3a71ab494c0b5b860bdc8407ae08978052417070c2ced38573a9157ad75b8ac" [[package]] -name = "core-foundation-sys" -version = "0.8.2" +name = "cpp_demangle" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea221b5284a47e40033bf9b66f35f984ec0ea2931eb03505246cd27a963f981b" +checksum = "44919ecaf6f99e8e737bc239408931c9a01e9a6c74814fee8242dd2506b65390" +dependencies = [ + "cfg-if 1.0.0", + "glob", +] [[package]] name = "cpuid-bool" @@ -1048,23 +816,117 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dcb25d077389e53838a8158c8e99174c5a9d902dee4904320db714f3c653ffba" [[package]] -name = "crc32fast" -version = "1.2.1" +name = "cranelift-bforest" +version = "0.69.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81156fece84ab6a9f2afdb109ce3ae577e42b1228441eded99bd77f627953b1a" +checksum = "4066fd63b502d73eb8c5fa6bcab9c7962b05cd580f6b149ee83a8e730d8ce7fb" dependencies = [ - "cfg-if 1.0.0", + "cranelift-entity", ] [[package]] -name = "crossbeam-channel" -version = "0.5.0" +name = "cranelift-codegen" +version = "0.69.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dca26ee1f8d361640700bde38b2c37d8c22b3ce2d360e1fc1c74ea4b0aa7d775" +checksum = "1a54e4beb833a3c873a18a8fe735d73d732044004c7539a072c8faa35ccb0c60" dependencies = [ - "cfg-if 1.0.0", - "crossbeam-utils 0.8.1", -] + "byteorder", + "cranelift-bforest", + "cranelift-codegen-meta", + "cranelift-codegen-shared", + "cranelift-entity", + "gimli", + "log", + "regalloc", + "serde", + "smallvec 1.6.1", + "target-lexicon", + "thiserror", +] + +[[package]] +name = "cranelift-codegen-meta" +version = "0.69.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c54cac7cacb443658d8f0ff36a3545822613fa202c946c0891897843bc933810" +dependencies = [ + "cranelift-codegen-shared", + "cranelift-entity", +] + +[[package]] +name = "cranelift-codegen-shared" +version = "0.69.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a109760aff76788b2cdaeefad6875a73c2b450be13906524f6c2a81e05b8d83c" + +[[package]] +name = "cranelift-entity" +version = "0.69.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b044234aa32531f89a08b487630ddc6744696ec04c8123a1ad388de837f5de3" +dependencies = [ + "serde", +] + +[[package]] +name = "cranelift-frontend" +version = "0.69.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5452b3e4e97538ee5ef2cc071301c69a86c7adf2770916b9d04e9727096abd93" +dependencies = [ + "cranelift-codegen", + "log", + "smallvec 1.6.1", + "target-lexicon", +] + +[[package]] +name = "cranelift-native" +version = "0.69.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f68035c10b2e80f26cc29c32fa824380877f38483504c2a47b54e7da311caaf3" +dependencies = [ + "cranelift-codegen", + "raw-cpuid", + "target-lexicon", +] + +[[package]] +name = "cranelift-wasm" +version = "0.69.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a530eb9d1c95b3309deb24c3d179d8b0ba5837ed98914a429787c395f614949d" +dependencies = [ + "cranelift-codegen", + "cranelift-entity", + "cranelift-frontend", + "itertools", + "log", + "serde", + "smallvec 1.6.1", + "thiserror", + "wasmparser", +] + +[[package]] +name = "crc32fast" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81156fece84ab6a9f2afdb109ce3ae577e42b1228441eded99bd77f627953b1a" +dependencies = [ + "cfg-if 1.0.0", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dca26ee1f8d361640700bde38b2c37d8c22b3ce2d360e1fc1c74ea4b0aa7d775" +dependencies = [ + "cfg-if 1.0.0", + "crossbeam-utils 0.8.3", +] [[package]] name = "crossbeam-deque" @@ -1084,8 +946,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94af6efb46fef72616855b036a624cf27ba656ffc9be1b9a3c931cfc7749a9a9" dependencies = [ "cfg-if 1.0.0", - "crossbeam-epoch 0.9.1", - "crossbeam-utils 0.8.1", + "crossbeam-epoch 0.9.3", + "crossbeam-utils 0.8.3", ] [[package]] @@ -1094,27 +956,26 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" dependencies = [ - "autocfg 1.0.1", + "autocfg", "cfg-if 0.1.10", "crossbeam-utils 0.7.2", "lazy_static", "maybe-uninit", "memoffset 0.5.6", - "scopeguard 1.1.0", + "scopeguard", ] [[package]] name = "crossbeam-epoch" -version = "0.9.1" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1aaa739f95311c2c7887a76863f500026092fb1dce0161dab577e559ef3569d" +checksum = "2584f639eb95fea8c798496315b297cf81b9b58b6d30ab066a75455333cf4b12" dependencies = [ "cfg-if 1.0.0", - "const_fn", - "crossbeam-utils 0.8.1", + "crossbeam-utils 0.8.3", "lazy_static", "memoffset 0.6.1", - "scopeguard 1.1.0", + "scopeguard", ] [[package]] @@ -1134,18 +995,18 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" dependencies = [ - "autocfg 1.0.1", + "autocfg", "cfg-if 0.1.10", "lazy_static", ] [[package]] name = "crossbeam-utils" -version = "0.8.1" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02d96d1e189ef58269ebe5b97953da3274d83a93af647c2ddd6f9dab28cedb8d" +checksum = "e7e9d99fa91428effe99c5c6d4634cdeba32b8cf784fc428a2a687f61a952c49" dependencies = [ - "autocfg 1.0.1", + "autocfg", "cfg-if 1.0.0", "lazy_static", ] @@ -1176,16 +1037,6 @@ dependencies = [ "subtle 2.4.0", ] -[[package]] -name = "crypto-mac" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4857fd85a0c34b3c3297875b747c1e02e06b6a0ea32dd892d8192b9ce0813ea6" -dependencies = [ - "generic-array 0.14.4", - "subtle 2.4.0", -] - [[package]] name = "ct-logs" version = "0.7.0" @@ -1196,22 +1047,24 @@ dependencies = [ ] [[package]] -name = "ctr" -version = "0.6.0" +name = "ctor" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb4a30d54f7443bf3d6191dcd486aca19e67cb3c49fa7a06a319966346707e7f" +checksum = "e8f45d9ad417bcef4817d614a501ab55cdd96a6fdb24f49aab89a54acfd66b19" dependencies = [ - "cipher", + "quote", + "syn", ] [[package]] name = "cuckoofilter" -version = "0.3.2" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8dd43f7cfaffe0a386636a10baea2ee05cc50df3b77bea4a456c9572a939bf1f" +checksum = "b810a8449931679f64cd7eef1bbd0fa315801b6d5d9cdc1ace2804d6529eee18" dependencies = [ - "byteorder 0.5.3", - "rand 0.3.23", + "byteorder", + "fnv", + "rand 0.7.3", ] [[package]] @@ -1220,7 +1073,7 @@ version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "434e1720189a637d44fe464f4df1e6eb900b4835255b14354497c78af37d9bb8" dependencies = [ - "byteorder 1.4.2", + "byteorder", "digest 0.8.1", "rand_core 0.5.1", "subtle 2.4.0", @@ -1233,7 +1086,7 @@ version = "3.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f627126b946c25a4638eec0ea634fc52506dea98db118aae985118ce7c3d723f" dependencies = [ - "byteorder 1.4.2", + "byteorder", "digest 0.9.0", "rand_core 0.5.1", "subtle 2.4.0", @@ -1247,15 +1100,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ee2393c4a91429dffb4bedf19f4d6abf27d8a732c8ce4980305d782e5426d57" [[package]] -name = "derive_more" -version = "0.14.1" +name = "data-encoding-macro" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d944ac6003ed268757ef1ee686753b57efc5fcf0ebe7b64c9fc81e7e32ff839" +checksum = "0a94feec3d2ba66c0b6621bca8bc6f68415b1e5c69af3586fdd0af9fd9f29b17" dependencies = [ - "proc-macro2 0.4.30", - "quote 0.6.13", - "rustc_version", - "syn 0.15.44", + "data-encoding", + "data-encoding-macro-internal", +] + +[[package]] +name = "data-encoding-macro-internal" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f83e699727abca3c56e187945f303389590305ab2f0185ea445aa66e8d5f2a" +dependencies = [ + "data-encoding", + "syn", ] [[package]] @@ -1264,9 +1125,9 @@ version = "0.99.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41cb0e6161ad61ed084a36ba71fbba9e3ac5aee3606fb607fe08da6acbcf3d8c" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -1289,14 +1150,23 @@ dependencies = [ [[package]] name = "directories" -version = "2.0.2" +version = "3.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "551a778172a450d7fc12e629ca3b0428d00f6afa9a43da1b630d54604e97371c" +checksum = "f8fed639d60b58d0f53498ab13d26f621fd77569cc6edb031f4cc36a2ad9da0f" dependencies = [ - "cfg-if 0.1.10", "dirs-sys", ] +[[package]] +name = "directories-next" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "339ee130d97a610ea5a5872d2bbb130fdf68884ff09d3028b81bec8a1ac23bbc" +dependencies = [ + "cfg-if 1.0.0", + "dirs-sys-next", +] + [[package]] name = "dirs-sys" version = "0.3.5" @@ -1304,15 +1174,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e93d7f5705de3e49895a2b5e0b8855a1c27f080192ae9c32a6432d50741a57a" dependencies = [ "libc", - "redox_users", + "redox_users 0.3.5", "winapi 0.3.9", ] [[package]] -name = "discard" -version = "1.0.4" +name = "dirs-sys-next" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "212d0f5754cb6769937f4501cc0e67f4f4483c8d2c3e1e922ee9edbe4ab4c7c0" +checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d" +dependencies = [ + "libc", + "redox_users 0.4.0", + "winapi 0.3.9", +] [[package]] name = "dns-parser" @@ -1320,7 +1195,7 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4d33be9473d06f75f58220f71f7a9317aca647dc061dbd3c361b0bef505fbea" dependencies = [ - "byteorder 1.4.2", + "byteorder", "quick-error", ] @@ -1340,9 +1215,9 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "558e40ea573c374cf53507fd240b7ee2f5477df7cfebdb97323ec61c719399c5" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -1380,15 +1255,6 @@ version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" -[[package]] -name = "encoding_rs" -version = "0.8.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80df024fbc5ac80f87dfef0d9f5209a252f2a497f7f42944cff24d8253cac065" -dependencies = [ - "cfg-if 1.0.0", -] - [[package]] name = "env_logger" version = "0.7.1" @@ -1418,44 +1284,52 @@ dependencies = [ ] [[package]] -name = "ethabi" -version = "12.0.0" +name = "errno" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "052a565e3de82944527d6d10a465697e6bb92476b772ca7141080c901f6a63c6" +checksum = "fa68f2fb9cae9d37c9b2b3584aba698a2e97f72d7aef7b9f7aa71d8b54ce46fe" dependencies = [ - "ethereum-types", - "rustc-hex", - "serde", - "serde_json", - "tiny-keccak 1.5.0", - "uint", + "errno-dragonfly", + "libc", + "winapi 0.3.9", +] + +[[package]] +name = "errno-dragonfly" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14ca354e36190500e1e1fb267c647932382b54053c50b14970856c0b00a35067" +dependencies = [ + "gcc", + "libc", ] [[package]] name = "ethbloom" -version = "0.9.2" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71a6567e6fd35589fea0c63b94b4cf2e55573e413901bdbe60ab15cf0e25e5df" +checksum = "779864b9c7f7ead1f092972c3257496c6a84b46dba2ce131dd8a282cb2cc5972" dependencies = [ "crunchy", "fixed-hash", "impl-codec", "impl-rlp", "impl-serde", - "tiny-keccak 2.0.2", + "tiny-keccak", ] [[package]] name = "ethereum" -version = "0.4.2" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df706418ff7d3874b9506424b04ea0bef569a2b39412b43a27ea86e679be108e" +checksum = "567ce064a8232c16e2b2c2173a936b91fbe35c2f2c5278871f5a1a31688b42e9" dependencies = [ "ethereum-types", + "funty", "hash-db", "hash256-std-hasher", "parity-scale-codec", - "rlp 0.4.6", + "rlp", "rlp-derive", "serde", "sha3 0.9.1", @@ -1464,9 +1338,9 @@ dependencies = [ [[package]] name = "ethereum-types" -version = "0.9.2" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "473aecff686bd8e7b9db0165cbbb53562376b39bf35b427f0c60446a9e1634b0" +checksum = "f64b5df66a228d85e4b17e5d6c6aa43b0310898ffe8a85988c4c032357aaabfd" dependencies = [ "ethbloom", "fixed-hash", @@ -1485,9 +1359,9 @@ checksum = "f7531096570974c3a9dcf9e4b8e1cede1ec26cf5046219fb3b9d897503b9be59" [[package]] name = "evm" -version = "0.18.0" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ae392693d655a526f86dcd9ee0846ee9250f3cef8c6ee67c35ce05d277b7a2" +checksum = "0467250a12bb144ad7b2f41e03e8675e38b971ab73f6d42ede6b78af07657e7b" dependencies = [ "ethereum", "evm-core", @@ -1496,17 +1370,18 @@ dependencies = [ "log", "parity-scale-codec", "primitive-types", - "rlp 0.4.6", + "rlp", "serde", "sha3 0.8.2", ] [[package]] name = "evm-core" -version = "0.18.3" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63c6c39300d7779427f461408d867426e202ea72ac7ece2455689ff0e4bddb6f" +checksum = "2f0db0394d7b497bf97be3d9ece9c828f8b7670a065fc9f3106c9598cce6556d" dependencies = [ + "funty", "parity-scale-codec", "primitive-types", "serde", @@ -1514,9 +1389,9 @@ dependencies = [ [[package]] name = "evm-gasometer" -version = "0.18.3" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "689c481648c3f45b64b1278077c04284ad535e068c9d6872153c7b74da7ccb03" +checksum = "c617616408f87be6826bda72cee7625aa8cbc09b759f05b1dccd329fb61b2077" dependencies = [ "evm-core", "evm-runtime", @@ -1525,9 +1400,9 @@ dependencies = [ [[package]] name = "evm-runtime" -version = "0.18.3" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61a148ad1b3e0af31aa03c6c3cc9df3a529e279dad8e29b4ef90dccad32601e4" +checksum = "8447504daa86bc5a7ae982b9b5c53225aa0ebcfba636b785cf0f53406eaa4d87" dependencies = [ "evm-core", "primitive-types", @@ -1540,7 +1415,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e43f2f1833d64e33f15592464d6fdd70f349dda7b1a53088eb83cd94014008c5" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", ] [[package]] @@ -1559,9 +1434,9 @@ version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa4da3c766cd7a0db8242e326e9e4e081edd567072893ed320008189715366a4" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", "synstructure", ] @@ -1571,6 +1446,12 @@ 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 = "fastrand" version = "1.4.0" @@ -1580,6 +1461,77 @@ dependencies = [ "instant", ] +[[package]] +name = "fc-consensus" +version = "0.1.0" +dependencies = [ + "derive_more", + "fp-consensus", + "fp-rpc", + "futures 0.3.13", + "log", + "parity-scale-codec", + "sc-client-api", + "sp-api", + "sp-block-builder", + "sp-blockchain", + "sp-consensus", + "sp-core", + "sp-inherents", + "sp-runtime", + "sp-timestamp", + "substrate-prometheus-endpoint", +] + +[[package]] +name = "fc-rpc" +version = "0.1.0" +dependencies = [ + "ethereum", + "ethereum-types", + "fc-consensus", + "fc-rpc-core", + "fp-rpc", + "futures 0.3.13", + "jsonrpc-core 15.1.0", + "jsonrpc-core-client 14.2.0", + "jsonrpc-derive 14.2.2", + "jsonrpc-pubsub 15.1.0", + "libsecp256k1", + "log", + "pallet-ethereum", + "pallet-evm", + "parity-scale-codec", + "rand 0.7.3", + "rlp", + "rustc-hex", + "sc-client-api", + "sc-network", + "sc-rpc", + "sc-service", + "sha3 0.8.2", + "sp-api", + "sp-blockchain", + "sp-io", + "sp-runtime", + "sp-storage", + "sp-transaction-pool", +] + +[[package]] +name = "fc-rpc-core" +version = "0.1.0" +dependencies = [ + "ethereum-types", + "jsonrpc-core 15.1.0", + "jsonrpc-core-client 14.2.0", + "jsonrpc-derive 14.2.2", + "jsonrpc-pubsub 15.1.0", + "rustc-hex", + "serde", + "serde_json", +] + [[package]] name = "fdlimit" version = "0.2.1" @@ -1590,44 +1542,38 @@ dependencies = [ ] [[package]] -name = "femme" -version = "2.1.1" +name = "file-per-thread-logger" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2af1a24f391a5a94d756db5092c6576aad494b88a71a5a36b20c67b63e0df034" +checksum = "4fdbe0d94371f9ce939b555dd342d0686cc4c0cadbcd4b61d70af5ff97eb4126" dependencies = [ - "cfg-if 0.1.10", - "js-sys", + "env_logger", "log", - "serde", - "serde_derive", - "serde_json", - "wasm-bindgen", - "web-sys", ] [[package]] name = "finality-grandpa" -version = "0.12.3" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8feb87a63249689640ac9c011742c33139204e3c134293d3054022276869133b" +checksum = "2cd795898c348a8ec9edc66ec9e014031c764d4c88cc26d09b492cd93eb41339" dependencies = [ "either", - "futures 0.3.12", - "futures-timer 2.0.2", + "futures 0.3.13", + "futures-timer 3.0.2", "log", "num-traits", "parity-scale-codec", - "parking_lot 0.9.0", + "parking_lot 0.11.1", ] [[package]] name = "fixed-hash" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11498d382790b7a8f2fd211780bec78619bba81cdad3a283997c0c41f836759c" +checksum = "cfcf0ed7fe52a17a03854ec54a9f76d6d84508d1c0e66bc1793301c73fc8493c" dependencies = [ - "byteorder 1.4.2", - "rand 0.7.3", + "byteorder", + "rand 0.8.3", "rustc-hex", "static_assertions", ] @@ -1658,50 +1604,72 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] -name = "foreign-types" -version = "0.3.2" +name = "fork-tree" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +checksum = "632b95f97f332b2ff5bc3a42bc8e28772b067e333830e03fd046504f11cd0fb8" dependencies = [ - "foreign-types-shared", + "parity-scale-codec", ] [[package]] -name = "foreign-types-shared" -version = "0.1.1" +name = "form_urlencoded" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" +checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191" +dependencies = [ + "matches", + "percent-encoding 2.1.0", +] [[package]] -name = "fork-tree" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bf6132b853c84f0f4534fa9c25d6f43e6c2552168da5ad8b4890f9c4fb59926" +name = "fp-consensus" +version = "0.1.0" dependencies = [ "parity-scale-codec", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] -name = "form_urlencoded" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ece68d15c92e84fa4f19d3780f1294e5ca82a78a6d515f1efaabcc144688be00" +name = "fp-evm" +version = "0.9.0" dependencies = [ - "matches", - "percent-encoding 2.1.0", + "evm", + "impl-trait-for-tuples 0.1.3", + "parity-scale-codec", + "serde", + "sp-core", + "sp-std", +] + +[[package]] +name = "fp-rpc" +version = "0.1.0" +dependencies = [ + "ethereum", + "ethereum-types", + "fp-evm", + "parity-scale-codec", + "sp-api", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "frame-benchmarking" -version = "2.0.1" +version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52b94f3dd88fd10ea9eb8bf6731ee22787deeb620c158766061ec1fc54170cda" +checksum = "70fe99487f84579a3f2c4ba52650fec875492eea41be0e4eea8019187f105052" dependencies = [ "frame-support", "frame-system", "linregress", "parity-scale-codec", - "paste", + "paste 1.0.4", "sp-api", "sp-io", "sp-runtime", @@ -1712,9 +1680,9 @@ dependencies = [ [[package]] name = "frame-executive" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb0c4bcb8c34936657327c73c8a191159c998df425620bf4639737486d4bf5c0" +checksum = "1da8fd471442bee91b9b3f587ec832e3f47800374fdb89b4a66591cd7c42b29f" dependencies = [ "frame-support", "frame-system", @@ -1729,9 +1697,9 @@ dependencies = [ [[package]] name = "frame-metadata" -version = "12.0.1" +version = "13.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61200390d9eb6bac07a60adafa6961ef250f9022970fabb2412183fc96ba5f6b" +checksum = "073f7bef18421362441a1708f8528e442234954611f95bdc554b313fb321948e" dependencies = [ "parity-scale-codec", "serde", @@ -1741,18 +1709,18 @@ dependencies = [ [[package]] name = "frame-support" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a569b3964b996dae5a9aab81a04a65f81a386645db1f16583647fc67190b0748" +checksum = "04e521e6214615bd82ba6b5fc7fd40a9cc14fdeb40f83da5eba12aa2f8179fb8" dependencies = [ - "bitmask", + "bitflags", "frame-metadata", "frame-support-procedural", - "impl-trait-for-tuples", + "impl-trait-for-tuples 0.2.1", "log", - "once_cell 1.5.2", + "once_cell", "parity-scale-codec", - "paste", + "paste 1.0.4", "serde", "smallvec 1.6.1", "sp-arithmetic", @@ -1760,6 +1728,7 @@ dependencies = [ "sp-inherents", "sp-io", "sp-runtime", + "sp-staking", "sp-state-machine", "sp-std", "sp-tracing", @@ -1767,158 +1736,66 @@ dependencies = [ [[package]] name = "frame-support-procedural" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c107da590c5cf22f9bb96193812256e59c60f73786a72429660142d9000c07b" +checksum = "2668e24cbaba7f0e91d0c92a94bd1ae425a942608ad0b775db32477f5df4da9e" dependencies = [ + "Inflector", "frame-support-procedural-tools", - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] name = "frame-support-procedural-tools" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb23ac15b9dfe806c1da92d6c8710fa09371ec61e13f4eadfdeef55e3d6b155b" -dependencies = [ - "frame-support-procedural-tools-derive", - "proc-macro-crate", - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", -] - -[[package]] -name = "frame-support-procedural-tools-derive" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66fb72ae75d457bfcb457e1098cf18134967e9069ecc4bba2c77416924b44843" -dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", -] - -[[package]] -name = "frame-system" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bd441142244193759326c7311d075716d1aaa98a9ad50491af923a4c6e42f3b" -dependencies = [ - "frame-support", - "impl-trait-for-tuples", - "parity-scale-codec", - "serde", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", - "sp-version", -] - -[[package]] -name = "frame-system-rpc-runtime-api" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "deb625cb0135571a965d63a99225733f7e37dfcfb59e28c1ad15416cee99fbaa" -dependencies = [ - "parity-scale-codec", - "sp-api", -] - -[[package]] -name = "frontier-consensus" -version = "0.1.0" -dependencies = [ - "derive_more 0.99.11", - "ethereum", - "frontier-consensus-primitives", - "futures 0.3.12", - "log", - "parity-scale-codec", - "sc-client-api", - "sp-api", - "sp-block-builder", - "sp-blockchain", - "sp-consensus", - "sp-core", - "sp-inherents", - "sp-runtime", - "sp-timestamp", - "substrate-prometheus-endpoint", -] - -[[package]] -name = "frontier-consensus-primitives" -version = "0.1.0" -dependencies = [ - "parity-scale-codec", - "sp-core", - "sp-runtime", - "sp-std", +checksum = "d4f88cfd111e004590f4542b75e6d3302137b9067d7e7219e4ac47a535c3b5c1" +dependencies = [ + "frame-support-procedural-tools-derive", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn", ] [[package]] -name = "frontier-rpc" -version = "0.1.0" +name = "frame-support-procedural-tools-derive" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79285388b120ac96c15a791c56b26b9264f7231324fbe0fd05026acd92bf2e6a" dependencies = [ - "ethereum", - "ethereum-types", - "frontier-consensus", - "frontier-rpc-core", - "frontier-rpc-primitives", - "futures 0.3.12", - "jsonrpc-core 15.1.0", - "jsonrpc-core-client", - "jsonrpc-derive", - "jsonrpc-pubsub", - "log", - "pallet-ethereum", - "pallet-evm", - "parity-scale-codec", - "rlp 0.4.6", - "rustc-hex", - "sc-client-api", - "sc-network", - "sc-rpc", - "sc-service", - "sha3 0.8.2", - "sp-api", - "sp-blockchain", - "sp-io", - "sp-runtime", - "sp-storage", - "sp-transaction-pool", + "proc-macro2", + "quote", + "syn", ] [[package]] -name = "frontier-rpc-core" -version = "0.1.0" +name = "frame-system" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5fedbff05d665c00bf4e089b4377fcb15b8bd37ebc3e5fc06665474cf6e25d7" dependencies = [ - "ethereum-types", - "jsonrpc-core 15.1.0", - "jsonrpc-core-client", - "jsonrpc-derive", - "jsonrpc-pubsub", - "rustc-hex", + "frame-support", + "impl-trait-for-tuples 0.2.1", + "parity-scale-codec", "serde", - "serde_json", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", + "sp-version", ] [[package]] -name = "frontier-rpc-primitives" -version = "0.1.0" +name = "frame-system-rpc-runtime-api" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cb9d2f86a903fdee4ca3d660c767e69a743cee8aeb103563a14ea52e9f0001d" dependencies = [ - "ethereum", - "ethereum-types", "parity-scale-codec", "sp-api", - "sp-core", - "sp-evm", - "sp-runtime", - "sp-std", ] [[package]] @@ -1933,6 +1810,12 @@ dependencies = [ "winapi 0.3.9", ] +[[package]] +name = "fs_extra" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2022715d62ab30faffd124d40b76f4134a550a87792276512b18d63272333394" + [[package]] name = "fuchsia-cprng" version = "0.1.1" @@ -1955,17 +1838,23 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" +[[package]] +name = "funty" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fed34cd105917e91daa4da6b3728c47b068749d6a62c59811f06ed2ac71d9da7" + [[package]] name = "futures" -version = "0.1.30" +version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c7e4c2612746b0df8fed4ce0c69156021b704c9aefa360311c04e6e9e002eed" +checksum = "3a471a38ef8ed83cd6e40aa59c1ffe17db6855c18e3604d9c4ed8c08ebc28678" [[package]] name = "futures" -version = "0.3.12" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da9052a1a50244d8d5aa9bf55cbc2fb6f357c86cc52e46c62ed390a7180cf150" +checksum = "7f55667319111d593ba876406af7c409c0ebb44dc4be6132a783ccf163ea14c1" dependencies = [ "futures-channel", "futures-core", @@ -1978,34 +1867,19 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.12" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2d31b7ec7efab6eefc7c57233bb10b847986139d88cc2f5a02a1ae6871a1846" +checksum = "8c2dd2df839b57db9ab69c2c9d8f3e8c81984781937fe2807dc6dcf3b2ad2939" dependencies = [ "futures-core", "futures-sink", ] -[[package]] -name = "futures-channel-preview" -version = "0.3.0-alpha.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5e5f4df964fa9c1c2f8bddeb5c3611631cacd93baf810fc8bb2fb4b495c263a" -dependencies = [ - "futures-core-preview", -] - [[package]] name = "futures-core" -version = "0.3.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79e5145dde8da7d1b3892dad07a9c98fc04bc39892b1ecc9692cf53e2b780a65" - -[[package]] -name = "futures-core-preview" -version = "0.3.0-alpha.19" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b35b6263fb1ef523c3056565fa67b1d16f0a8604ff12b11b08c25f28a734c60a" +checksum = "15496a72fabf0e62bdc3df11a59a3787429221dd0710ba8ef163d6f7a9112c94" [[package]] name = "futures-cpupool" @@ -2013,7 +1887,7 @@ version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab90cde24b3319636588d0c35fe03b1333857621051837ed769faefb4c2162e4" dependencies = [ - "futures 0.1.30", + "futures 0.1.31", "num_cpus", ] @@ -2023,8 +1897,8 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdcef58a173af8148b182684c9f2d5250875adbcaff7b5794073894f9d8634a9" dependencies = [ - "futures 0.1.30", - "futures 0.3.12", + "futures 0.1.31", + "futures 0.3.13", "lazy_static", "log", "parking_lot 0.9.0", @@ -2035,9 +1909,9 @@ dependencies = [ [[package]] name = "futures-executor" -version = "0.3.12" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9e59fdc009a4b3096bf94f740a0f2424c082521f20a9b08c5c07c48d90fd9b9" +checksum = "891a4b7b96d84d5940084b2a37632dd65deeae662c114ceaa2c879629c9c0ad1" dependencies = [ "futures-core", "futures-task", @@ -2047,9 +1921,9 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.12" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28be053525281ad8259d47e4de5de657b25e7bac113458555bb4b70bc6870500" +checksum = "d71c2c65c57704c32f5241c1223167c2c3294fd34ac020c807ddbe6db287ba59" [[package]] name = "futures-lite" @@ -2062,36 +1936,44 @@ dependencies = [ "futures-io", "memchr", "parking", - "pin-project-lite 0.2.4", + "pin-project-lite 0.2.5", "waker-fn", ] [[package]] name = "futures-macro" -version = "0.3.12" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c287d25add322d9f9abdcdc5927ca398917996600182178774032e9f8258fedd" +checksum = "ea405816a5139fb39af82c2beb921d52143f556038378d6db21183a5c37fbfb7" dependencies = [ "proc-macro-hack", - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-rustls" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a1387e07917c711fb4ee4f48ea0adb04a3c9739e53ef85bf43ae1edc2937a8b" +dependencies = [ + "futures-io", + "rustls 0.19.0", + "webpki", ] [[package]] name = "futures-sink" -version = "0.3.12" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "caf5c69029bda2e743fddd0582d1083951d65cc9539aebf8812f36c3491342d6" +checksum = "85754d98985841b7d4f5e8e6fbfa4a4ac847916893ec511a2917ccd8525b8bb3" [[package]] name = "futures-task" -version = "0.3.12" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13de07eb8ea81ae445aca7b69f5f7bf15d7bf4912d8ca37d6645c77ae8a58d86" -dependencies = [ - "once_cell 1.5.2", -] +checksum = "fa189ef211c15ee602667a6fcfe1c1fd9e07d42250d2156382820fba33c9df80" [[package]] name = "futures-timer" @@ -2107,11 +1989,11 @@ checksum = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c" [[package]] name = "futures-util" -version = "0.3.12" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "632a8cd0f2a4b3fdea1657f08bde063848c3bd00f9bbf6e256b8be78802e624b" +checksum = "1812c7ab8aedf8d6f2701a43e1243acdbcc2b36ab26e2ad421eb99ac963d96d1" dependencies = [ - "futures 0.1.30", + "futures 0.1.31", "futures-channel", "futures-core", "futures-io", @@ -2119,37 +2001,13 @@ dependencies = [ "futures-sink", "futures-task", "memchr", - "pin-project-lite 0.2.4", + "pin-project-lite 0.2.5", "pin-utils", "proc-macro-hack", "proc-macro-nested", "slab", ] -[[package]] -name = "futures-util-preview" -version = "0.3.0-alpha.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ce968633c17e5f97936bd2797b6e38fb56cf16a7422319f7ec2e30d3c470e8d" -dependencies = [ - "futures-channel-preview", - "futures-core-preview", - "pin-utils", - "slab", -] - -[[package]] -name = "futures_codec" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce54d63f8b0c75023ed920d46fd71d0cbbb830b0ee012726b5b4f506fb6dea5b" -dependencies = [ - "bytes 0.5.6", - "futures 0.3.12", - "memchr", - "pin-project 0.4.27", -] - [[package]] name = "gcc" version = "0.3.55" @@ -2158,18 +2016,18 @@ checksum = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2" [[package]] name = "generic-array" -version = "0.11.1" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8107dafa78c80c848b71b60133954b4a58609a3a1a5f9af037ecc7f67280f369" +checksum = "c68f0274ae0e023facc3c97b2e00f076be70e254bc851d972503b328db79b2ec" dependencies = [ "typenum", ] [[package]] name = "generic-array" -version = "0.12.3" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c68f0274ae0e023facc3c97b2e00f076be70e254bc851d972503b328db79b2ec" +checksum = "0ed1e761351b56f54eb9dcd0cfaca9fd0daecf93918e1cfc01c8a3d26ee7adcd" dependencies = [ "typenum", ] @@ -2184,28 +2042,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "get_if_addrs" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abddb55a898d32925f3148bd281174a68eeb68bbfd9a5938a57b18f506ee4ef7" -dependencies = [ - "c_linked_list", - "get_if_addrs-sys", - "libc", - "winapi 0.2.8", -] - -[[package]] -name = "get_if_addrs-sys" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d04f9fb746cf36b191c00f3ede8bde9c8e64f9f4b05ae2694a9ccf5e3f5ab48" -dependencies = [ - "gcc", - "libc", -] - [[package]] name = "getrandom" version = "0.1.16" @@ -2243,12 +2079,11 @@ name = "gimli" version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6503fe142514ca4799d4c26297c4248239fe8838d827db6bd6065c6ed29a6ce" - -[[package]] -name = "glob" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8be18de09a56b60ed0edf84bc9df007e30040691af7acd1c41874faac5895bfb" +dependencies = [ + "fallible-iterator", + "indexmap", + "stable_deref_trait", +] [[package]] name = "glob" @@ -2288,10 +2123,10 @@ version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a5b34c246847f938a410a03c5458c7fee2274436675e76d8b903c08efc29c462" dependencies = [ - "byteorder 1.4.2", + "byteorder", "bytes 0.4.12", "fnv", - "futures 0.1.30", + "futures 0.1.31", "http 0.1.21", "indexmap", "log", @@ -2335,43 +2170,13 @@ dependencies = [ "crunchy", ] -[[package]] -name = "hashbrown" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bae29b6653b3412c2e71e9d486db9f9df5d701941d86683005efb9f2d28e3da" -dependencies = [ - "byteorder 1.4.2", - "scopeguard 0.3.3", -] - -[[package]] -name = "hashbrown" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e6073d0ca812575946eb5f35ff68dbe519907b25c42530389ff946dc84c6ead" -dependencies = [ - "ahash 0.2.19", - "autocfg 0.1.7", -] - -[[package]] -name = "hashbrown" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e91b62f79061a0bc2e046024cb7ba44b08419ed238ecbd9adbd787434b9e8c25" -dependencies = [ - "ahash 0.3.8", - "autocfg 1.0.1", -] - [[package]] name = "hashbrown" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04" dependencies = [ - "ahash 0.4.7", + "ahash", ] [[package]] @@ -2408,12 +2213,6 @@ dependencies = [ "proc-macro-hack", ] -[[package]] -name = "hex-literal" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5af1f635ef1bc545d78392b136bfe1c9809e029023c84a3638a864a10b8819c8" - [[package]] name = "hex-literal-impl" version = "0.2.2" @@ -2429,16 +2228,6 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b07f60793ff0a4d9cef0f18e63b5357e06209987153a64648c972c1e5aff336f" -[[package]] -name = "hkdf" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51ab2f639c231793c5f6114bdb9bbe50a7dbbfcd7c7c6bd8475dec2d991e964f" -dependencies = [ - "digest 0.9.0", - "hmac 0.10.1", -] - [[package]] name = "hmac" version = "0.7.1" @@ -2459,16 +2248,6 @@ dependencies = [ "digest 0.9.0", ] -[[package]] -name = "hmac" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1441c6b1e930e2817404b5046f1f989899143a12bf92de603b69f4e0aee1e15" -dependencies = [ - "crypto-mac 0.10.0", - "digest 0.9.0", -] - [[package]] name = "hmac-drbg" version = "0.2.0" @@ -2509,7 +2288,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6741c859c1b2463a423a1dbce98d418e6c3c3fc720fb0d45528657320920292d" dependencies = [ "bytes 0.4.12", - "futures 0.1.30", + "futures 0.1.31", "http 0.1.21", "tokio-buf", ] @@ -2524,28 +2303,6 @@ dependencies = [ "http 0.2.3", ] -[[package]] -name = "http-types" -version = "2.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32613ebb139d1d430ef5783676f84abfa06fc5f2b4b5a25220cdeeff7e16ef5c" -dependencies = [ - "anyhow", - "async-channel", - "async-std", - "base64 0.13.0", - "cookie", - "futures-lite", - "infer", - "pin-project-lite 0.2.4", - "rand 0.7.3", - "serde", - "serde_json", - "serde_qs", - "serde_urlencoded", - "url 2.2.0", -] - [[package]] name = "httparse" version = "1.3.5" @@ -2569,12 +2326,12 @@ dependencies = [ [[package]] name = "hyper" -version = "0.12.35" +version = "0.12.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dbe6ed1438e1f8ad955a4701e9a944938e9519f6888d12d8558b645e247d5f6" +checksum = "5c843caf6296fc1f93444735205af9ed4e109a539005abb2564ae1d6fad34c52" dependencies = [ "bytes 0.4.12", - "futures 0.1.30", + "futures 0.1.31", "futures-cpupool", "h2 0.1.26", "http 0.1.21", @@ -2584,11 +2341,11 @@ dependencies = [ "itoa", "log", "net2", - "rustc_version", - "time 0.1.44", + "rustc_version 0.2.3", + "time", "tokio 0.1.22", "tokio-buf", - "tokio-executor 0.1.10", + "tokio-executor", "tokio-io", "tokio-reactor", "tokio-tcp", @@ -2632,26 +2389,13 @@ dependencies = [ "futures-util", "hyper 0.13.10", "log", - "rustls", + "rustls 0.18.1", "rustls-native-certs", "tokio 0.2.25", "tokio-rustls", "webpki", ] -[[package]] -name = "hyper-tls" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d979acc56dcb5b8dddba3917601745e877576475aa046df3226eabdecef78eed" -dependencies = [ - "bytes 0.5.6", - "hyper 0.13.10", - "native-tls", - "tokio 0.2.25", - "tokio-tls", -] - [[package]] name = "idna" version = "0.1.5" @@ -2665,31 +2409,68 @@ dependencies = [ [[package]] name = "idna" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de910d521f7cc3135c4de8db1cb910e0b5ed1dc6f57c381cd07e8e661ce10094" +checksum = "89829a5d69c23d348314a7ac337fe39173b61149a9864deabd260983aed48c21" dependencies = [ "matches", "unicode-bidi", "unicode-normalization", ] +[[package]] +name = "if-addrs" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28538916eb3f3976311f5dfbe67b5362d0add1293d0a9cad17debf86f8e3aa48" +dependencies = [ + "if-addrs-sys", + "libc", + "winapi 0.3.9", +] + +[[package]] +name = "if-addrs-sys" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de74b9dd780476e837e5eb5ab7c88b49ed304126e412030a0adba99c8efe79ea" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "if-watch" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97b8538953a3f0d0d3868f0a706eb4273535e10d72acb5c82c1c23ae48835c85" +dependencies = [ + "async-io", + "futures 0.3.13", + "futures-lite", + "if-addrs", + "ipnet", + "libc", + "log", + "winapi 0.3.9", +] + [[package]] name = "impl-codec" -version = "0.4.2" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1be51a921b067b0eaca2fad532d9400041561aa922221cc65f95a85641c6bf53" +checksum = "df170efa359aebdd5cb7fe78edcc67107748e4737bdca8a8fb40d15ea7a877ed" dependencies = [ "parity-scale-codec", ] [[package]] name = "impl-rlp" -version = "0.2.1" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f7a72f11830b52333f36e3b09a288333888bf54380fd0ac0790a3c31ab0f3c5" +checksum = "f28220f89297a075ddc7245cd538076ee98b01f2a9c23a53a4f1105d5a322808" dependencies = [ - "rlp 0.4.6", + "rlp", ] [[package]] @@ -2707,26 +2488,32 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ef5550a42e3740a0e71f909d4c861056a284060af885ae7aa6242820f920d9d" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] -name = "indexmap" -version = "1.6.1" +name = "impl-trait-for-tuples" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fb1fa934250de4de8aef298d81c729a7d33d8c239daa3a7575e6b92bfc7313b" +checksum = "d5dacb10c5b3bb92d46ba347505a9041e676bb20ad220101326bffb0c93031ee" dependencies = [ - "autocfg 1.0.1", - "hashbrown 0.9.1", + "proc-macro2", + "quote", + "syn", ] [[package]] -name = "infer" -version = "0.2.3" +name = "indexmap" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64e9829a50b42bb782c1df523f78d332fe371b10c661e78b7a3c34b0198e9fac" +checksum = "4fb1fa934250de4de8aef298d81c729a7d33d8c239daa3a7575e6b92bfc7313b" +dependencies = [ + "autocfg", + "hashbrown", + "serde", +] [[package]] name = "instant" @@ -2752,7 +2539,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64fa110ec7b8f493f416eed552740d10e7030ad5f63b2308f82c9608ec2df275" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "futures-timer 2.0.2", ] @@ -2779,9 +2566,9 @@ checksum = "47be2f14c678be2fdcab04ab1171db51b2762ce6f0a8ee87c8dd4a04ed216135" [[package]] name = "itertools" -version = "0.8.2" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f56a2d0bc861f9165be4eb3442afd3c236d8a98afd426f65d92324ae1091a484" +checksum = "284f18f85651fe11e8a991b2adb42cb078325c996ed026d994719efcfca1d54b" dependencies = [ "either", ] @@ -2792,15 +2579,61 @@ version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" +[[package]] +name = "jemalloc-sys" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d3b9f3f5c9b31aa0f5ed3260385ac205db665baa41d49bb8338008ae94ede45" +dependencies = [ + "cc", + "fs_extra", + "libc", +] + +[[package]] +name = "jemallocator" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43ae63fcfc45e99ab3d1b29a46782ad679e98436c3169d15a167a1108a724b69" +dependencies = [ + "jemalloc-sys", + "libc", +] + +[[package]] +name = "jobserver" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c71313ebb9439f74b00d9d2dcec36440beaf57a6aa0623068441dd7cd81a7f2" +dependencies = [ + "libc", +] + [[package]] name = "js-sys" -version = "0.3.47" +version = "0.3.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cfb73131c35423a367daf8cbd24100af0d077668c8c2943f0e7dd775fef0f65" +checksum = "dc9f84f9b115ce7843d60706df1422a916680bfdfcbdb0447c5614ff9d7e4d78" dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonrpc-client-transports" +version = "14.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2773fa94a2a1fd51efb89a8f45b8861023dbb415d18d3c9235ae9388d780f9ec" +dependencies = [ + "failure", + "futures 0.1.31", + "jsonrpc-core 14.2.0", + "jsonrpc-pubsub 14.2.0", + "log", + "serde", + "serde_json", + "url 1.7.2", +] + [[package]] name = "jsonrpc-client-transports" version = "15.1.0" @@ -2808,9 +2641,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "489b9c612e60c766f751ab40fcb43cbb55a1e10bb44a9b4307ed510ca598cbd7" dependencies = [ "failure", - "futures 0.1.30", + "futures 0.1.31", "jsonrpc-core 15.1.0", - "jsonrpc-pubsub", + "jsonrpc-pubsub 15.1.0", "log", "serde", "serde_json", @@ -2823,7 +2656,7 @@ version = "14.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0747307121ffb9703afd93afbd0fb4f854c38fb873f2c8b90e0e902f27c7b62" dependencies = [ - "futures 0.1.30", + "futures 0.1.31", "log", "serde", "serde_derive", @@ -2836,20 +2669,41 @@ version = "15.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0745a6379e3edc893c84ec203589790774e4247420033e71a76d3ab4687991fa" dependencies = [ - "futures 0.1.30", + "futures 0.1.31", "log", "serde", "serde_derive", "serde_json", ] +[[package]] +name = "jsonrpc-core-client" +version = "14.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34221123bc79b66279a3fde2d3363553835b43092d629b34f2e760c44dc94713" +dependencies = [ + "jsonrpc-client-transports 14.2.1", +] + [[package]] name = "jsonrpc-core-client" version = "15.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f764902d7b891344a0acb65625f32f6f7c6db006952143bd650209fbe7d94db" dependencies = [ - "jsonrpc-client-transports", + "jsonrpc-client-transports 15.1.0", +] + +[[package]] +name = "jsonrpc-derive" +version = "14.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0e77e8812f02155b85a677a96e1d16b60181950c0636199bc4528524fba98dc" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -2859,9 +2713,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99a847f9ec7bb52149b2786a17c9cb260d6effc6b8eeb8c16b343a487a7563a3" dependencies = [ "proc-macro-crate", - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -2870,7 +2724,7 @@ version = "15.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fb5c4513b7b542f42da107942b7b759f27120b5cc894729f88254b28dff44b7" dependencies = [ - "hyper 0.12.35", + "hyper 0.12.36", "jsonrpc-core 15.1.0", "jsonrpc-server-utils", "log", @@ -2893,6 +2747,19 @@ dependencies = [ "tokio-service", ] +[[package]] +name = "jsonrpc-pubsub" +version = "14.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d44f5602a11d657946aac09357956d2841299ed422035edf140c552cb057986" +dependencies = [ + "jsonrpc-core 14.2.0", + "log", + "parking_lot 0.10.2", + "rand 0.7.3", + "serde", +] + [[package]] name = "jsonrpc-pubsub" version = "15.1.0" @@ -2963,9 +2830,9 @@ dependencies = [ [[package]] name = "kvdb" -version = "0.7.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0315ef2f688e33844400b31f11c263f2b3dc21d8b9355c6891c5f185fae43f9a" +checksum = "8891bd853eff90e33024195d79d578dc984c82f9e0715fcd2b525a0c19d52811" dependencies = [ "parity-util-mem", "smallvec 1.6.1", @@ -2973,20 +2840,20 @@ dependencies = [ [[package]] name = "kvdb-memorydb" -version = "0.7.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73de822b260a3bdfb889dbbb65bb2d473eee2253973d6fa4a5d149a2a4a7c66e" +checksum = "30a0da8e08caf08d384a620ec19bb6c9b85c84137248e202617fb91881f25912" dependencies = [ "kvdb", "parity-util-mem", - "parking_lot 0.10.2", + "parking_lot 0.11.1", ] [[package]] name = "kvdb-rocksdb" -version = "0.9.1" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44947dd392f09475af614d740fe0320b66d01cb5b977f664bbbb5e45a70ea4c1" +checksum = "34446c373ccc494c2124439281c198c7636ccdc2752c06722bbffd56d459c1e4" dependencies = [ "fs-swap", "kvdb", @@ -2994,7 +2861,7 @@ dependencies = [ "num_cpus", "owning_ref", "parity-util-mem", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "regex", "rocksdb", "smallvec 1.6.1", @@ -3012,11 +2879,17 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" +[[package]] +name = "leb128" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3576a87f2ba00f6f106fdfcd16db1d698d648a26ad8e0573cad8537c3c362d2a" + [[package]] name = "libc" -version = "0.2.85" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ccac4b00700875e6a07c6cde370d44d32fa01c5a65cdd2fca6858c479d28bb3" +checksum = "265d751d31d6780a3f956bb5b8022feba2d94eeee5a84ba64f4212eedca42213" [[package]] name = "libloading" @@ -3036,13 +2909,13 @@ checksum = "c7d73b3f436185384286bd8098d17ec07c9a7d2388a6599f824d8502b529702a" [[package]] name = "libp2p" -version = "0.28.1" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "571f5a4604c1a40d75651da141dfde29ad15329f537a779528803297d2220274" +checksum = "d5133112ce42be9482f6a87be92a605dd6bbc9e93c297aee77d172ff06908f3a" dependencies = [ "atomic", - "bytes 0.5.6", - "futures 0.3.12", + "bytes 1.0.1", + "futures 0.3.13", "lazy_static", "libp2p-core", "libp2p-core-derive", @@ -3065,26 +2938,25 @@ dependencies = [ "libp2p-wasm-ext", "libp2p-websocket", "libp2p-yamux", - "multihash", "parity-multiaddr", - "parking_lot 0.10.2", - "pin-project 0.4.27", + "parking_lot 0.11.1", + "pin-project 1.0.5", "smallvec 1.6.1", "wasm-timer", ] [[package]] name = "libp2p-core" -version = "0.22.1" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f13ba8c7df0768af2eb391696d562c7de88cc3a35122531aaa6a7d77754d25" +checksum = "8a2d56aadc2c2bf22cd7797f86e56a65b5b3994a0136b65be3106938acae7a26" dependencies = [ "asn1_der", - "bs58 0.3.1", + "bs58", "ed25519-dalek", "either", "fnv", - "futures 0.3.12", + "futures 0.3.13", "futures-timer 3.0.2", "lazy_static", "libsecp256k1", @@ -3092,64 +2964,65 @@ dependencies = [ "multihash", "multistream-select", "parity-multiaddr", - "parking_lot 0.10.2", - "pin-project 0.4.27", + "parking_lot 0.11.1", + "pin-project 1.0.5", "prost", "prost-build", "rand 0.7.3", "ring", "rw-stream-sink", - "sha2 0.8.2", + "sha2 0.9.3", "smallvec 1.6.1", "thiserror", - "unsigned-varint 0.4.0", + "unsigned-varint 0.7.0", "void", "zeroize", ] [[package]] name = "libp2p-core-derive" -version = "0.20.2" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f753d9324cd3ec14bf04b8a8cd0d269c87f294153d6bf2a84497a63a5ad22213" +checksum = "f4bc40943156e42138d22ed3c57ff0e1a147237742715937622a99b10fbe0156" dependencies = [ - "quote 1.0.8", - "syn 1.0.60", + "quote", + "syn", ] [[package]] name = "libp2p-deflate" -version = "0.22.0" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74029ae187f35f4b8ddf26b9779a68b340045d708528a103917cdca49a296db5" +checksum = "6d42eed63305f0420736fa487f9acef720c4528bd7852a6a760f5ccde4813345" dependencies = [ "flate2", - "futures 0.3.12", + "futures 0.3.13", "libp2p-core", ] [[package]] name = "libp2p-dns" -version = "0.22.0" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cf319822e08dd65c8e060d2354e9f952895bbc433f5706c75ed010c152aee5e" +checksum = "5153b6db68fd4baa3b304e377db744dd8fea8ff4e4504509ee636abcde88d3e3" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "libp2p-core", "log", ] [[package]] name = "libp2p-floodsub" -version = "0.22.0" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8a9acb43a3e4a4e413e0c4abe0fa49308df7c6335c88534757b647199cb8a51" +checksum = "b3c63dfa06581b24b1d12bf9815b43689a784424be217d6545c800c7c75a207f" dependencies = [ "cuckoofilter", "fnv", - "futures 0.3.12", + "futures 0.3.13", "libp2p-core", "libp2p-swarm", + "log", "prost", "prost-build", "rand 0.7.3", @@ -3158,37 +3031,37 @@ dependencies = [ [[package]] name = "libp2p-gossipsub" -version = "0.22.0" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab20fcb60edebe3173bbb708c6ac3444afdf1e3152dc2866b10c4f5497f17467" +checksum = "12451ba9493e87c91baf2a6dffce9ddf1fbc807a0861532d7cf477954f8ebbee" dependencies = [ - "base64 0.11.0", - "byteorder 1.4.2", - "bytes 0.5.6", + "asynchronous-codec 0.5.0", + "base64 0.13.0", + "byteorder", + "bytes 1.0.1", "fnv", - "futures 0.3.12", - "futures_codec", + "futures 0.3.13", "hex_fmt", "libp2p-core", "libp2p-swarm", "log", - "lru_time_cache", "prost", "prost-build", "rand 0.7.3", - "sha2 0.8.2", + "regex", + "sha2 0.9.3", "smallvec 1.6.1", - "unsigned-varint 0.4.0", + "unsigned-varint 0.6.0", "wasm-timer", ] [[package]] name = "libp2p-identify" -version = "0.22.0" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56396ee63aa9164eacf40c2c5d2bda8c4133c2f57e1b0425d51d3a4e362583b1" +checksum = "b40fb36a059b7a8cce1514bd8b546fa612e006c9937caa7f5950cb20021fe91e" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "libp2p-core", "libp2p-swarm", "log", @@ -3200,98 +3073,98 @@ dependencies = [ [[package]] name = "libp2p-kad" -version = "0.23.0" +version = "0.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7fa9047f8b8f544278a35c2d9d45d3b2c1785f2d86d4e1629d6edf97be3955" +checksum = "cf3da6c9acbcc05f93235d201d7d45ef4e8b88a45d8836f98becd8b4d443f066" dependencies = [ "arrayvec 0.5.2", - "bytes 0.5.6", + "asynchronous-codec 0.6.0", + "bytes 1.0.1", "either", "fnv", - "futures 0.3.12", - "futures_codec", + "futures 0.3.13", "libp2p-core", "libp2p-swarm", "log", - "multihash", "prost", "prost-build", "rand 0.7.3", - "sha2 0.8.2", + "sha2 0.9.3", "smallvec 1.6.1", "uint", - "unsigned-varint 0.4.0", + "unsigned-varint 0.7.0", "void", "wasm-timer", ] [[package]] name = "libp2p-mdns" -version = "0.22.0" +version = "0.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3173b5a6b2f690c29ae07798d85b9441a131ac76ddae9015ef22905b623d0c69" +checksum = "0e9e6374814d1b118d97ccabdfc975c8910bd16dc38a8bc058eeb08bf2080fe1" dependencies = [ - "async-std", + "async-io", "data-encoding", "dns-parser", - "either", - "futures 0.3.12", + "futures 0.3.13", + "if-watch", "lazy_static", "libp2p-core", "libp2p-swarm", "log", - "net2", "rand 0.7.3", "smallvec 1.6.1", + "socket2", "void", - "wasm-timer", ] [[package]] name = "libp2p-mplex" -version = "0.22.0" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a73a799cc8410b36e40b8f4c4b6babbcb9efd3727111bf517876e4acfa612d3" +checksum = "350ce8b3923594aedabd5d6e3f875d058435052a29c3f32df378bc70d10be464" dependencies = [ - "bytes 0.5.6", - "fnv", - "futures 0.3.12", - "futures_codec", + "asynchronous-codec 0.6.0", + "bytes 1.0.1", + "futures 0.3.13", "libp2p-core", "log", - "parking_lot 0.10.2", - "unsigned-varint 0.4.0", + "nohash-hasher", + "parking_lot 0.11.1", + "rand 0.7.3", + "smallvec 1.6.1", + "unsigned-varint 0.7.0", ] [[package]] name = "libp2p-noise" -version = "0.24.0" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef6c490042f549fb1025f2892dfe6083d97a77558f450c1feebe748ca9eb15a" +checksum = "4aca322b52a0c5136142a7c3971446fb1e9964923a526c9cc6ef3b7c94e57778" dependencies = [ - "bytes 0.5.6", - "curve25519-dalek 2.1.2", - "futures 0.3.12", + "bytes 1.0.1", + "curve25519-dalek 3.0.2", + "futures 0.3.13", "lazy_static", "libp2p-core", "log", "prost", "prost-build", "rand 0.7.3", - "sha2 0.8.2", + "sha2 0.9.3", "snow", "static_assertions", - "x25519-dalek 0.6.0", + "x25519-dalek", "zeroize", ] [[package]] name = "libp2p-ping" -version = "0.22.0" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad063c21dfcea4518ac9e8bd4119d33a5b26c41e674f602f41f05617a368a5c8" +checksum = "6f3813276d0708c8db0f500d8beda1bda9ad955723b9cb272c41f4727256f73c" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "libp2p-core", "libp2p-swarm", "log", @@ -3302,31 +3175,30 @@ dependencies = [ [[package]] name = "libp2p-plaintext" -version = "0.22.0" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "903a12e99c72dbebefea258de887982adeacc7025baa1ceb10b7fa9928f54791" +checksum = "9d58defcadb646ae4b033e130b48d87410bf76394dc3335496cae99dac803e61" dependencies = [ - "bytes 0.5.6", - "futures 0.3.12", - "futures_codec", + "asynchronous-codec 0.6.0", + "bytes 1.0.1", + "futures 0.3.13", "libp2p-core", "log", "prost", "prost-build", - "rw-stream-sink", - "unsigned-varint 0.4.0", + "unsigned-varint 0.7.0", "void", ] [[package]] name = "libp2p-pnet" -version = "0.19.2" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96b3c2d5d26a9500e959a0e19743897239a6c4be78dadf99b70414301a70c006" +checksum = "6ce3374f3b28162db9d3442c9347c4f14cb01e8290052615c7d341d40eae0599" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "log", - "pin-project 0.4.27", + "pin-project 1.0.5", "rand 0.7.3", "salsa20", "sha3 0.9.1", @@ -3334,32 +3206,32 @@ dependencies = [ [[package]] name = "libp2p-request-response" -version = "0.3.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c0c9e8a4cd69d97e9646c54313d007512f411aba8c5226cfcda16df6a6e84a3" +checksum = "10e5552827c33d8326502682da73a0ba4bfa40c1b55b216af3c303f32169dd89" dependencies = [ "async-trait", - "bytes 0.5.6", - "futures 0.3.12", + "bytes 1.0.1", + "futures 0.3.13", "libp2p-core", "libp2p-swarm", "log", - "lru 0.6.4", + "lru", "minicbor", "rand 0.7.3", "smallvec 1.6.1", - "unsigned-varint 0.5.1", + "unsigned-varint 0.7.0", "wasm-timer", ] [[package]] name = "libp2p-swarm" -version = "0.22.0" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7193e444210132237b81b755ec7fe53f1c4bd2f53cf719729b94c0c72eb6eaa1" +checksum = "7955b973e1fd2bd61ffd43ce261c1223f61f4aacd5bae362a924993f9a25fd98" dependencies = [ "either", - "futures 0.3.12", + "futures 0.3.13", "libp2p-core", "log", "rand 0.7.3", @@ -3370,15 +3242,16 @@ dependencies = [ [[package]] name = "libp2p-tcp" -version = "0.22.0" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44f42ec130d7a37a7e47bf4398026b7ad9185c08ed26972e2720f8b94112796f" +checksum = "88a5aef80e519a6cb8e2663605142f97baaaea1a252eecbf8756184765f7471b" dependencies = [ - "async-std", - "futures 0.3.12", + "async-io", + "futures 0.3.13", "futures-timer 3.0.2", - "get_if_addrs", + "if-watch", "ipnet", + "libc", "libp2p-core", "log", "socket2", @@ -3386,23 +3259,23 @@ dependencies = [ [[package]] name = "libp2p-uds" -version = "0.22.0" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dea7acb0a034f70d7db94c300eba3f65c0f6298820105624088a9609c9974d77" +checksum = "80ac51ce419f60be966e02103c17f67ff5dc4422ba83ba54d251d6c62a4ed487" dependencies = [ "async-std", - "futures 0.3.12", + "futures 0.3.13", "libp2p-core", "log", ] [[package]] name = "libp2p-wasm-ext" -version = "0.22.0" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34c1faac6f92c21fbe155417957863ea822fba9e9fd5eb24c0912336a100e63f" +checksum = "6149c46cb76935c80bc8be6ec6e3ebd5f5e1679765a255fb34331d54610f15dd" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "js-sys", "libp2p-core", "parity-send-wrapper", @@ -3412,31 +3285,29 @@ dependencies = [ [[package]] name = "libp2p-websocket" -version = "0.23.0" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d650534ebd99f48f6fa292ed5db10d30df2444943afde4407ceeddab8e513fca" +checksum = "d3b1c6a3431045da8b925ed83384e4c5163e14b990572307fca9c507435d4d22" dependencies = [ - "async-tls", "either", - "futures 0.3.12", + "futures 0.3.13", + "futures-rustls", "libp2p-core", "log", "quicksink", - "rustls", "rw-stream-sink", "soketto", - "url 2.2.0", - "webpki", - "webpki-roots 0.18.0", + "url 2.2.1", + "webpki-roots", ] [[package]] name = "libp2p-yamux" -version = "0.25.0" +version = "0.30.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "781d9b9f043dcdabc40640807125368596b849fd4d96cdca2dcf052fdf6f33fd" +checksum = "4819358c542a86ff95f6ae691efb4b94ddaf477079b01a686f5705b79bfc232a" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "libp2p-core", "parking_lot 0.11.1", "thiserror", @@ -3451,7 +3322,7 @@ checksum = "eb5b56f651c204634b936be2f92dbb42c36867e00ff7fe2405591f3b9fa66f09" dependencies = [ "bindgen", "cc", - "glob 0.3.0", + "glob", "libc", ] @@ -3499,31 +3370,21 @@ dependencies = [ [[package]] name = "linregress" -version = "0.1.7" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9290cf6f928576eeb9c096c6fad9d8d452a0a1a70a2bbffa6e36064eedc0aac9" +checksum = "0d0ad4b5cc8385a881c561fac3501353d63d2a2b7a357b5064d71815c9a92724" dependencies = [ - "failure", "nalgebra", "statrs", ] -[[package]] -name = "lock_api" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62ebf1391f6acad60e5c8b43706dde4582df75c06698ab44511d15016bc2442c" -dependencies = [ - "scopeguard 0.3.3", -] - [[package]] name = "lock_api" version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4da24a77a3d8a6d4862d95f72e6fdb9c09a643ecdb402d754004a557f2bec75" dependencies = [ - "scopeguard 1.1.0", + "scopeguard", ] [[package]] @@ -3532,62 +3393,37 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd96ffd135b2fd7b973ac026d28085defbe8983df057ced3eb4f2130b0831312" dependencies = [ - "scopeguard 1.1.0", -] - -[[package]] -name = "lockdrop-oracle" -version = "1.7.0" -dependencies = [ - "ethabi", - "hex", - "hex-literal 0.2.1", - "libsecp256k1", - "log", - "pallet-plasm-lockdrop", - "parity-scale-codec", - "reqwest", - "sc-service", - "serde_json", - "sp-core", - "structopt", - "tide", - "web3", + "scopeguard", ] [[package]] name = "log" -version = "0.4.13" +version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcf3805d4480bb5b86070dcfeb9e2cb2ebc148adb753c5cca5f884d1d65a42b2" +checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" dependencies = [ - "cfg-if 0.1.10", + "cfg-if 1.0.0", + "value-bag", ] [[package]] name = "lru" -version = "0.4.3" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0609345ddee5badacf857d4f547e0e5a2e987db77085c24cd887f73573a04237" +checksum = "1f374d42cdfc1d7dbf3d3dec28afab2eb97ffbf43a3234d795b5986dbf4b90ba" dependencies = [ - "hashbrown 0.6.3", + "hashbrown", ] [[package]] -name = "lru" -version = "0.6.4" +name = "mach" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe2382d8ed3918ea4ba70d98d5b74e47a168e0331965f3f17cdbc748bdebc5a3" +checksum = "b823e83b2affd8f40a9ee8c29dbc56404c1e34cd2710921f2801e2cf29527afa" dependencies = [ - "hashbrown 0.9.1", + "libc", ] -[[package]] -name = "lru_time_cache" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb241df5c4caeb888755363fc95f8a896618dc0d435e9e775f7930cb099beab" - [[package]] name = "matchers" version = "0.0.1" @@ -3618,15 +3454,6 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" -[[package]] -name = "median" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7a2f0913a78cc1ac23b01a818180dc3eeeb6f148f561078ac342c70cbc2d277" -dependencies = [ - "generic-array 0.11.1", -] - [[package]] name = "memchr" version = "2.3.4" @@ -3634,13 +3461,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ee1c47aaa256ecabcaea351eae4a9b01ef39ed810004e298d2511ed284b1525" [[package]] -name = "memmap" -version = "0.7.0" +name = "memmap2" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6585fd95e7bb50d6cc31e20d4cf9afb4e2ba16c5846fc76793f11218da9c475b" +checksum = "04e3e85b970d650e2ae6d70592474087051c11c54da7f7b4949725c5735fbcc6" dependencies = [ "libc", - "winapi 0.3.9", ] [[package]] @@ -3649,7 +3475,7 @@ version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "043175f069eda7b85febe4a74abbaeff828d9f8b448515d3151a14a3542811aa" dependencies = [ - "autocfg 1.0.1", + "autocfg", ] [[package]] @@ -3658,17 +3484,17 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "157b4208e3059a8f9e78d559edc658e13df41410cb3ae03979c83130067fdd87" dependencies = [ - "autocfg 1.0.1", + "autocfg", ] [[package]] name = "memory-db" -version = "0.24.1" +version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36f36ddb0b2cdc25d38babba472108798e3477f02be5165f038c5e393e50c57a" +checksum = "814bbecfc0451fc314eeea34f05bbcd5b98a7ad7af37faee088b86a1e633f1d4" dependencies = [ "hash-db", - "hashbrown 0.8.2", + "hashbrown", "parity-util-mem", ] @@ -3684,56 +3510,40 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e261cf0f8b3c42ded9f7d2bb59dea03aa52bc8a1cbc7482f9fc3fd1229d3b42" dependencies = [ - "byteorder 1.4.2", + "byteorder", "keccak", "rand_core 0.5.1", "zeroize", ] -[[package]] -name = "mime" -version = "0.3.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" - -[[package]] -name = "mime_guess" -version = "2.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2684d4c2e97d99848d30b324b00c8fcc7e5c897b7cbb5819b09e7c90e8baf212" -dependencies = [ - "mime", - "unicase", -] - [[package]] name = "minicbor" -version = "0.5.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fc03ad6f8f548db7194a5ff5a6f96342ecae4e3ef67d2bf18bacc0e245cd041" +checksum = "1c2b2c73f9640fccab53947e2b3474d5071fcbc8f82cac51ddf6c8041a30a9ea" dependencies = [ "minicbor-derive", ] [[package]] name = "minicbor-derive" -version = "0.4.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c214bf3d90099b52f3e4b328ae0fe34837fd0fab683ad1e10fceb4629106df48" +checksum = "19ce18b5423c573a13e80cb3046ea0af6379ef725dc3af4886bdb8f4e5093068" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] name = "miniz_oxide" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f2d26ec3309788e423cfbf68ad1800f061638098d76a83681af979dc4eda19d" +checksum = "a92518e98c078586bc6c934028adcca4c92a53d6a958196de835170a01d84e4b" dependencies = [ "adler", - "autocfg 1.0.1", + "autocfg", ] [[package]] @@ -3812,21 +3622,54 @@ dependencies = [ "winapi 0.3.9", ] +[[package]] +name = "more-asserts" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0debeb9fcf88823ea64d64e4a815ab1643f33127d995978e099942ce38f25238" + +[[package]] +name = "multibase" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b78c60039650ff12e140ae867ef5299a58e19dded4d334c849dc7177083667e2" +dependencies = [ + "base-x", + "data-encoding", + "data-encoding-macro", +] + [[package]] name = "multihash" -version = "0.11.4" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567122ab6492f49b59def14ecc36e13e64dca4188196dd0cd41f9f3f979f3df6" +checksum = "4dac63698b887d2d929306ea48b63760431ff8a24fac40ddb22f9c7f49fb7cab" dependencies = [ "blake2b_simd", "blake2s_simd", + "blake3", "digest 0.9.0", - "sha-1 0.9.3", + "generic-array 0.14.4", + "multihash-derive", "sha2 0.9.3", "sha3 0.9.1", "unsigned-varint 0.5.1", ] +[[package]] +name = "multihash-derive" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ee3c48cb9d9b275ad967a0e96715badc13c6029adb92f34fa17b9ff28fd81f" +dependencies = [ + "proc-macro-crate", + "proc-macro-error", + "proc-macro2", + "quote", + "syn", + "synstructure", +] + [[package]] name = "multimap" version = "0.8.2" @@ -3835,32 +3678,33 @@ checksum = "1255076139a83bb467426e7f8d0134968a8118844faa755985e077cf31850333" [[package]] name = "multistream-select" -version = "0.8.5" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93faf2e41f9ee62fb01680ed48f3cc26652352327aa2e59869070358f6b7dd75" +checksum = "7d91ec0a2440aaff5f78ec35631a7027d50386c6163aa975f7caa0d5da4b6ff8" dependencies = [ - "bytes 0.5.6", - "futures 0.3.12", + "bytes 1.0.1", + "futures 0.3.13", "log", "pin-project 1.0.5", "smallvec 1.6.1", - "unsigned-varint 0.5.1", + "unsigned-varint 0.7.0", ] [[package]] name = "nalgebra" -version = "0.18.1" +version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aaa9fddbc34c8c35dd2108515587b8ce0cab396f17977b8c738568e4edb521a2" +checksum = "d6b6147c3d50b4f3cdabfe2ecc94a0191fd3d6ad58aefd9664cf396285883486" dependencies = [ - "alga", "approx", - "generic-array 0.12.3", + "generic-array 0.13.2", "matrixmultiply", "num-complex", "num-rational", "num-traits", - "rand 0.6.5", + "rand 0.7.3", + "rand_distr", + "simba", "typenum", ] @@ -3873,32 +3717,14 @@ dependencies = [ "rand 0.3.23", ] -[[package]] -name = "native-tls" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8d96b2e1c8da3957d58100b09f102c6d9cfdfced01b7ec5a8974044bb09dbd4" -dependencies = [ - "lazy_static", - "libc", - "log", - "openssl", - "openssl-probe", - "openssl-sys", - "schannel", - "security-framework 2.0.0", - "security-framework-sys 2.0.0", - "tempfile", -] - [[package]] name = "nb-connect" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8123a81538e457d44b933a02faf885d3fe8408806b23fa700e8f01c6c3a98998" +checksum = "670361df1bc2399ee1ff50406a0d422587dd3bb0da596e1978fe8e05dabddf4f" dependencies = [ "libc", - "winapi 0.3.9", + "socket2", ] [[package]] @@ -3912,19 +3738,6 @@ dependencies = [ "winapi 0.3.9", ] -[[package]] -name = "nix" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50e4785f2c3b7589a0d0c1dd60285e1188adac4006e8abd6dd578e1567027363" -dependencies = [ - "bitflags", - "cc", - "cfg-if 0.1.10", - "libc", - "void", -] - [[package]] name = "nodrop" version = "0.1.14" @@ -3953,7 +3766,7 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "090c7f9998ee0ff65aa5b723e4009f7b217707f1fb5ea551329cc4d6231fb304" dependencies = [ - "autocfg 1.0.1", + "autocfg", "num-integer", "num-traits", ] @@ -3964,7 +3777,7 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6b19411a9719e753aff12e5187b74d60d3dc449ec3f4dc21e3989c3f554bc95" dependencies = [ - "autocfg 1.0.1", + "autocfg", "num-traits", ] @@ -3974,7 +3787,7 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db" dependencies = [ - "autocfg 1.0.1", + "autocfg", "num-traits", ] @@ -3984,7 +3797,7 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c000134b5dbf44adc5cb772486d335293351644b801551abe8f75c84cfa4aef" dependencies = [ - "autocfg 1.0.1", + "autocfg", "num-bigint", "num-integer", "num-traits", @@ -3996,7 +3809,7 @@ version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" dependencies = [ - "autocfg 1.0.1", + "autocfg", "libm", ] @@ -4012,24 +3825,25 @@ dependencies = [ [[package]] name = "object" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9a7ab5d64814df0fe4a4b5ead45ed6c5f181ee3ff04ba344313a6c80446c5d4" - -[[package]] -name = "once_cell" -version = "0.1.8" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "532c29a261168a45ce28948f9537ddd7a5dd272cc513b3017b1e82a88f962c37" +checksum = "8d3b63360ec3cb337817c2dbd47ab4a0f170d285d8e5a2064600f3def1402397" dependencies = [ - "parking_lot 0.7.1", + "crc32fast", + "indexmap", ] +[[package]] +name = "object" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9a7ab5d64814df0fe4a4b5ead45ed6c5f181ee3ff04ba344313a6c80446c5d4" + [[package]] name = "once_cell" -version = "1.5.2" +version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13bd41f508810a131401606d54ac32a467c97172d74ba7662562ebba5ad07fa0" +checksum = "ea78b9742c52ac729753c1590e9adc5248ea9bdaf974597efd46c74cfaa5fb54" dependencies = [ "parking_lot 0.11.1", ] @@ -4046,63 +3860,12 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" -[[package]] -name = "openssl" -version = "0.10.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "038d43985d1ddca7a9900630d8cd031b56e4794eecc2e9ea39dd17aa04399a70" -dependencies = [ - "bitflags", - "cfg-if 1.0.0", - "foreign-types", - "lazy_static", - "libc", - "openssl-sys", -] - [[package]] name = "openssl-probe" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77af24da69f9d9341038eba93a073b1fdaaa1b788221b00a69bce9e762cb32de" -[[package]] -name = "openssl-sys" -version = "0.9.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "921fc71883267538946025deffb622905ecad223c28efbfdef9bb59a0175f3e6" -dependencies = [ - "autocfg 1.0.1", - "cc", - "libc", - "pkg-config", - "vcpkg", -] - -[[package]] -name = "ovmi" -version = "0.1.0" -dependencies = [ - "hash-db", - "hex", - "hex-literal 0.2.1", - "lazy_static", - "parity-scale-codec", - "primitive-types", - "serde", - "serde_json", - "sp-core", - "sp-runtime", -] - -[[package]] -name = "ovmi-cli" -version = "0.1.0" -dependencies = [ - "ovmi", - "serde_json", -] - [[package]] name = "owning_ref" version = "0.4.1" @@ -4114,13 +3877,13 @@ dependencies = [ [[package]] name = "pallet-authorship" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4b04a80b2d09fcaacaea6190926012348df6ddb225690de098cb8c4cf3fd19b" +checksum = "47433a94141451e7079aabf3ca28f2bde8c642d84b568be9626e9b7cae8b11b1" dependencies = [ "frame-support", "frame-system", - "impl-trait-for-tuples", + "impl-trait-for-tuples 0.2.1", "parity-scale-codec", "sp-authorship", "sp-inherents", @@ -4130,9 +3893,9 @@ dependencies = [ [[package]] name = "pallet-babe" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17e2d59cd974996dd81af46e14eefdf8183b39b11bcfd8efa2c2a3ca7b6d923b" +checksum = "fff7cb57d8df5fb919529ad6553ab4e49260592ed03f2a68a42b2bc53d644949" dependencies = [ "frame-benchmarking", "frame-support", @@ -4156,9 +3919,9 @@ dependencies = [ [[package]] name = "pallet-balances" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "452c3bfacacee9b272f4236a2bcad488dcb5751ebfd592b2cd8921fa5017df16" +checksum = "41aaeaf084e594273f82bcbf96416ef1fcab602e15dd1df04b9930eceb2eb518" dependencies = [ "frame-benchmarking", "frame-support", @@ -4169,42 +3932,19 @@ dependencies = [ "sp-std", ] -[[package]] -name = "pallet-contract-operator" -version = "1.7.0" -dependencies = [ - "derive_more 0.14.1", - "frame-support", - "frame-system", - "hex-literal 0.2.1", - "pallet-balances", - "pallet-contracts", - "pallet-plasm-support", - "pallet-randomness-collective-flip", - "pallet-timestamp", - "pallet-transaction-payment", - "parity-scale-codec", - "serde", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", - "wabt", -] - [[package]] name = "pallet-contracts" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b29ec11235d233bf0581cf291f82a39b1a0a6665a52abe7507097ffa15d77c8c" +checksum = "d0979c1dd82fc56a87b37311006fe56f406de027c24591353058e9e9fc56487c" dependencies = [ - "bitflags", "frame-support", "frame-system", "pallet-contracts-primitives", + "pallet-contracts-proc-macro", "parity-scale-codec", "parity-wasm", - "pwasm-utils", + "pwasm-utils 0.16.0", "serde", "sp-core", "sp-io", @@ -4216,24 +3956,36 @@ dependencies = [ [[package]] name = "pallet-contracts-primitives" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "500f8c78addfa87d4ae5f84de78d7887d3ae7db6c8c8660161a883551a5f7e52" +checksum = "621d75148763349f72e76e79f62365d28adb51e3f2e0285e4e8b8600ae600978" dependencies = [ + "bitflags", "parity-scale-codec", "sp-runtime", "sp-std", ] +[[package]] +name = "pallet-contracts-proc-macro" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90046017aeee3f77752a6c77cdfb1bc93eb728591dc6edad36e2706f7626fd50" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "pallet-contracts-rpc" -version = "0.8.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef28f226cba2527ee19b23501072d277d2cd8add5b8cdc055b7a4344503a696c" +checksum = "22491e3c304819f96c83d02e43bd99128e4e42a57da4d6a9d4b5193778da915b" dependencies = [ "jsonrpc-core 15.1.0", - "jsonrpc-core-client", - "jsonrpc-derive", + "jsonrpc-core-client 15.1.0", + "jsonrpc-derive 15.1.0", "pallet-contracts-primitives", "pallet-contracts-rpc-runtime-api", "parity-scale-codec", @@ -4247,9 +3999,9 @@ dependencies = [ [[package]] name = "pallet-contracts-rpc-runtime-api" -version = "0.8.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "943fb45a9eade6da9ec1330361473cd667a3e755b10b7234f55ed4967ae9d90e" +checksum = "bb4b410cb148e68256e3827854a67ec34b16157f448e78173219dcd6a8ec7343" dependencies = [ "pallet-contracts-primitives", "parity-scale-codec", @@ -4260,11 +4012,11 @@ dependencies = [ [[package]] name = "pallet-custom-signatures" -version = "1.7.0" +version = "1.8.0" dependencies = [ "frame-support", "frame-system", - "hex-literal 0.2.1", + "hex-literal", "libsecp256k1", "pallet-balances", "parity-scale-codec", @@ -4276,36 +4028,6 @@ dependencies = [ "sp-std", ] -[[package]] -name = "pallet-dapps-staking" -version = "1.7.0" -dependencies = [ - "derive_more 0.14.1", - "frame-support", - "frame-system", - "hex-literal 0.2.1", - "num-traits", - "pallet-balances", - "pallet-contract-operator", - "pallet-contracts", - "pallet-plasm-rewards", - "pallet-plasm-support", - "pallet-randomness-collective-flip", - "pallet-session", - "pallet-staking", - "pallet-timestamp", - "pallet-transaction-payment", - "parity-scale-codec", - "serde", - "sp-arithmetic", - "sp-core", - "sp-io", - "sp-runtime", - "sp-staking", - "sp-std", - "wabt", -] - [[package]] name = "pallet-ethereum" version = "0.1.0" @@ -4313,20 +4035,21 @@ dependencies = [ "ethereum", "ethereum-types", "evm", + "fp-consensus", + "fp-evm", + "fp-rpc", "frame-support", "frame-system", - "frontier-consensus-primitives", - "frontier-rpc-primitives", "libsecp256k1", "pallet-balances", "pallet-evm", "pallet-timestamp", "parity-scale-codec", - "rlp 0.4.6", + "rlp", "rustc-hex", "serde", "sha3 0.8.2", - "sp-evm", + "sp-core", "sp-io", "sp-runtime", "sp-std", @@ -4334,58 +4057,48 @@ dependencies = [ [[package]] name = "pallet-evm" -version = "2.0.0-rc6" +version = "3.0.0" dependencies = [ "evm", "evm-gasometer", "evm-runtime", + "fp-evm", "frame-support", "frame-system", - "impl-trait-for-tuples", - "log", "pallet-balances", "pallet-timestamp", "parity-scale-codec", "primitive-types", - "ripemd160", - "rlp 0.4.6", + "rlp", "serde", "sha3 0.8.2", "sp-core", - "sp-evm", "sp-io", "sp-runtime", "sp-std", ] [[package]] -name = "pallet-finality-tracker" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9cc2a60c50a1f5eaeea37e2356b525b58a205688b1dc4e0a750e61a4410191d" +name = "pallet-evm-precompile-simple" +version = "3.0.0" dependencies = [ - "frame-support", - "frame-system", - "impl-trait-for-tuples", - "parity-scale-codec", - "serde", - "sp-finality-tracker", - "sp-inherents", - "sp-runtime", - "sp-std", + "evm", + "fp-evm", + "ripemd160", + "sp-core", + "sp-io", ] [[package]] name = "pallet-grandpa" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1f2d199175fa44a595cc4d2e3e5b3decb7a1f03bdac02cd663bbc2fab58af70" +checksum = "7c012cb0337ce1eaf0685be2777bce1ef8c5d7b7be77ea33916c316b40af43fa" dependencies = [ "frame-benchmarking", "frame-support", "frame-system", "pallet-authorship", - "pallet-finality-tracker", "pallet-session", "parity-scale-codec", "serde", @@ -4399,104 +4112,67 @@ dependencies = [ ] [[package]] -name = "pallet-indices" -version = "2.0.1" +name = "pallet-im-online" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f204e45af958dd3bd8fe0e884a00c30fa745b653cc8ed7fe33f9f8db536fd58e" +checksum = "e5149e46f347bfcf7852693a6c2b6143ace94ae1fc2a81ac87a99c92f027329b" dependencies = [ "frame-support", "frame-system", + "pallet-authorship", "parity-scale-codec", "serde", + "sp-application-crypto", "sp-core", "sp-io", - "sp-keyring", "sp-runtime", + "sp-staking", "sp-std", ] [[package]] -name = "pallet-nicks" -version = "2.0.1" +name = "pallet-indices" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb91384f17c95170e1bf43815239873f0a452439cb1010bb4d98d311951646" -dependencies = [ - "frame-support", - "frame-system", - "parity-scale-codec", - "serde", - "sp-io", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "pallet-operator-trading" -version = "1.7.0" +checksum = "c080576a1fbb1187b7da9f4cba739076bbb197f44964892b2d392755920bbf63" dependencies = [ "frame-support", "frame-system", - "pallet-balances", - "pallet-plasm-support", - "pallet-timestamp", "parity-scale-codec", "serde", "sp-core", "sp-io", + "sp-keyring", "sp-runtime", "sp-std", ] [[package]] -name = "pallet-ovm" -version = "1.7.0" +name = "pallet-nicks" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4373fb3928866b1c43c82ac58518ee844811488a5ebd51b00b6af2163766c68" dependencies = [ "frame-support", "frame-system", - "hex-literal 0.2.1", - "lazy_static", - "ovmi", - "pallet-balances", "parity-scale-codec", "serde", - "sp-arithmetic", - "sp-core", "sp-io", "sp-runtime", "sp-std", ] [[package]] -name = "pallet-ovm-rpc-runtime-api" -version = "0.1.0" -dependencies = [ - "parity-scale-codec", - "sp-api", - "sp-std", -] - -[[package]] -name = "pallet-plasm-lockdrop" -version = "1.7.0" +name = "pallet-offences" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82ed59a0c9489ccf9d20d934dfdffcddc705685035bf8a2e2a8fdad0134eef50" dependencies = [ - "bs58 0.3.1", "frame-support", "frame-system", - "generic-array 0.11.1", - "hex", - "hex-literal 0.2.1", - "median", - "num-traits", "pallet-balances", - "pallet-session", - "pallet-timestamp", "parity-scale-codec", - "plasm-primitives", "serde", - "sp-arithmetic", - "sp-core", - "sp-io", - "sp-keyring", "sp-runtime", "sp-staking", "sp-std", @@ -4504,11 +4180,11 @@ dependencies = [ [[package]] name = "pallet-plasm-rewards" -version = "1.7.0" +version = "1.8.0" dependencies = [ "frame-support", "frame-system", - "hex-literal 0.2.1", + "hex-literal", "num-traits", "pallet-balances", "pallet-randomness-collective-flip", @@ -4527,7 +4203,7 @@ dependencies = [ [[package]] name = "pallet-plasm-support" -version = "1.7.0" +version = "1.8.0" dependencies = [ "frame-support", "sp-runtime", @@ -4536,11 +4212,11 @@ dependencies = [ [[package]] name = "pallet-plasm-validator" -version = "1.7.0" +version = "1.8.0" dependencies = [ "frame-support", "frame-system", - "hex-literal 0.2.1", + "hex-literal", "pallet-balances", "pallet-plasm-rewards", "pallet-randomness-collective-flip", @@ -4556,43 +4232,11 @@ dependencies = [ "sp-std", ] -[[package]] -name = "pallet-plasma" -version = "1.7.0" -dependencies = [ - "frame-support", - "frame-system", - "hex-literal 0.2.1", - "lazy_static", - "pallet-balances", - "pallet-contracts", - "pallet-ovm", - "pallet-randomness-collective-flip", - "pallet-timestamp", - "pallet-transaction-payment", - "parity-scale-codec", - "serde", - "sp-arithmetic", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "pallet-plasma-rpc-runtime-api" -version = "0.1.0" -dependencies = [ - "parity-scale-codec", - "sp-api", - "sp-std", -] - [[package]] name = "pallet-randomness-collective-flip" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "620221883f96e1b3d6288f29b3a87a0f27acaae069a15516440d5a5b8a66d2e3" +checksum = "ca3ea6fa9aa36735ec11d7ec4d97dd6472650c0656fdc6d4adaca2578bd71134" dependencies = [ "frame-support", "frame-system", @@ -4604,9 +4248,9 @@ dependencies = [ [[package]] name = "pallet-scheduler" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30da3f349dad70619631018c263a7499401ddb16609ba5615a7856c2f182d1ba" +checksum = "11230ac868a04833d27a18f37d00572d26866f4718e9cce0557d698e3997b6d6" dependencies = [ "frame-benchmarking", "frame-support", @@ -4620,13 +4264,13 @@ dependencies = [ [[package]] name = "pallet-session" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d239080d33f284a388b8510ffff3d08452314515e122c2f979d8989578e638aa" +checksum = "6d243c3ccac56a4c55fade6be5c5af1de07fac374fa7856377980a76b0c193cf" dependencies = [ "frame-support", "frame-system", - "impl-trait-for-tuples", + "impl-trait-for-tuples 0.2.1", "pallet-timestamp", "parity-scale-codec", "serde", @@ -4641,9 +4285,9 @@ dependencies = [ [[package]] name = "pallet-staking" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "def1b8639275c25dd621ae68a18c25d14f14992031c360eff98dd6a1d0095213" +checksum = "c95853affe89b7b755b2e7d1fcf7f8804b074dea53d98703f9b8b6ebf28dfb32" dependencies = [ "frame-support", "frame-system", @@ -4662,9 +4306,9 @@ dependencies = [ [[package]] name = "pallet-sudo" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f85da30f939010eef16b54bd5a7af6517ce8ba04c8de4ccfd49e092eeb284e0" +checksum = "c4a96774302e3824b7924c2465935ca4d558ea5f6a762c043fbc45fd2646ce89" dependencies = [ "frame-support", "frame-system", @@ -4677,14 +4321,14 @@ dependencies = [ [[package]] name = "pallet-timestamp" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e206c754d6cd6d8e6e79ba2ea1a55f72af68be106e7d725d367c11c52c96da32" +checksum = "b17dd274716a55a2c3e34d9c0ed66aaac3d7e0393ec9fd985e2b8532d697a7f3" dependencies = [ "frame-benchmarking", "frame-support", "frame-system", - "impl-trait-for-tuples", + "impl-trait-for-tuples 0.2.1", "parity-scale-codec", "serde", "sp-inherents", @@ -4695,13 +4339,12 @@ dependencies = [ [[package]] name = "pallet-transaction-payment" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a34775aaf85a16cb1db44a1bef33c4ce6ef327fedb0c8eda7543991ccee7f73" +checksum = "48e10dc1a10dd3f52edb20d3885cf5b2b16f26273a4d93e61331c6691fb13ab3" dependencies = [ "frame-support", "frame-system", - "pallet-transaction-payment-rpc-runtime-api", "parity-scale-codec", "serde", "smallvec 1.6.1", @@ -4713,16 +4356,15 @@ dependencies = [ [[package]] name = "pallet-transaction-payment-rpc" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8523248607c065de24924df7da7b2ac1d8255f9d7758439de5a1225e1c4a4bb9" +checksum = "7835717b7d8fb59c33dd73f083c68a6d143a1dbe6029364c63ea7f4cb0ba3f9c" dependencies = [ "jsonrpc-core 15.1.0", - "jsonrpc-core-client", - "jsonrpc-derive", + "jsonrpc-core-client 15.1.0", + "jsonrpc-derive 15.1.0", "pallet-transaction-payment-rpc-runtime-api", "parity-scale-codec", - "serde", "sp-api", "sp-blockchain", "sp-core", @@ -4732,23 +4374,21 @@ dependencies = [ [[package]] name = "pallet-transaction-payment-rpc-runtime-api" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31dee86d07fe9c5493be5ec01d53759cc2fd65b55b5c144ba7d2bb28fa8c243c" +checksum = "7a92d3383260d0d19d9a36f40766d48d779fd19baccba8b20c3e7d2670a26ee1" dependencies = [ - "frame-support", + "pallet-transaction-payment", "parity-scale-codec", - "serde", "sp-api", "sp-runtime", - "sp-std", ] [[package]] name = "pallet-utility" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c4578a0a2133fb7c5ef5c55ef7d0fe8e0e7a4bd8cedee308ee97fa10903966d" +checksum = "fcd63d1b336800d155ab60ee918afd111f7449e44cec936f460d555e850fa93b" dependencies = [ "frame-support", "frame-system", @@ -4762,41 +4402,43 @@ dependencies = [ [[package]] name = "parity-db" -version = "0.1.2" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00d595e372d119261593297debbe4193811a4dc811d2a1ccbb8caaa6666ad7ab" +checksum = "111e193c96758d476d272093a853882668da17489f76bf4361b8decae0b6c515" dependencies = [ "blake2-rfc", "crc32fast", + "hex", "libc", "log", - "memmap", - "parking_lot 0.10.2", + "memmap2", + "parking_lot 0.11.1", + "rand 0.8.3", ] [[package]] name = "parity-multiaddr" -version = "0.9.7" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbecae7b7cfaafea47ceb5253ecdd14155ca8410e3487ed86031a6c2d5c15873" +checksum = "d2c6805f98667a3828afb2ec2c396a8d610497e8d546f5447188aae47c5a79ec" dependencies = [ "arrayref", - "bs58 0.4.0", - "byteorder 1.4.2", + "bs58", + "byteorder", "data-encoding", "multihash", "percent-encoding 2.1.0", "serde", "static_assertions", - "unsigned-varint 0.5.1", - "url 2.2.0", + "unsigned-varint 0.7.0", + "url 2.2.1", ] [[package]] name = "parity-scale-codec" -version = "1.3.6" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79602888a81ace83e3d1d4b2873286c1f5f906c84db667594e8db8da3506c383" +checksum = "0cd3dab59b5cf4bc81069ade0fc470341a1ef3ad5fa73e5a8943bed2ec12b2e8" dependencies = [ "arrayvec 0.5.2", "bitvec", @@ -4807,14 +4449,14 @@ dependencies = [ [[package]] name = "parity-scale-codec-derive" -version = "1.2.2" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "198db82bb1c18fc00176004462dd809b2a6d851669550aa17af6dacd21ae0c14" +checksum = "fa04976a81fde04924b40cc4036c4d12841e8bb04325a5cf2ada75731a150a7d" dependencies = [ "proc-macro-crate", - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -4830,7 +4472,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e57fea504fea33f9fbb5f49f378359030e7e026a6ab849bb9e8f0787376f1bf" dependencies = [ "bytes 0.4.12", - "futures 0.1.30", + "futures 0.1.31", "libc", "log", "mio-named-pipes", @@ -4844,15 +4486,16 @@ dependencies = [ [[package]] name = "parity-util-mem" -version = "0.7.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "297ff91fa36aec49ce183484b102f6b75b46776822bd81525bfc4cc9b0dd0f5c" +checksum = "664a8c6b8e62d8f9f2f937e391982eb433ab285b4cd9545b342441e04a906e42" dependencies = [ - "cfg-if 0.1.10", - "hashbrown 0.8.2", - "impl-trait-for-tuples", + "cfg-if 1.0.0", + "hashbrown", + "impl-trait-for-tuples 0.2.1", + "jemallocator", "parity-util-mem-derive", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "primitive-types", "smallvec 1.6.1", "winapi 0.3.9", @@ -4864,8 +4507,8 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f557c32c6d268a07c921471619c0295f5efad3a0e76d4f97a05c091a51d110b2" dependencies = [ - "proc-macro2 1.0.24", - "syn 1.0.60", + "proc-macro2", + "syn", "synstructure", ] @@ -4881,7 +4524,7 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e02a625dd75084c2a7024f07c575b61b782f729d18702dabb3cdbf31911dc61" dependencies = [ - "byteorder 1.4.2", + "byteorder", "bytes 0.4.12", "httparse", "log", @@ -4890,7 +4533,7 @@ dependencies = [ "rand 0.7.3", "sha-1 0.8.2", "slab", - "url 2.2.0", + "url 2.2.1", ] [[package]] @@ -4899,16 +4542,6 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "427c3892f9e783d91cc128285287e70a59e206ca452770ece88a76f7a3eddd72" -[[package]] -name = "parking_lot" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab41b4aed082705d1056416ae4468b6ea99d52599ecf3169b00088d43113e337" -dependencies = [ - "lock_api 0.1.5", - "parking_lot_core 0.4.0", -] - [[package]] name = "parking_lot" version = "0.9.0" @@ -4917,7 +4550,7 @@ checksum = "f842b1982eb6c2fe34036a4fbfb06dd185a3f5c8edfaacdf7d1ea10b07de6252" dependencies = [ "lock_api 0.3.4", "parking_lot_core 0.6.2", - "rustc_version", + "rustc_version 0.2.3", ] [[package]] @@ -4938,20 +4571,7 @@ checksum = "6d7744ac029df22dca6284efe4e898991d28e3085c706c972bcd7da4a27a15eb" dependencies = [ "instant", "lock_api 0.4.2", - "parking_lot_core 0.8.2", -] - -[[package]] -name = "parking_lot_core" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94c8c7923936b28d546dfd14d4472eaf34c99b14e1c973a32b3e6d4eb04298c9" -dependencies = [ - "libc", - "rand 0.6.5", - "rustc_version", - "smallvec 0.6.14", - "winapi 0.3.9", + "parking_lot_core 0.8.3", ] [[package]] @@ -4964,7 +4584,7 @@ dependencies = [ "cloudabi", "libc", "redox_syscall 0.1.57", - "rustc_version", + "rustc_version 0.2.3", "smallvec 0.6.14", "winapi 0.3.9", ] @@ -4985,14 +4605,14 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ccb628cad4f84851442432c60ad8e1f607e29752d0bf072cbd0baf28aa34272" +checksum = "fa7a782938e745763fe6907fc6ba86946d72f49fe7e21de074e08128a99fb018" dependencies = [ "cfg-if 1.0.0", "instant", "libc", - "redox_syscall 0.1.57", + "redox_syscall 0.2.5", "smallvec 1.6.1", "winapi 0.3.9", ] @@ -5007,6 +4627,12 @@ dependencies = [ "proc-macro-hack", ] +[[package]] +name = "paste" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5d65c4d95931acda4498f675e332fcbdc9a06705cd07086c510e9b6009cd1c1" + [[package]] name = "paste-impl" version = "0.1.18" @@ -5022,9 +4648,17 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "006c038a43a45995a9670da19e67600114740e8511d4333bf97a56e66a7542d9" dependencies = [ - "byteorder 1.4.2", - "crypto-mac 0.7.0", - "rayon", + "byteorder", + "crypto-mac 0.7.0", +] + +[[package]] +name = "pbkdf2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "216eaa586a190f0a738f2f918511eecfa90f13295abec0e457cdebcceda80cbd" +dependencies = [ + "crypto-mac 0.8.0", ] [[package]] @@ -5051,6 +4685,15 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" +[[package]] +name = "pest" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10f4872ae94d7b90ae48754df22fd42ad52ce740b8f370b03da4835417403e53" +dependencies = [ + "ucd-trie", +] + [[package]] name = "petgraph" version = "0.5.1" @@ -5085,9 +4728,9 @@ version = "0.4.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65ad2ae56b6abe3a1ee25f15ee605bacadb9a764edaba9c2bf4103800d4a1895" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -5096,9 +4739,9 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "758669ae3558c6f74bd2a18b41f7ac0b5a195aea6639d6a9b5e5d1ad5ba24c0b" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -5109,9 +4752,9 @@ checksum = "c917123afa01924fc84bb20c4c03f004d9c38e5127e3c039bbf7f4b9c76a2f6b" [[package]] name = "pin-project-lite" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439697af366c49a6d0a010c56a0d97685bc140ce0d377b13a2ea2aa42d64a827" +checksum = "0cf491442e4b033ed1c722cb9f0df5fcfcf4de682466c46469c36bc47dc5548a" [[package]] name = "pin-utils" @@ -5125,25 +4768,28 @@ version = "0.3.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3831453b3449ceb48b6d9c7ad7c96d5ea673e9b470a1dc578c2ce6521230884c" +[[package]] +name = "plasm" +version = "1.8.0" +dependencies = [ + "parity-util-mem", + "plasm-cli", +] + [[package]] name = "plasm-cli" -version = "1.7.0" +version = "1.8.0" dependencies = [ + "fc-consensus", + "fc-rpc-core", + "fp-consensus", "frame-system", - "frontier-consensus", - "futures 0.3.12", + "futures 0.3.13", "hex", - "hex-literal 0.2.1", - "jsonrpc-core 15.1.0", - "jsonrpc-pubsub", - "lockdrop-oracle", - "log", + "hex-literal", "pallet-contracts", - "pallet-dapps-staking", "pallet-evm", - "pallet-finality-tracker", - "pallet-ovm", - "pallet-plasm-lockdrop", + "pallet-im-online", "pallet-transaction-payment", "parity-scale-codec", "plasm-primitives", @@ -5156,6 +4802,7 @@ dependencies = [ "sc-client-db", "sc-consensus", "sc-consensus-babe", + "sc-consensus-slots", "sc-executor", "sc-finality-grandpa", "sc-network", @@ -5180,7 +4827,7 @@ dependencies = [ [[package]] name = "plasm-primitives" -version = "1.7.0" +version = "1.8.0" dependencies = [ "frame-system", "parity-scale-codec", @@ -5191,12 +4838,13 @@ dependencies = [ [[package]] name = "plasm-rpc" -version = "1.7.0" +version = "1.8.0" dependencies = [ - "frontier-rpc", - "frontier-rpc-primitives", + "fc-rpc", + "fc-rpc-core", + "fp-rpc", "jsonrpc-core 15.1.0", - "jsonrpc-pubsub", + "jsonrpc-pubsub 15.1.0", "pallet-contracts-rpc", "pallet-transaction-payment-rpc", "plasm-primitives", @@ -5207,7 +4855,6 @@ dependencies = [ "sc-consensus-epochs", "sc-finality-grandpa", "sc-finality-grandpa-rpc", - "sc-keystore", "sc-network", "sc-rpc", "sc-rpc-api", @@ -5216,6 +4863,7 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-consensus-babe", + "sp-keystore", "sp-runtime", "sp-transaction-pool", "substrate-frame-rpc-system", @@ -5223,36 +4871,32 @@ dependencies = [ [[package]] name = "plasm-runtime" -version = "1.7.0" +version = "1.8.0" dependencies = [ + "fp-rpc", "frame-executive", "frame-support", "frame-system", "frame-system-rpc-runtime-api", - "frontier-rpc-primitives", - "hex-literal 0.2.1", + "hex-literal", "lazy_static", "pallet-authorship", "pallet-babe", "pallet-balances", - "pallet-contract-operator", "pallet-contracts", "pallet-contracts-primitives", "pallet-contracts-rpc-runtime-api", "pallet-custom-signatures", - "pallet-dapps-staking", "pallet-ethereum", "pallet-evm", - "pallet-finality-tracker", + "pallet-evm-precompile-simple", "pallet-grandpa", + "pallet-im-online", "pallet-indices", "pallet-nicks", - "pallet-operator-trading", - "pallet-ovm", - "pallet-plasm-lockdrop", + "pallet-offences", "pallet-plasm-rewards", "pallet-plasm-validator", - "pallet-plasma", "pallet-randomness-collective-flip", "pallet-scheduler", "pallet-session", @@ -5282,9 +4926,9 @@ dependencies = [ [[package]] name = "platforms" -version = "0.2.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "feb3b2b1033b8a60b4da6ee470325f887758c95d5320f52f9ce0df055a55940e" +checksum = "989d43012e2ca1c4a02507c67282691a0a3207f9dc67cec596b43fe925b3d325" [[package]] name = "polling" @@ -5328,9 +4972,9 @@ checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857" [[package]] name = "primitive-types" -version = "0.7.3" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd39dcacf71411ba488570da7bbc89b717225e46478b30ba99b92db6b149809" +checksum = "2415937401cb030a2a0a4d922483f945fa068f52a7dbb22ce0fe5f2b6f6adace" dependencies = [ "fixed-hash", "impl-codec", @@ -5355,9 +4999,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" dependencies = [ "proc-macro-error-attr", - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", "version_check", ] @@ -5367,8 +5011,8 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", + "proc-macro2", + "quote", "version_check", ] @@ -5384,31 +5028,22 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc881b2c22681370c6a780e47af9840ef841837bc98118431d4e1868bd0c1086" -[[package]] -name = "proc-macro2" -version = "0.4.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" -dependencies = [ - "unicode-xid 0.1.0", -] - [[package]] name = "proc-macro2" version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71" dependencies = [ - "unicode-xid 0.2.1", + "unicode-xid", ] [[package]] name = "prometheus" -version = "0.10.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30d70cf4412832bcac9cffe27906f4a66e450d323525e977168c70d1b36120ae" +checksum = "c8425533e7122f0c3cc7a37e6244b16ad3a2cc32ae7ac6276e2a75da0d9c200d" dependencies = [ - "cfg-if 0.1.10", + "cfg-if 1.0.0", "fnv", "lazy_static", "parking_lot 0.11.1", @@ -5418,21 +5053,21 @@ dependencies = [ [[package]] name = "prost" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce49aefe0a6144a45de32927c77bd2859a5f7677b55f220ae5b744e87389c212" +checksum = "9e6984d2f1a23009bd270b8bb56d0926810a3d483f59c987d77969e9d8e840b2" dependencies = [ - "bytes 0.5.6", + "bytes 1.0.1", "prost-derive", ] [[package]] name = "prost-build" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02b10678c913ecbd69350e8535c3aef91a8676c0773fc1d7b95cdd196d7f2f26" +checksum = "32d3ebd75ac2679c2af3a92246639f9fcc8a442ee420719cc4fe195b98dd5fa3" dependencies = [ - "bytes 0.5.6", + "bytes 1.0.1", "heck", "itertools", "log", @@ -5441,39 +5076,59 @@ dependencies = [ "prost", "prost-types", "tempfile", - "which", + "which 4.0.2", ] [[package]] name = "prost-derive" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "537aa19b95acde10a12fec4301466386f757403de4cd4e5b4fa78fb5ecb18f72" +checksum = "169a15f3008ecb5160cba7d37bcd690a7601b6d30cfb87a117d45e59d52af5d4" dependencies = [ "anyhow", "itertools", - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] name = "prost-types" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1834f67c0697c001304b75be76f67add9c89742eda3a085ad8ee0bb38c3417aa" +checksum = "b518d7cdd93dab1d1122cf07fa9a60771836c668dde9d9e2a139f957f0d9f1bb" dependencies = [ - "bytes 0.5.6", + "bytes 1.0.1", "prost", ] +[[package]] +name = "psm" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3abf49e5417290756acfd26501536358560c4a5cc4a0934d390939acb3e7083a" +dependencies = [ + "cc", +] + [[package]] name = "pwasm-utils" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f53bc2558e8376358ebdc28301546471d67336584f6438ed4b7c7457a055fd7" dependencies = [ - "byteorder 1.4.2", + "byteorder", + "log", + "parity-wasm", +] + +[[package]] +name = "pwasm-utils" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c8ac87af529432d3a4f0e2b3bbf08af49f28f09cc73ed7e551161bdaef5f78d" +dependencies = [ + "byteorder", "log", "parity-wasm", ] @@ -5497,27 +5152,18 @@ dependencies = [ [[package]] name = "quote" -version = "0.6.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" -dependencies = [ - "proc-macro2 0.4.30", -] - -[[package]] -name = "quote" -version = "1.0.8" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "991431c3519a3f36861882da93630ce66b52918dcf1b8e2fd66b397fc96f28df" +checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7" dependencies = [ - "proc-macro2 1.0.24", + "proc-macro2", ] [[package]] name = "radium" -version = "0.3.0" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "def50a86306165861203e7f84ecffbbdfdea79f0e51039b33de1e952358c47ac" +checksum = "643f8f41a8ebc4c5dc4515c82bb8abd397b527fc20fd681b7c011c2aee5d44fb" [[package]] name = "rand" @@ -5542,38 +5188,6 @@ dependencies = [ "winapi 0.3.9", ] -[[package]] -name = "rand" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" -dependencies = [ - "cloudabi", - "fuchsia-cprng", - "libc", - "rand_core 0.3.1", - "winapi 0.3.9", -] - -[[package]] -name = "rand" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca" -dependencies = [ - "autocfg 0.1.7", - "libc", - "rand_chacha 0.1.1", - "rand_core 0.4.2", - "rand_hc 0.1.0", - "rand_isaac", - "rand_jitter", - "rand_os", - "rand_pcg 0.1.2", - "rand_xorshift", - "winapi 0.3.9", -] - [[package]] name = "rand" version = "0.7.3" @@ -5585,7 +5199,7 @@ dependencies = [ "rand_chacha 0.2.2", "rand_core 0.5.1", "rand_hc 0.2.0", - "rand_pcg 0.2.1", + "rand_pcg", ] [[package]] @@ -5596,20 +5210,10 @@ checksum = "0ef9e7e66b4468674bfcb0c81af8b7fa0bb154fa9f28eb840da5c447baeb8d7e" dependencies = [ "libc", "rand_chacha 0.3.0", - "rand_core 0.6.1", + "rand_core 0.6.2", "rand_hc 0.3.0", ] -[[package]] -name = "rand_chacha" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "556d3a1ca6600bfcbab7c7c91ccb085ac7fbbcd70e008a98742e7847f4f7bcef" -dependencies = [ - "autocfg 0.1.7", - "rand_core 0.3.1", -] - [[package]] name = "rand_chacha" version = "0.2.2" @@ -5627,7 +5231,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e12735cf05c9e10bf21534da50a147b924d555dc7a547c42e6bb2d5b6017ae0d" dependencies = [ "ppv-lite86", - "rand_core 0.6.1", + "rand_core 0.6.2", ] [[package]] @@ -5656,20 +5260,20 @@ dependencies = [ [[package]] name = "rand_core" -version = "0.6.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c026d7df8b298d90ccbbc5190bd04d85e159eaf5576caeacf8741da93ccbd2e5" +checksum = "34cf66eb183df1c5876e2dcf6b13d57340741e8dc255b48e40a26de954d06ae7" dependencies = [ "getrandom 0.2.2", ] [[package]] -name = "rand_hc" -version = "0.1.0" +name = "rand_distr" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4" +checksum = "96977acbdd3a6576fb1d27391900035bf3863d4a16422973a409b488cf29ffb2" dependencies = [ - "rand_core 0.3.1", + "rand 0.7.3", ] [[package]] @@ -5687,51 +5291,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3190ef7066a446f2e7f42e239d161e905420ccab01eb967c9eb27d21b2322a73" dependencies = [ - "rand_core 0.6.1", -] - -[[package]] -name = "rand_isaac" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08" -dependencies = [ - "rand_core 0.3.1", -] - -[[package]] -name = "rand_jitter" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1166d5c91dc97b88d1decc3285bb0a99ed84b05cfd0bc2341bdf2d43fc41e39b" -dependencies = [ - "libc", - "rand_core 0.4.2", - "winapi 0.3.9", -] - -[[package]] -name = "rand_os" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071" -dependencies = [ - "cloudabi", - "fuchsia-cprng", - "libc", - "rand_core 0.4.2", - "rdrand", - "winapi 0.3.9", -] - -[[package]] -name = "rand_pcg" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abf9b09b01790cfe0364f52bf32995ea3c39f4d2dd011eac241d2914146d0b44" -dependencies = [ - "autocfg 0.1.7", - "rand_core 0.4.2", + "rand_core 0.6.2", ] [[package]] @@ -5744,12 +5304,14 @@ dependencies = [ ] [[package]] -name = "rand_xorshift" -version = "0.1.1" +name = "raw-cpuid" +version = "8.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c" +checksum = "1fdf7d9dbd43f3d81d94a49c1c3df73cc2b3827995147e6cf7f89d4ec5483e73" dependencies = [ - "rand_core 0.3.1", + "bitflags", + "cc", + "rustc_version 0.2.3", ] [[package]] @@ -5764,7 +5326,7 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b0d8e0819fadc20c74ea8373106ead0600e3a67ef1fe8da56e39b9ae7275674" dependencies = [ - "autocfg 1.0.1", + "autocfg", "crossbeam-deque 0.8.0", "either", "rayon-core", @@ -5778,7 +5340,7 @@ checksum = "9ab346ac5921dc62ffa9f89b7a773907511cdfa5490c572ae9be1be33e8afa4a" dependencies = [ "crossbeam-channel", "crossbeam-deque 0.8.0", - "crossbeam-utils 0.8.1", + "crossbeam-utils 0.8.3", "lazy_static", "num_cpus", ] @@ -5800,9 +5362,9 @@ checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce" [[package]] name = "redox_syscall" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05ec8ca9416c5ea37062b502703cd7fcb207736bc294f6e0cf367ac6fc234570" +checksum = "94341e4e44e24f6b591b59e47a8a027df12e008d73fd5672dbea9cc22f4507d9" dependencies = [ "bitflags", ] @@ -5818,6 +5380,16 @@ dependencies = [ "rust-argon2", ] +[[package]] +name = "redox_users" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "528532f3d801c87aec9def2add9ca802fe569e44a544afe633765267840abe64" +dependencies = [ + "getrandom 0.2.2", + "redox_syscall 0.2.5", +] + [[package]] name = "ref-cast" version = "1.0.6" @@ -5833,9 +5405,20 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c38e3aecd2b21cb3959637b883bb3714bc7e43f0268b9a29d3743ee3e55cdd2" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "regalloc" +version = "0.0.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "571f7f397d61c4755285cd37853fe8e03271c243424a907415909379659381c5" +dependencies = [ + "log", + "rustc-hash", + "smallvec 1.6.1", ] [[package]] @@ -5856,7 +5439,7 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae1ded71d66a4a97f5e961fd0cb25a5f366a42a41570d16a763a69c092c26ae4" dependencies = [ - "byteorder 1.4.2", + "byteorder", "regex-syntax", ] @@ -5867,49 +5450,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5eb417147ba9860a96cfe72a0b93bf88fee1744b5636ec99ab20c1aa9376581" [[package]] -name = "remove_dir_all" -version = "0.5.3" +name = "region" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" +checksum = "877e54ea2adcd70d80e9179344c97f93ef0dffd6b03e1f4529e6e83ab2fa9ae0" dependencies = [ + "bitflags", + "libc", + "mach", "winapi 0.3.9", ] [[package]] -name = "reqwest" -version = "0.10.10" +name = "remove_dir_all" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0718f81a8e14c4dbb3b34cf23dc6aaf9ab8a0dfec160c534b3dbca1aaa21f47c" +checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" dependencies = [ - "base64 0.13.0", - "bytes 0.5.6", - "encoding_rs", - "futures-core", - "futures-util", - "http 0.2.3", - "http-body 0.3.1", - "hyper 0.13.10", - "hyper-rustls", - "ipnet", - "js-sys", - "lazy_static", - "log", - "mime", - "mime_guess", - "percent-encoding 2.1.0", - "pin-project-lite 0.2.4", - "rustls", - "serde", - "serde_json", - "serde_urlencoded", - "tokio 0.2.25", - "tokio-rustls", - "url 2.2.0", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "webpki-roots 0.20.0", - "winreg", + "winapi 0.3.9", ] [[package]] @@ -5920,13 +5478,13 @@ checksum = "53552c6c49e1e13f1a203ef0080ab3bbef0beb570a528993e83df057a9d9bba1" [[package]] name = "ring" -version = "0.16.12" +version = "0.16.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ba5a8ec64ee89a76c98c549af81ff14813df09c3e6dc4766c3856da48597a0c" +checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" dependencies = [ "cc", - "lazy_static", "libc", + "once_cell", "spin", "untrusted", "web-sys", @@ -5944,15 +5502,6 @@ dependencies = [ "opaque-debug 0.3.0", ] -[[package]] -name = "rlp" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1190dcc8c3a512f1eef5d09bb8c84c7f39e1054e174d1795482e18f5272f2e73" -dependencies = [ - "rustc-hex", -] - [[package]] name = "rlp" version = "0.5.0" @@ -5969,9 +5518,9 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e33d7b2abe0c340d8797fe2907d3f20d3b5ea5908683618bfe80df7f621f672a" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -5984,17 +5533,11 @@ dependencies = [ "librocksdb-sys", ] -[[package]] -name = "route-recognizer" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56770675ebc04927ded3e60633437841581c285dc6236109ea25fbf3beb7b59e" - [[package]] name = "rpassword" -version = "4.0.5" +version = "5.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99371657d3c8e4d816fb6221db98fa408242b0b53bac08f8676a41f8554fe99f" +checksum = "ffc936cf8a7ea60c58f030fd36a612a48f440610214dc54bc36431f9ea0c3efb" dependencies = [ "libc", "winapi 0.3.9", @@ -6009,7 +5552,7 @@ dependencies = [ "base64 0.13.0", "blake2b_simd", "constant_time_eq", - "crossbeam-utils 0.8.1", + "crossbeam-utils 0.8.3", ] [[package]] @@ -6036,7 +5579,16 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" dependencies = [ - "semver", + "semver 0.9.0", +] + +[[package]] +name = "rustc_version" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0dfe2087c51c460008730de8b57e6a320782fbfb312e1f4d520e6c6fae155ee" +dependencies = [ + "semver 0.11.0", ] [[package]] @@ -6052,6 +5604,19 @@ dependencies = [ "webpki", ] +[[package]] +name = "rustls" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "064fd21ff87c6e87ed4506e68beb42459caa4a0e2eb144932e6776768556980b" +dependencies = [ + "base64 0.13.0", + "log", + "ring", + "sct", + "webpki", +] + [[package]] name = "rustls-native-certs" version = "0.4.0" @@ -6059,9 +5624,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "629d439a7672da82dd955498445e496ee2096fe2117b9f796558a43fdb9e59b8" dependencies = [ "openssl-probe", - "rustls", + "rustls 0.18.1", "schannel", - "security-framework 1.0.0", + "security-framework", ] [[package]] @@ -6070,7 +5635,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4da5fcb054c46f5a5dff833b129285a93d3f0179531735e6c866e8cc307d2020" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "pin-project 0.4.27", "static_assertions", ] @@ -6087,25 +5652,25 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d3d055a2582e6b00ed7a31c1524040aa391092bf636328350813f3a0605215c" dependencies = [ - "rustc_version", + "rustc_version 0.2.3", ] [[package]] name = "salsa20" -version = "0.6.0" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f47b10fa80f6969bbbd9c8e7cc998f082979d402a9e10579e2303a87955395" +checksum = "399f290ffc409596022fce5ea5d4138184be4784f2b28c62c59f0d8389059a15" dependencies = [ - "stream-cipher", + "cipher", ] [[package]] name = "sc-basic-authorship" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c087f2beb766773fd08e4c9df6296868a41ce8f3ea5e3d42eff78a09e89dd7c" +checksum = "de86afb63617599821312bda08882451ff2b49d9c45e22513ddff5a07c6d966e" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "futures-timer 3.0.2", "log", "parity-scale-codec", @@ -6121,14 +5686,13 @@ dependencies = [ "sp-runtime", "sp-transaction-pool", "substrate-prometheus-endpoint", - "tokio-executor 0.2.0-alpha.6", ] [[package]] name = "sc-block-builder" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39ed774daf2956291bb2ed943fcfa93ebb3d956db54b96c0d1f476185dbf601b" +checksum = "9862161f9d09d870401c7256c89ad1eb3afa56a61f7d7135c2bac76ff7152955" dependencies = [ "parity-scale-codec", "sc-client-api", @@ -6144,60 +5708,56 @@ dependencies = [ [[package]] name = "sc-chain-spec" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb9a5bfd8e2de21b2ec0041961b3d8c134473a2ed7a7558ad84dff417101b97c" +checksum = "50d97030776b49bc9c109e2d349212d8f2500637761048e1af5b7ce2dfd994c7" dependencies = [ - "impl-trait-for-tuples", + "impl-trait-for-tuples 0.2.1", "parity-scale-codec", "sc-chain-spec-derive", + "sc-consensus-babe", + "sc-consensus-epochs", + "sc-finality-grandpa", "sc-network", "sc-telemetry", "serde", "serde_json", "sp-chain-spec", + "sp-consensus-babe", "sp-core", "sp-runtime", ] [[package]] name = "sc-chain-spec-derive" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e8725cf0c53da3734df5b89b3b4f457fba6c3d359762f3a24b24ec9c4011830" +checksum = "5f14985513db9798fcedea58bdc8a08f1c6b3a515d6546ced7467b059b7982c4" dependencies = [ "proc-macro-crate", - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] name = "sc-cli" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3655ef6fcc2dd8a167085fa6d5ae026819c27e75253a6f927b38d96e00801ee6" +checksum = "7ec1647b5c1483fa05f7f32e436d0e378e2f3d5696a5a30bddf66f5faf28acb4" dependencies = [ - "ansi_term 0.12.1", - "atty", - "bip39", "chrono", - "derive_more 0.99.11", "fdlimit", - "futures 0.3.12", + "futures 0.3.13", "hex", - "lazy_static", "libp2p", "log", "names", - "nix", "parity-scale-codec", - "parity-util-mem", "rand 0.7.3", "regex", "rpassword", "sc-client-api", - "sc-informant", "sc-keystore", "sc-network", "sc-service", @@ -6208,38 +5768,33 @@ dependencies = [ "sp-blockchain", "sp-core", "sp-keyring", + "sp-keystore", "sp-panic-handler", "sp-runtime", - "sp-state-machine", "sp-utils", "sp-version", "structopt", - "substrate-prometheus-endpoint", - "time 0.1.44", + "thiserror", + "tiny-bip39", "tokio 0.2.25", - "tracing", - "tracing-log", - "tracing-subscriber", ] [[package]] name = "sc-client-api" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "592d3f0f8d777e6b21a95217a88859d53eb9b8ced1d6d5f2de917f637c0089b1" +checksum = "56d8b2c8dc0cee9ac56e87ad50c980edbdeb35bdd5b5d9da4ae90567423363be" dependencies = [ - "derive_more 0.99.11", + "derive_more", "fnv", - "futures 0.3.12", + "futures 0.3.13", "hash-db", - "hex-literal 0.3.1", "kvdb", "lazy_static", "log", "parity-scale-codec", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "sc-executor", - "sc-telemetry", "sp-api", "sp-blockchain", "sp-consensus", @@ -6247,7 +5802,7 @@ dependencies = [ "sp-database", "sp-externalities", "sp-inherents", - "sp-keyring", + "sp-keystore", "sp-runtime", "sp-state-machine", "sp-std", @@ -6261,9 +5816,9 @@ dependencies = [ [[package]] name = "sc-client-db" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3db7eeff373a5a3daf93a64857dcaac9a1ba95151868c0cbd65ee3ac12d6a2e7" +checksum = "5741e447d71ff36c147f961b2271b6b3fad0cc347e96936bc8b63ddffa594b27" dependencies = [ "blake2-rfc", "hash-db", @@ -6275,7 +5830,7 @@ dependencies = [ "parity-db", "parity-scale-codec", "parity-util-mem", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "sc-client-api", "sc-executor", "sc-state-db", @@ -6292,9 +5847,9 @@ dependencies = [ [[package]] name = "sc-consensus" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79886c07e275cb1f105459cb439034a5a0d82f310c121b8e43729d171792361b" +checksum = "99f20cc8b8a74e218365ac4187bce26ea631d58d221caa1797bc6ec8056dba33" dependencies = [ "sc-client-api", "sp-blockchain", @@ -6304,13 +5859,13 @@ dependencies = [ [[package]] name = "sc-consensus-babe" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f1f50e27ce3cddd9bed5aeab449ab5f62dbdf8670cba6b1a012e07323ca89b3" +checksum = "98d52048476e0fcb53feae8ca919a602104f1ba0b89a729b496440f36b332961" dependencies = [ - "derive_more 0.99.11", + "derive_more", "fork-tree", - "futures 0.3.12", + "futures 0.3.13", "futures-timer 3.0.2", "log", "merlin", @@ -6318,7 +5873,7 @@ dependencies = [ "num-rational", "num-traits", "parity-scale-codec", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "pdqselect", "rand 0.7.3", "retain_mut", @@ -6336,10 +5891,12 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-consensus-babe", + "sp-consensus-slots", "sp-consensus-vrf", "sp-core", "sp-inherents", "sp-io", + "sp-keystore", "sp-runtime", "sp-timestamp", "sp-utils", @@ -6349,18 +5906,17 @@ dependencies = [ [[package]] name = "sc-consensus-babe-rpc" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "936655f94393a1ead8ac9108c4fdb7e8f3fbdd2a6506b6b9a46a6fee22b01b96" +checksum = "5e5ddc4720f72196a39fcde1eb54bac1cc39a036fad913c1067320e85b0c50f8" dependencies = [ - "derive_more 0.99.11", - "futures 0.3.12", + "derive_more", + "futures 0.3.13", "jsonrpc-core 15.1.0", - "jsonrpc-core-client", - "jsonrpc-derive", + "jsonrpc-core-client 15.1.0", + "jsonrpc-derive 15.1.0", "sc-consensus-babe", "sc-consensus-epochs", - "sc-keystore", "sc-rpc-api", "serde", "sp-api", @@ -6369,18 +5925,19 @@ dependencies = [ "sp-consensus", "sp-consensus-babe", "sp-core", + "sp-keystore", "sp-runtime", ] [[package]] name = "sc-consensus-epochs" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "107e56c59690372725b8d5a6f432c26a0b355776c4cdea9e927dc50528c92a05" +checksum = "326313ffb249a526e8ee8e08af9fdf0c4459cebeaa760b934e9df3985b68e4df" dependencies = [ "fork-tree", "parity-scale-codec", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "sc-client-api", "sp-blockchain", "sp-runtime", @@ -6388,19 +5945,20 @@ dependencies = [ [[package]] name = "sc-consensus-slots" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4c497d8d503496725e31270adb3cb71300d8c1ddf00720ccbc52df339229a86" +checksum = "76e09ff8b680d449102da9717a70c3bbbbb981fd4cf1bfbafc1739d954eb0898" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "futures-timer 3.0.2", "log", "parity-scale-codec", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "sc-client-api", "sc-telemetry", "sp-api", "sp-application-crypto", + "sp-arithmetic", "sp-blockchain", "sp-consensus", "sp-consensus-slots", @@ -6408,13 +5966,15 @@ dependencies = [ "sp-inherents", "sp-runtime", "sp-state-machine", + "sp-trie", + "thiserror", ] [[package]] name = "sc-consensus-uncles" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2c5828de266141d5dad38a55e07de0900efb9ac43acf1ecd02abfeb59c73755" +checksum = "37294bae6d787eecf2b15255dc75cd559b4ad813e0efcf28cd4423e218931b80" dependencies = [ "log", "sc-client-api", @@ -6427,19 +5987,20 @@ dependencies = [ [[package]] name = "sc-executor" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95038e7e148e5529ae3e254e14559253db018e84ff8f9327c3469c2477d3fbc6" +checksum = "bace6a35999d2da7311d8fb98a29c1e89dbf0d14e50ac14140f2c38089819f46" dependencies = [ - "derive_more 0.99.11", + "derive_more", "lazy_static", "libsecp256k1", "log", "parity-scale-codec", "parity-wasm", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "sc-executor-common", "sc-executor-wasmi", + "sc-executor-wasmtime", "sp-api", "sp-core", "sp-externalities", @@ -6447,6 +6008,7 @@ dependencies = [ "sp-panic-handler", "sp-runtime-interface", "sp-serializer", + "sp-tasks", "sp-trie", "sp-version", "sp-wasm-interface", @@ -6455,27 +6017,26 @@ dependencies = [ [[package]] name = "sc-executor-common" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b3772b7631ba1aeae54aee9492a1272e9aaf8b29f20b36d6596ba3ad9540782" +checksum = "87004102a8e95f432f1c624c7fa7fb0edc5995db2e0fcbabbb697f1955e7c1d2" dependencies = [ - "derive_more 0.99.11", - "log", + "derive_more", "parity-scale-codec", "parity-wasm", "sp-allocator", "sp-core", - "sp-runtime-interface", "sp-serializer", "sp-wasm-interface", + "thiserror", "wasmi", ] [[package]] name = "sc-executor-wasmi" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f1579a26b4c15e44ec5c65639bfe99b9594b75907d628435a5771142a4fff1a" +checksum = "2d3d7b6db2df5f2c24848883a855a8276363f00cef5b49744974f7e1203bf274" dependencies = [ "log", "parity-scale-codec", @@ -6487,21 +6048,41 @@ dependencies = [ "wasmi", ] +[[package]] +name = "sc-executor-wasmtime" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24673c981fad2dff4398a09a1086579e2774f18d81639fa2bd9cb215e6dd9e36" +dependencies = [ + "log", + "parity-scale-codec", + "parity-wasm", + "pwasm-utils 0.14.0", + "sc-executor-common", + "scoped-tls", + "sp-allocator", + "sp-core", + "sp-runtime-interface", + "sp-wasm-interface", + "wasmtime", +] + [[package]] name = "sc-finality-grandpa" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45e8f0387bad591eff97c85da017910bdec5b307cfda4a9cefa7838aef182c57" +checksum = "a7e87e63c57933e173a8643ff197b579e3fc5c91b16ca006096f482de8159318" dependencies = [ - "derive_more 0.99.11", + "derive_more", "finality-grandpa", "fork-tree", - "futures 0.3.12", + "futures 0.3.13", "futures-timer 3.0.2", + "linked-hash-map", "log", "parity-scale-codec", - "parking_lot 0.10.2", - "pin-project 0.4.27", + "parking_lot 0.11.1", + "pin-project 1.0.5", "rand 0.7.3", "sc-block-builder", "sc-client-api", @@ -6518,8 +6099,8 @@ dependencies = [ "sp-consensus", "sp-core", "sp-finality-grandpa", - "sp-finality-tracker", "sp-inherents", + "sp-keystore", "sp-runtime", "sp-utils", "substrate-prometheus-endpoint", @@ -6527,17 +6108,17 @@ dependencies = [ [[package]] name = "sc-finality-grandpa-rpc" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03ea0e17531f6615df0778a559dd5b33c5c7b5b4ac847dce9a79bc32e3a39340" +checksum = "145cb4dfafa73269565857c43e204d71f6334c7f1260b783bb5942a6a4e77831" dependencies = [ - "derive_more 0.99.11", + "derive_more", "finality-grandpa", - "futures 0.3.12", + "futures 0.3.13", "jsonrpc-core 15.1.0", - "jsonrpc-core-client", - "jsonrpc-derive", - "jsonrpc-pubsub", + "jsonrpc-core-client 15.1.0", + "jsonrpc-derive 15.1.0", + "jsonrpc-pubsub 15.1.0", "log", "parity-scale-codec", "sc-client-api", @@ -6552,12 +6133,12 @@ dependencies = [ [[package]] name = "sc-informant" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a1216d1c69f8af706793f68436a173b24291e13fc5171dd3b65022d6ce45bb4" +checksum = "4f4c8994853e1158dc4f448b014aa83eef56ced214ec0af316eecf4a6ca3268f" dependencies = [ "ansi_term 0.12.1", - "futures 0.3.12", + "futures 0.3.13", "log", "parity-util-mem", "sc-client-api", @@ -6571,31 +6152,35 @@ dependencies = [ [[package]] name = "sc-keystore" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "032a394435900fabbc8c4e42f2c8022277b6c7db810c8de310af9c5990707b96" +checksum = "d966ed36c404eced656bd63aad8a30d2c1a14633f07cd1d7d9c11b62f75a7905" dependencies = [ - "derive_more 0.99.11", + "async-trait", + "derive_more", + "futures 0.3.13", + "futures-util", "hex", "merlin", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "rand 0.7.3", "serde_json", "sp-application-crypto", "sp-core", + "sp-keystore", "subtle 2.4.0", ] [[package]] name = "sc-light" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb25de28df183903037147093adba25dc6e4e00342e8da87ff3b0341f672ca17" +checksum = "04e8dbcb2951f7cf76ddf97ed26dcef0dab79d76745de4a8f169d58236ea8704" dependencies = [ "hash-db", "lazy_static", "parity-scale-codec", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "sc-client-api", "sc-executor", "sp-api", @@ -6608,34 +6193,35 @@ dependencies = [ [[package]] name = "sc-network" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e41944816f2543f1a350576325b2f43937589df99911440b41edd85accbe793" +checksum = "20fb4ed5d6b86faafb0743c8c2fd1c89b52cde7697373b254c7553800efaebbf" dependencies = [ "async-std", "async-trait", + "asynchronous-codec 0.5.0", "bitflags", - "bs58 0.3.1", - "bytes 0.5.6", - "derive_more 0.99.11", + "bs58", + "bytes 1.0.1", + "cid", + "derive_more", "either", "erased-serde", "fnv", "fork-tree", - "futures 0.3.12", + "futures 0.3.13", "futures-timer 3.0.2", - "futures_codec", "hex", "ip_network", "libp2p", "linked-hash-map", "linked_hash_set", "log", - "lru 0.4.3", + "lru", "nohash-hasher", "parity-scale-codec", - "parking_lot 0.10.2", - "pin-project 0.4.27", + "parking_lot 0.11.1", + "pin-project 1.0.5", "prost", "prost-build", "rand 0.7.3", @@ -6644,9 +6230,7 @@ dependencies = [ "sc-peerset", "serde", "serde_json", - "slog", - "slog_derive", - "smallvec 0.6.14", + "smallvec 1.6.1", "sp-arithmetic", "sp-blockchain", "sp-consensus", @@ -6655,7 +6239,7 @@ dependencies = [ "sp-utils", "substrate-prometheus-endpoint", "thiserror", - "unsigned-varint 0.4.0", + "unsigned-varint 0.6.0", "void", "wasm-timer", "zeroize", @@ -6663,36 +6247,37 @@ dependencies = [ [[package]] name = "sc-network-gossip" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e47d598e67b8dd5786b4898b369fe6809b49dccea629a2fbc3df954357a11f0" +checksum = "e2cd5487d6f8051863a186e2aea4c233a07bb691780d3b117c9d6ffe1ff9a8fe" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "futures-timer 3.0.2", "libp2p", "log", - "lru 0.4.3", + "lru", "sc-network", "sp-runtime", + "substrate-prometheus-endpoint", "wasm-timer", ] [[package]] name = "sc-offchain" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0ba62ba971b00027a686f7378e3a7c8b8ae26f2fa684282269dcb8b64979a5e" +checksum = "7bc91fc71c128748a3393cb3421e12a7759ccffcc1cc4a9e6ff4ead6cc68ba48" dependencies = [ "bytes 0.5.6", "fnv", - "futures 0.3.12", + "futures 0.3.13", "futures-timer 3.0.2", "hyper 0.13.10", "hyper-rustls", "log", "num_cpus", "parity-scale-codec", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "rand 0.7.3", "sc-client-api", "sc-keystore", @@ -6707,11 +6292,11 @@ dependencies = [ [[package]] name = "sc-peerset" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b25fd0cbe552fccb7732735db76e1404ad6faa73db1ac32a6c1849a0d91679" +checksum = "ce454e528e7797a239e734d0d66bf904d48be47aa92691ac7546a45ec32a64cf" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "libp2p", "log", "serde_json", @@ -6721,9 +6306,9 @@ dependencies = [ [[package]] name = "sc-proposer-metrics" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c84e1e897657580ffb1471b1139d4a45c499a5d9f9951314154f980a5bfaa168" +checksum = "ecfc2c6cc5dc0ecb1109cce9773b50ad9a3cdbf239dc702ef9071949244dcf3e" dependencies = [ "log", "substrate-prometheus-endpoint", @@ -6731,27 +6316,29 @@ dependencies = [ [[package]] name = "sc-rpc" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6545650472d32e9c3ba01697b6df1f57ee70f9bcc25582341c0c79a4e4f1e62e" +checksum = "750397c6aa5a4f922cac99599ad74a4082e3e87553d51ceb4c48abfa056ff32c" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "hash-db", "jsonrpc-core 15.1.0", - "jsonrpc-pubsub", + "jsonrpc-pubsub 15.1.0", "log", "parity-scale-codec", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "sc-block-builder", "sc-client-api", "sc-executor", "sc-keystore", "sc-rpc-api", + "sc-tracing", "serde_json", "sp-api", "sp-blockchain", "sp-chain-spec", "sp-core", + "sp-keystore", "sp-offchain", "sp-rpc", "sp-runtime", @@ -6764,19 +6351,19 @@ dependencies = [ [[package]] name = "sc-rpc-api" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a55fed0bc8199907d2b4f06730b0f3f99726fe54da1f2d33287e24b7c7c784be" +checksum = "dc8393410297df2885efec20d0629a9833b4fd9e4ad83a92471e1ea0c11a0a54" dependencies = [ - "derive_more 0.99.11", - "futures 0.3.12", + "derive_more", + "futures 0.3.13", "jsonrpc-core 15.1.0", - "jsonrpc-core-client", - "jsonrpc-derive", - "jsonrpc-pubsub", + "jsonrpc-core-client 15.1.0", + "jsonrpc-derive 15.1.0", + "jsonrpc-pubsub 15.1.0", "log", "parity-scale-codec", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "serde", "serde_json", "sp-chain-spec", @@ -6789,15 +6376,15 @@ dependencies = [ [[package]] name = "sc-rpc-server" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7845e84f57590cf124b4bc4c526d42aa878c4bf523ab4943de78278542d290ce" +checksum = "17c76164897bd3b0d04c2d6aeeb4d3492c86e324b0b08f408b847ea35421b589" dependencies = [ - "futures 0.1.30", + "futures 0.1.31", "jsonrpc-core 15.1.0", "jsonrpc-http-server", "jsonrpc-ipc-server", - "jsonrpc-pubsub", + "jsonrpc-pubsub 15.1.0", "jsonrpc-ws-server", "log", "serde", @@ -6808,25 +6395,24 @@ dependencies = [ [[package]] name = "sc-service" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53ea41ceed173954e72f8fb04a1f52c3472331156a31039b90b018d256f4d15f" +checksum = "a9315b44eb991ca4f477d889bbd649a2b4b557f963fe48ec5a36c3422518e4a0" dependencies = [ - "derive_more 0.99.11", "directories", "exit-future", - "futures 0.1.30", - "futures 0.3.12", + "futures 0.1.31", + "futures 0.3.13", "futures-timer 3.0.2", "hash-db", "jsonrpc-core 15.1.0", - "jsonrpc-pubsub", + "jsonrpc-pubsub 15.1.0", "lazy_static", "log", "parity-scale-codec", "parity-util-mem", - "parking_lot 0.10.2", - "pin-project 0.4.27", + "parking_lot 0.11.1", + "pin-project 1.0.5", "rand 0.7.3", "sc-block-builder", "sc-chain-spec", @@ -6845,7 +6431,6 @@ dependencies = [ "sc-transaction-pool", "serde", "serde_json", - "slog", "sp-api", "sp-application-crypto", "sp-block-builder", @@ -6855,6 +6440,7 @@ dependencies = [ "sp-externalities", "sp-inherents", "sp-io", + "sp-keystore", "sp-runtime", "sp-session", "sp-state-machine", @@ -6865,79 +6451,104 @@ dependencies = [ "sp-version", "substrate-prometheus-endpoint", "tempfile", + "thiserror", "tracing", + "tracing-futures", "wasm-timer", ] [[package]] name = "sc-state-db" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b1b6ad30864b94daf8b65273ce7d6b4b4bd8931fb9b9a9159386f320282dfc6" +checksum = "8f144043d5860ce133f701fa78679d6278f2dfc698686beb5f6d892c267e9d92" dependencies = [ "log", "parity-scale-codec", "parity-util-mem", "parity-util-mem-derive", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "sc-client-api", "sp-core", + "thiserror", ] [[package]] name = "sc-telemetry" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad9e02e7f4b7ee6ace3f6b59c9891dfe05f60c6ef94cc7d3e31411f5a73bd536" +checksum = "d05040c594b331d90d7341e82c6dc6a3eb7bb2afb4e5dc9c36a79a6754166057" dependencies = [ - "futures 0.3.12", - "futures-timer 3.0.2", + "chrono", + "futures 0.3.13", "libp2p", "log", - "parking_lot 0.10.2", - "pin-project 0.4.27", + "parking_lot 0.11.1", + "pin-project 1.0.5", "rand 0.7.3", "serde", - "slog", - "slog-json", - "slog-scope", + "serde_json", + "sp-utils", "take_mut", + "tracing", + "tracing-subscriber", "void", "wasm-timer", ] [[package]] name = "sc-tracing" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aba4d60fa9bf76aea74c64868769f311189539407736bc375d1b6ab0ff598d0b" +checksum = "ef0a4aa327b8bc89d9c5ae57a2f493d8f54ccd706f6763614ab522559fe481d8" dependencies = [ + "ansi_term 0.12.1", + "atty", "erased-serde", + "lazy_static", "log", - "parking_lot 0.10.2", + "once_cell", + "parking_lot 0.11.1", + "regex", "rustc-hash", "sc-telemetry", + "sc-tracing-proc-macro", "serde", "serde_json", - "slog", "sp-tracing", + "thiserror", "tracing", "tracing-core", + "tracing-log", "tracing-subscriber", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "sc-tracing-proc-macro" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec18b0506911e6d624d9ea8f8cc5f503e7944a0fe7d37de95ee84033cf160ebc" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn", ] [[package]] name = "sc-transaction-graph" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53f57f64ce160124404e4a140da79c7d363627830e5bb31b6ac54c6cd6955fdb" +checksum = "87b385b8f66cce185478c500ad3de8f4775ab0e948c31561aeac78a27bedc654" dependencies = [ - "derive_more 0.99.11", - "futures 0.3.12", + "derive_more", + "futures 0.3.13", "linked-hash-map", "log", "parity-util-mem", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "retain_mut", "serde", "sp-blockchain", @@ -6945,23 +6556,23 @@ dependencies = [ "sp-runtime", "sp-transaction-pool", "sp-utils", + "thiserror", "wasm-timer", ] [[package]] name = "sc-transaction-pool" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "749ff49bf873dc43ed85ac86fce64d169c7c7397b720194799e7e6c6eb269972" +checksum = "09f4331ea8da2ff45a9466637f90f5cc89f9d31fcd1cd20f74f2520b33bff069" dependencies = [ - "derive_more 0.99.11", - "futures 0.3.12", + "futures 0.3.13", "futures-diagnose", "intervalier", "log", "parity-scale-codec", "parity-util-mem", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "sc-client-api", "sc-transaction-graph", "sp-api", @@ -6972,6 +6583,7 @@ dependencies = [ "sp-transaction-pool", "sp-utils", "substrate-prometheus-endpoint", + "thiserror", "wasm-timer", ] @@ -6998,16 +6610,17 @@ dependencies = [ "merlin", "rand 0.7.3", "rand_core 0.5.1", + "serde", "sha2 0.8.2", "subtle 2.4.0", "zeroize", ] [[package]] -name = "scopeguard" -version = "0.3.3" +name = "scoped-tls" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94258f53601af11e6a49f722422f6e3425c52b06245a5cf9bc09908b174f5e27" +checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" [[package]] name = "scopeguard" @@ -7016,38 +6629,40 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" [[package]] -name = "sct" -version = "0.6.0" +name = "scroll" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3042af939fca8c3453b7af0f1c66e533a15a86169e39de2657310ade8f98d3c" +checksum = "fda28d4b4830b807a8b43f7b0e6b5df875311b3e7621d84577188c175b6ec1ec" dependencies = [ - "ring", - "untrusted", + "scroll_derive", ] [[package]] -name = "secp256k1" -version = "0.17.2" +name = "scroll_derive" +version = "0.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2932dc07acd2066ff2e3921a4419606b220ba6cd03a9935123856cc534877056" +checksum = "aaaae8f38bb311444cfb7f1979af0bc9240d95795f75f9ceddf6a59b79ceffa0" dependencies = [ - "secp256k1-sys", + "proc-macro2", + "quote", + "syn", ] [[package]] -name = "secp256k1-sys" -version = "0.1.2" +name = "sct" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ab2c26f0d3552a0f12e639ae8a64afc2e3db9c52fe32f5fc6c289d38519f220" +checksum = "e3042af939fca8c3453b7af0f1c66e533a15a86169e39de2657310ade8f98d3c" dependencies = [ - "cc", + "ring", + "untrusted", ] [[package]] name = "secrecy" -version = "0.6.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9182278ed645df3477a9c27bfee0621c621aa16f6972635f7f795dae3d81070f" +checksum = "0673d6a6449f5e7d12a1caf424fd9363e2af3a4953023ed455e3c4beef4597c0" dependencies = [ "zeroize", ] @@ -7059,23 +6674,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad502866817f0575705bd7be36e2b2535cc33262d493aa733a2ec862baa2bc2b" dependencies = [ "bitflags", - "core-foundation 0.7.0", - "core-foundation-sys 0.7.0", - "libc", - "security-framework-sys 1.0.0", -] - -[[package]] -name = "security-framework" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1759c2e3c8580017a484a7ac56d3abc5a6c1feadf88db2f3633f12ae4268c69" -dependencies = [ - "bitflags", - "core-foundation 0.9.1", - "core-foundation-sys 0.8.2", + "core-foundation", + "core-foundation-sys", "libc", - "security-framework-sys 2.0.0", + "security-framework-sys", ] [[package]] @@ -7084,27 +6686,26 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51ceb04988b17b6d1dcd555390fa822ca5637b4a14e1f5099f13d351bed4d6c7" dependencies = [ - "core-foundation-sys 0.7.0", + "core-foundation-sys", "libc", ] [[package]] -name = "security-framework-sys" -version = "2.0.0" +name = "semver" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f99b9d5e26d2a71633cc4f2ebae7cc9f874044e0c351a27e17892d76dce5678b" +checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" dependencies = [ - "core-foundation-sys 0.8.2", - "libc", + "semver-parser 0.7.0", ] [[package]] name = "semver" -version = "0.9.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" +checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" dependencies = [ - "semver-parser", + "semver-parser 0.10.2", ] [[package]] @@ -7113,6 +6714,15 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" +[[package]] +name = "semver-parser" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" +dependencies = [ + "pest", +] + [[package]] name = "serde" version = "1.0.123" @@ -7128,41 +6738,17 @@ version = "1.0.123" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9391c295d64fc0abb2c556bad848f33cb8296276b1ad2677d1ae1ace4f258f31" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] name = "serde_json" -version = "1.0.62" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea1c6153794552ea7cf7cf63b1231a25de00ec90db326ba6264440fa08e31486" -dependencies = [ - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_qs" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5af82de3c6549b001bec34961ff2d6a54339a87bab37ce901b693401f27de6cb" -dependencies = [ - "data-encoding", - "percent-encoding 2.1.0", - "serde", - "thiserror", -] - -[[package]] -name = "serde_urlencoded" -version = "0.7.0" +version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edfa57a7f8d9c1d260a549e7224100f6c43d43f9103e06dd8b4095a9b2b43ce9" +checksum = "799e97dc9fdae36a5c8b8f2cae9ce2ee9fdce2058c57a93e6099d919fd982f79" dependencies = [ - "form_urlencoded", "itoa", "ryu", "serde", @@ -7182,9 +6768,9 @@ dependencies = [ [[package]] name = "sha-1" -version = "0.9.3" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4b312c3731e3fe78a185e6b9b911a7aa715b8e31cce117975219aab2acf285d" +checksum = "dfebf75d25bd900fd1e7d11501efab59bc846dbc76196839663e6637bba9f25f" dependencies = [ "block-buffer 0.9.0", "cfg-if 1.0.0", @@ -7193,12 +6779,6 @@ dependencies = [ "opaque-debug 0.3.0", ] -[[package]] -name = "sha1" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2579985fda508104f7587689507983eadd6a6e84dd35d6d115361f530916fa0d" - [[package]] name = "sha2" version = "0.8.2" @@ -7266,9 +6846,9 @@ checksum = "7fdf1b9db47230893d76faad238fd6097fd6d6a9245cd7a4d90dbd639536bbd2" [[package]] name = "signal-hook" -version = "0.3.4" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "780f5e3fe0c66f67197236097d89de1e86216f1f6fdeaf47c442f854ab46c240" +checksum = "8a7f3f92a1da3d6b1d32245d0cbcbbab0cfc45996d8df619c42bccfa6d2bbb5f" dependencies = [ "libc", "signal-hook-registry", @@ -7290,63 +6870,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f0242b8e50dd9accdd56170e94ca1ebd223b098eb9c83539a6e367d0f36ae68" [[package]] -name = "simple-mutex" -version = "1.1.5" +name = "simba" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38aabbeafa6f6dead8cebf246fe9fae1f9215c8d29b3a69f93bd62a9e4a3dcd6" +checksum = "fb931b1367faadea6b1ab1c306a860ec17aaa5fa39f367d0c744e69d971a1fb2" dependencies = [ - "event-listener", + "approx", + "num-complex", + "num-traits", + "paste 0.1.18", ] [[package]] name = "slab" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" - -[[package]] -name = "slog" -version = "2.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8347046d4ebd943127157b94d63abb990fcf729dc4e9978927fdf4ac3c998d06" -dependencies = [ - "erased-serde", -] - -[[package]] -name = "slog-json" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddc0d2aff1f8f325ef660d9a0eb6e6dcd20b30b3f581a5897f58bf42d061c37a" -dependencies = [ - "chrono", - "erased-serde", - "serde", - "serde_json", - "slog", -] - -[[package]] -name = "slog-scope" -version = "4.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f95a4b4c3274cd2869549da82b57ccc930859bdbf5bcea0424bc5f140b3c786" -dependencies = [ - "arc-swap", - "lazy_static", - "slog", -] - -[[package]] -name = "slog_derive" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a945ec7f7ce853e89ffa36be1e27dce9a43e82ff9093bf3461c30d5da74ed11b" -dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", -] +checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" [[package]] name = "smallvec" @@ -7369,16 +6908,16 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "795dd7aeeee24468e5a32661f6d27f7b5cbed802031b2d7640c7b10f8fb2dd50" dependencies = [ - "aes-gcm 0.7.0", + "aes-gcm", "blake2", "chacha20poly1305", "rand 0.7.3", "rand_core 0.5.1", "ring", - "rustc_version", + "rustc_version 0.2.3", "sha2 0.9.3", "subtle 2.4.0", - "x25519-dalek 1.1.0", + "x25519-dalek", ] [[package]] @@ -7401,31 +6940,31 @@ dependencies = [ "base64 0.12.3", "bytes 0.5.6", "flate2", - "futures 0.3.12", + "futures 0.3.13", "httparse", "log", "rand 0.7.3", - "sha-1 0.9.3", + "sha-1 0.9.4", ] [[package]] name = "sp-allocator" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "019c540ebf398feefe9bf766dee9b2f4f649ca9a7fd7a2f01f0b4d9e4a6d1307" +checksum = "ec5f988ad0cabdb646318cb515a91e9d89062debc9728f9b634d73acab3f3f39" dependencies = [ - "derive_more 0.99.11", "log", "sp-core", "sp-std", "sp-wasm-interface", + "thiserror", ] [[package]] name = "sp-api" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8496732f255ef290eee6d438ebd0ecdbfe31ec8246e31870a4faf44df76b6280" +checksum = "e63c3460d5daecf67df542c34c2bbd636214a5a200d4bddcfa2ffb9e72c346af" dependencies = [ "hash-db", "parity-scale-codec", @@ -7435,26 +6974,27 @@ dependencies = [ "sp-state-machine", "sp-std", "sp-version", + "thiserror", ] [[package]] name = "sp-api-proc-macro" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c863d32b9e36849f2fc76efad959924561b2fcb15b3abdebb3d3f48a94074a00" +checksum = "289624f4fe0f61e63a5019ed26c3bc732b5145eb52796ac6053cd72656d947a1" dependencies = [ "blake2-rfc", "proc-macro-crate", - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] name = "sp-application-crypto" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eda2660cca492b58328d6a057bf5ba6c8a58e9f6e079a2f603b623d030300841" +checksum = "c52e2e6d43036b97c4fce1ed87c5262c1ffdc78c655ada4d3024a3f8094bdd2c" dependencies = [ "parity-scale-codec", "serde", @@ -7465,9 +7005,9 @@ dependencies = [ [[package]] name = "sp-arithmetic" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c4d204b1cf8e1d4826804ffbd2edd2c4df385ee3046fa4581f09bc18977ea89" +checksum = "d0f1c69966c192d1dee8521f0b29ece2b14db07b9b44d801a94e295234761645" dependencies = [ "integer-sqrt", "num-traits", @@ -7479,9 +7019,9 @@ dependencies = [ [[package]] name = "sp-authorship" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c99612989f07a55a160b1d041cac74c9089f97b3d0e0244cdde4ed3e00560ff" +checksum = "1ec68fb8e5a37548b06c14ee91a9c574cc330324c86d37810ec29dd4f8bc68d7" dependencies = [ "parity-scale-codec", "sp-inherents", @@ -7491,9 +7031,9 @@ dependencies = [ [[package]] name = "sp-block-builder" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42446637a0363c14117c9fe2401649bbe5806fa230c731378be9478e2d787121" +checksum = "0adc979dbe619f56d664ebd1293dce13fcad6b8a47bcdd620ed53a454d330d12" dependencies = [ "parity-scale-codec", "sp-api", @@ -7504,27 +7044,28 @@ dependencies = [ [[package]] name = "sp-blockchain" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ba612ede91aa09d602a5f7df18630728a81991fa6b5a13a0071ea00799fb509" +checksum = "e8007c1ad8e9fb6cd8eed4e0fc91504a9ca4b228e1315302a2fbb0ac7f509f1b" dependencies = [ - "derive_more 0.99.11", + "futures 0.3.13", "log", - "lru 0.4.3", + "lru", "parity-scale-codec", - "parking_lot 0.10.2", - "sp-block-builder", + "parking_lot 0.11.1", + "sp-api", "sp-consensus", "sp-database", "sp-runtime", "sp-state-machine", + "thiserror", ] [[package]] name = "sp-chain-spec" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f20aee31e7576ab5bef17345e9c2d4c1863dae3a3cc3ab3540592182e118720d" +checksum = "3a24beb11980d0c755ead0c05f3f966c490e4a3730785c04c03855fada65d697" dependencies = [ "serde", "serde_json", @@ -7532,17 +7073,16 @@ dependencies = [ [[package]] name = "sp-consensus" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb095bf31d07e6b48489b68e127eabd55534c3ac8dc2c04d2fec581bd5f407" +checksum = "884db6c4b03f0f2fb2993127a2db95fc740fcd3496746dcaa6829c9868e7dc75" dependencies = [ - "derive_more 0.99.11", - "futures 0.3.12", + "futures 0.3.13", "futures-timer 3.0.2", "libp2p", "log", "parity-scale-codec", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "serde", "sp-api", "sp-core", @@ -7554,14 +7094,15 @@ dependencies = [ "sp-utils", "sp-version", "substrate-prometheus-endpoint", + "thiserror", "wasm-timer", ] [[package]] name = "sp-consensus-babe" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940734344fd43cc26618baf75638592e22ae609965c25280231843c3bf1425de" +checksum = "a153085b1542b5cbe23686433cd36d1a634964f1b707671d0ffb01d8d9313047" dependencies = [ "merlin", "parity-scale-codec", @@ -7572,6 +7113,7 @@ dependencies = [ "sp-consensus-vrf", "sp-core", "sp-inherents", + "sp-keystore", "sp-runtime", "sp-std", "sp-timestamp", @@ -7579,19 +7121,20 @@ dependencies = [ [[package]] name = "sp-consensus-slots" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f822876fba433e197c73c31482f16a340eb807c040f2321ad5228b089dac31c4" +checksum = "32bd501ab76c827d74f145063cd8cb993a9f634dac93c9b0d909111cd5900a6a" dependencies = [ "parity-scale-codec", + "sp-arithmetic", "sp-runtime", ] [[package]] name = "sp-consensus-vrf" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7e76b3073ea5be8aac66aaaa3f5e9ac4e0606d74571591ce879702f96cabbee" +checksum = "030895d70bf3095c857f4727a7cce7c43af29efe3413bb547ee28700f7d78766" dependencies = [ "parity-scale-codec", "schnorrkel", @@ -7602,17 +7145,16 @@ dependencies = [ [[package]] name = "sp-core" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb1b8a5031e866ebee7535446915c83e8f676c68dcc8555f0c0f149ff4b48035" +checksum = "abbc8d4e9b8a7d5819ed26f1374017bb32833ef4890e4ff065e1da30669876bc" dependencies = [ "base58", "blake2-rfc", - "byteorder 1.4.2", - "derive_more 0.99.11", + "byteorder", "dyn-clonable", "ed25519-dalek", - "futures 0.3.12", + "futures 0.3.13", "hash-db", "hash256-std-hasher", "hex", @@ -7624,22 +7166,23 @@ dependencies = [ "num-traits", "parity-scale-codec", "parity-util-mem", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "primitive-types", "rand 0.7.3", "regex", "schnorrkel", "secrecy", "serde", - "sha2 0.8.2", + "sha2 0.9.3", "sp-debug-derive", "sp-externalities", "sp-runtime-interface", "sp-std", "sp-storage", "substrate-bip39", + "thiserror", "tiny-bip39", - "tiny-keccak 2.0.2", + "tiny-keccak", "twox-hash", "wasmi", "zeroize", @@ -7647,41 +7190,30 @@ dependencies = [ [[package]] name = "sp-database" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52c11be572a236b81cdf5e5339ea6253d17e91bd4018b198b3d861cc66154979" +checksum = "c8c3f018913eef191d95c824657c5759c459d28670e654fa34f5d9bd5e6f0492" dependencies = [ "kvdb", - "parking_lot 0.10.2", + "parking_lot 0.11.1", ] [[package]] name = "sp-debug-derive" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "558a1a24f2feab950ce382923b62879f253207c6cbf7832eb1e47dba5f57fba8" -dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", -] - -[[package]] -name = "sp-evm" -version = "0.8.0" +checksum = "e80275f23b4e7ba8f54dec5f90f016530e7307d2ee9445f617ab986cbe97f31e" dependencies = [ - "evm", - "parity-scale-codec", - "serde", - "sp-core", - "sp-std", + "proc-macro2", + "quote", + "syn", ] [[package]] name = "sp-externalities" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "144c39acb7affd7a9ce478e289157b9a6c225e3f08a7d4d2f4fee85cc3899684" +checksum = "2fdc625f8c7b13b9a136d334888b21b5743d2081cb666cb03efca1dc9b8f74d1" dependencies = [ "environmental", "parity-scale-codec", @@ -7691,9 +7223,9 @@ dependencies = [ [[package]] name = "sp-finality-grandpa" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9cf9e52b1dc6b39c46ec73e57cbfe8236009c928bf1d83e1d42c75060d9c637" +checksum = "702e0be150e1b557df42326ec9b82c2010366631d03be27c69912d446abbf87a" dependencies = [ "finality-grandpa", "log", @@ -7702,48 +7234,39 @@ dependencies = [ "sp-api", "sp-application-crypto", "sp-core", + "sp-keystore", "sp-runtime", "sp-std", ] -[[package]] -name = "sp-finality-tracker" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5688c61363d620cd29591b1f7640da84346b519d33d9e4ce5e7978ff89425c37" -dependencies = [ - "parity-scale-codec", - "sp-inherents", - "sp-std", -] - [[package]] name = "sp-inherents" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ebcf5925a850392cb044af9b8da20dc0610e613ff15607b3b96bed6461f9193" +checksum = "2542380b535c6941502a0a3069a657eb5abb70fd67b11afa164d4a4b038ba73a" dependencies = [ - "derive_more 0.99.11", "parity-scale-codec", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "sp-core", "sp-std", + "thiserror", ] [[package]] name = "sp-io" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bffbebdeacf0a313ac65e043c37e37d98b48ea75cd1e8ab9ba40a925fecb616b" +checksum = "33fd69f0a6e91bedc2fb1c5cc3689c212474b6c918274cb4cb14dbbe3c428c14" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "hash-db", "libsecp256k1", "log", "parity-scale-codec", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "sp-core", "sp-externalities", + "sp-keystore", "sp-runtime-interface", "sp-state-machine", "sp-std", @@ -7756,9 +7279,9 @@ dependencies = [ [[package]] name = "sp-keyring" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9741dcf007b33496e1add259fae40d59cfe64847bf992d2605edcecd8ae6d0c2" +checksum = "7b59f2b0e94b2048d4984aa6eb40eef2e4c05d3adf27a083dd3c9b0fce74ef7a" dependencies = [ "lazy_static", "sp-core", @@ -7766,36 +7289,55 @@ dependencies = [ "strum", ] +[[package]] +name = "sp-keystore" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db6ccd2baf189112355338e8b224dc513cd239b974dbd717f12b3dc7a7248c3b" +dependencies = [ + "async-trait", + "derive_more", + "futures 0.3.13", + "merlin", + "parity-scale-codec", + "parking_lot 0.11.1", + "schnorrkel", + "serde", + "sp-core", + "sp-externalities", +] + [[package]] name = "sp-npos-elections" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "404f9b99ff38395d48bf2f041096fc5dbc1b892a8c314314c7bf66a0dfb5622c" +checksum = "54e6e8b84ee0dc7bb65b55beba55ffbc17803222ab7c746a74f72fc5869c7320" dependencies = [ "parity-scale-codec", "serde", "sp-arithmetic", + "sp-core", "sp-npos-elections-compact", "sp-std", ] [[package]] name = "sp-npos-elections-compact" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4ac5b8443203fbc6472f08f376b3b09307dc3ae1b0c1a91776a3b934f1314ce" +checksum = "085fbb1aa72d85a17524047fc1e708bc3bd038b02b46dc7ac601fa39c8af93d3" dependencies = [ "proc-macro-crate", - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] name = "sp-offchain" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d54d50a7a5459ed6f63c879eae715732f0f5e5fd5d99dfb553b111e0b5932f6f" +checksum = "0bd80eedcedcc8342e77c26d59ad90b6904715a862731fa16616650773570e63" dependencies = [ "sp-api", "sp-core", @@ -7804,19 +7346,18 @@ dependencies = [ [[package]] name = "sp-panic-handler" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1055031d4994705cd9eca38602fea1ed88f6916c0979f85352c3d540baedb2e8" +checksum = "54702e109f1c8a870dd4065a497d2612d42cec5817126e96cc0658c5ea975784" dependencies = [ "backtrace", - "log", ] [[package]] name = "sp-rpc" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "009f2b8ae311ff2c5f319e545492f26a3954fc84f477f85e2c3dd49fde605cf9" +checksum = "a2e5b1ed655d11449073b914b048895f45241e02b3919d1d0187f315435fee18" dependencies = [ "serde", "sp-core", @@ -7824,33 +7365,33 @@ dependencies = [ [[package]] name = "sp-runtime" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85d8d12cba8cb9c50d8c0eee517d74044c22faa9322260e88dccb5bd06bf0762" +checksum = "dfa4b353b76f04616dbdb8d269d58dcac47acb31c006d3b70e7b64233e68695e" dependencies = [ "either", "hash256-std-hasher", - "impl-trait-for-tuples", + "impl-trait-for-tuples 0.2.1", "log", "parity-scale-codec", "parity-util-mem", - "paste", + "paste 1.0.4", "rand 0.7.3", "serde", "sp-application-crypto", "sp-arithmetic", "sp-core", - "sp-inherents", "sp-io", "sp-std", ] [[package]] name = "sp-runtime-interface" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fb6574401a7b5c89111b417efecbc9f0c3d38c2c539ce3a964b8393769c3e15" +checksum = "b2e5c88b4bc8d607e4e2ff767a85db58cf7101f3dd6064f06929342ea67fe8fb" dependencies = [ + "impl-trait-for-tuples 0.2.1", "parity-scale-codec", "primitive-types", "sp-externalities", @@ -7864,22 +7405,22 @@ dependencies = [ [[package]] name = "sp-runtime-interface-proc-macro" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d724b1feca629bf958dc0db0453225e59d9b2098fe5a47f86cd964cbc116d89d" +checksum = "19a6c7c2251512c9e533d15db8a863b06ece1cbee778130dd9adbe44b6b39aa9" dependencies = [ "Inflector", "proc-macro-crate", - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] name = "sp-sandbox" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b788997f8456b9dfaa3d5ec5e4e8d19c1c24a854ca861abadacdb4ae08eff532" +checksum = "0e92caf4555d676d8f0b67def0041da789f79a5d5f341130496f15a6261926cc" dependencies = [ "parity-scale-codec", "sp-core", @@ -7891,9 +7432,9 @@ dependencies = [ [[package]] name = "sp-serializer" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3b8c2658dfa3f0a9447dbbebffa672905c4af48e6b914a814b04c39e2a8700b" +checksum = "982d793f01eb9eea9f30ffc63b821170068b9f0d9edf715d8ba77dc4de9c300f" dependencies = [ "serde", "serde_json", @@ -7901,9 +7442,9 @@ dependencies = [ [[package]] name = "sp-session" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "242e7e9069cfd163b6ceb22c2d1aba7a09144ac8360f07270739ca7917520b69" +checksum = "2c7cf161533725a78083b04f3269effe4c3b4b6ce5f655019b3eec3e729ba4d4" dependencies = [ "parity-scale-codec", "sp-api", @@ -7915,9 +7456,9 @@ dependencies = [ [[package]] name = "sp-staking" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6abfd1a33f36879117b5f511ac066e265258028d1190088be89924794967f395" +checksum = "fc729eb10f8809c61a1fe439ac118a4413de004aaf863003ee8752ac0b596e73" dependencies = [ "parity-scale-codec", "sp-runtime", @@ -7926,15 +7467,15 @@ dependencies = [ [[package]] name = "sp-state-machine" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "095a8c33f70151e561c53fdaca23ad19cc059088807a25be0d60d04fb2ededea" +checksum = "46fa4143e58e9130f726d4e8a9b86f3530a8bd19a2eedcdcf4af205f4b5a6d4f" dependencies = [ "hash-db", "log", "num-traits", "parity-scale-codec", - "parking_lot 0.10.2", + "parking_lot 0.11.1", "rand 0.7.3", "smallvec 1.6.1", "sp-core", @@ -7942,21 +7483,22 @@ dependencies = [ "sp-panic-handler", "sp-std", "sp-trie", + "thiserror", "trie-db", "trie-root", ] [[package]] name = "sp-std" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2585fb8f5f4fde53c2f9ccebac4517da4dc435373a8fcaf5db7f54b798da66c2" +checksum = "35391ea974fa5ee869cb094d5b437688fbf3d8127d64d1b9fed5822a1ed39b12" [[package]] name = "sp-storage" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "781cc04c8d61c7bb1c269ca68d5d001fcaafbca8a21af46f87bf2e79a749c295" +checksum = "86af458d4a0251c490cdde9dcaaccb88d398f3b97ac6694cdd49ed9337e6b961" dependencies = [ "impl-serde", "parity-scale-codec", @@ -7966,13 +7508,27 @@ dependencies = [ "sp-std", ] +[[package]] +name = "sp-tasks" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c585340cbee96c53a9b43fd07d81edf6cebeb80e4ca7c0ee79b856c0b1883a0e" +dependencies = [ + "log", + "sp-core", + "sp-externalities", + "sp-io", + "sp-runtime-interface", + "sp-std", +] + [[package]] name = "sp-timestamp" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d86fb8fd203faa146ba06b0d88c60f9bcb4c1dcbe49f64e36d4038893018536" +checksum = "27387c541197b9f47f3d9ddcab5649a3ecdca582d2f2ea2b511af24a3d3cbf83" dependencies = [ - "impl-trait-for-tuples", + "impl-trait-for-tuples 0.2.1", "parity-scale-codec", "sp-api", "sp-inherents", @@ -7983,9 +7539,9 @@ dependencies = [ [[package]] name = "sp-tracing" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c574a06ac032f3c6fc29ae61ae1292546499342219c256098914f6110312f6f4" +checksum = "567382d8d4e14fb572752863b5cd57a78f9e9a6583332b590b726f061f3ea957" dependencies = [ "log", "parity-scale-codec", @@ -7997,25 +7553,26 @@ dependencies = [ [[package]] name = "sp-transaction-pool" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "429125cf86f74715559d9fc1e27ed8f69d6a857c30db4ca4957e05c4549ecf1b" +checksum = "3264d3b7ea31483eddffa2cc7f28c4d9c022598e456a985fd1cb5879a4609853" dependencies = [ - "derive_more 0.99.11", - "futures 0.3.12", + "derive_more", + "futures 0.3.13", "log", "parity-scale-codec", "serde", "sp-api", "sp-blockchain", "sp-runtime", + "thiserror", ] [[package]] name = "sp-trie" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "311f320e1a1d6d961664af519d343d7a0493d9fe2f81dc3de488841e4fbaaa46" +checksum = "b85b7f745da41ef825c6f7b93f1fdc897b03df94a4884adfbb70fbcd0aed1298" dependencies = [ "hash-db", "memory-db", @@ -8028,11 +7585,11 @@ dependencies = [ [[package]] name = "sp-utils" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5af5eb60fe8721a250ad67346d4e4c859527b1c4f287e963ffbbf7bd22b731f8" +checksum = "b4ec2a5f924f7affd1e959f8f3c02bd87cdfa0e11c71a4cbc075f955ead8c1a1" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "futures-core", "futures-timer 3.0.2", "lazy_static", @@ -8041,9 +7598,9 @@ dependencies = [ [[package]] name = "sp-version" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d5fb7fa5f747a7d1b1854a1b69b813a9df6425ab0f0a9876cbddea8c6b9ab34" +checksum = "dbeffa538a13d715d30e01d57a2636ba32845b737a29a3ea32403576588222e7" dependencies = [ "impl-serde", "parity-scale-codec", @@ -8054,11 +7611,11 @@ dependencies = [ [[package]] name = "sp-wasm-interface" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "554daa08d61bb3bf2d81ac79b7ae089733339fc8fdc129dc21d074195f1219be" +checksum = "b214e125666a6416cf30a70cc6a5dacd34a4e5197f8a3d479f714af7e1dc7a47" dependencies = [ - "impl-trait-for-tuples", + "impl-trait-for-tuples 0.2.1", "parity-scale-codec", "sp-std", "wasmi", @@ -8076,15 +7633,6 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" -[[package]] -name = "standback" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2beb4d1860a61f571530b3f855a1b538d0200f7871c63331ecd6f17b1f014f8" -dependencies = [ - "version_check", -] - [[package]] name = "static_assertions" version = "1.1.0" @@ -8093,62 +7641,13 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "statrs" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10102ac8d55e35db2b3fafc26f81ba8647da2e15879ab686a67e6d19af2685e8" -dependencies = [ - "rand 0.5.6", -] - -[[package]] -name = "stdweb" -version = "0.4.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d022496b16281348b52d0e30ae99e01a73d737b2f45d38fed4edf79f9325a1d5" -dependencies = [ - "discard", - "rustc_version", - "stdweb-derive", - "stdweb-internal-macros", - "stdweb-internal-runtime", - "wasm-bindgen", -] - -[[package]] -name = "stdweb-derive" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c87a60a40fccc84bef0652345bbbbbe20a605bf5d0ce81719fc476f5c03b50ef" -dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "serde", - "serde_derive", - "syn 1.0.60", -] - -[[package]] -name = "stdweb-internal-macros" -version = "0.2.9" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58fa5ff6ad0d98d1ffa8cb115892b6e69d67799f6763e162a1c9db421dc22e11" +checksum = "cce16f6de653e88beca7bd13780d08e09d4489dbca1f9210e041bc4852481382" dependencies = [ - "base-x", - "proc-macro2 1.0.24", - "quote 1.0.8", - "serde", - "serde_derive", - "serde_json", - "sha1", - "syn 1.0.60", + "rand 0.7.3", ] -[[package]] -name = "stdweb-internal-runtime" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0" - [[package]] name = "stream-cipher" version = "0.7.1" @@ -8193,30 +7692,30 @@ checksum = "5ba9cdfda491b814720b6b06e0cac513d922fc407582032e8706e9f137976f90" dependencies = [ "heck", "proc-macro-error", - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] name = "strum" -version = "0.16.0" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6138f8f88a16d90134763314e3fc76fa3ed6a7db4725d6acf9a3ef95a3188d22" +checksum = "7318c509b5ba57f18533982607f24070a55d353e90d4cae30c467cdb2ad5ac5c" dependencies = [ "strum_macros", ] [[package]] name = "strum_macros" -version = "0.16.0" +version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0054a7df764039a6cd8592b9de84be4bec368ff081d203a7d5371cbfa8e65c81" +checksum = "ee8bc6b87a5112aeeab1f4a9f7ab634fe6cbefc4850006df31267f4cfb9e3149" dependencies = [ "heck", - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -8226,7 +7725,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bed6646a0159b9935b5d045611560eeef842b78d7adc3ba36f5ca325a13a0236" dependencies = [ "hmac 0.7.1", - "pbkdf2", + "pbkdf2 0.3.0", "schnorrkel", "sha2 0.8.2", "zeroize", @@ -8234,24 +7733,24 @@ dependencies = [ [[package]] name = "substrate-build-script-utils" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9726c2926418239f73d4d939fcc4ceb5c6697609426c64dd3bcf664f06986afa" +checksum = "bd540ba72520174c2c73ce96bf507eeba3cc8a481f58be92525b69110e1fa645" dependencies = [ "platforms", ] [[package]] name = "substrate-frame-rpc-system" -version = "2.0.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46bf9f4c01086bb9b1e14ca6ebb5f12c2cb21a5c3810a01f07a7e621ea1e5db1" +checksum = "8e46123ec4a690d91967de07cd6af4dde90d14519a1a8d43f61bd3f78dd3d0ef" dependencies = [ "frame-system-rpc-runtime-api", - "futures 0.3.12", + "futures 0.3.13", "jsonrpc-core 15.1.0", - "jsonrpc-core-client", - "jsonrpc-derive", + "jsonrpc-core-client 15.1.0", + "jsonrpc-derive 15.1.0", "log", "parity-scale-codec", "sc-client-api", @@ -8267,12 +7766,12 @@ dependencies = [ [[package]] name = "substrate-prometheus-endpoint" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45c36fcefaaa1292fe37d8a478ebc57311df0de8b5d01bffb5e2abc9bbda0b4f" +checksum = "2eb561c19a121e1c89daa79dbfa67a55080f813caa47fd231833a0669696d508" dependencies = [ "async-std", - "derive_more 0.99.11", + "derive_more", "futures-util", "hyper 0.13.10", "log", @@ -8298,26 +7797,15 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e81da0851ada1f3e9d4312c704aa4f8806f0f9d69faaf8df2f3464b4a9437c2" -[[package]] -name = "syn" -version = "0.15.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5" -dependencies = [ - "proc-macro2 0.4.30", - "quote 0.6.13", - "unicode-xid 0.1.0", -] - [[package]] name = "syn" version = "1.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c700597eca8a5a762beb35753ef6b94df201c81cca676604f547495a0d7f0081" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "unicode-xid 0.2.1", + "proc-macro2", + "quote", + "unicode-xid", ] [[package]] @@ -8326,10 +7814,10 @@ version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b834f2d66f734cb897113e34aaff2f1ab4719ca946f9a7358dba8f8064148701" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", - "unicode-xid 0.2.1", + "proc-macro2", + "quote", + "syn", + "unicode-xid", ] [[package]] @@ -8338,6 +7826,18 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f764005d11ee5f36500a149ace24e00e3da98b0158b3e2d53a7495660d3f4d60" +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "target-lexicon" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "422045212ea98508ae3d28025bc5aaa2bd4a9cdaecd442a08da2ee620ee9ea95" + [[package]] name = "tempfile" version = "3.2.0" @@ -8347,7 +7847,7 @@ dependencies = [ "cfg-if 1.0.0", "libc", "rand 0.8.3", - "redox_syscall 0.2.4", + "redox_syscall 0.2.5", "remove_dir_all", "winapi 0.3.9", ] @@ -8372,22 +7872,22 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.23" +version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76cc616c6abf8c8928e2fdcc0dbfab37175edd8fb49a4641066ad1364fdab146" +checksum = "e0f4a65597094d4483ddaed134f409b2cb7c1beccf25201a9f73c719254fa98e" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.23" +version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9be73a2caec27583d0046ef3796c3794f868a5bc813db689eed00c7631275cd1" +checksum = "7765189610d8241a44529806d6fd1f2e0a08734313a35d5b3a556f92b381f3c0" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -8396,7 +7896,7 @@ version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8018d24e04c95ac8790716a5987d0fec4f8b27249ffa0f7d33f1369bdfb88cbd" dependencies = [ - "once_cell 1.5.2", + "once_cell", ] [[package]] @@ -8408,27 +7908,6 @@ dependencies = [ "num_cpus", ] -[[package]] -name = "tide" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c4c4e35f5a89ed08cbb59b6e4e1d648e563d6f8daa804002f3557d11d3c8f9" -dependencies = [ - "async-h1", - "async-session", - "async-sse", - "async-std", - "async-trait", - "femme", - "futures-util", - "http-types", - "kv-log-macro", - "pin-project-lite 0.1.11", - "route-recognizer", - "serde", - "serde_json", -] - [[package]] name = "time" version = "0.1.44" @@ -8440,67 +7919,22 @@ dependencies = [ "winapi 0.3.9", ] -[[package]] -name = "time" -version = "0.2.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1195b046942c221454c2539395f85413b33383a067449d78aab2b7b052a142f7" -dependencies = [ - "const_fn", - "libc", - "standback", - "stdweb", - "time-macros", - "version_check", - "winapi 0.3.9", -] - -[[package]] -name = "time-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "957e9c6e26f12cb6d0dd7fc776bb67a706312e7299aed74c8dd5b17ebb27e2f1" -dependencies = [ - "proc-macro-hack", - "time-macros-impl", -] - -[[package]] -name = "time-macros-impl" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5c3be1edfad6027c69f5491cf4cb310d1a71ecd6af742788c6ff8bced86b8fa" -dependencies = [ - "proc-macro-hack", - "proc-macro2 1.0.24", - "quote 1.0.8", - "standback", - "syn 1.0.60", -] - [[package]] name = "tiny-bip39" -version = "0.7.3" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0165e045cc2ae1660270ca65e1676dbaab60feb0f91b10f7d0665e9b47e31f2" +checksum = "d9e44c4759bae7f1032e286a7ef990bd9ed23fe831b7eeba0beb97484c2e59b8" dependencies = [ - "failure", - "hmac 0.7.1", - "once_cell 1.5.2", - "pbkdf2", + "anyhow", + "hmac 0.8.1", + "once_cell", + "pbkdf2 0.4.0", "rand 0.7.3", "rustc-hash", - "sha2 0.8.2", + "sha2 0.9.3", + "thiserror", "unicode-normalization", -] - -[[package]] -name = "tiny-keccak" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d8a021c69bb74a44ccedb824a046447e2c84a01df9e5c20779750acb38e11b2" -dependencies = [ - "crunchy", + "zeroize", ] [[package]] @@ -8534,16 +7968,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a09c0b5bb588872ab2f09afa13ee6e9dac11e10a0ec9e8e3ba39a5a5d530af6" dependencies = [ "bytes 0.4.12", - "futures 0.1.30", + "futures 0.1.31", "mio", "num_cpus", "tokio-codec", "tokio-current-thread", - "tokio-executor 0.1.10", + "tokio-executor", "tokio-fs", "tokio-io", "tokio-reactor", - "tokio-sync 0.1.8", + "tokio-sync", "tokio-tcp", "tokio-threadpool", "tokio-timer", @@ -8581,7 +8015,7 @@ checksum = "8fb220f46c53859a4b7ec083e41dec9778ff0b1851c0942b211edb89e0ccdc46" dependencies = [ "bytes 0.4.12", "either", - "futures 0.1.30", + "futures 0.1.31", ] [[package]] @@ -8591,7 +8025,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25b2998660ba0e70d18684de5d06b70b70a3a747469af9dea7618cc59e75976b" dependencies = [ "bytes 0.4.12", - "futures 0.1.30", + "futures 0.1.31", "tokio-io", ] @@ -8601,8 +8035,8 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1de0e32a83f131e002238d7ccde18211c0a5397f60cbfffcb112868c2e0e20e" dependencies = [ - "futures 0.1.30", - "tokio-executor 0.1.10", + "futures 0.1.31", + "tokio-executor", ] [[package]] @@ -8612,18 +8046,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb2d1b8f4548dbf5e1f7818512e9c406860678f29c300cdf0ebac72d1a3a1671" dependencies = [ "crossbeam-utils 0.7.2", - "futures 0.1.30", -] - -[[package]] -name = "tokio-executor" -version = "0.2.0-alpha.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ee9ceecf69145923834ea73f32ba40c790fd877b74a7817dd0b089f1eb9c7c8" -dependencies = [ - "futures-util-preview", - "lazy_static", - "tokio-sync 0.2.0-alpha.6", + "futures 0.1.31", ] [[package]] @@ -8632,7 +8055,7 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "297a1206e0ca6302a0eed35b700d292b275256f596e2f3fea7729d5e629b6ff4" dependencies = [ - "futures 0.1.30", + "futures 0.1.31", "tokio-io", "tokio-threadpool", ] @@ -8644,7 +8067,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57fc868aae093479e3131e3d165c93b1c7474109d13c90ec0dda2a1bbfff0674" dependencies = [ "bytes 0.4.12", - "futures 0.1.30", + "futures 0.1.31", "log", ] @@ -8655,7 +8078,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d282d483052288b2308ba5ee795f5673b159c9bdf63c385a05609da782a5eae" dependencies = [ "bytes 0.4.12", - "futures 0.1.30", + "futures 0.1.31", "mio", "mio-named-pipes", "tokio 0.1.22", @@ -8668,16 +8091,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09bc590ec4ba8ba87652da2068d150dcada2cfa2e07faae270a5e0409aa51351" dependencies = [ "crossbeam-utils 0.7.2", - "futures 0.1.30", + "futures 0.1.31", "lazy_static", "log", "mio", "num_cpus", "parking_lot 0.9.0", "slab", - "tokio-executor 0.1.10", + "tokio-executor", "tokio-io", - "tokio-sync 0.1.8", + "tokio-sync", ] [[package]] @@ -8687,39 +8110,28 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e12831b255bcfa39dc0436b01e19fea231a37db570686c06ee72c423479f889a" dependencies = [ "futures-core", - "rustls", + "rustls 0.18.1", "tokio 0.2.25", "webpki", ] [[package]] name = "tokio-service" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24da22d077e0f15f55162bdbdc661228c1581892f52074fb242678d015b45162" -dependencies = [ - "futures 0.1.30", -] - -[[package]] -name = "tokio-sync" -version = "0.1.8" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edfe50152bc8164fcc456dab7891fa9bf8beaf01c5ee7e1dd43a397c3cf87dee" +checksum = "24da22d077e0f15f55162bdbdc661228c1581892f52074fb242678d015b45162" dependencies = [ - "fnv", - "futures 0.1.30", + "futures 0.1.31", ] [[package]] name = "tokio-sync" -version = "0.2.0-alpha.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f1aaeb685540f7407ea0e27f1c9757d258c7c6bf4e3eb19da6fc59b747239d2" +checksum = "edfe50152bc8164fcc456dab7891fa9bf8beaf01c5ee7e1dd43a397c3cf87dee" dependencies = [ "fnv", - "futures-core-preview", - "futures-util-preview", + "futures 0.1.31", ] [[package]] @@ -8729,7 +8141,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "98df18ed66e3b72e742f185882a9e201892407957e45fbff8da17ae7a7c51f72" dependencies = [ "bytes 0.4.12", - "futures 0.1.30", + "futures 0.1.31", "iovec", "mio", "tokio-io", @@ -8745,12 +8157,12 @@ dependencies = [ "crossbeam-deque 0.7.3", "crossbeam-queue", "crossbeam-utils 0.7.2", - "futures 0.1.30", + "futures 0.1.31", "lazy_static", "log", "num_cpus", "slab", - "tokio-executor 0.1.10", + "tokio-executor", ] [[package]] @@ -8760,19 +8172,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93044f2d313c95ff1cb7809ce9a7a05735b012288a888b62d4434fd58c94f296" dependencies = [ "crossbeam-utils 0.7.2", - "futures 0.1.30", + "futures 0.1.31", "slab", - "tokio-executor 0.1.10", -] - -[[package]] -name = "tokio-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a70f4fcd7b3b24fb194f837560168208f669ca8cb70d0c4b862944452396343" -dependencies = [ - "native-tls", - "tokio 0.2.25", + "tokio-executor", ] [[package]] @@ -8782,7 +8184,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2a0b10e610b39c38b031a2fcab08e4b82f16ece36504988dcbd81dbba650d82" dependencies = [ "bytes 0.4.12", - "futures 0.1.30", + "futures 0.1.31", "log", "mio", "tokio-codec", @@ -8797,7 +8199,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab57a4ac4111c8c9dbcf70779f6fc8bc35ae4b2454809febac840ad19bd7e4e0" dependencies = [ "bytes 0.4.12", - "futures 0.1.30", + "futures 0.1.31", "iovec", "libc", "log", @@ -8839,26 +8241,26 @@ checksum = "360dfd1d6d30e05fda32ace2c8c70e9c0a9da713275777f5a4dbb8a1893930c6" [[package]] name = "tracing" -version = "0.1.23" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7d40a22fd029e33300d8d89a5cc8ffce18bb7c587662f54629e94c9de5487f3" +checksum = "01ebdc2bb4498ab1ab5f5b73c5803825e60199229ccba0698170e3be0e7f959f" dependencies = [ "cfg-if 1.0.0", "log", - "pin-project-lite 0.2.4", + "pin-project-lite 0.2.5", "tracing-attributes", "tracing-core", ] [[package]] name = "tracing-attributes" -version = "0.1.12" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43f080ea7e4107844ef4766459426fa2d5c1ada2e47edba05dc7fa99d9629f47" +checksum = "a8a9bd1db7706f2373a190b0d067146caa39350c486f3d455b0e33b431f94c07" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -8872,19 +8274,19 @@ dependencies = [ [[package]] name = "tracing-futures" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab7bb6f14721aa00656086e9335d363c5c8747bae02ebe32ea2c7dece5689b4c" +checksum = "97d095ae15e245a057c8e8451bab9b3ee1e1f68e9ba2b4fbc18d0ac5237835f2" dependencies = [ - "pin-project 0.4.27", + "pin-project 1.0.5", "tracing", ] [[package]] name = "tracing-log" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e0f8c7178e13481ff6765bd169b33e8d554c5d2bbede5e32c356194be02b9b9" +checksum = "a6923477a48e41c1951f1999ef8bb5a3023eb723ceadafe78ffb65dc366761e3" dependencies = [ "lazy_static", "log", @@ -8903,9 +8305,9 @@ dependencies = [ [[package]] name = "tracing-subscriber" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1fa8f0c8f4c594e4fc9debc1990deab13238077271ba84dd853d54902ee3401" +checksum = "8ab8966ac3ca27126141f7999361cc97dd6fb4b71da04c02044fa9045d98bb96" dependencies = [ "ansi_term 0.12.1", "chrono", @@ -8930,7 +8332,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec051edf7f0fc9499a2cb0947652cab2148b9d7f61cee7605e312e9f970dacaf" dependencies = [ "hash-db", - "hashbrown 0.9.1", + "hashbrown", "log", "rustc-hex", "smallvec 1.6.1", @@ -8952,7 +8354,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1631b201eb031b563d2e85ca18ec8092508e262a3196ce9bd10a67ec87b9f5c" dependencies = [ "hash-db", - "rlp 0.5.0", + "rlp", ] [[package]] @@ -8978,15 +8380,21 @@ version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "373c8a200f9e67a0c95e62a4f52fbf80c23b4381c05a17845531982fa99e6b33" +[[package]] +name = "ucd-trie" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c" + [[package]] name = "uint" -version = "0.8.5" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9db035e67dfaf7edd9aebfe8676afcd63eed53c8a4044fed514c8cccf1835177" +checksum = "e11fe9a9348741cf134085ad57c249508345fe16411b3d7fb4ff2da2f1d6382e" dependencies = [ - "byteorder 1.4.2", + "byteorder", "crunchy", - "rustc-hex", + "hex", "static_assertions", ] @@ -9010,9 +8418,9 @@ dependencies = [ [[package]] name = "unicode-normalization" -version = "0.1.16" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a13e63ab62dbe32aeee58d1c5408d35c36c392bba5d9d3142287219721afe606" +checksum = "07fbfce1c8a97d547e8b5334978438d9d6ec8c20e38f56d4a4374d181493eaef" dependencies = [ "tinyvec", ] @@ -9029,12 +8437,6 @@ version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" -[[package]] -name = "unicode-xid" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" - [[package]] name = "unicode-xid" version = "0.2.1" @@ -9053,22 +8455,30 @@ dependencies = [ [[package]] name = "unsigned-varint" -version = "0.4.0" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7fdeedbf205afadfe39ae559b75c3240f24e257d0ca27e85f85cb82aa19ac35" + +[[package]] +name = "unsigned-varint" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "669d776983b692a906c881fcd0cfb34271a48e197e4d6cb8df32b05bfc3d3fa5" +checksum = "35581ff83d4101e58b582e607120c7f5ffb17e632a980b1f38334d76b36908b2" dependencies = [ - "bytes 0.5.6", + "asynchronous-codec 0.5.0", + "bytes 1.0.1", "futures-io", "futures-util", - "futures_codec", ] [[package]] name = "unsigned-varint" -version = "0.5.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7fdeedbf205afadfe39ae559b75c3240f24e257d0ca27e85f85cb82aa19ac35" +checksum = "5f8d425fafb8cd76bc3f22aace4af471d3156301d7508f2107e98fbeae10bc7f" dependencies = [ + "asynchronous-codec 0.6.0", + "bytes 1.0.1", "futures-io", "futures-util", ] @@ -9092,15 +8502,23 @@ dependencies = [ [[package]] name = "url" -version = "2.2.0" +version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5909f2b0817350449ed73e8bcd81c8c3c8d9a7a5d8acba4b27db277f1868976e" +checksum = "9ccd964113622c8e9322cfac19eb1004a07e636c545f325da085d5cdde6f1f8b" dependencies = [ "form_urlencoded", - "idna 0.2.1", + "idna 0.2.2", "matches", "percent-encoding 2.1.0", - "serde", +] + +[[package]] +name = "value-bag" +version = "1.0.0-alpha.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b676010e055c99033117c2343b33a40a30b91fecd6c49055ac9cd2d6c305ab1" +dependencies = [ + "ctor", ] [[package]] @@ -9123,12 +8541,13 @@ checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" [[package]] name = "vergen" -version = "3.1.0" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ce50d8996df1f85af15f2cd8d33daae6e479575123ef4314a51a70a230739cb" +checksum = "e7141e445af09c8919f1d5f8a20dae0b20c3b57a45dee0d5823c6ed5d237f15a" dependencies = [ "bitflags", "chrono", + "rustc_version 0.3.3", ] [[package]] @@ -9143,29 +8562,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" -[[package]] -name = "wabt" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00bef93d5e6c81a293bccf107cf43aa47239382f455ba14869d36695d8963b9c" -dependencies = [ - "serde", - "serde_derive", - "serde_json", - "wabt-sys", -] - -[[package]] -name = "wabt-sys" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a4e043159f63e16986e713e9b5e1c06043df4848565bf672e27c523864c7791" -dependencies = [ - "cc", - "cmake", - "glob 0.2.11", -] - [[package]] name = "waker-fn" version = "1.1.0" @@ -9178,7 +8574,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6395efa4784b027708f7451087e647ec73cc74f5d9bc2e418404248d679a230" dependencies = [ - "futures 0.1.30", + "futures 0.1.31", "log", "try-lock", ] @@ -9207,36 +8603,34 @@ checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" [[package]] name = "wasm-bindgen" -version = "0.2.70" +version = "0.2.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55c0f7123de74f0dab9b7d00fd614e7b19349cd1e2f5252bbe9b1754b59433be" +checksum = "7ee1280240b7c461d6a0071313e08f34a60b0365f14260362e5a2b17d1d31aa7" dependencies = [ "cfg-if 1.0.0", - "serde", - "serde_json", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" -version = "0.2.70" +version = "0.2.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bc45447f0d4573f3d65720f636bbcc3dd6ce920ed704670118650bcd47764c7" +checksum = "5b7d8b6942b8bb3a9b0e73fc79b98095a27de6fa247615e59d096754a3bc2aa8" dependencies = [ "bumpalo", "lazy_static", "log", - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.20" +version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3de431a2910c86679c34283a33f66f4e4abd7e0aec27b6669060148872aadf94" +checksum = "8e67a5806118af01f0d9045915676b22aaebecf4178ae7021bc171dab0b897ab" dependencies = [ "cfg-if 1.0.0", "js-sys", @@ -9246,32 +8640,32 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.70" +version = "0.2.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b8853882eef39593ad4174dd26fc9865a64e84026d223f63bb2c42affcbba2c" +checksum = "e5ac38da8ef716661f0f36c0d8320b89028efe10c7c0afde65baffb496ce0d3b" dependencies = [ - "quote 1.0.8", + "quote", "wasm-bindgen-macro-support", ] [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.70" +version = "0.2.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4133b5e7f2a531fa413b3a1695e925038a05a71cf67e87dafa295cb645a01385" +checksum = "cc053ec74d454df287b9374ee8abb36ffd5acb95ba87da3ba5b7d3fe20eb401e" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.70" +version = "0.2.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd4945e4943ae02d15c13962b38a5b1e81eadd4b71214eee75af64a4d6a4fd64" +checksum = "7d6f8ec44822dd71f5f221a5847fb34acd9060535c1211b70a05844c0f6383b1" [[package]] name = "wasm-timer" @@ -9279,7 +8673,7 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be0ecb0db480561e9a7642b5d3e4187c128914e58aa84330b9493e3eb68c5e7f" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "js-sys", "parking_lot 0.11.1", "pin-utils", @@ -9312,76 +8706,241 @@ dependencies = [ ] [[package]] -name = "web-sys" -version = "0.3.47" +name = "wasmparser" +version = "0.71.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89a30c99437829ede826802bfcf28500cf58df00e66cb9114df98813bc145ff1" + +[[package]] +name = "wasmtime" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c40dc691fc48003eba817c38da7113c15698142da971298003cac3ef175680b3" +checksum = "7426055cb92bd9a1e9469b48154d8d6119cd8c498c8b70284e420342c05dc45d" dependencies = [ - "js-sys", - "wasm-bindgen", + "anyhow", + "backtrace", + "bincode", + "cfg-if 1.0.0", + "cpp_demangle", + "indexmap", + "libc", + "log", + "region", + "rustc-demangle", + "serde", + "smallvec 1.6.1", + "target-lexicon", + "wasmparser", + "wasmtime-cache", + "wasmtime-environ", + "wasmtime-jit", + "wasmtime-profiling", + "wasmtime-runtime", + "wat", + "winapi 0.3.9", ] [[package]] -name = "web3" -version = "0.13.0" +name = "wasmtime-cache" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50d03f64be59921dbc5791f05af61a87594bb454518fe4e97d827405422279a0" +checksum = "c01d9287e36921e46f5887a47007824ae5dbb9b7517a2d565660ab4471478709" dependencies = [ - "arrayvec 0.5.2", - "base64 0.12.3", - "derive_more 0.99.11", - "ethabi", - "ethereum-types", - "futures 0.3.12", - "futures-timer 3.0.2", - "hyper 0.13.10", - "hyper-tls", - "jsonrpc-core 14.2.0", + "anyhow", + "base64 0.13.0", + "bincode", + "directories-next", + "errno", + "file-per-thread-logger", + "libc", "log", - "native-tls", - "parking_lot 0.11.1", - "rlp 0.4.6", - "rustc-hex", - "secp256k1", "serde", - "serde_json", - "tiny-keccak 2.0.2", - "url 2.2.0", + "sha2 0.9.3", + "toml", + "winapi 0.3.9", + "zstd", ] [[package]] -name = "webpki" -version = "0.21.2" +name = "wasmtime-cranelift" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1f50e1972865d6b1adb54167d1c8ed48606004c2c9d0ea5f1eeb34d95e863ef" +checksum = "4134ed3a4316cd0de0e546c6004850afe472b0fa3fcdc2f2c15f8d449562d962" dependencies = [ - "ring", - "untrusted", + "cranelift-codegen", + "cranelift-entity", + "cranelift-frontend", + "cranelift-wasm", + "wasmtime-environ", ] [[package]] -name = "webpki-roots" -version = "0.18.0" +name = "wasmtime-debug" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91cd5736df7f12a964a5067a12c62fa38e1bd8080aff1f80bc29be7c80d19ab4" +checksum = "e91fa931df6dd8af2b02606307674d3bad23f55473d5f4c809dddf7e4c4dc411" dependencies = [ - "webpki", + "anyhow", + "gimli", + "more-asserts", + "object 0.22.0", + "target-lexicon", + "thiserror", + "wasmparser", + "wasmtime-environ", ] [[package]] -name = "webpki-roots" -version = "0.19.0" +name = "wasmtime-environ" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8eff4b7516a57307f9349c64bf34caa34b940b66fed4b2fb3136cb7386e5739" +checksum = "a1098871dc3120aaf8190d79153e470658bb79f63ee9ca31716711e123c28220" dependencies = [ - "webpki", + "anyhow", + "cfg-if 1.0.0", + "cranelift-codegen", + "cranelift-entity", + "cranelift-wasm", + "gimli", + "indexmap", + "log", + "more-asserts", + "serde", + "thiserror", + "wasmparser", +] + +[[package]] +name = "wasmtime-jit" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "738bfcd1561ede8bb174215776fd7d9a95d5f0a47ca3deabe0282c55f9a89f68" +dependencies = [ + "addr2line", + "anyhow", + "cfg-if 1.0.0", + "cranelift-codegen", + "cranelift-entity", + "cranelift-frontend", + "cranelift-native", + "cranelift-wasm", + "gimli", + "log", + "more-asserts", + "object 0.22.0", + "rayon", + "region", + "serde", + "target-lexicon", + "thiserror", + "wasmparser", + "wasmtime-cranelift", + "wasmtime-debug", + "wasmtime-environ", + "wasmtime-obj", + "wasmtime-profiling", + "wasmtime-runtime", + "winapi 0.3.9", +] + +[[package]] +name = "wasmtime-obj" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e96d77f1801131c5e86d93e42a3cf8a35402107332c202c245c83f34888a906" +dependencies = [ + "anyhow", + "more-asserts", + "object 0.22.0", + "target-lexicon", + "wasmtime-debug", + "wasmtime-environ", +] + +[[package]] +name = "wasmtime-profiling" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60bb672c9d894776d7b9250dd9b4fe890f8760201ee4f53e5f2da772b6c4debb" +dependencies = [ + "anyhow", + "cfg-if 1.0.0", + "gimli", + "lazy_static", + "libc", + "object 0.22.0", + "scroll", + "serde", + "target-lexicon", + "wasmtime-environ", + "wasmtime-runtime", +] + +[[package]] +name = "wasmtime-runtime" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978086740949eeedfefcee667b57a9e98d9a7fc0de382fcfa0da30369e3530d" +dependencies = [ + "backtrace", + "cc", + "cfg-if 1.0.0", + "indexmap", + "lazy_static", + "libc", + "log", + "memoffset 0.6.1", + "more-asserts", + "psm", + "region", + "thiserror", + "wasmtime-environ", + "winapi 0.3.9", +] + +[[package]] +name = "wast" +version = "35.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db5ae96da18bb5926341516fd409b5a8ce4e4714da7f0a1063d3b20ac9f9a1e1" +dependencies = [ + "leb128", +] + +[[package]] +name = "wat" +version = "1.0.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b0fa059022c5dabe129f02b429d67086400deb8277f89c975555dacc1dadbcc" +dependencies = [ + "wast", +] + +[[package]] +name = "web-sys" +version = "0.3.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec600b26223b2948cedfde2a0aa6756dcf1fef616f43d7b3097aaf53a6c4d92b" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki" +version = "0.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e38c0608262c46d4a56202ebabdeb094cef7e560ca7a226c6bf055188aa4ea" +dependencies = [ + "ring", + "untrusted", ] [[package]] name = "webpki-roots" -version = "0.20.0" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f20dea7535251981a9670857150d571846545088359b28e4951d350bdaf179f" +checksum = "82015b7e0b8bad8185994674a13a93306bea76cf5a16c5a181382fd3a5ec2376" dependencies = [ "webpki", ] @@ -9404,6 +8963,16 @@ dependencies = [ "libc", ] +[[package]] +name = "which" +version = "4.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87c14ef7e1b8b8ecfc75d5eca37949410046e66f15d185c01d70824f1f8111ef" +dependencies = [ + "libc", + "thiserror", +] + [[package]] name = "winapi" version = "0.2.8" @@ -9447,15 +9016,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "winreg" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0120db82e8a1e0b9fb3345a539c478767c0048d842860994d96113d5b667bd69" -dependencies = [ - "winapi 0.3.9", -] - [[package]] name = "ws2_32-sys" version = "0.2.1" @@ -9467,15 +9027,10 @@ dependencies = [ ] [[package]] -name = "x25519-dalek" -version = "0.6.0" +name = "wyz" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "637ff90c9540fa3073bb577e65033069e4bae7c79d49d74aa3ffdf5342a53217" -dependencies = [ - "curve25519-dalek 2.1.2", - "rand_core 0.5.1", - "zeroize", -] +checksum = "85e60b0d1b5f99db2556934e21937020776a5d31520bf169e851ac44e6420214" [[package]] name = "x25519-dalek" @@ -9490,11 +9045,11 @@ dependencies = [ [[package]] name = "yamux" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aeb8c4043cac71c3c299dff107171c220d179492350ea198e109a414981b83c" +checksum = "1cc7bd8c983209ed5d527f44b01c41b7dc146fd960c61cf9e1d25399841dc271" dependencies = [ - "futures 0.3.12", + "futures 0.3.13", "log", "nohash-hasher", "parking_lot 0.11.1", @@ -9517,8 +9072,39 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3f369ddb18862aba61aa49bf31e74d29f0f162dec753063200e1dc084345d16" dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", + "proc-macro2", + "quote", + "syn", "synstructure", ] + +[[package]] +name = "zstd" +version = "0.5.4+zstd.1.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69996ebdb1ba8b1517f61387a883857818a66c8a295f487b1ffd8fd9d2c82910" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "2.0.6+zstd.1.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98aa931fb69ecee256d44589d19754e61851ae4769bf963b385119b1cc37a49e" +dependencies = [ + "libc", + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "1.4.18+zstd.1.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1e6e8778706838f43f771d80d37787cb2fe06dafe89dd3aebaf6721b9eaec81" +dependencies = [ + "cc", + "glob", + "itertools", + "libc", +] diff --git a/Cargo.toml b/Cargo.toml index 745344cdf6..76c4cd3c34 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,23 +1,14 @@ [workspace] members = [ + "bin/node", "bin/node/cli", "bin/node/rpc", "bin/node/runtime", "bin/node/primitives", - "frame/operator", - "frame/trading", - "frame/dapps-staking", "frame/plasm-rewards", - "frame/plasm-lockdrop", "frame/plasm-support", "frame/plasm-validator", - "frame/ovm", - "frame/ovm/rpc/runtime-api", - "frame/plasma", - "frame/plasma/rpc/runtime-api", "frame/custom-signatures", - "ovmi/lib", - "ovmi/cli", ] exclude = [ diff --git a/bin/node/Cargo.toml b/bin/node/Cargo.toml new file mode 100644 index 0000000000..8dea53f71a --- /dev/null +++ b/bin/node/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "plasm" +version = "1.8.0" +authors = ["Stake Technologies "] +description = "Plasm node implementation in Rust." +edition = "2018" + +[[bin]] +name = "plasm" +path = "src/main.rs" + +[dependencies] +parity-util-mem = { version = "0.9.0", default-features = false, features = ["jemalloc-global"] } +plasm-cli = { path = "cli" } diff --git a/bin/node/cli/Cargo.toml b/bin/node/cli/Cargo.toml index af9bfdc78e..f82d75a69d 100644 --- a/bin/node/cli/Cargo.toml +++ b/bin/node/cli/Cargo.toml @@ -1,90 +1,78 @@ [package] name = "plasm-cli" -version = "1.7.0" +version = "1.8.0" authors = ["Stake Technologies "] -description = "Plasm node implementation in Rust." +description = "Plasm node console line interfaces." build = "build.rs" edition = "2018" -default-run = "plasm-node" - -[[bin]] -name = "plasm-node" -path = "bin/main.rs" -required-features = ["cli"] - -[lib] -crate-type = ["cdylib", "rlib"] [dependencies] # thidr-party dependencies -codec = { package = "parity-scale-codec", version = "1.3" } +codec = { package = "parity-scale-codec", version = "2.0" } serde = { version = "1.0", features = [ "derive" ] } structopt = { version = "0.3.8", optional = true } -jsonrpc-core = "15.0.0" -jsonrpc-pubsub = "15.0.0" hex-literal = "0.2.1" serde_json = "1.0" futures = "0.3.4" -log = "0.4.8" hex = "0.4" # primitives -sp-core = "2.0.0" -sp-runtime = "2.0.0" -sp-inherents = "2.0.0" -sp-consensus = "0.8.0" -sp-consensus-babe = "0.8.0" -sp-finality-grandpa = "2.0.0" -sp-transaction-pool = "2.0.0" +sp-core = "3.0.0" +sp-runtime = "3.0.0" +sp-inherents = "3.0.0" +sp-consensus = "0.9.0" +sp-consensus-babe = "0.9.0" +sp-finality-grandpa = "3.0.0" +sp-transaction-pool = "3.0.0" # client dependencies -sc-client-api = "2.0.0" -sc-chain-spec = "2.0.0" -sc-consensus = "0.8.0" -sc-executor = "0.8.0" -sc-transaction-pool = "2.0.0" -sc-network = "0.8.0" -sc-finality-grandpa = "0.8.0" -sc-offchain = "2.0.0" -sc-client-db = { version = "0.8.0", default-features = false } -sc-rpc = "2.0.0" -sc-basic-authorship = "0.8.0" -sc-service = "0.8.0" -sc-telemetry = "2.0.0" -sc-consensus-babe = "0.8.0" -frontier-consensus = { path = "../../../vendor/frontier/consensus" } +sc-client-api = "3.0.0" +sc-chain-spec = "3.0.0" +sc-consensus = "0.9.0" +sc-consensus-slots = "0.9.0" +sc-executor = "0.9.0" +sc-transaction-pool = "3.0.0" +sc-network = "0.9.0" +sc-finality-grandpa = "0.9.0" +sc-offchain = "3.0.0" +sc-client-db = { version = "0.9.0", default-features = false } +sc-rpc = "3.0.0" +sc-basic-authorship = "0.9.0" +sc-service = "0.9.0" +sc-telemetry = "3.0.0" +sc-consensus-babe = "0.9.0" +fc-consensus = { path = "../../../vendor/frontier/client/consensus" } +fp-consensus = { path = "../../../vendor/frontier/primitives/consensus" } +fc-rpc-core= { path = "../../../vendor/frontier/client/rpc-core" } # plasm-specific dependencies -lockdrop-oracle = { path = "./lockdrop-oracle" } plasm-primitives = { path = "../primitives" } plasm-runtime = { path = "../runtime" } plasm-rpc = { path = "../rpc" } # frame dependencies -frame-system = "2.0.0" -pallet-transaction-payment = "2.0.0" -pallet-finality-tracker = "2.0.0" -pallet-contracts = "2.0.0" -pallet-dapps-staking = { path = "../../../frame/dapps-staking" } -pallet-plasm-lockdrop = { path = "../../../frame/plasm-lockdrop" } -pallet-ovm = { path = "../../../frame/ovm" } +frame-system = "3.0.0" +pallet-transaction-payment = "3.0.0" +pallet-contracts = "3.0.0" +pallet-im-online = "3.0.0" +#pallet-dapps-staking = { path = "../../../frame/dapps-staking" } +#pallet-ovm = { path = "../../../frame/ovm" } pallet-evm = { path = "../../../vendor/frontier/frame/evm" } # CLI-specific dependencies -sc-cli = { version = "0.8.0", optional = true } +sc-cli = { version = "0.9.0", optional = true } [build-dependencies] -sc-cli = "0.8.0" -build-script-utils = { package = "substrate-build-script-utils", version = "2.0.0" } -lockdrop-oracle = { path = "./lockdrop-oracle" } +sc-cli = "0.9.0" +build-script-utils = { package = "substrate-build-script-utils", version = "3.0.0" } structopt = { version = "0.3.8", optional = true } vergen = { version = "3.0.4", optional = true } [features] -default = ["cli"] +default = ["cli","wasmtime"] +wasmtime = [ "sc-cli/wasmtime" ] cli = [ "sc-cli", - "sc-service/db", "structopt", "vergen", ] diff --git a/bin/node/cli/bin/main.rs b/bin/node/cli/bin/main.rs deleted file mode 100644 index 303e5dcaca..0000000000 --- a/bin/node/cli/bin/main.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Plasm Node CLI - -#![warn(missing_docs)] - -fn main() -> Result<(), sc_cli::Error> { - plasm_cli::run() -} diff --git a/bin/node/cli/lockdrop-oracle/Cargo.toml b/bin/node/cli/lockdrop-oracle/Cargo.toml deleted file mode 100644 index 0e9d3573f1..0000000000 --- a/bin/node/cli/lockdrop-oracle/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "lockdrop-oracle" -version = "1.7.0" -authors = ["Stake Technologies "] -edition = "2018" - -[dependencies] -codec = { package = "parity-scale-codec", version = "1.3" } -pallet-plasm-lockdrop = { path = "../../../../frame/plasm-lockdrop" } -reqwest = { version = "0.10", default-features = false, features = ["rustls-tls", "json", "blocking"] } -web3 = { version = "0.13", default-features = false, features = ["http-tls"] } -ethabi = "12.0" -sp-core = "2.0.0" -sc-service = "0.8.0" -libsecp256k1 = "0.3.5" -serde_json = "1.0" -structopt = "0.3.8" -log = "0.4.8" -hex = "0.4" -tide = "0.13" - -[dev-dependencies] -hex-literal = "0.2.1" diff --git a/bin/node/cli/lockdrop-oracle/abis/chainlink.json b/bin/node/cli/lockdrop-oracle/abis/chainlink.json deleted file mode 100644 index 7fd5dea191..0000000000 --- a/bin/node/cli/lockdrop-oracle/abis/chainlink.json +++ /dev/null @@ -1 +0,0 @@ -[{"constant":true,"inputs":[],"name":"latestAnswer","outputs":[{"name":"","type":"int256"}],"payable":false,"stateMutability":"view","type":"function"}] diff --git a/bin/node/cli/lockdrop-oracle/src/chainlink.rs b/bin/node/cli/lockdrop-oracle/src/chainlink.rs deleted file mode 100644 index aa2fb60ebd..0000000000 --- a/bin/node/cli/lockdrop-oracle/src/chainlink.rs +++ /dev/null @@ -1,19 +0,0 @@ -///! Chainlink smart contract based price oracle. -use web3::contract::{Contract, Error, Options}; - -// ROPSTEN -const ETHUSD: &str = "30B5068156688f818cEa0874B580206dFe081a03"; - -pub async fn eth_usd(web3: web3::Web3) -> Result { - let contract = ETHUSD.parse().expect("correct oracle address"); - - let contract = Contract::from_json( - web3.eth(), - contract, - include_bytes!("../abis/chainlink.json"), - ) - .unwrap(); - contract - .query("latestAnswer", (), None, Options::default(), None) - .await -} diff --git a/bin/node/cli/lockdrop-oracle/src/cli.rs b/bin/node/cli/lockdrop-oracle/src/cli.rs deleted file mode 100644 index 1062dcd332..0000000000 --- a/bin/node/cli/lockdrop-oracle/src/cli.rs +++ /dev/null @@ -1,16 +0,0 @@ -//! Lockdrop module CLI parameters. - -use structopt::StructOpt; - -#[derive(Debug, Clone, StructOpt)] -pub struct Config { - /// Ethereum node endpoint. - #[structopt(long, default_value = "https://ropsten.infura.io/v3")] - pub ethereum_endpoint: String, - /// Ethereum lockdrop smart contract address. - #[structopt(long, default_value = "33251e1298dF5Ff84166E62Abecf85FCCD1A1241")] - pub lockdrop_contract: String, - /// Ethereum minimum transaction confirmations. - #[structopt(long, default_value = "10")] - pub safe_eth_confirmations: u64, -} diff --git a/bin/node/cli/lockdrop-oracle/src/eth_utils.rs b/bin/node/cli/lockdrop-oracle/src/eth_utils.rs deleted file mode 100644 index 9e67d10ccf..0000000000 --- a/bin/node/cli/lockdrop-oracle/src/eth_utils.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! Ethereum locking helpers. - -use sp_core::{keccak_256, H160, U256}; - -/// Get Ethereum address for given ECDSA public key. -pub fn to_address(public: &[u8]) -> Option { - if let Ok(pubkey) = secp256k1::PublicKey::parse_slice(public, None) { - let address = H160::from_slice(&keccak_256(&pubkey.serialize()[1..])[12..32]); - Some(address) - } else { - None - } -} - -/// Compile smart contract input for lock value on given duration. -pub fn lock_method(duration: u64) -> Vec { - // Lock method signature - let method = keccak_256("lock(uint256,address)".as_bytes()); - // Duration in days - let duration_param = U256::from(duration / 86400); - // Transaction input - ethabi::encode(&[ - ethabi::Token::FixedBytes(method[0..4].to_vec()), - ethabi::Token::Uint(duration_param), - ]) -} diff --git a/bin/node/cli/lockdrop-oracle/src/lib.rs b/bin/node/cli/lockdrop-oracle/src/lib.rs deleted file mode 100644 index e67990f708..0000000000 --- a/bin/node/cli/lockdrop-oracle/src/lib.rs +++ /dev/null @@ -1,120 +0,0 @@ -//! Web-server helper for Lockdrop runtime module. - -#![feature(proc_macro_hygiene)] - -use codec::Decode; -use pallet_plasm_lockdrop::LockCheck; -use tide::{http::StatusCode, Response}; - -mod chainlink; -mod cli; -mod eth_utils; - -pub use cli::Config; - -#[derive(Clone)] -struct ServerState { - pub ethereum_transport: web3::transports::Http, - pub lockdrop_contract: web3::types::Address, - pub safe_eth_confirmations: u64, -} - -pub async fn start(config: Config) { - let ethereum_transport = - web3::transports::Http::new(config.ethereum_endpoint.as_str()).unwrap(); - let lockdrop_contract = config.lockdrop_contract.parse().unwrap(); - let safe_eth_confirmations = config.safe_eth_confirmations; - let mut app = tide::with_state(ServerState { - ethereum_transport, - lockdrop_contract, - safe_eth_confirmations, - }); - - app.at("/eth/ticker") - .get(|req: tide::Request| async move { - let web3 = web3::Web3::new(req.state().ethereum_transport.clone()); - let usd_price = chainlink::eth_usd(web3).await? / 10_u128.pow(8); - Ok(usd_price.to_string()) - }); - - app.at("/eth/lock") - .post(|mut req: tide::Request| async move { - let body = req.body_bytes().await?; - let lock = LockCheck::decode(&mut &body[..])?; - log::debug!( - target: "lockdrop-oracle", - "ETH lock check request: {:#?}", lock - ); - - let web3 = web3::Web3::new(req.state().ethereum_transport.clone()); - let block_number = web3.eth().block_number().await?; - let tx = web3 - .eth() - .transaction(web3::types::TransactionId::Hash(lock.tx_hash)) - .await? - .unwrap(); - log::debug!( - target: "lockdrop-oracle", - "Ethereum transaction at {}: {:#?}", lock.tx_hash, tx - ); - - // check transaction value - if tx.value != lock.value.into() { - log::debug!(target: "lockdrop-oracle", "lock value mismatch"); - return Ok(Response::new(StatusCode::BadRequest)); - } - - let tx_block_number = tx.block_number.unwrap_or(Default::default()); - let tx_confirmations = if block_number > tx_block_number { - block_number - tx_block_number - } else { - Default::default() - }; - log::debug!( - target: "lockdrop-oracle", - "Transaction confirmations: {}", tx_confirmations - ); - if tx_confirmations < req.state().safe_eth_confirmations.into() { - log::debug!(target: "lockdrop-oracle", "transaction isn't confirmed yet"); - return Ok(Response::new(StatusCode::BadRequest)); - } - - let sender = - eth_utils::to_address(lock.public_key.as_ref()).unwrap_or(Default::default()); - log::debug!( - target: "lockdrop-oracle", - "ETH address for public key {}: {}", - lock.public_key, sender - ); - // check sender address - if tx.from != sender { - log::debug!(target: "lockdrop-oracle", "sender address mismatch"); - return Ok(Response::new(StatusCode::BadRequest)); - } - - // check that destination is lockdrop smart contract - if tx.to != Some(req.state().lockdrop_contract) { - log::debug!(target: "lockdrop-oracle", "contract address mismatch"); - return Ok(Response::new(StatusCode::BadRequest)); - } - - // check smart contract method input - let lock_method = eth_utils::lock_method(lock.duration); - if tx.input.0[0..36] == lock_method[0..36] { - log::debug!( - target: "lockdrop-oracle", - "lock method mismatch: {} /= {}", - hex::encode(tx.input.0), - hex::encode(lock_method), - ); - return Ok(Response::new(StatusCode::BadRequest)); - } - - Ok(Response::new(StatusCode::Ok)) - }); - - app.listen("127.0.0.1:34347") - .await - .map_err(|e| log::error!("oracle web-server error: {}", e)) - .unwrap_or(()); -} diff --git a/bin/node/cli/src/chain_spec.rs b/bin/node/cli/src/chain_spec.rs index 7676be475b..e20873c8af 100644 --- a/bin/node/cli/src/chain_spec.rs +++ b/bin/node/cli/src/chain_spec.rs @@ -1,11 +1,12 @@ //! Chain specification. +use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use plasm_primitives::{AccountId, Balance, Signature}; use plasm_runtime::constants::currency::PLM; use plasm_runtime::Block; use plasm_runtime::{ BabeConfig, BalancesConfig, ContractsConfig, EVMConfig, EthereumConfig, GenesisConfig, - GrandpaConfig, IndicesConfig, PlasmLockdropConfig, PlasmRewardsConfig, PlasmValidatorConfig, + GrandpaConfig, ImOnlineConfig, IndicesConfig, PlasmRewardsConfig, PlasmValidatorConfig, SessionConfig, SessionKeys, SudoConfig, SystemConfig, WASM_BINARY, }; use sc_chain_spec::ChainSpecExtension; @@ -14,10 +15,7 @@ use serde::{Deserialize, Serialize}; use sp_consensus_babe::AuthorityId as BabeId; use sp_core::{sr25519, Pair, Public, H160, U256}; use sp_finality_grandpa::AuthorityId as GrandpaId; -use sp_runtime::{ - traits::{IdentifyAccount, Verify}, - Perbill, -}; +use sp_runtime::traits::{IdentifyAccount, Verify}; type AccountPublic = ::Signer; @@ -76,21 +74,26 @@ where } /// Helper function to generate controller and session key from seed -pub fn get_authority_keys_from_seed(seed: &str) -> (AccountId, BabeId, GrandpaId) { +pub fn get_authority_keys_from_seed(seed: &str) -> (AccountId, BabeId, GrandpaId, ImOnlineId) { ( get_account_id_from_seed::(seed), get_from_seed::(seed), get_from_seed::(seed), + get_from_seed::(seed), ) } -fn session_keys(babe: BabeId, grandpa: GrandpaId) -> SessionKeys { - SessionKeys { babe, grandpa } +fn session_keys(babe: BabeId, grandpa: GrandpaId, im_online: ImOnlineId) -> SessionKeys { + SessionKeys { + babe, + grandpa, + im_online, + } } fn testnet_genesis( initial_authorities: Vec, - keys: Vec<(AccountId, BabeId, GrandpaId)>, + keys: Vec<(AccountId, BabeId, GrandpaId, ImOnlineId)>, endowed_accounts: Option>, sudo_key: AccountId, ) -> GenesisConfig { @@ -118,7 +121,7 @@ fn testnet_genesis( /// Helper function to create GenesisConfig fn make_genesis( initial_authorities: Vec, - keys: Vec<(AccountId, BabeId, GrandpaId)>, + keys: Vec<(AccountId, BabeId, GrandpaId, ImOnlineId)>, balances: Vec<(AccountId, Balance)>, root_key: AccountId, enable_println: bool, @@ -136,17 +139,6 @@ fn make_genesis( pallet_plasm_validator: Some(PlasmValidatorConfig { validators: initial_authorities, }), - pallet_plasm_lockdrop: Some(PlasmLockdropConfig { - // Alpha2: 0.44698108660714747 - alpha: Perbill::from_parts(446_981_087), - // Price in dollars: BTC $11000, ETH $400 - dollar_rate: (11_000, 400), - vote_threshold: 1, - positive_votes: 1, - // Start from launch for testing purposes - lockdrop_bounds: (0, 1_000), - keys: vec![], - }), pallet_session: Some(SessionConfig { keys: keys .iter() @@ -154,7 +146,7 @@ fn make_genesis( ( x.0.clone(), x.0.clone(), - session_keys(x.1.clone(), x.2.clone()), + session_keys(x.1.clone(), x.2.clone(), x.3.clone()), ) }) .collect::>(), @@ -165,6 +157,7 @@ fn make_genesis( pallet_grandpa: Some(GrandpaConfig { authorities: vec![], }), + pallet_im_online: Some(ImOnlineConfig { keys: vec![] }), pallet_contracts: Some(ContractsConfig { current_schedule: pallet_contracts::Schedule { enable_println, // this should only be enabled on development chains diff --git a/bin/node/cli/src/cli.rs b/bin/node/cli/src/cli.rs index 8878f5be44..7bcee694b5 100644 --- a/bin/node/cli/src/cli.rs +++ b/bin/node/cli/src/cli.rs @@ -47,8 +47,4 @@ pub enum Subcommand { /// Revert the chain to a previous state. Revert(sc_cli::RevertCmd), - - /// Plasm Lockdrop oracle authority support module. - #[structopt(name = "oracle", about = "Launch lockdrop oracle module.")] - LockdropOracle(lockdrop_oracle::Config), } diff --git a/bin/node/cli/src/command.rs b/bin/node/cli/src/command.rs index 8c55400601..5541f3575f 100644 --- a/bin/node/cli/src/command.rs +++ b/bin/node/cli/src/command.rs @@ -6,7 +6,7 @@ use sc_service::PartialComponents; impl SubstrateCli for Cli { fn impl_name() -> String { - "Plasm Node".into() + "Plasm Network".into() } fn impl_version() -> String { @@ -22,7 +22,7 @@ impl SubstrateCli for Cli { } fn support_url() -> String { - "https://github.com/staketechnologies/plasm/issues/new".into() + "https://github.com/PlasmNetwork/Plasm/issues/new".into() } fn copyright_start_year() -> i32 { @@ -53,12 +53,15 @@ pub fn run() -> sc_cli::Result<()> { match &cli.subcommand { None => { let runner = cli.create_runner(&cli.run)?; - runner.run_node_until_exit(|config| match config.role { - Role::Light => service::new_light(config), - _ => service::new_full(config), + runner.run_node_until_exit(|config| async move { + match config.role { + Role::Light => service::new_light(config), + _ => service::new_full(config), + } + .map_err(sc_cli::Error::Service) }) } - Some(Subcommand::Key(cmd)) => cmd.run(), + Some(Subcommand::Key(cmd)) => cmd.run(&cli), Some(Subcommand::Sign(cmd)) => cmd.run(), Some(Subcommand::Verify(cmd)) => cmd.run(), Some(Subcommand::Vanity(cmd)) => cmd.run(), @@ -128,11 +131,5 @@ pub fn run() -> sc_cli::Result<()> { Ok((cmd.run(client, backend), task_manager)) }) } - Some(Subcommand::LockdropOracle(config)) => { - log::info!("Plasm Lockdrop oracle launch..."); - Ok(futures::executor::block_on(lockdrop_oracle::start( - config.clone(), - ))) - } } } diff --git a/bin/node/cli/src/lib.rs b/bin/node/cli/src/lib.rs index 4a80f6629f..4bfaf79cc5 100644 --- a/bin/node/cli/src/lib.rs +++ b/bin/node/cli/src/lib.rs @@ -21,3 +21,5 @@ pub use browser::*; pub use cli::*; #[cfg(feature = "cli")] pub use command::*; + +pub use sc_cli::Error; diff --git a/bin/node/cli/src/service.rs b/bin/node/cli/src/service.rs index 4dba868109..6df61f085e 100644 --- a/bin/node/cli/src/service.rs +++ b/bin/node/cli/src/service.rs @@ -1,17 +1,19 @@ //! Service implementation. Specialized wrapper over substrate service. -use frontier_consensus::FrontierBlockImport; +use fc_consensus::FrontierBlockImport; +use fc_rpc_core::types::{FilterPool, PendingTransactions}; use plasm_primitives::Block; use plasm_runtime::RuntimeApi; -use sc_client_api::{ExecutorProvider, RemoteBackend}; -use sc_consensus_babe; +use sc_client_api::{BlockchainEvents, ExecutorProvider, RemoteBackend}; use sc_finality_grandpa::{self as grandpa, FinalityProofProvider as GrandpaFinalityProofProvider}; use sc_network::NetworkService; use sc_service::{config::Configuration, error::Error as ServiceError, RpcHandlers, TaskManager}; -use sp_core::traits::BareCryptoStorePtr; use sp_inherents::InherentDataProviders; use sp_runtime::traits::Block as BlockT; -use std::sync::Arc; +use std::{ + collections::{BTreeMap, HashMap}, + sync::{Arc, Mutex}, +}; sc_executor::native_executor_instance!( pub Executor, @@ -47,7 +49,7 @@ pub fn new_partial( >, ServiceError, > { - let (client, backend, keystore, task_manager) = + let (client, backend, keystore_container, task_manager) = sc_service::new_full_parts::(&config)?; let client = Arc::new(client); @@ -55,6 +57,7 @@ pub fn new_partial( let transaction_pool = sc_transaction_pool::BasicPool::new_full( config.transaction_pool.clone(), + config.role.is_authority().into(), config.prometheus_registry(), task_manager.spawn_handle(), client.clone(), @@ -82,7 +85,6 @@ pub fn new_partial( babe_link.clone(), block_import.clone(), Some(Box::new(justification_import)), - None, client.clone(), select_chain.clone(), inherent_data_providers.clone(), @@ -95,7 +97,7 @@ pub fn new_partial( client, backend, task_manager, - keystore, + keystore_container, select_chain, import_queue, transaction_pool, @@ -122,20 +124,26 @@ pub fn new_full_base( backend, mut task_manager, import_queue, - keystore, + keystore_container, select_chain, transaction_pool, inherent_data_providers, other: import_setup, } = new_partial(&config)?; - let (_, grandpa_link, babe_link) = &import_setup; + let (block_import, grandpa_link, babe_link) = import_setup; + + let pending_transactions: PendingTransactions = Some(Arc::new(Mutex::new(HashMap::new()))); + + let filter_pool: Option = Some(Arc::new(Mutex::new(BTreeMap::new()))); let justification_stream = grandpa_link.justification_stream(); let shared_authority_set = grandpa_link.shared_authority_set().clone(); let shared_voter_state = grandpa::SharedVoterState::empty(); - let finality_proof_provider = - GrandpaFinalityProofProvider::new_for_service(backend.clone(), client.clone()); + let finality_proof_provider = GrandpaFinalityProofProvider::new_for_service( + backend.clone(), + Some(shared_authority_set.clone()), + ); let (network, network_status_sinks, system_rpc_tx, network_starter) = sc_service::build_network(sc_service::BuildNetworkParams { @@ -146,8 +154,6 @@ pub fn new_full_base( import_queue, on_demand: None, block_announce_validator_builder: None, - finality_proof_request_builder: None, - finality_proof_provider: Some(finality_proof_provider.clone()), })?; if config.offchain_worker.enabled { @@ -163,10 +169,11 @@ pub fn new_full_base( let role = config.role.clone(); let is_authority = role.is_authority(); let force_authoring = config.force_authoring; + let backoff_authoring_blocks = + Some(sc_consensus_slots::BackoffAuthoringOnFinalizedHeadLagging::default()); let name = config.network.node_name.clone(); let enable_grandpa = !config.disable_grandpa; let prometheus_registry = config.prometheus_registry().cloned(); - let telemetry_connection_sinks = sc_service::TelemetryConnectionSinks::default(); let rpc_extensions_builder = { let babe_config = babe_link.config().clone(); @@ -176,8 +183,10 @@ pub fn new_full_base( let client = client.clone(); let pool = transaction_pool.clone(); let select_chain = select_chain.clone(); - let keystore = keystore.clone(); + let keystore = keystore_container.sync_keystore(); let network = network.clone(); + let pending = pending_transactions.clone(); + let filter_pool = filter_pool.clone(); move |deny_unsafe, subscription_executor: sc_rpc::SubscriptionTaskExecutor| { let deps = plasm_rpc::FullDeps { @@ -187,6 +196,8 @@ pub fn new_full_base( deny_unsafe, is_authority, network: network.clone(), + pending_transactions: pending.clone(), + filter_pool: filter_pool.clone(), babe: plasm_rpc::BabeDeps { babe_config: babe_config.clone(), shared_epoch_changes: shared_epoch_changes.clone(), @@ -205,26 +216,96 @@ pub fn new_full_base( } }; - sc_service::spawn_tasks(sc_service::SpawnTasksParams { - config, - backend: backend.clone(), - client: client.clone(), - keystore: keystore.clone(), - network: network.clone(), - rpc_extensions_builder: Box::new(rpc_extensions_builder), - transaction_pool: transaction_pool.clone(), - task_manager: &mut task_manager, - on_demand: None, - remote_blockchain: None, - telemetry_connection_sinks: telemetry_connection_sinks.clone(), - network_status_sinks, - system_rpc_tx, - })?; + let (_rpc_handlers, telemetry_connection_notifier) = + sc_service::spawn_tasks(sc_service::SpawnTasksParams { + config, + backend: backend.clone(), + client: client.clone(), + keystore: keystore_container.sync_keystore(), + network: network.clone(), + rpc_extensions_builder: Box::new(rpc_extensions_builder), + transaction_pool: transaction_pool.clone(), + task_manager: &mut task_manager, + on_demand: None, + remote_blockchain: None, + network_status_sinks, + system_rpc_tx, + })?; - let (block_import, grandpa_link, babe_link) = import_setup; + // Spawn Frontier EthFilterApi maintenance task. + if filter_pool.is_some() { + use futures::StreamExt; + // Each filter is allowed to stay in the pool for 100 blocks. + const FILTER_RETAIN_THRESHOLD: u64 = 100; + task_manager.spawn_essential_handle().spawn( + "frontier-filter-pool", + client + .import_notification_stream() + .for_each(move |notification| { + if let Ok(locked) = &mut filter_pool.clone().unwrap().lock() { + let imported_number: u64 = notification.header.number as u64; + for (k, v) in locked.clone().iter() { + let lifespan_limit = v.at_block + FILTER_RETAIN_THRESHOLD; + if lifespan_limit <= imported_number { + locked.remove(&k); + } + } + } + futures::future::ready(()) + }), + ); + } + + // Spawn Frontier pending transactions maintenance task (as essential, otherwise we leak). + if pending_transactions.is_some() { + use fp_consensus::{ConsensusLog, FRONTIER_ENGINE_ID}; + use futures::StreamExt; + use sp_runtime::generic::OpaqueDigestItemId; + + const TRANSACTION_RETAIN_THRESHOLD: u64 = 5; + task_manager.spawn_essential_handle().spawn( + "frontier-pending-transactions", + client + .import_notification_stream() + .for_each(move |notification| { + if let Ok(locked) = &mut pending_transactions.clone().unwrap().lock() { + // As pending transactions have a finite lifespan anyway + // we can ignore MultiplePostRuntimeLogs error checks. + let mut frontier_log: Option<_> = None; + for log in notification.header.digest.logs { + let log = log.try_to::(OpaqueDigestItemId::Consensus( + &FRONTIER_ENGINE_ID, + )); + if let Some(log) = log { + frontier_log = Some(log); + } + } + + let imported_number: u64 = notification.header.number as u64; + + if let Some(ConsensusLog::EndBlock { + block_hash: _, + transaction_hashes, + }) = frontier_log + { + // Retain all pending transactions that were not + // processed in the current block. + locked.retain(|&k, _| !transaction_hashes.contains(&k)); + } + locked.retain(|_, v| { + // Drop all the transactions that exceeded the given lifespan. + let lifespan_limit = v.at_block + TRANSACTION_RETAIN_THRESHOLD; + lifespan_limit > imported_number + }); + } + futures::future::ready(()) + }), + ); + } if let sc_service::config::Role::Authority { .. } = &role { let proposer = sc_basic_authorship::ProposerFactory::new( + task_manager.spawn_handle(), client.clone(), transaction_pool.clone(), prometheus_registry.as_ref(), @@ -234,7 +315,7 @@ pub fn new_full_base( sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()); let babe_config = sc_consensus_babe::BabeParams { - keystore: keystore.clone(), + keystore: keystore_container.sync_keystore(), client: client.clone(), select_chain, env: proposer, @@ -242,6 +323,7 @@ pub fn new_full_base( sync_oracle: network.clone(), inherent_data_providers: inherent_data_providers.clone(), force_authoring, + backoff_authoring_blocks, babe_link, can_author_with, }; @@ -255,7 +337,7 @@ pub fn new_full_base( // if the node isn't actively participating in consensus then it doesn't // need a keystore, regardless of which protocol we use below. let keystore = if role.is_authority() { - Some(keystore as BareCryptoStorePtr) + Some(keystore_container.sync_keystore()) } else { None }; @@ -281,8 +363,7 @@ pub fn new_full_base( config, link: grandpa_link, network: network.clone(), - inherent_data_providers: inherent_data_providers.clone(), - telemetry_on_connect: Some(telemetry_connection_sinks.on_connect_stream()), + telemetry_on_connect: telemetry_connection_notifier.map(|x| x.on_connect_stream()), voting_rule: grandpa::VotingRulesBuilder::default().build(), prometheus_registry, shared_voter_state, @@ -293,8 +374,6 @@ pub fn new_full_base( task_manager .spawn_essential_handle() .spawn_blocking("grandpa-voter", grandpa::run_grandpa_voter(grandpa_config)?); - } else { - grandpa::setup_disabled_grandpa(client.clone(), &inherent_data_providers, network.clone())?; } network_starter.start_network(); @@ -326,7 +405,7 @@ pub fn new_light_base( ), ServiceError, > { - let (client, backend, keystore, mut task_manager, on_demand) = + let (client, backend, keystore_container, mut task_manager, on_demand) = sc_service::new_light_parts::(&config)?; let select_chain = sc_consensus::LongestChain::new(backend.clone()); @@ -339,16 +418,13 @@ pub fn new_light_base( on_demand.clone(), )); - let grandpa_block_import = grandpa::light_block_import( + let (grandpa_block_import, _) = grandpa::block_import( client.clone(), - backend.clone(), &(client.clone() as Arc<_>), - Arc::new(on_demand.checker().clone()), + select_chain.clone(), )?; let finality_proof_import = grandpa_block_import.clone(); - let finality_proof_request_builder = - finality_proof_import.create_finality_proof_request_builder(); let (babe_block_import, babe_link) = sc_consensus_babe::block_import( sc_consensus_babe::Config::get_or_compute(&*client)?, @@ -361,7 +437,6 @@ pub fn new_light_base( let import_queue = sc_consensus_babe::import_queue( babe_link, babe_block_import, - None, Some(Box::new(finality_proof_import)), client.clone(), select_chain.clone(), @@ -371,9 +446,6 @@ pub fn new_light_base( sp_consensus::NeverCanAuthor, )?; - let finality_proof_provider = - GrandpaFinalityProofProvider::new_for_service(backend.clone(), client.clone()); - let (network, network_status_sinks, system_rpc_tx, network_starter) = sc_service::build_network(sc_service::BuildNetworkParams { config: &config, @@ -383,8 +455,6 @@ pub fn new_light_base( import_queue, on_demand: Some(on_demand.clone()), block_announce_validator_builder: None, - finality_proof_request_builder: Some(finality_proof_request_builder), - finality_proof_provider: Some(finality_proof_provider), })?; network_starter.start_network(); @@ -407,21 +477,21 @@ pub fn new_light_base( let rpc_extensions = plasm_rpc::create_light(light_deps); - let rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams { - on_demand: Some(on_demand), - remote_blockchain: Some(backend.remote_blockchain()), - rpc_extensions_builder: Box::new(sc_service::NoopRpcExtensionBuilder(rpc_extensions)), - client: client.clone(), - transaction_pool: transaction_pool.clone(), - config, - keystore, - backend, - network_status_sinks, - system_rpc_tx, - network: network.clone(), - telemetry_connection_sinks: sc_service::TelemetryConnectionSinks::default(), - task_manager: &mut task_manager, - })?; + let (rpc_handlers, _telemetry_connection_notifier) = + sc_service::spawn_tasks(sc_service::SpawnTasksParams { + on_demand: Some(on_demand), + remote_blockchain: Some(backend.remote_blockchain()), + rpc_extensions_builder: Box::new(sc_service::NoopRpcExtensionBuilder(rpc_extensions)), + client: client.clone(), + transaction_pool: transaction_pool.clone(), + config, + keystore: keystore_container.sync_keystore(), + backend, + network_status_sinks, + system_rpc_tx, + network: network.clone(), + task_manager: &mut task_manager, + })?; Ok(( task_manager, diff --git a/bin/node/primitives/Cargo.toml b/bin/node/primitives/Cargo.toml index f2b5eaa8a9..c6d867d091 100644 --- a/bin/node/primitives/Cargo.toml +++ b/bin/node/primitives/Cargo.toml @@ -1,15 +1,15 @@ [package] name = "plasm-primitives" -version = "1.7.0" +version = "1.8.0" authors = ["Stake Technologies "] edition = "2018" [dependencies] -codec = { package = "parity-scale-codec", version = "1.3.5", default-features = false } -sp-core = { version = "2.0.0", default-features = false } -sp-runtime = { version = "2.0.0", default-features = false } -sp-application-crypto = { version = "2.0.0", default-features = false } -frame-system = { version = "2.0.0", default-features = false } +codec = { package = "parity-scale-codec", version = "2.0", default-features = false } +sp-core = { version = "3.0.0", default-features = false } +sp-runtime = { version = "3.0.0", default-features = false } +sp-application-crypto = { version = "3.0.0", default-features = false } +frame-system = { version = "3.0.0", default-features = false } [features] default = ["std"] diff --git a/bin/node/rpc/Cargo.toml b/bin/node/rpc/Cargo.toml index 6ea3aa67c5..dbb118c7f9 100644 --- a/bin/node/rpc/Cargo.toml +++ b/bin/node/rpc/Cargo.toml @@ -1,33 +1,34 @@ [package] name = "plasm-rpc" -version = "1.7.0" +version = "1.8.0" authors = ["Stake Technologies "] edition = "2018" [dependencies] plasm-runtime = { path = "../runtime" } plasm-primitives = { path = "../primitives" } -frontier-rpc = { path = "../../../vendor/frontier/rpc" } -frontier-rpc-primitives = { path = "../../../vendor/frontier/rpc/primitives" } +fc-rpc = { path = "../../../vendor/frontier/client/rpc" } +fc-rpc-core = { path = "../../../vendor/frontier/client/rpc-core" } +fp-rpc = { path = "../../../vendor/frontier/primitives/rpc" } jsonrpc-core = "15.0.0" jsonrpc-pubsub = "15.0.0" -sp-api = "2.0.0" -sp-runtime = "2.0.0" -sp-blockchain = "2.0.0" -sp-block-builder = "2.0.0" -sp-consensus = "0.8.0" -sp-consensus-babe = "0.8.0" -sp-transaction-pool = "2.0.0" -sc-rpc = "2.0.0" -sc-rpc-api = "0.8.0" -sc-keystore = "2.0.0" -sc-client-api = "2.0.0" -sc-consensus-babe = "0.8.0" -sc-consensus-babe-rpc = "0.8.0" -sc-consensus-epochs = "0.8.0" -sc-finality-grandpa = "0.8.0" -sc-finality-grandpa-rpc = "0.8.0" -sc-network = "0.8.0" -pallet-contracts-rpc = "0.8.0" -pallet-transaction-payment-rpc = "2.0.0" -substrate-frame-rpc-system = "2.0.0" +sp-api = "3.0.0" +sp-runtime = "3.0.0" +sp-blockchain = "3.0.0" +sp-block-builder = "3.0.0" +sp-consensus = "0.9.0" +sp-consensus-babe = "0.9.0" +sp-transaction-pool = "3.0.0" +sp-keystore = "0.9.0" +sc-rpc = "3.0.0" +sc-rpc-api = "0.9.0" +sc-client-api = "3.0.0" +sc-consensus-babe = "0.9.0" +sc-consensus-babe-rpc = "0.9.0" +sc-consensus-epochs = "0.9.0" +sc-finality-grandpa = "0.9.0" +sc-finality-grandpa-rpc = "0.9.0" +sc-network = "0.9.0" +pallet-contracts-rpc = "3.0.0" +pallet-transaction-payment-rpc = "3.0.0" +substrate-frame-rpc-system = "3.0.0" diff --git a/bin/node/rpc/src/lib.rs b/bin/node/rpc/src/lib.rs index 3244c0bc5d..d4a77c04cd 100644 --- a/bin/node/rpc/src/lib.rs +++ b/bin/node/rpc/src/lib.rs @@ -15,6 +15,7 @@ use std::sync::Arc; +use fc_rpc_core::types::{FilterPool, PendingTransactions}; use jsonrpc_pubsub::manager::SubscriptionManager; use plasm_primitives::{AccountId, Balance, Block, BlockNumber, Hash, Index}; use sc_client_api::{ @@ -28,7 +29,6 @@ use sc_finality_grandpa::{ FinalityProofProvider, GrandpaJustificationStream, SharedAuthoritySet, SharedVoterState, }; use sc_finality_grandpa_rpc::GrandpaRpcHandler; -use sc_keystore::KeyStorePtr; use sc_rpc::SubscriptionTaskExecutor; pub use sc_rpc_api::DenyUnsafe; use sp_api::ProvideRuntimeApi; @@ -36,6 +36,7 @@ use sp_block_builder::BlockBuilder; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; use sp_consensus::SelectChain; use sp_consensus_babe::BabeApi; +use sp_keystore::SyncCryptoStorePtr; use sp_transaction_pool::TransactionPool; /// Light client extra dependencies. @@ -57,7 +58,7 @@ pub struct BabeDeps { /// BABE pending epoch changes. pub shared_epoch_changes: SharedEpochChanges, /// The keystore that manages the keys of the node. - pub keystore: KeyStorePtr, + pub keystore: SyncCryptoStorePtr, } /// Extra dependencies for GRANDPA @@ -88,6 +89,10 @@ pub struct FullDeps { pub is_authority: bool, /// Network service pub network: Arc>, + /// Ethereum pending transactions. + pub pending_transactions: PendingTransactions, + /// EthFilterApi pool. + pub filter_pool: Option, /// BABE specific dependencies. pub babe: BabeDeps, /// GRANDPA specific dependencies. @@ -110,7 +115,7 @@ where C::Api: substrate_frame_rpc_system::AccountNonceApi, C::Api: pallet_contracts_rpc::ContractsRuntimeApi, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, - C::Api: frontier_rpc_primitives::EthereumRuntimeRPCApi, + C::Api: fp_rpc::EthereumRuntimeRPCApi, C::Api: BabeApi, C::Api: BlockBuilder, ::Error: std::fmt::Debug, @@ -119,8 +124,9 @@ where B: sc_client_api::Backend + Send + Sync + 'static, B::State: StateBackend>, { - use frontier_rpc::{ - EthApi, EthApiServer, EthPubSubApi, EthPubSubApiServer, NetApi, NetApiServer, + use fc_rpc::{ + EthApi, EthApiServer, EthFilterApi, EthFilterApiServer, EthPubSubApi, EthPubSubApiServer, + HexEncodedIdProvider, NetApi, NetApiServer, Web3Api, Web3ApiServer, }; use pallet_contracts_rpc::{Contracts, ContractsApi}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; @@ -134,6 +140,8 @@ where deny_unsafe, is_authority, network, + pending_transactions, + filter_pool, babe, grandpa, } = deps; @@ -187,14 +195,30 @@ where pool.clone(), plasm_runtime::TransactionConverter, network.clone(), + pending_transactions.clone(), + Default::default(), is_authority, ))); - io.extend_with(NetApiServer::to_delegate(NetApi::new(client.clone()))); + if let Some(filter_pool) = filter_pool { + io.extend_with(EthFilterApiServer::to_delegate(EthFilterApi::new( + client.clone(), + filter_pool.clone(), + 500 as usize, // max stored filters + ))); + } + io.extend_with(NetApiServer::to_delegate(NetApi::new( + client.clone(), + network.clone(), + ))); + io.extend_with(Web3ApiServer::to_delegate(Web3Api::new(client.clone()))); io.extend_with(EthPubSubApiServer::to_delegate(EthPubSubApi::new( pool.clone(), client.clone(), network.clone(), - SubscriptionManager::new(Arc::new(subscription_task_executor)), + SubscriptionManager::::with_id_provider( + HexEncodedIdProvider::default(), + Arc::new(subscription_task_executor), + ), ))); io diff --git a/bin/node/runtime/Cargo.toml b/bin/node/runtime/Cargo.toml index 1856d0df8c..0ca78e9ab5 100644 --- a/bin/node/runtime/Cargo.toml +++ b/bin/node/runtime/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "plasm-runtime" -version = "1.7.0" +version = "1.8.0" authors = ["Stake Technologies "] edition = "2018" build = "build.rs" @@ -8,60 +8,61 @@ build = "build.rs" [dependencies] # third-party dependencies serde = { version = "1.0.106", optional = true } -codec = { package = "parity-scale-codec", version = "1.3.5", default-features = false, features = ["derive"] } +codec = { package = "parity-scale-codec", version = "2.0", default-features = false, features = ["derive"] } lazy_static = { version = "1.4", optional = true } hex-literal = { version = "0.2", optional = true } # primitives plasm-primitives = { path = "../primitives", default-features = false } -sp-core = { version = "2.0.0", default-features = false } -sp-io = { version = "2.0.0", default-features = false } -sp-runtime = { version = "2.0.0", default-features = false } -sp-runtime-interface = { version = "2.0.0", default-features = false } -sp-consensus-babe = { version = "0.8.0", default-features = false } -sp-offchain = { version = "2.0.0", default-features = false } -sp-api = { version = "2.0.0", default-features = false } -sp-inherents = { version = "2.0.0", default-features = false } -sp-block-builder = { version = "2.0.0", default-features = false } -sp-transaction-pool = { version = "2.0.0", default-features = false } -sp-std = { version = "2.0.0", default-features = false } -sp-version = { version = "2.0.0", default-features = false } -sp-session = { version = "2.0.0", default-features = false } +sp-core = { version = "3.0.0", default-features = false } +sp-io = { version = "3.0.0", default-features = false } +sp-runtime = { version = "3.0.0", default-features = false } +sp-runtime-interface = { version = "3.0.0", default-features = false } +sp-consensus-babe = { version = "0.9.0", default-features = false } +sp-offchain = { version = "3.0.0", default-features = false } +sp-api = { version = "3.0.0", default-features = false } +sp-inherents = { version = "3.0.0", default-features = false } +sp-block-builder = { version = "3.0.0", default-features = false } +sp-transaction-pool = { version = "3.0.0", default-features = false } +sp-std = { version = "3.0.0", default-features = false } +sp-version = { version = "3.0.0", default-features = false } +sp-session = { version = "3.0.0", default-features = false } # frame dependencies -pallet-contract-operator = { path = "../../../frame/operator", default-features = false } -pallet-operator-trading = { path = "../../../frame/trading", default-features = false } -pallet-dapps-staking = { path = "../../../frame/dapps-staking", default-features = false } +#pallet-contract-operator = { path = "../../../frame/operator", default-features = false } +#pallet-operator-trading = { path = "../../../frame/trading", default-features = false } +#pallet-dapps-staking = { path = "../../../frame/dapps-staking", default-features = false } pallet-plasm-rewards = { path = "../../../frame/plasm-rewards", default-features = false } pallet-plasm-validator = { path = "../../../frame/plasm-validator", default-features = false } -pallet-plasm-lockdrop = { path = "../../../frame/plasm-lockdrop", default-features = false } pallet-custom-signatures = { path = "../../../frame/custom-signatures", default-features = false } -pallet-ovm = { path = "../../../frame/ovm", default-features = false } -pallet-plasma = { path = "../../../frame/plasma", default-features = false } +#pallet-ovm = { path = "../../../frame/ovm", default-features = false } +#pallet-plasma = { path = "../../../frame/plasma", default-features = false } pallet-evm = { path = "../../../vendor/frontier/frame/evm", default-features = false } -frame-executive = { version = "2.0.0", default-features = false } -pallet-authorship = { version = "2.0.0", default-features = false } -pallet-babe = { version = "2.0.0", default-features = false } -pallet-balances = { version = "2.0.0", default-features = false } -pallet-contracts = { version = "2.0.0", default-features = false } -pallet-contracts-primitives = { version = "2.0.0", default-features = false } -pallet-contracts-rpc-runtime-api = { version = "0.8.0", default-features = false } -pallet-finality-tracker = { version = "2.0.0", default-features = false } -pallet-grandpa = { version = "2.0.0", default-features = false } -pallet-indices = { version = "2.0.0", default-features = false } -pallet-nicks = { version = "2.0.0", default-features = false } -pallet-randomness-collective-flip = { version = "2.0.0", default-features = false } -pallet-scheduler = { version = "2.0.0", default-features = false } -pallet-session = { version = "2.0.0", default-features = false, features = ["historical"] } -pallet-sudo = { version = "2.0.0", default-features = false } -frame-support = { version = "2.0.0", default-features = false } -frame-system = { version = "2.0.0", default-features = false } -frame-system-rpc-runtime-api = { version = "2.0.0", default-features = false } -pallet-timestamp = { version = "2.0.0", default-features = false } -pallet-transaction-payment = { version = "2.0.0", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { version = "2.0.0", default-features = false } -pallet-utility = { version = "2.0.0", default-features = false } -frontier-rpc-primitives = { path = "../../../vendor/frontier/rpc/primitives", default-features = false } +pallet-evm-precompile-simple = { path = "../../../vendor/frontier/frame/evm/precompile/simple", default-features = false } +frame-executive = { version = "3.0.0", default-features = false } +pallet-authorship = { version = "3.0.0", default-features = false } +pallet-babe = { version = "3.0.0", default-features = false } +pallet-balances = { version = "3.0.0", default-features = false } +pallet-contracts = { version = "3.0.0", default-features = false } +pallet-contracts-primitives = { version = "3.0.0", default-features = false } +pallet-contracts-rpc-runtime-api = { version = "3.0.0", default-features = false } +pallet-grandpa = { version = "3.0.0", default-features = false } +pallet-indices = { version = "3.0.0", default-features = false } +pallet-im-online = { version = "3.0.0", default-features = false } +pallet-nicks = { version = "3.0.0", default-features = false } +pallet-randomness-collective-flip = { version = "3.0.0", default-features = false } +pallet-scheduler = { version = "3.0.0", default-features = false } +pallet-session = { version = "3.0.0", default-features = false, features = ["historical"] } +pallet-sudo = { version = "3.0.0", default-features = false } +pallet-offences = { version = "3.0.0", default-features = false } +frame-support = { version = "3.0.0", default-features = false } +frame-system = { version = "3.0.0", default-features = false } +frame-system-rpc-runtime-api = { version = "3.0.0", default-features = false } +pallet-timestamp = { version = "3.0.0", default-features = false } +pallet-transaction-payment = { version = "3.0.0", default-features = false } +pallet-transaction-payment-rpc-runtime-api = { version = "3.0.0", default-features = false } +pallet-utility = { version = "3.0.0", default-features = false } +fp-rpc = { path = "../../../vendor/frontier/primitives/rpc", default-features = false } pallet-ethereum = { path = "../../../vendor/frontier/frame/ethereum", default-features = false } [build-dependencies] @@ -74,24 +75,25 @@ std = [ "codec/std", "lazy_static", "hex-literal", - "sp-std/std", "sp-api/std", + "sp-block-builder/std", "sp-core/std", "sp-io/std", "sp-consensus-babe/std", "sp-runtime/std", "sp-runtime-interface/std", "sp-session/std", + "sp-std/std", "sp-version/std", - "sp-block-builder/std", "sp-transaction-pool/std", "sp-inherents/std", + "sp-offchain/std", "plasm-primitives/std", "frame-support/std", "frame-executive/std", "frame-system/std", "frame-system-rpc-runtime-api/std", - "frontier-rpc-primitives/std", + "fp-rpc/std", "pallet-authorship/std", "pallet-babe/std", "pallet-balances/std", @@ -99,27 +101,27 @@ std = [ "pallet-contracts-primitives/std", "pallet-contracts-rpc-runtime-api/std", "pallet-evm/std", - "pallet-finality-tracker/std", + "pallet-evm-precompile-simple/std", "pallet-grandpa/std", "pallet-indices/std", + "pallet-im-online/std", "pallet-nicks/std", - "sp-offchain/std", "pallet-custom-signatures/std", "pallet-plasm-rewards/std", "pallet-plasm-validator/std", - "pallet-plasm-lockdrop/std", - "pallet-plasma/std", +# "pallet-plasma/std", "pallet-randomness-collective-flip/std", "pallet-scheduler/std", "pallet-session/std", - "pallet-contract-operator/std", - "pallet-operator-trading/std", - "pallet-dapps-staking/std", +# "pallet-contract-operator/std", +# "pallet-operator-trading/std", +# "pallet-dapps-staking/std", "pallet-ethereum/std", "pallet-sudo/std", "pallet-timestamp/std", "pallet-transaction-payment/std", "pallet-transaction-payment-rpc-runtime-api/std", "pallet-utility/std", - "pallet-ovm/std", + "pallet-offences/std", +# "pallet-ovm/std", ] diff --git a/bin/node/runtime/src/constants.rs b/bin/node/runtime/src/constants.rs index 96ba98f8be..4284c12eea 100644 --- a/bin/node/runtime/src/constants.rs +++ b/bin/node/runtime/src/constants.rs @@ -6,6 +6,10 @@ pub mod currency { pub const MILLIPLM: Balance = 1_000_000_000_000; pub const PLM: Balance = 1_000 * MILLIPLM; + pub const fn deposit(items: u32, bytes: u32) -> Balance { + items as Balance * 150 * MILLIPLM + (bytes as Balance) * 60 * MILLIPLM + } + #[cfg(feature = "std")] use hex_literal::hex; @@ -319,6 +323,10 @@ pub mod time { pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4); pub const EPOCH_DURATION_IN_BLOCKS: BlockNumber = 4 * HOURS; + pub const EPOCH_DURATION_IN_SLOTS: u64 = { + const SLOT_FILL_RATE: f64 = MILLISECS_PER_BLOCK as f64 / SLOT_DURATION as f64; + (EPOCH_DURATION_IN_BLOCKS as f64 * SLOT_FILL_RATE) as u64 + }; // These time units are defined in number of blocks. pub const MINUTES: BlockNumber = 60 / (SECS_PER_BLOCK as BlockNumber); diff --git a/bin/node/runtime/src/legacy.rs b/bin/node/runtime/src/legacy.rs deleted file mode 100644 index 2809d296e8..0000000000 --- a/bin/node/runtime/src/legacy.rs +++ /dev/null @@ -1,103 +0,0 @@ -//! Backward compatibility layer. - -use sp_std::prelude::*; - -/// Interface for accessing the storage from within the runtime. -/// * Removed in substrate >2.0.0-alpha.6 but used in Plasm Mainnet genesis. -#[sp_runtime_interface::runtime_interface] -pub trait Storage { - /// Read child key. - fn child_get( - &self, - storage_key: &[u8], - _child_definition: &[u8], - _child_type: u32, - key: &[u8], - ) -> Option> { - sp_io::default_child_storage::get(storage_key, key) - } - - /// Read child key. - fn child_read( - &self, - storage_key: &[u8], - _child_definition: &[u8], - _child_type: u32, - key: &[u8], - value_out: &mut [u8], - value_offset: u32, - ) -> Option { - sp_io::default_child_storage::read(storage_key, key, value_out, value_offset) - } - - /// Set a child storage value. - fn child_set( - &mut self, - storage_key: &[u8], - _child_definition: &[u8], - _child_type: u32, - key: &[u8], - value: &[u8], - ) { - sp_io::default_child_storage::set(storage_key, key, value) - } - - /// Remove child key value. - fn child_clear( - &mut self, - storage_key: &[u8], - _child_definition: &[u8], - _child_type: u32, - key: &[u8], - ) { - sp_io::default_child_storage::clear(storage_key, key) - } - - /// Remove all child storage values. - fn child_storage_kill( - &mut self, - storage_key: &[u8], - _child_definition: &[u8], - _child_type: u32, - ) { - sp_io::default_child_storage::storage_kill(storage_key) - } - - /// Check a child storage key. - fn child_exists( - &self, - storage_key: &[u8], - _child_definition: &[u8], - _child_type: u32, - key: &[u8], - ) -> bool { - sp_io::default_child_storage::exists(storage_key, key) - } - - /// Clear child key by prefix. - fn child_clear_prefix( - &mut self, - storage_key: &[u8], - _child_definition: &[u8], - _child_type: u32, - prefix: &[u8], - ) { - sp_io::default_child_storage::clear_prefix(storage_key, prefix) - } - - /// Child trie root calcualation. - fn child_root(&mut self, storage_key: &[u8]) -> Vec { - sp_io::default_child_storage::root(storage_key) - } - - /// Child storage key iteration. - fn child_next_key( - &mut self, - storage_key: &[u8], - _child_definition: &[u8], - _child_type: u32, - key: &[u8], - ) -> Option> { - sp_io::default_child_storage::next_key(storage_key, key) - } -} diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index a9e11f3f89..9ba3f1fa4f 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -7,55 +7,53 @@ use codec::{Decode, Encode}; use frame_support::{ construct_runtime, debug, parameter_types, - traits::{FindAuthor, Get, KeyOwnerProofSystem, Randomness}, + traits::{FindAuthor, KeyOwnerProofSystem, Randomness}, weights::{ constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND}, - IdentityFee, Weight, + DispatchClass, IdentityFee, Weight, }, }; -use frontier_rpc_primitives::TransactionStatus; -use pallet_contracts_rpc_runtime_api::ContractExecResult; +use frame_system::limits::{BlockLength, BlockWeights}; +use pallet_contracts::weights::WeightInfo; use pallet_evm::{ Account as EVMAccount, EnsureAddressRoot, EnsureAddressTruncated, FeeCalculator, HashedAddressMapping, Runner, }; use pallet_grandpa::fg_primitives; use pallet_grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList}; +use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use pallet_session::historical as pallet_session_historical; -use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment}; -use pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo; +use pallet_transaction_payment::{ + CurrencyAdapter, FeeDetails, Multiplier, RuntimeDispatchInfo, TargetedFeeAdjustment, +}; use plasm_primitives::{ AccountId, AccountIndex, Balance, BlockNumber, Hash, Index, Moment, Signature, }; use sp_api::impl_runtime_apis; -use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; -use sp_core::{H160, H256, U256}; +use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H160, H256, U256}; use sp_inherents::{CheckInherentsResult, InherentData}; use sp_runtime::traits::{ - BlakeTwo256, Block as BlockT, ConvertInto, Extrinsic, Keccak256, NumberFor, OpaqueKeys, - SaturatedConversion, Saturating, StaticLookup, Verify, + BlakeTwo256, Block as BlockT, ConvertInto, Extrinsic, NumberFor, OpaqueKeys, + SaturatedConversion, StaticLookup, Verify, }; use sp_runtime::transaction_validity::{ TransactionPriority, TransactionSource, TransactionValidity, }; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, ApplyExtrinsicResult, FixedPointNumber, - MultiSigner, Perbill, Perquintill, RuntimeAppPublic, + create_runtime_str, generic, impl_opaque_keys, ApplyExtrinsicResult, FixedPointNumber, Perbill, + Perquintill, RuntimeAppPublic, }; +use sp_std::convert::TryFrom; use sp_std::prelude::*; #[cfg(any(feature = "std", test))] use sp_version::NativeVersion; use sp_version::RuntimeVersion; pub use pallet_balances::Call as BalancesCall; -pub use pallet_contracts::Gas; pub use pallet_timestamp::Call as TimestampCall; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; -/// Deprecated but used runtime interfaces. -pub mod legacy; - /// Constant values used within the runtime. pub mod constants; use constants::{currency::*, time::*}; @@ -73,8 +71,8 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // and set impl_version to equal spec_version. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. - spec_version: 9, - impl_version: 9, + spec_version: 10, + impl_version: 10, apis: RUNTIME_API_VERSIONS, transaction_version: 2, }; @@ -88,20 +86,46 @@ pub fn native_version() -> NativeVersion { } } +/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers. +/// This is used to limit the maximal weight of a single extrinsic. +const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10); +/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used +/// by Operational extrinsics. +const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); +/// We allow for 2 seconds of compute with a 6 second average block time. +const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND; + parameter_types! { pub const BlockHashCount: BlockNumber = 2400; - /// We allow for 3 seconds of compute with a 10 second average block time. - pub const MaximumBlockWeight: Weight = 3 * WEIGHT_PER_SECOND; - pub const MaximumBlockLength: u32 = 5 * 1024 * 1024; - pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); - /// Assume 10% of weight for average on_initialize calls - pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get() - .saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get(); pub const Version: RuntimeVersion = VERSION; + pub RuntimeBlockLength: BlockLength = + BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); + pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() + .base_block(BlockExecutionWeight::get()) + .for_class(DispatchClass::all(), |weights| { + weights.base_extrinsic = ExtrinsicBaseWeight::get(); + }) + .for_class(DispatchClass::Normal, |weights| { + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + .for_class(DispatchClass::Operational, |weights| { + weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); + // Operational transactions have some extra reserved space, so that they + // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. + weights.reserved = Some( + MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT + ); + }) + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic(); + pub const SS58Prefix: u8 = 5; } -impl frame_system::Trait for Runtime { +impl frame_system::Config for Runtime { type BaseCallFilter = (); + type BlockWeights = RuntimeBlockWeights; + type BlockLength = RuntimeBlockLength; + type DbWeight = RocksDbWeight; type Origin = Origin; type Call = Call; type Index = Index; @@ -112,28 +136,24 @@ impl frame_system::Trait for Runtime { type Lookup = Indices; type Header = generic::Header; type Event = Event; - type DbWeight = RocksDbWeight; type BlockHashCount = BlockHashCount; - type BlockExecutionWeight = BlockExecutionWeight; - type ExtrinsicBaseWeight = ExtrinsicBaseWeight; - type MaximumExtrinsicWeight = MaximumExtrinsicWeight; - type MaximumBlockWeight = MaximumBlockWeight; - type MaximumBlockLength = MaximumBlockLength; - type AvailableBlockRatio = AvailableBlockRatio; type Version = Version; type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); - type SystemWeightInfo = (); + type SystemWeightInfo = frame_system::weights::SubstrateWeight; + type SS58Prefix = SS58Prefix; } parameter_types! { pub const EpochDuration: u64 = EPOCH_DURATION_IN_BLOCKS as u64; pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK; + pub const ReportLongevity: u64 = + BondingDuration::get() as u64 * SessionsPerEra::get() as u64 * EpochDuration::get(); } -impl pallet_babe::Trait for Runtime { +impl pallet_babe::Config for Runtime { type EpochDuration = EpochDuration; type ExpectedBlockTime = ExpectedBlockTime; type EpochChangeTrigger = pallet_babe::ExternalTrigger; @@ -150,7 +170,8 @@ impl pallet_babe::Trait for Runtime { pallet_babe::AuthorityId, )>>::IdentificationTuple; - type HandleEquivocation = pallet_babe::EquivocationHandler; + type HandleEquivocation = + pallet_babe::EquivocationHandler; type WeightInfo = (); } @@ -159,7 +180,7 @@ parameter_types! { pub const IndexDeposit: Balance = 1 * PLM; } -impl pallet_indices::Trait for Runtime { +impl pallet_indices::Config for Runtime { type AccountIndex = AccountIndex; type Event = Event; type Currency = Balances; @@ -172,7 +193,7 @@ parameter_types! { pub const MaxLocks: u32 = 50; } -impl pallet_balances::Trait for Runtime { +impl pallet_balances::Config for Runtime { type Balance = Balance; type DustRemoval = (); type Event = Event; @@ -189,9 +210,8 @@ parameter_types! { pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 1_000_000_000u128); } -impl pallet_transaction_payment::Trait for Runtime { - type Currency = Balances; - type OnTransactionPayment = (); +impl pallet_transaction_payment::Config for Runtime { + type OnChargeTransaction = CurrencyAdapter; type TransactionByteFee = TransactionByteFee; type WeightToFee = IdentityFee; type FeeMultiplierUpdate = @@ -202,7 +222,7 @@ parameter_types! { pub const MinimumPeriod: Moment = SLOT_DURATION / 2; } -impl pallet_timestamp::Trait for Runtime { +impl pallet_timestamp::Config for Runtime { type Moment = Moment; type OnTimestampSet = Babe; type MinimumPeriod = MinimumPeriod; @@ -213,44 +233,50 @@ parameter_types! { pub const UncleGenerations: BlockNumber = 5; } -impl pallet_authorship::Trait for Runtime { +impl pallet_authorship::Config for Runtime { type FindAuthor = pallet_session::FindAccountFromAuthorIndex; type UncleGenerations = UncleGenerations; type FilterUncle = (); - type EventHandler = (); + type EventHandler = ImOnline; } impl_opaque_keys! { pub struct SessionKeys { pub babe: Babe, pub grandpa: Grandpa, + pub im_online: ImOnline, } } -impl pallet_session::Trait for Runtime { +parameter_types! { + pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17); +} + +impl pallet_session::Config for Runtime { type SessionManager = PlasmRewards; type SessionHandler = ::KeyTypeIdProviders; type ShouldEndSession = Babe; type NextSessionRotation = Babe; type Event = Event; type Keys = SessionKeys; - type ValidatorId = ::AccountId; + type ValidatorId = ::AccountId; type ValidatorIdOf = ConvertInto; - type DisabledValidatorsThreshold = (); + type DisabledValidatorsThreshold = DisabledValidatorsThreshold; type WeightInfo = (); } -impl pallet_session::historical::Trait for Runtime { +impl pallet_session::historical::Config for Runtime { type FullIdentification = (); type FullIdentificationOf = (); } parameter_types! { - pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * MaximumBlockWeight::get(); + pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * + RuntimeBlockWeights::get().max_block; pub const MaxScheduledPerBlock: u32 = 50; } -impl pallet_scheduler::Trait for Runtime { +impl pallet_scheduler::Config for Runtime { type Event = Event; type Origin = Origin; type PalletsOrigin = OriginCaller; @@ -266,7 +292,7 @@ parameter_types! { pub const BondingDuration: pallet_plasm_rewards::EraIndex = 24 * 28; } -impl pallet_plasm_rewards::Trait for Runtime { +impl pallet_plasm_rewards::Config for Runtime { type Currency = Balances; type Time = Timestamp; type SessionsPerEra = SessionsPerEra; @@ -278,7 +304,7 @@ impl pallet_plasm_rewards::Trait for Runtime { type Event = Event; } -impl pallet_plasm_validator::Trait for Runtime { +impl pallet_plasm_validator::Config for Runtime { type Currency = Balances; type Time = Timestamp; type RewardRemainder = (); // Reward remainder is burned. @@ -290,7 +316,8 @@ impl pallet_plasm_validator::Trait for Runtime { type Event = Event; } -impl pallet_dapps_staking::Trait for Runtime { +/* +impl pallet_dapps_staking::Config for Runtime { type Currency = Balances; type BondingDuration = BondingDuration; type ContractFinder = Operator; @@ -303,57 +330,109 @@ impl pallet_dapps_staking::Trait for Runtime { type HistoryDepthFinder = PlasmRewards; type Event = Event; } +*/ parameter_types! { - pub const TombstoneDeposit: Balance = 1 * PLM; - pub const RentByteFee: Balance = 1 * PLM; - pub const RentDepositOffset: Balance = 1000 * PLM; - pub const SurchargeReward: Balance = 150 * PLM; + pub const TombstoneDeposit: Balance = deposit( + 1, + sp_std::mem::size_of::>() as u32 + ); + pub const DepositPerContract: Balance = TombstoneDeposit::get(); + pub const DepositPerStorageByte: Balance = deposit(0, 1); + pub const DepositPerStorageItem: Balance = deposit(1, 0); + pub RentFraction: Perbill = Perbill::from_rational_approximation(1u32, 30 * DAYS); + pub const SurchargeReward: Balance = 150 * MILLIPLM; + pub const SignedClaimHandicap: u32 = 2; + pub const MaxDepth: u32 = 32; + pub const MaxValueSize: u32 = 16 * 1024; + // The lazy deletion runs inside on_initialize. + pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO * + RuntimeBlockWeights::get().max_block; + // The weight needed for decoding the queue should be less or equal than a fifth + // of the overall weight dedicated to the lazy deletion. + pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / ( + ::WeightInfo::on_initialize_per_queue_item(1) - + ::WeightInfo::on_initialize_per_queue_item(0) + )) / 5) as u32; + pub MaxCodeSize: u32 = 128 * 1024; } -impl pallet_contracts::Trait for Runtime { +impl pallet_contracts::Config for Runtime { type Time = Timestamp; type Randomness = RandomnessCollectiveFlip; type Currency = Balances; type Event = Event; - type DetermineContractAddress = pallet_contracts::SimpleAddressDeterminer; - type TrieIdGenerator = pallet_contracts::TrieIdFromParentCounter; type RentPayment = (); - type SignedClaimHandicap = pallet_contracts::DefaultSignedClaimHandicap; + type SignedClaimHandicap = SignedClaimHandicap; type TombstoneDeposit = TombstoneDeposit; - type StorageSizeOffset = pallet_contracts::DefaultStorageSizeOffset; - type RentByteFee = RentByteFee; - type RentDepositOffset = RentDepositOffset; + type DepositPerContract = DepositPerContract; + type DepositPerStorageByte = DepositPerStorageByte; + type DepositPerStorageItem = DepositPerStorageItem; + type RentFraction = RentFraction; type SurchargeReward = SurchargeReward; - type MaxDepth = pallet_contracts::DefaultMaxDepth; - type MaxValueSize = pallet_contracts::DefaultMaxValueSize; + type MaxDepth = MaxDepth; + type MaxValueSize = MaxValueSize; type WeightPrice = pallet_transaction_payment::Module; + type WeightInfo = pallet_contracts::weights::SubstrateWeight; + type ChainExtension = (); + type DeletionQueueDepth = DeletionQueueDepth; + type DeletionWeightLimit = DeletionWeightLimit; + type MaxCodeSize = MaxCodeSize; } -impl pallet_contract_operator::Trait for Runtime { +/* +impl pallet_contract_operator::Config for Runtime { type Parameters = pallet_dapps_staking::parameters::StakingParameters; type Event = Event; } -impl pallet_operator_trading::Trait for Runtime { +impl pallet_operator_trading::Config for Runtime { type Currency = Balances; type OperatorFinder = Operator; type TransferOperator = Operator; type Event = Event; } +*/ -impl pallet_utility::Trait for Runtime { +impl pallet_utility::Config for Runtime { type Event = Event; type Call = Call; type WeightInfo = (); } -impl pallet_sudo::Trait for Runtime { +impl pallet_sudo::Config for Runtime { type Event = Event; type Call = Call; } -impl pallet_grandpa::Trait for Runtime { +parameter_types! { + pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_SLOTS as _; + pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value(); +} + +impl pallet_im_online::Config for Runtime { + type AuthorityId = ImOnlineId; + type Event = Event; + type ValidatorSet = Historical; + type SessionDuration = SessionDuration; + type ReportUnresponsiveness = Offences; + type UnsignedPriority = ImOnlineUnsignedPriority; + type WeightInfo = pallet_im_online::weights::SubstrateWeight; +} + +parameter_types! { + pub OffencesWeightSoftLimit: Weight = Perbill::from_percent(60) * + RuntimeBlockWeights::get().max_block; +} + +impl pallet_offences::Config for Runtime { + type Event = Event; + type IdentificationTuple = pallet_session::historical::IdentificationTuple; + type OnOffenceHandler = (); + type WeightSoftLimit = OffencesWeightSoftLimit; +} + +impl pallet_grandpa::Config for Runtime { type Event = Event; type Call = Call; @@ -367,47 +446,20 @@ impl pallet_grandpa::Trait for Runtime { GrandpaId, )>>::IdentificationTuple; - type HandleEquivocation = pallet_grandpa::EquivocationHandler; + type HandleEquivocation = pallet_grandpa::EquivocationHandler< + Self::KeyOwnerIdentification, + Offences, + ReportLongevity, + >; type WeightInfo = (); } -parameter_types! { - pub const WindowSize: BlockNumber = 101; - pub const ReportLatency: BlockNumber = 1000; -} - -impl pallet_finality_tracker::Trait for Runtime { - type OnFinalizationStalled = Grandpa; - type WindowSize = WindowSize; - type ReportLatency = ReportLatency; -} - -parameter_types! { - pub const MedianFilterExpire: Moment = 30000; // ms - pub const LockdropUnsignedPriority: TransactionPriority = TransactionPriority::max_value(); -} - -impl pallet_plasm_lockdrop::Trait for Runtime { - type Currency = Balances; - type DurationBonus = pallet_plasm_lockdrop::DustyDurationBonus; - type MedianFilterExpire = MedianFilterExpire; - type MedianFilterWidth = pallet_plasm_lockdrop::typenum::U5; - type AuthorityId = pallet_plasm_lockdrop::sr25519::AuthorityId; - type Account = MultiSigner; - type Time = Timestamp; - type Moment = Moment; - type DollarRate = Balance; - type BalanceConvert = Balance; - type Event = Event; - type UnsignedPriority = LockdropUnsignedPriority; -} - parameter_types! { pub const EcdsaUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2; } -impl pallet_custom_signatures::Trait for Runtime { +impl pallet_custom_signatures::Config for Runtime { type Event = Event; type Call = Call; type Signature = pallet_custom_signatures::ethereum::EthereumSignature; @@ -470,6 +522,7 @@ where type Extrinsic = UncheckedExtrinsic; } +/* parameter_types! { pub const MaxDepth: u32 = 32; pub const DisputePeriod: BlockNumber = 7; @@ -500,7 +553,7 @@ impl Get> for GetAtomicPred } } -impl pallet_ovm::Trait for Runtime { +impl pallet_ovm::Config for Runtime { type MaxDepth = MaxDepth; type DisputePeriod = DisputePeriod; type DeterminePredicateAddress = pallet_ovm::SimpleAddressDeterminer; @@ -517,13 +570,14 @@ impl Get for MaximumTokenAddress { } } -impl pallet_plasma::Trait for Runtime { +impl pallet_plasma::Config for Runtime { type Currency = Balances; type DeterminePlappsAddress = pallet_plasma::SimpleAddressDeterminer; type MaximumTokenAddress = MaximumTokenAddress; type PlasmaHashing = Keccak256; type Event = Event; } +*/ parameter_types! { pub const NickReservationFee: u128 = 0; @@ -531,7 +585,7 @@ parameter_types! { pub const MaxNickLength: usize = 32; } -impl pallet_nicks::Trait for Runtime { +impl pallet_nicks::Config for Runtime { type Event = Event; type Currency = Balances; type ReservationFee = NickReservationFee; @@ -541,11 +595,23 @@ impl pallet_nicks::Trait for Runtime { type MaxLength = MaxNickLength; } -pub struct FixedGasPrice; -impl FeeCalculator for FixedGasPrice { - fn min_gas_price() -> U256 { - // Gas price is always one token per gas. - 1.into() +/// Current approximation of the gas/s consumption considering +/// EVM execution over compiled WASM (on 4.4Ghz CPU). +/// Given the 500ms Weight, from which 75% only are used for transactions, +/// the total EVM execution gas limit is: GAS_PER_SECOND * 0.500 * 0.75 => 6_000_000. +pub const GAS_PER_SECOND: u64 = 16_000_000; + +/// Approximate ratio of the amount of Weight per Gas. +/// u64 works for approximations because Weight is a very small unit compared to gas. +pub const WEIGHT_PER_GAS: u64 = WEIGHT_PER_SECOND / GAS_PER_SECOND; + +pub struct GasWeightMapping; +impl pallet_evm::GasWeightMapping for GasWeightMapping { + fn gas_to_weight(gas: u64) -> Weight { + Weight::try_from(gas.saturating_mul(WEIGHT_PER_GAS)).unwrap_or(Weight::MAX) + } + fn weight_to_gas(weight: Weight) -> u64 { + u64::try_from(weight.wrapping_div(WEIGHT_PER_GAS)).unwrap_or(u64::MAX) } } @@ -553,8 +619,9 @@ parameter_types! { pub const ChainId: u64 = 0x50; } -impl pallet_evm::Trait for Runtime { - type FeeCalculator = FixedGasPrice; +impl pallet_evm::Config for Runtime { + type FeeCalculator = (); + type GasWeightMapping = GasWeightMapping; type CallOrigin = EnsureAddressRoot; type WithdrawOrigin = EnsureAddressTruncated; type AddressMapping = HashedAddressMapping; @@ -562,25 +629,23 @@ impl pallet_evm::Trait for Runtime { type Event = Event; type Runner = pallet_evm::runner::stack::Runner; type Precompiles = ( - pallet_evm::precompiles::ECRecover, - pallet_evm::precompiles::Sha256, - pallet_evm::precompiles::Ripemd160, - pallet_evm::precompiles::Identity, + pallet_evm_precompile_simple::ECRecover, + pallet_evm_precompile_simple::Sha256, + pallet_evm_precompile_simple::Ripemd160, + pallet_evm_precompile_simple::Identity, ); type ChainId = ChainId; } pub struct TransactionConverter; -impl frontier_rpc_primitives::ConvertTransaction for TransactionConverter { +impl fp_rpc::ConvertTransaction for TransactionConverter { fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic { UncheckedExtrinsic::new_unsigned( pallet_ethereum::Call::::transact(transaction).into(), ) } } -impl frontier_rpc_primitives::ConvertTransaction - for TransactionConverter -{ +impl fp_rpc::ConvertTransaction for TransactionConverter { fn convert_transaction( &self, transaction: pallet_ethereum::Transaction, @@ -609,9 +674,15 @@ impl> FindAuthor for EthereumFindAuthor { } } -impl pallet_ethereum::Trait for Runtime { +parameter_types! { + pub BlockGasLimit: U256 = U256::from(9_000_000); +} + +impl pallet_ethereum::Config for Runtime { type Event = Event; type FindAuthor = EthereumFindAuthor; + type StateRoot = pallet_ethereum::IntermediateStateRoot; + type BlockGasLimit = BlockGasLimit; } construct_runtime!( @@ -625,29 +696,29 @@ construct_runtime!( Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, Authorship: pallet_authorship::{Module, Call, Storage, Inherent}, TransactionPayment: pallet_transaction_payment::{Module, Storage}, + Scheduler: pallet_scheduler::{Module, Call, Storage, Event}, Indices: pallet_indices::{Module, Call, Storage, Event, Config}, Balances: pallet_balances::{Module, Call, Storage, Event, Config}, - Contracts: pallet_contracts::{Module, Call, Storage, Event, Config}, - DappsStaking: pallet_dapps_staking::{Module, Call, Storage, Event}, - PlasmLockdrop: pallet_plasm_lockdrop::{Module, Call, Storage, Event, Config, ValidateUnsigned}, + Contracts: pallet_contracts::{Module, Call, Storage, Event, Config}, + //DappsStaking: pallet_dapps_staking::{Module, Call, Storage, Event}, PlasmValidator: pallet_plasm_validator::{Module, Call, Storage, Event, Config}, PlasmRewards: pallet_plasm_rewards::{Module, Call, Storage, Event, Config}, Session: pallet_session::{Module, Call, Storage, Event, Config}, Historical: pallet_session_historical::{Module}, Babe: pallet_babe::{Module, Call, Storage, Config, Inherent, ValidateUnsigned}, Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event, ValidateUnsigned}, - FinalityTracker: pallet_finality_tracker::{Module, Call, Inherent}, - Operator: pallet_contract_operator::{Module, Call, Storage, Event}, - Trading: pallet_operator_trading::{Module, Call, Storage, Event}, + ImOnline: pallet_im_online::{Module, Call, Storage, Event, ValidateUnsigned, Config}, + Offences: pallet_offences::{Module, Call, Storage, Event}, + //Operator: pallet_contract_operator::{Module, Call, Storage, Event}, + //Trading: pallet_operator_trading::{Module, Call, Storage, Event}, RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage}, Sudo: pallet_sudo::{Module, Call, Storage, Event, Config}, - OVM: pallet_ovm::{Module, Call, Storage, Event}, - Plasma: pallet_plasma::{Module, Call, Storage, Event}, + //OVM: pallet_ovm::{Module, Call, Storage, Event}, + //Plasma: pallet_plasma::{Module, Call, Storage, Event}, Nicks: pallet_nicks::{Module, Call, Storage, Event}, Ethereum: pallet_ethereum::{Module, Call, Storage, Event, Config, ValidateUnsigned}, EVM: pallet_evm::{Module, Call, Storage, Config, Event}, EthCall: pallet_custom_signatures::{Module, Call, Event, ValidateUnsigned}, - Scheduler: pallet_scheduler::{Module, Call, Storage, Event}, } ); @@ -793,12 +864,20 @@ impl_runtime_apis! { } } - fn current_epoch_start() -> sp_consensus_babe::SlotNumber { + fn current_epoch_start() -> sp_consensus_babe::Slot { Babe::current_epoch_start() } + fn current_epoch() -> sp_consensus_babe::Epoch { + Babe::current_epoch() + } + + fn next_epoch() -> sp_consensus_babe::Epoch { + Babe::next_epoch() + } + fn generate_key_ownership_proof( - _slot_number: sp_consensus_babe::SlotNumber, + _slot_number: sp_consensus_babe::Slot, authority_id: sp_consensus_babe::AuthorityId, ) -> Option { use codec::Encode; @@ -834,17 +913,8 @@ impl_runtime_apis! { value: Balance, gas_limit: u64, input_data: Vec, - ) -> ContractExecResult { - let (exec_result, gas_consumed) = - Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data); - match exec_result { - Ok(v) => ContractExecResult::Success { - flags: v.flags.bits(), - data: v.data, - gas_consumed: gas_consumed, - }, - Err(_) => ContractExecResult::Error, - } + ) -> pallet_contracts_primitives::ContractExecResult { + Contracts::bare_call(origin, dest, value, gas_limit, input_data) } fn get_storage( @@ -868,6 +938,9 @@ impl_runtime_apis! { fn query_info(uxt: ::Extrinsic, len: u32) -> RuntimeDispatchInfo { TransactionPayment::query_info(uxt, len) } + fn query_fee_details(uxt: ::Extrinsic, len: u32) -> FeeDetails { + TransactionPayment::query_fee_details(uxt, len) + } } impl sp_session::SessionKeys for Runtime { @@ -882,9 +955,9 @@ impl_runtime_apis! { } } - impl frontier_rpc_primitives::EthereumRuntimeRPCApi for Runtime { + impl fp_rpc::EthereumRuntimeRPCApi for Runtime { fn chain_id() -> u64 { - ::ChainId::get() + ::ChainId::get() } fn account_basic(address: H160) -> EVMAccount { @@ -892,7 +965,7 @@ impl_runtime_apis! { } fn gas_price() -> U256 { - ::FeeCalculator::min_gas_price() + ::FeeCalculator::min_gas_price() } fn account_code_at(address: H160) -> Vec { @@ -909,7 +982,7 @@ impl_runtime_apis! { EVM::account_storages(address, H256::from_slice(&tmp[..])) } - fn current_transaction_statuses() -> Option> { + fn current_transaction_statuses() -> Option> { Ethereum::current_transaction_statuses() } @@ -924,7 +997,7 @@ impl_runtime_apis! { fn current_all() -> ( Option, Option>, - Option> + Option> ) { ( Ethereum::current_block(), @@ -941,15 +1014,26 @@ impl_runtime_apis! { gas_limit: U256, gas_price: Option, nonce: Option, + estimate: bool, ) -> Result { - ::Runner::call( + let config = if estimate { + let mut config = ::config().clone(); + config.estimate = true; + Some(config) + } else { + None + }; + + #[allow(clippy::or_fun_call)] // suggestion not helpful here + ::Runner::call( from, to, data, value, - gas_limit.low_u32(), + gas_limit.low_u64(), gas_price, nonce, + config.as_ref().unwrap_or(::config()), ).map_err(|err| err.into()) } @@ -960,14 +1044,25 @@ impl_runtime_apis! { gas_limit: U256, gas_price: Option, nonce: Option, + estimate: bool, ) -> Result { - ::Runner::create( + let config = if estimate { + let mut config = ::config().clone(); + config.estimate = true; + Some(config) + } else { + None + }; + + #[allow(clippy::or_fun_call)] // suggestion not helpful here + ::Runner::create( from, data, value, - gas_limit.low_u32(), + gas_limit.low_u64(), gas_price, nonce, + config.as_ref().unwrap_or(::config()), ).map_err(|err| err.into()) } } diff --git a/bin/node/src/main.rs b/bin/node/src/main.rs new file mode 100644 index 0000000000..9e4a0ad79a --- /dev/null +++ b/bin/node/src/main.rs @@ -0,0 +1,7 @@ +//! Plasm Node executable. + +#![warn(missing_docs)] + +fn main() -> Result<(), plasm_cli::Error> { + plasm_cli::run() +} diff --git a/frame/custom-signatures/Cargo.toml b/frame/custom-signatures/Cargo.toml index f461ebd6c4..fb40fcaa5f 100644 --- a/frame/custom-signatures/Cargo.toml +++ b/frame/custom-signatures/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-custom-signatures" -version = "1.7.0" +version = "1.8.0" authors = ["Stake Technologies "] edition = "2018" license = "Apache-2.0" @@ -9,21 +9,21 @@ repository = "https://github.com/staketechnologies/Plasm/" description = "FRAME pallet for user defined extrinsic signatures" [dependencies] -codec = { package = "parity-scale-codec", version = "1.3.5", features = ["derive"], default-features = false } +codec = { package = "parity-scale-codec", version = "2.0", features = ["derive"], default-features = false } serde = { version = "1.0.106", features = ["derive"], optional = true } -sp-io = { version = "2.0.0", default_features = false } -sp-std = { version = "2.0.0", default_features = false } -sp-core = { version = "2.0.0", default_features = false } -sp-runtime = { version = "2.0.0", default_features = false } -frame-support = { version = "2.0.0", default_features = false } -frame-system = { version = "2.0.0", default_features = false } +sp-io = { version = "3.0.0", default_features = false } +sp-std = { version = "3.0.0", default_features = false } +sp-core = { version = "3.0.0", default_features = false } +sp-runtime = { version = "3.0.0", default_features = false } +frame-support = { version = "3.0.0", default_features = false } +frame-system = { version = "3.0.0", default_features = false } [dev-dependencies] -pallet-balances = "2.0.0" +pallet-balances = "3.0.0" libsecp256k1 = "0.3.2" hex-literal = "0.2.1" -sp-keyring = "2.0.0" -sp-core = "2.0.0" +sp-keyring = "3.0.0" +sp-core = "3.0.0" [features] default = ["std"] diff --git a/frame/custom-signatures/src/lib.rs b/frame/custom-signatures/src/lib.rs index 956c8c2bf4..326f77a6dd 100644 --- a/frame/custom-signatures/src/lib.rs +++ b/frame/custom-signatures/src/lib.rs @@ -24,9 +24,9 @@ use sp_std::prelude::*; pub mod ethereum; /// The module's configuration trait. -pub trait Trait: frame_system::Trait { +pub trait Config: frame_system::Config { /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// A signable call. type Call: Parameter + UnfilteredDispatchable + GetDispatchInfo; @@ -45,7 +45,7 @@ pub trait Trait: frame_system::Trait { } decl_error! { - pub enum Error for Module { + pub enum Error for Module { /// Signature decode fails. DecodeFailure, /// Signature and account mismatched. @@ -56,7 +56,7 @@ decl_error! { decl_event!( pub enum Event where - AccountId = ::AccountId, + AccountId = ::AccountId, { /// A call just executed. \[result\] Executed(AccountId, DispatchResult), @@ -64,7 +64,7 @@ decl_event!( ); decl_module! { - pub struct Module for enum Call where origin: T::Origin { + pub struct Module for enum Call where origin: T::Origin { type Error = Error; fn deposit_event() = default; @@ -72,13 +72,13 @@ decl_module! { #[weight = (call.get_dispatch_info().weight + 10_000, call.get_dispatch_info().class)] fn call( origin, - call: Box<::Call>, + call: Box<::Call>, account: T::AccountId, signature: Vec, ) -> DispatchResultWithPostInfo { ensure_none(origin)?; - let signature = ::Signature::try_from(signature) + let signature = ::Signature::try_from(signature) .map_err(|_| Error::::DecodeFailure)?; if signature.verify(&call.encode()[..], &account) { let new_origin = frame_system::RawOrigin::Signed(account.clone()).into(); @@ -94,7 +94,7 @@ decl_module! { const SIGNATURE_DECODE_FAILURE: u8 = 1; -impl frame_support::unsigned::ValidateUnsigned for Module { +impl frame_support::unsigned::ValidateUnsigned for Module { type Call = Call; fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { @@ -102,7 +102,7 @@ impl frame_support::unsigned::ValidateUnsigned for Module { frame_support::runtime_print!("CALL: {:?}", call.encode()); frame_support::runtime_print!("SIGNATURE: {:?}", signature); - if let Ok(signature) = ::Signature::try_from(signature.clone()) { + if let Ok(signature) = ::Signature::try_from(signature.clone()) { if signature.verify(&call.encode()[..], &signer) { return ValidTransaction::with_tag_prefix("CustomSignatures") .priority(T::UnsignedPriority::get()) @@ -126,10 +126,7 @@ impl frame_support::unsigned::ValidateUnsigned for Module { mod tests { use crate as custom_signatures; use custom_signatures::*; - use frame_support::{ - assert_err, assert_ok, impl_outer_dispatch, impl_outer_event, impl_outer_origin, - parameter_types, - }; + use frame_support::{assert_err, assert_ok, parameter_types}; use hex_literal::hex; use sp_core::{crypto::Ss58Codec, ecdsa, Pair}; use sp_io::hashing::keccak_256; @@ -138,46 +135,36 @@ mod tests { testing::{Header, H256}, traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, transaction_validity::TransactionPriority, - MultiSignature, MultiSigner, Perbill, + MultiSignature, MultiSigner, }; pub const ECDSA_SEED: [u8; 32] = hex_literal::hex!["7e9c7ad85df5cdc88659f53e06fb2eb9bab3ebc59083a3190eaf2c730332529c"]; - #[derive(Clone, PartialEq, Eq, Debug)] - pub struct Runtime; - type Balance = u128; type BlockNumber = u64; type Signature = MultiSignature; type AccountId = <::Signer as IdentifyAccount>::AccountId; - - impl_outer_origin! { - pub enum Origin for Runtime {} - } - - impl_outer_dispatch! { - pub enum Call for Runtime where origin: Origin { - pallet_balances::Balances, + type Block = frame_system::mocking::MockBlock; + type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; + + frame_support::construct_runtime!( + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + Balances: pallet_balances::{Module, Call, Storage, Config, Event}, + System: frame_system::{Module, Call, Config, Storage, Event}, + CustomSignatures: custom_signatures::{Module, Call, Event}, } - } - - impl_outer_event! { - pub enum Event for Runtime { - frame_system, - pallet_balances, - custom_signatures, - } - } + ); parameter_types! { pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: u32 = 1024; - pub const MaximumBlockLength: u32 = 2 * 1024; - pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl frame_system::Trait for Runtime { + impl frame_system::Config for Runtime { type Origin = Origin; type BaseCallFilter = (); type Index = u64; @@ -190,26 +177,23 @@ mod tests { type Header = Header; type Event = Event; type BlockHashCount = BlockHashCount; - type MaximumBlockWeight = MaximumBlockWeight; - type MaximumBlockLength = MaximumBlockLength; - type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletInfo = (); + type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = (); type SystemWeightInfo = (); + type BlockWeights = (); + type BlockLength = (); + type SS58Prefix = (); } parameter_types! { pub const ExistentialDeposit: Balance = 1; } - impl pallet_balances::Trait for Runtime { + impl pallet_balances::Config for Runtime { type Balance = Balance; type Event = Event; type DustRemoval = (); @@ -223,7 +207,7 @@ mod tests { pub const Priority: TransactionPriority = TransactionPriority::max_value(); } - impl Trait for Runtime { + impl Config for Runtime { type Event = Event; type Call = Call; type Signature = ethereum::EthereumSignature; @@ -231,10 +215,6 @@ mod tests { type UnsignedPriority = Priority; } - type System = frame_system::Module; - type Balances = pallet_balances::Module; - type CustomSignatures = custom_signatures::Module; - fn new_test_ext() -> sp_io::TestExternalities { let mut storage = frame_system::GenesisConfig::default() .build_storage::() @@ -270,8 +250,8 @@ mod tests { #[test] fn invalid_signature() { - let bob: ::AccountId = Keyring::Bob.into(); - let alice: ::AccountId = Keyring::Alice.into(); + let bob: ::AccountId = Keyring::Bob.into(); + let alice: ::AccountId = Keyring::Alice.into(); let call = pallet_balances::Call::::transfer(alice.clone(), 1_000).into(); let signature = Vec::from(&hex!["dd0992d40e5cdf99db76bed162808508ac65acd7ae2fdc8573594f03ed9c939773e813181788fc02c3c68f3fdc592759b35f6354484343e18cb5317d34dab6c61b"][..]); assert_err!( @@ -286,7 +266,7 @@ mod tests { let pair = ecdsa::Pair::from_seed(&ECDSA_SEED); let account = MultiSigner::from(pair.public()).into_account(); - let alice: ::AccountId = Keyring::Alice.into(); + let alice: ::AccountId = Keyring::Alice.into(); assert_eq!(System::account(alice.clone()).data.free, 0); let call: Call = diff --git a/frame/dapps-staking/Cargo.toml b/frame/dapps-staking/Cargo.toml deleted file mode 100644 index a460ee49c2..0000000000 --- a/frame/dapps-staking/Cargo.toml +++ /dev/null @@ -1,63 +0,0 @@ -[package] -name = "pallet-dapps-staking" -version = "1.7.0" -authors = ["Stake Technologies "] -edition = "2018" -license = "Apache-2.0" -homepage = "https://docs.plasmnet.io/" -repository = "https://github.com/staketechnologies/Plasm/" -description = "FRAME pallet to staking for dapps" - -[dependencies] -codec = { package = "parity-scale-codec", version = "1.3.5", features = ["derive"], default-features = false } -serde = { version = "1.0.106", features = ["derive"], optional = true } -num-traits = { version = "0.2", default-features = false } - -sp-core = { version = "2.0.0", default_features = false } -sp-runtime = { version = "2.0.0", default_features = false } -sp-arithmetic = { version = "2.0.0", default_features = false } -sp-io = { version = "2.0.0", default_features = false } -sp-std = { version = "2.0.0", default_features = false } -pallet-balances = { version = "2.0.0", default_features = false } -frame-support = { version = "2.0.0", default_features = false } -pallet-session = { version = "2.0.0", default-features = false } -pallet-timestamp = { version = "2.0.0", default_features = false } -frame-system = { version = "2.0.0", default_features = false } -pallet-contracts = { version = "2.0.0", default_features = false } -pallet-staking = { version = "2.0.0", default_features = false } -sp-staking = { version = "2.0.0", default_features = false } - -pallet-contract-operator = { path = "../operator", version = "1.7.0", default_features = false } -pallet-plasm-rewards = { path = "../plasm-rewards", version = "1.7.0", default_features = false } -pallet-plasm-support = { path = "../plasm-support", version = "1.7.0", default_features = false } - -[dev-dependencies] -wabt = "0.10.0" -derive_more = "0.14.0" -hex-literal = "0.2.1" -pallet-randomness-collective-flip = "2.0.0" -pallet-transaction-payment = "2.0.0" - -[features] -default = ["std"] -std = [ - "serde", - "codec/std", - "num-traits/std", - "sp-core/std", - "sp-runtime/std", - "sp-arithmetic/std", - "sp-io/std", - "sp-std/std", - "frame-support/std", - "frame-system/std", - "pallet-balances/std", - "pallet-session/std", - "pallet-timestamp/std", - "pallet-contracts/std", - "pallet-staking/std", - "pallet-contract-operator/std", - "pallet-plasm-rewards/std", - "pallet-plasm-support/std", - "sp-staking/std", -] diff --git a/frame/dapps-staking/src/lib.rs b/frame/dapps-staking/src/lib.rs deleted file mode 100644 index 888aa17dd0..0000000000 --- a/frame/dapps-staking/src/lib.rs +++ /dev/null @@ -1,1207 +0,0 @@ -//! # Plasm Staking Module -//! -//! The Plasm staking module manages era, total amounts of rewards and how to distribute. -#![cfg_attr(not(feature = "std"), no_std)] - -use codec::{Decode, Encode, HasCompact}; -use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, - dispatch::DispatchResult, - ensure, - traits::{ - Currency, Get, Imbalance, LockIdentifier, LockableCurrency, OnUnbalanced, Time, - WithdrawReasons, - }, - weights::Weight, - IterableStorageDoubleMap, StorageMap, StorageValue, -}; -use frame_system::{self as system, ensure_signed}; -use pallet_plasm_rewards::{ - traits::{ComputeEraWithParam, EraFinder, ForDappsEraRewardFinder, HistoryDepthFinder}, - EraIndex, Releases, -}; -use pallet_plasm_support::ContractFinder; -pub use pallet_staking::{Forcing, RewardDestination}; -use sp_runtime::{ - traits::{AtLeast32BitUnsigned, CheckedSub, Saturating, StaticLookup, Zero}, - Perbill, RuntimeDebug, -}; -use sp_std::{collections::btree_map::BTreeMap, prelude::*, result, vec::Vec}; - -mod log; -#[cfg(test)] -mod mock; -pub mod parameters; -pub mod rewards; -#[cfg(test)] -mod tests; - -pub use parameters::StakingParameters; -pub use rewards::ComputeRewardsForDapps; -pub use sp_staking::SessionIndex; - -pub type BalanceOf = - <::Currency as Currency<::AccountId>>::Balance; -pub type MomentOf = <::Time as Time>::Moment; - -type PositiveImbalanceOf = - <::Currency as Currency<::AccountId>>::PositiveImbalance; -type NegativeImbalanceOf = - <::Currency as Currency<::AccountId>>::NegativeImbalance; - -const MAX_NOMINATIONS: usize = 128; -const MAX_UNLOCKING_CHUNKS: usize = 32; -const STAKING_ID: LockIdentifier = *b"dapstake"; -const MAX_VOTES: usize = 128; -const VOTES_REQUIREMENT: u32 = 12; - -/// A record of the nominations made by a specific account. -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] -pub struct Nominations { - /// The targets of nomination and amounts of staking. - pub targets: Vec<(AccountId, Balance)>, - /// The era the nominations were submitted. - /// - /// Except for initial nominations which are considered submitted at era 0. - pub submitted_in: EraIndex, - /// Whether the nominations have been suppressed. - pub suppressed: bool, -} - -/// Reward points of an era. Used to split era total payout between dapps rewards. -/// -/// This points will be used to reward contracts operators and their respective nominators. -#[derive(PartialEq, Encode, Decode, Default, RuntimeDebug)] -pub struct EraStakingPoints { - /// Total number of staking. Equals the sum of staking points for each contracts. - total: Balance, - /// The balance of stakinng earned by a given contracts. - individual: BTreeMap, -} - -/// Just a Balance/BlockNumber tuple to encode when a chunk of funds will be unlocked. -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] -pub struct UnlockChunk { - /// Amount of funds to be unlocked. - #[codec(compact)] - value: Balance, - /// Era number at which point it'll be unlocked. - #[codec(compact)] - era: EraIndex, -} - -/// The ledger of a (bonded) stash. -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] -pub struct StakingLedger { - /// The stash account whose balance is actually locke,ed and at stake. - pub stash: AccountId, - /// The total amount of the stash's balance that we are currently accounting for. - /// It's just `active` plus all the `unlocking` balances. - #[codec(compact)] - pub total: Balance, - /// The total amount of the stash's balance that will be at stake in any forthcoming - /// rounds. - #[codec(compact)] - pub active: Balance, - /// Any balance that is becoming free, which may eventually be transferred out - /// of the stash (assuming it doesn't get slashed first). - pub unlocking: Vec>, - /// The latest and highest era which the staker has claimed reward for. - pub last_reward: Option, -} - -impl - StakingLedger -{ - /// Remove entries from `unlocking` that are sufficiently old and reduce the - /// total by the sum of their balances. - fn consolidate_unlocked(self, current_era: EraIndex, amount_locked: Balance) -> Self { - let mut total = self.total; - let mut unlocking: Vec> = self - .unlocking - .into_iter() - .filter(|chunk| { - if chunk.era > current_era { - true - } else { - total = total.saturating_sub(chunk.value); - false - } - }) - .collect(); - if amount_locked > Zero::zero() { - total = total.saturating_add(amount_locked); - unlocking.push(UnlockChunk { - value: amount_locked, - era: current_era, - }); - } - Self { - total, - active: self.active, - stash: self.stash, - unlocking, - last_reward: self.last_reward, - } - } -} - -impl StakingLedger -where - Balance: AtLeast32BitUnsigned + Saturating + Copy, -{ - /// Slash the account for a given amount of balance. - /// - /// Slashes from `active` funds first, and then `unlocking`, starting with the - /// chunks that are closest to unlocking. - fn slash(&mut self, mut value: Balance) -> Balance { - let pre_total = self.total; - let total = &mut self.total; - let active = &mut self.active; - - let slash_out_of = - |total_remaining: &mut Balance, target: &mut Balance, value: &mut Balance| { - let slash_from_target = (*value).min(*target); - - if !slash_from_target.is_zero() { - *target -= slash_from_target; - *total_remaining = total_remaining.saturating_sub(slash_from_target); - *value -= slash_from_target; - } - }; - - slash_out_of(total, active, &mut value); - - let i = self - .unlocking - .iter_mut() - .map(|chunk| { - slash_out_of(total, &mut chunk.value, &mut value); - chunk.value - }) - .take_while(|value| value.is_zero()) // take all fully-consumed chunks out. - .count(); - - // kill all drained chunks. - let _ = self.unlocking.drain(..i); - - pre_total.saturating_sub(*total) - } -} - -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] -pub enum Vote { - Bad, - Good, -} - -#[derive(PartialEq, Eq, Clone, Encode, Decode, Default, RuntimeDebug)] -pub struct VoteCounts { - bad: u32, - good: u32, -} - -pub trait Trait: pallet_session::Trait { - /// The staking balance. - type Currency: LockableCurrency; - - // The check valid operated contracts. - type ContractFinder: ContractFinder; - - /// Number of eras that staked funds must remain bonded for. - type BondingDuration: Get; - - /// Tokens have been minted and are unused for validator-reward. Maybe, dapps-staking uses (). - type RewardRemainder: OnUnbalanced>; - - /// Handler for the unbalanced increment when rewarding a staker. Maybe, dapps-staking uses (). - type Reward: OnUnbalanced>; - - //TODO Handler for the unbalanced reduction when slashing a staker. - //type Slash: OnUnbalanced>; - - //TODO - // Number of eras that slashes are deferred by, after computation. This - // should be less than the bonding duration. Set to 0 if slashes should be - // applied immediately, without opportunity for intervention. - //type SlashDeferDuration: Get; - - // TODO - // The origin which can cancel a deferred slash. Root can always do this. - //type SlashCancelOrigin: EnsureOrigin; - - /// Time used for computing era duration. - type Time: Time; - - type ComputeRewardsForDapps: ComputeRewardsForDapps; - - /// The information of era. - type EraFinder: EraFinder>; - - /// The rewards for dapps operator. - type ForDappsEraReward: ForDappsEraRewardFinder>; - - /// the history depth - type HistoryDepthFinder: HistoryDepthFinder; - - /// The overarching event type. - type Event: From> + Into<::Event>; -} - -decl_storage! { - trait Store for Module as DappsStaking { - /// The already untreated era is EraIndex. - pub UntreatedEra get(fn untreated_era): EraIndex; - - // The untreated era for each contract - pub ContractsUntreatedEra get(fn contracts_untreated_era): - map hasher(twox_64_concat) T::AccountId => EraIndex; - - // The untreated era for each contract for votes - pub ContractVotesUntreatedEra get(fn contract_votes_untreated_era): - map hasher(twox_64_concat) T::AccountId => EraIndex; - - // ----- Staking uses. - /// Map from all locked "stash" accounts to the controller account. - pub Bonded get(fn bonded): map hasher(twox_64_concat) T::AccountId => Option; - - /// Map from all (unlocked) "controller" accounts to the info regarding the staking. - pub Ledger get(fn ledger): - map hasher(blake2_128_concat) T::AccountId - => Option>>; - - /// Where the reward payment should be made. Keyed by stash. - pub Payee get(fn payee): map hasher(twox_64_concat) T::AccountId => RewardDestination; - - /// The map from nominator stash key to the set of stash keys of all contracts to nominate. - /// - /// NOTE: is private so that we can ensure upgraded before all typical accesses. - /// Direct storage APIs can still bypass this protection. - DappsNominations get(fn dapps_nominations): map hasher(twox_64_concat) - T::AccountId => Option>>; - - /// Similarly to `ErasStakers` this holds the parameters of contracts. - /// - /// This is keyed first by the era index to allow bulk deletion and then the contracts account. - /// - /// Is it removed after `HISTORY_DEPTH` eras. - pub ErasContractsParameters get(fn eras_contracts_parameters): - double_map hasher(twox_64_concat) EraIndex, hasher(twox_64_concat) T::AccountId - => Option; - - /// Rewards of stakers for contracts(called by "Dapps Nominator") at era. - /// - /// This is keyed first by the era index, 2nd keyed contract account to allow the stash account. - /// Rewards for the last `HISTORY_DEPTH` eras. - /// - /// If reward hasn't been set or has been removed then 0 reward is returned. - pub ErasStakingPoints get(fn eras_staking_points): - double_map hasher(twox_64_concat) EraIndex, hasher(twox_64_concat) T::AccountId - => EraStakingPoints>; - - /// The total amount staked for the last `HISTORY_DEPTH` eras. - /// If total hasn't been set or has been removed then 0 stake is returned. - pub ErasTotalStake get(fn eras_total_stake): - map hasher(twox_64_concat) EraIndex => BalanceOf; - - /// The total amounts of staking for pairs of nominator and contract - pub TotalStakes get(fn total_stakes): - double_map hasher(twox_64_concat) T::AccountId, hasher(twox_64_concat) T::AccountId - => BalanceOf; - - /// Votes for pairs of an account and a contract - pub AccountsVote get(fn accounts_vote): - double_map hasher(twox_64_concat) T::AccountId, hasher(twox_64_concat) T::AccountId => VoteCounts; - - /// Votes for pairs of an era and a contract - pub ErasVotes get(fn eras_votes): - double_map hasher(twox_64_concat) EraIndex, hasher(twox_64_concat) T::AccountId => VoteCounts; - - /// Storage version of the pallet. - /// - /// This is set to v1.0.0 for new networks. - StorageVersion build(|_: &GenesisConfig| Releases::V1_0_0): Releases; - } -} - -decl_event!( - pub enum Event - where - AccountId = ::AccountId, - Balance = BalanceOf, - { - /// The amount of minted rewards. (for dapps with nominators) - Reward(Balance, Balance), - /// An account has bonded this amount. - /// - /// NOTE: This event is only emitted when funds are bonded via a dispatchable. Notably, - /// it will not be emitted for staking rewards when they are added to stake. - Bonded(AccountId, Balance), - /// An account has unbonded this amount. - Unbonded(AccountId, Balance), - /// An account has called `withdraw_unbonded` and removed unbonding chunks worth `Balance` - /// from the unlocking queue. - Withdrawn(AccountId, Balance), - /// The total amount of minted rewards for dapps. - TotalDappsRewards(EraIndex, Balance), - /// Nominate of stash address. - Nominate(AccountId), - } -); - -decl_error! { - /// Error for the staking module. - pub enum Error for Module { - /// Not a controller account. - NotController, - /// Not a stash account. - NotStash, - /// Stash is already bonded. - AlreadyBonded, - /// Controller is already paired. - AlreadyPaired, - /// Targets cannot be empty. - EmptyTargets, - /// Duplicate index. - DuplicateIndex, - /// Slash record index out of bounds. - InvalidSlashIndex, - /// Can not bond with value less than minimum balance. - InsufficientValue, - /// Can not schedule more unlock chunks. - NoMoreChunks, - /// Can not rebond without unlocking chunks. - NoUnlockChunk, - /// Attempting to target a stash that still has funds. - FundedTarget, - /// Invalid era to reward. - InvalidEraToReward, - /// Invalid number of nominations. - InvalidNumberOfNominations, - /// Items are not sorted and unique. - NotSortedAndUnique, - /// Targets must be latest 1. - EmptyNominateTargets, - /// Targets must be operated contracts - NotOperatedContracts, - /// The nominations amount more than active staking amount. - NotEnoughStaking, - } -} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - fn deposit_event() = default; - - fn on_runtime_upgrade() -> Weight { - migrate::(); - // TODO: weight - 50_000 - } - - /// Take the origin account as a stash and lock up `value` of its balance. `controller` will - /// be the account that controls it. - /// - /// `value` must be more than the `minimum_balance` specified by `T::Currency`. - /// - /// The dispatch origin for this call must be _Signed_ by the stash account. - /// - /// # - /// - Independent of the arguments. Moderate complexity. - /// - O(1). - /// - Three extra DB entries. - /// - /// NOTE: Two of the storage writes (`Self::bonded`, `Self::payee`) are _never_ cleaned unless - /// the `origin` falls below _existential deposit_ and gets removed as dust. - /// # - /// TODO: weight - #[weight = 500_000] - fn bond(origin, - controller: ::Source, - #[compact] value: BalanceOf, - payee: RewardDestination, - ) { - let stash = ensure_signed(origin)?; - - if >::contains_key(&stash) { - Err("stash already bonded")? - } - - let controller = T::Lookup::lookup(controller)?; - - if >::contains_key(&controller) { - Err("controller already paired")? - } - - // reject a bond which is considered to be _dust_. - if value < T::Currency::minimum_balance() { - Err("can not bond with value less than minimum balance")? - } - - // You're auto-bonded forever, here. We might improve this by only bonding when - // you actually validate/nominate and remove once you unbond __everything__. - >::insert(&stash, &controller); - >::insert(&stash, payee); - - // increments account reference counter for not removing accounts. - system::Module::::inc_ref(&stash); - - let stash_balance = T::Currency::free_balance(&stash); - let value = value.min(stash_balance); - Self::deposit_event(RawEvent::Bonded(stash.clone(), value.clone())); - let item = StakingLedger { - stash, - total: value, - active: value, - unlocking: vec![], - last_reward: T::EraFinder::current() - }; - Self::update_ledger(&controller, &item); - } - - /// Add some extra amount that have appeared in the stash `free_balance` into the balance up - /// for staking. - /// - /// Use this if there are additional funds in your stash account that you wish to bond. - /// Unlike [`bond`] or [`unbond`] this function does not impose any limitation on the amount - /// that can be added. - /// - /// The dispatch origin for this call must be _Signed_ by the stash, not the controller. - /// - /// # - /// - Independent of the arguments. Insignificant complexity. - /// - O(1). - /// - One DB entry. - /// # - /// TODO: weight - #[weight = 500_000] - fn bond_extra(origin, #[compact] max_additional: BalanceOf) { - let stash = ensure_signed(origin)?; - - let controller = Self::bonded(&stash).ok_or(Error::::NotStash)?; - let mut ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - - let stash_balance = T::Currency::free_balance(&stash); - - if let Some(extra) = stash_balance.checked_sub(&ledger.total) { - let extra = extra.min(max_additional); - ledger.total += extra; - ledger.active += extra; - Self::deposit_event(RawEvent::Bonded(stash, extra)); - Self::update_ledger(&controller, &ledger); - } - } - - /// Schedule a portion of the stash to be unlocked ready for transfer out after the bond - /// period ends. If this leaves an amount actively bonded less than - /// T::Currency::minimum_balance(), then it is increased to the full amount. - /// - /// Once the unlock period is done, you can call `withdraw_unbonded` to actually move - /// the funds out of management ready for transfer. - /// - /// No more than a limited number of unlocking chunks (see `MAX_UNLOCKING_CHUNKS`) - /// can co-exists at the same time. In that case, [`Call::withdraw_unbonded`] need - /// to be called first to remove some of the chunks (if possible). - /// - /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. - /// - /// See also [`Call::withdraw_unbonded`]. - /// - /// # - /// - Independent of the arguments. Limited but potentially exploitable complexity. - /// - Contains a limited number of reads. - /// - Each call (requires the remainder of the bonded balance to be above `minimum_balance`) - /// will cause a new entry to be inserted into a vector (`Ledger.unlocking`) kept in storage. - /// The only way to clean the aforementioned storage item is also user-controlled via - /// `withdraw_unbonded`. - /// - One DB entry. - /// - /// TODO: weight - #[weight = 400_000] - fn unbond(origin, #[compact] value: BalanceOf) { - let controller = ensure_signed(origin)?; - let mut ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - ensure!( - ledger.unlocking.len() < MAX_UNLOCKING_CHUNKS, - Error::::NoMoreChunks - ); - - let mut value = value.min(ledger.active); - - if !value.is_zero() { - ledger.active -= value; - - // Avoid there being a dust balance left in the staking system. - if ledger.active < T::Currency::minimum_balance() { - value += ledger.active; - ledger.active = Zero::zero(); - } - - Self::deposit_event(RawEvent::Unbonded(ledger.stash.clone(), value)); - let era = T::EraFinder::current().unwrap_or(Zero::zero()) + T::BondingDuration::get(); - ledger.unlocking.push(UnlockChunk { value, era }); - Self::update_ledger(&controller, &ledger); - } - } - - /// Remove any unlocked chunks from the `unlocking` queue from our management. - /// - /// This essentially frees up that balance to be used by the stash account to do - /// whatever it wants. - /// - /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. - /// - /// Emits `Withdrawn`. - /// - /// See also [`Call::unbond`]. - /// - /// # - /// - Could be dependent on the `origin` argument and how much `unlocking` chunks exist. - /// It implies `consolidate_unlocked` which loops over `Ledger.unlocking`, which is - /// indirectly user-controlled. See [`unbond`] for more detail. - /// - Contains a limited number of reads, yet the size of which could be large based on `ledger`. - /// - Writes are limited to the `origin` account key. - /// # - /// TODO: weight - #[weight = 400_000] - fn withdraw_unbonded(origin) { - let controller = ensure_signed(origin)?; - let mut ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - let (stash, old_total) = (ledger.stash.clone(), ledger.total); - - if let Some(current_era) = T::EraFinder::current() { - let amount_locked = match Self::dapps_nominations(&stash) { - Some(n) => n.targets - .iter() - .filter(|(contract, _)| Self::is_locked(contract, ¤t_era)) - .fold(BalanceOf::::zero(), |sum, (_, value)| sum.saturating_add(*value)), - None => BalanceOf::::zero() - }; - - ledger = ledger.consolidate_unlocked(current_era, amount_locked) - } - - if ledger.unlocking.is_empty() && ledger.active.is_zero() { - // This account must have called `unbond()` with some value that caused the active - // portion to fall below existential deposit + will have no more unlocking chunks - // left. We can now safely remove all staking-related information. - Self::kill_stash(&stash)?; - // remove the lock. - T::Currency::remove_lock(STAKING_ID, &stash); - } else { - // This was the consequence of a partial unbond. just update the ledger and move on. - Self::update_ledger(&controller, &ledger); - } - - // `old_total` should never be less than the new total because - // `consolidate_unlocked` strictly subtracts balance. - if ledger.total < old_total { - // Already checked that this won't overflow by entry condition. - let value = old_total - ledger.total; - Self::deposit_event(RawEvent::Withdrawn(stash, value)); - } - } - - /// Declare the desire to nominate `targets` for the origin controller. - /// - /// Effects will be felt at the beginning of the next era. - /// - /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. - /// - /// # - /// - The transaction's complexity is proportional to the size of `targets`, - /// which is capped at `MAX_NOMINATIONS`. - /// - Both the reads and writes follow a similar pattern. - /// # - /// TODO: weight - #[weight = 750_000] - fn nominate_contracts(origin, targets: Vec<(::Source, BalanceOf)>) { - let controller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - let stash = &ledger.stash; - ensure!(!targets.is_empty(), Error::::EmptyNominateTargets); - let targets = targets.into_iter() - .take(MAX_NOMINATIONS) - .map(|t| match T::Lookup::lookup(t.0) { - Ok(a) => Ok((a, t.1)), - Err(err) => Err(err), - }) - .collect::)>, _>>()?; - - // check the is targets operated contracts? - if !targets.iter().all(|t| T::ContractFinder::is_exists_contract(&(t.0))) { - Err(Error::::NotOperatedContracts)? - } - - if targets - .iter() - .fold(BalanceOf::::zero(), - |sum, t| sum.saturating_add(t.1)) > ledger.active { - Err(Error::::NotEnoughStaking)? - } - - let nominations = Nominations { - targets, - submitted_in: T::EraFinder::current().unwrap_or(Zero::zero()), - suppressed: false, - }; - - Self::take_in_nominations(stash, nominations); - Self::deposit_event(RawEvent::Nominate(stash.clone())); - } - - /// vote some contracts with Bad/Good. - /// If you have already voted for a contract on your account, your vote for that contract will be overridden. - /// - /// TODO: weight - #[weight = 100_000] - fn vote_contracts(origin, targets: Vec<(::Source, Vote)>) { - let sender = ensure_signed(origin)?; - ensure!(!targets.is_empty(), Error::::EmptyNominateTargets); - - let targets = targets.into_iter() - .take(MAX_VOTES) - .map(|t| match T::Lookup::lookup(t.0) { - Ok(a) => Ok((a, t.1)), - Err(err) => Err(err), - }) - .collect::, _>>()?; - - if !targets.iter().all(|t| T::ContractFinder::is_exists_contract(&(t.0))) { - Err(Error::::NotOperatedContracts)? - } - - if let Some(current_era) = T::EraFinder::current() { - let next_era = current_era + 1; - for (contract, vote) in targets.iter() { - let counts = Self::vote_counts(vote.clone()); - - if >::contains_key(&next_era, &contract) { - >::mutate(&next_era, &contract, |votes| { - if >::contains_key(&sender, &contract) { - let clear_counts = Self::accounts_vote(&sender, &contract); - (*votes).bad -= clear_counts.bad; - (*votes).good -= clear_counts.good; - } - (*votes).bad += counts.bad; - (*votes).good += counts.good; - }); - } else { - >::insert(&next_era, &contract, &counts); - } - >::insert(&sender, &contract, counts); - } - } - } - - /// Declare no desire to either validate or nominate. - /// - /// Effects will be felt at the beginning of the next era. - /// - /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. - /// - /// # - /// - Independent of the arguments. Insignificant complexity. - /// - Contains one read. - /// - Writes are limited to the `origin` account key. - /// # - /// TODO: weight - #[weight = 500_000] - fn chill(origin) { - let controller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - Self::chill_stash(&ledger.stash); - } - - /// (Re-)set the payment target for a controller. - /// - /// Effects will be felt at the beginning of the next era. - /// - /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. - /// - /// # - /// - Independent of the arguments. Insignificant complexity. - /// - Contains a limited number of reads. - /// - Writes are limited to the `origin` account key. - /// # - /// TODO: weight - #[weight = 500_000] - fn set_payee(origin, payee: RewardDestination) { - let controller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - let stash = &ledger.stash; - >::insert(stash, payee); - } - - /// slash the account for the contract. - /// - /// If there are more votes than the required number of votes and - /// the good is less than the bad for two consecutive terms, - /// this function returns true. - /// - /// TODO: weight - #[weight = 100_000] - fn slash(origin, controller: ::Source, contract: ::Source) { - ensure_signed(origin)?; - let controller = T::Lookup::lookup(controller)?; - let mut ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - let stash = &ledger.stash; - - let contract = T::Lookup::lookup(contract)?; - if !T::ContractFinder::is_exists_contract(&contract) { - Err(Error::::NotOperatedContracts)? - } - - if let Some(current_era) = T::EraFinder::current() { - if !Self::is_slashable(&contract, ¤t_era) { - Err("not slashable")? - } - - let each_points = (current_era.saturating_sub(T::HistoryDepthFinder::get())..=current_era) - .map(|era| Self::eras_staking_points(&era, &contract)); - let mut slash_amount = BalanceOf::::zero(); - for points in each_points { - slash_amount += points.individual.get(&stash).unwrap_or(&BalanceOf::::zero()).clone(); - } - - ledger.slash(slash_amount); - } - } - - /// (Re-)set the controller of a stash. - /// - /// Effects will be felt at the beginning of the next era. - /// - /// The dispatch origin for this call must be _Signed_ by the stash, not the controller. - /// - /// # - /// - Independent of the arguments. Insignificant complexity. - /// - Contains a limited number of reads. - /// - Writes are limited to the `origin` account key. - /// # - /// TODO: weight - #[weight = 750_000] - fn set_controller(origin, controller: ::Source) { - let stash = ensure_signed(origin)?; - let old_controller = Self::bonded(&stash).ok_or(Error::::NotStash)?; - let controller = T::Lookup::lookup(controller)?; - if >::contains_key(&controller) { - Err("controller already paired")? - } - if controller != old_controller { - >::insert(&stash, &controller); - if let Some(l) = >::take(&old_controller) { - >::insert(&controller, l); - } - } - } - - /// rewards are claimed by the contract. - /// - /// era must be in the range `[current_era - history_depth; active_era)`. - #[weight = 1_000] - fn claim(origin, contract: ::Source, era: EraIndex) { - ensure_signed(origin)?; - - let contract = T::Lookup::lookup(contract)?; - if !T::ContractFinder::is_exists_contract(&contract) { - Err(Error::::NotOperatedContracts)? - } - - // check if era is valid - if let Some(active_era) = T::EraFinder::active() { - if era >= active_era.index { - Err("cannot claim yet")? - } - } - if let Some(current_era) = T::EraFinder::current() { - if era < current_era.saturating_sub(T::HistoryDepthFinder::get()) { - Err("the era is expired")? - } - } - - let mut untreated_era = Self::contracts_untreated_era(&contract); - if era == untreated_era { - Err("the contract is already rewarded")? - } - while era > untreated_era { - Self::propagate_eras_staking_points_total(&contract, &untreated_era, &(untreated_era + 1)); - untreated_era += 1; - } - >::insert(&contract, untreated_era); - - let rewards = match T::ForDappsEraReward::get(&era) { - Some(rewards) => rewards, - None => { - frame_support::print("Error: start_session_index must be set for current_era"); - BalanceOf::::zero() - } - }; - - let mut actual_rewarded = BalanceOf::::zero(); - - // rewards for the operator - if let Some(operator) = T::ContractFinder::operator(&contract) { - actual_rewarded += Self::reward_operator(&era, rewards, &operator, &contract); - } - - // rewards for nominators - let each_points = (era.saturating_sub(T::HistoryDepthFinder::get())..=era) - .map(|era| Self::eras_staking_points(&era, &contract)); - for points in each_points { - for (nominator, _) in points.individual { - actual_rewarded += Self::reward_nominator(&era, rewards, &nominator, &contract); - } - } - - // deposit event to total rewards - Self::deposit_event(RawEvent::TotalDappsRewards(era, actual_rewarded)); - } - } -} - -fn migrate() {} - -impl Module { - // MUTABLES (DANGEROUS) - - /// Update the ledger for a controller. This will also update the stash lock. The lock will - /// will lock the entire funds except paying for further transactions. - fn update_ledger( - controller: &T::AccountId, - ledger: &StakingLedger>, - ) { - T::Currency::set_lock( - STAKING_ID, - &ledger.stash, - ledger.total, - WithdrawReasons::all(), - ); - >::insert(controller, ledger); - } - - /// Remove all associated data of a stash account from the staking system. - /// - /// Assumes storage is upgraded before calling. - /// - /// This is called : - /// - Immediately when an account's balance falls below existential deposit. - /// - after a `withdraw_unbond()` call that frees all of a stash's bonded balance. - fn kill_stash(stash: &T::AccountId) -> DispatchResult { - let controller = Bonded::::take(stash).ok_or(Error::::NotStash)?; - >::remove(&controller); - - >::remove(stash); - if let Some(nominations) = Self::dapps_nominations(stash) { - Self::remove_nominations(stash, nominations); - } - - system::Module::::dec_ref(stash); - Ok(()) - } - - /// Chill a stash account. - fn chill_stash(stash: &T::AccountId) { - if let Some(nominations) = Self::dapps_nominations(stash) { - Self::remove_nominations(stash, nominations); - } - } - - fn reward_nominator( - era: &EraIndex, - max_payout: BalanceOf, - nominator: &T::AccountId, - contract: &T::AccountId, - ) -> BalanceOf { - let mut total_imbalance = >::zero(); - let (_, nominators_reward) = - T::ComputeRewardsForDapps::compute_rewards_for_dapps(max_payout); - - let total_staked = Self::eras_total_stake(era); - - let mut nominate_values: Vec<_> = Vec::new(); - - // collect target points - let mut each_points: Vec<_> = Vec::new(); - for e in era.saturating_sub(T::HistoryDepthFinder::get())..=*era { - for (c, points) in >::iter_prefix(&e) { - if c != *contract { - continue; - } - if Self::is_rewardable(&contract, &e) { - each_points.push(( - Self::eras_staking_points(era, contract).total, - points.individual, - )); - } - } - } - - // summarize nominated values - let mut nominate_total = BalanceOf::::zero(); - for (total, individual) in each_points { - for (account, value) in individual { - if account == *nominator { - nominate_total += value; - nominate_values.push((total, value)); - } - } - } - - let reward = T::ComputeRewardsForDapps::compute_reward_for_nominator( - nominate_total, - total_staked, - nominators_reward, - nominate_values, - ); - total_imbalance.subsume( - Self::make_payout(nominator, reward).unwrap_or(PositiveImbalanceOf::::zero()), - ); - - let total_payout = total_imbalance.peek(); - - let rest = max_payout.saturating_sub(total_payout.clone()); - - T::Reward::on_unbalanced(total_imbalance); - T::RewardRemainder::on_unbalanced(T::Currency::issue(rest)); - total_payout - } - - fn reward_operator( - era: &EraIndex, - max_payout: BalanceOf, - operator: &T::AccountId, - contract: &T::AccountId, - ) -> BalanceOf { - let mut total_imbalance = >::zero(); - let (operators_reward, _) = - T::ComputeRewardsForDapps::compute_rewards_for_dapps(max_payout); - - let total_staked = Self::eras_total_stake(era); - - let mut stakes = BalanceOf::::zero(); - for e in era.saturating_sub(T::HistoryDepthFinder::get())..=*era { - for (c, _) in >::iter_prefix(&e) { - if c != *contract { - continue; - } - if let Some(o) = T::ContractFinder::operator(&contract) { - if o == *operator && Self::is_rewardable(&contract, &e) { - stakes += Self::eras_staking_points(era, contract).total; - } - } - } - } - - let reward = T::ComputeRewardsForDapps::compute_reward_for_operator( - stakes, - total_staked, - operators_reward, - ); - total_imbalance.subsume( - T::Currency::deposit_into_existing(operator, reward) - .unwrap_or(PositiveImbalanceOf::::zero()), - ); - - let total_payout = total_imbalance.peek(); - - let rest = max_payout.saturating_sub(total_payout.clone()); - - T::Reward::on_unbalanced(total_imbalance); - T::RewardRemainder::on_unbalanced(T::Currency::issue(rest)); - total_payout - } - - fn propagate_eras_staking_points_total( - contract: &T::AccountId, - src_era: &EraIndex, - dst_era: &EraIndex, - ) { - if >::contains_key(src_era, contract) { - let untreated_points = >::get(src_era, contract); - - >::mutate(&dst_era, &contract, |points| { - (*points).total += untreated_points.total.clone(); - }); - } - } - - fn compute_total_stake(era: &EraIndex) -> BalanceOf { - let mut untreated_era = Self::untreated_era(); - while *era > untreated_era { - let total = Self::eras_total_stake(&untreated_era); - >::mutate(&untreated_era + 1, |next_total| *next_total += total); - untreated_era += 1; - } - UntreatedEra::put(untreated_era); - let total_staked = Self::eras_total_stake(era); - total_staked - } - - fn make_payout(stash: &T::AccountId, amount: BalanceOf) -> Option> { - let dest = Self::payee(stash); - match &dest { - RewardDestination::Controller => Self::bonded(stash).and_then(|controller| { - T::Currency::deposit_into_existing(&controller, amount).ok() - }), - RewardDestination::Stash => T::Currency::deposit_into_existing(stash, amount).ok(), - RewardDestination::Staked => Self::bonded(stash) - .and_then(|c| Self::ledger(&c).map(|l| (c, l))) - .and_then(|(controller, mut l)| { - l.active += amount; - l.total += amount; - let r = T::Currency::deposit_into_existing(stash, amount).ok(); - Self::update_ledger(&controller, &l); - r - }), - RewardDestination::Account(account) => { - T::Currency::deposit_into_existing(account, amount).ok() - } - } - } - - fn take_in_nominations( - stash: &T::AccountId, - nominations: Nominations>, - ) { - if let Some(current_era) = T::EraFinder::current() { - let next_era = current_era + 1; - - for (contract, value) in nominations.targets.iter() { - if >::contains_key(&next_era, &contract) { - >::mutate(&next_era, &contract, |points| { - (*points).total += value.clone(); - (*points).individual.insert(stash.clone(), value.clone()); - }); - } else { - let points = EraStakingPoints { - total: value.clone(), - individual: vec![(stash.clone(), value.clone())] - .into_iter() - .collect::>>(), - }; - >::insert(&next_era, &contract, points); - } - - >::mutate(&next_era, |total| { - *total += value.clone(); - }); - } - } - >::insert(stash, nominations); - } - - fn remove_nominations( - stash: &T::AccountId, - nominations: Nominations>, - ) { - let era = nominations.submitted_in + 1; - for (contract, value) in nominations.targets.iter() { - >::mutate(&era, &contract, |points| { - (*points).total = points.total.saturating_sub(value.clone()); - (*points).individual.remove(stash); - }); - - >::mutate(&era, |total| { - *total = total.saturating_sub(value.clone()); - }); - } - >::remove(stash); - } - - fn propagate_eras_votes(contract: &T::AccountId, src_era: &EraIndex, dst_era: &EraIndex) { - if >::contains_key(src_era, contract) { - let untreated_votes = >::get(src_era, contract); - - >::mutate(&dst_era, &contract, |votes| { - (*votes).bad += untreated_votes.bad.clone(); - (*votes).good += untreated_votes.good.clone(); - }); - } - } - - // lazily update ErasVotes - fn update_vote_counts(contract: &T::AccountId, era: &EraIndex) { - let current_era = T::EraFinder::current().unwrap_or(Zero::zero()); - if current_era < *era { - return; - } - let mut untreated_era = Self::contract_votes_untreated_era(&contract); - while *era > untreated_era { - Self::propagate_eras_votes(&contract, &untreated_era, &(untreated_era + 1)); - untreated_era += 1; - } - >::insert(&contract, untreated_era); - } - - // convert Vote into VoteCounts - fn vote_counts(vote: Vote) -> VoteCounts { - let mut counts = VoteCounts { bad: 0, good: 0 }; - if vote == Vote::Bad { - counts.bad += 1 - } else { - counts.good += 1 - }; - counts - } - - // check the number of votes meets the required number of votes - fn has_votes_requirement(contract: &T::AccountId, era: &EraIndex) -> bool { - let vote_counts = Self::eras_votes(era, contract); - vote_counts.bad + vote_counts.good >= VOTES_REQUIREMENT - } - - // If there are more than the required number of votes and - // the good has been voted for four times the bad in two consecutive periods, - // this function returns true. - fn is_rewardable(contract: &T::AccountId, era: &EraIndex) -> bool { - Self::update_vote_counts(contract, era); - if *era <= Zero::zero() { - return false; - } - let prev_votes = Self::eras_votes(era - 1, contract); - let votes = Self::eras_votes(era, contract); - Self::has_votes_requirement(contract, &(era - 1)) - && Self::has_votes_requirement(contract, era) - && prev_votes.good >= prev_votes.bad * 4 - && votes.good >= votes.bad * 4 - } - - // If there are more votes the required number of votes and - // the good is less than twice the bad in the previous era, - // this function returns true. - fn is_locked(contract: &T::AccountId, era: &EraIndex) -> bool { - Self::update_vote_counts(contract, era); - if *era <= Zero::zero() { - return false; - } - let prev_votes = Self::eras_votes(era - 1, contract); - Self::has_votes_requirement(contract, &(era - 1)) - && Self::has_votes_requirement(contract, era) - && prev_votes.good < prev_votes.bad * 2 - } - - // If there are more votes than the required number of votes and - // the good is less than the bad for two consecutive terms, - // this function returns true. - fn is_slashable(contract: &T::AccountId, era: &EraIndex) -> bool { - Self::update_vote_counts(contract, era); - if *era <= Zero::zero() { - return false; - } - let prev_votes = Self::eras_votes(era - 1, contract); - let votes = Self::eras_votes(era, contract); - Self::has_votes_requirement(contract, &(era - 1)) - && Self::has_votes_requirement(contract, era) - && prev_votes.good < prev_votes.bad - && votes.good < votes.bad - } -} - -/// Get the amount of staking per Era in a module in the Plasm Network. -impl ComputeEraWithParam for Module { - type Param = BalanceOf; - fn compute(era: &EraIndex) -> BalanceOf { - Self::compute_total_stake(era) - } -} diff --git a/frame/dapps-staking/src/log.rs b/frame/dapps-staking/src/log.rs deleted file mode 100644 index 826f573f63..0000000000 --- a/frame/dapps-staking/src/log.rs +++ /dev/null @@ -1,133 +0,0 @@ -use sp_std::convert::TryInto; - -/// Simple u32 power of 2 function - simply uses a bit shift -macro_rules! pow2 { - ($n:expr) => { - 1_u32 << $n - }; -} - -/// Returns the k_th per_million taylor term for a log2 function -fn taylor_term(k: u32, y_num: u128, y_den: u128) -> u32 { - let _2_div_ln_2: u128 = 2_885_390u128; - - if k == 0 { - (_2_div_ln_2 * (y_num).pow(1) / (y_den).pow(1)) - .try_into() - .unwrap() - } else { - let mut res = _2_div_ln_2 * (y_num).pow(3) / (y_den).pow(3); - for _ in 1..k { - res = res * (y_num).pow(2) / (y_den).pow(2); - } - res /= 2 * k as u128 + 1; - - res.try_into().unwrap() - } -} - -/// Performs a log2 operation using a rational fraction -/// -/// result = log2(p/q) where p/q is bound to [1, 1_000_000] -/// Where: -/// * q represents the numerator of the rational fraction input -/// * p represents the denominator of the rational fraction input -/// * result represents a per-million output of log2 -pub fn log2(p: u32, q: u32) -> u32 { - assert!(p >= q); // keep p/q bound to [1, inf) - assert!(p <= u32::max_value() / 2); - - // This restriction should not be mandatory. But function is only tested and used for this. - assert!(p <= 1_000_000); - assert!(q <= 1_000_000); - - // log2(1) = 0 - if p == q { - return 0; - } - - // find the power of 2 where q * 2^n <= p < q * 2^(n+1) - let mut n = 0u32; - while !(p >= pow2!(n) * q) || !(p < pow2!(n + 1) * q) { - n += 1; - assert!(n < 32); // cannot represent 2^32 in u32 - } - assert!(p < pow2!(n + 1) * q); - - let y_num: u32 = (p - pow2!(n) * q).try_into().unwrap(); - let y_den: u32 = (p + pow2!(n) * q).try_into().unwrap(); - - // Loop through each Taylor series coefficient until it reaches 10^-6 - let mut res = n * 1_000_000u32; - let mut k = 0; - loop { - let term = taylor_term(k, y_num.into(), y_den.into()); - if term == 0 { - break; - } - - res += term; - k += 1; - } - - res -} - -#[test] -fn test_log() { - let div = 1_000; - for p in 0..=div { - for q in 1..=p { - let p: u32 = (1_000_000 as u64 * p as u64 / div as u64) - .try_into() - .unwrap(); - let q: u32 = (1_000_000 as u64 * q as u64 / div as u64) - .try_into() - .unwrap(); - - let res = -(log2(p, q) as i64); - let expected = ((q as f64 / p as f64).log(2.0) * 1_000_000 as f64).round() as i64; - assert!((res - expected).abs() <= 6); - } - } -} - -#[test] -#[should_panic] -fn test_log_p_must_be_greater_than_q() { - let p: u32 = 1_000; - let q: u32 = 1_001; - let _ = log2(p, q); -} - -#[test] -#[should_panic] -fn test_log_p_upper_bound() { - let p: u32 = 1_000_001; - let q: u32 = 1_000_000; - let _ = log2(p, q); -} - -#[test] -#[should_panic] -fn test_log_q_limit() { - let p: u32 = 1_000_000; - let q: u32 = 0; - let _ = log2(p, q); -} - -#[test] -fn test_log_of_one_boundary() { - let p: u32 = 1_000_000; - let q: u32 = 1_000_000; - assert_eq!(log2(p, q), 0); -} - -#[test] -fn test_log_of_largest_input() { - let p: u32 = 1_000_000; - let q: u32 = 1; - let expected = 19_931_568; - let tolerance = 100; - assert!((log2(p, q) as i32 - expected as i32).abs() < tolerance); -} diff --git a/frame/dapps-staking/src/mock.rs b/frame/dapps-staking/src/mock.rs deleted file mode 100644 index dcaa37a830..0000000000 --- a/frame/dapps-staking/src/mock.rs +++ /dev/null @@ -1,530 +0,0 @@ -//! Test utilities - -#![cfg(test)] - -use super::*; -use frame_support::{ - assert_ok, impl_outer_dispatch, impl_outer_origin, parameter_types, - traits::OnFinalize, - weights::{WeightToFeeCoefficients, WeightToFeePolynomial}, -}; -use pallet_contracts::Gas; -use pallet_plasm_rewards::{inflation::SimpleComputeTotalPayout, traits::MaybeValidators}; -use sp_core::{crypto::key_types, H256}; -use sp_runtime::{ - testing::{Header, UintAuthorityId}, - traits::{BlakeTwo256, ConvertInto, Hash, IdentityLookup, OpaqueKeys}, - KeyTypeId, Perbill, -}; - -pub type BlockNumber = u64; -pub type AccountId = u64; -pub type Balance = u64; - -pub const ALICE_STASH: u64 = 1; -pub const BOB_STASH: u64 = 2; -pub const ALICE_CTRL: u64 = 3; -pub const BOB_CTRL: u64 = 4; -pub const VALIDATOR_A: u64 = 5; -pub const VALIDATOR_B: u64 = 6; -pub const OPERATOR_A: u64 = 9; -pub const OPERATOR_B: u64 = 10; -pub const OPERATOR_C: u64 = 11; -pub const OPERATED_CONTRACT_A: u64 = 19; -pub const OPERATED_CONTRACT_B: u64 = 20; -pub const OPERATED_CONTRACT_C: u64 = 21; -pub const BOB_CONTRACT: u64 = 12; - -impl_outer_origin! { - pub enum Origin for Test {} -} - -impl_outer_dispatch! { - pub enum Call for Test where origin: Origin { - pallet_session::Session, - pallet_balances::Balances, - pallet_contracts::Contracts, - dapps_staking::DappsStaking, - } -} - -pub fn new_test_ext() -> sp_io::TestExternalities { - let mut storage = system::GenesisConfig::default() - .build_storage::() - .unwrap(); - - let _ = pallet_balances::GenesisConfig:: { - balances: vec![ - (ALICE_STASH, 1000), - (BOB_STASH, 2000), - (ALICE_CTRL, 10), - (BOB_CTRL, 20), - (VALIDATOR_A, 1_000_000), - (VALIDATOR_B, 1_000_000), - ], - } - .assimilate_storage(&mut storage); - - let _ = pallet_contracts::GenesisConfig { - current_schedule: pallet_contracts::Schedule { - enable_println: true, - ..Default::default() - }, - } - .assimilate_storage(&mut storage); - - let _ = pallet_plasm_rewards::GenesisConfig { - ..Default::default() - } - .assimilate_storage(&mut storage); - - let _ = GenesisConfig { - ..Default::default() - } - .assimilate_storage(&mut storage); - - let validators = vec![VALIDATOR_A, VALIDATOR_B]; - - let _ = pallet_session::GenesisConfig:: { - keys: validators - .iter() - .map(|x| (*x, *x, UintAuthorityId(*x))) - .collect(), - } - .assimilate_storage(&mut storage); - - storage.into() -} - -#[derive(Clone, PartialEq, Eq, Debug)] -pub struct Test; - -parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: u32 = 1024; - pub const MaximumBlockLength: u32 = 2 * 1024; - pub const AvailableBlockRatio: Perbill = Perbill::one(); -} - -impl system::Trait for Test { - type Origin = Origin; - type BaseCallFilter = (); - type Index = u64; - type BlockNumber = BlockNumber; - type Call = Call; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; - type Header = Header; - type Event = (); - type BlockHashCount = BlockHashCount; - type MaximumBlockWeight = MaximumBlockWeight; - type MaximumBlockLength = MaximumBlockLength; - type AvailableBlockRatio = AvailableBlockRatio; - type Version = (); - type PalletInfo = (); - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = (); - type SystemWeightInfo = (); -} - -parameter_types! { - pub const MinimumPeriod: u64 = 1; -} -impl pallet_timestamp::Trait for Test { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); -} - -parameter_types! { - pub const Period: u64 = 1; - pub const Offset: u64 = 0; -} - -pub struct TestSessionHandler; - -impl pallet_session::SessionHandler for TestSessionHandler { - const KEY_TYPE_IDS: &'static [KeyTypeId] = &[key_types::DUMMY]; - fn on_genesis_session(_validators: &[(u64, T)]) {} - fn on_new_session( - _changed: bool, - _validators: &[(u64, T)], - _queued_validators: &[(u64, T)], - ) { - } - fn on_disabled(_validator_index: usize) {} - fn on_before_session_ending() {} -} - -impl pallet_session::Trait for Test { - type ShouldEndSession = pallet_session::PeriodicSessions; - type NextSessionRotation = pallet_session::PeriodicSessions; - type SessionManager = PlasmRewards; - type SessionHandler = TestSessionHandler; - type ValidatorId = u64; - type ValidatorIdOf = ConvertInto; - type Keys = UintAuthorityId; - type Event = (); - type DisabledValidatorsThreshold = (); - type WeightInfo = (); -} - -parameter_types! { - pub const ExistentialDeposit: Balance = 10; -} - -impl pallet_balances::Trait for Test { - type Balance = Balance; - type Event = (); - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = system::Module; - type WeightInfo = (); - type MaxLocks = (); -} - -pub struct WeightToFee; -impl WeightToFeePolynomial for WeightToFee { - type Balance = u64; - fn polynomial() -> WeightToFeeCoefficients { - Default::default() - } -} - -parameter_types! { - pub const TransactionByteFee: u64 = 0; -} - -impl pallet_transaction_payment::Trait for Test { - type Currency = Balances; - type OnTransactionPayment = (); - type TransactionByteFee = TransactionByteFee; - type WeightToFee = WeightToFee; - type FeeMultiplierUpdate = (); -} - -pub struct DummyContractAddressFor; -impl pallet_contracts::ContractAddressFor for DummyContractAddressFor { - fn contract_address_for(_code_hash: &H256, _data: &[u8], origin: &u64) -> u64 { - *origin + 10 - } -} - -pub struct DummyTrieIdGenerator; - -impl pallet_contracts::TrieIdGenerator for DummyTrieIdGenerator { - fn trie_id(account_id: &u64) -> pallet_contracts::TrieId { - use sp_core::storage::well_known_keys; - - let new_seed = pallet_contracts::AccountCounter::mutate(|v| { - *v = v.wrapping_add(1); - *v - }); - - // TODO: see https://github.com/paritytech/substrate/issues/2325 - let mut res = vec![]; - res.extend_from_slice(well_known_keys::CHILD_STORAGE_KEY_PREFIX); - res.extend_from_slice(b"default:"); - res.extend_from_slice(&new_seed.to_le_bytes()); - res.extend_from_slice(&account_id.to_le_bytes()); - res - } -} - -parameter_types! { - pub const ContractTransactionBaseFee: Balance = 0; - pub const ContractTransactionByteFee: Balance = 0; - pub const ContractFee: Balance = 0; - pub const TombstoneDeposit: Balance = 0; - pub const RentByteFee: Balance = 0; - pub const RentDepositOffset: Balance = 0; - pub const SurchargeReward: Balance = 0; -} - -impl pallet_contracts::Trait for Test { - type Time = Timestamp; - type Randomness = pallet_randomness_collective_flip::Module; - type Currency = Balances; - type Event = (); - type DetermineContractAddress = DummyContractAddressFor; - type TrieIdGenerator = DummyTrieIdGenerator; - type RentPayment = (); - type SignedClaimHandicap = pallet_contracts::DefaultSignedClaimHandicap; - type TombstoneDeposit = TombstoneDeposit; - type StorageSizeOffset = pallet_contracts::DefaultStorageSizeOffset; - type RentByteFee = RentByteFee; - type RentDepositOffset = RentDepositOffset; - type SurchargeReward = SurchargeReward; - type MaxDepth = pallet_contracts::DefaultMaxDepth; - type MaxValueSize = pallet_contracts::DefaultMaxValueSize; - type WeightPrice = pallet_transaction_payment::Module; -} - -impl pallet_contract_operator::Trait for Test { - type Parameters = parameters::StakingParameters; - type Event = (); -} - -pub struct DummyMaybeValidators; -impl MaybeValidators for DummyMaybeValidators { - fn compute(_current_era: EraIndex) -> Option> { - Some(vec![1, 2, 3]) - } -} - -parameter_types! { - pub const SessionsPerEra: sp_staking::SessionIndex = 10; - pub const BondingDuration: EraIndex = 3; -} - -impl pallet_plasm_rewards::Trait for Test { - type Currency = Balances; - type Time = Timestamp; - type SessionsPerEra = SessionsPerEra; - type BondingDuration = BondingDuration; - type ComputeEraForDapps = DappsStaking; - type ComputeEraForSecurity = DappsStaking; - type ComputeTotalPayout = SimpleComputeTotalPayout; - type MaybeValidators = DummyMaybeValidators; - type Event = (); -} - -impl Trait for Test { - type Currency = Balances; - type BondingDuration = BondingDuration; - type ContractFinder = Operator; - type RewardRemainder = (); // Reward remainder is burned. - type Reward = (); // Reward is minted. - type Time = Timestamp; - type ComputeRewardsForDapps = rewards::VoidableRewardsForDapps; - type EraFinder = PlasmRewards; - type ForDappsEraReward = PlasmRewards; - type HistoryDepthFinder = PlasmRewards; - type Event = (); -} - -/// ValidatorManager module. -pub type System = system::Module; -pub type Session = pallet_session::Module; -pub type Balances = pallet_balances::Module; -pub type Timestamp = pallet_timestamp::Module; -pub type Contracts = pallet_contracts::Module; -pub type Operator = pallet_contract_operator::Module; -pub type PlasmRewards = pallet_plasm_rewards::Module; -pub type DappsStaking = Module; - -/// Generate Wasm binary and code hash from wabt source. -pub fn compile_module( - wabt_module: &str, -) -> result::Result<(Vec, ::Output), wabt::Error> -where - T: system::Trait, -{ - let wasm = wabt::wat2wasm(wabt_module)?; - let code_hash = T::Hashing::hash(&wasm); - Ok((wasm, code_hash)) -} - -pub const CODE_RETURN_FROM_START_FN: &str = r#" -(module - (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) - (import "seal0" "seal_deposit_event" (func $seal_deposit_event (param i32 i32 i32 i32))) - (import "env" "memory" (memory 1 1)) - - (start $start) - (func $start - (call $seal_deposit_event - (i32.const 0) ;; The topics buffer - (i32.const 0) ;; The topics buffer's length - (i32.const 8) ;; The data buffer - (i32.const 4) ;; The data buffer's length - ) - (call $seal_return - (i32.const 0) - (i32.const 8) - (i32.const 4) - ) - (unreachable) - ) - - (func (export "call") - (unreachable) - ) - (func (export "deploy")) - - (data (i32.const 8) "\01\02\03\04") -) -"#; - -pub fn valid_instatiate() { - let (wasm, code_hash) = compile_module::(CODE_RETURN_FROM_START_FN).unwrap(); - - // prepare - let _ = Balances::deposit_creating(&OPERATOR_A, 1_000_000); - assert_ok!(Contracts::put_code( - Origin::signed(OPERATOR_A), - wasm.clone() - )); - - let _ = Balances::deposit_creating(&OPERATOR_B, 1_000_000); - assert_ok!(Contracts::put_code( - Origin::signed(OPERATOR_B), - wasm.clone() - )); - - let _ = Balances::deposit_creating(&OPERATOR_C, 1_000_000); - assert_ok!(Contracts::put_code( - Origin::signed(OPERATOR_C), - wasm.clone() - )); - - let test_params = parameters::StakingParameters { - can_be_nominated: true, - option_expired: 100, - option_p: Perbill::from_percent(20).deconstruct(), - }; - - // instantiate - // Check at the end to get hash on error easily - let _ = Operator::instantiate( - Origin::signed(OPERATOR_A), - 100, - Gas::max_value(), - code_hash.into(), - vec![], - test_params.clone(), - ); - let _ = Operator::instantiate( - Origin::signed(OPERATOR_B), - 100, - Gas::max_value(), - code_hash.into(), - vec![], - test_params.clone(), - ); - let _ = Operator::instantiate( - Origin::signed(OPERATOR_C), - 100, - Gas::max_value(), - code_hash.into(), - vec![], - test_params.clone(), - ); - - // checks deployed contract - assert!(pallet_contracts::ContractInfoOf::::contains_key( - OPERATED_CONTRACT_A - )); - assert!(pallet_contracts::ContractInfoOf::::contains_key( - OPERATED_CONTRACT_B - )); - assert!(pallet_contracts::ContractInfoOf::::contains_key( - OPERATED_CONTRACT_C - )); - - // checks mapping operator and contract - // OPERATOR_A operates a only OPERATED_CONTRACT_A contract. - assert!(pallet_contract_operator::OperatorHasContracts::::contains_key(OPERATOR_A)); - let tree = pallet_contract_operator::OperatorHasContracts::::get(&OPERATOR_A); - assert_eq!(tree.len(), 1); - assert!(tree.contains(&OPERATED_CONTRACT_A)); - - // checks mapping operator and contract - // OPERATOR_B operates a only OPERATED_CONTRACT_B contract. - assert!(pallet_contract_operator::OperatorHasContracts::::contains_key(OPERATOR_B)); - let tree = pallet_contract_operator::OperatorHasContracts::::get(&OPERATOR_B); - assert_eq!(tree.len(), 1); - assert!(tree.contains(&OPERATED_CONTRACT_B)); - - // checks mapping operator and contract - // OPERATOR_C operates a only OPERATED_CONTRACT_C contract. - assert!(pallet_contract_operator::OperatorHasContracts::::contains_key(OPERATOR_C)); - let tree = pallet_contract_operator::OperatorHasContracts::::get(&OPERATOR_C); - assert_eq!(tree.len(), 1); - assert!(tree.contains(&OPERATED_CONTRACT_C)); - - // OPERATED_CONTRACT_A contract is operated by OPERATOR_A. - assert!( - pallet_contract_operator::ContractHasOperator::::contains_key(OPERATED_CONTRACT_A) - ); - assert_eq!( - pallet_contract_operator::ContractHasOperator::::get(&OPERATED_CONTRACT_A), - Some(OPERATOR_A) - ); - - // OPERATED_CONTRACT_B contract is operated by OPERATOR_B. - assert!( - pallet_contract_operator::ContractHasOperator::::contains_key(OPERATED_CONTRACT_B) - ); - assert_eq!( - pallet_contract_operator::ContractHasOperator::::get(&OPERATED_CONTRACT_B), - Some(OPERATOR_B) - ); - - // OPERATED_CONTRACT_C contract is operated by OPERATOR_C. - assert!( - pallet_contract_operator::ContractHasOperator::::contains_key(OPERATED_CONTRACT_C) - ); - assert_eq!( - pallet_contract_operator::ContractHasOperator::::get(&OPERATED_CONTRACT_C), - Some(OPERATOR_C) - ); - - // OPERATED_CONTRACT's contract Parameters is same test_params. - assert!( - pallet_contract_operator::ContractParameters::::contains_key(OPERATED_CONTRACT_A) - ); - assert_eq!( - pallet_contract_operator::ContractParameters::::get(&OPERATED_CONTRACT_A), - Some(test_params.clone()) - ); - - // OPERATED_CONTRACT_B's contract Parameters is same test_params. - assert!( - pallet_contract_operator::ContractParameters::::contains_key(OPERATED_CONTRACT_B) - ); - assert_eq!( - pallet_contract_operator::ContractParameters::::get(&OPERATED_CONTRACT_B), - Some(test_params.clone()) - ); - - // OPERATED_CONTRACT_C's contract Parameters is same test_params. - assert!( - pallet_contract_operator::ContractParameters::::contains_key(OPERATED_CONTRACT_C) - ); - assert_eq!( - pallet_contract_operator::ContractParameters::::get(&OPERATED_CONTRACT_C), - Some(test_params.clone()) - ); -} - -pub const PER_SESSION: u64 = 60 * 1000; - -pub fn advance_session() { - // increase block numebr - let next = System::block_number() + 1; - System::set_block_number(next); - // increase timestamp + 10 - let now_time = Timestamp::get(); - Timestamp::set_timestamp(now_time + PER_SESSION); - Session::rotate_session(); - assert_eq!(Session::current_index(), (next / Period::get()) as u32); - - // on finalize - PlasmRewards::on_finalize(next); -} - -pub fn advance_era() { - let current_era = PlasmRewards::current_era().unwrap(); - while current_era == PlasmRewards::current_era().unwrap() { - advance_session(); - } -} diff --git a/frame/dapps-staking/src/parameters.rs b/frame/dapps-staking/src/parameters.rs deleted file mode 100644 index 92621038db..0000000000 --- a/frame/dapps-staking/src/parameters.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! *Plasm Staking Parameters* -//! -//! Rewards_{option_{i,j}^{old}}=Rewards_{opeartor_{i}}\times \frac{stake_{i,j}^{old}}{\sum^{n^{old}}_{i,j}\sum^{m_i^{old}}_jstake_{i,j}^{old}}\times p^{old}_{operator_i} -//! -//! Used Perbil other parameters. -use codec::{Decode, Encode}; -use pallet_contract_operator::parameters::Verifiable; -#[cfg(feature = "std")] -use serde::{Deserialize, Serialize}; -use sp_runtime::{DispatchError, Perbill}; - -#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub struct StakingParameters { - /// If true, the operated contracts can be nominated else is can't. - pub can_be_nominated: bool, - /// Expired of that **option** can be exercised. - pub option_expired: u128, - /// For calculating option, **p**. - pub option_p: u32, -} - -impl Verifiable for StakingParameters { - fn verify(&self) -> Result<(), DispatchError> { - if self.option_p > Perbill::from_percent(20).deconstruct() { - Err("**p** of option's parameters must be lower than 20%(0_200_000_000)")? - } - Ok(()) - } -} - -#[cfg(feature = "std")] -impl std::fmt::Display for StakingParameters { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - -impl sp_std::fmt::Debug for StakingParameters { - #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { - write!(f, "{:?}", self) - } - - #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { - Ok(()) - } -} diff --git a/frame/dapps-staking/src/rewards.rs b/frame/dapps-staking/src/rewards.rs deleted file mode 100644 index d0aaab0c4b..0000000000 --- a/frame/dapps-staking/src/rewards.rs +++ /dev/null @@ -1,183 +0,0 @@ -//! This is explains plasm inflation models. -//! The staking has 2 kinds. -//! -//! 1. Validator Staking -//! 2. Dapps(Operator) Staking -//! -//! About each staking, this module computes issuing new tokens. - -use super::*; -use log::log2; -use num_traits::sign::Unsigned; -use sp_arithmetic::traits::{BaseArithmetic, SaturatedConversion}; - -/// Compute reards for dapps from total dapps rewards to operators and nominators. -pub trait ComputeRewardsForDapps { - fn compute_rewards_for_dapps(total_dapps_rewards: N) -> (N, N) - where - N: BaseArithmetic + Unsigned + Clone + From; - - fn compute_reward_for_nominator( - nominate_total: N, - total_staked: N, - nominators_reward: N, - staked_values: Vec<(N, N)>, - ) -> N - where - N: BaseArithmetic + Unsigned + Clone + From; - - fn compute_reward_for_operator( - staked_operator: N, - total_staked: N, - operators_reward: N, - ) -> N - where - N: BaseArithmetic + Unsigned + Clone + From; -} - -/// The based compute rewards for dapps. -/// Following of https://docs.plasmnet.io/learn/token-economy#inflation-model, `t = 4`. -pub struct BasedComputeRewardsForDapps; - -impl ComputeRewardsForDapps for BasedComputeRewardsForDapps { - fn compute_rewards_for_dapps(total_dapps_rewards: N) -> (N, N) - where - N: BaseArithmetic + Unsigned + Clone + From, - { - let operators_reward = - Perbill::from_rational_approximation(N::from(4 as u32), N::from(5 as u32)) - * total_dapps_rewards.clone(); - let nominators_reward = total_dapps_rewards - .checked_sub(&operators_reward) - .unwrap_or(N::zero()); - (operators_reward, nominators_reward) - } - - fn compute_reward_for_nominator( - nominate_total: N, - total_staked: N, - nominators_reward: N, - _: Vec<(N, N)>, - ) -> N - where - N: BaseArithmetic + Unsigned + Clone + From, - { - Perbill::from_rational_approximation(nominate_total, total_staked) * nominators_reward - } - - fn compute_reward_for_operator(staked_operator: N, total_staked: N, operators_reward: N) -> N - where - N: BaseArithmetic + Unsigned + Clone + From, - { - Perbill::from_rational_approximation(staked_operator, total_staked) * operators_reward - } -} - -pub struct VoidableRewardsForDapps; - -impl ComputeRewardsForDapps for VoidableRewardsForDapps { - /// distribute dapps rewards into 50% to operators and the other 50% to nominators - fn compute_rewards_for_dapps(total_dapps_rewards: N) -> (N, N) - where - N: BaseArithmetic + Unsigned + Clone + From, - { - let operators_reward = - Perbill::from_rational_approximation(N::from(1 as u32), N::from(2 as u32)) - * total_dapps_rewards.clone(); - let nominators_reward = total_dapps_rewards - .checked_sub(&operators_reward) - .unwrap_or(N::zero()); - (operators_reward, nominators_reward) - } - - /// Stakings that are less than 3% of total staking are ignored. - /// Nominators get paid according to the value of each staking value multiplied by the scaling value - /// Each scaling value is decided like the more staked contract becomes the fewer value. - /// - /// If you stake against contract A, which accounts for 10% of the total staking volume, - /// the scaling value alpha will be -1 * log(10/100) - /// In addition, multiply the staking value by the coefficient beta (= 0.197). - /// This is necessary to make alpha*beta closer to 1.0 when the ratio is 3%. - fn compute_reward_for_nominator( - _nominate_total: N, - total_staked: N, - nominators_reward: N, - staked_values: Vec<(N, N)>, - ) -> N - where - N: BaseArithmetic + Unsigned + Clone + From, - { - let threshold = total_staked.clone() * N::from(3 as u32) / N::from(100 as u32); - - let weighted_staking_total = staked_values - .iter() - .filter(|(total, _value)| threshold <= total.clone()) - .fold(N::from(0 as u32), |sum, (total, value)| { - // -1 * log2(p/q) = log2(q/p) - let alpha = N::from(log2( - total_staked.clone().saturated_into::(), - total.clone().saturated_into::(), - )); - sum + (value.clone().saturating_mul(alpha) / N::from(1_000 as u32)) - .saturating_mul(N::from(197 as u32)) - }); - Perbill::from_rational_approximation(weighted_staking_total, total_staked) - * N::from(1 as u32) - * nominators_reward - } - - fn compute_reward_for_operator(staked_operator: N, total_staked: N, operators_reward: N) -> N - where - N: BaseArithmetic + Unsigned + Clone + From, - { - Perbill::from_rational_approximation(staked_operator, total_staked) * operators_reward - } -} - -#[cfg(test)] -mod test { - use super::*; - fn compute_payout_test(total_dapps_tokens: N) -> (N, N) - where - N: BaseArithmetic + Unsigned + Clone + From, - { - BasedComputeRewardsForDapps::compute_rewards_for_dapps(total_dapps_tokens) - } - - fn compute_voidable_rewards_payout(total_dapps_tokens: N) -> (N, N) - where - N: BaseArithmetic + Unsigned + Clone + From, - { - VoidableRewardsForDapps::compute_rewards_for_dapps(total_dapps_tokens) - } - - #[test] - fn test_compute_payout_test() { - assert_eq!( - compute_payout_test(100_000_000u64), - (80_000_000, 20_000_000) - ); - - assert_eq!(compute_payout_test(10_000_000u64), (8_000_000, 2_000_000)); - - assert_eq!(compute_payout_test(11_111_111u64), (8_888_889, 2_222_222)); - } - - #[test] - fn test_compute_voidable_rewards_payout() { - assert_eq!( - compute_voidable_rewards_payout(100_000_000u64), - (50_000_000, 50_000_000) - ); - - assert_eq!( - compute_voidable_rewards_payout(10_000_000u64), - (5_000_000, 5_000_000) - ); - - assert_eq!( - compute_voidable_rewards_payout(11_111_111u64), - (5_555_555, 5_555_556) - ); - } -} diff --git a/frame/dapps-staking/src/tests.rs b/frame/dapps-staking/src/tests.rs deleted file mode 100644 index e9d84aa379..0000000000 --- a/frame/dapps-staking/src/tests.rs +++ /dev/null @@ -1,1007 +0,0 @@ -//! Tests for the dapps-staking module. - -#![cfg(test)] - -use super::*; -use crate::mock::*; -use frame_support::{assert_noop, assert_ok, traits::OnFinalize}; -use pallet_balances::{BalanceLock, Reasons}; -use pallet_plasm_rewards::traits::ComputeTotalPayout; -use sp_runtime::DispatchError; - -#[test] -fn bond_scenario_test() { - new_test_ext().execute_with(|| { - // bond ALICE -> BOB - assert_ok!(DappsStaking::bond( - Origin::signed(ALICE_STASH), - ALICE_CTRL, - 1000, - RewardDestination::Stash, - )); - assert_eq!(DappsStaking::bonded(ALICE_STASH), Some(ALICE_CTRL)); - assert_eq!(DappsStaking::bonded(ALICE_CTRL), None); - assert_eq!(DappsStaking::payee(ALICE_STASH), RewardDestination::Stash); - assert_eq!( - DappsStaking::ledger(ALICE_CTRL), - Some(StakingLedger { - stash: ALICE_STASH, - total: 1000, - active: 1000, - unlocking: vec![], - last_reward: Some(0), - }) - ); - assert_eq!(DappsStaking::ledger(ALICE_STASH), None); - assert_eq!( - Balances::locks(ALICE_STASH), - vec![BalanceLock { - id: STAKING_ID, - amount: 1000, - reasons: Reasons::All, - },] - ) - }) -} - -#[test] -fn bond_failed_test() { - new_test_ext().execute_with(|| { - assert_eq!( - DappsStaking::bond( - Origin::signed(ALICE_STASH), - ALICE_CTRL, - 9, - RewardDestination::Stash, - ), - Err(DispatchError::Other( - "can not bond with value less than minimum balance" - )) - ); - - success_first_bond(ALICE_STASH, ALICE_CTRL, 10, RewardDestination::Stash); - - assert_eq!( - DappsStaking::bond( - Origin::signed(ALICE_STASH), - ALICE_CTRL, - 100, - RewardDestination::Stash, - ), - Err(DispatchError::Other("stash already bonded")) - ); - - assert_eq!( - DappsStaking::bond( - Origin::signed(BOB_STASH), - ALICE_CTRL, - 100, - RewardDestination::Stash, - ), - Err(DispatchError::Other("controller already paired")) - ); - }); -} - -fn success_first_bond( - stash: AccountId, - ctrl: AccountId, - balance: Balance, - dest: RewardDestination, -) { - // bond ALICE -> BOB - assert_ok!(DappsStaking::bond( - Origin::signed(stash), - ctrl, - balance, - dest, - )); - assert_eq!(DappsStaking::bonded(stash), Some(ctrl)); - assert_eq!(DappsStaking::payee(stash), dest); - assert_eq!( - DappsStaking::ledger(ctrl), - Some(StakingLedger { - stash: stash, - total: balance, - active: balance, - unlocking: vec![], - last_reward: Some(0), - }) - ); - assert_eq!( - Balances::locks(stash), - vec![BalanceLock { - id: STAKING_ID, - amount: balance, - reasons: Reasons::All, - },] - ) -} - -#[test] -fn bond_extra_scenario_test() { - new_test_ext().execute_with(|| { - // success first bond BOB_STASH -> BOB_CTRL - success_first_bond(BOB_STASH, BOB_CTRL, 1000, RewardDestination::Stash); - - assert_ok!(DappsStaking::bond_extra(Origin::signed(BOB_STASH), 1000)); - assert_eq!(DappsStaking::bonded(BOB_STASH), Some(BOB_CTRL)); - assert_eq!(DappsStaking::payee(BOB_STASH), RewardDestination::Stash); - assert_eq!( - DappsStaking::ledger(BOB_CTRL), - Some(StakingLedger { - stash: BOB_STASH, - total: 2000, - active: 2000, - unlocking: vec![], - last_reward: Some(0), - }) - ); - assert_eq!( - Balances::locks(BOB_STASH), - vec![BalanceLock { - id: STAKING_ID, - amount: 2000, - reasons: Reasons::All, - },] - ); - }) -} - -#[test] -fn bond_extra_failed_test() { - new_test_ext().execute_with(|| { - assert_noop!( - DappsStaking::bond_extra(Origin::signed(BOB_STASH), 1000), - Error::::NotStash, - ); - >::insert(BOB_STASH, BOB_CTRL); - assert_noop!( - DappsStaking::bond_extra(Origin::signed(BOB_STASH), 1000), - Error::::NotController, - ); - }) -} - -#[test] -fn unbond_scenario_test() { - new_test_ext().execute_with(|| { - success_first_bond(BOB_STASH, BOB_CTRL, 1000, RewardDestination::Stash); - - assert_ok!(DappsStaking::unbond(Origin::signed(BOB_CTRL), 300)); - assert_eq!( - DappsStaking::ledger(BOB_CTRL), - Some(StakingLedger { - stash: BOB_STASH, - total: 1000, - active: 700, - unlocking: vec![UnlockChunk { - value: 300, - era: 3, // current_era(0) + bonding_duration(3) - }], - last_reward: Some(0), - }) - ); - assert_eq!( - Balances::locks(BOB_STASH), - vec![BalanceLock { - id: STAKING_ID, - amount: 1000, - reasons: Reasons::All, - },] - ); - - advance_era(); - - assert_ok!(DappsStaking::unbond(Origin::signed(BOB_CTRL), 200)); - assert_eq!( - DappsStaking::ledger(BOB_CTRL), - Some(StakingLedger { - stash: BOB_STASH, - total: 1000, - active: 500, - unlocking: vec![ - UnlockChunk { - value: 300, - era: 3, // current_era(0) + bonding_duration(3) - }, - UnlockChunk { - value: 200, - era: 4, // current_era(1) + bonding_duration(3) - } - ], - last_reward: Some(0), - }) - ); - assert_eq!( - Balances::locks(BOB_STASH), - vec![BalanceLock { - id: STAKING_ID, - amount: 1000, - reasons: Reasons::All, - },] - ); - }) -} - -fn success_unbond(ctrl: AccountId, balance: Balance) { - let now_ledger = DappsStaking::ledger(ctrl).unwrap(); - let now_unlock_chunk = now_ledger.unlocking; - let now_len = now_unlock_chunk.len(); - let current_era = PlasmRewards::current_era().unwrap(); - - assert_ok!(DappsStaking::unbond(Origin::signed(ctrl), balance)); - - let after_ledger = DappsStaking::ledger(ctrl).unwrap(); - let after_unlock_chunks = after_ledger.unlocking; - assert_eq!(now_unlock_chunk, after_unlock_chunks.split_at(now_len).0); - assert_eq!( - after_unlock_chunks[now_len], - UnlockChunk { - value: balance, - era: current_era + 3, // current_era(0) + bonding_duration(3) - } - ); - assert_eq!(now_ledger.total, after_ledger.total); - assert_eq!(now_ledger.active, after_ledger.active + balance); -} - -#[test] -fn unbond_failed_test() { - new_test_ext().execute_with(|| { - success_first_bond(BOB_STASH, BOB_CTRL, 1000, RewardDestination::Stash); - assert_noop!( - DappsStaking::unbond(Origin::signed(BOB_STASH), 300), - Error::::NotController, - ); - for _ in 0..32 { - success_unbond(BOB_CTRL, 10); - } - assert_noop!( - DappsStaking::unbond(Origin::signed(BOB_CTRL), 300), - Error::::NoMoreChunks, - ); - }) -} - -#[test] -fn withdraw_unbonded_scenario_test() { - new_test_ext().execute_with(|| { - success_first_bond(BOB_STASH, BOB_CTRL, 1000, RewardDestination::Stash); - success_unbond(BOB_CTRL, 300); - - // era 0 -> 1 - advance_era(); - - success_unbond(BOB_CTRL, 700); - - // era 1 -> 2 - advance_era(); - - assert_ok!(DappsStaking::withdraw_unbonded(Origin::signed(BOB_CTRL))); - assert_eq!( - DappsStaking::ledger(BOB_CTRL), - Some(StakingLedger { - stash: BOB_STASH, - total: 1000, - active: 0, - unlocking: vec![ - UnlockChunk { value: 300, era: 3 }, - UnlockChunk { value: 700, era: 4 }, - ], - last_reward: Some(0), - }) - ); - assert_eq!( - Balances::locks(BOB_STASH), - vec![BalanceLock { - id: STAKING_ID, - amount: 1000, - reasons: Reasons::All, - },] - ); - - // era 2 -> 3 - advance_era(); - - assert_ok!(DappsStaking::withdraw_unbonded(Origin::signed(BOB_CTRL))); - assert_eq!( - DappsStaking::ledger(BOB_CTRL), - Some(StakingLedger { - stash: BOB_STASH, - total: 700, - active: 0, - unlocking: vec![UnlockChunk { value: 700, era: 4 },], - last_reward: Some(0), - }) - ); - assert_eq!( - Balances::locks(BOB_STASH), - vec![BalanceLock { - id: STAKING_ID, - amount: 700, - reasons: Reasons::All, - },] - ); - - // era 3 -> 4 - advance_era(); - - assert_ok!(DappsStaking::withdraw_unbonded(Origin::signed(BOB_CTRL))); - assert_eq!(DappsStaking::ledger(BOB_CTRL), None); - assert_eq!(Balances::locks(BOB_STASH), vec![]); - }) -} - -#[test] -fn withdraw_unbonded_failed_test() { - new_test_ext().execute_with(|| { - success_first_bond(BOB_STASH, BOB_CTRL, 1000, RewardDestination::Stash); - success_unbond(BOB_CTRL, 300); - assert_noop!( - DappsStaking::withdraw_unbonded(Origin::signed(BOB_STASH)), - Error::::NotController, - ); - }) -} - -#[test] -fn nominate_contracts_scenario_test() { - new_test_ext().execute_with(|| { - valid_instatiate(); - success_first_bond(BOB_STASH, BOB_CTRL, 1000, RewardDestination::Stash); - assert_ok!(DappsStaking::nominate_contracts( - Origin::signed(BOB_CTRL), - vec![(OPERATED_CONTRACT_A, 1000)] - )); - assert_eq!( - DappsStaking::dapps_nominations(BOB_STASH), - Some(Nominations { - targets: vec![(OPERATED_CONTRACT_A, 1000)], - submitted_in: 0, - suppressed: false, - }) - ); - }) -} - -fn success_nominate_contracts(ctrl: AccountId, targets: Vec<(AccountId, Balance)>) { - assert_ok!(DappsStaking::nominate_contracts( - Origin::signed(ctrl), - targets.clone() - )); - let stash = DappsStaking::ledger(&ctrl).unwrap().stash; - let current_era = PlasmRewards::current_era().unwrap(); - assert_eq!( - DappsStaking::dapps_nominations(stash), - Some(Nominations { - targets: targets, - submitted_in: current_era, - suppressed: false, - }) - ); -} - -#[test] -fn nominate_contracts_failed_test() { - new_test_ext().execute_with(|| { - valid_instatiate(); - success_first_bond(BOB_STASH, BOB_CTRL, 1000, RewardDestination::Stash); - assert_noop!( - DappsStaking::nominate_contracts( - Origin::signed(BOB_STASH), - vec![(OPERATED_CONTRACT_A, 1_000)] - ), - Error::::NotController, - ); - assert_noop!( - DappsStaking::nominate_contracts(Origin::signed(BOB_CTRL), vec![]), - Error::::EmptyNominateTargets, - ); - assert_noop!( - DappsStaking::nominate_contracts(Origin::signed(BOB_CTRL), vec![(BOB_CONTRACT, 1_000)]), - Error::::NotOperatedContracts, - ); - assert_noop!( - DappsStaking::nominate_contracts( - Origin::signed(BOB_CTRL), - vec![(OPERATED_CONTRACT_A, 5_000)] - ), - Error::::NotEnoughStaking, - ); - }) -} - -#[test] -fn chill_scenario_test() { - new_test_ext().execute_with(|| { - valid_instatiate(); - success_first_bond(BOB_STASH, BOB_CTRL, 1000, RewardDestination::Stash); - success_nominate_contracts(BOB_CTRL, vec![(OPERATED_CONTRACT_A, 1000)]); - assert_ok!(DappsStaking::chill(Origin::signed(BOB_CTRL))); - assert_eq!(DappsStaking::dapps_nominations(BOB_STASH), None); - }) -} - -#[test] -fn chill_failed_test() { - new_test_ext().execute_with(|| { - valid_instatiate(); - success_first_bond(BOB_STASH, BOB_CTRL, 1000, RewardDestination::Stash); - success_nominate_contracts(BOB_CTRL, vec![(OPERATED_CONTRACT_A, 1000)]); - assert_noop!( - DappsStaking::chill(Origin::signed(BOB_STASH)), - Error::::NotController, - ); - }) -} - -#[test] -fn set_payee_scenario_test() { - new_test_ext().execute_with(|| { - success_first_bond(ALICE_STASH, ALICE_CTRL, 1000, RewardDestination::Stash); - assert_ok!(DappsStaking::set_payee( - Origin::signed(ALICE_CTRL), - RewardDestination::Controller - )); - assert_eq!( - DappsStaking::payee(ALICE_STASH), - RewardDestination::Controller - ); - }) -} - -#[test] -fn set_payee_failed_test() { - new_test_ext().execute_with(|| { - success_first_bond(ALICE_STASH, ALICE_CTRL, 1000, RewardDestination::Stash); - assert_noop!( - DappsStaking::set_payee(Origin::signed(ALICE_STASH), RewardDestination::Controller), - Error::::NotController, - ); - }) -} - -#[test] -fn set_controller_scenario_test() { - new_test_ext().execute_with(|| { - success_first_bond(ALICE_STASH, ALICE_CTRL, 1000, RewardDestination::Stash); - assert_ok!(DappsStaking::set_controller( - Origin::signed(ALICE_STASH), - BOB_CTRL - )); - assert_eq!(DappsStaking::bonded(ALICE_STASH), Some(BOB_CTRL)); - assert_eq!( - DappsStaking::ledger(BOB_CTRL), - Some(StakingLedger { - stash: ALICE_STASH, - total: 1000, - active: 1000, - unlocking: vec![], - last_reward: Some(0), - }) - ); - assert_eq!(DappsStaking::ledger(ALICE_CTRL), None); - }) -} - -#[test] -fn set_controller_failed_test() { - new_test_ext().execute_with(|| { - success_first_bond(ALICE_STASH, ALICE_CTRL, 1000, RewardDestination::Stash); - assert_noop!( - DappsStaking::set_controller(Origin::signed(ALICE_CTRL), BOB_CTRL), - Error::::NotStash, - ); - success_first_bond(BOB_STASH, BOB_CTRL, 1000, RewardDestination::Stash); - assert_noop!( - DappsStaking::set_controller(Origin::signed(ALICE_STASH), BOB_CTRL), - "controller already paired", - ); - }) -} - -const SIX_HOURS: u64 = 6 * 60 * 60 * 1000; - -#[test] -fn reward_test() { - new_test_ext().execute_with(|| { - valid_instatiate(); - assert_ok!(Operator::change_operator( - Origin::signed(OPERATOR_A), - vec![OPERATED_CONTRACT_A], - ALICE_STASH - )); - success_first_bond(BOB_STASH, BOB_CTRL, 1_000, RewardDestination::Stash); - success_first_bond( - ALICE_STASH, - ALICE_CTRL, - 1_000, - RewardDestination::Controller, - ); - success_nominate_contracts(BOB_CTRL, vec![(OPERATED_CONTRACT_A, 1_000)]); - success_nominate_contracts(ALICE_CTRL, vec![(OPERATED_CONTRACT_A, 1_000)]); - success_nominate_contracts(ALICE_CTRL, vec![(OPERATED_CONTRACT_B, 1_000)]); - - let current_era = PlasmRewards::current_era().unwrap(); - assert_eq!(DappsStaking::eras_total_stake(current_era), 0); - assert_eq!(DappsStaking::eras_total_stake(current_era + 1), 3_000); - - advance_era(); - - let pre_total_issuarance = Balances::total_issuance(); - let (_, b) = ::ComputeTotalPayout::compute( - pre_total_issuarance, - SIX_HOURS, - 0, - 0, - ); - - advance_session(); - - let current_era = PlasmRewards::current_era().unwrap(); - ErasVotes::::insert( - current_era - 1, - OPERATED_CONTRACT_A, - VoteCounts { bad: 3, good: 12 }, - ); - ErasVotes::::insert( - current_era, - OPERATED_CONTRACT_A, - VoteCounts { bad: 3, good: 12 }, - ); - ErasVotes::::insert( - current_era - 1, - OPERATED_CONTRACT_B, - VoteCounts { bad: 3, good: 12 }, - ); - ErasVotes::::insert( - current_era, - OPERATED_CONTRACT_B, - VoteCounts { bad: 3, good: 12 }, - ); - let positive_imbalance_a = - DappsStaking::reward_nominator(¤t_era, b, &BOB_STASH, &OPERATED_CONTRACT_A); - let positive_imbalance_b = - DappsStaking::reward_nominator(¤t_era, b, &BOB_STASH, &OPERATED_CONTRACT_B); - assert_eq!(Balances::free_balance(&BOB_STASH), 2_000 + 343); // +nomiante reward - assert_eq!(Balances::free_balance(&BOB_CTRL), 20 + 0); // +0 - assert_eq!(positive_imbalance_a, 343); - assert_eq!(positive_imbalance_b, 0); - assert_eq!(Balances::total_issuance(), pre_total_issuarance + 343); - - let positive_imbalance_a = - DappsStaking::reward_operator(¤t_era, b, &ALICE_STASH, &OPERATED_CONTRACT_A); - assert_eq!(Balances::free_balance(&ALICE_STASH), 1_000 + 228); // +operator reward - assert_eq!(positive_imbalance_a, 228); - assert_eq!(Balances::total_issuance(), pre_total_issuarance + 571); - - let positive_imbalance_a = - DappsStaking::reward_nominator(¤t_era, b, &ALICE_STASH, &OPERATED_CONTRACT_A); - assert_eq!(Balances::free_balance(&ALICE_CTRL), 10 + 343); // +nominate reward - assert_eq!(positive_imbalance_a, 343); - assert_eq!(Balances::total_issuance(), pre_total_issuarance + 914); - }) -} - -#[test] -fn new_session_scenario_test() { - new_test_ext().execute_with(|| { - advance_session(); - valid_instatiate(); - assert_ok!(Operator::change_operator( - Origin::signed(OPERATOR_A), - vec![OPERATED_CONTRACT_A], - ALICE_STASH - )); - assert_ok!(Operator::change_operator( - Origin::signed(OPERATOR_B), - vec![OPERATED_CONTRACT_B], - ALICE_STASH - )); - assert_ok!(Operator::change_operator( - Origin::signed(OPERATOR_C), - vec![OPERATED_CONTRACT_C], - ALICE_STASH - )); - success_first_bond(BOB_STASH, BOB_CTRL, 1_000, RewardDestination::Stash); - success_first_bond( - ALICE_STASH, - ALICE_CTRL, - 1_000, - RewardDestination::Controller, - ); - success_nominate_contracts(BOB_CTRL, vec![(OPERATED_CONTRACT_A, 1_000)]); - success_nominate_contracts(ALICE_CTRL, vec![(OPERATED_CONTRACT_A, 1_000)]); - success_nominate_contracts(ALICE_CTRL, vec![(OPERATED_CONTRACT_B, 1_000)]); - success_nominate_contracts(ALICE_CTRL, vec![(OPERATED_CONTRACT_C, 1_000)]); - - let current_era = PlasmRewards::current_era().unwrap(); - assert_eq!(DappsStaking::eras_total_stake(current_era), 0); - assert_eq!(DappsStaking::eras_total_stake(current_era + 1), 4_000); - let target_era = current_era + 1; - - advance_era(); - DappsStaking::on_finalize(0); - advance_session(); - - let pre_total_issuarance = Balances::total_issuance(); - assert_eq!(Balances::free_balance(&BOB_STASH), 2_000); - assert_eq!(Balances::free_balance(&BOB_CTRL), 20); - assert_eq!(Balances::free_balance(&ALICE_STASH), 1_000); - assert_eq!(Balances::free_balance(&ALICE_CTRL), 10); - assert_eq!(pre_total_issuarance, 5_003_030); - - advance_era(); - DappsStaking::on_finalize(0); - advance_session(); - - ErasVotes::::insert( - target_era - 1, - OPERATED_CONTRACT_A, - VoteCounts { bad: 3, good: 12 }, - ); - ErasVotes::::insert( - target_era, - OPERATED_CONTRACT_A, - VoteCounts { bad: 3, good: 12 }, - ); - ErasVotes::::insert( - target_era - 1, - OPERATED_CONTRACT_B, - VoteCounts { bad: 3, good: 12 }, - ); - ErasVotes::::insert( - target_era, - OPERATED_CONTRACT_B, - VoteCounts { bad: 3, good: 12 }, - ); - ErasVotes::::insert( - target_era - 1, - OPERATED_CONTRACT_C, - VoteCounts { bad: 3, good: 12 }, - ); - ErasVotes::::insert( - target_era, - OPERATED_CONTRACT_C, - VoteCounts { bad: 3, good: 12 }, - ); - - assert_ok!(DappsStaking::claim( - Origin::signed(BOB_STASH), - OPERATED_CONTRACT_A, - target_era - )); - assert_ok!(DappsStaking::claim( - Origin::signed(BOB_STASH), - OPERATED_CONTRACT_B, - target_era - )); - - // OPERATED_CONTRACT_C has not been claimed yet - - assert_eq!(Balances::free_balance(&BOB_STASH), 2_000 + 10); // +nomiante reward - assert_eq!(Balances::free_balance(&BOB_CTRL), 20 + 0); // +0 - - assert_eq!(Balances::free_balance(&ALICE_STASH), 1_000 + 6); // +operator reward - assert_eq!(Balances::free_balance(&ALICE_CTRL), 10 + 20); // +nominate reward - assert_eq!(Balances::total_issuance(), 5_003_030 + 36); - - assert_ok!(DappsStaking::claim( - Origin::signed(BOB_STASH), - OPERATED_CONTRACT_C, - target_era - )); - - assert_eq!(Balances::free_balance(&ALICE_STASH), 1_000 + 8); // +operator reward - assert_eq!(Balances::free_balance(&ALICE_CTRL), 10 + 30); // +nominate reward - }) -} - -#[test] -fn ignore_nomination_test() { - new_test_ext().execute_with(|| { - advance_session(); - valid_instatiate(); - assert_ok!(Operator::change_operator( - Origin::signed(OPERATOR_A), - vec![OPERATED_CONTRACT_A], - ALICE_STASH - )); - success_first_bond(BOB_STASH, BOB_CTRL, 1_000, RewardDestination::Stash); - success_first_bond( - ALICE_STASH, - ALICE_CTRL, - 1_000, - RewardDestination::Controller, - ); - success_nominate_contracts(BOB_CTRL, vec![(OPERATED_CONTRACT_A, 1_000)]); - success_nominate_contracts(ALICE_CTRL, vec![(OPERATED_CONTRACT_A, 1_000)]); - success_nominate_contracts(ALICE_CTRL, vec![(OPERATED_CONTRACT_B, 1)]); - - let current_era = PlasmRewards::current_era().unwrap(); - assert_eq!(DappsStaking::eras_total_stake(current_era), 0); - assert_eq!(DappsStaking::eras_total_stake(current_era + 1), 2_001); - let target_era = current_era + 1; - - advance_era(); - DappsStaking::on_finalize(0); - advance_session(); - - let pre_total_issuarance = Balances::total_issuance(); - assert_eq!(Balances::free_balance(&BOB_STASH), 2_000); - assert_eq!(Balances::free_balance(&BOB_CTRL), 20); - assert_eq!(Balances::free_balance(&ALICE_STASH), 1_000); - assert_eq!(Balances::free_balance(&ALICE_CTRL), 10); - assert_eq!(pre_total_issuarance, 5_003_030); - - advance_era(); - DappsStaking::on_finalize(0); - advance_session(); - - ErasVotes::::insert( - target_era - 1, - OPERATED_CONTRACT_A, - VoteCounts { bad: 3, good: 12 }, - ); - ErasVotes::::insert( - target_era, - OPERATED_CONTRACT_A, - VoteCounts { bad: 3, good: 12 }, - ); - ErasVotes::::insert( - target_era - 1, - OPERATED_CONTRACT_B, - VoteCounts { bad: 3, good: 12 }, - ); - ErasVotes::::insert( - target_era, - OPERATED_CONTRACT_B, - VoteCounts { bad: 3, good: 12 }, - ); - - assert_ok!(DappsStaking::claim( - Origin::signed(BOB_STASH), - OPERATED_CONTRACT_A, - target_era, - )); - - assert_ok!(DappsStaking::claim( - Origin::signed(BOB_STASH), - OPERATED_CONTRACT_B, - target_era, - )); - - assert_eq!(Balances::free_balance(&BOB_STASH), 2_000 + 10); // +nomiante reward - assert_eq!(Balances::free_balance(&BOB_CTRL), 20 + 0); // +0 - - assert_eq!(Balances::free_balance(&ALICE_STASH), 1_000 + 9); // +operator reward - assert_eq!(Balances::free_balance(&ALICE_CTRL), 10 + 10); // +nominate reward - assert_eq!(Balances::total_issuance(), 5_003_030 + 29); - }) -} - -#[test] -fn vote_contracts_test() { - new_test_ext().execute_with(|| { - advance_session(); - valid_instatiate(); - let current_era = PlasmRewards::current_era().unwrap(); - - assert_ok!(DappsStaking::vote_contracts( - Origin::signed(ALICE_CTRL), - vec![(OPERATED_CONTRACT_A, Vote::Good)] - )); - assert_eq!( - DappsStaking::accounts_vote(ALICE_CTRL, OPERATED_CONTRACT_A), - VoteCounts { bad: 0, good: 1 } - ); - assert_eq!( - DappsStaking::eras_votes(current_era + 1, OPERATED_CONTRACT_A), - VoteCounts { bad: 0, good: 1 } - ); - - assert_ok!(DappsStaking::vote_contracts( - Origin::signed(ALICE_CTRL), - vec![(OPERATED_CONTRACT_A, Vote::Bad)] - )); - assert_eq!( - DappsStaking::accounts_vote(ALICE_CTRL, OPERATED_CONTRACT_A), - VoteCounts { bad: 1, good: 0 } - ); - assert_eq!( - DappsStaking::eras_votes(current_era + 1, OPERATED_CONTRACT_A), - VoteCounts { bad: 1, good: 0 } - ); - - assert_ok!(DappsStaking::vote_contracts( - Origin::signed(BOB_CTRL), - vec![(OPERATED_CONTRACT_A, Vote::Good)] - )); - assert_eq!( - DappsStaking::accounts_vote(BOB_CTRL, OPERATED_CONTRACT_A), - VoteCounts { bad: 0, good: 1 } - ); - assert_eq!( - DappsStaking::eras_votes(current_era + 1, OPERATED_CONTRACT_A), - VoteCounts { bad: 1, good: 1 } - ); - - assert_eq!( - DappsStaking::has_votes_requirement(&OPERATED_CONTRACT_A, &(current_era + 1)), - false - ); - assert_eq!( - DappsStaking::has_votes_requirement(&OPERATED_CONTRACT_B, &(current_era + 1)), - false - ); - - ErasVotes::::insert( - current_era + 1, - OPERATED_CONTRACT_A, - VoteCounts { bad: 3, good: 12 }, - ); - assert_eq!( - DappsStaking::has_votes_requirement(&OPERATED_CONTRACT_A, &(current_era + 1)), - true - ); - }) -} - -#[test] -fn is_rewardable_test() { - new_test_ext().execute_with(|| { - let current_era = PlasmRewards::current_era().unwrap(); - - ErasVotes::::insert( - current_era + 1, - OPERATED_CONTRACT_A, - VoteCounts { bad: 3, good: 12 }, - ); - - assert_eq!( - DappsStaking::is_rewardable(&OPERATED_CONTRACT_A, ¤t_era), - false - ); - assert_eq!( - DappsStaking::is_rewardable(&OPERATED_CONTRACT_A, &(current_era + 1)), - false - ); - assert_eq!( - DappsStaking::is_rewardable(&OPERATED_CONTRACT_A, &(current_era + 2)), - false - ); - - ErasVotes::::insert( - current_era + 2, - OPERATED_CONTRACT_A, - VoteCounts { bad: 3, good: 12 }, - ); - - assert_eq!( - DappsStaking::is_rewardable(&OPERATED_CONTRACT_A, &(current_era + 1)), - false - ); - assert_eq!( - DappsStaking::is_rewardable(&OPERATED_CONTRACT_A, &(current_era + 2)), - true - ); - }) -} - -#[test] -fn is_locked_test() { - new_test_ext().execute_with(|| { - let current_era = PlasmRewards::current_era().unwrap(); - - ErasVotes::::insert( - current_era + 1, - OPERATED_CONTRACT_A, - VoteCounts { bad: 3, good: 12 }, - ); - - assert_eq!( - DappsStaking::is_locked(&OPERATED_CONTRACT_A, ¤t_era), - false - ); - assert_eq!( - DappsStaking::is_locked(&OPERATED_CONTRACT_A, &(current_era + 1)), - false - ); - assert_eq!( - DappsStaking::is_locked(&OPERATED_CONTRACT_A, &(current_era + 2)), - false - ); - - ErasVotes::::insert( - current_era + 2, - OPERATED_CONTRACT_A, - VoteCounts { bad: 3, good: 12 }, - ); - - assert_eq!( - DappsStaking::is_locked(&OPERATED_CONTRACT_A, &(current_era + 1)), - false - ); - assert_eq!( - DappsStaking::is_locked(&OPERATED_CONTRACT_A, &(current_era + 2)), - false - ); - - ErasVotes::::insert( - current_era + 1, - OPERATED_CONTRACT_A, - VoteCounts { bad: 5, good: 9 }, - ); - - assert_eq!( - DappsStaking::is_locked(&OPERATED_CONTRACT_A, &(current_era + 1)), - false - ); - assert_eq!( - DappsStaking::is_locked(&OPERATED_CONTRACT_A, &(current_era + 2)), - true - ); - }) -} - -#[test] -fn is_slashable_test() { - new_test_ext().execute_with(|| { - let current_era = PlasmRewards::current_era().unwrap(); - - ErasVotes::::insert( - current_era + 1, - OPERATED_CONTRACT_A, - VoteCounts { bad: 3, good: 12 }, - ); - - assert_eq!( - DappsStaking::is_slashable(&OPERATED_CONTRACT_A, ¤t_era), - false - ); - assert_eq!( - DappsStaking::is_slashable(&OPERATED_CONTRACT_A, &(current_era + 1)), - false - ); - assert_eq!( - DappsStaking::is_slashable(&OPERATED_CONTRACT_A, &(current_era + 2)), - false - ); - - ErasVotes::::insert( - current_era + 2, - OPERATED_CONTRACT_A, - VoteCounts { bad: 3, good: 12 }, - ); - - assert_eq!( - DappsStaking::is_slashable(&OPERATED_CONTRACT_A, &(current_era + 1)), - false - ); - assert_eq!( - DappsStaking::is_slashable(&OPERATED_CONTRACT_A, &(current_era + 2)), - false - ); - - ErasVotes::::insert( - current_era + 1, - OPERATED_CONTRACT_A, - VoteCounts { bad: 10, good: 9 }, - ); - ErasVotes::::insert( - current_era + 2, - OPERATED_CONTRACT_A, - VoteCounts { bad: 10, good: 9 }, - ); - - assert_eq!( - DappsStaking::is_slashable(&OPERATED_CONTRACT_A, &(current_era + 1)), - false - ); - assert_eq!( - DappsStaking::is_slashable(&OPERATED_CONTRACT_A, &(current_era + 2)), - true - ); - }) -} diff --git a/frame/operator/Cargo.toml b/frame/operator/Cargo.toml deleted file mode 100644 index d53113b062..0000000000 --- a/frame/operator/Cargo.toml +++ /dev/null @@ -1,48 +0,0 @@ -[package] -name = "pallet-contract-operator" -version = "1.7.0" -authors = ["Stake Technologies "] -edition = "2018" -license = "Apache-2.0" -homepage = "https://docs.plasmnet.io/" -repository = "https://github.com/staketechnologies/Plasm/" -description = "FRAME pallet to manage operator developing smart contracts" - -[dependencies] -codec = { package = "parity-scale-codec", version = "1.3.5", features = ["derive"], default-features = false } -serde = { version = "1.0.106", features = ["derive"], optional = true } - -sp-core = { version = "2.0.0", default_features = false } -sp-runtime = { version = "2.0.0", default_features = false } -sp-io = { version = "2.0.0", default_features = false } -sp-std = { version = "2.0.0", default_features = false } -pallet-balances = { version = "2.0.0", default_features = false } -frame-support = { version = "2.0.0", default_features = false } -pallet-timestamp = { version = "2.0.0", default_features = false } -frame-system = { version = "2.0.0", default_features = false } -pallet-contracts = { version = "2.0.0", default_features = false } -pallet-plasm-support = { path = "../plasm-support", version = "1.7.0", default_features = false } - -[dev-dependencies] -wabt = "0.10.0" -derive_more = "0.14.0" -hex-literal = "0.2.1" -pallet-randomness-collective-flip = "2.0.0" -pallet-transaction-payment = "2.0.0" - -[features] -default = ["std"] -std = [ - "serde", - "codec/std", - "sp-core/std", - "sp-runtime/std", - "sp-io/std", - "sp-std/std", - "pallet-balances/std", - "frame-support/std", - "pallet-timestamp/std", - "frame-system/std", - "pallet-contracts/std", - "pallet-plasm-support/std", -] diff --git a/frame/operator/src/lib.rs b/frame/operator/src/lib.rs deleted file mode 100644 index c2ba6c0abb..0000000000 --- a/frame/operator/src/lib.rs +++ /dev/null @@ -1,186 +0,0 @@ -#![cfg_attr(not(feature = "std"), no_std)] - -use frame_support::dispatch::UnfilteredDispatchable; -use frame_support::{decl_event, decl_module, decl_storage, Parameter}; -use frame_system::{ensure_signed, RawOrigin}; -use pallet_contracts::{BalanceOf, CodeHash, ContractAddressFor, Gas}; -use sp_runtime::traits::{MaybeDisplay, MaybeSerialize, Member}; -use sp_std::prelude::*; - -pub mod parameters; -#[cfg(test)] -mod tests; - -use crate::parameters::Verifiable; - -use pallet_plasm_support::{ContractFinder, OperatorFinder, TransferOperator}; - -/// The module's configuration trait. -pub trait Trait: pallet_contracts::Trait { - type Parameters: Parameter - + Member - + MaybeSerialize - + MaybeDisplay - + Default - + sp_std::hash::Hash - + parameters::Verifiable; - - /// The overarching event type. - type Event: From> + Into<::Event>; -} - -// This module's storage items. -decl_storage! { - trait Store for Module as Operator { - /// A mapping from operators to operated contracts by them. - pub OperatorHasContracts get(fn operator_has_contracts): map hasher(blake2_128_concat) - T::AccountId => Vec; - /// A mapping from operated contract by operator to it. - pub ContractHasOperator get(fn contract_has_operator): map hasher(blake2_128_concat) - T::AccountId => Option; - /// A mapping from contract to it's parameters. - pub ContractParameters get(fn contract_parameters): map hasher(blake2_128_concat) - T::AccountId => Option; - } -} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - // Initializing events - // this is needed only if you are using events in your module - fn deposit_event() = default; - - /// Deploys a contact and insert relation of a contract and an operator to mapping. - #[weight = *gas_limit] - pub fn instantiate( - origin, - #[compact] endowment: BalanceOf, - #[compact] gas_limit: Gas, - code_hash: CodeHash, - data: Vec, - parameters: T::Parameters, - ) { - let operator = ensure_signed(origin)?; - - // verify parameters. - parameters.verify()?; - - let contract = T::DetermineContractAddress::contract_address_for(&code_hash, &data, &operator); - pallet_contracts::Call::::instantiate(endowment, gas_limit, code_hash, data) - .dispatch_bypass_filter(RawOrigin::Signed(operator.clone()).into()) - .map_err(|e| e.error)?; - - // add operator to contracts - >::mutate(&operator, |tree| (*tree).push(contract.clone())); - // add contract to operator - >::insert(&contract, operator.clone()); - // add contract to parameters - >::insert(&contract, parameters); - - // issue an event operator -> contract - Self::deposit_event(RawEvent::SetOperator(operator, contract)); - } - - /// Updates parameters for an identified contact. - /// TODO: weight - #[weight = 50_000] - pub fn update_parameters( - origin, - contract: T::AccountId, - parameters: T::Parameters, - ) { - let operator = ensure_signed(origin)?; - - // verify parameters - parameters.verify()?; - - let contracts = >::get(&operator); - - // check the actually operate the contract. - if !contracts.contains(&contract) { - Err("The sender don't operate the contract address.")? - } - - // update parameters - >::insert(&contract, parameters.clone()); - // issue set parameter events - Self::deposit_event(RawEvent::SetParameters(contract, parameters)); - } - - /// Changes an operator for identified contracts. - /// TODO: weight - #[weight = 100_000] - pub fn change_operator( - origin, - contracts: Vec, - new_operator: T::AccountId, - ) { - let operator = ensure_signed(origin)?; - Self::transfer_operator(operator, contracts, new_operator)?; - } - } -} - -decl_event!( - pub enum Event - where - AccountId = ::AccountId, - Parameters = ::Parameters, - { - /// When operator changed, - /// it is issued that 1-st Operator AccountId and 2-nd Contract AccountId. - SetOperator(AccountId, AccountId), - - /// When contract's parameters changed, - /// it is issued that 1-st Contract AccountId and 2-nd the contract's new parameters. - SetParameters(AccountId, Parameters), - } -); - -impl ContractFinder for Module { - fn is_exists_contract(contract_id: &T::AccountId) -> bool { - >::contains_key(contract_id) - } - fn operator(contract_id: &T::AccountId) -> Option { - >::get(contract_id) - } - fn parameters(contract_id: &T::AccountId) -> Option { - >::get(contract_id) - } -} -impl OperatorFinder for Module { - fn contracts(operator_id: &T::AccountId) -> Vec { - >::get(operator_id) - } -} - -impl TransferOperator for Module { - /// Force Changes an operator for identified contracts without verify. - fn force_transfer_operator( - current_operator: T::AccountId, - contracts: Vec, - new_operator: T::AccountId, - ) { - // remove origin operator to contracts - >::mutate(¤t_operator, |tree| { - *tree = tree - .iter() - .filter(|&x| !contracts.contains(x)) - .cloned() - .collect() - }); - - // add new_operator to contracts - >::mutate(&new_operator, |tree| { - for c in contracts.iter() { - (*tree).push(c.clone()); - } - }); - for c in contracts.iter() { - // add contract to new_operator - >::insert(&c, new_operator.clone()); - // issue an event operator -> contract - Self::deposit_event(RawEvent::SetOperator(new_operator.clone(), c.clone())); - } - } -} diff --git a/frame/operator/src/parameters.rs b/frame/operator/src/parameters.rs deleted file mode 100644 index 0c005b8b98..0000000000 --- a/frame/operator/src/parameters.rs +++ /dev/null @@ -1,41 +0,0 @@ -use codec::{Decode, Encode}; -#[cfg(feature = "std")] -use serde::{Deserialize, Serialize}; -use sp_runtime::DispatchError; - -pub trait Verifiable { - fn verify(&self) -> Result<(), DispatchError>; -} - -#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub struct DefaultParameters { - pub can_be_nominated: bool, - pub option_expired: u128, - pub option_p: u128, -} - -impl Verifiable for DefaultParameters { - fn verify(&self) -> Result<(), DispatchError> { - Ok(()) - } -} - -#[cfg(feature = "std")] -impl std::fmt::Display for DefaultParameters { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{:?}", self) - } -} - -impl sp_std::fmt::Debug for DefaultParameters { - #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { - write!(f, "{:?}", self) - } - - #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { - Ok(()) - } -} diff --git a/frame/operator/src/tests.rs b/frame/operator/src/tests.rs deleted file mode 100644 index 6e1d90afec..0000000000 --- a/frame/operator/src/tests.rs +++ /dev/null @@ -1,962 +0,0 @@ -// TODO: #1417 Add more integration tests -// also remove the #![allow(unused)] below. - -#![allow(unused)] - -use super::*; -use codec::{Decode, Encode, KeyedVec}; -use frame_support::{ - assert_err, assert_ok, impl_outer_dispatch, impl_outer_event, impl_outer_origin, - parameter_types, - storage::child, - traits::{Currency, Get}, - weights::{DispatchClass, DispatchInfo, WeightToFeeCoefficients, WeightToFeePolynomial}, - StorageMap, StorageValue, -}; -use frame_system::{self as system, EventRecord, Phase}; -use hex_literal::*; -use pallet_balances as balances; -use pallet_contracts::Gas; -use pallet_contracts::{ - self as contracts, BalanceOf, ContractAddressFor, ContractInfo, ContractInfoOf, - RawAliveContractInfo, Schedule, TrieId, TrieIdFromParentCounter, TrieIdGenerator, -}; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; -use sp_core::storage::well_known_keys; -use sp_runtime::{ - testing::{Digest, DigestItem, Header, UintAuthorityId, H256}, - traits::{BlakeTwo256, Hash, IdentityLookup, SignedExtension}, - BuildStorage, DispatchError, Perbill, -}; -use std::{ - cell::RefCell, - sync::atomic::{AtomicUsize, Ordering}, -}; - -mod operator { - // Re-export contents of the root. This basically - // needs to give a name for the current crate. - // This hack is required for `impl_outer_event!`. - pub use super::super::*; - use frame_support::impl_outer_event; -} -impl_outer_event! { - pub enum MetaEvent for Test { - system, - balances, - contracts, - operator, - } -} -impl_outer_origin! { - pub enum Origin for Test { } -} -impl_outer_dispatch! { - pub enum Call for Test where origin: Origin { - balances::Balances, - contracts::Contracts, - } -} - -thread_local! { - static EXISTENTIAL_DEPOSIT: RefCell = RefCell::new(0); - static BLOCK_GAS_LIMIT: RefCell = RefCell::new(0); -} - -pub struct ExistentialDeposit; - -impl Get for ExistentialDeposit { - fn get() -> u64 { - EXISTENTIAL_DEPOSIT.with(|v| *v.borrow()) - } -} - -pub struct BlockGasLimit; - -impl Get for BlockGasLimit { - fn get() -> u64 { - BLOCK_GAS_LIMIT.with(|v| *v.borrow()) - } -} - -#[derive(Clone, Eq, PartialEq, Debug)] -pub struct Test; -parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: u32 = 1024; - pub const MaximumBlockLength: u32 = 2 * 1024; - pub const AvailableBlockRatio: Perbill = Perbill::one(); -} -impl frame_system::Trait for Test { - type Origin = Origin; - type BaseCallFilter = (); - type Index = u64; - type BlockNumber = u64; - type Hash = H256; - type Call = Call; - type Hashing = BlakeTwo256; - type AccountId = u64; - type Lookup = IdentityLookup; - type Header = Header; - type Event = MetaEvent; - type BlockHashCount = BlockHashCount; - type MaximumBlockWeight = MaximumBlockWeight; - type AvailableBlockRatio = AvailableBlockRatio; - type MaximumBlockLength = MaximumBlockLength; - type Version = (); - type PalletInfo = (); - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = (); - type SystemWeightInfo = (); -} - -impl pallet_balances::Trait for Test { - type Balance = u64; - type Event = MetaEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Module; - type WeightInfo = (); - type MaxLocks = (); -} - -parameter_types! { - pub const MinimumPeriod: u64 = 1; -} - -impl pallet_timestamp::Trait for Test { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); -} - -pub struct WeightToFee; -impl WeightToFeePolynomial for WeightToFee { - type Balance = u64; - fn polynomial() -> WeightToFeeCoefficients { - Default::default() - } -} - -parameter_types! { - pub const TransactionByteFee: u64 = 0; -} - -impl pallet_transaction_payment::Trait for Test { - type Currency = Balances; - type OnTransactionPayment = (); - type TransactionByteFee = TransactionByteFee; - type WeightToFee = WeightToFee; - type FeeMultiplierUpdate = (); -} - -parameter_types! { - pub const SignedClaimHandicap: u64 = 2; - pub const TombstoneDeposit: u64 = 16; - pub const StorageSizeOffset: u32 = 8; - pub const RentByteFee: u64 = 4; - pub const RentDepositOffset: u64 = 10_000; - pub const SurchargeReward: u64 = 150; -} - -impl pallet_contracts::Trait for Test { - type Time = Timestamp; - type Randomness = Randomness; - type Currency = Balances; - type DetermineContractAddress = DummyContractAddressFor; - type Event = MetaEvent; - type TrieIdGenerator = DummyTrieIdGenerator; - type RentPayment = (); - type SignedClaimHandicap = SignedClaimHandicap; - type TombstoneDeposit = TombstoneDeposit; - type StorageSizeOffset = StorageSizeOffset; - type RentByteFee = RentByteFee; - type RentDepositOffset = RentDepositOffset; - type SurchargeReward = SurchargeReward; - type MaxDepth = pallet_contracts::DefaultMaxDepth; - type MaxValueSize = pallet_contracts::DefaultMaxValueSize; - type WeightPrice = pallet_transaction_payment::Module; -} - -#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, Hash)] -#[cfg_attr( - feature = "std", - derive(Debug, Serialize, Deserialize, derive_more::Display) -)] -pub struct TestParameters { - pub a: u128, -} - -const TEST_MAX_PARAMS_A: u128 = 1000_000_000_000; - -impl parameters::Verifiable for TestParameters { - fn verify(&self) -> Result<(), DispatchError> { - if self.a > TEST_MAX_PARAMS_A { - return Err(DispatchError::Other("over max params.")); - } - Ok(()) - } -} - -impl Trait for Test { - type Parameters = TestParameters; - type Event = MetaEvent; -} - -type Balances = pallet_balances::Module; -type Timestamp = pallet_timestamp::Module; -type Contracts = pallet_contracts::Module; -type System = frame_system::Module; -type Randomness = pallet_randomness_collective_flip::Module; -type Operator = Module; - -pub struct DummyContractAddressFor; - -impl ContractAddressFor for DummyContractAddressFor { - fn contract_address_for(_code_hash: &H256, _data: &[u8], origin: &u64) -> u64 { - *origin + 1 - } -} - -pub struct DummyTrieIdGenerator; - -impl TrieIdGenerator for DummyTrieIdGenerator { - fn trie_id(account_id: &u64) -> TrieId { - use sp_core::storage::well_known_keys; - - let new_seed = pallet_contracts::AccountCounter::mutate(|v| { - *v = v.wrapping_add(1); - *v - }); - - // TODO: see https://github.com/paritytech/substrate/issues/2325 - let mut res = vec![]; - res.extend_from_slice(well_known_keys::CHILD_STORAGE_KEY_PREFIX); - res.extend_from_slice(b"default:"); - res.extend_from_slice(&new_seed.to_le_bytes()); - res.extend_from_slice(&account_id.to_le_bytes()); - res - } -} - -const ALICE: u64 = 1; -const BOB: u64 = 2; -const CHARLIE: u64 = 3; -const DJANGO: u64 = 4; -const DEFAULT_PARAMETERS: TestParameters = TestParameters { a: 5_000_000 }; -const INVALID_PARAMETERS: TestParameters = TestParameters { - a: TEST_MAX_PARAMS_A + 1, -}; - -pub struct ExtBuilder { - existential_deposit: u64, - gas_price: u64, - block_gas_limit: u64, - transfer_fee: u64, - instantiation_fee: u64, -} - -impl Default for ExtBuilder { - fn default() -> Self { - Self { - existential_deposit: 0, - gas_price: 2, - block_gas_limit: 100_000_000, - transfer_fee: 0, - instantiation_fee: 0, - } - } -} - -impl ExtBuilder { - pub fn existential_deposit(mut self, existential_deposit: u64) -> Self { - self.existential_deposit = existential_deposit; - self - } - pub fn gas_price(mut self, gas_price: u64) -> Self { - self.gas_price = gas_price; - self - } - pub fn block_gas_limit(mut self, block_gas_limit: u64) -> Self { - self.block_gas_limit = block_gas_limit; - self - } - pub fn transfer_fee(mut self, transfer_fee: u64) -> Self { - self.transfer_fee = transfer_fee; - self - } - pub fn instantiation_fee(mut self, instantiation_fee: u64) -> Self { - self.instantiation_fee = instantiation_fee; - self - } - pub fn set_associated_consts(&self) { - EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit); - BLOCK_GAS_LIMIT.with(|v| *v.borrow_mut() = self.block_gas_limit); - } - pub fn build(self) -> sp_io::TestExternalities { - self.set_associated_consts(); - let mut t = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); - pallet_balances::GenesisConfig:: { balances: vec![] } - .assimilate_storage(&mut t) - .unwrap(); - pallet_contracts::GenesisConfig { - current_schedule: Schedule { - enable_println: true, - ..Default::default() - }, - } - .assimilate_storage(&mut t) - .unwrap(); - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| System::set_block_number(1)); - ext - } -} - -/// Generate Wasm binary and code hash from wabt source. -fn compile_module( - wabt_module: &str, -) -> std::result::Result<(Vec, ::Output), wabt::Error> -where - T: frame_system::Trait, -{ - let wasm = wabt::wat2wasm(wabt_module)?; - let code_hash = T::Hashing::hash(&wasm); - Ok((wasm, code_hash)) -} - -const CODE_RETURN_FROM_START_FN: &str = r#" -(module - (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) - (import "seal0" "seal_deposit_event" (func $seal_deposit_event (param i32 i32 i32 i32))) - (import "env" "memory" (memory 1 1)) - - (start $start) - (func $start - (call $seal_deposit_event - (i32.const 0) ;; The topics buffer - (i32.const 0) ;; The topics buffer's length - (i32.const 8) ;; The data buffer - (i32.const 4) ;; The data buffer's length - ) - (call $seal_return - (i32.const 0) - (i32.const 8) - (i32.const 4) - ) - (unreachable) - ) - - (func (export "call") - (unreachable) - ) - (func (export "deploy")) - - (data (i32.const 8) "\01\02\03\04") -) -"#; - -#[test] -fn instantiate_and_call_and_deposit_event() { - let (wasm, code_hash) = compile_module::(CODE_RETURN_FROM_START_FN).unwrap(); - - ExtBuilder::default() - .existential_deposit(100) - .build() - .execute_with(|| { - Balances::deposit_creating(&ALICE, 2_000_000); - - assert_ok!(Contracts::put_code(Origin::signed(ALICE), wasm)); - - // Check at the end to get hash on error easily - let creation = Contracts::instantiate( - Origin::signed(ALICE), - 1_000_000, - Gas::max_value(), - code_hash.into(), - vec![], - ); - - assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(ALICE)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Endowed( - ALICE, 2_000_000 - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::CodeStored( - code_hash.into() - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(BOB)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Endowed( - BOB, 1_000_000 - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Transfer( - ALICE, BOB, 1_000_000 - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::ContractExecution( - BOB, - vec![1, 2, 3, 4], - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::Instantiated( - ALICE, BOB - )), - topics: vec![], - } - ] - ); - - assert_ok!(creation); - assert!(ContractInfoOf::::contains_key(BOB)); - }); -} - -#[test] -fn instantiate_and_relate_operator() { - let (wasm, code_hash) = compile_module::(CODE_RETURN_FROM_START_FN).unwrap(); - - ExtBuilder::default() - .existential_deposit(100) - .build() - .execute_with(|| { - // prepare - Balances::deposit_creating(&ALICE, 2_000_000); - assert_ok!(Contracts::put_code(Origin::signed(ALICE), wasm)); - - let test_params = DEFAULT_PARAMETERS.clone(); - - // instantiate - // Check at the end to get hash on error easily - assert_ok!(Operator::instantiate( - Origin::signed(ALICE), - 1_000_000, - Gas::max_value(), - code_hash.into(), - vec![], - test_params.clone(), - )); - // checks eventRecord - assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(ALICE)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Endowed( - ALICE, 2_000_000 - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::CodeStored( - code_hash.into() - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(BOB)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Endowed( - BOB, 1_000_000 - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Transfer( - ALICE, BOB, 1_000_000 - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::ContractExecution( - BOB, - vec![1, 2, 3, 4], - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::Instantiated( - ALICE, BOB - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::operator(RawEvent::SetOperator(ALICE, BOB)), - topics: vec![], - } - ] - ); - - // checks deployed contract - assert!(ContractInfoOf::::contains_key(BOB)); - - // checks mapping operator and contract - // ALICE operates a only BOB contract. - assert!(OperatorHasContracts::::contains_key(ALICE)); - let tree = OperatorHasContracts::::get(&ALICE); - assert_eq!(tree.len(), 1); - assert!(tree.contains(&BOB)); - - // BOB contract is operated by ALICE. - assert!(ContractHasOperator::::contains_key(BOB)); - assert_eq!(ContractHasOperator::::get(&BOB), Some(ALICE)); - - // BOB's contract Parameters is same test_params. - assert!(ContractParameters::::contains_key(BOB)); - assert_eq!(ContractParameters::::get(&BOB), Some(test_params)); - }); -} - -#[test] -fn instantiate_failed() { - let (wasm, code_hash) = compile_module::(CODE_RETURN_FROM_START_FN).unwrap(); - - ExtBuilder::default() - .existential_deposit(100) - .build() - .execute_with(|| { - // prepare - Balances::deposit_creating(&ALICE, 1_000_000); - assert_ok!(Contracts::put_code(Origin::signed(ALICE), wasm)); - - let test_params = INVALID_PARAMETERS; - - // instantiate - // Check at the end to get hash on error easily - assert_err!( - Operator::instantiate( - Origin::signed(ALICE), - 100, - Gas::max_value(), - code_hash.into(), - vec![], - test_params, - ), - "over max params." - ); - }); -} - -fn valid_instatiate(wasm: Vec, code_hash: CodeHash) { - // prepare - Balances::deposit_creating(&ALICE, 2_000_000); - assert_ok!(Contracts::put_code(Origin::signed(ALICE), wasm)); - - let test_params = TestParameters { a: 5_000_000 }; - - // instantiate - // Check at the end to get hash on error easily - let creation = Operator::instantiate( - Origin::signed(ALICE), - 1_000_000, - Gas::max_value(), - code_hash.into(), - vec![], - test_params.clone(), - ); - // checks eventRecord - assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(ALICE)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Endowed(ALICE, 2_000_000)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::CodeStored( - code_hash.into() - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(BOB)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Endowed(BOB, 1_000_000)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Transfer( - ALICE, BOB, 1_000_000 - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::ContractExecution( - BOB, - vec![1, 2, 3, 4] - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::Instantiated(ALICE, BOB)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::operator(RawEvent::SetOperator(ALICE, BOB)), - topics: vec![], - } - ] - ); - - // checks deployed contract - assert!(ContractInfoOf::::contains_key(BOB)); - - // checks mapping operator and contract - // ALICE operates a only BOB contract. - assert!(OperatorHasContracts::::contains_key(ALICE)); - let tree = OperatorHasContracts::::get(&ALICE); - assert_eq!(tree.len(), 1); - assert!(tree.contains(&BOB)); - - // BOB contract is operated by ALICE. - assert!(ContractHasOperator::::contains_key(BOB)); - assert_eq!(ContractHasOperator::::get(&BOB), Some(ALICE)); - - // BOB's contract Parameters is same test_params. - assert!(ContractParameters::::contains_key(BOB)); - assert_eq!(ContractParameters::::get(&BOB), Some(test_params)); -} - -#[test] -fn update_parameters_passed() { - let (wasm, code_hash) = compile_module::(CODE_RETURN_FROM_START_FN).unwrap(); - - ExtBuilder::default() - .existential_deposit(100) - .build() - .execute_with(|| { - valid_instatiate(wasm, code_hash); - - // do update parameters - let new_parameters = TestParameters { a: 100_000_000 }; - assert_ok!(Operator::update_parameters( - Origin::signed(ALICE), - BOB, - new_parameters.clone() - )); - - // check updated paramters - // BOB's contract Parameters is same test_params. - assert!(ContractParameters::::contains_key(BOB)); - assert_eq!( - ContractParameters::::get(&BOB), - Some(new_parameters.clone()) - ); - - // To issue SetParameter - assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(ALICE)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Endowed( - ALICE, 2_000_000 - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::CodeStored( - code_hash.into() - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(BOB)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Endowed( - BOB, 1_000_000 - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Transfer( - ALICE, BOB, 1_000_000 - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::ContractExecution( - BOB, - vec![1, 2, 3, 4], - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::Instantiated( - ALICE, BOB - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::operator(RawEvent::SetOperator(ALICE, BOB)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::operator(RawEvent::SetParameters(BOB, new_parameters)), - topics: vec![], - }, - ] - ); - }); -} - -#[test] -fn update_parameters_failed() { - let (wasm, code_hash) = compile_module::(CODE_RETURN_FROM_START_FN).unwrap(); - - ExtBuilder::default() - .existential_deposit(100) - .build() - .execute_with(|| { - valid_instatiate(wasm, code_hash); - - // failed update parameters empty operate - let new_parameters = TestParameters { a: 100_000_000 }; - assert_err!( - Operator::update_parameters(Origin::signed(BOB), BOB, new_parameters), - "The sender don't operate the contract address." - ); - - // failed update parameters not operate contract address. - let new_parameters = TestParameters { a: 100_000_000 }; - assert_err!( - Operator::update_parameters(Origin::signed(ALICE), ALICE, new_parameters), - "The sender don't operate the contract address." - ); - - // failed invalid parameters. - let new_parameters = INVALID_PARAMETERS; - assert_err!( - Operator::update_parameters(Origin::signed(ALICE), BOB, new_parameters), - "over max params." - ); - - // check updated paramters - // BOB's contract Parameters is not changed. - assert!(ContractParameters::::contains_key(BOB)); - assert_eq!( - ContractParameters::::get(&BOB), - Some(DEFAULT_PARAMETERS) - ); - }); -} - -#[test] -fn change_operator_passed() { - let (wasm, code_hash) = compile_module::(CODE_RETURN_FROM_START_FN).unwrap(); - - ExtBuilder::default() - .existential_deposit(100) - .build() - .execute_with(|| { - valid_instatiate(wasm, code_hash); - - // do change operator form alice to charlie. - let new_operator = CHARLIE; - assert_ok!(Operator::change_operator( - Origin::signed(ALICE), - vec! {BOB,}, - new_operator.clone() - )); - - // checks mapping operator and contract - // ALICE doesn't operate a BOB contract. - let tree = OperatorHasContracts::::get(&ALICE); - assert_eq!(tree.len(), 0); - - // CHARLIE operate a only BOB contract. - assert!(OperatorHasContracts::::contains_key(CHARLIE)); - let tree = OperatorHasContracts::::get(&CHARLIE); - assert_eq!(tree.len(), 1); - assert!(tree.contains(&BOB)); - - // BOB contract is operated by CHARLIE. - assert!(ContractHasOperator::::contains_key(BOB)); - assert_eq!(ContractHasOperator::::get(&BOB), Some(CHARLIE)); - - // To issue SetParameter - assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(ALICE)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Endowed( - ALICE, 2_000_000 - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::CodeStored( - code_hash.into() - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(BOB)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Endowed( - BOB, 1_000_000 - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Transfer( - ALICE, BOB, 1_000_000 - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::ContractExecution( - BOB, - vec![1, 2, 3, 4], - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::contracts(pallet_contracts::RawEvent::Instantiated( - ALICE, BOB - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::operator(RawEvent::SetOperator(ALICE, BOB)), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::operator(RawEvent::SetOperator(CHARLIE, BOB)), - topics: vec![], - }, - ] - ); - }); -} - -#[test] -fn change_operator_failed() { - let (wasm, code_hash) = compile_module::(CODE_RETURN_FROM_START_FN).unwrap(); - - ExtBuilder::default() - .existential_deposit(100) - .build() - .execute_with(|| { - valid_instatiate(wasm, code_hash); - - // failed update parameter, invalid operator. - let new_operator = CHARLIE; - assert_err!( - Operator::change_operator( - Origin::signed(ALICE), - vec! {DJANGO,}, - new_operator.clone() - ), - "The sender don't operate the contracts address." - ); - - // checks mapping operator and contract is not changed. - // ALICE operates a only BOB contract. - assert!(OperatorHasContracts::::contains_key(ALICE)); - let tree = OperatorHasContracts::::get(&ALICE); - assert_eq!(tree.len(), 1); - assert!(tree.contains(&BOB)); - - // BOB contract is operated by ALICE. - assert!(ContractHasOperator::::contains_key(BOB)); - assert_eq!(ContractHasOperator::::get(&BOB), Some(ALICE)); - }); -} diff --git a/frame/ovm/Cargo.toml b/frame/ovm/Cargo.toml deleted file mode 100644 index 22cdbff508..0000000000 --- a/frame/ovm/Cargo.toml +++ /dev/null @@ -1,40 +0,0 @@ -[package] -name = "pallet-ovm" -version = "1.7.0" -authors = ["Stake Technologies "] -edition = "2018" -license = "Apache-2.0" -homepage = "https://docs.plasmnet.io/" -repository = "https://github.com/staketechnologies/Plasm/" -description = "FRAME pallet to optimstic virtual machine" - -[dependencies] -serde = { version = "1.0", optional = true, features = ["derive"] } -codec = { package = "parity-scale-codec", version = "1.2.0", features = ['derive'], default-features = false } -ovmi = { path = "../../ovmi/lib", version = "0.1.0", default-features = false } -sp-core = { version = "2.0.0", default-features = false } -sp-runtime = { version = "2.0.0", default-features = false } -sp-arithmetic = { version = "2.0.0", default-features = false } -sp-std = { version = "2.0.0", default-features = false } -frame-support = { version = "2.0.0", default-features = false } -frame-system = { version = "2.0.0", default-features = false } - -[dev-dependencies] -hex-literal = "0.2.1" -sp-io = { version = "2.0.0" } -pallet-balances = { version = "2.0.0" } -lazy_static = { version = "1.4" } - -[features] -default = ["std"] -std = [ - 'serde', - 'codec/std', - 'sp-runtime/std', - 'sp-arithmetic/std', - 'sp-std/std', - 'sp-core/std', - 'frame-support/std', - 'frame-system/std', - 'ovmi/std', -] diff --git a/frame/ovm/rpc/runtime-api/Cargo.toml b/frame/ovm/rpc/runtime-api/Cargo.toml deleted file mode 100644 index 0cbf669ff3..0000000000 --- a/frame/ovm/rpc/runtime-api/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "pallet-ovm-rpc-runtime-api" -version = "0.1.0" -authors = ["Takumi Yamashita "] -edition = "2018" -license = "GPL-3.0" -homepage = "https://plasmnet.io" -repository = "https://github.com/staketechnologies/Plasm/" -description = "Runtime API definition required by Ovm RPC extensions." - -[dependencies] -sp-api = { version = "2.0.0", default-features = false } -codec = { package = "parity-scale-codec", version = "1.2.0", default-features = false, features = ["derive"] } -sp-std = { version = "2.0.0", default-features = false } - -[features] -default = ["std"] -std = [ - "sp-api/std", - "codec/std", - "sp-std/std", -] diff --git a/frame/ovm/rpc/runtime-api/src/lib.rs b/frame/ovm/rpc/runtime-api/src/lib.rs deleted file mode 100644 index 25d8a5ddce..0000000000 --- a/frame/ovm/rpc/runtime-api/src/lib.rs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2019-2020 Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// Substrate is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Substrate is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Substrate. If not, see . - -//! Runtime API definition required by Ovm RPC extensions. -//! -//! This API should be imported and implemented by the runtime, -//! of a node that wants to use the custom RPC extension -//! adding Ovm access methods. - -#![cfg_attr(not(feature = "std"), no_std)] - -use codec::Codec; -use sp_std::vec::Vec; - -sp_api::decl_runtime_apis! { - /// The API to interact with contracts without using executive. - pub trait OvmApi where - Property: Codec, - Decision: Codec, - ChallengeGame: Codec, - Hash: Codec, - { - fn is_decided(property: Property) -> Decision; - fn get_game(claim_id: Hash) -> Option; - fn get_property_id(property: Property) -> Option; - } -} diff --git a/frame/ovm/src/lib.rs b/frame/ovm/src/lib.rs deleted file mode 100644 index 821da6865f..0000000000 --- a/frame/ovm/src/lib.rs +++ /dev/null @@ -1,657 +0,0 @@ -//! # Ovm Module -//! -//! The Ovm module provides functionality for handling layer2 dispute logics. -//! This refer to: https://github.com/cryptoeconomicslab/ovm-contracts/blob/master/contracts/UniversalAdjudicationContract.sol -//! -//! - [`ovm::Trait`](./trait.Trait.html) -//! - [`Call`](./enum.Call.html) -//! - [`Module`](./struct.Module.html) -//! -//! ## Overview -//! Ovm module is the substrate pallet to archive dispute game defined by predicate logic. -//! -//! -//! -#![cfg_attr(not(feature = "std"), no_std)] -#![allow(deprecated)] - -use codec::{Decode, Encode}; -use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, - dispatch::DispatchResult, - ensure, - traits::Get, - weights::{DispatchClass, FunctionOf, Pays, Weight}, - StorageMap, -}; -use frame_system::{self as system, ensure_signed}; - -use ovmi::executor::ExecError; -pub type ExecResult = Result, ExecError<::AccountId>>; - -#[cfg(feature = "std")] -use serde::{Deserialize, Serialize}; -use sp_core::crypto::UncheckedFrom; -use sp_runtime::{ - traits::{Hash, Zero}, - RuntimeDebug, -}; -use sp_std::marker::PhantomData; -use sp_std::{collections::btree_map::BTreeMap, prelude::*, rc::Rc, vec::Vec}; - -#[cfg(test)] -mod mock; -#[cfg(test)] -mod tests; - -pub mod predicate; -pub mod traits; - -use predicate::{ExecutionContext, PredicateLoader, PredicateOvm}; -use traits::{Ext, NewCallContext, PredicateAddressFor}; - -/// PredicateContract wrapped Predicate and initial arguments. -/// -/// Required functions of each PredicateContract: -/// - isValidChallenge -/// - decide -/// -/// isValidChallenge validates valid child node of game tree. -#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)] -pub struct PredicateContract { - pub predicate_hash: CodeHash, - pub inputs: Vec, -} - -/// Property stands for dispute logic and we can claim every Properties to Adjudicator Contract. -/// Property has its predicate address and array of input. -#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)] -pub struct Property { - /// Indicates the address of Predicate. - pub predicate_address: AccountId, - /// Every input are bytes. Each Atomic Predicate decode inputs to the specific type. - pub inputs: Vec>, -} - -/// The game decision by predicates. -#[derive(Encode, Decode, RuntimeDebug, PartialEq, Eq)] -pub enum Decision { - Undecided, - True, - False, -} - -/// ChallengeGame is a part of L2 dispute. It's instantiated by claiming property. -/// The client can get a game instance from this module. -#[derive(Encode, Decode, RuntimeDebug, PartialEq, Eq)] -pub struct ChallengeGame { - /// Property of challenging targets. - property_hash: Hash, - /// challenges inputs - challenges: Vec, - /// the result of this challenge. - decision: Decision, - /// the block number when this was issued. - created_block: BlockNumber, -} - -/// Definition of the cost schedule and other parameterizations for optimistic virtual machine. -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -#[derive(Clone, Encode, Decode, PartialEq, Eq, RuntimeDebug)] -pub struct Schedule { - /// Version of the schedule. - pub version: u32, - - /// Cost of putting a byte of code into storage. - pub put_code_per_byte_cost: Weight, -} - -// 500 (2 instructions per nano second on 2GHZ) * 1000x slowdown through wasmi -// This is a wild guess and should be viewed as a rough estimation. -// Proper benchmarks are needed before this value and its derivatives can be used in production. -const OVM_INSTRUCTION_COST: Weight = 500_000; - -impl Default for Schedule { - fn default() -> Schedule { - Schedule { - version: 0, - put_code_per_byte_cost: OVM_INSTRUCTION_COST, - } - } -} - -/// In-memory cache of configuration values. -/// -/// We assume that these values can't be changed in the -/// course of transaction execution. -pub struct Config { - pub schedule: Schedule, - pub max_depth: u32, // about down 30. -} - -impl Config { - fn preload() -> Config { - Config { - schedule: >::current_schedule(), - max_depth: T::MaxDepth::get(), - } - } -} - -/// Atomic Predicate AccountId List. -/// It is inject when runtime setup. -pub struct AtomicPredicateIdConfig { - pub not_address: AccountId, - pub and_address: AccountId, - pub or_address: AccountId, - pub for_all_address: AccountId, - pub there_exists_address: AccountId, - pub equal_address: AccountId, - pub is_contained_address: AccountId, - pub is_less_address: AccountId, - pub is_stored_address: AccountId, - pub is_valid_signature_address: AccountId, - pub verify_inclusion_address: AccountId, - pub secp256k1: Hash, -} - -pub struct SimpleAddressDeterminer(PhantomData); -impl PredicateAddressFor for SimpleAddressDeterminer -where - T::AccountId: UncheckedFrom + AsRef<[u8]>, -{ - fn predicate_address_for( - code_hash: &T::Hash, - data: &[u8], - origin: &T::AccountId, - ) -> T::AccountId { - let data_hash = T::Hashing::hash(data); - - let mut buf = Vec::new(); - buf.extend_from_slice(code_hash.as_ref()); - buf.extend_from_slice(data_hash.as_ref()); - buf.extend_from_slice(origin.as_ref()); - - UncheckedFrom::unchecked_from(T::Hashing::hash(&buf[..])) - } -} - -type PredicateHash = ::Hash; -type ChallengeGameOf = - ChallengeGame<::Hash, ::BlockNumber>; -pub type PropertyOf = Property<::AccountId>; -type AccountIdOf = ::AccountId; -type PredicateContractOf = PredicateContract<::Hash>; - -pub trait Trait: system::Trait { - /// The maximum nesting level of a call/instantiate stack. - type MaxDepth: Get; - - /// During the dispute period defined here, the user can challenge. - /// If nothing is found, the state is determined after the dispute period. - type DisputePeriod: Get; - - /// A function type to get the contract address given the instantiator. - type DeterminePredicateAddress: PredicateAddressFor, Self::AccountId>; - - /// The hashing system (algorithm) being used in the runtime (e.g. Keccak256). - type HashingL2: Hash; - - /// ExternalCall context. - type ExternalCall: Ext + NewCallContext; - - type AtomicPredicateIdConfig: Get>; - - /// The overarching event type. - type Event: From> + Into<::Event>; -} - -decl_storage! { - trait Store for Module as Ovm { - /// Current cost schedule for contracts. - pub CurrentSchedule get(fn current_schedule) config(): Schedule = Schedule::default(); - - /// A mapping from an original code hash to the original code, untouched by instrumentation. - pub PredicateCodes get(fn predicate_codes): map hasher(identity) PredicateHash => Option>; - - /// A mapping between an original code hash and instrumented ovm(predicate) code, ready for execution. - pub PredicateCache get(fn predicate_cache): map hasher(identity) PredicateHash => Option; - - /// Mapping the predicate address to Predicate. - /// Predicate is handled similar to contracts. - pub Predicates get(fn predicates): map hasher(blake2_128_concat) - T::AccountId => Option>; - - /// Mapping the game id to Challenge Game. - pub Games get(fn games): map hasher(blake2_128_concat) T::Hash => Option>; - } -} - -decl_event!( - pub enum Event - where - AccountId = ::AccountId, - Property = PropertyOf, - Hash = ::Hash, - BlockNumber = ::BlockNumber, - { - /// (predicate_address: AccountId); - PutPredicate(Hash), - /// (predicate_address: AccountId); - InstantiatePredicate(AccountId), - /// (game_id: Hash, property: Property, created_block: BlockNumber) - PropertyClaimed(Hash, Property, BlockNumber), - /// (gameId: Hash, challenge_game_id: Hash) - PropertyChallenged(Hash, Hash), - /// (game_id: Hash, decision: bool) - PropertyDecided(Hash, bool), - /// (game_id: Hash, challengeGameId: Hash) - ChallengeRemoved(Hash, Hash), - } -); - -decl_error! { - /// Error for the staking module. - pub enum Error for Module { - /// Does not exist game - DoesNotExistGame, - /// setPredicateDecision must be called from predicate - MustBeCalledFromPredicate, - /// index must be less than challenges.length - OutOfRangeOfChallenges, - /// game is already started - GameIsAlradyStarted, - /// property is not claimed - PropertyIsNotClaimed, - /// challenge is already started - ChallengeIsAlreadyStarted, - /// challenge is not in the challenge list - ChallengeIsNotInTheChallengeList, - /// challenge property is not decided to false - ChallengePropertyIsNotDecidedToFalse, - /// challenge list is not empty - ChallengeListIsNotEmpty, - /// dispute period has not been passed - DisputePeriodHasNotBeenPassed, - /// undecided challenge exists - UndecidedChallengeExists, - } -} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - /// During the dispute period defined here, the user can challenge. - /// If nothing is found, the state is determined after the dispute period. - const DisputePeriod: ::BlockNumber = T::DisputePeriod::get(); - - type Error = Error; - - fn deposit_event() = default; - - fn on_runtime_upgrade() -> Weight { - migrate::(); - // TODO: weight - T::MaximumBlockWeight::get() - } - - /// Stores the given binary Wasm code into the chain's storage and returns its `codehash`. - /// You can instantiate contracts only with stored code. - #[weight = FunctionOf( - |args: (&Vec,)| Module::::calc_code_put_costs(args.0), - DispatchClass::Normal, - Pays::Yes - )] - pub fn put_code( - origin, - predicate: Vec - ) -> DispatchResult { - let _ = ensure_signed(origin)?; - let schedule = Self::current_schedule(); - match predicate::save_code::(predicate, &schedule) { - Ok(predicate_hash) => { - Self::deposit_event(RawEvent::PutPredicate(predicate_hash)); - }, - Err(err) => return Err(err.into()), - } - Ok(()) - } - - /// Deploy predicate and made predicate address as AccountId. - /// TODO: weight - #[weight = 100_000] - pub fn instantiate(origin, predicate_hash: PredicateHash, inputs: Vec) { - let origin = ensure_signed(origin)?; - - // Calc predicate address. - let predicate_address = T::DeterminePredicateAddress::predicate_address_for( - &predicate_hash, - &inputs, - &origin - ); - let predicate_contract = PredicateContract { - predicate_hash, - inputs, - }; - - >::insert(&predicate_address, predicate_contract); - - Self::deposit_event(RawEvent::InstantiatePredicate(predicate_address)); - } - - /// Claims property and create new game. Id of game is hash of claimed property - /// TODO: weight - #[weight = 100_000] - pub fn claim(origin, claim: PropertyOf) { - let origin = ensure_signed(origin)?; - Self::only_from_dispute_contract(&origin, &claim)?; - // get the id of this property - let game_id = Self::get_property_id(&claim); - ensure!( - Self::started(&game_id), - Error::::GameIsAlradyStarted, - ); - - let game = Self::create_game(game_id); - >::insert(game_id, game); - Self::deposit_event(RawEvent::PropertyClaimed(game_id, claim, Self::block_number())); - } - - /// Challenge to an existing game instance by a property. - /// - /// challenge will be added to `challenges` field of challenged game instance. - /// if property does not exist, revert. - /// if challenge with same property was made before, revert. - /// - /// TODO: weight - #[weight = 100_000] - pub fn challenge(origin, property: PropertyOf, challenge_property: PropertyOf) { - let origin = ensure_signed(origin)?; - Self::only_from_dispute_contract(&origin, &property)?; - - // validation - let id = Self::get_property_id(&property); - ensure!( - Self::started(&id), - Error::::PropertyIsNotClaimed, - ); - - let challenging_game_id = Self::get_property_id(&challenge_property); - ensure!( - Self::started(&challenging_game_id), - Error::::ChallengeIsAlreadyStarted, - ); - - // start challenging game - let challenge_game = Self::create_game(challenging_game_id); - >::insert(challenging_game_id, challenge_game); - - // add challenge to challenged game's challenge list - let mut game = Self::games(&id).ok_or(Error::::DoesNotExistGame)?; - game.challenges.push(challenging_game_id); - >::insert(id, game); - Self::deposit_event(RawEvent::PropertyChallenged(id, challenging_game_id)); - } - - /// remove challenge - /// set challenging game decision to false and remove it from challenges field of challenged game - /// if property does not exist, revert. - /// if challenge property does not exist, revert. - /// - /// TODO: weight - #[weight = 100_000] - pub fn remove_challenge(origin, property: PropertyOf, challenge_property: PropertyOf) { - let origin = ensure_signed(origin)?; - Self::only_from_dispute_contract(&origin, &property)?; - - let id = Self::get_property_id(&property); - ensure!( - Self::started(&id), - Error::::PropertyIsNotClaimed, - ); - - let challenging_game_id = Self::get_property_id(&property); - ensure!( - Self::started(&challenging_game_id), - Error::::ChallengeIsAlreadyStarted, - ); - - let mut game = Self::games(&id).ok_or(Error::::DoesNotExistGame)?; - let _ = Self::find_index(&game.challenges, &challenging_game_id) - .ok_or(Error::::ChallengeIsNotInTheChallengeList)?; - - let challenge_game = Self::games(&challenging_game_id).ok_or(Error::::DoesNotExistGame)?; - ensure!( - challenge_game.decision == Decision::False, - Error::::ChallengePropertyIsNotDecidedToFalse, - ); - - // remove challenge - game.challenges = game - .challenges - .into_iter() - .filter(|challenge| challenge != &challenging_game_id) - .collect(); - >::insert(id, game); - Self::deposit_event(RawEvent::ChallengeRemoved(id, challenging_game_id)); - } - - /// set game result to given result value. - /// only called from dispute contract - /// - /// TODO: weight - #[weight = 100_000] - pub fn set_game_result(origin, property: PropertyOf, result: bool) - { - let origin = ensure_signed(origin)?; - Self::only_from_dispute_contract(&origin, &property)?; - - let id = Self::get_property_id(&property); - ensure!( - Self::started(&id), - Error::::PropertyIsNotClaimed, - ); - - let mut game = Self::games(&id).ok_or(Error::::DoesNotExistGame)?; - ensure!( - game.challenges.len() == 0, - Error::::ChallengeListIsNotEmpty, - ); - - game.decision = Self::get_decision(result); - Self::deposit_event(RawEvent::PropertyDecided(id, result)); - } - - /// settle game - /// settle started game whose dispute period has passed. - /// if no challenge for the property exists, decide to true. - /// if any of its challenges decided to true, decide game to false. - /// if undecided challenge remains, revert. - /// - /// TODO: weight - #[weight = 100_000] - pub fn settle_game(origin, property: PropertyOf) - { - let origin = ensure_signed(origin)?; - Self::only_from_dispute_contract(&origin, &property)?; - - let id = Self::get_property_id(&property); - ensure!( - Self::started(&id), - Error::::PropertyIsNotClaimed, - ); - - let mut game = Self::games(&id).ok_or(Error::::DoesNotExistGame)?; - ensure!( - game.created_block < Self::block_number() - T::DisputePeriod::get(), - Error::::DisputePeriodHasNotBeenPassed, - ); - - for challenge in game.challenges.iter() { - let decision = Self::get_game(challenge).ok_or(Error::::DoesNotExistGame)?.decision; - if decision == Decision::True { - game.decision = Decision::False; - Self::deposit_event(RawEvent::PropertyDecided(id, false)); - return Ok(()); - } - ensure!( - decision == Decision::Undecided, - Error::::UndecidedChallengeExists, - ); - } - game.decision = Decision::True; - >::insert(id, game); - Self::deposit_event(RawEvent::PropertyDecided(id, true)); - } - } -} - -fn migrate() { - // TODO: When runtime upgrade, migrate stroage. - // if let Some(current_era) = CurrentEra::get() { - // let history_depth = HistoryDepth::get(); - // for era in current_era.saturating_sub(history_depth)..=current_era { - // ErasStartSessionIndex::migrate_key_from_blake(era); - // } -} - -impl Module { - fn calc_code_put_costs(code: &Vec) -> Weight { - >::current_schedule() - .put_code_per_byte_cost - .saturating_mul(code.len() as Weight) - } - - // ======= main ========== - /// Perform a call to a specified contract. - /// - /// This function is similar to `Self::call`, but doesn't perform any address lookups and better - /// suitable for calling directly from Rust. - pub fn bare_call( - origin: T::AccountId, - dest: T::AccountId, - input_data: Vec, - ) -> ExecResult { - Self::execute_ovm(origin, |ctx| ctx.call(dest, input_data)) - } - - fn execute_ovm( - origin: T::AccountId, - func: impl FnOnce(&mut ExecutionContext) -> ExecResult, - ) -> ExecResult { - let cfg = Rc::new(Config::preload::()); - let schedule = Rc::new(cfg.schedule.clone()); - let vm = Rc::new(PredicateOvm::new(Rc::clone(&schedule))); - let loader = Rc::new(PredicateLoader::new(Rc::clone(&schedule))); - let mut ctx = ExecutionContext::top_level(origin.clone(), cfg, vm, loader); - - func(&mut ctx) - } - - // ======= callable ====== - /// Get of true/false the decision of property. - pub fn is_decided(property: &PropertyOf) -> Decision { - let game = match Self::games(Self::get_property_id(property)) { - Some(game) => game, - None => return Decision::Undecided, - }; - game.decision - } - - /// Get of true/false the decision of game id. - pub fn is_decided_by_id(id: T::Hash) -> Decision { - let game = match Self::games(&id) { - Some(game) => game, - None => return Decision::Undecided, - }; - game.decision - } - - /// Get of the instatiated challenge game from claim_id. - pub fn get_game(claim_id: &T::Hash) -> Option> { - Self::games(claim_id) - } - - /// Get of the property id from the propaty itself. - pub fn get_property_id(property: &PropertyOf) -> T::Hash { - T::Hashing::hash_of(property) - } - - pub fn is_challenge_of(property: &PropertyOf, challenge_property: &PropertyOf) -> bool { - if let Some(game) = Self::get_game(&Self::get_property_id(property)) { - if let Some(_) = - Self::find_index(&game.challenges, &Self::get_property_id(challenge_property)) - { - return true; - } - } - false - } - - /// check if game of given id is already started. - pub fn started(id: &T::Hash) -> bool { - if let Some(game) = Self::games(id) { - game.created_block != ::BlockNumber::zero() - } else { - false - } - } - - // ======= helper ======= - pub fn block_number() -> ::BlockNumber { - >::block_number() - } - - pub fn is_decidable(property_id: &T::Hash) -> bool { - let game = match Self::games(property_id) { - Some(game) => game, - None => return false, - }; - - if game.created_block > Self::block_number() - T::DisputePeriod::get() { - return false; - } - - // check all game.challenges should be false - game.challenges.iter().all(|challenge| { - if let Some(challenging_game) = Self::games(challenge) { - return challenging_game.decision == Decision::False; - } - false - }) - } - - fn create_game(id: T::Hash) -> ChallengeGameOf { - ChallengeGame { - property_hash: id, - /// challenges inputs - challenges: vec![], - /// the result of this challenge. - decision: Decision::Undecided, - /// the block number when this was issued. - created_block: Self::block_number(), - } - } - - fn get_decision(result: bool) -> Decision { - if result { - return Decision::True; - } - Decision::False - } - - fn find_index(array: &Vec, item: &Hash) -> Option { - array.iter().position(|hash| hash == item) - } - - // ======= modifier ======= - fn only_from_dispute_contract( - origin: &T::AccountId, - property: &PropertyOf, - ) -> DispatchResult { - ensure!( - &property.predicate_address == origin, - Error::::MustBeCalledFromPredicate, - ); - Ok(()) - } -} diff --git a/frame/ovm/src/mock.rs b/frame/ovm/src/mock.rs deleted file mode 100644 index d116d963b1..0000000000 --- a/frame/ovm/src/mock.rs +++ /dev/null @@ -1,221 +0,0 @@ -//! Test utilities - -#![cfg(test)] - -use super::*; -use crate::predicate::CallContext; -use frame_support::{impl_outer_dispatch, impl_outer_event, impl_outer_origin, parameter_types}; -pub use hex_literal::hex; -use pallet_balances as balances; -use sp_core::{crypto::AccountId32, Pair, H256}; -use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, IdentifyAccount, IdentityLookup}, - Perbill, -}; -pub type BlockNumber = u64; -pub type AccountId = AccountId32; -pub type Balance = u64; - -lazy_static::lazy_static! { - pub static ref ALICE_STASH: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000005553" - ]); -} - -impl_outer_origin! { - pub enum Origin for Test where system = frame_system {} -} - -impl_outer_dispatch! { - pub enum Call for Test where origin: Origin { - pallet_balances::Balances, - } -} - -mod ovm { - // Re-export contents of the root. This basically - // needs to give a name for the current crate. - // This hack is required for `impl_outer_event!`. - pub use super::super::*; -} - -impl_outer_event! { - pub enum MetaEvent for Test { - system, - balances, - ovm, - } -} -pub fn new_test_ext() -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); - - let _ = pallet_balances::GenesisConfig:: { - balances: vec![((*ALICE_STASH).clone(), 1_000_000_000_000_000_000)], - } - .assimilate_storage(&mut storage); - - let _ = GenesisConfig { - current_schedule: Default::default(), - } - .assimilate_storage(&mut storage); - - storage.into() -} - -#[derive(Clone, PartialEq, Eq, Debug)] -pub struct Test; - -parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: u32 = 1024; - pub const MaximumBlockLength: u32 = 2 * 1024; - pub const AvailableBlockRatio: Perbill = Perbill::one(); -} - -impl frame_system::Trait for Test { - type Origin = Origin; - type BaseCallFilter = (); - type Index = u64; - type BlockNumber = BlockNumber; - type Call = Call; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; - type Header = Header; - type Event = MetaEvent; - type DbWeight = (); - type BlockHashCount = BlockHashCount; - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = (); - type MaximumBlockWeight = MaximumBlockWeight; - type MaximumBlockLength = MaximumBlockLength; - type AvailableBlockRatio = AvailableBlockRatio; - type Version = (); - type PalletInfo = (); - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); -} - -parameter_types! { - pub const ExistentialDeposit: Balance = 10; -} - -impl pallet_balances::Trait for Test { - type Balance = Balance; - type Event = MetaEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Module; - type WeightInfo = (); - type MaxLocks = (); -} - -parameter_types! { - pub const MaxDepth: u32 = 32; - pub const DisputePeriod: BlockNumber = 7; -} - -lazy_static::lazy_static! { - pub static ref NOT_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000003" - ]); - pub static ref AND_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000004" - ]); - pub static ref OR_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000005" - ]); - pub static ref FOR_ALL_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000006" - ]); - pub static ref THERE_EXISTS_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000007" - ]); - pub static ref EQUAL_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000008" - ]); - pub static ref IS_CONTAINED_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000009" - ]); - pub static ref IS_LESS_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000010" - ]); - pub static ref IS_STORED_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000011" - ]); - pub static ref IS_VALID_SIGNATURE_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000012" - ]); - pub static ref VERIFY_INCLUSION_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000013" - ]); - pub static ref SECP_256_K1: H256 = H256::from(&hex![ - "d4fa99b1e08c4e5e6deb461846aa629344d95ff03ed04754c2053d54c756f439" - ]); -} - -impl Get> for AtomicPredicateIdConfig { - fn get() -> AtomicPredicateIdConfig { - AtomicPredicateIdConfig { - not_address: (*NOT_ADDRESS).clone(), - and_address: (*AND_ADDRESS).clone(), - or_address: (*OR_ADDRESS).clone(), - for_all_address: (*FOR_ALL_ADDRESS).clone(), - there_exists_address: (*THERE_EXISTS_ADDRESS).clone(), - equal_address: (*EQUAL_ADDRESS).clone(), - is_contained_address: (*IS_CONTAINED_ADDRESS).clone(), - is_less_address: (*IS_LESS_ADDRESS).clone(), - is_stored_address: (*IS_STORED_ADDRESS).clone(), - is_valid_signature_address: (*IS_VALID_SIGNATURE_ADDRESS).clone(), - verify_inclusion_address: (*VERIFY_INCLUSION_ADDRESS).clone(), - secp256k1: (*SECP_256_K1).clone(), - } - } -} - -impl Trait for Test { - type MaxDepth = MaxDepth; - type DisputePeriod = DisputePeriod; - type DeterminePredicateAddress = SimpleAddressDeterminer; - type HashingL2 = BlakeTwo256; - type ExternalCall = CallContext; - type AtomicPredicateIdConfig = AtomicPredicateIdConfig; - type Event = MetaEvent; -} - -pub type System = frame_system::Module; -pub type Balances = pallet_balances::Module; -pub type Ovm = Module; - -pub fn advance_block() { - let next = System::block_number() + 1; - // increase block numebr - System::set_block_number(next); -} - -/// Generate compiled predicate binary and code hash from predicate source. -pub fn compile_predicate(predicate_module: &str) -> (Vec, ::Output) -where - T: frame_system::Trait, -{ - // TODO actually predicate to compiled predicate. - let compiled_predicate = predicate_module.as_bytes().to_vec(); - let code_hash = T::Hashing::hash_of(&compiled_predicate); - (compiled_predicate.to_vec(), code_hash) -} - -pub fn to_account_from_seed(seed: &[u8; 32]) -> AccountId { - to_account(sp_core::ecdsa::Pair::from_seed(&seed).public().as_ref()) -} - -pub fn to_account(full_public: &[u8]) -> AccountId { - let public = sp_core::ecdsa::Public::from_full(full_public).unwrap(); - sp_runtime::MultiSigner::from(public).into_account() -} diff --git a/frame/ovm/src/predicate/call.rs b/frame/ovm/src/predicate/call.rs deleted file mode 100644 index e86c2b385d..0000000000 --- a/frame/ovm/src/predicate/call.rs +++ /dev/null @@ -1,72 +0,0 @@ -//! This CallContext is the mock ExternalCall implementation. -//! **Note that it is not used in the production environment.** -//! -//! When Plasma module is used, it is implemented by injecting CallContext of Plasma module as Ext of ExecutionContext. - -use crate::predicate::*; -use crate::traits::{Ext, NewCallContext}; -use crate::{AccountIdOf, Decision, PropertyOf, Trait}; - -pub struct CallContext { - ctx: Rc>, - caller: T::AccountId, -} - -impl NewCallContext for CallContext { - fn new(ctx: Rc>, caller: AccountIdOf) -> Self { - CallContext { ctx: ctx, caller } - } -} - -/// An interface that provides access to the external environment in which the -/// predicate-contract is executed similar to a smart-contract. -/// -/// This interface is specialized to an account of the executing code, so all -/// operations are implicitly performed on that account. -impl Ext for CallContext -where - T: Trait, -{ - fn call(&self, to: &AccountIdOf, input_data: Vec) -> ExecResult { - self.ctx.call(to.clone(), input_data) - } - - fn caller(&self) -> &AccountIdOf { - &self.caller - } - - fn address(&self) -> &AccountIdOf { - &self.ctx.self_account - } - - fn is_stored(&self, _address: &AccountIdOf, _key: &[u8], _value: &[u8]) -> bool { - true - } - - fn verify_inclusion_with_root( - &self, - _leaf: T::Hash, - _token_address: AccountIdOf, - _range: &[u8], - _inclusion_proof: &[u8], - _root: &[u8], - ) -> bool { - true - } - - fn is_decided(&self, property: &PropertyOf) -> bool { - Decision::True == >::is_decided(property) - } - - fn is_decided_by_id(&self, id: T::Hash) -> bool { - Decision::True == >::is_decided_by_id(id) - } - - fn set_predicate_decision( - &self, - _game_id: T::Hash, - _decision: bool, - ) -> Result> { - Ok(true) - } -} diff --git a/frame/ovm/src/predicate/code_cache.rs b/frame/ovm/src/predicate/code_cache.rs deleted file mode 100644 index 3d45be01dd..0000000000 --- a/frame/ovm/src/predicate/code_cache.rs +++ /dev/null @@ -1,43 +0,0 @@ -use super::super::*; -use crate::predicate::*; - -/// Put code in the storage. The hash of code is used as a key and is returned -/// as a result of this function. -/// -/// This function instruments the given code and caches it in the storage. -pub fn save( - original_code: Vec, - schedule: &Schedule, -) -> Result, &'static str> { - let prefab = prepare::prepare_predicate(&original_code, schedule)?; - let predicate_hash = ::Hashing::hash_of(&original_code); - >::insert(&predicate_hash, original_code); - >::insert(&predicate_hash, prefab); - - Ok(predicate_hash) -} - -/// Load code with the given code hash. -/// -/// If the module was instrumented with a lower version of schedule than -/// the current one given as an argument, then this function will perform -/// re-instrumentation and update the cache in the storage. -pub fn load( - code_hash: &PredicateHash, - schedule: &Schedule, -) -> Result { - let mut prefab_module = - >::get(code_hash).ok_or_else(|| "code is not found")?; - - if prefab_module.schedule_version < schedule.version { - // The current schedule version is greater than the version of the one cached - // in the storage. - // - // We need to re-instrument the code with the latest schedule here. - let original_code = - >::get(code_hash).ok_or_else(|| "predicate code is not found")?; - prefab_module = prepare::prepare_predicate(&original_code, schedule)?; - >::insert(code_hash, &prefab_module); - } - Ok(prefab_module) -} diff --git a/frame/ovm/src/predicate/ext.rs b/frame/ovm/src/predicate/ext.rs deleted file mode 100644 index e1a968bac9..0000000000 --- a/frame/ovm/src/predicate/ext.rs +++ /dev/null @@ -1,125 +0,0 @@ -//! The external call function connecting to OVMinterpreter. - -use crate::traits::Ext; -use crate::*; -use ovmi::executor::{ExecResultT, ExternalCall}; -use ovmi::predicates::PredicateCallInputs; - -// Setting External environment. -pub struct ExternalCallImpl<'a, T: Trait> { - pub inter: &'a T::ExternalCall, -} - -impl<'a, T: Trait> ExternalCallImpl<'a, T> { - pub fn new(inter: &'a T::ExternalCall) -> Self { - ExternalCallImpl { inter } - } -} - -impl ExternalCall for ExternalCallImpl<'_, T> { - type Address = T::AccountId; - type Hash = T::Hash; - type Hashing = T::HashingL2; - - fn not_address() -> Self::Address { - T::AtomicPredicateIdConfig::get().not_address - } - fn and_address() -> Self::Address { - T::AtomicPredicateIdConfig::get().and_address - } - fn or_address() -> Self::Address { - T::AtomicPredicateIdConfig::get().or_address - } - fn for_all_address() -> Self::Address { - T::AtomicPredicateIdConfig::get().for_all_address - } - fn there_exists_address() -> Self::Address { - T::AtomicPredicateIdConfig::get().there_exists_address - } - fn equal_address() -> Self::Address { - T::AtomicPredicateIdConfig::get().equal_address - } - fn is_contained_address() -> Self::Address { - T::AtomicPredicateIdConfig::get().is_contained_address - } - fn is_less_address() -> Self::Address { - T::AtomicPredicateIdConfig::get().is_less_address - } - fn is_stored_address() -> Self::Address { - T::AtomicPredicateIdConfig::get().is_stored_address - } - fn is_valid_signature_address() -> Self::Address { - T::AtomicPredicateIdConfig::get().is_valid_signature_address - } - fn verify_inclusion_address() -> Self::Address { - T::AtomicPredicateIdConfig::get().verify_inclusion_address - } - fn secp256k1() -> Self::Hash { - T::AtomicPredicateIdConfig::get().secp256k1 - } - - fn ext_call( - &self, - to: &Self::Address, - input_data: PredicateCallInputs, - ) -> ExecResultT, Self::Address> { - self.inter.call(to, input_data.encode()) - } - - fn ext_caller(&self) -> Self::Address { - self.inter.caller().clone() - } - - fn ext_address(&self) -> Self::Address { - self.inter.address().clone() - } - - fn ext_is_stored(&self, address: &Self::Address, key: &[u8], value: &[u8]) -> bool { - self.inter.is_stored(address, key, value) - } - - /// At first implementing, only ECDSA signature. - fn ext_verify(&self, _hash: &Self::Hash, _signature: &[u8], _address: &Self::Address) -> bool { - // if signature.len() != 65 { - // return false; - // } - // let sig: ecdsa::Signature = ecdsa::Signature::from_slice(signature); - // if let Some(public) = sig.recover(hash) { - // return Self::hash_of(address) - // == Self::hash_of(&MultiSigner::from(public).into_account()); - // } - false - } - - fn ext_verify_inclusion_with_root( - &self, - leaf: Self::Hash, - token_address: Self::Address, - range: &[u8], - inclusion_proof: &[u8], - root: &[u8], - ) -> bool { - self.inter - .verify_inclusion_with_root(leaf, token_address, range, inclusion_proof, root) - } - - fn ext_is_decided(&self, property: &ovmi::executor::PropertyOf) -> bool { - if let Ok(property) = Decode::decode(&mut &property.encode()[..]) { - return self.inter.is_decided(&property); - } - false - } - fn ext_is_decided_by_id(&self, id: Self::Hash) -> bool { - self.inter.is_decided_by_id(id) - } - fn ext_get_property_id(&self, property: &ovmi::executor::PropertyOf) -> Self::Hash { - Self::hash_of(property) - } - fn ext_set_predicate_decision( - &self, - game_id: Self::Hash, - decision: bool, - ) -> ExecResultT { - self.inter.set_predicate_decision(game_id, decision) - } -} diff --git a/frame/ovm/src/predicate/mod.rs b/frame/ovm/src/predicate/mod.rs deleted file mode 100644 index bebb541610..0000000000 --- a/frame/ovm/src/predicate/mod.rs +++ /dev/null @@ -1,179 +0,0 @@ -use super::*; -use crate::traits::*; -use ovmi::executor::{CompiledExecutor, OvmExecutor}; -use sp_std::marker::PhantomData; -mod call; -mod code_cache; -mod ext; -mod prepare; - -pub use self::code_cache::save as save_code; -pub use call::CallContext; -use ovmi::predicates::CompiledExecutable; - -/// A prepared wasm module ready for execution. -#[derive(Clone, Encode, Decode)] -pub struct PrefabOvmModule { - /// Version of the schedule with which the code was instrumented. - #[codec(compact)] - schedule_version: u32, - /// Code instrumented with the latest schedule. - code: Vec, -} - -/// Ovm executable loaded by `OvmLoader` and executed by `OptimisticOvm`. -pub struct OvmExecutable { - code: ovmi::compiled_predicates::CompiledPredicate, - payout: T::AccountId, - address_inputs: BTreeMap, - bytes_inputs: BTreeMap>, -} - -/// Loader which fetches `OvmExecutable` from the code cache. -pub struct PredicateLoader { - schedule: Rc, -} - -impl PredicateLoader { - pub fn new(schedule: Rc) -> Self { - PredicateLoader { schedule } - } -} - -impl Loader for PredicateLoader { - type Executable = OvmExecutable; - - fn load_main( - &self, - predicate: PredicateContractOf, - ) -> Result, &'static str> { - let prefab_module = code_cache::load::(&predicate.predicate_hash, &self.schedule)?; - let code = Decode::decode(&mut &prefab_module.code[..]) - .map_err(|_| "Predicate code cannot decode error.")?; - let (payout, address_inputs, bytes_inputs) = Decode::decode(&mut &predicate.inputs[..]) - .map_err(|_| "Constructor inputs cannot decode error.")?; - Ok(OvmExecutable { - code, - payout, - address_inputs, - bytes_inputs, - }) - } -} - -#[derive(Clone)] -pub struct ExecutionContext { - pub self_account: T::AccountId, - pub depth: usize, - // pub deferred: Vec>, - pub config: Rc, - pub vm: Rc>, - pub loader: Rc, -} - -impl ExecutionContext -where - T: Trait, -{ - /// Create the top level execution context. - /// - /// The specified `origin` address will be used as `sender` for. The `origin` must be a regular - /// account (not a contract). - pub fn top_level( - origin: T::AccountId, - cfg: Rc, - vm: Rc>, - loader: Rc, - ) -> Self { - ExecutionContext { - self_account: origin, - depth: 0, - // deferred: Vec::new(), - config: cfg, - vm: vm, - loader: loader, - } - } - - fn nested(&self, dest: T::AccountId) -> ExecutionContext { - ExecutionContext { - self_account: dest, - depth: self.depth + 1, - // deferred: Vec::new(), - config: Rc::clone(&self.config), - vm: Rc::clone(&self.vm), - loader: Rc::clone(&self.loader), - } - } - - /// Make a call to the specified address, optionally transferring some funds. - pub fn call(&self, dest: T::AccountId, input_data: Vec) -> ExecResult { - if self.depth == self.config.max_depth as usize { - return Err("reached maximum depth, cannot make a call".into()); - } - - // Assumption: `collect_rent` doesn't collide with overlay because - // `collect_rent` will be done on first call and destination contract and balance - // cannot be changed before the first call - let predicate = match >::get(&dest) { - Some(predicate) => predicate, - None => return Err("predicate not found".into()), - }; - - let caller = self.self_account.clone(); - let nested = self.nested(dest); - let executable = nested - .loader - .load_main(predicate) - .map_err(>::from)?; - nested - .vm - .execute(executable, nested.new_call_context(caller), input_data) - } - - fn new_call_context(&self, caller: T::AccountId) -> T::ExternalCall { - T::ExternalCall::new(Rc::new(self.clone()), caller) - } -} - -/// Implementation of `Vm` that takes `PredicateOvm` and executes it. -pub struct PredicateOvm { - _schedule: Rc, - _phantom: PhantomData, -} - -impl PredicateOvm { - pub fn new(_schedule: Rc) -> Self { - PredicateOvm { - _schedule, - _phantom: PhantomData, - } - } -} - -impl Vm for PredicateOvm { - type Executable = OvmExecutable; - - fn execute( - &self, - exec: Self::Executable, - ext: T::ExternalCall, - input_data: Vec, - ) -> ExecResult { - let ext_impl = ext::ExternalCallImpl::::new(&ext); - let executable = ovmi::prepare::executable_from_compiled( - &ext_impl, - exec.code, - exec.payout, - exec.address_inputs.clone(), - exec.bytes_inputs.clone(), - ); - let call_input_data = - ovmi::predicates::PredicateCallInputs::::decode(&mut &input_data[..]) - .map_err(|_| >::from("Call inputs cannot decode error."))?; - CompiledExecutor::>, ext::ExternalCallImpl>::execute( - executable, - call_input_data, - ) - } -} diff --git a/frame/ovm/src/predicate/prepare.rs b/frame/ovm/src/predicate/prepare.rs deleted file mode 100644 index 95c4c9937b..0000000000 --- a/frame/ovm/src/predicate/prepare.rs +++ /dev/null @@ -1,20 +0,0 @@ -use crate::predicate::PrefabOvmModule; -use crate::Schedule; - -/// Loads the given module given in `original_code`, performs some checks on it and -/// does some preprocessing. -/// -/// The checks are: -/// -/// - provided code is a valid predicate codes in ovm. -/// -/// The preprocessing includes injecting code for metering the height of stack. -pub fn prepare_predicate( - original_code: &[u8], - schedule: &Schedule, -) -> Result { - Ok(PrefabOvmModule { - schedule_version: schedule.version, - code: original_code.to_vec(), - }) -} diff --git a/frame/ovm/src/tests.rs b/frame/ovm/src/tests.rs deleted file mode 100644 index 146cc06fd9..0000000000 --- a/frame/ovm/src/tests.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! Tests for the ovm module. - -#![cfg(test)] - -use super::*; -use crate::mock::*; -use frame_support::assert_ok; -use frame_system::{EventRecord, Phase}; - -const VALID_PREDICATE: &str = r#"valid."#; - -#[test] -fn test_calls() { - let (valid_predicate, code_hash) = compile_predicate::(VALID_PREDICATE); - new_test_ext().execute_with(|| { - advance_block(); - assert_ok!(Ovm::put_code( - Origin::signed((*ALICE_STASH).clone()), - valid_predicate.clone() - )); - assert_eq!(Ovm::predicate_codes(&code_hash), Some(valid_predicate),); - assert_eq!( - System::events(), - vec![EventRecord { - phase: Phase::Initialization, - event: MetaEvent::ovm(RawEvent::PutPredicate(code_hash)), - topics: vec![], - }] - ); - }) -} diff --git a/frame/ovm/src/traits.rs b/frame/ovm/src/traits.rs deleted file mode 100644 index bd039c7a12..0000000000 --- a/frame/ovm/src/traits.rs +++ /dev/null @@ -1,96 +0,0 @@ -use super::*; -use crate::predicate::ExecutionContext; - -/// A function that generates an `AccountId` for a predicate upon instantiation. -pub trait PredicateAddressFor { - fn predicate_address_for( - code_hash: &PredicateHash, - data: &[u8], - origin: &AccountId, - ) -> AccountId; -} - -/// Loader is a companion of the `Vm` trait. It loads an appropriate abstract -/// executable to be executed by an accompanying `Vm` implementation. -pub trait Loader { - type Executable; - - /// Load the main portion of the code specified by the `code_hash`. This executable - /// is called for each call to a contract. - fn load_main( - &self, - predicate: PredicateContractOf, - ) -> Result; -} - -/// For the initalize call context. -pub trait NewCallContext { - fn new(ctx: Rc>, caller: AccountIdOf) -> Self; -} - -/// An interface that provides access to the external environment in which the -/// predicate-contract is executed similar to a smart-contract. -/// -/// This interface is specialized to an account of the executing code, so all -/// operations are implicitly performed on that account. -/// -/// Predicate call the only below functions. -/// - call: call to other predicate. -/// - caller: get of the caller of this predicate. -/// - address: the predicate's address. -/// - is_stored: check the storage of other modules or contracts. -pub trait Ext { - /// Call (possibly other predicate) into the specified account. - fn call(&self, to: &AccountIdOf, input_data: Vec) -> ExecResult; - - /// Returns a reference to the account id of the caller. - fn caller(&self) -> &AccountIdOf; - - /// Returns a reference to the account id of the current contract. - fn address(&self) -> &AccountIdOf; - - // TODO: Notes a call other storage. - // Only return true or false. - // CommitmentAddress(special) isCommitment(address) -> Commitment - // is_stored_predicate(&mut self, address, key, value);? - // ref: https://github.com/cryptoeconomicslab/ovm-contracts/blob/master/contracts/Predicate/Atomic/IsStoredPredicate.sol - fn is_stored(&self, _address: &AccountIdOf, _key: &[u8], _value: &[u8]) -> bool; - - /// Needs Plasma. - fn verify_inclusion_with_root( - &self, - leaf: T::Hash, - token_address: AccountIdOf, - range: &[u8], - inclusion_proof: &[u8], - root: &[u8], - ) -> bool; - - fn is_decided(&self, property: &PropertyOf) -> bool; - fn is_decided_by_id(&self, id: T::Hash) -> bool; - - fn set_predicate_decision( - &self, - game_id: T::Hash, - decision: bool, - ) -> Result>; -} - -/// A trait that represent an optimistic virtual machine. -/// -/// You can view an optimistic virtual machine as something that takes code, an input data buffer, -/// queries it and/or performs actions on the given `Ext` and optionally -/// returns an output data buffer. The type of code depends on the particular virtual machine. -/// -/// Execution of code can end by either implicit termination (that is, reached the end of -/// executable), explicit termination via returning a buffer or termination due to a trap. -pub trait Vm { - type Executable; - - fn execute( - &self, - exec: Self::Executable, - ext: T::ExternalCall, - input_data: Vec, - ) -> ExecResult; -} diff --git a/frame/plasm-lockdrop/Cargo.toml b/frame/plasm-lockdrop/Cargo.toml deleted file mode 100644 index a260722e57..0000000000 --- a/frame/plasm-lockdrop/Cargo.toml +++ /dev/null @@ -1,51 +0,0 @@ -[package] -name = "pallet-plasm-lockdrop" -version = "1.7.0" -authors = ["Stake Technologies "] -edition = "2018" -license = "Apache-2.0" -homepage = "https://docs.plasmnet.io/" -repository = "https://github.com/staketechnologies/Plasm/" -description = "FRAME pallet to real-time ETH and BTC lockdrop" - -[dependencies] -serde = { version = "1.0.106", optional = true } -codec = { package = "parity-scale-codec", version = "1.3.5", default-features = false, features = ["derive"] } -num-traits = { version = "0.2", default-features = false } -median = { version = "0.3", default-features = false } -generic-array = { version = "0.11", default-features = false } -hex = { version = "0.4", default-features = false } -bs58 = { version = "0.3.0", default-features = false, features = ["alloc"] } -sp-io = { version = "2.0.0", default-features = false } -sp-std = { version = "2.0.0", default-features = false } -sp-core = { version = "2.0.0", default-features = false } -sp-runtime = { version = "2.0.0", default-features = false } -sp-arithmetic = { version = "2.0.0", default-features = false } -frame-system = { version = "2.0.0", default-features = false } -frame-support = { version = "2.0.0", default-features = false } -pallet-session = { version = "2.0.0", default-features = false } -pallet-timestamp = { version = "2.0.0", default-features = false } - -[dev-dependencies] -hex-literal = "0.2.1" -pallet-balances = { version = "2.0.0" } -sp-staking = { version = "2.0.0" } -sp-keyring = { version = "2.0.0" } -plasm-primitives = { path = "../../bin/node/primitives" } - -[features] -default = ["std","pallet-session/historical"] -std = [ - "serde", - "hex/std", - "codec/std", - "num-traits/std", - "sp-io/std", - "sp-std/std", - "sp-core/std", - "sp-runtime/std", - "frame-system/std", - "frame-support/std", - "pallet-session/std", - "pallet-timestamp/std", -] diff --git a/frame/plasm-lockdrop/src/crypto.rs b/frame/plasm-lockdrop/src/crypto.rs deleted file mode 100644 index c0cfd48aaa..0000000000 --- a/frame/plasm-lockdrop/src/crypto.rs +++ /dev/null @@ -1,100 +0,0 @@ -//! Lockdrop authorities keys. - -use sp_core::ecdsa; -use sp_io::{crypto::secp256k1_ecdsa_recover_compressed, hashing::keccak_256}; -use sp_runtime::app_crypto::KeyTypeId; -use sp_std::vec::Vec; - -/// Plasm Lockdrop Authority local KeyType. -/// -/// For security reasons the offchain worker doesn't have direct access to the keys -/// but only to app-specific subkeys, which are defined and grouped by their `KeyTypeId`. -pub const KEY_TYPE: KeyTypeId = KeyTypeId(*b"plaa"); - -/// SR25519 keys support -pub mod sr25519 { - mod app_sr25519 { - use crate::KEY_TYPE; - use sp_runtime::app_crypto::{app_crypto, sr25519}; - app_crypto!(sr25519, KEY_TYPE); - } - - /// An authority keypair using sr25519 as its crypto. - #[cfg(feature = "std")] - pub type AuthorityPair = app_sr25519::Pair; - - /// An authority signature using sr25519 as its crypto. - pub type AuthoritySignature = app_sr25519::Signature; - - /// An authority identifier using sr25519 as its crypto. - pub type AuthorityId = app_sr25519::Public; -} - -/// ED25519 keys support -pub mod ed25519 { - mod app_ed25519 { - use crate::KEY_TYPE; - use sp_runtime::app_crypto::{app_crypto, ed25519}; - app_crypto!(ed25519, KEY_TYPE); - } - - /// An authority keypair using ed25519 as its crypto. - #[cfg(feature = "std")] - pub type AuthorityPair = app_ed25519::Pair; - - /// An authority signature using ed25519 as its crypto. - pub type AuthoritySignature = app_ed25519::Signature; - - /// An authority identifier using ed25519 as its crypto. - pub type AuthorityId = app_ed25519::Public; -} - -// Constructs the message that Ethereum RPC's `personal_sign` and `eth_sign` would sign. -fn ethereum_signable_message(what: &[u8]) -> Vec { - let mut l = what.len(); - let mut rev = Vec::new(); - while l > 0 { - rev.push(b'0' + (l % 10) as u8); - l /= 10; - } - let mut v = b"\x19Ethereum Signed Message:\n".to_vec(); - v.extend(rev.into_iter().rev()); - v.extend_from_slice(what); - v -} - -// Attempts to recover the Ethereum public key from a message signature signed by using -// the Ethereum RPC's `personal_sign` and `eth_sign`. -pub fn eth_recover(s: &[u8; 65], what: &[u8]) -> Option { - let msg = keccak_256(ðereum_signable_message(what)); - let public = secp256k1_ecdsa_recover_compressed(s, &msg).ok()?; - Some(ecdsa::Public::from_raw(public)) -} - -/* -// Constructs the message that Bitcoin RPC's would sign. -fn bitcoin_signable_message(what: &[u8]) -> Vec { - let mut l = what.len(); - let mut rev = Vec::new(); - while l > 0 { - rev.push(b'0' + (l % 10) as u8); - l /= 10; - } - let mut v = b"\x18Bitcoin Signed Message:\n".to_vec(); - v.extend(rev.into_iter().rev()); - v.extend_from_slice(what); - v -} - -// Attempts to recover the Bitcoin public key from a message signature signed by using -// the Bitcoin RPC's. -pub fn btc_recover(s: &ecdsa::Signature, what: &[u8]) -> Option { - let msg = sha2_256(&bitcoin_signable_message(what)); - match secp256k1_ecdsa_recover_compressed(s.as_ref(), &msg) { - Ok(public) => Some(ecdsa::Public::from_raw(public)), - Err(e) => { - panic!("recover error: {:?}", e.encode()); - } - } -} -*/ diff --git a/frame/plasm-lockdrop/src/lib.rs b/frame/plasm-lockdrop/src/lib.rs deleted file mode 100644 index f2853725a8..0000000000 --- a/frame/plasm-lockdrop/src/lib.rs +++ /dev/null @@ -1,880 +0,0 @@ -//! # Plasm Lockdrop Module -//! This module held lockdrop event on live network. -//! -//! - [`plasm_lockdrop::Trait`](./trait.Trait.html) -//! - [`Call`](./enum.Call.html) -//! -//! ## Overview -//! -//! -//! ## Interface -//! -//! ### Dispatchable Functions -//! -//! -//! [`Call`]: ./enum.Call.html -//! [`Trait`]: ./trait.Trait.html - -// Ensure we're `no_std` when compiling for Wasm. -#![cfg_attr(not(feature = "std"), no_std)] - -use codec::{Decode, Encode}; -use frame_support::{ - debug, decl_error, decl_event, decl_module, decl_storage, - dispatch::Parameter, - ensure, - storage::IterableStorageMap, - traits::{Currency, Get, Time}, - weights::Weight, - StorageMap, StorageValue, -}; -use frame_system::{ - self as system, ensure_none, ensure_root, - offchain::{SendTransactionTypes, SubmitTransaction}, -}; -pub use generic_array::typenum; -use median::{Filter, ListNode}; -use sp_core::{ecdsa, H256}; -use sp_runtime::{ - app_crypto::RuntimeAppPublic, - traits::{AtLeast32Bit, BlakeTwo256, Hash, IdentifyAccount, Member, Saturating}, - transaction_validity::{ - InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity, - ValidTransaction, - }, - DispatchResult, Perbill, RuntimeDebug, -}; -use sp_std::collections::btree_set::BTreeSet; -use sp_std::prelude::*; - -/// Authority keys. -mod crypto; -/// Oracle client. -mod oracle; - -pub use crypto::*; -pub use oracle::*; - -#[cfg(test)] -mod mock; -#[cfg(test)] -mod tests; - -pub type BalanceOf = - <::Currency as Currency<::AccountId>>::Balance; - -#[derive(Encode, Decode, Clone)] -pub struct EcdsaSignature(pub [u8; 65]); - -impl PartialEq for EcdsaSignature { - fn eq(&self, other: &Self) -> bool { - &self.0[..] == &other.0[..] - } -} - -impl sp_std::fmt::Debug for EcdsaSignature { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { - write!(f, "EcdsaSignature({:?})", &self.0[..]) - } -} - -/// The module's main configuration trait. -pub trait Trait: SendTransactionTypes> + frame_system::Trait { - /// The lockdrop balance. - type Currency: Currency; - - /// Lock duration bonuses. - type DurationBonus: DurationBonus; - - /// How long dollar rate parameters valid in secs. - type MedianFilterExpire: Get; - - /// Median filter window size. - type MedianFilterWidth: generic_array::ArrayLength>; - - /// The identifier type for an authority. - type AuthorityId: Member + Parameter + RuntimeAppPublic + Default + Ord; - - /// System level account type. - /// This used for resolving account ID's of ECDSA lockdrop public keys. - type Account: IdentifyAccount + From; - - /// Module that could provide timestamp. - type Time: Time; - - /// Timestamp type. - type Moment: Member - + Parameter - + Saturating - + AtLeast32Bit - + Copy - + Default - + From - + Into - + Into; - - /// Dollar rate number data type. - type DollarRate: Member - + Parameter - + AtLeast32Bit - + num_traits::sign::Unsigned - + Copy - + Default - + Into - + From - + sp_std::str::FromStr; - - // XXX: I don't known how to convert into Balance from u128 without it - // TODO: Should be removed - type BalanceConvert: From - + Into<::AccountId>>::Balance>; - - /// The regular events type. - type Event: From> + Into<::Event>; - - /// Base priority for unsigned transactions. - type UnsignedPriority: Get; -} - -/// Lock duration bonuses, -/// in principle when you lock for long time you'll get more lockdrop tokens. -pub trait DurationBonus { - /// Lockdrop bonus depends of lockding duration (in secs). - fn bonus(duration: u64) -> u16; -} - -pub struct DustyDurationBonus; -impl DurationBonus for DustyDurationBonus { - fn bonus(duration: u64) -> u16 { - const DAYS: u64 = 24 * 60 * 60; // One day in seconds - if duration < 3 * DAYS { - 0 // Dont permit to participate with locking less - } else if duration < 10 * DAYS { - 24 - } else if duration < 30 * DAYS { - 100 - } else if duration < 100 * DAYS { - 360 - } else { - 1600 - } - } -} - -/// Claim id is a hash of claim parameters. -pub type ClaimId = H256; - -/// Type for enumerating claim proof votes. -pub type AuthorityVote = u32; - -/// Type for enumerating authorities in list (2^16 authorities is enough). -pub type AuthorityIndex = u16; - -/// Plasm Lockdrop parameters. -#[cfg_attr(feature = "std", derive(Eq))] -#[derive(Encode, Decode, RuntimeDebug, PartialEq, Clone)] -pub enum Lockdrop { - /// Bitcoin lockdrop is pretty simple: - /// transaction sended with time-lockding opcode, - /// BTC token locked and could be spend some timestamp. - /// Duration in blocks and value in shatoshi could be derived from BTC transaction. - Bitcoin { - transaction_hash: H256, - public_key: ecdsa::Public, - duration: u64, - value: u128, - }, - /// Ethereum lockdrop transactions sent to pre-deployed smart contract. - #[codec(index = 1)] - Ethereum { - transaction_hash: H256, - public_key: ecdsa::Public, - duration: u64, - value: u128, - }, -} - -impl Default for Lockdrop { - fn default() -> Self { - Lockdrop::Ethereum { - public_key: Default::default(), - value: Default::default(), - duration: Default::default(), - transaction_hash: Default::default(), - } - } -} - -/// Lockdrop claim request description. -#[cfg_attr(feature = "std", derive(Eq))] -#[derive(Encode, Decode, RuntimeDebug, PartialEq, Default, Clone)] -pub struct Claim { - params: Lockdrop, - approve: BTreeSet, - decline: BTreeSet, - amount: u128, - complete: bool, -} - -/// Lockdrop claim vote. -#[cfg_attr(feature = "std", derive(Eq))] -#[derive(Encode, Decode, RuntimeDebug, PartialEq, Clone)] -pub struct ClaimVote { - claim_id: ClaimId, - approve: bool, - authority: AuthorityIndex, -} - -/// Oracle dollar rate ticker. -#[cfg_attr(feature = "std", derive(Eq))] -#[derive(Encode, Decode, RuntimeDebug, PartialEq, Clone)] -pub struct TickerRate { - authority: AuthorityIndex, - btc: DollarRate, - eth: DollarRate, -} - -decl_event!( - pub enum Event - where ::AccountId, - ::AuthorityId, - ::DollarRate, - Balance = BalanceOf, - { - /// Lockdrop token claims requested by user - ClaimRequest(ClaimId), - /// Lockdrop token claims response by authority - ClaimResponse(ClaimId, AuthorityId, bool), - /// Lockdrop token claim paid - ClaimComplete(ClaimId, AccountId, Balance), - /// Dollar rate updated by oracle: BTC, ETH. - NewDollarRate(DollarRate, DollarRate), - /// New authority list registered - NewAuthorities(Vec), - } -); - -pub const ERROR_ALREADY_CLAIMED: u8 = 1; -pub const ERROR_WRONG_POW_PROOF: u8 = 2; -pub const ERROR_CLAIM_ON_VOTING: u8 = 3; -pub const ERROR_UNKNOWN_AUTHORITY: u8 = 4; - -decl_error! { - pub enum Error for Module { - /// Unknown authority index in voting message. - UnknownAuthority, - /// This claim already paid to requester. - AlreadyPaid, - /// Votes for this claim isn't enough to pay it. - NotEnoughVotes, - /// Authorities reject this claim request. - NotApproved, - /// Lockdrop isn't run now, request could not be processed. - OutOfBounds, - } -} - -decl_storage! { - trait Store for Module as Provider { - /// Offchain lock check requests made within this block execution. - Requests get(fn requests): Vec; - /// List of lockdrop authority id's. - Keys get(fn keys) config(): Vec; - /// Token claim requests. - Claims get(fn claims): - map hasher(blake2_128_concat) ClaimId - => Claim; - /// Double vote prevention registry. - HasVote get(fn has_vote): - double_map hasher(blake2_128_concat) T::AuthorityId, hasher(blake2_128_concat) ClaimId - => bool; - /// Lockdrop alpha parameter, where α ∈ [0; 1] - Alpha get(fn alpha) config(): Perbill; - /// Lockdrop dollar rate parameter: BTC, ETH. - DollarRate get(fn dollar_rate) config(): (T::DollarRate, T::DollarRate); - /// Lockdrop dollar rate median filter table: Time, BTC, ETH. - DollarRateF get(fn dollar_rate_f): - map hasher(blake2_128_concat) T::AuthorityId - => (T::Moment, T::DollarRate, T::DollarRate); - /// How much authority votes module should receive to decide claim result. - VoteThreshold get(fn vote_threshold) config(): AuthorityVote; - /// How much positive votes requered to approve claim. - /// Positive votes = approve votes - decline votes. - PositiveVotes get(fn positive_votes) config(): AuthorityVote; - /// Timestamp bounds of lockdrop held period. - LockdropBounds get(fn lockdrop_bounds) config(): (T::BlockNumber, T::BlockNumber); - } -} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - type Error = Error; - - /// Initializing events - fn deposit_event() = default; - - /// Clean the state on initialisation of a block - fn on_initialize(_now: T::BlockNumber) -> Weight { - // At the beginning of each block execution, system triggers all - // `on_initialize` functions, which allows us to set up some temporary state or - like - // in this case - clean up other states - ::kill(); - // TODO: weight - 50_000 - } - - /// Request authorities to check locking transaction. - /// TODO: weight - #[weight = 50_000] - fn request( - origin, - params: Lockdrop, - _nonce: H256, - ) -> DispatchResult { - ensure_none(origin)?; - - let claim_id = BlakeTwo256::hash_of(¶ms); - ensure!( - !>::get(claim_id).complete, - Error::::AlreadyPaid, - ); - - if !>::contains_key(claim_id) { - let now = >::block_number(); - ensure!(Self::is_active(now), Error::::OutOfBounds); - - let amount = match params { - Lockdrop::Bitcoin { .. } => { - // Cast bitcoin value to PLM order: - // satoshi = BTC * 10^9; - // PLM unit = PLM * 10^15; - // (it also helps to make evaluations more precise) - //let value_btc = value * 1_000_000; - //Self::btc_issue_amount(value_btc, duration) - - // XXX - 0 - }, - Lockdrop::Ethereum { value, duration, .. } => { - // Cast Ethereum value to PLM order: - // satoshi = ETH * 10^18; - // PLM unit = PLM * 10^15; - // (it also helps to make evaluations more precise) - let value_eth = value / 1_000; - Self::eth_issue_amount(value_eth, duration) - } - }; - let claim = Claim { params, amount, .. Default::default() }; - >::insert(claim_id, claim); - } - - ::mutate(|requests| requests.push(claim_id)); - Self::deposit_event(RawEvent::ClaimRequest(claim_id)); - - Ok(()) - } - - /// Claim tokens for the lockdrop public key. - /// TODO: weight - #[weight = 50_000] - fn claim( - origin, - claim_id: ClaimId, - ) -> DispatchResult { - ensure_none(origin)?; - Self::claim_token(claim_id, None) - } - - /// Claim tokens for any account address. - /// TODO: weight - #[weight = 50_000] - fn claim_to( - origin, - claim_id: ClaimId, - recipient: T::AccountId, - // since signature verification is done in `validate_unsigned` - // we can skip doing it here again. - _signature: EcdsaSignature, - ) -> DispatchResult { - ensure_none(origin)?; - Self::claim_token(claim_id, Some(recipient)) - } - - /// Vote for claim request according to check results. (for authorities only) - /// TODO: weight - #[weight = 50_000] - fn vote( - origin, - vote: ClaimVote, - // since signature verification is done in `validate_unsigned` - // we can skip doing it here again. - _signature: ::Signature, - ) -> DispatchResult { - ensure_none(origin)?; - - let keys = Keys::::get(); - if let Some(authority) = keys.get(vote.authority as usize) { - >::insert(authority, &vote.claim_id, true); - Self::deposit_event(RawEvent::ClaimResponse(vote.claim_id, authority.clone(), vote.approve)); - - >::mutate(&vote.claim_id, |claim| - if vote.approve { - claim.approve.insert(authority.clone()); - claim.decline.remove(&authority); - } - else { - claim.decline.insert(authority.clone()); - claim.approve.remove(&authority); - } - ); - - Ok(()) - } else { - Err(Error::::UnknownAuthority)? - } - } - - /// Dollar Rate oracle entrypoint. (for authorities only) - /// TODO: weight - #[weight = 50_000] - fn set_dollar_rate( - origin, - rate: TickerRate, - // since signature verification is done in `validate_unsigned` - // we can skip doing it here again. - _signature: ::Signature, - ) -> DispatchResult { - ensure_none(origin)?; - - let now = T::Time::now(); - - let keys = Keys::::get(); - if let Some(authority) = keys.get(rate.authority as usize) { - DollarRateF::::insert(authority, (now, rate.btc, rate.eth)); - } else { - return Err(Error::::UnknownAuthority)? - } - - let expire = T::MedianFilterExpire::get(); - let mut btc_filter: Filter = Filter::new(); - let mut eth_filter: Filter = Filter::new(); - let (mut btc_filtered_rate, mut eth_filtered_rate) = >::get(); - for (a, item) in >::iter() { - if now.saturating_sub(item.0) < expire { - // Use value in filter when not expired - btc_filtered_rate = btc_filter.consume(item.1); - eth_filtered_rate = eth_filter.consume(item.2); - } else { - // Drop value when expired - >::remove(a); - } - } - - >::put((btc_filtered_rate, eth_filtered_rate)); - Self::deposit_event(RawEvent::NewDollarRate(btc_filtered_rate, eth_filtered_rate)); - - Ok(()) - } - - /// Set lockdrop alpha value. - #[weight = 50_000] - fn set_alpha(origin, alpha_parts: u32) { - ensure_root(origin)?; - ::put(Perbill::from_parts(alpha_parts)); - } - - /// Set lockdrop held time. - #[weight = 50_000] - fn set_bounds(origin, from: T::BlockNumber, to: T::BlockNumber) { - ensure_root(origin)?; - ensure!(from < to, "wrong arguments"); - >::put((from, to)); - } - - /// Set minimum of positive votes required for lock approve. - #[weight = 50_000] - fn set_positive_votes(origin, count: AuthorityVote) { - ensure_root(origin)?; - ensure!(count > 0, "wrong argument"); - ::put(count); - } - - /// Set minimum votes required to pass lock confirmation process. - #[weight = 50_000] - fn set_vote_threshold(origin, count: AuthorityVote) { - ensure_root(origin)?; - ensure!(count > 0, "wrong argument"); - ::put(count); - } - - /// Set lockdrop authorities list. - #[weight = 50_000] - fn set_authorities(origin, authorities: Vec) { - ensure_root(origin)?; - Keys::::put(authorities.clone()); - Self::deposit_event(RawEvent::NewAuthorities(authorities)); - } - - // Runs after every block within the context and current state of said block. - fn offchain_worker(now: T::BlockNumber) { - // Launch if validator and lockdrop is active. - if Self::is_active(now) && T::AuthorityId::all().len() > 0 { - debug::RuntimeLogger::init(); - - match Self::offchain() { - Err(_) => debug::error!( - target: "lockdrop-offchain-worker", - "lockdrop worker failed", - ), - _ => (), - } - } - } - } -} - -impl Module { - /// The main offchain worker entry point. - fn offchain() -> Result<(), ()> { - for key in T::AuthorityId::all() { - let delay = T::Time::now() - >::get(key.clone()).0; - if delay > T::MedianFilterExpire::get() { - Self::send_dollar_rate(key)?; - } - } - Self::claim_request_oracle() - } - - fn claim_request_oracle() -> Result<(), ()> { - for claim_id in Self::requests() { - debug::debug!( - target: "lockdrop-offchain-worker", - "new claim request: id = {}", claim_id - ); - - let approve = Self::check_lock(claim_id)?; - debug::info!( - target: "lockdrop-offchain-worker", - "claim id {} => check result: {}", claim_id, approve - ); - - for key in T::AuthorityId::all() { - if let Some(authority) = Self::authority_index_of(&key) { - let vote = ClaimVote { - authority, - claim_id, - approve, - }; - let signature = key.sign(&vote.encode()).ok_or(())?; - let call = Call::vote(vote, signature); - debug::debug!( - target: "lockdrop-offchain-worker", - "claim id {} => vote extrinsic: {:?}", claim_id, call - ); - - let res = - SubmitTransaction::>::submit_unsigned_transaction(call.into()); - debug::debug!( - target: "lockdrop-offchain-worker", - "claim id {} => vote extrinsic send: {:?}", claim_id, res - ); - } - } - } - - Ok(()) - } - - /// Send dollar rate as unsigned extrinsic from authority. - fn send_dollar_rate(key: T::AuthorityId) -> Result<(), ()> { - if let Some(authority) = Self::authority_index_of(&key) { - let btc_price: f32 = BitcoinPrice::fetch()?; - let eth_price: f32 = EthereumPrice::fetch()?; - - let rate = TickerRate { - authority, - btc: (btc_price as u32).into(), - eth: (eth_price as u32).into(), - }; - let signature = key.sign(&rate.encode()).ok_or(())?; - let call = Call::set_dollar_rate(rate, signature); - debug::debug!( - target: "lockdrop-offchain-worker", - "dollar rate extrinsic: {:?}", call - ); - - let res = SubmitTransaction::>::submit_unsigned_transaction(call.into()); - debug::debug!( - target: "lockdrop-offchain-worker", - "dollar rate extrinsic send: {:?}", res - ); - } else { - debug::debug!( - target: "lockdrop-offchain-worker", - "key {:?} is not lockdrop authority", key - ); - } - - Ok(()) - } - - /// Check locking parameters of given claim. - fn check_lock(claim_id: ClaimId) -> Result { - let Claim { params, .. } = Self::claims(claim_id); - match params { - Lockdrop::Bitcoin { .. } => { - /* - let success = BitcoinLock::check(transaction_hash, public_key, duration, value)?; - debug::debug!( - target: "lockdrop-offchain-worker", - "claim id {} => lock result: {}", claim_id, success - ); - Ok(success) - */ - Err(()) - } - Lockdrop::Ethereum { - transaction_hash, - public_key, - duration, - value, - } => { - let success = EthereumLock::check(transaction_hash, public_key, duration, value)?; - debug::debug!( - target: "lockdrop-offchain-worker", - "claim id {} => lock result: {}", claim_id, success - ); - Ok(success) - } - } - } - - fn claim_token(claim_id: ClaimId, recipient: Option) -> DispatchResult { - let claim = >::get(claim_id); - ensure!(!claim.complete, Error::::AlreadyPaid); - - let approve = claim.approve.len(); - let decline = claim.decline.len(); - ensure!( - approve + decline >= ::get() as usize, - Error::::NotEnoughVotes, - ); - ensure!( - approve.saturating_sub(decline) >= ::get() as usize, - Error::::NotApproved, - ); - - let account = recipient.unwrap_or({ - // Deposit lockdrop tokens on locking public key. - let public_key = match claim.params { - Lockdrop::Bitcoin { public_key, .. } => public_key, - Lockdrop::Ethereum { public_key, .. } => public_key, - }; - T::Account::from(public_key).into_account() - }); - let amount: BalanceOf = T::BalanceConvert::from(claim.amount).into(); - T::Currency::deposit_creating(&account, amount); - - // Finalize claim request - >::mutate(claim_id, |claim| claim.complete = true); - Self::deposit_event(RawEvent::ClaimComplete(claim_id, account, amount)); - - Ok(()) - } - - /* - /// PLM issue amount for given BTC value and locking duration (in secs). - fn btc_issue_amount(value: u128, duration: u64) -> u128 { - // https://medium.com/stake-technologies/plasm-lockdrop-introduction-99fa2dfc37c0 - let rate = Self::alpha() * Self::dollar_rate().0 * T::DurationBonus::bonus(duration).into(); - rate.into() * value - } - */ - - /// PLM issue amount for given ETH value and locking duration (in secs). - fn eth_issue_amount(value: u128, duration: u64) -> u128 { - // https://medium.com/stake-technologies/plasm-lockdrop-introduction-99fa2dfc37c0 - let rate = Self::alpha() * Self::dollar_rate().1 * T::DurationBonus::bonus(duration).into(); - rate.into() * value - } - - /// Check that authority key list contains given account - fn authority_index_of(public: &T::AuthorityId) -> Option { - let keys = Keys::::get(); - // O(n) is ok because of short list - for (i, elem) in keys.iter().enumerate() { - if elem.eq(public) { - return Some(i as AuthorityIndex); - } - } - None - } - - /// Check that block suits lockdrop bounds. - fn is_active(now: T::BlockNumber) -> bool { - let bounds = >::get(); - now >= bounds.0 && now < bounds.1 - } - - /// Create message to sign it for claiming to custom address. - fn claim_message(claim_id: &ClaimId, recipient: &T::AccountId) -> Vec { - let mut v = b"I declare to claim lockdrop reward with ID ".to_vec(); - v.extend(hex::encode(claim_id).bytes()); - v.extend(" to AccountId ".bytes()); - v.extend(hex::encode(recipient.encode()).bytes()); - v - } -} - -impl sp_runtime::BoundToRuntimeAppPublic for Module { - type Public = T::AuthorityId; -} - -impl frame_support::unsigned::ValidateUnsigned for Module { - type Call = Call; - - fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { - match call { - Call::request(params, nonce) => { - if !matches!(params, Lockdrop::Ethereum{..}) { - // Only Ethereum requests allowed - return InvalidTransaction::Call.into(); - } - - let claim_id = BlakeTwo256::hash_of(¶ms); - if >::get(claim_id).complete { - return InvalidTransaction::Custom(ERROR_ALREADY_CLAIMED).into(); - } - - // Simple proof of work - let pow_byte = BlakeTwo256::hash_of(&(claim_id, nonce)).as_bytes()[0]; - if pow_byte > 0 { - return InvalidTransaction::Custom(ERROR_WRONG_POW_PROOF).into(); - } - - ValidTransaction::with_tag_prefix("PlasmLockdrop") - .priority(T::UnsignedPriority::get()) - .and_provides((params, nonce)) - .longevity(64_u64) - .propagate(true) - .build() - } - - Call::claim(claim_id) => { - let claim = >::get(claim_id); - if claim.complete { - return InvalidTransaction::Custom(ERROR_ALREADY_CLAIMED).into(); - } - - let approve = claim.approve.len(); - let decline = claim.decline.len(); - let on_vote = approve + decline < ::get() as usize; - let not_approved = - approve.saturating_sub(decline) < ::get() as usize; - if on_vote || not_approved { - return InvalidTransaction::Custom(ERROR_CLAIM_ON_VOTING).into(); - } - - ValidTransaction::with_tag_prefix("PlasmLockdrop") - .priority(T::UnsignedPriority::get()) - .and_provides(claim_id) - .longevity(64_u64) - .propagate(true) - .build() - } - - Call::claim_to(claim_id, recipient, signature) => { - let claim = >::get(claim_id); - if claim.complete { - return InvalidTransaction::Custom(ERROR_ALREADY_CLAIMED).into(); - } - - let approve = claim.approve.len(); - let decline = claim.decline.len(); - let on_vote = approve + decline < ::get() as usize; - let not_approved = - approve.saturating_sub(decline) < ::get() as usize; - if on_vote || not_approved { - return InvalidTransaction::Custom(ERROR_CLAIM_ON_VOTING).into(); - } - - let msg = Self::claim_message(claim_id, recipient); - match claim.params { - Lockdrop::Bitcoin { .. } => { - // Only Ethereum requests allowed - return InvalidTransaction::Call.into(); - /* - let signer = crypto::btc_recover(signature, msg.as_ref()); - if signer != Some(public_key) { - return InvalidTransaction::BadProof.into(); - } - */ - } - Lockdrop::Ethereum { public_key, .. } => { - let signer = crypto::eth_recover(&signature.0, msg.as_ref()); - if signer != Some(public_key) { - return InvalidTransaction::BadProof.into(); - } - } - } - - ValidTransaction::with_tag_prefix("PlasmLockdrop") - .priority(T::UnsignedPriority::get()) - .and_provides((claim_id, recipient)) - .longevity(64_u64) - .propagate(true) - .build() - } - - Call::vote(vote, signature) => { - // Verify call params - if !>::contains_key(vote.claim_id.clone()) { - return InvalidTransaction::Call.into(); - } - - vote.using_encoded(|encoded_vote| { - // Verify authority - let keys = Keys::::get(); - if let Some(authority) = keys.get(vote.authority as usize) { - // Check that sender is authority - if !authority.verify(&encoded_vote, &signature) { - return InvalidTransaction::BadProof.into(); - } - } else { - return InvalidTransaction::Custom(ERROR_UNKNOWN_AUTHORITY).into(); - } - - ValidTransaction::with_tag_prefix("PlasmLockdrop") - .priority(T::UnsignedPriority::get()) - .and_provides(encoded_vote) - .longevity(64_u64) - .propagate(true) - .build() - }) - } - - Call::set_dollar_rate(rate, signature) => { - rate.using_encoded(|encoded_rate| { - let keys = Keys::::get(); - if let Some(authority) = keys.get(rate.authority as usize) { - // Check that sender is authority - if !authority.verify(&encoded_rate, &signature) { - return InvalidTransaction::BadProof.into(); - } - } else { - return InvalidTransaction::Custom(ERROR_UNKNOWN_AUTHORITY).into(); - } - - ValidTransaction::with_tag_prefix("PlasmLockdrop") - .priority(T::UnsignedPriority::get()) - .and_provides(encoded_rate.to_vec()) - .longevity(64_u64) - .propagate(true) - .build() - }) - } - - _ => InvalidTransaction::Call.into(), - } - } -} diff --git a/frame/plasm-lockdrop/src/mock.rs b/frame/plasm-lockdrop/src/mock.rs deleted file mode 100644 index 018231d894..0000000000 --- a/frame/plasm-lockdrop/src/mock.rs +++ /dev/null @@ -1,159 +0,0 @@ -//! Runtime mockup for plasm-lockdrop module. - -#![cfg(test)] - -use super::*; -use plasm_primitives::{AccountId, Balance, Moment}; - -use frame_support::{impl_outer_dispatch, impl_outer_origin, parameter_types, weights::Weight}; -use hex_literal::hex; -use sp_core::crypto::UncheckedInto; -use sp_runtime::{ - testing::{Header, TestXt}, - traits::IdentityLookup, - MultiSigner, Perbill, -}; - -impl_outer_origin! { - pub enum Origin for Runtime {} -} - -impl_outer_dispatch! { - pub enum Call for Runtime where origin: Origin { - pallet_balances::Balances, - pallet_plasm_lockdrop::PlasmLockdrop, - } -} - -#[derive(Clone, PartialEq, Eq, Debug)] -pub struct Runtime; - -parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: Weight = 1024; - pub const MaximumBlockLength: u32 = 2 * 1024; - pub const AvailableBlockRatio: Perbill = Perbill::one(); -} - -impl frame_system::Trait for Runtime { - type Origin = Origin; - type BaseCallFilter = (); - type Index = u64; - type BlockNumber = u64; - type Call = Call; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; - type Header = Header; - type Event = (); - type BlockHashCount = BlockHashCount; - type MaximumBlockWeight = MaximumBlockWeight; - type MaximumBlockLength = MaximumBlockLength; - type AvailableBlockRatio = AvailableBlockRatio; - type Version = (); - type PalletInfo = (); - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = (); - type SystemWeightInfo = (); -} - -parameter_types! { - pub const MinimumPeriod: u64 = 1; -} - -impl pallet_timestamp::Trait for Runtime { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); -} - -parameter_types! { - pub const Period: u64 = 1; - pub const Offset: u64 = 0; -} - -parameter_types! { - pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(33); -} - -parameter_types! { - pub const ExistentialDeposit: Balance = 10; -} - -impl pallet_balances::Trait for Runtime { - type Balance = Balance; - type Event = (); - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Module; - type WeightInfo = (); - type MaxLocks = (); -} - -parameter_types! { - pub const MedianFilterExpire: Moment = 2; -} - -/// An extrinsic type used for tests. -pub type Extrinsic = TestXt; - -impl frame_system::offchain::SendTransactionTypes for Runtime -where - Call: From, -{ - type OverarchingCall = Call; - type Extrinsic = Extrinsic; -} - -impl Trait for Runtime { - type Currency = Balances; - type DurationBonus = DustyDurationBonus; - type MedianFilterExpire = MedianFilterExpire; - type MedianFilterWidth = generic_array::typenum::U3; - type AuthorityId = sr25519::AuthorityId; - type Account = MultiSigner; - type Time = Timestamp; - type Moment = Moment; - type DollarRate = Balance; - type BalanceConvert = Balance; - type Event = (); - type UnsignedPriority = (); -} - -pub type Balances = pallet_balances::Module; -pub type Timestamp = pallet_timestamp::Module; -pub type PlasmLockdrop = Module; - -pub fn new_test_ext() -> sp_io::TestExternalities { - let alice: ::AuthorityId = - hex!["c83f0a4067f1b166132ed45995eee17ba7aeafeea27fe17550728ee34f998c4e"].unchecked_into(); - let bob: ::AuthorityId = - hex!["fa1b7e37aa3e463c81215f63f65a7c2b36ced251dd6f1511d357047672afa422"].unchecked_into(); - let charlie: ::AuthorityId = - hex!["88da12401449623ab60f20ed4302ab6e5db53de1e7b5271f35c858ab8b5ab37f"].unchecked_into(); - - let mut storage = system::GenesisConfig::default() - .build_storage::() - .unwrap(); - - let _ = GenesisConfig:: { - keys: vec![alice, bob, charlie], - // Alpha2: 0.44698108660714747 - alpha: Perbill::from_parts(446_981_087), - // Price in cents: BTC $9000, ETH $200 - dollar_rate: (9_000, 200), - vote_threshold: 3, - positive_votes: 2, - lockdrop_bounds: (0, 1_000_000), - } - .assimilate_storage(&mut storage); - - storage.into() -} diff --git a/frame/plasm-lockdrop/src/oracle.rs b/frame/plasm-lockdrop/src/oracle.rs deleted file mode 100644 index 9521f187d3..0000000000 --- a/frame/plasm-lockdrop/src/oracle.rs +++ /dev/null @@ -1,152 +0,0 @@ -//! Plasm Lockdrop Oracle module client. -//! -//! Lockdrop Oracle has REST HTTP API: -//! -//! **GET** -//! - /btc/ticker - returns BTC price in USD -//! - /eth/ticker - returns ETH price in USD -//! -//! **POST** -//! - /eth/lock -//! Body: LockCheck struct -//! Returns: `OK` when lock success -//! -//! - /btc/lock -//! Body: LockCheck struct -//! Returns `OK` when lock success -//! - -use codec::{Decode, Encode}; -use frame_support::debug; -use sp_core::{ecdsa, H256}; -use sp_runtime::{offchain::http::Request, RuntimeDebug}; -use sp_std::prelude::*; - -/// HTTP source of currency price. -pub trait PriceOracle { - /// HTTP request URI - fn uri() -> &'static str; - - /// Fetch price data, parse it and return raw dollar rate. - /// Note: this method requires off-chain worker context. - fn fetch() -> Result { - let uri = Self::uri(); - debug::debug!( - target: "lockdrop-offchain-worker", - "Price oracle request to {}", uri - ); - - let request = Request::get(uri).send().map_err(|e| { - debug::error!( - target: "lockdrop-offchain-worker", - "Request error: {:?}", e - ); - })?; - - let response = request.wait().map_err(|e| { - debug::error!( - target: "lockdrop-offchain-worker", - "Response error: {:?}", e - ); - })?; - - let body = response.body().collect::>(); - let price = sp_std::str::from_utf8(&body[..]).map_err(|e| { - debug::error!( - target: "lockdrop-offchain-worker", - "Response body isn't UTF-8 string: {:?}", e - ); - })?; - - price.parse().map_err(|_| { - debug::error!( - target: "lockdrop-offchain-worker", - "Response body string parsing error" - ); - }) - } -} - -/// BTC price oracle. -pub struct BitcoinPrice; -impl PriceOracle for BitcoinPrice { - fn uri() -> &'static str { - "http://127.0.0.1:34347/btc/ticker" - } -} - -/// ETH price oracle. -pub struct EthereumPrice; -impl PriceOracle for EthereumPrice { - fn uri() -> &'static str { - "http://127.0.0.1:34347/eth/ticker" - } -} - -/// Lock check request parameters. -#[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode)] -pub struct LockCheck { - /// Transaction hash. - pub tx_hash: H256, - /// Sender public key. - pub public_key: ecdsa::Public, - /// Lock duration in seconds. - pub duration: u64, - /// Lock value in units. - pub value: u128, -} - -/// HTTP source of blockchain transactions. -pub trait LockOracle { - /// HTTP request URI - fn uri() -> &'static str; - - /// Check lock transaction data. - /// Note: this method requires off-chain worker context. - fn check( - tx_hash: H256, - public_key: ecdsa::Public, - duration: u64, - value: u128, - ) -> Result { - let lock = LockCheck { - tx_hash, - public_key, - duration, - value, - }; - let request = Request::post(Self::uri(), vec![lock.encode()]) - .send() - .map_err(|e| { - debug::error!( - target: "lockdrop-offchain-worker", - "Request error: {:?}", e - ); - })?; - - let response = request.wait().map_err(|e| { - debug::error!( - target: "lockdrop-offchain-worker", - "Response error: {:?}", e - ); - })?; - - Ok(response.code == 200) - } -} - -/// Bitcoin chain transactions oracle. -pub struct BitcoinLock; -impl LockOracle for BitcoinLock { - fn uri() -> &'static str { - "http://127.0.0.1:34347/btc/lock" - } -} - -/// Ethereum chain transactions oracle. -pub struct EthereumLock; -impl LockOracle for EthereumLock { - fn uri() -> &'static str { - "http://127.0.0.1:34347/eth/lock" - } -} diff --git a/frame/plasm-lockdrop/src/tests.rs b/frame/plasm-lockdrop/src/tests.rs deleted file mode 100644 index 034dadbf83..0000000000 --- a/frame/plasm-lockdrop/src/tests.rs +++ /dev/null @@ -1,703 +0,0 @@ -//! Tests for the plasm-lockdrop module. - -#![cfg(test)] - -use super::*; -use crate::mock::*; - -use frame_support::unsigned::ValidateUnsigned; -use frame_support::{assert_noop, assert_ok}; -use hex_literal::hex; -use plasm_primitives::AccountId; -use sp_core::{ - crypto::UncheckedInto, - offchain::{ - testing::{TestOffchainExt, TestTransactionPoolExt}, - OffchainExt, TransactionPoolExt, - }, - testing::KeyStore, - traits::KeystoreExt, - Pair, -}; -use sp_runtime::DispatchError; - -#[test] -fn lockdrop_authorities() { - let alice: ::AuthorityId = - hex!["c83f0a4067f1b166132ed45995eee17ba7aeafeea27fe17550728ee34f998c4e"].unchecked_into(); - let bob: ::AuthorityId = - hex!["fa1b7e37aa3e463c81215f63f65a7c2b36ced251dd6f1511d357047672afa422"].unchecked_into(); - let charlie: ::AuthorityId = - hex!["88da12401449623ab60f20ed4302ab6e5db53de1e7b5271f35c858ab8b5ab37f"].unchecked_into(); - let dave: ::AuthorityId = - hex!["1a0f0be3d6596d1dbc302243fe4e975ff20de67559100053024d8f5a7b435b2b"].unchecked_into(); - - new_test_ext().execute_with(|| { - assert_noop!( - PlasmLockdrop::set_authorities(Origin::none(), vec![]), - DispatchError::BadOrigin, - ); - - assert_eq!(PlasmLockdrop::authority_index_of(&alice), Some(0)); - assert_eq!(PlasmLockdrop::authority_index_of(&bob), Some(1)); - assert_eq!(PlasmLockdrop::authority_index_of(&charlie), Some(2)); - assert_eq!(PlasmLockdrop::authority_index_of(&dave), None); - - assert_ok!(PlasmLockdrop::set_authorities( - Origin::root(), - vec![bob.clone(), charlie.clone()], - )); - assert_eq!(>::get(), vec![bob.clone(), charlie.clone()]); - assert_eq!(PlasmLockdrop::authority_index_of(&alice), None); - assert_eq!(PlasmLockdrop::authority_index_of(&bob), Some(0)); - assert_eq!(PlasmLockdrop::authority_index_of(&charlie), Some(1)); - assert_eq!(PlasmLockdrop::authority_index_of(&dave), None); - - assert_ok!(PlasmLockdrop::set_authorities( - Origin::root(), - vec![alice.clone(), bob.clone()], - )); - assert_eq!(>::get(), vec![alice.clone(), bob.clone()]); - assert_eq!(PlasmLockdrop::authority_index_of(&alice), Some(0)); - assert_eq!(PlasmLockdrop::authority_index_of(&bob), Some(1)); - assert_eq!(PlasmLockdrop::authority_index_of(&charlie), None); - assert_eq!(PlasmLockdrop::authority_index_of(&dave), None); - }) -} - -#[test] -fn oracle_unsinged_transaction() { - let rate = TickerRate { - btc: 10, - eth: 12, - authority: 0, - }; - let vote = ClaimVote { - claim_id: Default::default(), - approve: false, - authority: 0, - }; - - new_test_ext().execute_with(|| { - // Invalid signature - let dispatch = PlasmLockdrop::pre_dispatch(&crate::Call::set_dollar_rate( - rate.clone(), - Default::default(), - )) - .map_err(|e| <&'static str>::from(e)); - assert_noop!(dispatch, "Transaction has a bad signature"); - - // Invalid call - let dispatch = PlasmLockdrop::pre_dispatch(&crate::Call::claim(Default::default())) - .map_err(|e| <&'static str>::from(e)); - assert_noop!(dispatch, "InvalidTransaction custom error"); - - let bad_account: AccountId = sp_keyring::sr25519::Keyring::Dave.into(); - let bad_pair = - sr25519::AuthorityPair::from_string(&format!("//{}", bad_account), None).unwrap(); - - let bad_rate = TickerRate { - btc: 666, - eth: 666, - authority: 4, - }; - let signature = bad_pair.sign(&bad_rate.encode()); - let dispatch = - PlasmLockdrop::pre_dispatch(&crate::Call::set_dollar_rate(bad_rate, signature)) - .map_err(|e| <&'static str>::from(e)); - assert_noop!(dispatch, "InvalidTransaction custom error"); - - let lockdrop: Lockdrop = Default::default(); - assert_ok!(PlasmLockdrop::request( - Origin::none(), - lockdrop.clone(), - Default::default(), - )); - let bad_vote = ClaimVote { - claim_id: BlakeTwo256::hash_of(&lockdrop), - authority: 4, - ..vote - }; - let signature = bad_pair.sign(&bad_vote.encode()); - let dispatch = PlasmLockdrop::pre_dispatch(&crate::Call::vote(bad_vote, signature)) - .map_err(|e| <&'static str>::from(e)); - assert_noop!(dispatch, "InvalidTransaction custom error"); - - let account: AccountId = sp_keyring::sr25519::Keyring::Alice.into(); - let pair = sr25519::AuthorityPair::from_string(&format!("//{}", account), None).unwrap(); - - // Invalid parameter - let signature = pair.sign(&vote.encode()); - let dispatch = PlasmLockdrop::pre_dispatch(&crate::Call::vote(vote.clone(), signature)) - .map_err(|e| <&'static str>::from(e)); - assert_noop!(dispatch, "Transaction call is not expected"); - - // Valid signature & params - let signature = pair.sign(&rate.encode()); - let dispatch = PlasmLockdrop::pre_dispatch(&crate::Call::set_dollar_rate(rate, signature)); - assert_ok!(dispatch); - - // Valid signature & params - let valid_vote = ClaimVote { - claim_id: BlakeTwo256::hash_of(&lockdrop), - ..vote - }; - let signature = pair.sign(&valid_vote.encode()); - let dispatch = - PlasmLockdrop::pre_dispatch(&crate::Call::vote(valid_vote.clone(), signature.clone())); - assert_ok!(dispatch); - assert_ok!(PlasmLockdrop::vote( - Origin::none(), - valid_vote.clone(), - signature.clone() - )); - - // Double vote is not a problem, decision could be changed because of transaction - // confirmation or other reasons. - let dispatch = PlasmLockdrop::pre_dispatch(&crate::Call::vote(valid_vote, signature)); - assert_ok!(dispatch); - }); -} - -#[test] -fn dollar_rate_median_filter() { - let alice: ::AuthorityId = - hex!["c83f0a4067f1b166132ed45995eee17ba7aeafeea27fe17550728ee34f998c4e"].unchecked_into(); - let bob: ::AuthorityId = - hex!["fa1b7e37aa3e463c81215f63f65a7c2b36ced251dd6f1511d357047672afa422"].unchecked_into(); - let charlie: ::AuthorityId = - hex!["88da12401449623ab60f20ed4302ab6e5db53de1e7b5271f35c858ab8b5ab37f"].unchecked_into(); - - new_test_ext().execute_with(|| { - let rate = TickerRate { - btc: 10, - eth: 12, - authority: 0, - }; - assert_ok!(PlasmLockdrop::set_dollar_rate( - Origin::none(), - rate, - Default::default() - )); - assert_eq!(>::get(), (10, 12)); - assert_eq!(>::get(alice.clone()), (0, 10, 12)); - - let rate = TickerRate { - btc: 9, - eth: 11, - authority: 1, - }; - assert_ok!(PlasmLockdrop::set_dollar_rate( - Origin::none(), - rate, - Default::default() - )); - assert_eq!(>::get(), (9, 11)); - assert_eq!(>::get(bob.clone()), (0, 9, 11)); - - let rate = TickerRate { - btc: 15, - eth: 3, - authority: 2, - }; - assert_ok!(PlasmLockdrop::set_dollar_rate( - Origin::none(), - rate, - Default::default() - )); - assert_eq!(>::get(), (10, 11)); - assert_eq!(>::get(charlie.clone()), (0, 15, 3)); - - Timestamp::set_timestamp(1); - - let rate = TickerRate { - btc: 11, - eth: 11, - authority: 0, - }; - assert_ok!(PlasmLockdrop::set_dollar_rate( - Origin::none(), - rate, - Default::default() - )); - assert_eq!(>::get(), (11, 11)); - assert_eq!(>::get(alice), (1, 11, 11)); - - let rate = TickerRate { - btc: 9, - eth: 11, - authority: 1, - }; - assert_ok!(PlasmLockdrop::set_dollar_rate( - Origin::none(), - rate, - Default::default() - )); - assert_eq!(>::get(), (11, 11)); - assert_eq!(>::get(bob), (1, 9, 11)); - - let rate = TickerRate { - btc: 50, - eth: 25, - authority: 2, - }; - assert_ok!(PlasmLockdrop::set_dollar_rate( - Origin::none(), - rate, - Default::default() - )); - assert_eq!(>::get(), (11, 11)); - assert_eq!(>::get(charlie), (1, 50, 25)); - }) -} - -#[test] -fn dollar_rate_should_expire() { - let alice: ::AuthorityId = - hex!["c83f0a4067f1b166132ed45995eee17ba7aeafeea27fe17550728ee34f998c4e"].unchecked_into(); - let bob: ::AuthorityId = - hex!["fa1b7e37aa3e463c81215f63f65a7c2b36ced251dd6f1511d357047672afa422"].unchecked_into(); - let charlie: ::AuthorityId = - hex!["88da12401449623ab60f20ed4302ab6e5db53de1e7b5271f35c858ab8b5ab37f"].unchecked_into(); - - new_test_ext().execute_with(|| { - let rate = TickerRate { - btc: 10, - eth: 12, - authority: 0, - }; - assert_ok!(PlasmLockdrop::set_dollar_rate( - Origin::none(), - rate, - Default::default() - )); - assert_eq!(>::get(), (10, 12)); - assert_eq!(>::get(alice.clone()), (0, 10, 12)); - - let rate = TickerRate { - btc: 9, - eth: 11, - authority: 1, - }; - assert_ok!(PlasmLockdrop::set_dollar_rate( - Origin::none(), - rate, - Default::default() - )); - assert_eq!(>::get(), (9, 11)); - assert_eq!(>::get(bob.clone()), (0, 9, 11)); - - let rate = TickerRate { - btc: 15, - eth: 3, - authority: 2, - }; - assert_ok!(PlasmLockdrop::set_dollar_rate( - Origin::none(), - rate, - Default::default() - )); - assert_eq!(>::get(), (10, 11)); - assert_eq!(>::get(charlie.clone()), (0, 15, 3)); - - Timestamp::set_timestamp(1); - - let rate = TickerRate { - btc: 50, - eth: 50, - authority: 0, - }; - assert_ok!(PlasmLockdrop::set_dollar_rate( - Origin::none(), - rate, - Default::default() - )); - assert_eq!(>::get(), (15, 11)); - assert_eq!(>::get(alice.clone()), (1, 50, 50)); - - Timestamp::set_timestamp(2); - - let rate = TickerRate { - btc: 55, - eth: 55, - authority: 0, - }; - assert_ok!(PlasmLockdrop::set_dollar_rate( - Origin::none(), - rate, - Default::default() - )); - assert_eq!(>::get(), (55, 55)); - assert_eq!(>::get(alice), (2, 55, 55)); - // Followed items should be ereased as expired - assert_eq!(>::get(bob), (0, 0, 0)); - assert_eq!(>::get(charlie), (0, 0, 0)); - }) -} - -/* -#[test] -fn check_btc_issue_amount() { - new_test_ext().execute_with(|| { - assert_eq!(>::get(), (9_000, 200)); - assert_eq!(::get(), Perbill::from_parts(446_981_087)); - - let day = 24 * 60 * 60; - for i in 1..2000 { - if i < 3 { - assert_eq!(PlasmLockdrop::btc_issue_amount(1, i * day), 0); - assert_eq!(PlasmLockdrop::btc_issue_amount(i as u128, i * day), 0); - } else if i < 10 { - assert_eq!(PlasmLockdrop::btc_issue_amount(1, i * day), 96552); - assert_eq!( - PlasmLockdrop::btc_issue_amount(i as u128, i * day), - 96552 * i as u128 - ); - } else if i < 30 { - assert_eq!(PlasmLockdrop::btc_issue_amount(1, i * day), 402300); - assert_eq!( - PlasmLockdrop::btc_issue_amount(i as u128, i * day), - 402300 * i as u128 - ); - } else if i < 100 { - assert_eq!(PlasmLockdrop::btc_issue_amount(1, i * day), 1448280); - assert_eq!( - PlasmLockdrop::btc_issue_amount(i as u128, i * day), - 1448280 * i as u128 - ); - } else { - assert_eq!(PlasmLockdrop::btc_issue_amount(1, i * day), 6436800); - assert_eq!( - PlasmLockdrop::btc_issue_amount(i as u128, i * day), - 6436800 * i as u128 - ); - } - } - }) -} -*/ - -#[test] -fn check_eth_issue_amount() { - new_test_ext().execute_with(|| { - assert_eq!(>::get(), (9_000, 200)); - assert_eq!(::get(), Perbill::from_parts(446_981_087)); - - let day = 24 * 60 * 60; - for i in 1..2000 { - if i < 3 { - assert_eq!(PlasmLockdrop::eth_issue_amount(1, i * day), 0); - assert_eq!(PlasmLockdrop::eth_issue_amount(i as u128, i * day), 0); - } else if i < 10 { - assert_eq!(PlasmLockdrop::eth_issue_amount(1, i * day), 2136); - assert_eq!( - PlasmLockdrop::eth_issue_amount(i as u128, i * day), - 2136 * i as u128 - ); - } else if i < 30 { - assert_eq!(PlasmLockdrop::eth_issue_amount(1, i * day), 8900); - assert_eq!( - PlasmLockdrop::eth_issue_amount(i as u128, i * day), - 8900 * i as u128 - ); - } else if i < 100 { - assert_eq!(PlasmLockdrop::eth_issue_amount(1, i * day), 32040); - assert_eq!( - PlasmLockdrop::eth_issue_amount(i as u128, i * day), - 32040 * i as u128 - ); - } else { - assert_eq!(PlasmLockdrop::eth_issue_amount(1, i * day), 142400); - assert_eq!( - PlasmLockdrop::eth_issue_amount(i as u128, i * day), - 142400 * i as u128 - ); - } - } - }) -} - -#[test] -fn dollar_rate_ticker_works() { - let mut ext = new_test_ext(); - let (offchain, state) = TestOffchainExt::new(); - ext.register_extension(OffchainExt::new(offchain)); - - ext.execute_with(|| { - state - .write() - .expect_request(sp_core::offchain::testing::PendingRequest { - method: "GET".into(), - uri: "http://127.0.0.1:34347/btc/ticker".into(), - sent: true, - response: Some("6766".into()), - ..Default::default() - }); - assert_eq!(BitcoinPrice::fetch(), Ok(6766)); - state - .write() - .expect_request(sp_core::offchain::testing::PendingRequest { - method: "GET".into(), - uri: "http://127.0.0.1:34347/eth/ticker".into(), - sent: true, - response: Some("139".into()), - ..Default::default() - }); - assert_eq!(EthereumPrice::fetch(), Ok(139)); - }) -} - -#[test] -fn dollar_rate_offchain_worker() { - let mut ext = new_test_ext(); - let (offchain, state) = TestOffchainExt::new(); - let (pool, pool_state) = TestTransactionPoolExt::new(); - ext.register_extension(KeystoreExt(KeyStore::new())); - ext.register_extension(OffchainExt::new(offchain)); - ext.register_extension(TransactionPoolExt::new(pool)); - - let account: AccountId = sp_keyring::sr25519::Keyring::Alice.into(); - ext.execute_with(|| { - let seed = format!("//{}", account).as_bytes().to_vec(); - ::AuthorityId::generate_pair(Some(seed)); - - state - .write() - .expect_request(sp_core::offchain::testing::PendingRequest { - method: "GET".into(), - uri: "http://127.0.0.1:34347/btc/ticker".into(), - sent: true, - response: Some("6766".into()), - ..Default::default() - }); - state - .write() - .expect_request(sp_core::offchain::testing::PendingRequest { - method: "GET".into(), - uri: "http://127.0.0.1:34347/eth/ticker".into(), - sent: true, - response: Some("139".into()), - ..Default::default() - }); - - let key = ::AuthorityId::all()[0].clone(); - assert_ok!(PlasmLockdrop::send_dollar_rate(key)); - - let transaction = pool_state.write().transactions.pop().unwrap(); - let ex: Extrinsic = Decode::decode(&mut &*transaction).unwrap(); - // Simple parameter checks - match ex.call { - crate::mock::Call::PlasmLockdrop(call) => { - if let crate::Call::set_dollar_rate(rate, signature) = call.clone() { - assert_eq!( - rate, - TickerRate { - authority: 0, - btc: 6766, - eth: 139 - } - ); - assert!(Keys::::get()[rate.authority as usize] - .verify(&rate.encode(), &signature)); - } - - let dispatch = - PlasmLockdrop::pre_dispatch(&call).map_err(|e| <&'static str>::from(e)); - assert_ok!(dispatch); - } - e => panic!("Unexpected call: {:?}", e), - } - }) -} - -#[test] -fn simple_success_lockdrop_request() { - new_test_ext().execute_with(|| { - let lockdrop: Lockdrop = Default::default(); - let claim_id = BlakeTwo256::hash_of(&lockdrop); - assert_ok!(PlasmLockdrop::request( - Origin::none(), - lockdrop, - Default::default(), - )); - let vote = ClaimVote { - claim_id, - approve: true, - authority: 0, - }; - let vote2 = ClaimVote { - claim_id, - approve: true, - authority: 1, - }; - let vote3 = ClaimVote { - claim_id, - approve: true, - authority: 2, - }; - assert_ok!(PlasmLockdrop::vote( - Origin::none(), - vote, - Default::default(), - )); - assert_noop!( - PlasmLockdrop::claim(Origin::none(), claim_id), - DispatchError::Module { - index: 0, - error: 2, - message: Some("NotEnoughVotes") - }, - ); - assert_ok!(PlasmLockdrop::vote( - Origin::none(), - vote2, - Default::default(), - )); - assert_noop!( - PlasmLockdrop::claim(Origin::none(), claim_id), - DispatchError::Module { - index: 0, - error: 2, - message: Some("NotEnoughVotes") - }, - ); - assert_ok!(PlasmLockdrop::vote( - Origin::none(), - vote3, - Default::default() - )); - assert_ok!(PlasmLockdrop::claim(Origin::none(), claim_id)); - }) -} - -#[test] -fn simple_fail_lockdrop_request() { - new_test_ext().execute_with(|| { - let lockdrop: Lockdrop = Default::default(); - let claim_id = BlakeTwo256::hash_of(&lockdrop); - assert_ok!(PlasmLockdrop::request( - Origin::none(), - lockdrop, - Default::default(), - )); - let vote = ClaimVote { - claim_id, - approve: false, - authority: 0, - }; - let vote2 = ClaimVote { - claim_id, - approve: false, - authority: 1, - }; - let vote3 = ClaimVote { - claim_id, - approve: false, - authority: 2, - }; - assert_ok!(PlasmLockdrop::vote( - Origin::none(), - vote, - Default::default(), - )); - assert_noop!( - PlasmLockdrop::claim(Origin::none(), claim_id), - DispatchError::Module { - index: 0, - error: 2, - message: Some("NotEnoughVotes") - }, - ); - assert_ok!(PlasmLockdrop::vote( - Origin::none(), - vote2, - Default::default(), - )); - assert_noop!( - PlasmLockdrop::claim(Origin::none(), claim_id), - DispatchError::Module { - index: 0, - error: 2, - message: Some("NotEnoughVotes") - }, - ); - assert_ok!(PlasmLockdrop::vote( - Origin::none(), - vote3, - Default::default() - )); - assert_noop!( - PlasmLockdrop::claim(Origin::none(), claim_id), - DispatchError::Module { - index: 0, - error: 3, - message: Some("NotApproved") - }, - ); - }) -} - -#[test] -fn lockdrop_request_hash() { - let transaction_hash = - hex!["6c4364b2f5a847ffc69f787a0894191b75aa278a95020f02e4753c76119324e0"].into(); - let public_key = ecdsa::Public::from_raw(hex![ - "039360c9cbbede9ee771a55581d4a53cbcc4640953169549993a3b0e6ec7984061" - ]); - let params = Lockdrop::Ethereum { - transaction_hash, - public_key, - duration: 2592000, - value: 100000000000000000, - }; - let claim_id = hex!["a94710e9db798a7d1e977b9f748ae802031eee2400a77600c526158892cd93d8"].into(); - assert_eq!(BlakeTwo256::hash_of(¶ms), claim_id); - - let transaction_hash = - hex!["896d1cbe07c0207b714d87bcde04a535fec049a62c4e279dc2a6b71108afa523"].into(); - let public_key = ecdsa::Public::from_raw(hex![ - "039360c9cbbede9ee771a55581d4a53cbcc4640953169549993a3b0e6ec7984061" - ]); - let params = Lockdrop::Ethereum { - transaction_hash, - public_key, - duration: 2592000, - value: 100000000000000000, - }; - let claim_id = hex!["0c4fb4f0dd7bdff67e5f8f7df5822d8cd8738f7e60a0a8d6151ef9abf51f8f4d"].into(); - assert_eq!(BlakeTwo256::hash_of(¶ms), claim_id); -} - -#[test] -fn lockdrop_request_pow() { - let nonce = hex!["30df083c7f59ea11a39bb341d37bd26d126d8522d408ebc2133bf7c7dc9d0c38"]; - let claim_id = hex!["a94710e9db798a7d1e977b9f748ae802031eee2400a77600c526158892cd93d8"]; - let pow_byte = BlakeTwo256::hash_of(&(claim_id, nonce)).as_bytes()[0]; - assert_eq!(pow_byte, 0); - - let nonce = hex!["6e64a5e25d145dd43b20c3ba4af5f4673ba88389f17afe2307ee4cb1a513978e"]; - let claim_id = hex!["0c4fb4f0dd7bdff67e5f8f7df5822d8cd8738f7e60a0a8d6151ef9abf51f8f4d"]; - let pow_byte = BlakeTwo256::hash_of(&(claim_id, nonce)).as_bytes()[0]; - assert_eq!(pow_byte, 0); -} - -#[test] -fn eth_recover_works() { - use sp_core::ecdsa; - let msg = "test eth signed message"; - let pair = ecdsa::Pair::from_seed(&hex![ - "7e9c7ad85df5cdc88659f53e06fb2eb9bab3ebc59083a3190eaf2c730332529c" - ]); - let signature = hex!["dd0992d40e5cdf99db76bed162808508ac65acd7ae2fdc8573594f03ed9c939773e813181788fc02c3c68f3fdc592759b35f6354484343e18cb5317d34dab6c61b"]; - assert_eq!(eth_recover(&signature, msg.as_ref()), Some(pair.public())); - - let claim_id = H256::from(hex![ - "952e4e0f1f15f5b3828632320c0bcb4941c164974e08bea2e3996ae74c64cf58" - ]); - let account_id = AccountId::from(hex![ - "16eb796bee0c857db3d646ee7070252707aec0c7d82b2eda856632f6a2306a58" - ]); - let msg2 = PlasmLockdrop::claim_message(&claim_id, &account_id); - let signature2 = hex!["80137f73ee7c3dc73f1219916dc58deb7ea2b9b00f39dbb01773038ec352efab5c4caf412b40a176a591db858cfa8717fe9f8b81cfd6d40905877c3e301320791b"]; - assert_eq!(eth_recover(&signature2, msg2.as_ref()), Some(pair.public())); -} diff --git a/frame/plasm-rewards/Cargo.toml b/frame/plasm-rewards/Cargo.toml index f8cffa04f0..3b5ab5adc6 100644 --- a/frame/plasm-rewards/Cargo.toml +++ b/frame/plasm-rewards/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-plasm-rewards" -version = "1.7.0" +version = "1.8.0" authors = ["Stake Technologies "] edition = "2018" license = "Apache-2.0" @@ -10,24 +10,24 @@ description = "FRAME pallet to manage rewards for plasm network" [dependencies] serde = { version = "1.0.106", optional = true } -codec = { package = "parity-scale-codec", version = "1.3.5", features = ["derive"], default-features = false } +codec = { package = "parity-scale-codec", version = "2.0", features = ["derive"], default-features = false } num-traits = { version = "0.2", default-features = false } -sp-runtime = { version = "2.0.0", default_features = false } -sp-arithmetic = { version = "2.0.0", default_features = false } -sp-io = { version = "2.0.0", default_features = false } -sp-std = { version = "2.0.0", default_features = false } -frame-support = { version = "2.0.0", default_features = false } -pallet-session = { version = "2.0.0", default-features = false } -frame-system = { version = "2.0.0", default_features = false } -pallet-staking = { version = "2.0.0", default_features = false } -sp-staking = { version = "2.0.0", default_features = false } +sp-runtime = { version = "3.0.0", default_features = false } +sp-arithmetic = { version = "3.0.0", default_features = false } +sp-io = { version = "3.0.0", default_features = false } +sp-std = { version = "3.0.0", default_features = false } +frame-support = { version = "3.0.0", default_features = false } +pallet-session = { version = "3.0.0", default-features = false } +frame-system = { version = "3.0.0", default_features = false } +pallet-staking = { version = "3.0.0", default_features = false } +sp-staking = { version = "3.0.0", default_features = false } [dev-dependencies] hex-literal = "0.2.1" -sp-core = "2.0.0" -pallet-balances = "2.0.0" -pallet-timestamp = "2.0.0" -pallet-randomness-collective-flip = "2.0.0" +sp-core = "3.0.0" +pallet-balances = "3.0.0" +pallet-timestamp = "3.0.0" +pallet-randomness-collective-flip = "3.0.0" [features] default = ["std"] diff --git a/frame/plasm-rewards/src/lib.rs b/frame/plasm-rewards/src/lib.rs index 8842002b76..da0a9576a9 100644 --- a/frame/plasm-rewards/src/lib.rs +++ b/frame/plasm-rewards/src/lib.rs @@ -2,7 +2,7 @@ //! //! The Plasm rewards module provides functionality for handling whole rewards and era. //! -//! - [`plasm_rewards::Trait`](./trait.Trait.html) +//! - [`plasm_rewards::Config`](./trait.Config.html) //! - [`Call`](./enum.Call.html) //! - [`Module`](./struct.Module.html) //! @@ -41,8 +41,8 @@ pub use sp_staking::SessionIndex; pub type EraIndex = u32; pub type BalanceOf = - <::Currency as Currency<::AccountId>>::Balance; -pub type MomentOf = <::Time as Time>::Moment; + <::Currency as Currency<::AccountId>>::Balance; +pub type MomentOf = <::Time as Time>::Moment; // A value placed in storage that represents the current version of the Staking storage. // This value is used by the `on_runtime_upgrade` logic to determine whether we run @@ -70,7 +70,7 @@ pub struct ActiveEraInfo { pub start: Option, } -pub trait Trait: pallet_session::Trait { +pub trait Config: pallet_session::Config { /// The staking balance. type Currency: LockableCurrency; @@ -99,11 +99,11 @@ pub trait Trait: pallet_session::Trait { type MaybeValidators: traits::MaybeValidators; /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; } decl_storage! { - trait Store for Module as DappsStaking { + trait Store for Module as DappsStaking { /// This is the compensation paid for the dapps operator of the Plasm Network. /// This is stored on a per-era basis. pub ForDappsEraReward get(fn for_dapps_era_reward): map hasher(twox_64_concat) EraIndex => Option>; @@ -169,7 +169,7 @@ decl_event!( decl_error! { /// Error for the staking module. - pub enum Error for Module { + pub enum Error for Module { /// Duplicate index. DuplicateIndex, /// Invalid era to reward. @@ -178,7 +178,7 @@ decl_error! { } decl_module! { - pub struct Module for enum Call where origin: T::Origin { + pub struct Module for enum Call where origin: T::Origin { /// Number of sessions per era. const SessionsPerEra: SessionIndex = T::SessionsPerEra::get(); @@ -257,7 +257,7 @@ decl_module! { } } -fn migrate() { +fn migrate() { // TODO: When runtime upgrade, migrate stroage. // if let Some(current_era) = CurrentEra::get() { // let history_depth = HistoryDepth::get(); @@ -267,7 +267,7 @@ fn migrate() { // } } -impl Module { +impl Module { // MUTABLES (DANGEROUS) /// Plan a new session potentially trigger a new era. @@ -423,7 +423,7 @@ impl Module { /// /// Once the first new_session is planned, all session must start and then end in order, though /// some session can lag in between the newest session planned and the latest session started. -impl SessionManager for Module { +impl SessionManager for Module { fn new_session(new_index: SessionIndex) -> Option> { Self::new_session(new_index) } @@ -436,7 +436,7 @@ impl SessionManager for Module { } /// In this implementation using validator and dapps rewards module. -impl EraFinder> for Module { +impl EraFinder> for Module { fn current() -> Option { Self::current_era() } @@ -449,21 +449,21 @@ impl EraFinder> for Module { } /// Get the security rewards for validator module. -impl ForSecurityEraRewardFinder> for Module { +impl ForSecurityEraRewardFinder> for Module { fn get(era: &EraIndex) -> Option> { Self::for_security_era_reward(&era) } } /// Get the dapps rewards for dapps staking module. -impl ForDappsEraRewardFinder> for Module { +impl ForDappsEraRewardFinder> for Module { fn get(era: &EraIndex) -> Option> { Self::for_dapps_era_reward(&era) } } /// Get the history depth -impl HistoryDepthFinder for Module { +impl HistoryDepthFinder for Module { fn get() -> u32 { Self::history_depth() } diff --git a/frame/plasm-rewards/src/mock.rs b/frame/plasm-rewards/src/mock.rs index 565792db3e..a1f417d373 100644 --- a/frame/plasm-rewards/src/mock.rs +++ b/frame/plasm-rewards/src/mock.rs @@ -1,51 +1,43 @@ -//! Test utilities +//! Runtime utilities #![cfg(test)] use super::*; -use frame_support::{impl_outer_dispatch, impl_outer_origin, parameter_types, traits::OnFinalize}; +use crate as plasm_rewards; +use frame_support::{parameter_types, traits::OnFinalize}; use sp_core::{crypto::key_types, H256}; -use sp_runtime::testing::{Header, UintAuthorityId}; -use sp_runtime::traits::{BlakeTwo256, ConvertInto, IdentityLookup, OpaqueKeys}; -use sp_runtime::{KeyTypeId, Perbill}; +use sp_runtime::{ + testing::{Header, UintAuthorityId}, + traits::{BlakeTwo256, ConvertInto, IdentityLookup, OpaqueKeys}, + BuildStorage, KeyTypeId, +}; use traits::{ComputeEraWithParam, MaybeValidators}; pub type BlockNumber = u64; pub type AccountId = u64; pub type Balance = u64; -pub const ALICE_STASH: u64 = 1; - -impl_outer_origin! { - pub enum Origin for Test {} -} - -impl_outer_dispatch! { - pub enum Call for Test where origin: Origin { - pallet_session::Session, - pallet_balances::Balances, - plasm_rewards::PlasmRewards, - } -} +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; pub fn new_test_ext() -> sp_io::TestExternalities { let mut storage = frame_system::GenesisConfig::default() - .build_storage::() + .build_storage::() .unwrap(); - let _ = pallet_balances::GenesisConfig:: { - balances: vec![(ALICE_STASH, 1_000_000_000_000_000_000)], - } - .assimilate_storage(&mut storage); - let validators = vec![1, 2]; + let balances = validators + .iter() + .map(|x| (*x, 1_000_000_000_000_000_000)) + .collect(); + let _ = pallet_balances::GenesisConfig:: { balances }.assimilate_storage(&mut storage); let _ = GenesisConfig { ..Default::default() } .assimilate_storage(&mut storage); - let _ = pallet_session::GenesisConfig:: { + let _ = pallet_session::GenesisConfig:: { keys: validators .iter() .map(|x| (*x, *x, UintAuthorityId(*x))) @@ -56,17 +48,25 @@ pub fn new_test_ext() -> sp_io::TestExternalities { storage.into() } -#[derive(Clone, PartialEq, Eq, Debug)] -pub struct Test; +frame_support::construct_runtime!( + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Module, Call, Config, Storage, Event}, + Timestamp: pallet_timestamp::{Module, Storage}, + Session: pallet_session::{Module, Call, Storage, Event}, + Balances: pallet_balances::{Module, Call, Storage, Config, Event}, + PlasmRewards: plasm_rewards::{Module, Call, Storage, Config, Event}, + } +); parameter_types! { pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: u32 = 1024; - pub const MaximumBlockLength: u32 = 2 * 1024; - pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl frame_system::Trait for Test { +impl frame_system::Config for Runtime { type Origin = Origin; type BaseCallFilter = (); type Index = u64; @@ -77,27 +77,24 @@ impl frame_system::Trait for Test { type AccountId = AccountId; type Lookup = IdentityLookup; type Header = Header; - type Event = (); + type Event = Event; type BlockHashCount = BlockHashCount; - type MaximumBlockWeight = MaximumBlockWeight; - type MaximumBlockLength = MaximumBlockLength; - type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletInfo = (); - type AccountData = pallet_balances::AccountData; + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = (); type SystemWeightInfo = (); + type BlockWeights = (); + type BlockLength = (); + type SS58Prefix = (); } parameter_types! { pub const MinimumPeriod: u64 = 1; } -impl pallet_timestamp::Trait for Test { +impl pallet_timestamp::Config for Runtime { type Moment = u64; type OnTimestampSet = (); type MinimumPeriod = MinimumPeriod; @@ -109,9 +106,9 @@ parameter_types! { pub const Offset: u64 = 0; } -pub struct TestSessionHandler; +pub struct RuntimeSessionHandler; -impl pallet_session::SessionHandler for TestSessionHandler { +impl pallet_session::SessionHandler for RuntimeSessionHandler { const KEY_TYPE_IDS: &'static [KeyTypeId] = &[key_types::DUMMY]; fn on_genesis_session(_validators: &[(u64, T)]) {} fn on_new_session( @@ -124,15 +121,15 @@ impl pallet_session::SessionHandler for TestSessionHandler { fn on_before_session_ending() {} } -impl pallet_session::Trait for Test { +impl pallet_session::Config for Runtime { type ShouldEndSession = pallet_session::PeriodicSessions; type NextSessionRotation = pallet_session::PeriodicSessions; type SessionManager = PlasmRewards; - type SessionHandler = TestSessionHandler; + type SessionHandler = RuntimeSessionHandler; type ValidatorId = u64; type ValidatorIdOf = ConvertInto; type Keys = UintAuthorityId; - type Event = (); + type Event = Event; type DisabledValidatorsThreshold = (); type WeightInfo = (); } @@ -141,12 +138,12 @@ parameter_types! { pub const ExistentialDeposit: Balance = 10; } -impl pallet_balances::Trait for Test { +impl pallet_balances::Config for Runtime { type Balance = Balance; - type Event = (); + type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Module; + type AccountStore = frame_system::Module; type WeightInfo = (); type MaxLocks = (); } @@ -179,7 +176,7 @@ parameter_types! { pub const BondingDuration: EraIndex = 3; } -impl Trait for Test { +impl Config for Runtime { type Currency = Balances; type Time = Timestamp; type SessionsPerEra = SessionsPerEra; @@ -188,16 +185,9 @@ impl Trait for Test { type ComputeEraForSecurity = DummyForSecurityStaking; type ComputeTotalPayout = inflation::MaintainRatioComputeTotalPayout; type MaybeValidators = DummyMaybeValidators; - type Event = (); + type Event = Event; } -/// ValidatorManager module. -pub type System = frame_system::Module; -pub type Session = pallet_session::Module; -pub type Balances = pallet_balances::Module; -pub type Timestamp = pallet_timestamp::Module; -pub type PlasmRewards = Module; - pub const PER_SESSION: u64 = 60 * 1000; pub fn advance_session() { diff --git a/frame/plasm-rewards/src/tests.rs b/frame/plasm-rewards/src/tests.rs index e2984547a7..2e5631b417 100644 --- a/frame/plasm-rewards/src/tests.rs +++ b/frame/plasm-rewards/src/tests.rs @@ -118,9 +118,12 @@ fn normal_incremental_era() { assert_eq!(PlasmRewards::eras_start_session_index(2).unwrap(), 20); assert_eq!( PlasmRewards::for_security_era_reward(1).unwrap(), - 3168333332066 + 6336666664132, + ); + assert_eq!( + PlasmRewards::for_dapps_era_reward(1).unwrap(), + 1267333335868 ); - assert_eq!(PlasmRewards::for_dapps_era_reward(1).unwrap(), 633666667934); assert_eq!(Session::current_index(), i); assert_eq!(Session::validators(), vec![1, 2, 3, 102]); } @@ -185,9 +188,12 @@ fn force_new_era_incremental_era() { assert_eq!(PlasmRewards::eras_start_session_index(2).unwrap(), 12); assert_eq!( PlasmRewards::for_security_era_reward(1).unwrap(), - 3168333332066, + 6336666664132, + ); + assert_eq!( + PlasmRewards::for_dapps_era_reward(1).unwrap(), + 1267333335868 ); - assert_eq!(PlasmRewards::for_dapps_era_reward(1).unwrap(), 633666667934); assert_eq!(Session::validators(), vec![1, 2, 3, 102]); assert_eq!(Session::current_index(), 12); }) @@ -227,9 +233,9 @@ fn force_new_era_always_incremental_era() { _ => { assert_eq!( PlasmRewards::for_security_era_reward(1).unwrap(), - 315833333207, + 631666666414, ); - assert_eq!(PlasmRewards::for_dapps_era_reward(1).unwrap(), 63166666793); + assert_eq!(PlasmRewards::for_dapps_era_reward(1).unwrap(), 126333333586); } } assert_eq!(Session::validators(), vec![1, 2, 3, 100 + (i as u64 - 1)]); diff --git a/frame/plasm-rewards/src/traits.rs b/frame/plasm-rewards/src/traits.rs index 8fdefb3c11..667c9888c4 100644 --- a/frame/plasm-rewards/src/traits.rs +++ b/frame/plasm-rewards/src/traits.rs @@ -8,13 +8,13 @@ pub trait ComputeEraWithParam { fn compute(era: &EraIndex) -> Self::Param; } -pub struct DefaultForDappsStaking { +pub struct DefaultForDappsStaking { _phantom: PhantomData, } -impl ComputeEraWithParam for DefaultForDappsStaking { +impl ComputeEraWithParam for DefaultForDappsStaking { type Param = BalanceOf; fn compute(_era: &EraIndex) -> BalanceOf { - 0.into() + Default::default() } } diff --git a/frame/plasm-support/Cargo.toml b/frame/plasm-support/Cargo.toml index 0c92401e6e..dc0f2c350b 100644 --- a/frame/plasm-support/Cargo.toml +++ b/frame/plasm-support/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-plasm-support" -version = "1.7.0" +version = "1.8.0" authors = ["Stake Technologies "] edition = "2018" license = "Apache-2.0" @@ -9,9 +9,9 @@ repository = "https://github.com/staketechnologies/Plasm/" description = "FRAME support pallet for Plasm traits" [dependencies] -sp-runtime = { version = "2.0.0", default_features = false } -frame-support = { version = "2.0.0", default_features = false } -sp-std = { version = "2.0.0", default_features = false } +sp-runtime = { version = "3.0.0", default_features = false } +frame-support = { version = "3.0.0", default_features = false } +sp-std = { version = "3.0.0", default_features = false } [dev-dependencies] diff --git a/frame/plasm-validator/Cargo.toml b/frame/plasm-validator/Cargo.toml index e2e2cb3e7b..bc9340f733 100644 --- a/frame/plasm-validator/Cargo.toml +++ b/frame/plasm-validator/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-plasm-validator" -version = "1.7.0" +version = "1.8.0" authors = ["Stake Technologies "] edition = "2018" license = "Apache-2.0" @@ -10,25 +10,25 @@ description = "FRAME pallet to manage validators for plasm network" [dependencies] serde = { version = "1.0.106", optional = true } -codec = { package = "parity-scale-codec", version = "1.3.5", features = ["derive"], default-features = false } +codec = { package = "parity-scale-codec", version = "2.0", features = ["derive"], default-features = false } -sp-core = { version = "2.0.0", default_features = false } -sp-runtime = { version = "2.0.0", default_features = false } -sp-arithmetic = { version = "2.0.0", default_features = false } -sp-io = { version = "2.0.0", default_features = false } -sp-std = { version = "2.0.0", default_features = false } -pallet-balances = { version = "2.0.0", default_features = false } -frame-support = { version = "2.0.0", default_features = false } -frame-system = { version = "2.0.0", default_features = false } -sp-staking = { version = "2.0.0", default_features = false } +sp-core = { version = "3.0.0", default_features = false } +sp-runtime = { version = "3.0.0", default_features = false } +sp-arithmetic = { version = "3.0.0", default_features = false } +sp-io = { version = "3.0.0", default_features = false } +sp-std = { version = "3.0.0", default_features = false } +pallet-balances = { version = "3.0.0", default_features = false } +frame-support = { version = "3.0.0", default_features = false } +frame-system = { version = "3.0.0", default_features = false } +sp-staking = { version = "3.0.0", default_features = false } pallet-plasm-rewards = { path = "../plasm-rewards", version = "1.7.0", default_features = false } [dev-dependencies] hex-literal = "0.2.1" -pallet-timestamp = "2.0.0" -pallet-session = "2.0.0" -pallet-randomness-collective-flip = "2.0.0" +pallet-timestamp = "3.0.0" +pallet-session = "3.0.0" +pallet-randomness-collective-flip = "3.0.0" [features] default = ["std"] diff --git a/frame/plasm-validator/src/compute_era.rs b/frame/plasm-validator/src/compute_era.rs index 5d2cae251b..ad4e08966a 100644 --- a/frame/plasm-validator/src/compute_era.rs +++ b/frame/plasm-validator/src/compute_era.rs @@ -7,7 +7,7 @@ pub trait ComputeEraOnModule { } /// This is first validator rewards algorithm. -impl ComputeEraOnModule for Module { +impl ComputeEraOnModule for Module { fn compute(era: &EraIndex) -> u32 { match >::get(era) { Some(validators) => validators.len() as u32, diff --git a/frame/plasm-validator/src/lib.rs b/frame/plasm-validator/src/lib.rs index 00f5441d1c..5f55930079 100644 --- a/frame/plasm-validator/src/lib.rs +++ b/frame/plasm-validator/src/lib.rs @@ -29,15 +29,15 @@ mod compute_era; pub use compute_era::*; pub type BalanceOf = - <::Currency as Currency<::AccountId>>::Balance; -pub type MomentOf = <::Time as Time>::Moment; + <::Currency as Currency<::AccountId>>::Balance; +pub type MomentOf = <::Time as Time>::Moment; type PositiveImbalanceOf = - <::Currency as Currency<::AccountId>>::PositiveImbalance; + <::Currency as Currency<::AccountId>>::PositiveImbalance; type NegativeImbalanceOf = - <::Currency as Currency<::AccountId>>::NegativeImbalance; + <::Currency as Currency<::AccountId>>::NegativeImbalance; -pub trait Trait: system::Trait { +pub trait Config: system::Config { /// The staking balance. type Currency: LockableCurrency; @@ -63,11 +63,11 @@ pub trait Trait: system::Trait { type ComputeEra: ComputeEraOnModule; /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; } decl_storage! { - trait Store for Module as DappsStaking { + trait Store for Module as DappsStaking { /// The already untreated era is EraIndex. pub UntreatedEra get(fn untreated_era): EraIndex; @@ -81,7 +81,7 @@ decl_storage! { } decl_module! { - pub struct Module for enum Call where origin: T::Origin { + pub struct Module for enum Call where origin: T::Origin { fn deposit_event() = default; fn on_finalize() { @@ -126,7 +126,7 @@ decl_module! { decl_event!( pub enum Event where - AccountId = ::AccountId, + AccountId = ::AccountId, Balance = BalanceOf, { /// Validator set changed. @@ -138,7 +138,7 @@ decl_event!( } ); -impl Module { +impl Module { pub fn reward_to_validators(era: &EraIndex, max_payout: &BalanceOf) -> BalanceOf { if let Some(validators) = Self::elected_validators(era) { let validator_len: u64 = validators.len() as u64; @@ -167,7 +167,7 @@ impl Module { } /// Returns the next validator candidate for calling by plasm-rewards when new era. -impl MaybeValidators for Module { +impl MaybeValidators for Module { fn compute(current_era: EraIndex) -> Option> { // Apply new validator set >::insert(¤t_era, >::get()); @@ -177,7 +177,7 @@ impl MaybeValidators for Module { /// Get the amount of staking per Era in a module in the Plasm Network /// for callinng by plasm-rewards when end era. -impl ComputeEraWithParam for Module { +impl ComputeEraWithParam for Module { type Param = T::ComputeEraParam; fn compute(era: &EraIndex) -> T::ComputeEraParam { T::ComputeEra::compute(era) diff --git a/frame/plasm-validator/src/mock.rs b/frame/plasm-validator/src/mock.rs index 7dfd1c08d8..e473a520a2 100644 --- a/frame/plasm-validator/src/mock.rs +++ b/frame/plasm-validator/src/mock.rs @@ -1,14 +1,17 @@ -//! Test utilities +//! Runtime utilities #![cfg(test)] use super::*; -use frame_support::{impl_outer_dispatch, impl_outer_origin, parameter_types, traits::OnFinalize}; +use crate as plasm_validator; +use frame_support::{parameter_types, traits::OnFinalize}; use pallet_plasm_rewards::inflation::SimpleComputeTotalPayout; use sp_core::{crypto::key_types, H256}; -use sp_runtime::testing::{Header, UintAuthorityId}; -use sp_runtime::traits::{BlakeTwo256, ConvertInto, IdentityLookup, OpaqueKeys}; -use sp_runtime::{KeyTypeId, Perbill}; +use sp_runtime::{ + testing::{Header, UintAuthorityId}, + traits::{BlakeTwo256, ConvertInto, IdentityLookup, OpaqueKeys}, + KeyTypeId, +}; pub type BlockNumber = u64; pub type AccountId = u64; @@ -20,25 +23,15 @@ pub const VALIDATOR_C: u64 = 3; pub const VALIDATOR_D: u64 = 4; pub const VALIDATOR_E: u64 = 5; -impl_outer_origin! { - pub enum Origin for Test {} -} - -impl_outer_dispatch! { - pub enum Call for Test where origin: Origin { - pallet_session::Session, - pallet_balances::Balances, - plasm_rewards::PlasmRewards, - plasm_validator::PlasmValidator, - } -} +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; pub fn new_test_ext() -> sp_io::TestExternalities { let mut storage = frame_system::GenesisConfig::default() - .build_storage::() + .build_storage::() .unwrap(); - let _ = pallet_balances::GenesisConfig:: { + let _ = pallet_balances::GenesisConfig:: { balances: vec![ (VALIDATOR_A, 1_000_000_000_000_000_000), (VALIDATOR_B, 1_000_000_000_000_000_000), @@ -55,12 +48,12 @@ pub fn new_test_ext() -> sp_io::TestExternalities { } .assimilate_storage(&mut storage); - let _ = GenesisConfig:: { + let _ = plasm_validator::GenesisConfig:: { validators: validators.clone(), } .assimilate_storage(&mut storage); - let _ = pallet_session::GenesisConfig:: { + let _ = pallet_session::GenesisConfig:: { keys: validators .iter() .map(|x| (*x, *x, UintAuthorityId(*x))) @@ -71,17 +64,26 @@ pub fn new_test_ext() -> sp_io::TestExternalities { storage.into() } -#[derive(Clone, PartialEq, Eq, Debug)] -pub struct Test; +frame_support::construct_runtime!( + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Module, Call, Config, Storage, Event}, + Timestamp: pallet_timestamp::{Module, Storage}, + Session: pallet_session::{Module, Call, Storage, Event}, + Balances: pallet_balances::{Module, Call, Storage, Config, Event}, + PlasmRewards: pallet_plasm_rewards::{Module, Call, Storage, Config, Event}, + PlasmValidator: plasm_validator::{Module, Call, Storage, Config, Event}, + } +); parameter_types! { pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: u32 = 1024; - pub const MaximumBlockLength: u32 = 2 * 1024; - pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl frame_system::Trait for Test { +impl frame_system::Config for Runtime { type Origin = Origin; type BaseCallFilter = (); type Index = u64; @@ -92,27 +94,24 @@ impl frame_system::Trait for Test { type AccountId = AccountId; type Lookup = IdentityLookup; type Header = Header; - type Event = (); + type Event = Event; type BlockHashCount = BlockHashCount; - type MaximumBlockWeight = MaximumBlockWeight; - type MaximumBlockLength = MaximumBlockLength; - type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletInfo = (); + type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = (); type SystemWeightInfo = (); + type BlockWeights = (); + type BlockLength = (); + type SS58Prefix = (); } parameter_types! { pub const MinimumPeriod: u64 = 1; } -impl pallet_timestamp::Trait for Test { +impl pallet_timestamp::Config for Runtime { type Moment = u64; type OnTimestampSet = (); type MinimumPeriod = MinimumPeriod; @@ -138,7 +137,7 @@ impl pallet_session::SessionHandler for TestSessionHandler { fn on_before_session_ending() {} } -impl pallet_session::Trait for Test { +impl pallet_session::Config for Runtime { type ShouldEndSession = pallet_session::PeriodicSessions; type NextSessionRotation = pallet_session::PeriodicSessions; type SessionManager = PlasmRewards; @@ -146,7 +145,7 @@ impl pallet_session::Trait for Test { type ValidatorId = u64; type ValidatorIdOf = ConvertInto; type Keys = UintAuthorityId; - type Event = (); + type Event = Event; type DisabledValidatorsThreshold = (); type WeightInfo = (); } @@ -155,12 +154,12 @@ parameter_types! { pub const ExistentialDeposit: Balance = 1_000_000_000_000; } -impl pallet_balances::Trait for Test { +impl pallet_balances::Config for Runtime { type Balance = Balance; - type Event = (); + type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Module; + type AccountStore = frame_system::Module; type WeightInfo = (); type MaxLocks = (); } @@ -170,7 +169,7 @@ parameter_types! { pub const BondingDuration: EraIndex = 3; } -impl pallet_plasm_rewards::Trait for Test { +impl pallet_plasm_rewards::Config for Runtime { type Currency = Balances; type Time = Timestamp; type SessionsPerEra = SessionsPerEra; @@ -179,10 +178,10 @@ impl pallet_plasm_rewards::Trait for Test { type ComputeEraForSecurity = PlasmValidator; type ComputeTotalPayout = SimpleComputeTotalPayout; type MaybeValidators = PlasmValidator; - type Event = (); + type Event = Event; } -impl Trait for Test { +impl Config for Runtime { type Currency = Balances; type Time = Timestamp; type RewardRemainder = (); // Reward remainder is burned. @@ -191,16 +190,9 @@ impl Trait for Test { type ForSecurityEraReward = PlasmRewards; type ComputeEraParam = u32; type ComputeEra = PlasmValidator; - type Event = (); + type Event = Event; } -pub type System = frame_system::Module; -pub type Session = pallet_session::Module; -pub type Balances = pallet_balances::Module; -pub type Timestamp = pallet_timestamp::Module; -pub type PlasmRewards = pallet_plasm_rewards::Module; -pub type PlasmValidator = Module; - pub const PER_SESSION: u64 = 60 * 1000; pub fn advance_session() { diff --git a/frame/plasm-validator/src/tests.rs b/frame/plasm-validator/src/tests.rs index fc1542a8c6..833c6bf656 100644 --- a/frame/plasm-validator/src/tests.rs +++ b/frame/plasm-validator/src/tests.rs @@ -135,7 +135,7 @@ fn reward_to_validator_test() { let pre_total_issuarance = Balances::total_issuance(); - let (a, _) = ::ComputeTotalPayout::compute( + let (a, _) = ::ComputeTotalPayout::compute( pre_total_issuarance, SIX_HOURS, 0, diff --git a/frame/plasma/Cargo.toml b/frame/plasma/Cargo.toml deleted file mode 100644 index a20a52984d..0000000000 --- a/frame/plasma/Cargo.toml +++ /dev/null @@ -1,47 +0,0 @@ -[package] -name = "pallet-plasma" -version = "1.7.0" -authors = ["Stake Technologies "] -edition = "2018" -license = "Apache-2.0" -homepage = "https://docs.plasmnet.io/" -repository = "https://github.com/staketechnologies/Plasm/" -description = "FRAME pallet to plasma solution on ovm" - -[dependencies] -serde = { version = "1.0", optional = true, features = ["derive"] } -codec = { package = "parity-scale-codec", version = "1.3.5", features = ['derive'], default-features = false } -sp-core = { version = "2.0.0", default-features = false } -sp-runtime = { version = "2.0.0", default_features = false } -sp-arithmetic = { version = "2.0.0", default_features = false } -sp-io = { version = "2.0.0", default_features = false } -sp-std = { version = "2.0.0", default_features = false } -frame-support = { version = "2.0.0", default_features = false } -frame-system = { version = "2.0.0", default_features = false } -pallet-contracts = { version = "2.0.0", default_features = false } -pallet-ovm = { path = "../ovm", default_features = false } - -[dev-dependencies] -hex-literal = "0.2.1" -lazy_static = { version = "1.4" } -sp-core = { version = "2.0.0" } -pallet-balances = "2.0.0" -pallet-timestamp = "2.0.0" -pallet-randomness-collective-flip = "2.0.0" -pallet-transaction-payment = "2.0.0" - -[features] -default = ["std"] -std = [ - 'serde', - 'codec/std', - 'sp-core/std', - 'sp-runtime/std', - 'sp-arithmetic/std', - 'sp-io/std', - 'sp-std/std', - 'frame-support/std', - 'frame-system/std', - 'pallet-ovm/std', - 'pallet-contracts/std', -] diff --git a/frame/plasma/rpc/runtime-api/Cargo.toml b/frame/plasma/rpc/runtime-api/Cargo.toml deleted file mode 100644 index bcaea747ab..0000000000 --- a/frame/plasma/rpc/runtime-api/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "pallet-plasma-rpc-runtime-api" -version = "0.1.0" -authors = ["Takumi Yamashita "] -edition = "2018" -license = "GPL-3.0" -homepage = "https://plasmnet.io" -repository = "https://github.com/staketechnologies/Plasm/" -description = "Runtime API definition required by Plasma RPC extensions." - -[dependencies] -sp-api = { version = "2.0.0", default-features = false } -codec = { package = "parity-scale-codec", version = "1.2.0", default-features = false, features = ["derive"] } -sp-std = { version = "2.0.0", default-features = false } - -[features] -default = ["std"] -std = [ - "sp-api/std", - "codec/std", - "sp-std/std", -] diff --git a/frame/plasma/rpc/runtime-api/src/lib.rs b/frame/plasma/rpc/runtime-api/src/lib.rs deleted file mode 100644 index 7ef31723a0..0000000000 --- a/frame/plasma/rpc/runtime-api/src/lib.rs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2019-2020 Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// Substrate is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Substrate is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Substrate. If not, see . - -//! Runtime API definition required by Plasma RPC extensions. -//! -//! This API should be imported and implemented by the runtime, -//! of a node that wants to use the custom RPC extension -//! adding Plasma access methods. - -#![cfg_attr(not(feature = "std"), no_std)] - -use codec::Codec; -use sp_std::vec::Vec; - -sp_api::decl_runtime_apis! { - /// The API to interact with contracts without using executive. - pub trait PlasmaApi where - AccountId: Codec, - BlockNumber: Codec, - Range: Codec, - Hash: Codec, - InclusionProof: Codec, - { - fn retrieve(plapps_id: AccountId, block_number: BlockNumber) -> Hash; - - fn verify_inclusion( - plapps_id: AccountId, - leaf: Hash, - token_address: AccountId, - range: Range, - inclusion_proof: InclusionProof, - block_number: BlockNumber, - ) -> bool; - - fn verify_inclusion_with_root( - leaf: Hash, - token_address: AccountId, - range: Range, - inclusion_proof: InclusionProof, - root: Hash, - ) -> bool; - } -} diff --git a/frame/plasma/src/deserializer.rs b/frame/plasma/src/deserializer.rs deleted file mode 100644 index cf88714b0d..0000000000 --- a/frame/plasma/src/deserializer.rs +++ /dev/null @@ -1,60 +0,0 @@ -use super::*; -use sp_std::marker::PhantomData; - -pub struct Deserializer(PhantomData); - -impl Deserializer { - /// @dev deserialize property to Exit instance - pub fn deserialize_exit(exit: &PropertyOf) -> DispatchResultT> { - let state_update_property: PropertyOf = - Decode::decode(&mut &exit.inputs[0][..]).map_err(|_| Error::::MustBeDecodable)?; - let inclusion_proof: InclusionProofOf = - Decode::decode(&mut &exit.inputs[1][..]).map_err(|_| Error::::MustBeDecodable)?; - Ok(ExitOf:: { - state_update: Self::deserialize_state_update(&state_update_property)?, - inclusion_proof, - }) - } - - /// @dev deserialize property to Exit_deposit instance - pub fn deserialize_exit_deposit(exit: &PropertyOf) -> DispatchResultT> { - let state_update_property: PropertyOf = - Decode::decode(&mut &exit.inputs[0][..]).map_err(|_| Error::::MustBeDecodable)?; - let checkpoint_property: PropertyOf = - Decode::decode(&mut &exit.inputs[1][..]).map_err(|_| Error::::MustBeDecodable)?; - - Ok(ExitDeposit { - state_update: Self::deserialize_state_update(&state_update_property)?, - checkpoint: Self::deserialize_checkpoint(&checkpoint_property)?, - }) - } - - /// @dev deserialize property to State_update instance - pub fn deserialize_state_update( - state_update: &PropertyOf, - ) -> DispatchResultT> { - let deposit_address: T::AccountId = Decode::decode(&mut &state_update.inputs[0][..]) - .map_err(|_| Error::::MustBeDecodable)?; - let range: RangeOf = Decode::decode(&mut &state_update.inputs[1][..]) - .map_err(|_| Error::::MustBeDecodable)?; - - let block_number: T::BlockNumber = Decode::decode(&mut &state_update.inputs[2][..]) - .map_err(|_| Error::::MustBeDecodable)?; - - let state_object: PropertyOf = Decode::decode(&mut &state_update.inputs[3][..]) - .map_err(|_| Error::::MustBeDecodable)?; - - Ok(StateUpdate { - block_number, - deposit_contract_address: deposit_address, - range, - state_object, - }) - } - - pub fn deserialize_checkpoint(checkpoint: &PropertyOf) -> DispatchResultT> { - let state_update: PropertyOf = Decode::decode(&mut &checkpoint.inputs[0][..]) - .map_err(|_| Error::::MustBeDecodable)?; - Ok(Checkpoint { state_update }) - } -} diff --git a/frame/plasma/src/lib.rs b/frame/plasma/src/lib.rs deleted file mode 100644 index 32efb1f8fa..0000000000 --- a/frame/plasma/src/lib.rs +++ /dev/null @@ -1,890 +0,0 @@ -//! # Plasma Module -//! -//! The Plasma module provides functionality for handling layer2 dispute logics. -//! This refer to: https://github.com/cryptoeconomicslab/ovm-contracts/blob/master/contracts/UniversalAdjudicationContract.sol -//! -//! - [`plasma::Trait`](./trait.Trait.html) -//! - [`Call`](./enum.Call.html) -//! - [`Module`](./struct.Module.html) -//! -//! ## Overview -//! Plasma Module is a module that is responsible for processing specific to Plasma. -//! It calls the OVM Module and the specified smart contract function. -//! The Plasma Module has one "Commitment" and "Deposit" address per application. -//! These are each defined by decl_child_storage. decl_child_storage! is a macro that -//! implements DB in SubTrie. This sets AccountId as the key value. -//! This is like a contract address. Specifically, implements with reference to AccountDb of contract module. -//! -//! This is modularized Commitment, Deposit and CompiledPredicate contracts in the Ethereum. -//! -#![cfg_attr(not(feature = "std"), no_std)] - -use codec::{Decode, Encode}; -use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, - dispatch::DispatchResult, - ensure, - traits::{Currency, Get}, - weights::Weight, - StorageDoubleMap, StorageMap, -}; -use frame_system::{self as system, ensure_signed}; -use pallet_contracts::Gas; -use sp_core::crypto::UncheckedFrom; -use sp_runtime::{ - traits::{Bounded, Hash, One, SaturatedConversion, Saturating, Zero}, - DispatchError, RuntimeDebug, -}; -use sp_std::{marker::PhantomData, prelude::*, vec::Vec}; - -pub use pallet_ovm::{Decision, Property, PropertyOf}; - -mod deserializer; -#[cfg(test)] -mod mock; -#[cfg(test)] -mod tests; - -pub use deserializer::Deserializer; -pub type DispatchResultT = Result; - -#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)] -pub struct Range { - start: Balance, - end: Balance, -} - -#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)] -pub struct StateUpdate { - deposit_contract_address: AccountId, - range: Range, - block_number: BlockNumber, - state_object: Property, -} - -#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)] -pub struct Checkpoint { - state_update: Property, -} - -#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)] -pub struct Exit { - state_update: StateUpdate, - inclusion_proof: InclusionProof, -} - -#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)] -pub struct InclusionProof { - address_inclusion_proof: AddressInclusionProof, - interval_inclusion_proof: IntervalInclusionProof, -} - -#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)] -pub struct IntervalInclusionProof { - leaf_index: Balance, - leaf_position: Balance, - siblings: Vec>, -} - -#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)] -pub struct AddressInclusionProof { - leaf_index: AccountId, - leaf_position: Balance, - siblings: Vec>, -} - -#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)] -pub struct IntervalTreeNode { - data: Hash, - start: Balance, -} - -#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)] -pub struct AddressTreeNode { - data: Hash, - token_address: AccountId, -} - -#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, Eq)] -pub struct ExitDeposit { - state_update: StateUpdate, - checkpoint: Checkpoint, -} - -pub type BalanceOf = - <::Currency as Currency<::AccountId>>::Balance; -pub type CheckpointOf = Checkpoint<::AccountId>; -pub type ExitDepositOf = ExitDeposit< - ::AccountId, - BalanceOf, - ::BlockNumber, ->; -pub type RangeOf = Range>; -pub type ExitOf = Exit< - ::AccountId, - ::BlockNumber, - BalanceOf, - ::Hash, ->; -pub type StateUpdateOf = StateUpdate< - ::AccountId, - BalanceOf, - ::BlockNumber, ->; -pub type InclusionProofOf = InclusionProof< - ::AccountId, - BalanceOf, - ::Hash, ->; -pub type IntervalInclusionProofOf = - IntervalInclusionProof, ::Hash>; -pub type IntervalTreeNodeOf = IntervalTreeNode, ::Hash>; -pub type AddressInclusionProofOf = AddressInclusionProof< - ::AccountId, - BalanceOf, - ::Hash, ->; -pub type AddressTreeNodeOf = - AddressTreeNode<::AccountId, ::Hash>; -pub trait PlappsAddressFor { - fn plapps_address_for(hash: &Hash, origin: &AccountId) -> AccountId; -} - -/// Simple plapps address determiner. -/// -/// Address calculated from the code (of the constructor), input data to the constructor, -/// and the account id that requested the account creation. -/// -/// Formula: `blake2_256(plapps_hash + origin)` -/// ```plapps_hash = blake2_256(&( -/// blake2_256(&aggregator_id), -/// blake2_256(&balances), -/// blake2_256(&state_update_predicate), -/// blake2_256(&exit_predicate), -/// blake2_256(&exit_deposit_predicate), -// ));``` -pub struct SimpleAddressDeterminer(PhantomData); -impl PlappsAddressFor for SimpleAddressDeterminer -where - T::AccountId: UncheckedFrom + AsRef<[u8]>, -{ - fn plapps_address_for(hash: &T::Hash, origin: &T::AccountId) -> T::AccountId { - let mut buf = Vec::new(); - buf.extend_from_slice(hash.as_ref()); - buf.extend_from_slice(origin.as_ref()); - - UncheckedFrom::unchecked_from(T::Hashing::hash(&buf[..])) - } -} - -pub trait Trait: pallet_ovm::Trait + pallet_contracts::Trait { - /// Plasma Range's currency. - type Currency: Currency; - - /// A function type to get the contract address given the instantiator. - type DeterminePlappsAddress: PlappsAddressFor; - - /// The using initial right over token address. - type MaximumTokenAddress: Get; - - /// The hashing system (algorithm) being used in the Plasma module (e.g. Keccak256). - type PlasmaHashing: Hash; - - /// The overarching event type. - type Event: From> + Into<::Event>; -} - -decl_storage! { - trait Store for Module as Plasma { - // Commitment storage: Plapps address => Commitment Child Storage. ==== - - /// Single aggregator address: AggregatorId - AggregatorAddress get(fn aggregator_address): map hasher(twox_64_concat) T::AccountId => T::AccountId; - /// Current block number of commitment chain: BlockNumber - CurrentBlock get(fn current_block): map hasher(twox_64_concat) T::AccountId => T::BlockNumber; - /// History of Merkle Root - Blocks get(fn blocks): double_map hasher(twox_64_concat) T::AccountId, hasher(blake2_128_concat) T::BlockNumber => T::Hash; - - - // Deposit storage: Plapps address => Deposit Child Storage. ==== - /// mapping from Plapps address to ERC20 based contract address. - ERC20 get(fn erc20): map hasher(twox_64_concat) T::AccountId => T::AccountId; - /// mapping from Plapps address to StateUpdate predicate address. - StateUpdatePredicate get(fn state_update_predicate): map hasher(twox_64_concat) T::AccountId => T::AccountId; - /// mapping from Plapps address to Exit predicate address. - ExitPredicate get(fn exit_predicate): map hasher(twox_64_concat) T::AccountId => T::AccountId; - /// mapping from Plapps address to ExitDeposit predicate address. - ExitDepositPredicate get(fn exit_deposit_predicate): map hasher(twox_64_concat) T::AccountId => T::AccountId; - - /// TotalDeposited is the most right coin id which has been deposited. - TotalDeposited get(fn total_deposited): map hasher(twox_64_concat) T::AccountId => BalanceOf; - /// DepositedRanges are currently deposited ranges. - DepositedRanges get(fn deposited_ranges): double_map hasher(twox_64_concat) T::AccountId, hasher(blake2_128_concat) BalanceOf => RangeOf; - /// Range's Checkpoints. - Checkpoints get(fn checkpoints): double_map hasher(twox_64_concat) T::AccountId, hasher(blake2_128_concat) T::Hash => bool; - - /// predicate address => payout address - Payout get(fn payout): map hasher(twox_64_concat) T::AccountId => T::AccountId; - } -} - -decl_event!( - pub enum Event - where - AccountId = ::AccountId, - Hash = ::Hash, - BlockNumber = ::BlockNumber, - Range = RangeOf, - Checkpoint = CheckpointOf, - { - /// Deplpoyed Plapps. (creator: AccountId, plapps_id: AccountId) - Deploy(AccountId, AccountId), - /// Event definitions (AccountID: PlappsAddress, BlockNumber, Hash: root) - BlockSubmitted(AccountId, BlockNumber, Hash), - /// (AccountID: PlappsAddress, checkpointId: Hash, checkpoint: Checkpoint); - CheckpointFinalized(AccountId, Hash, Checkpoint), - /// (AccountID: PlappsAddress, exit_id: Hash) - ExitFinalized(AccountId, Hash), - /// (AccountID: PlappsAddress, new_range: Range) - DepositedRangeExtended(AccountId, Range), - /// (AccountID: PlappsAddress, removed_range: Range) - DepositedRangeRemoved(AccountId, Range), - } -); - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - fn deposit_event() = default; - - const MaximumTokenAddress: ::AccountId = T::MaximumTokenAddress::get(); - - fn on_runtime_upgrade() -> Weight { - migrate::(); - T::MaximumBlockWeight::get() - } - - /// Commitment constructor + Deposit constructor - /// TODO: weight - #[weight = 100_000] - fn deploy( - origin, - aggregator_id: T::AccountId, - erc20: T::AccountId, - state_update_predicate: T::AccountId, - exit_predicate: T::AccountId, - exit_deposit_predicate: T::AccountId, - ) { - let sender = ensure_signed(origin)?; - let plapps_hash = Self::generate_plapps_hash( - &aggregator_id, - &erc20, - &state_update_predicate, - &exit_predicate, - &exit_deposit_predicate, - ); - let plapps_id = T::DeterminePlappsAddress::plapps_address_for(&plapps_hash, &sender); - >::insert(&plapps_id, aggregator_id); - >::insert(&plapps_id, erc20); - >::insert(&plapps_id, state_update_predicate); - >::insert(&plapps_id, exit_predicate); - >::insert(&plapps_id, exit_deposit_predicate); - Self::deposit_event(RawEvent::Deploy(sender, plapps_id)); - } - - // Commitment callable methods. ======== - - /// Submit root hash of Plasma chain. - /// TODO: weight - #[weight = 100_000] - fn submit_root(origin, plapps_id: T::AccountId, - block_number: T::BlockNumber, root: T::Hash) { - let aggregator = ensure_signed(origin)?; - Self::ensure_aggregator(&plapps_id, &aggregator)?; - ensure!( - Self::current_block(&plapps_id) + T::BlockNumber::one() == block_number, - Error::::BlockNumberShouldBeNextBlock, - ); - - >::insert(&plapps_id, &block_number, root.clone()); - >::insert(&plapps_id, block_number.clone()); - Self::deposit_event(RawEvent::BlockSubmitted(plapps_id, block_number, root)); - } - - /// deposit ERC20 token to deposit contract with initial state. - /// following https://docs.plasma.group/projects/spec/en/latest/src/02-contracts/deposit-contract.html#deposit - /// - @param amount to deposit - /// - @param initial_state The initial state of deposit - /// TODO: weight - #[weight = 100_000] - fn deposit(origin, plapps_id: T::AccountId, - amount: BalanceOf, initial_state: PropertyOf, gas_limit: Gas) { - let _ = ensure_signed(origin)?; - let total_deposited = Self::total_deposited(&plapps_id); - ensure!( - total_deposited < BalanceOf::::max_value().saturating_sub(amount), - Error::::TotalDepositedExceedMaxBalance, - ); - // TODO: transfer_from origin -> plapps_id (amount) at balances. - // let _ = contracts::bare_call( - // origin, - // Self::balances(&plapps_id),fAccountID - // BalanceOf::zero(), - // gas_limit, - // "transfer_from(origin, plapps_id, amount)", - // )?; - - let deposit_range = RangeOf:: { - start: total_deposited, - end: total_deposited.saturating_add(amount.clone()), - }; - let state_update = PropertyOf:: { - predicate_address: Self::state_update_predicate(&plapps_id), - inputs: vec![ - plapps_id.encode(), - deposit_range.encode(), - Self::get_latest_plasma_block_number(&plapps_id).encode(), - initial_state.encode(), - ], - }; - let checkpoint = Checkpoint { - state_update: state_update, - }; - Self::bare_extend_deposited_ranges(&plapps_id, amount); - let checkpoint_id = Self::get_checkpoint_id(&checkpoint); - >::insert(plapps_id.clone(), &checkpoint_id, true); - Self::deposit_event(RawEvent::CheckpointFinalized(plapps_id, checkpoint_id, checkpoint)); - } - - /// TODO: weight, not external - #[weight = 100_000] - fn extend_deposited_ranges(origin, plapps_id: T::AccountId, amount: BalanceOf) { - ensure_signed(origin)?; - Self::bare_extend_deposited_ranges(&plapps_id, amount); - } - - /// TODO: weight, not external - #[weight = 100_000] - fn remove_deposited_range(origin, plapps_id: T::AccountId, - range: RangeOf, deposited_range_id: BalanceOf) { - ensure_signed(origin)?; - Self::bare_remove_deposited_range( - &plapps_id, - &range, - &deposited_range_id, - )?; - } - - /// finalizeCheckpoint - /// - @param _checkpointProperty A property which is instance of checkpoint predicate - /// its first input is range to create checkpoint and second input is property for stateObject. - /// TODO: weight - #[weight = 100_000] - fn finalize_checkpoint(origin, plapps_id: T::AccountId, - checkpoint_property: PropertyOf) { - ensure!( - >::is_decided(&checkpoint_property) != Decision::True, - Error::::ClaimMustBeDecided, - ); - let property: PropertyOf = Decode::decode(&mut &checkpoint_property.inputs[0][..]) - .map_err(|_| Error::::MustBeDecodable)?; - let checkpoint = Checkpoint { - state_update: property, - }; - - let checkpoint_id = Self::get_checkpoint_id(&checkpoint); - // store the checkpoint - >::insert(&plapps_id, &checkpoint_id, true); - Self::deposit_event(RawEvent::CheckpointFinalized(plapps_id, checkpoint_id, checkpoint)); - } - - /// finalizeExit - /// - @param _exitProperty A property which is instance of exit predicate and its inputs are range and StateUpdate that exiting account wants to withdraw. - /// _exitProperty can be a property of ether ExitPredicate or ExitDepositPredicate. - /// - @param _depositedRangeId Id of deposited range - /// - @return return StateUpdate of exit property which is finalized. - /// - @dev The steps of finalizeExit. - /// 1. Serialize exit property - /// 2. check the property is decided by Adjudication Contract. - /// 3. Transfer asset to payout contract corresponding to StateObject. - /// - /// Please alse see https://docs.plasma.group/projects/spec/en/latest/src/02-contracts/deposit-contract.html#finalizeexit - /// TODO: weight - #[weight = 50_000_000] - fn finalize_exit(origin, plapps_id: T::AccountId, - exit_property: PropertyOf, deposited_range_id: BalanceOf, _owner: T::AccountId) { - let origin = ensure_signed(origin)?; - let state_update = Self::bare_finalize_exit( - &plapps_id, - &exit_property, - &deposited_range_id - )?; - let owner: T::AccountId = Decode::decode(&mut &state_update.state_object.inputs[0][..]) - .map_err(|_| Error::::MustBeDecodable)?; - let _amount = state_update.range.end - state_update.range.start; - ensure!( - origin == owner, - Error::::OriginMustBeOwner, - ); - // TODO: finalize_exit payout -> owner[state_update.state_objects.inputs[0]] (amount[state_update.range]) at payout. - // let _ = contracts::bare_call( - // plapps_id, - // Self::payout(&plapps_id), - // BalanceOf::zero(), - // gas_limit, - // "finalize_exit(state_update)", - // )?; - } - } -} - -decl_error! { - /// Error for the staking module. - pub enum Error for Module { - /// Sender isn't valid aggregator. - IsNotAggregator, - /// blkNumber should be next block. - BlockNumberShouldBeNextBlock, - /// leftStart must be less than _rightStart - LeftMustBeLessThanRight, - /// firstRightSiblingStart must be greater than siblingStart - FirstRightMustBeGreaterThanSibling, - /// required range must not exceed the implicit range - RangeMustNotExceedTheImplicitRange, - /// required address must not exceed the implicit address - AddressMustNotExceedTheImplicitAddress, - /// DepositContract: totalDeposited exceed max uint256 - TotalDepositedExceedMaxBalance, - /// must approved - MustApproved, - /// range must be of a depostied range (the one that has not been exited - RangeMustBeOfDepositedRange, - /// Checkpointing claim must be decied - ClaimMustBeDecided, - /// Must decode from checkpointInputs[0] to Property. - MustBeDecodable, - /// Exit must be decided after this block - ExitMustBeDecided, - /// finalizeExit must be called from payout contract - FinalizeExitMustBeCalledFromPayout, - /// origin must be owner - OriginMustBeOwner, - /// checkpoint must be finalized - CheckpointMustBeFinalized, - /// depositContractAddress must be same - DepositContractAddressMustBeSame, - /// blockNumber must be same, - BlockNumberMustBeSame, - /// range must be subrange of checkpoint - RangeMustBeSubrangeOfCheckpoint, - /// StateUpdate.depositContractAddress must be this contract address - DepositContractAddressMustBePlappsId, - } -} - -fn migrate() { - // TODO: When runtime upgrade, migrate stroage. - // if let Some(current_era) = CurrentEra::get() { - // let history_depth = HistoryDepth::get(); - // for era in current_era.saturating_sub(history_depth)..=current_era { - // ErasStartSessionIndex::migrate_key_from_blake(era); - // } - // } -} - -/// Public callable Plasma commitment module methods. -impl Module { - // Plasma Commitment parts ==== - pub fn retrieve(plapps_id: T::AccountId, block_number: T::BlockNumber) -> T::Hash { - >::get(&plapps_id, &block_number) - } - - /// verifyInclusion method verifies inclusion of message in Double Layer Tree. - /// The message has range and token address and these also must be verified. - /// Please see https://docs.plasma.group/projects/spec/en/latest/src/01-core/double-layer-tree.html for further details. - /// - @param leaf a message to verify its inclusion - /// - @param token_address token address of the message - /// - @param range range of the message - /// - @param inclusion_proof The proof data to verify inclusion - /// - @param block_number block number where the Merkle root is stored - pub fn verify_inclusion( - plapps_id: T::AccountId, - leaf: T::Hash, - token_address: T::AccountId, - range: RangeOf, - inclusion_proof: InclusionProofOf, - block_number: T::BlockNumber, - ) -> DispatchResultT { - let root = >::get(&plapps_id, &block_number); - Self::verify_inclusion_with_root(leaf, token_address, range, inclusion_proof, root) - } - - pub fn verify_inclusion_with_root( - leaf: T::Hash, - token_address: T::AccountId, - range: RangeOf, - inclusion_proof: InclusionProofOf, - root: T::Hash, - ) -> DispatchResultT { - // Calcurate the root of interval tree - let (computed_root, implicit_end) = Self::compute_interval_tree_root( - &leaf, - &inclusion_proof.interval_inclusion_proof.leaf_index, - &inclusion_proof.interval_inclusion_proof.leaf_position, - &inclusion_proof.interval_inclusion_proof.siblings, - )?; - - ensure!( - range.start >= inclusion_proof.interval_inclusion_proof.leaf_index - && range.end <= implicit_end, - Error::::RangeMustNotExceedTheImplicitRange, - ); - - // Calcurate the root of address tree - let (computed_root, implicit_address) = Self::compute_address_tree_root( - &computed_root, - &token_address, - &inclusion_proof.address_inclusion_proof.leaf_position, - &inclusion_proof.address_inclusion_proof.siblings, - )?; - - ensure!( - token_address <= implicit_address, - Error::::AddressMustNotExceedTheImplicitAddress, - ); - return Ok(computed_root == root); - } -} - -/// Private(Helper) Plasma commitment module methods. -impl Module { - // Plasma Commitment Parts - fn ensure_aggregator(sender: &T::AccountId, plapps_id: &T::AccountId) -> DispatchResult { - ensure!( - sender != &Self::aggregator_address(plapps_id), - Error::::IsNotAggregator, - ); - Ok(()) - } - - /// @dev computeIntervalTreeRoot method calculates the root of Interval Tree. - /// Please see https://docs.plasma.group/projects/spec/en/latest/src/01-core/merkle-interval-tree.html for further details. - fn compute_interval_tree_root( - computed_root: &T::Hash, - computed_start: &BalanceOf, - interval_tree_merkle_path: &BalanceOf, - interval_tree_proof: &Vec>, - ) -> DispatchResultT<(T::Hash, BalanceOf)> { - let mut first_right_sibling_start = BalanceOf::::max_value(); - let mut is_first_right_sibling_start_set = false; - let mut ret_computed_root: T::Hash = computed_root.clone(); - let mut ret_computed_start: BalanceOf = computed_start.clone(); - for (i, node) in interval_tree_proof.iter().enumerate() { - let sibling = &node.data; - let sibling_start = &node.start; - let is_computed_right_sibling = - interval_tree_merkle_path.clone().saturated_into::() >> i; - if is_computed_right_sibling == 1 { - ret_computed_root = Self::get_parent( - sibling, - sibling_start, - &ret_computed_root, - &ret_computed_start, - )?; - } else { - if !is_first_right_sibling_start_set { - first_right_sibling_start = sibling_start.clone(); - is_first_right_sibling_start_set = true; - } - ensure!( - &first_right_sibling_start <= sibling_start, - Error::::FirstRightMustBeGreaterThanSibling, - ); - ret_computed_root = Self::get_parent( - &ret_computed_root, - &ret_computed_start, - sibling, - sibling_start, - )?; - ret_computed_start = sibling_start.clone(); - } - } - Ok((ret_computed_root, first_right_sibling_start)) - } - - /// @dev computeAddressTreeRoot method calculates the root of Address Tree. - /// Address Tree is almost the same as Merkle Tree. - /// But leaf has their address and we can verify the address each leaf belongs to. - fn compute_address_tree_root( - computed_root: &T::Hash, - compute_address: &T::AccountId, - address_tree_merkle_path: &BalanceOf, - address_tree_proof: &Vec>, - ) -> DispatchResultT<(T::Hash, T::AccountId)> { - let mut first_right_sibling_address = T::MaximumTokenAddress::get(); - let mut is_first_right_sibling_address_set = false; - let mut ret_computed_root: T::Hash = computed_root.clone(); - let mut ret_compute_address: T::AccountId = compute_address.clone(); - for (i, node) in address_tree_proof.iter().enumerate() { - let sibling = &node.data; - let sibling_address = &node.token_address; - let is_computed_right_sibling = - (address_tree_merkle_path.clone().saturated_into::() >> i) & 1; - if is_computed_right_sibling == 1 { - ret_computed_root = Self::get_parent_of_address_tree_node( - sibling, - sibling_address, - &ret_computed_root, - &ret_compute_address, - ); - ret_compute_address = sibling_address.clone(); - } else { - if !is_first_right_sibling_address_set { - first_right_sibling_address = sibling_address.clone(); - is_first_right_sibling_address_set = true; - } - ensure!( - &first_right_sibling_address <= sibling_address, - Error::::FirstRightMustBeGreaterThanSibling, - ); - ret_computed_root = Self::get_parent_of_address_tree_node( - &ret_computed_root, - &ret_compute_address, - sibling, - sibling_address, - ); - } - } - Ok((ret_computed_root, first_right_sibling_address)) - } - - fn get_parent( - left: &T::Hash, - left_start: &BalanceOf, - right: &T::Hash, - right_start: &BalanceOf, - ) -> DispatchResultT { - ensure!( - right_start >= left_start, - Error::::LeftMustBeLessThanRight, - ); - return Ok(T::PlasmaHashing::hash_of(&( - left, - left_start, - right, - right_start, - ))); - } -} - -/// Public callable Plasma deposit module methods. -impl Module { - pub fn bare_extend_deposited_ranges(plapps_id: &T::AccountId, amount: BalanceOf) { - let total_deposited = Self::total_deposited(plapps_id); - let old_range = Self::deposited_ranges(plapps_id, &total_deposited); - let new_start = if old_range.start == BalanceOf::::zero() - && old_range.end == BalanceOf::::zero() - { - // Creat a new range when the rightmost range has been removed - total_deposited - } else { - // Delete the old range and make a new one with the total length - >::remove(plapps_id, old_range.end); - old_range.start - }; - - let new_end = total_deposited.saturating_add(amount.clone()); - let new_range = Range { - start: new_start, - end: new_end, - }; - >::insert(plapps_id, &new_end, new_range.clone()); - >::insert(plapps_id, total_deposited.saturating_add(amount)); - Self::deposit_event(RawEvent::DepositedRangeExtended( - plapps_id.clone(), - new_range, - )); - } - - pub fn bare_remove_deposited_range( - plapps_id: &T::AccountId, - range: &RangeOf, - deposited_range_id: &BalanceOf, - ) -> DispatchResult { - let deposited_ranges = Self::deposited_ranges(plapps_id, deposited_range_id); - ensure!( - Self::is_subrange(range, &deposited_ranges), - Error::::RangeMustBeOfDepositedRange, - ); - - /* - * depositedRanges makes O(1) checking existence of certain range. - * Since _range is subrange of encompasingRange, we only have to check is each start and end are same or not. - * So, there are 2 patterns for each start and end of _range and encompasingRange. - * There are nothing todo for _range.start is equal to encompasingRange.start. - */ - // Check start of range - if range.start != deposited_ranges.start { - let left_split_range = Range { - start: deposited_ranges.start, - end: range.start, - }; - >::insert(plapps_id, left_split_range.end, left_split_range); - } - // Check end of range - if range.end == deposited_ranges.end { - /* - * Deposited range Id is end value of the range, we must remove the range from depositedRanges - * when range.end is changed. - */ - >::remove(plapps_id, &deposited_ranges.end); - } else { - >::insert( - plapps_id, - &deposited_ranges.end, - Range { - start: range.end, - end: deposited_ranges.end, - }, - ); - } - Self::deposit_event(RawEvent::DepositedRangeRemoved( - plapps_id.clone(), - range.clone(), - )); - Ok(()) - } - - /// bare_finalize_exit - /// called by this module. - /// - @param _exitProperty A property which is instance of exit predicate and its inputs are range and StateUpdate that exiting account wants to withdraw. - /// _exitProperty can be a property of ether ExitPredicate or ExitDepositPredicate. - /// - @param _depositedRangeId Id of deposited range - /// - @return return StateUpdate of exit property which is finalized. - /// - @dev The steps of finalizeExit. - /// 1. Serialize exit property - /// 2. check the property is decided by Adjudication Contract. - /// 3. Transfer asset to payout contract corresponding to StateObject. - /// - /// Please alse see https://docs.plasma.group/projects/spec/en/latest/src/02-contracts/deposit-contract.html#finalizeexit - pub fn bare_finalize_exit( - plapps_id: &T::AccountId, - exit_property: &PropertyOf, - deposited_range_id: &BalanceOf, - ) -> DispatchResultT> { - let state_update = Self::verify_exit_property(plapps_id, exit_property)?; - let exit_id = Self::get_exit_id(exit_property); - // get payout contract address - let _payout = Self::payout(plapps_id); - - // Check that we are authorized to finalize this exit - ensure!( - >::is_decided(exit_property) != Decision::True, - Error::::ExitMustBeDecided, - ); - - ensure!( - &state_update.deposit_contract_address == plapps_id, - Error::::DepositContractAddressMustBePlappsId, - ); - - // Remove the deposited range - Self::bare_remove_deposited_range(plapps_id, &state_update.range, deposited_range_id)?; - // Transfer tokens to its predicate - let _amount = state_update.range.end - state_update.range.start; - - // TODO: transfer plapps_id -> payout (amount) at balances. - // let _ = contracts::bare_call( - // origin, - // Self::balances(&plapps_id), - // BalanceOf::zero(), - // gas_limit, - // "transfer(payout, amount)", - // )?; - Self::deposit_event(RawEvent::ExitFinalized(plapps_id.clone(), exit_id)); - Ok(state_update) - } - - /// @dev verify StateUpdate in Exit property. - /// _exitProperty must be instance of ether ExitPredicate or ExitDepositPredicate. - /// if _exitProperty is instance of ExitDepositPredicate, check _exitProperty.su is subrange of _exitProperty.checkpoint. - pub fn verify_exit_property( - plapps_id: &T::AccountId, - exit_property: &PropertyOf, - ) -> DispatchResultT> { - if exit_property.predicate_address == Self::exit_predicate(plapps_id) { - let exit: ExitOf = >::deserialize_exit(exit_property)?; - // TODO: check inclusion proof - return Ok(exit.state_update); - } else if exit_property.predicate_address == Self::exit_deposit_predicate(plapps_id) { - let exit_deposit = >::deserialize_exit_deposit(exit_property)?; - let checkpoint = exit_deposit.checkpoint; - let state_update = - >::deserialize_state_update(&checkpoint.state_update)?; - ensure!( - Self::checkpoints(plapps_id, Self::get_checkpoint_id(&checkpoint)), - Error::::CheckpointMustBeFinalized, - ); - ensure!( - state_update.deposit_contract_address - == exit_deposit.state_update.deposit_contract_address, - Error::::DepositContractAddressMustBeSame, - ); - ensure!( - state_update.block_number == exit_deposit.state_update.block_number, - Error::::BlockNumberMustBeSame, - ); - ensure!( - Self::is_subrange(&exit_deposit.state_update.range, &state_update.range), - Error::::RangeMustBeSubrangeOfCheckpoint, - ); - return Ok(exit_deposit.state_update); - } - Err(DispatchError::Other( - "verify_exit_property not return value.", - )) - } -} - -/// Priavte(Helper) callable Plasma deposit module methods. -impl Module { - fn get_parent_of_address_tree_node( - left: &T::Hash, - left_address: &T::AccountId, - right: &T::Hash, - right_address: &T::AccountId, - ) -> T::Hash { - T::PlasmaHashing::hash_of(&(left, left_address, right, right_address)) - } - - fn get_latest_plasma_block_number(plapps_id: &T::AccountId) -> T::BlockNumber { - return Self::current_block(&plapps_id); - } - - fn get_checkpoint_id(checkpoint: &CheckpointOf) -> T::Hash { - ::Hashing::hash_of(checkpoint) - } - - fn get_exit_id(exit: &PropertyOf) -> T::Hash { - ::Hashing::hash_of(exit) - } - - fn is_subrange(subrange: &RangeOf, surrounding_range: &RangeOf) -> bool { - subrange.start >= surrounding_range.start && subrange.end <= surrounding_range.end - } - - fn generate_plapps_hash( - aggregator_id: &T::AccountId, - erc20: &T::AccountId, - state_update_predicate: &T::AccountId, - exit_predicate: &T::AccountId, - exit_deposit_predicate: &T::AccountId, - ) -> T::Hash { - T::Hashing::hash_of(&( - T::Hashing::hash_of(&aggregator_id), - T::Hashing::hash_of(&erc20), - T::Hashing::hash_of(&state_update_predicate), - T::Hashing::hash_of(&exit_predicate), - T::Hashing::hash_of(&exit_deposit_predicate), - )) - } -} diff --git a/frame/plasma/src/mock.rs b/frame/plasma/src/mock.rs deleted file mode 100644 index 4e56e6c708..0000000000 --- a/frame/plasma/src/mock.rs +++ /dev/null @@ -1,333 +0,0 @@ -//! Test utilities - -#![cfg(test)] - -use super::*; -pub use frame_support::{ - impl_outer_dispatch, impl_outer_event, impl_outer_origin, parameter_types, - traits::OnFinalize, - weights::{WeightToFeeCoefficients, WeightToFeePolynomial}, -}; -pub use hex_literal::hex; -pub use pallet_balances as balances; -pub use pallet_contracts::{self as contracts, ContractAddressFor, TrieId, TrieIdGenerator}; -pub use pallet_ovm::{self as ovm, AtomicPredicateIdConfig}; -use sp_core::crypto::AccountId32; -pub use sp_core::{ - crypto::{key_types, UncheckedInto}, - Pair, H256, -}; -pub use sp_runtime::testing::{Header, UintAuthorityId}; -pub use sp_runtime::traits::{BlakeTwo256, ConvertInto, IdentifyAccount, IdentityLookup}; -pub use sp_runtime::{KeyTypeId, Perbill}; - -pub type BlockNumber = u64; -pub type AccountId = AccountId32; -pub type Balance = u64; - -lazy_static::lazy_static! { - pub static ref ALICE_STASH: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000005553" - ]); - pub static ref BOB_STASH: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000008553" - ]); - pub static ref CHARLIE_STASH: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000009553" - ]); -} - -impl_outer_origin! { - pub enum Origin for Test where system = frame_system {} -} - -impl_outer_dispatch! { - pub enum Call for Test where origin: Origin { - pallet_balances::Balances, - pallet_contracts::Contracts, - } -} - -mod plasma { - // Re-export contents of the root. This basically - // needs to give a name for the current crate. - // This hack is required for `impl_outer_event!`. - pub use super::super::*; -} - -impl_outer_event! { - pub enum MetaEvent for Test { - system, - balances, - contracts, - ovm, - plasma, - } -} - -pub fn new_test_ext() -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); - - let _ = pallet_balances::GenesisConfig:: { - balances: vec![((*ALICE_STASH).clone(), 1_000_000_000_000_000_000)], - } - .assimilate_storage(&mut storage); - - let _ = ovm::GenesisConfig { - current_schedule: Default::default(), - } - .assimilate_storage(&mut storage); - - storage.into() -} - -#[derive(Clone, PartialEq, Eq, Debug)] -pub struct Test; - -parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: u32 = 1024; - pub const MaximumBlockLength: u32 = 2 * 1024; - pub const AvailableBlockRatio: Perbill = Perbill::one(); -} - -impl frame_system::Trait for Test { - type Origin = Origin; - type BaseCallFilter = (); - type Index = u64; - type BlockNumber = BlockNumber; - type Call = Call; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; - type Header = Header; - type Event = MetaEvent; - type DbWeight = (); - type BlockHashCount = BlockHashCount; - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = (); - type MaximumBlockWeight = MaximumBlockWeight; - type MaximumBlockLength = MaximumBlockLength; - type AvailableBlockRatio = AvailableBlockRatio; - type Version = (); - type PalletInfo = (); - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); -} - -parameter_types! { - pub const ExistentialDeposit: Balance = 10; -} - -impl pallet_balances::Trait for Test { - type Balance = Balance; - type Event = MetaEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Module; - type WeightInfo = (); - type MaxLocks = (); -} - -parameter_types! { - pub const MinimumPeriod: u64 = 1; -} - -impl pallet_timestamp::Trait for Test { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); -} - -pub struct WeightToFee; -impl WeightToFeePolynomial for WeightToFee { - type Balance = u64; - fn polynomial() -> WeightToFeeCoefficients { - Default::default() - } -} - -impl pallet_transaction_payment::Trait for Test { - type Currency = Balances; - type OnTransactionPayment = (); - type TransactionByteFee = TransactionByteFee; - type WeightToFee = WeightToFee; - type FeeMultiplierUpdate = (); -} - -parameter_types! { - pub const SignedClaimHandicap: u64 = 2; - pub const TombstoneDeposit: u64 = 16; - pub const StorageSizeOffset: u32 = 8; - pub const RentByteFee: u64 = 4; - pub const RentDepositOffset: u64 = 10_000; - pub const SurchargeReward: u64 = 150; - pub const TransactionBaseFee: u64 = 2; - pub const TransactionByteFee: u64 = 6; - pub const ContractFee: u64 = 21; - pub const CallBaseFee: u64 = 135; - pub const InstantiateBaseFee: u64 = 175; - pub const MaxDepth: u32 = 100; - pub const MaxValueSize: u32 = 16_384; -} - -impl pallet_contracts::Trait for Test { - type Time = Timestamp; - type Randomness = Randomness; - type Currency = Balances; - type Event = MetaEvent; - type DetermineContractAddress = pallet_contracts::SimpleAddressDeterminer; - type TrieIdGenerator = pallet_contracts::TrieIdFromParentCounter; - type RentPayment = (); - type SignedClaimHandicap = SignedClaimHandicap; - type TombstoneDeposit = TombstoneDeposit; - type StorageSizeOffset = StorageSizeOffset; - type RentByteFee = RentByteFee; - type RentDepositOffset = RentDepositOffset; - type SurchargeReward = SurchargeReward; - type MaxDepth = MaxDepth; - type MaxValueSize = MaxValueSize; - type WeightPrice = (); -} - -parameter_types! { - pub const DisputePeriod: BlockNumber = 7; -} - -lazy_static::lazy_static! { - pub static ref NOT_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000003" - ]); - pub static ref AND_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000004" - ]); - pub static ref OR_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000005" - ]); - pub static ref FOR_ALL_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000006" - ]); - pub static ref THERE_EXISTS_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000007" - ]); - pub static ref EQUAL_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000008" - ]); - pub static ref IS_CONTAINED_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000009" - ]); - pub static ref IS_LESS_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000010" - ]); - pub static ref IS_STORED_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000011" - ]); - pub static ref IS_VALID_SIGNATURE_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000012" - ]); - pub static ref VERIFY_INCLUSION_ADDRESS: AccountId = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000013" - ]); - pub static ref SECP_256_K1: H256 = H256::from(&hex![ - "d4fa99b1e08c4e5e6deb461846aa629344d95ff03ed04754c2053d54c756f439" - ]); -} - -pub struct MockAtomicPredicateIdConfigGetter; -impl Get> for MockAtomicPredicateIdConfigGetter { - fn get() -> AtomicPredicateIdConfig { - AtomicPredicateIdConfig { - not_address: (*NOT_ADDRESS).clone(), - and_address: (*AND_ADDRESS).clone(), - or_address: (*OR_ADDRESS).clone(), - for_all_address: (*FOR_ALL_ADDRESS).clone(), - there_exists_address: (*THERE_EXISTS_ADDRESS).clone(), - equal_address: (*EQUAL_ADDRESS).clone(), - is_contained_address: (*IS_CONTAINED_ADDRESS).clone(), - is_less_address: (*IS_LESS_ADDRESS).clone(), - is_stored_address: (*IS_STORED_ADDRESS).clone(), - is_valid_signature_address: (*IS_VALID_SIGNATURE_ADDRESS).clone(), - verify_inclusion_address: (*VERIFY_INCLUSION_ADDRESS).clone(), - secp256k1: (*SECP_256_K1).clone(), - } - } -} - -impl pallet_ovm::Trait for Test { - type MaxDepth = MaxDepth; - type DisputePeriod = DisputePeriod; - type DeterminePredicateAddress = ovm::SimpleAddressDeterminer; - type HashingL2 = BlakeTwo256; - type ExternalCall = ovm::predicate::CallContext; - type AtomicPredicateIdConfig = MockAtomicPredicateIdConfigGetter; - type Event = MetaEvent; -} - -pub struct MaximumTokenAddress; -impl Get for MaximumTokenAddress { - fn get() -> AccountId { - H256::from(&hex![ - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - ]) - .unchecked_into() - } -} - -impl Trait for Test { - type Currency = Balances; - type DeterminePlappsAddress = SimpleAddressDeterminer; - type MaximumTokenAddress = MaximumTokenAddress; - // TODO: should be Keccak; - type PlasmaHashing = BlakeTwo256; - type Event = MetaEvent; -} - -pub type System = frame_system::Module; -pub type Balances = pallet_balances::Module; -pub type Contracts = pallet_contracts::Module; -// pub type Ovm = pallet_ovm::Module; -pub type Plasma = Module; -pub type Timestamp = pallet_timestamp::Module; -pub type Randomness = pallet_randomness_collective_flip::Module; - -pub fn advance_block() { - System::finalize(); - let next = System::block_number() + 1; - // increase block numebr - System::set_block_number(next); - System::initialize( - &next, - &[0u8; 32].into(), - &[0u8; 32].into(), - &Default::default(), - system::InitKind::Full, - ); - System::note_finished_initialize(); -} - -/// Generate compiled predicate binary and code hash from predicate source. -pub fn compile_predicate(predicate_module: &str) -> (Vec, ::Output) -where - T: frame_system::Trait, -{ - // TODO actually predicate to compiled predicate. - let compiled_predicate = predicate_module.as_bytes().to_vec(); - let code_hash = T::Hashing::hash_of(&compiled_predicate); - (compiled_predicate.to_vec(), code_hash) -} - -pub fn to_account_from_seed(seed: &[u8; 32]) -> AccountId { - to_account(sp_core::ecdsa::Pair::from_seed(&seed).public().as_ref()) -} - -pub fn to_account(full_public: &[u8]) -> AccountId { - let public = sp_core::ecdsa::Public::from_full(full_public).unwrap(); - sp_runtime::MultiSigner::from(public).into_account() -} diff --git a/frame/plasma/src/tests.rs b/frame/plasma/src/tests.rs deleted file mode 100644 index 718369970e..0000000000 --- a/frame/plasma/src/tests.rs +++ /dev/null @@ -1,465 +0,0 @@ -//! Tests for the ovm module. - -#![cfg(test)] - -use super::*; -use crate::mock::*; -use frame_support::assert_ok; -use frame_system::{EventRecord, Phase}; -use hex_literal::hex; - -lazy_static::lazy_static! { - pub static ref AGGREGATOR_ID: AccountId = to_account_from_seed(&hex![ - "1000000000000000000000000000000000000000000000000000000000005553" - ]); - - pub static ref ERC20_ID: AccountId = to_account_from_seed(&hex![ - "1000000000000000000000000000000000000000000000000000000000005553" - ]); - pub static ref STATE_UPDATE_ID: AccountId = to_account_from_seed(&hex![ - "1000000000000000000000000000000000000000000000000000000000005553" - ]); - pub static ref EXIT_ID: AccountId = to_account_from_seed(&hex![ - "1000000000000000000000000000000000000000000000000000000000005553" - ]); - pub static ref EXIT_DEPOSIT_ID: AccountId = to_account_from_seed(&hex![ - "1000000000000000000000000000000000000000000000000000000000005553" - ]); -} - -fn success_deploy( - sender: AccountId, - aggregator_id: AccountId, - erc20: AccountId, - state_update_predicate: AccountId, - exit_predicate: AccountId, - exit_deposit_predicate: AccountId, -) -> AccountId { - assert_ok!(Plasma::deploy( - Origin::signed(sender.clone()), - aggregator_id.clone(), - erc20.clone(), - state_update_predicate.clone(), - exit_predicate.clone(), - exit_deposit_predicate.clone() - )); - - let plapps_id = SimpleAddressDeterminer::::plapps_address_for( - &Module::::generate_plapps_hash( - &aggregator_id, - &erc20, - &state_update_predicate, - &exit_predicate, - &exit_deposit_predicate, - ), - &sender, - ); - - // check initail config ids - assert_eq!(Plasma::aggregator_address(&plapps_id), aggregator_id); - assert_eq!(Plasma::erc20(&plapps_id), erc20); - assert_eq!( - Plasma::state_update_predicate(&plapps_id), - state_update_predicate - ); - assert_eq!(Plasma::exit_predicate(&plapps_id), exit_predicate); - assert_eq!( - Plasma::exit_deposit_predicate(&plapps_id), - exit_deposit_predicate - ); - assert_eq!( - System::events(), - vec![EventRecord { - phase: Phase::ApplyExtrinsic(0), - event: MetaEvent::plasma(RawEvent::Deploy(sender, plapps_id.clone())), - topics: vec![], - }] - ); - return plapps_id; -} - -#[test] -fn deploy_sucess() { - new_test_ext().execute_with(|| { - advance_block(); - success_deploy( - (*ALICE_STASH).clone(), - (*AGGREGATOR_ID).clone(), - (*ERC20_ID).clone(), - (*STATE_UPDATE_ID).clone(), - (*EXIT_ID).clone(), - (*EXIT_DEPOSIT_ID).clone(), - ); - }) -} - -fn success_submit_root( - sender: AccountId, - plapps_id: AccountId, - block_number: BlockNumber, - root: H256, -) -> (AccountId, BlockNumber, H256) { - assert_ok!(Plasma::submit_root( - Origin::signed(sender.clone()), - plapps_id.clone(), - block_number, - root, - )); - - // check update blocks - assert_eq!(Plasma::blocks(&plapps_id, &block_number), root); - // check upadte current block - assert_eq!(Plasma::current_block(&plapps_id), block_number); - assert_eq!( - System::events(), - vec![EventRecord { - phase: Phase::ApplyExtrinsic(0), - event: MetaEvent::plasma(RawEvent::BlockSubmitted( - plapps_id.clone(), - block_number.clone(), - root.clone() - )), - topics: vec![], - }] - ); - return (plapps_id, block_number, root); -} - -#[test] -fn submit_root_success() { - new_test_ext().execute_with(|| { - advance_block(); - let plapps_id = success_deploy( - (*ALICE_STASH).clone(), - (*AGGREGATOR_ID).clone(), - (*ERC20_ID).clone(), - (*STATE_UPDATE_ID).clone(), - (*EXIT_ID).clone(), - (*EXIT_DEPOSIT_ID).clone(), - ); - - advance_block(); - - // 1-indexed. - success_submit_root( - (*AGGREGATOR_ID).clone(), - plapps_id.clone(), - 1, - H256::default(), - ); - advance_block(); - success_submit_root( - (*AGGREGATOR_ID).clone(), - plapps_id.clone(), - 2, - H256::default(), - ); - advance_block(); - success_submit_root( - (*AGGREGATOR_ID).clone(), - plapps_id.clone(), - 3, - H256::default(), - ); - }) -} - -#[test] -fn verify_inclusion_test() { - /* - * Tree for test case - * root - * / \ - * root0 root1 - * / \ - * / \ / \ / \ - * 0 1 2 3 1-0 1-1 - */ - new_test_ext().execute_with(|| { - let token_address: AccountId = to_account_from_seed(&hex![ - "9000000000000000000000000000000000000000000000000000000000000003" - ]); - let leaf_0: H256 = BlakeTwo256::hash("leaf0".as_bytes()); - let _leaf_1: H256 = BlakeTwo256::hash("leaf1".as_bytes()); - let _leaf_2: H256 = BlakeTwo256::hash("leaf2".as_bytes()); - let _leaf_3: H256 = BlakeTwo256::hash("leaf3".as_bytes()); - let block_number: BlockNumber = 1; - let root: H256 = H256::from(hex![ - "1aa3429d5aa7bf693f3879fdfe0f1a979a4b49eaeca9638fea07ad7ee5f0b64f" - ]); - let valid_inclusion_proof: InclusionProof = - InclusionProof:: { - address_inclusion_proof: AddressInclusionProof { - leaf_position: 0, - leaf_index: AccountId::default(), - siblings: vec![AddressTreeNode { - token_address: token_address.clone(), - data: H256::from(hex![ - "dd779be20b84ced84b7cbbdc8dc98d901ecd198642313d35d32775d75d916d3a" - ]), - }], - }, - interval_inclusion_proof: IntervalInclusionProof { - leaf_position: 0, - leaf_index: 0, - siblings: vec![ - IntervalTreeNode { - start: 7, - data: H256::from(hex![ - "036491cc10808eeb0ff717314df6f19ba2e232d04d5f039f6fa382cae41641da" - ]), - }, - IntervalTreeNode { - start: 5000, - data: H256::from(hex![ - "ef583c07cae62e3a002a9ad558064ae80db17162801132f9327e8bb6da16ea8a" - ]), - }, - ], - }, - }; - - advance_block(); - // previous tests. - - let plapps_id = success_deploy( - (*ALICE_STASH).clone(), - (*AGGREGATOR_ID).clone(), - (*ERC20_ID).clone(), - (*STATE_UPDATE_ID).clone(), - (*EXIT_ID).clone(), - (*EXIT_DEPOSIT_ID).clone(), - ); - - advance_block(); - // 1-indexed. - success_submit_root( - (*AGGREGATOR_ID).clone(), - plapps_id.clone(), - block_number, - root, - ); - - // suceed to verify inclusion of the most left leaf - let result = Plasma::verify_inclusion( - plapps_id, - leaf_0.clone(), - token_address, - Range:: { start: 0, end: 5 }, - valid_inclusion_proof, - block_number, - ); - // TODO: shuld be passed true. - assert_eq!(result, Ok(false)); - }) -} - -fn simulation_extend_ranges(plapps_id: &AccountId, amount: &Balance) -> RangeOf { - let total_deposited = Plasma::total_deposited(plapps_id); - let old_range = Plasma::deposited_ranges(plapps_id, &total_deposited); - let new_start = if old_range.start == BalanceOf::::zero() - && old_range.end == BalanceOf::::zero() - { - total_deposited - } else { - old_range.start - }; - - let new_end = total_deposited.saturating_add(amount.clone()); - Range { - start: new_start, - end: new_end, - } -} - -fn success_deposit( - sender: AccountId, - plapps_id: AccountId, - amount: BalanceOf, - initial_state: PropertyOf, - gas_limit: Gas, -) { - let total_deposited = Plasma::total_deposited(&plapps_id); - let deposit_range = RangeOf:: { - start: total_deposited, - end: total_deposited.saturating_add(amount.clone()), - }; - let new_range = simulation_extend_ranges(&plapps_id, &amount); - let state_update = PropertyOf:: { - predicate_address: Plasma::state_update_predicate(&plapps_id), - inputs: vec![ - plapps_id.encode(), - deposit_range.encode(), - Plasma::get_latest_plasma_block_number(&plapps_id).encode(), - initial_state.encode(), - ], - }; - let checkpoint = Checkpoint { - state_update: state_update, - }; - let checkpoint_id = Plasma::get_checkpoint_id(&checkpoint); - - assert_ok!(Plasma::deposit( - Origin::signed(sender.clone().clone()), - plapps_id.clone(), - amount, - initial_state.clone(), - gas_limit, - )); - - assert_eq!( - Plasma::deposited_ranges(plapps_id.clone(), new_range.end), - new_range, - ); - assert_eq!( - Plasma::total_deposited(&plapps_id), - total_deposited + amount - ); - assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::ApplyExtrinsic(0), - event: MetaEvent::plasma(RawEvent::DepositedRangeExtended( - plapps_id.clone(), - new_range - )), - topics: vec![], - }, - EventRecord { - phase: Phase::ApplyExtrinsic(0), - event: MetaEvent::plasma(RawEvent::CheckpointFinalized( - plapps_id.clone(), - checkpoint_id.clone(), - checkpoint.clone(), - )), - topics: vec![], - } - ] - ); - assert_eq!(Plasma::checkpoints(plapps_id.clone(), &checkpoint_id), true); -} - -fn success_extend_deposited_ranges(sender: AccountId, plapps_id: AccountId, amount: Balance) { - let total_deposited = Plasma::total_deposited(&plapps_id); - let new_range = simulation_extend_ranges(&plapps_id, &amount); - assert_ok!(Plasma::extend_deposited_ranges( - Origin::signed(sender.clone()), - plapps_id.clone(), - amount - )); - assert_eq!( - Plasma::deposited_ranges(plapps_id.clone(), new_range.end), - new_range, - ); - assert_eq!( - Plasma::total_deposited(&plapps_id), - total_deposited + amount - ); - assert_eq!( - System::events(), - vec![EventRecord { - phase: Phase::ApplyExtrinsic(0), - event: MetaEvent::plasma(RawEvent::DepositedRangeExtended(plapps_id, new_range)), - topics: vec![], - },] - ); -} - -fn success_remove_deposited_range( - sender: AccountId, - plapps_id: AccountId, - range: RangeOf, - deposited_range_id: Balance, -) { - assert_ok!(Plasma::remove_deposited_range( - Origin::signed(sender.clone()), - plapps_id.clone(), - range.clone(), - deposited_range_id - )); - assert_eq!( - System::events(), - vec![EventRecord { - phase: Phase::ApplyExtrinsic(0), - event: MetaEvent::plasma(RawEvent::DepositedRangeRemoved(plapps_id.clone(), range)), - topics: vec![], - },] - ); -} - -#[test] -fn scenario_test() { - new_test_ext().execute_with(|| { - advance_block(); - let plapps_id = success_deploy( - (*ALICE_STASH).clone(), - (*AGGREGATOR_ID).clone(), - (*ERC20_ID).clone(), - (*STATE_UPDATE_ID).clone(), - (*EXIT_ID).clone(), - (*EXIT_DEPOSIT_ID).clone(), - ); - - advance_block(); - success_deposit( - (*ALICE_STASH).clone(), - plapps_id.clone(), - 10, - PropertyOf:: { - predicate_address: (*STATE_UPDATE_ID).clone(), - inputs: vec![hex!["01"].to_vec()], - }, - 1000000, - ); - - advance_block(); - success_deposit( - (*BOB_STASH).clone(), - plapps_id.clone(), - 30, - PropertyOf:: { - predicate_address: (*STATE_UPDATE_ID).clone(), - inputs: vec![hex!["01"].to_vec()], - }, - 1000000, - ); - - advance_block(); - success_deposit( - (*CHARLIE_STASH).clone(), - plapps_id.clone(), - 80, - PropertyOf:: { - predicate_address: (*STATE_UPDATE_ID).clone(), - inputs: vec![hex!["01"].to_vec()], - }, - 1000000, - ); - - advance_block(); - success_extend_deposited_ranges((*ALICE_STASH).clone(), plapps_id.clone(), 100); - - advance_block(); - success_remove_deposited_range( - (*ALICE_STASH).clone(), - plapps_id.clone(), - Range { - start: 120, - end: 200, - }, - 220, - ); - - advance_block(); - success_remove_deposited_range( - (*ALICE_STASH).clone(), - plapps_id.clone(), - Range { - start: 200, - end: 220, - }, - 220, - ); - }); -} diff --git a/frame/trading/Cargo.toml b/frame/trading/Cargo.toml deleted file mode 100644 index 74f3c11ab6..0000000000 --- a/frame/trading/Cargo.toml +++ /dev/null @@ -1,39 +0,0 @@ -[package] -name = "pallet-operator-trading" -version = "1.7.0" -authors = ["Stake Technologies "] -edition = "2018" -license = "Apache-2.0" -homepage = "https://docs.plasmnet.io/" -repository = "https://github.com/staketechnologies/Plasm/" -description = "FRAME pallet to trade the authority of smart contract operator" - -[dependencies] -codec = { package = "parity-scale-codec", version = "1.3.5", features = ["derive"], default-features = false } -serde = { version = "1.0.106", features = ["derive"], optional = true } -sp-core = { version = "2.0.0", default_features = false } -sp-runtime = { version = "2.0.0", default_features = false } -sp-io = { version = "2.0.0", default_features = false } -sp-std = { version = "2.0.0", default_features = false } -pallet-balances = { version = "2.0.0", default_features = false } -frame-support = { version = "2.0.0", default_features = false } -pallet-timestamp = { version = "2.0.0", default_features = false } -frame-system = { version = "2.0.0", default_features = false } - -pallet-plasm-support = { path = "../plasm-support", version = "1.7.0", default_features = false } - -[features] -default = ["std"] -std = [ - "serde", - "codec/std", - "sp-core/std", - "sp-runtime/std", - "sp-io/std", - "sp-std/std", - "pallet-balances/std", - "frame-support/std", - "pallet-timestamp/std", - "frame-system/std", - "pallet-plasm-support/std", -] diff --git a/frame/trading/src/lib.rs b/frame/trading/src/lib.rs deleted file mode 100644 index fc5940ac89..0000000000 --- a/frame/trading/src/lib.rs +++ /dev/null @@ -1,244 +0,0 @@ -#![cfg_attr(not(feature = "std"), no_std)] - -use codec::{Decode, Encode}; -use frame_support::{ - decl_event, decl_module, decl_storage, - traits::{Currency, ExistenceRequirement, LockIdentifier, LockableCurrency, WithdrawReasons}, -}; -use frame_system::ensure_signed; -use pallet_plasm_support::{OperatorFinder, TransferOperator}; -use sp_std::prelude::*; - -#[cfg(feature = "std")] -use serde::{Deserialize, Serialize}; - -#[cfg(test)] -mod tests; - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -pub enum OfferState { - Waiting, - Reject, - Accept, -} - -impl Default for OfferState { - fn default() -> OfferState { - OfferState::Waiting - } -} - -#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -pub struct Offer { - pub buyer: AccountId, - pub sender: AccountId, - pub contracts: Vec, - pub amount: Balance, - pub expired: Moment, - pub state: OfferState, -} - -pub type BalanceOf = - <::Currency as Currency<::AccountId>>::Balance; -pub type OfferOf = Offer< - ::AccountId, - BalanceOf, - ::BlockNumber, ->; - -const TRADING_ID: LockIdentifier = *b"trading_"; - -/// The module's configuration trait. -pub trait Trait: frame_system::Trait { - // use amount of values. - type Currency: LockableCurrency; - /// The helper of checking the state of operators. - type OperatorFinder: OperatorFinder; - /// The helper of transfering operator's authorities. - type TransferOperator: TransferOperator; - /// The overarching event type. - type Event: From> + Into<::Event>; -} - -decl_storage! { - trait Store for Module as Operator { - /// A mapping from the offering account id to Offer - pub Offers: map hasher(blake2_128_concat) T::AccountId => Option>; - } -} - -decl_module! { - /// The module declaration. - pub struct Module for enum Call where origin: T::Origin { - // Initializing events - // this is needed only if you are using events in your module - fn deposit_event() = default; - - /// Offer is an easy contract to trade. - /// If the sender `accept` during the period, the operator trading will be completed. - /// After the offer, the part of the amount of the buyer's balances will lock. - /// - /// Note: Only one offer can be issued at the same time each an account. - /// TODO: weight - #[weight = 500_000] - pub fn offer(origin, sender: T::AccountId, contracts: Vec, amount: BalanceOf, expired: T::BlockNumber) { - let buyer = ensure_signed(origin)?; - let offer_account = buyer.clone(); - let sender_account = sender.clone(); - - if T::Currency::free_balance(&buyer) <= amount { - Err("buyer does not have enough balances.")? - } - // check that the operator has contracts. - let has_contracts = T::OperatorFinder::contracts(&sender); - if !contracts.iter().all(|v| { - has_contracts.contains(&v) - }) { - Err("sender does not have these contracts.")? - } - - let offer = OfferOf:: { - buyer, - sender, - contracts, - amount, - expired, - state: OfferState::Waiting, - }; - - if let Some(current_offer) = >::get(&offer_account) { - if current_offer.state == OfferState::Waiting { - Err("this offer was already issued.")? - } - } - - // lock amount - T::Currency::set_lock( - TRADING_ID, &offer.buyer, offer.amount, - WithdrawReasons::all(), - ); - // insert new a offer. - >::insert(&offer_account, offer); - Self::deposit_event(RawEvent::Offer(offer_account, sender_account)); - } - - /// Reject the target offer. - /// the offer's buyer or sender can reject the offer. - /// After the reject, the buyer's balances will be unlock. - /// TODO: weight - #[weight = 100_000] - pub fn reject(origin, offer_id: T::AccountId) { - let rejector = ensure_signed(origin)?; - let mut offer = match >::get(&offer_id) { - Some(o) => o, - None => Err("can not find the offer id.")? - }; - if rejector != offer.sender && rejector != offer.buyer { - Err("the rejector can not reject. only sender or buyer can reject.")?; - } - if offer.state == OfferState::Accept { - Err("the offer was already accepted.")?; - } - - offer.state = OfferState::Reject; - - // unlock amount - T::Currency::remove_lock(TRADING_ID, &offer.buyer); - // insert changing offer - >::insert(&offer_id, offer); - Self::deposit_event(RawEvent::Reject(rejector, offer_id)); - } - - /// Accept the target offer. - /// Only the offer's sender can accept the offer. - /// After the accept: - /// 1. the buyer's balances will be unlock. - /// 2. the buyer's balances tranfer to the sender. - /// 3. the sender's target contracts transfer to the buyer. - /// TODO: weight - #[weight = 500_000] - pub fn accept(origin, offer_id: T::AccountId) { - let acceptor = ensure_signed(origin)?; - let mut offer = match >::get(&offer_id) { - Some(o) => o, - None => Err("can not find the offer id.")? - }; - if acceptor != offer.sender { - Err("the accept can not accept. only sender can accept.")?; - } - if >::block_number() >= offer.expired { - Err("the offer was already expired.")?; - } - - - // check change operator's contracts - T::TransferOperator::verify_transfer_operator(&offer.sender, &offer.contracts)?; - - // unlock amount - T::Currency::remove_lock(TRADING_ID, &offer.buyer); - // transfer amount - T::Currency::transfer(&offer.buyer, &offer.sender, offer.amount, ExistenceRequirement::KeepAlive)?; - - // change operator's contracts - T::TransferOperator::force_transfer_operator(offer.sender.clone(), offer.contracts.clone(), offer.buyer.clone()); - - // insert changing offer - offer.state = OfferState::Accept; - >::insert(&offer_id, offer); - Self::deposit_event(RawEvent::Accept(acceptor, offer_id)); - } - - /// Remove the offer. - /// The offer's owner can remove the offer. - /// But, if the offer is living(until expired), he can not remove the offer. - /// TODO: weight - #[weight = 100_000] - pub fn remove(origin) { - let remover = ensure_signed(origin)?; - let offer = match >::get(&remover) { - Some(o) => o, - None => Err("the remover does not have a offer.")? - }; - if offer.state == OfferState::Waiting && offer.expired > >::block_number() { - Err("the offer is living.")? - } - // unlock amount - T::Currency::remove_lock(TRADING_ID, &offer.buyer); - // remove the offer - >::remove(&remover); - Self::deposit_event(RawEvent::Remove(remover)); - } - } -} - -decl_event!( - pub enum Event - where - AccountId = ::AccountId, - { - /// When call offer, - /// it is issued arguments: - /// 1: New Operator(buyer) - /// 2: Current Operator(sender) - Offer(AccountId, AccountId), - - /// When call reject, - /// it is issued arguments: - /// 1: Rejector account id(current operator and sender) - /// 2: Offer account id - Reject(AccountId, AccountId), - - /// When call reject, - /// it is issued arguments: - /// 1: Acceptor account id(current operator and sender) - /// 2: Offer account id - Accept(AccountId, AccountId), - - /// When call remove, - /// it is issued arguments: - /// 1: the remover - Remove(AccountId), - } -); diff --git a/frame/trading/src/tests.rs b/frame/trading/src/tests.rs deleted file mode 100644 index dc22e808a6..0000000000 --- a/frame/trading/src/tests.rs +++ /dev/null @@ -1,514 +0,0 @@ -use super::*; -use frame_support::{ - assert_err, assert_ok, impl_outer_event, impl_outer_origin, parameter_types, StorageMap, -}; -use frame_system::{self as system, EventRecord, Phase}; -use pallet_balances::{self as balances, Reasons}; -use sp_runtime::{ - testing::{Header, H256}, - traits::{BlakeTwo256, IdentityLookup}, - Perbill, -}; -use sp_std::marker::PhantomData; - -mod trading { - // Re-export contents of the root. This basically - // needs to give a name for the current crate. - // This hack is required for `impl_outer_event!`. - pub use super::super::*; -} -impl_outer_event! { - pub enum MetaEvent for Test { - system, balances, trading, - } -} -impl_outer_origin! { - pub enum Origin for Test { } -} - -pub type AccountId = u64; - -#[derive(Clone, Eq, PartialEq, Debug)] -pub struct Test; -parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: u32 = 1024; - pub const MaximumBlockLength: u32 = 2 * 1024; - pub const AvailableBlockRatio: Perbill = Perbill::one(); -} -impl frame_system::Trait for Test { - type Origin = Origin; - type BaseCallFilter = (); - type Index = u64; - type BlockNumber = u64; - type Hash = H256; - type Call = (); - type Hashing = BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; - type Header = Header; - type Event = MetaEvent; - type BlockHashCount = BlockHashCount; - type MaximumBlockWeight = MaximumBlockWeight; - type AvailableBlockRatio = AvailableBlockRatio; - type MaximumBlockLength = MaximumBlockLength; - type Version = (); - type PalletInfo = (); - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = (); - type SystemWeightInfo = (); -} -parameter_types! { - pub const ExistentialDeposit: u64 = 1; // Should be greather than zero -} -impl pallet_balances::Trait for Test { - type Balance = u64; - type Event = MetaEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Module; - type WeightInfo = (); - type MaxLocks = (); -} -parameter_types! { - pub const MinimumPeriod: u64 = 1; -} -impl pallet_timestamp::Trait for Test { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); -} - -/// define mock operator trait -pub trait MockOperatorTrait: frame_system::Trait {} -decl_storage! { - trait Store for MockOperatorModule as MockOperator { - /// A mapping from operators to operated contracts by them. - pub OperatorHasContracts: map hasher(blake2_128_concat) T::AccountId => Vec; - } -} -pub struct MockOperatorModule(PhantomData); -impl OperatorFinder for MockOperatorModule { - fn contracts(operator_id: &T::AccountId) -> Vec { - >::get(operator_id) - } -} -impl TransferOperator for MockOperatorModule { - /// Force Changes an operator for identified contracts without verify. - fn force_transfer_operator( - current_operator: T::AccountId, - contracts: Vec, - new_operator: T::AccountId, - ) { - // remove origin operator to contracts - >::mutate(¤t_operator, |tree| { - *tree = tree - .iter() - .filter(|&x| !contracts.contains(x)) - .cloned() - .collect() - }); - - // add new_operator to contracts - >::mutate(&new_operator, |tree| { - for c in contracts.iter() { - (*tree).push(c.clone()); - } - }); - } -} - -impl MockOperatorTrait for Test {} - -impl Trait for Test { - type Currency = Balances; - type OperatorFinder = MockOperatorModule; - /// The helper of transfering operator's authorities. - type TransferOperator = MockOperatorModule; - type Event = MetaEvent; -} - -struct ExtBuilder; -impl ExtBuilder { - pub fn build() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); - pallet_balances::GenesisConfig:: { - balances: vec![(ALICE, 1000), (BOB, 1000), (CHARLIE, 1000), (DAVE, 1000)], - } - .assimilate_storage(&mut t) - .unwrap(); - sp_io::TestExternalities::new(t) - } -} - -type System = frame_system::Module; -type Balances = pallet_balances::Module; -type Timestamp = pallet_timestamp::Module; -type Trading = Module; - -// operators -pub const ALICE: u64 = 1; -pub const BOB: u64 = 2; -pub const CHARLIE: u64 = 3; -pub const DAVE: u64 = 4; - -// contracts -pub const ANT: u64 = 11; -pub const BLUE: u64 = 12; -pub const CUT: u64 = 13; -pub const DEEN: u64 = 14; - -pub const PER_SESSION: u64 = 10; - -fn initialize_operator_storage_settings() { - for (x, y) in vec![ - (ALICE, vec![ANT, BLUE, CUT]), - (BOB, vec![DEEN]), - (CHARLIE, vec![]), - (DAVE, vec![]), - ] { - >::insert(&x, y); - } -} - -fn advance_session() { - let now = System::block_number(); - System::initialize( - &(now + 1), - &[0u8; 32].into(), - &[0u8; 32].into(), - &Default::default(), - frame_system::InitKind::Full, - ); - // increase timestamp + 10 - let now_time = Timestamp::get(); - Timestamp::set_timestamp(now_time + PER_SESSION); -} - -#[test] -fn correct_offer_test() { - ExtBuilder::build().execute_with(|| { - initialize_operator_storage_settings(); - advance_session(); - correct_offer(CHARLIE, ALICE, vec![ANT, BLUE], 800, 2); - }) -} - -#[test] -fn offer_error_test() { - ExtBuilder::build().execute_with(|| { - initialize_operator_storage_settings(); - advance_session(); - - assert_err!( - Trading::offer(Origin::signed(CHARLIE), ALICE, vec![CUT, DEEN], 800, 20), - "sender does not have these contracts.", - ); - assert_err!( - Trading::offer(Origin::signed(BOB), ALICE, vec![CUT, DEEN], 1000, 20), - "buyer does not have enough balances.", - ); - - correct_offer(CHARLIE, ALICE, vec![ANT, BLUE], 800, 2); - - advance_session(); - - assert_err!( - Trading::offer(Origin::signed(CHARLIE), ALICE, vec![ANT, BLUE], 800, 20), - "this offer was already issued.", - ); - }) -} - -fn correct_offer( - buyer: AccountId, - sender: AccountId, - contracts: Vec, - amount: u64, - expired: u64, -) { - assert_ok!(Trading::offer( - Origin::signed(buyer), - sender, - contracts.clone(), - amount, - expired, - )); - let offer = OfferOf:: { - buyer, - sender, - contracts, - amount, - expired, - state: OfferState::Waiting, - }; - assert_eq!( - System::events(), - vec![EventRecord { - phase: Phase::Initialization, - event: MetaEvent::trading(RawEvent::Offer(buyer, sender)), - topics: vec![], - },] - ); - assert_eq!(Some(offer.clone()), >::get(&buyer)); - // Locking buyer test - assert_eq!( - vec![pallet_balances::BalanceLock { - id: TRADING_ID, - amount: amount, - reasons: Reasons::from(WithdrawReasons::all()), - }], - Balances::locks(&buyer) - ) -} - -#[test] -fn offer_and_reject_test() { - ExtBuilder::build().execute_with(|| { - initialize_operator_storage_settings(); - - advance_session(); - - correct_offer(CHARLIE, ALICE, vec![ANT, BLUE], 800, 2); - - advance_session(); - - correct_reject(CHARLIE, CHARLIE); - - advance_session(); - - correct_offer(CHARLIE, ALICE, vec![ANT, BLUE], 500, 4); - - advance_session(); - - correct_reject(ALICE, CHARLIE); - }) -} - -fn correct_reject(rejector: AccountId, offer_id: AccountId) { - let offer = >::get(&offer_id).unwrap(); - let contracts = MockOperatorModule::::contracts(&offer.sender); - assert_ok!(Trading::reject(Origin::signed(rejector), offer_id)); - assert_eq!( - System::events(), - vec![EventRecord { - phase: Phase::Initialization, - event: MetaEvent::trading(RawEvent::Reject(rejector, offer_id.clone())), - topics: vec![], - },] - ); - let mut reject_offer = offer.clone(); - reject_offer.state = OfferState::Reject; - // equal reject. - assert_eq!(Some(reject_offer), >::get(&offer_id)); - // not changed. - assert_eq!(MockOperatorModule::::contracts(&ALICE), contracts); - // Unlocking buyer test - assert_eq!( - Vec::>::new(), - Balances::locks(&offer_id) - ) -} - -#[test] -fn reject_error_test() { - ExtBuilder::build().execute_with(|| { - initialize_operator_storage_settings(); - - advance_session(); - - correct_offer(CHARLIE, ALICE, vec![ANT, BLUE], 800, 5); - - advance_session(); - - assert_err!( - Trading::reject(Origin::signed(CHARLIE), BOB), - "can not find the offer id." - ); - assert_err!( - Trading::reject(Origin::signed(BOB), CHARLIE), - "the rejector can not reject. only sender or buyer can reject." - ); - - correct_accept(ALICE, CHARLIE); - - assert_err!( - Trading::reject(Origin::signed(ALICE), CHARLIE), - "the offer was already accepted." - ); - }) -} - -#[test] -fn offer_and_accept_test() { - ExtBuilder::build().execute_with(|| { - initialize_operator_storage_settings(); - - advance_session(); - - correct_offer(CHARLIE, ALICE, vec![ANT, BLUE], 800, 10); - - advance_session(); - - correct_accept(ALICE, CHARLIE); - - advance_session(); - - correct_offer(BOB, CHARLIE, vec![ANT], 200, 10); - - advance_session(); - - correct_accept(CHARLIE, BOB); - }) -} - -fn correct_accept(acceptor: AccountId, offer_id: AccountId) { - let offer = >::get(&offer_id).unwrap(); - let buyer_contracts = MockOperatorModule::::contracts(&offer.buyer); - let sender_contracts = MockOperatorModule::::contracts(&offer.sender); - let buyer_balances = Balances::free_balance(&offer.buyer); - let sender_balances = Balances::free_balance(&offer.sender); - - assert_ok!(Trading::accept(Origin::signed(acceptor), offer_id)); - assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::balances(pallet_balances::RawEvent::Transfer( - offer.buyer, - offer.sender, - offer.amount, - )), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::trading(RawEvent::Accept(acceptor, offer_id.clone())), - topics: vec![], - }, - ], - ); - - let mut accept_offer = offer.clone(); - accept_offer.state = OfferState::Accept; - // equal reject. - assert_eq!(Some(accept_offer), >::get(&offer_id)); - // Changed!. sender contracts - let sender_new_contracts: Vec = sender_contracts - .iter() - .filter(|c| !offer.contracts.contains(*c)) - .cloned() - .collect(); - assert_eq!( - MockOperatorModule::::contracts(&offer.sender), - sender_new_contracts - ); - // Changed!. buyer contracts. - let buyer_new_contracts: Vec = buyer_contracts - .iter() - .chain(offer.contracts.iter()) - .cloned() - .collect(); - assert_eq!( - MockOperatorModule::::contracts(&offer.buyer), - buyer_new_contracts - ); - // Check transfered bueyr -> sende: amount - assert_eq!( - buyer_balances - offer.amount, - Balances::free_balance(&offer.buyer) - ); - assert_eq!( - sender_balances + offer.amount, - Balances::free_balance(&offer.sender) - ); - // Unlocking buyer test - assert_eq!( - Vec::>::new(), - Balances::locks(&offer.buyer) - ) -} - -#[test] -fn accept_error_test() { - ExtBuilder::build().execute_with(|| { - initialize_operator_storage_settings(); - - advance_session(); - - correct_offer(CHARLIE, ALICE, vec![ANT, BLUE], 800, 3); - - advance_session(); - - assert_err!( - Trading::accept(Origin::signed(CHARLIE), BOB), - "can not find the offer id." - ); - assert_err!( - Trading::accept(Origin::signed(BOB), CHARLIE), - "the accept can not accept. only sender can accept." - ); - - advance_session(); - - advance_session(); - - assert_err!( - Trading::accept(Origin::signed(ALICE), CHARLIE), - "the offer was already expired." - ) - }) -} - -#[test] -fn remove_test() { - ExtBuilder::build().execute_with(|| { - initialize_operator_storage_settings(); - - advance_session(); - - correct_offer(CHARLIE, ALICE, vec![ANT, BLUE], 800, 4); - - advance_session(); - - assert_err!( - Trading::remove(Origin::signed(CHARLIE)), - "the offer is living." - ); - assert_err!( - Trading::remove(Origin::signed(ALICE)), - "the remover does not have a offer." - ); - - advance_session(); - advance_session(); - - correct_remove(CHARLIE); - }) -} - -fn correct_remove(remover: AccountId) { - assert_ok!(Trading::remove(Origin::signed(remover))); - assert_eq!( - System::events(), - vec![EventRecord { - phase: Phase::Initialization, - event: MetaEvent::trading(RawEvent::Remove(remover)), - topics: vec![], - },] - ); - // Unlocking buyer test - assert_eq!( - Vec::>::new(), - Balances::locks(&remover) - ) -} diff --git a/ovmi/cli/Cargo.toml b/ovmi/cli/Cargo.toml deleted file mode 100644 index 7c5d1a4e14..0000000000 --- a/ovmi/cli/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "ovmi-cli" -version = "0.1.0" -authors = ["Stake Technologies "] -edition = "2018" -description = "Optimistic virtual machine innterpreter in Rust." - -[[bin]] -name = "ovmi-cli" -path = "src/main.rs" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -ovmi = { path = "../lib", default_features = false } -serde_json = "1.0" - -[features] -default = ["std"] -std = [ - 'ovmi/std', -] diff --git a/ovmi/cli/src/main.rs b/ovmi/cli/src/main.rs deleted file mode 100644 index e5c9de2216..0000000000 --- a/ovmi/cli/src/main.rs +++ /dev/null @@ -1,9 +0,0 @@ -use ovmi; - -fn main() { - let compiled_predicate = match ovmi::compile_from_json("{}") { - Ok(res) => res, - Err(err) => panic!(err), - }; - println!("{:?}", compiled_predicate); -} diff --git a/ovmi/lib/Cargo.toml b/ovmi/lib/Cargo.toml deleted file mode 100644 index 8cb69555e7..0000000000 --- a/ovmi/lib/Cargo.toml +++ /dev/null @@ -1,33 +0,0 @@ -[package] -name = "ovmi" -version = "0.1.0" -authors = ["Stake Technologies "] -edition = "2018" -license = "Apache-2.0" -homepage = "https://docs.plasmnet.io/" -repository = "https://github.com/staketechnologies/Plasm/" -description = "Optimstic virtual machine interperter" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -serde = { version = "1.0", optional = true, features = ["derive"] } -codec = { package = "parity-scale-codec", version = "1.2.0", features = ['derive'], default-features = false } -serde_json = "1.0" -hash-db = { version = "0.15", default-features = false } - -[dev-dependencies] -primitive-types = { version = "0.7" } -sp-runtime = "2.0.0" -sp-core = "2.0.0" -hex = "0.4" -hex-literal = "0.2.1" -lazy_static = "1.4.0" - -[features] -default = ["std"] -std = [ - 'serde', - 'codec/std', - 'hash-db/std', -] diff --git a/ovmi/lib/src/compiled_predicates.rs b/ovmi/lib/src/compiled_predicates.rs deleted file mode 100644 index 29250afc96..0000000000 --- a/ovmi/lib/src/compiled_predicates.rs +++ /dev/null @@ -1,385 +0,0 @@ -use super::*; -use codec::{Decode, Encode}; - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum PredicateType { - CompiledPredicate, - IntermediateCompiledPredicate, - AtomicProposition, - AtomicPredicateCall, - InputPredicateCall, - VariablePredicateCall, - CompiledPredicateCall, - CompiledInput, - ConstantInput, - LabelInput, - NormalInput, - VariableInput, - SelfInput, -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum VarType { - Address, - Bytes, -} - -/// Compiled Property definition -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct CompiledPredicate { - pub r#type: PredicateType, - pub name: Vec, - pub input_defs: Vec>, - pub contracts: Vec, - pub constants: Option>, - pub entry_point: Vec, -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct ConstantVariable { - pub var_type: VarType, - pub name: Vec, -} - -/// IntermediateCompiledPredicate is core of compilation which has only atomic propositions as its inputs. -/// When we have for a in B() {Foo(a) and Bar(a)}, -/// "for a in B() {...}" and "Foo(a) and Bar(a)" are IntermediateCompiledPredicate. -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct IntermediateCompiledPredicate { - pub r#type: PredicateType, - pub name: Vec, - pub original_predicate_name: Vec, - // logical connective - pub connective: LogicalConnective, - pub input_defs: Vec>, - pub inputs: Vec, - pub property_inputs: Vec, -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum AtomicPropositionOrPlaceholder { - AtomicProposition(AtomicProposition), - Placeholder(Vec), -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct AtomicProposition { - pub r#type: PredicateType, - pub predicate: PredicateCall, - pub inputs: Vec, - pub is_compiled: Option, -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum PredicateCall { - AtomicPredicateCall(AtomicPredicateCall), - InputPredicateCall(InputPredicateCall), - VariablePredicateCall(VariablePredicateCall), - CompiledPredicateCall(CompiledPredicateCall), -} - -/// e.g. IsValidSignature() -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct AtomicPredicateCall { - pub r#type: PredicateType, - pub source: Vec, -} - -/// e.g. a() of "def Foo(a) := a()" -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct InputPredicateCall { - pub r#type: PredicateType, - pub source: NormalInput, -} - -/// e.g. su() of "def Foo(a) := with SU(a) as su {su()}" -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct VariablePredicateCall { - pub r#type: PredicateType, -} - -/// For predicates dynamic linking -/// e.g. Confsig() user defined predicate -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct CompiledPredicateCall { - pub r#type: PredicateType, - pub source: Vec, -} - -/// CompiledInput indicates which value to pass to PredicateCall as input of predicate -/// For example,parent_property.inputs[0].inputs[1] is NormalInput andinput_index is 0 and children is [1]. -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum CompiledInput { - ConstantInput(ConstantInput), - LabelInput(LabelInput), - NormalInput(NormalInput), - VariableInput(VariableInput), - SelfInput(SelfInput), -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct ConstantInput { - pub r#type: PredicateType, - pub name: Vec, -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct LabelInput { - pub r#type: PredicateType, - pub label: Vec, -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct NormalInput { - pub r#type: PredicateType, - pub input_index: u8, - pub children: Vec, -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct VariableInput { - pub r#type: PredicateType, - pub placeholder: Vec, - pub children: Vec, -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct SelfInput { - pub r#type: PredicateType, - pub children: Vec, -} - -/// LogicalConnective -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum LogicalConnective { - And, - ForAllSuchThat, - Not, - Or, - ThereExistsSuchThat, -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::prepare::*; - use serde::{Deserialize, Serialize}; - macro_rules! serde_from_test { - ($name:ident, $t:ty, $s:ty, $pr:expr) => { - #[test] - fn $name() { - let res: $s = match serde_json::from_str($pr) { - Ok(res) => res, - Err(err) => { - println!( - "ERR: {:?}, {}, {}", - err.classify(), - err.line(), - err.column() - ); - assert!(false); - return; - } - }; - println!("success serde : {:?}", res); - let res: $t = res.into(); - println!("success encode: {:?}", res); - } - }; - } - - serde_from_test!( - logical_connective_test, - LogicalConnective, - LogicalConnectiveSerializable, - r#""ThereExistsSuchThat""# - ); - - serde_from_test!( - atomic_predicate_call_test, - AtomicPredicateCall, - AtomicPredicateCallSerializable, - r#"{ - "type": "AtomicPredicateCall", - "source": "IsValidSignature" - }"# - ); - - serde_from_test!( - normal_input_test, - NormalInput, - NormalInputSerializable, - r#"{ - "type": "NormalInput", - "inputIndex": 2, - "children": [] - }"# - ); - - serde_from_test!( - variable_input_test, - VariableInput, - VariableInputSerializable, - r#"{ - "type": "VariableInput", - "placeholder": "v0", - "children": [] - }"# - ); - - serde_from_test!( - constant_input_test, - ConstantInput, - ConstantInputSerializable, - r#"{ - "type": "ConstantInput", - "name": "secp256k1" - }"# - ); - - serde_from_test!( - atomic_proposition_test, - AtomicProposition, - AtomicPropositionSerializable, - r#"{ - "type": "AtomicProposition", - "predicate": { - "type": "AtomicPredicateCall", - "source": "IsValidSignature" - }, - "inputs": [ - { - "type": "NormalInput", - "inputIndex": 2, - "children": [] - }, - { - "type": "VariableInput", - "placeholder": "v0", - "children": [] - }, - { - "type": "NormalInput", - "inputIndex": 1, - "children": [] - }, - { - "type": "ConstantInput", - "name": "secp256k1" - } - ] - }"# - ); - - serde_from_test!( - intermediate_compiled_predicate_test, - IntermediateCompiledPredicate, - IntermediateCompiledPredicateSerializable, - r#" - { - "type": "IntermediateCompiledPredicate", - "originalPredicateName": "Ownership", - "name": "OwnershipT", - "connective": "ThereExistsSuchThat", - "inputDefs": [ - "OwnershipT", - "owner", - "tx" - ], - "inputs": [ - "signatures,KEY,${tx}", - "v0", - { - "type": "AtomicProposition", - "predicate": { - "type": "AtomicPredicateCall", - "source": "IsValidSignature" - }, - "inputs": [ - { - "type": "NormalInput", - "inputIndex": 2, - "children": [] - }, - { - "type": "VariableInput", - "placeholder": "v0", - "children": [] - }, - { - "type": "NormalInput", - "inputIndex": 1, - "children": [] - }, - { - "type": "ConstantInput", - "name": "secp256k1" - } - ] - } - ], - "propertyInputs": [] - }"# - ); - - serde_from_test!( - constant_variable_test, - ConstantVariable, - ConstantVariableSerializable, - r#" - { - "varType": "bytes", - "name": "secp256k1" - }"# - ); - - #[derive(Serialize, Deserialize, Debug)] - enum MessageSerializable { - Request { id: String, method: String }, - Response { id: String, result: u8 }, - } - - impl From for Message { - fn from(f: MessageSerializable) -> Message { - match f { - MessageSerializable::Request { id, method } => Message::Request { - id: id.as_bytes().to_vec(), - method: method.as_bytes().to_vec(), - }, - MessageSerializable::Response { id, result } => Message::Response { - id: id.as_bytes().to_vec(), - result, - }, - } - } - } - - #[derive(Debug)] - enum Message { - Request { id: Vec, method: Vec }, - Response { id: Vec, result: u8 }, - } - - const MES: &str = r#"{"Request": {"id": "...", "method": "..."}}"#; - - serde_from_test!(message_test, Message, MessageSerializable, MES); -} diff --git a/ovmi/lib/src/executor.rs b/ovmi/lib/src/executor.rs deleted file mode 100644 index eb1ec34565..0000000000 --- a/ovmi/lib/src/executor.rs +++ /dev/null @@ -1,496 +0,0 @@ -use super::*; -use crate::predicates::*; -use codec::Codec; -use core::fmt::Debug; -use core::marker::PhantomData; -pub use hash_db::Hasher; - -#[derive(PartialEq)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum ExecError
{ - Require { - msg: &'static str, - }, - CallMethod { - call_method: PredicateCallInputs
, - expected: &'static str, - }, - CallAddress { - address: Address, - }, - CodecError { - type_name: &'static str, - }, - ExternalError { - msg: &'static str, - }, - Unexpected { - msg: &'static str, - }, - /// Unimplemented error. - Unimplemented, -} - -impl
From<&'static str> for ExecError
{ - fn from(msg: &'static str) -> ExecError
{ - ExecError::
::ExternalError { msg } - } -} - -/// convert to error code from error tyoe. -pub fn codec_error
(expected_type_name: &'static str) -> ExecError
{ - ExecError::CodecError { - type_name: expected_type_name, - } -} - -/// Default ExecResult type bool. -pub type ExecResult
= core::result::Result>; -/// Generic ExecResult type. -pub type ExecResultT = core::result::Result>; -/// Generic ExecResult tyoe from Ext. -pub type ExecResultTOf = core::result::Result>>; -/// Address type from external. -pub type AddressOf = ::Address; -/// Hash type from external. -pub type HashOf = ::Hash; -/// Hashing type from external. -pub type HashingOf = ::Hashing; -/// Property type from external. -pub type PropertyOf = Property<::Address>; - -/// Maybe Address defines the traits should be implemented. -pub trait MaybeAddress: Codec + Debug + Clone + Eq + PartialEq + Default {} -impl MaybeAddress for T {} - -pub trait MaybeHash: - AsRef<[u8]> - + AsMut<[u8]> - + Default - + Codec - + Debug - + core::hash::Hash - + Send - + Sync - + Clone - + Copy - + Eq - + PartialEq - + Ord -{ -} -impl< - T: AsRef<[u8]> - + AsMut<[u8]> - + Default - + Codec - + Debug - + core::hash::Hash - + Send - + Sync - + Clone - + Copy - + Eq - + PartialEq - + Ord, - > MaybeHash for T -{ -} - -pub const NOT_VARIABLE: &'static [u8] = b"Not"; -pub const AND_VARIABLE: &'static [u8] = b"And"; -pub const OR_VARIABLE: &'static [u8] = b"Or"; -pub const FOR_ALL_VARIABLE: &'static [u8] = b"ForAllSuchThat"; -pub const THERE_EXISTS_VARIABLE: &'static [u8] = b"ThereExistsSuchThat"; -pub const EQUAL_VARIABLE: &'static [u8] = b"Equal"; -pub const IS_CONTAINED_VARIABLE: &'static [u8] = b"IsContained"; -pub const IS_LESS_VARIABLE: &'static [u8] = b"IsLessThan"; -pub const IS_STORED_VARIABLE: &'static [u8] = b"IsStored"; -pub const IS_VALID_SIGNATURE_VARIABLE: &'static [u8] = b"IsValidSignature"; -pub const VERIFY_INCLUSION_VARIABLE: &'static [u8] = b"VerifyInclusion"; - -pub trait ExternalCall { - /// The address type of Plasma child chain (default: AccountId32) - type Address: MaybeAddress; - /// The hash type of Plasma child chain (default: H256) - type Hash: MaybeHash; - /// The hashing type of Plasma child chain (default: Keccak256) - type Hashing: Hasher; - - // relation const any atomic predicate address. - /// The address of not predicate address. - fn not_address() -> Self::Address; - /// The address of and predicate address. - fn and_address() -> Self::Address; - /// The address of or predicate address. - fn or_address() -> Self::Address; - /// The address of for all predicate address. - fn for_all_address() -> Self::Address; - /// The address of there exists predicate address. - fn there_exists_address() -> Self::Address; - /// The address of equal predicate address. - fn equal_address() -> Self::Address; - /// The address of is contained predicate address. - fn is_contained_address() -> Self::Address; - /// The address of is less than predicate address. - fn is_less_address() -> Self::Address; - /// The address of is stored predicate address. - fn is_stored_address() -> Self::Address; - /// The address of is valid signature predicate address. - fn is_valid_signature_address() -> Self::Address; - /// The address of verify inclusion predicate address. - fn verify_inclusion_address() -> Self::Address; - - fn vec_to_address(key: &Vec) -> Option { - match key { - x if x.as_slice() == NOT_VARIABLE => Some(Self::not_address()), - x if x.as_slice() == AND_VARIABLE => Some(Self::and_address()), - x if x.as_slice() == OR_VARIABLE => Some(Self::or_address()), - x if x.as_slice() == FOR_ALL_VARIABLE => Some(Self::for_all_address()), - x if x.as_slice() == THERE_EXISTS_VARIABLE => Some(Self::there_exists_address()), - x if x.as_slice() == EQUAL_VARIABLE => Some(Self::equal_address()), - x if x.as_slice() == IS_CONTAINED_VARIABLE => Some(Self::is_contained_address()), - x if x.as_slice() == IS_LESS_VARIABLE => Some(Self::is_less_address()), - x if x.as_slice() == IS_STORED_VARIABLE => Some(Self::is_stored_address()), - x if x.as_slice() == IS_VALID_SIGNATURE_VARIABLE => { - Some(Self::is_valid_signature_address()) - } - x if x.as_slice() == VERIFY_INCLUSION_VARIABLE => { - Some(Self::verify_inclusion_address()) - } - _ => None, - } - } - - /// relation const any signature algorithm. - fn secp256k1() -> Self::Hash; - - /// Produce the hash of some codec-encodable value. - fn hash_of(s: &S) -> Self::Hash { - Encode::using_encoded(s, Self::Hashing::hash) - } - - /// Call (other predicate) into the specified account. - fn ext_call( - &self, - to: &Self::Address, - input_data: PredicateCallInputs, - ) -> ExecResultT, Self::Address>; - - /// Returns a reference to the account id of the caller. - fn ext_caller(&self) -> Self::Address; - - /// Returns a reference to the account id of the current contract. - fn ext_address(&self) -> Self::Address; - - /// Notes a call other storage. - /// Only return true or false. - /// CommitmentAddress(special) isCommitment(address) -> Commitment - /// is_stored_predicate(&self, address, key, value);? - /// ref: https://github.com/cryptoeconomicslab/ovm-contracts/blob/master/contracts/Predicate/Atomic/IsStoredPredicate.sol - fn ext_is_stored(&self, address: &Self::Address, key: &[u8], value: &[u8]) -> bool; - - /// Verify messagge hash with signature and address. - /// Should be used by ECDSA. - fn ext_verify(&self, hash: &Self::Hash, signature: &[u8], address: &Self::Address) -> bool; - - /// verifyInclusionWithRoot method verifies inclusion proof in Double Layer Tree. - /// Must be used by kind of Commitment contract by Plasma module. - fn ext_verify_inclusion_with_root( - &self, - leaf: Self::Hash, - token_address: Self::Address, - range: &[u8], - inclusion_proof: &[u8], - root: &[u8], - ) -> bool; - - /* Helpers of UniversalAdjudicationContract. */ - /// `is_decided` function of UniversalAdjudication in OVM module. - fn ext_is_decided(&self, property: &PropertyOf) -> bool; - /// `is_decided_by_id` function of UniversalAdjudication in OVM module. - fn ext_is_decided_by_id(&self, id: Self::Hash) -> bool; - /// `get_property_id` function of UniversalAdjudication in OVM module. - fn ext_get_property_id(&self, property: &PropertyOf) -> Self::Hash; - /// `set_predicate_decision` function of UniversalAdjudication in OVM module. - fn ext_set_predicate_decision( - &self, - game_id: Self::Hash, - decision: bool, - ) -> ExecResult; - - /* Helpers of UtilsContract. */ - /// @dev check target is variable or not. - /// A variable has prefix V and its length is less than 20. - fn is_placeholder(target: &Vec) -> bool { - return target.len() < 20 && target.get(0) == Some(&(b'V' as u8)); - } - - /// @dev check target is label or not. - /// A label has prefix L and its length is less than 20. - fn is_label(target: &Vec) -> bool { - return target.len() < 20 && target.get(0) == Some(&(b'L' as u8)); - } - - /// sub_bytes of [start_idnex, end_idnex). - fn sub_bytes(target: &Vec, start_index: u128, end_index: u128) -> Vec { - target - .as_slice() - .get((start_index as usize)..(end_index as usize)) - .unwrap_or(vec![].as_slice()) - .to_vec() - } - - /// sub array of [start_idnex, end_idnex). - fn sub_array(target: &Vec>, start_index: usize, end_index: usize) -> Vec> { - target - .as_slice() - .get((start_index)..(end_index)) - .unwrap_or(vec![].as_slice()) - .to_vec() - } - - /// sub_bytes of [1...). - fn get_input_value(target: &Vec) -> Vec { - Self::sub_bytes(target, 1, target.len() as u128) - } - - /// Decoded to u128 - fn bytes_to_u128(target: &Vec) -> ExecResultT { - Decode::decode(&mut &target[..]).map_err(|_| codec_error::("u128")) - } - - /// Decoded to range - fn bytes_to_range(target: &Vec) -> ExecResultT { - Decode::decode(&mut &target[..]).map_err(|_| codec_error::("Range")) - } - - /// Decoded to Address - fn bytes_to_address(target: &Vec) -> ExecResultT { - Decode::decode(&mut &target[..]).map_err(|_| codec_error::("Address")) - } - - /// Decoded to bool - fn bytes_to_bool(target: &Vec) -> ExecResultT { - Decode::decode(&mut &target[..]).map_err(|_| codec_error::("bool")) - } - - /// Decoded to Property - fn bytes_to_property(target: &Vec) -> ExecResultT, Self::Address> { - Decode::decode(&mut &target[..]) - .map_err(|_| codec_error::("PropertyOf")) - } - - /// Decoded to Vec> - fn bytes_to_bytes_array(target: &Vec) -> ExecResultT>, Self::Address> { - Decode::decode(&mut &target[..]).map_err(|_| codec_error::("Vec>")) - } - - fn prefix_label(source: &Vec) -> Vec { - Self::prefix(b'L', source) - } - - fn prefix_variable(source: &Vec) -> Vec { - Self::prefix(b'V', source) - } - - fn prefix(prefix: u8, source: &Vec) -> Vec { - vec![vec![prefix], source.clone()].concat() - } -} - -pub trait OvmExecutor

{ - type ExtCall: ExternalCall; - fn execute( - executable: P, - call_method: PredicateCallInputs>, - ) -> ExecResultT, AddressOf>; -} - -pub struct AtomicExecutor { - _phantom: PhantomData<(P, Ext)>, -} - -impl OvmExecutor

for AtomicExecutor -where - P: predicates::AtomicPredicateInterface>, - Ext: ExternalCall, -{ - type ExtCall = Ext; - fn execute( - predicate: P, - call_method: PredicateCallInputs>, - ) -> ExecResultT, Ext::Address> { - match call_method { - PredicateCallInputs::AtomicPredicate(atomic) => { - match atomic { - AtomicPredicateCallInputs::Decide { inputs } => { - return Ok(predicate.decide(inputs)?.encode()); - } - AtomicPredicateCallInputs::DecideTrue { inputs } => { - predicate.decide_true(inputs)?; - return Ok(true.encode()); - } - }; - } - other => Err(ExecError::CallMethod { - call_method: other, - expected: "AtomicPredicateCallInputs", - }), - } - } -} - -pub struct BaseAtomicExecutor { - _phantom: PhantomData<(P, Ext)>, -} - -impl OvmExecutor

for BaseAtomicExecutor -where - P: predicates::BaseAtomicPredicateInterface>, - Ext: ExternalCall, -{ - type ExtCall = Ext; - fn execute( - predicate: P, - call_method: PredicateCallInputs>, - ) -> ExecResultT, Ext::Address> { - match call_method { - PredicateCallInputs::BaseAtomicPredicate(atomic) => { - match atomic { - BaseAtomicPredicateCallInputs::Decide { inputs } => { - return Ok(predicate.decide(inputs)?.encode()); - } - BaseAtomicPredicateCallInputs::DecideTrue { inputs } => { - predicate.decide_true(inputs)?; - return Ok(true.encode()); - } - BaseAtomicPredicateCallInputs::DecideWithWitness { inputs, witness } => { - return Ok(predicate.decide_with_witness(inputs, witness)?.encode()); - } - }; - } - other => Err(ExecError::CallMethod { - call_method: other, - expected: "BaseAtomicPredicateCallInputs", - }), - } - } -} - -pub struct LogicalConnectiveExecutor { - _phantom: PhantomData<(P, Ext)>, -} - -impl OvmExecutor

for LogicalConnectiveExecutor -where - P: predicates::LogicalConnectiveInterface>, - Ext: ExternalCall, -{ - type ExtCall = Ext; - fn execute( - predicate: P, - call_method: PredicateCallInputs>, - ) -> ExecResultT, Ext::Address> { - match call_method { - PredicateCallInputs::LogicalConnective(atomic) => { - match atomic { - LogicalConnectiveCallInputs::IsValidChallenge { - inputs, - challenge_inputs, - challenge, - } => { - return Ok(predicate - .is_valid_challenge(inputs, challenge_inputs, challenge)? - .encode()) - } - }; - } - other => Err(ExecError::CallMethod { - call_method: other, - expected: "LogicalConnectiveCallInputs", - }), - } - } -} - -pub struct DecidableExecutor { - _phantom: PhantomData<(P, Ext)>, -} - -impl OvmExecutor

for DecidableExecutor -where - P: predicates::DecidablePredicateInterface>, - Ext: ExternalCall, -{ - type ExtCall = Ext; - fn execute( - predicate: P, - call_method: PredicateCallInputs>, - ) -> ExecResultT, Ext::Address> { - match call_method { - PredicateCallInputs::DecidablePredicate(atomic) => { - match atomic { - DecidablePredicateCallInputs::DecideWithWitness { inputs, witness } => { - return Ok(predicate.decide_with_witness(inputs, witness)?.encode()); - } - }; - } - other => Err(ExecError::CallMethod { - call_method: other, - expected: "DecidablePredicateCallInputs", - }), - } - } -} - -pub struct CompiledExecutor { - _phantom: PhantomData<(P, Ext)>, -} - -impl OvmExecutor

for CompiledExecutor -where - P: predicates::CompiledPredicateInterface>, - Ext: ExternalCall, -{ - type ExtCall = Ext; - fn execute( - predicate: P, - call_method: PredicateCallInputs>, - ) -> ExecResultT, Ext::Address> { - match call_method { - PredicateCallInputs::CompiledPredicate(atomic) => { - match atomic { - CompiledPredicateCallInputs::IsValidChallenge { - inputs, - challenge_inputs, - challenge, - } => { - return Ok(predicate - .is_valid_challenge(inputs, challenge_inputs, challenge)? - .encode()); - } - CompiledPredicateCallInputs::Decide { inputs, witness } => { - return Ok(predicate.decide(inputs, witness)?.encode()); - } - CompiledPredicateCallInputs::DecideTrue { inputs, witness } => { - return Ok(predicate.decide_true(inputs, witness)?.encode()); - } - CompiledPredicateCallInputs::DecideWithWitness { inputs, witness } => { - return Ok(predicate.decide_with_witness(inputs, witness)?.encode()); - } - CompiledPredicateCallInputs::GetChild { - inputs, - challenge_input, - } => { - return Ok(predicate.get_child(inputs, challenge_input)?.encode()); - } - }; - } - other => Err(ExecError::CallMethod { - call_method: other, - expected: "CompiledPredicateCallInputs", - }), - } - } -} diff --git a/ovmi/lib/src/lib.rs b/ovmi/lib/src/lib.rs deleted file mode 100644 index 766f52231e..0000000000 --- a/ovmi/lib/src/lib.rs +++ /dev/null @@ -1,150 +0,0 @@ -//! # ovmi -//! This library allows **Predicate** to be loaded in binary format and their functions invoked. -//! -//! # Introduction -//! Predicate is a DSL for resolving Layer 2 dispute logic, -//! and the Optimistic Virtual Machine gives simulated environment by Predicate. -//! -//! There are several types of Predicate, each of which has an interface that looks like this. -//! ## Atomic Predicate -//! - decideTrue -//! - decide -//! -//! ## CompiledPredicate -//! - payoutContractAddress -//! - isValidChallenge -//! - getChild -//! - decide -//! - decideTrue -//! - decideWithWitness -//! -//! ## DecidablePredicate -//! - decideWithWitness -//! -//! ## LogicalConnective -//! - isValidChallenge -//! -//! Each of these definitions can be imported and exported. -//! -//! OVM does not manage the state, but it can be called externally. -//! -//! # Loading and Validation -//! Before execution, a module must be validated. This process checks that the module is well-formed and makes only allowed operations. -//! -//! You can get the binary of predicate from json. -//! The json format is refer to: https://github.com/cryptoeconomicslab/wakkanay/blob/master/packages/ovm-transpiler/src/CompiledPredicate.ts -//! ```ignore -//! use ovmi::prepare; -//! let compiled_predicate = prepare::compile_from_json("").unwrap(); -//! let binary_predicate = compiled_predicate::encode(); -//! -//! if let Err(err) = prepare::validate(binary_predicate) { -//! panic!(err); -//! } -//! ``` -//! -//! # Set external environments and. -//! -//! ## Example) Compiled Predicate Execute -//! ```ignore -//! use ovmi::prepare; -//! -//! type AccountId = u64; -//! -//! // Setting External environment. -//! struct MockExternalCall{..}; -//! impl ExternalCall for MockExternalCall { -//! ... -//! } -//! -//! fn call_execute(inputs: Vec>, inputs: PredicateCallInputs) -> ExecResult { -//! let compiled_predicate = prepare::compile_from_json("").unwrap(); -//! let (payout, address_input, bytes_inputs) = prepare::parse_inputs(inputs); -//! let ext = MockExternalCall{..}; -//! let executable = prepare::executable_from_compiled( -//! &mut ext, -//! code: compiled_predicate, -//! payout, -//! address_inputs, -//! bytes_inputs, -//! ); -//! // execute and return value. -//! CompiledExecutor::execute(&executable, inputs) -//! } -//! ``` -//! -//! ## Example) Logical Connective Predicate Execute -//! ```ignore -//! use ovmi::prepare; -//! -//! type AccountId = u64; -//! -//! // Setting External environment. -//! struct MockExternalCall{..}; -//! impl ExternalCall for MockExternalCall { -//! ... -//! } -//! -//! fn call_execute(address: AccountId, inputs: PredicateCallInputs) -> ExecResult { -//! let ext = MockExternalCall{..}; -//! let executable = prepare::logical_connective_executable_from_address( -//! &mut ext, -//! address, -//! ); -//! // execute and return value. -//! LogicalConnectiveExecutor::execute(&executable, inputs) -//! } -//! ``` -#![cfg_attr(not(feature = "std"), no_std)] -#![macro_use] - -#[macro_export] -macro_rules! require { - ($val:expr) => { - if !($val) { - return Err(crate::executor::ExecError::Require { - msg: stringify!($val), - }); - } - }; -} - -#[macro_export] -macro_rules! require_with_message { - ($val:expr, $message:expr) => { - if !($val) { - return Err(crate::executor::ExecError::Require { msg: $message }); - } - }; -} - -#[macro_use] -pub extern crate alloc; -use alloc::{collections::btree_map::BTreeMap, vec::Vec}; - -pub mod compiled_predicates; -pub mod executor; -pub mod predicates; -pub mod prepare; -use codec::{Decode, Encode}; -pub use compiled_predicates::CompiledPredicate; -#[cfg(feature = "std")] -pub use prepare::compile_from_json; - -#[cfg(test)] -mod mock; -#[cfg(test)] -mod tests; - -/// An opaque 32-byte cryptographic identifier. -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Default, Encode, Decode)] -#[cfg_attr(feature = "std", derive(Hash))] -pub struct AccountId([u8; 32]); - -/// An opaque Range(u128, u128). -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Default, Encode, Decode)] -#[cfg_attr(feature = "std", derive(Hash))] -pub struct Range { - pub start: u128, - pub end: u128, -} diff --git a/ovmi/lib/src/mock.rs b/ovmi/lib/src/mock.rs deleted file mode 100644 index df2463443b..0000000000 --- a/ovmi/lib/src/mock.rs +++ /dev/null @@ -1,384 +0,0 @@ -use crate::executor::*; -use crate::predicates::*; -use crate::prepare::*; -use crate::*; -use alloc::collections::btree_map::BTreeMap; -pub use hex_literal::hex; -use lazy_static::lazy_static; - -use crate::prepare::{ - base_atomic_executable_from_address, deciable_executable_from_address, - executable_from_compiled, logical_connective_executable_from_address, -}; -use primitive_types::H256; -pub use sp_runtime::traits::Keccak256; - -pub use sp_core::{ - crypto::{AccountId32, Pair, UncheckedFrom}, - ecdsa::{Pair as ECDSAPair, Public, Signature}, -}; -use sp_runtime::{traits::IdentifyAccount, MultiSigner}; - -pub type Address = AccountId32; -pub type Hash = H256; - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -struct StoredPredicate { - pub code: CompiledPredicate, - pub payout: Address, - address_inputs: BTreeMap, - bytes_inputs: BTreeMap, -} - -pub struct MockExternalCall { - mock_stored: BTreeMap, Vec>>, - mock_predicate: BTreeMap, -} - -lazy_static! { - pub static ref PAY_OUT_CONTRACT_ADDRESS: Address = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000010000" - ]); - pub static ref CALLER_ADDRESS: Address = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000001" - ]); - pub static ref PREDICATE_X_ADDRESS: Address = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000002" - ]); -} - -lazy_static! { - pub static ref NOT_ADDRESS: Address = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000003" - ]); - pub static ref AND_ADDRESS: Address = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000004" - ]); - pub static ref OR_ADDRESS: Address = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000005" - ]); - pub static ref FOR_ALL_ADDRESS: Address = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000006" - ]); - pub static ref THERE_EXISTS_ADDRESS: Address = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000007" - ]); - pub static ref EQUAL_ADDRESS: Address = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000008" - ]); - pub static ref IS_CONTAINED_ADDRESS: Address = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000009" - ]); - pub static ref IS_LESS_ADDRESS: Address = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000010" - ]); - pub static ref IS_STORED_ADDRESS: Address = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000011" - ]); - pub static ref IS_VALID_SIGNATURE_ADDRESS: Address = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000012" - ]); - pub static ref VERIFY_INCLUAION_ADDRESS: Address = to_account_from_seed(&hex![ - "0000000000000000000000000000000000000000000000000000000000000013" - ]); - pub static ref SECP_256_K1: Hash = Hash::from(&hex![ - "d4fa99b1e08c4e5e6deb461846aa629344d95ff03ed04754c2053d54c756f439" - ]); -} - -pub const JSON: &str = r#" - { - "type": "CompiledPredicate", - "name": "Ownership", - "inputDefs": [ - "owner", - "tx" - ], - "contracts": [ - { - "type": "IntermediateCompiledPredicate", - "originalPredicateName": "Ownership", - "name": "OwnershipT", - "connective": "ThereExistsSuchThat", - "inputDefs": [ - "OwnershipT", - "owner", - "tx" - ], - "inputs": [ - "signatures,KEY,${tx}", - "v0", - { - "type": "AtomicProposition", - "predicate": { - "type": "AtomicPredicateCall", - "source": "IsValidSignature" - }, - "inputs": [ - { - "type": "NormalInput", - "inputIndex": 2, - "children": [] - }, - { - "type": "VariableInput", - "placeholder": "v0", - "children": [] - }, - { - "type": "NormalInput", - "inputIndex": 1, - "children": [] - }, - { - "type": "ConstantInput", - "name": "secp256k1" - } - ] - } - ], - "propertyInputs": [] - } - ], - "entryPoint": "OwnershipT", - "constants": [ - { - "varType": "bytes", - "name": "secp256k1" - } - ] - }"#; - -impl MockExternalCall { - pub fn init() -> Self { - MockExternalCall { - mock_stored: BTreeMap::new(), - mock_predicate: BTreeMap::new(), - } - } - - // test set stored. - pub fn set_stored(&mut self, address: &Address, key: &[u8], value: &[u8]) { - if !self.mock_stored.contains_key(&address) { - self.mock_stored.insert(address.clone(), BTreeMap::new()); - } - let mut s = self - .mock_stored - .get_mut(address) - .map(|s| s.clone()) - .unwrap(); - s.insert(key.to_vec(), value.to_vec()); - self.mock_stored.insert(address.clone(), s); - } - - // test deploy - pub fn deploy( - &mut self, - compiled_predicate: CompiledPredicate, - payout: Address, - address_inputs: BTreeMap, - bytes_inputs: BTreeMap, - ) -> Address { - let stored = StoredPredicate { - code: compiled_predicate, - payout, - address_inputs, - bytes_inputs, - }; - let hash = Self::hash_of(&stored); - let address: Address = UncheckedFrom::unchecked_from(hash); - self.mock_predicate.insert(address.clone(), stored); - address - } - - // test compiled_parts_from_address - pub fn compiled_parts_from_address( - _address: &Address, - ) -> ( - CompiledPredicate, - Address, - BTreeMap, - BTreeMap>, - ) { - let code = compile_from_json(JSON).unwrap(); - let payout = (*PAY_OUT_CONTRACT_ADDRESS).clone(); - let address_inputs = BTreeMap::new(); - let bytes_inputs = vec![(Hash::default(), vec![0 as u8, 1 as u8])] - .iter() - .map(|(a, b)| (a.clone(), b.clone())) - .collect(); - (code, payout, address_inputs, bytes_inputs) - } - - pub fn call_execute( - &self, - to: &Address, - input_data: PredicateCallInputs

, - ) -> ExecResultT, Address> { - println!("call_execute to: {:?}", to); - println!("call_execute input_data: {:?}", input_data); - match &input_data { - PredicateCallInputs::DecidablePredicate(_) => { - let p = - deciable_executable_from_address(self, to).ok_or(ExecError::CallAddress { - address: to.clone(), - })?; - DecidableExecutor::, Self>::execute(p, input_data) - } - PredicateCallInputs::LogicalConnective(_) => { - let p = logical_connective_executable_from_address(self, to).ok_or( - ExecError::CallAddress { - address: to.clone(), - }, - )?; - LogicalConnectiveExecutor::, Self>::execute( - p, input_data, - ) - } - PredicateCallInputs::AtomicPredicate(_) => { - let p = atomic_executable_from_address(self, to).ok_or(ExecError::CallAddress { - address: to.clone(), - })?; - AtomicExecutor::, Self>::execute(p, input_data) - } - PredicateCallInputs::BaseAtomicPredicate(_) => { - let p = base_atomic_executable_from_address(self, to).ok_or( - ExecError::CallAddress { - address: to.clone(), - }, - )?; - BaseAtomicExecutor::, Self>::execute(p, input_data) - } - PredicateCallInputs::CompiledPredicate(_) => { - let (cp, payout, address_inputs, bytes_inputs) = - Self::compiled_parts_from_address(to); - let p = executable_from_compiled(self, cp, payout, address_inputs, bytes_inputs); - CompiledExecutor::, Self>::execute(p, input_data) - } - } - } -} - -impl ExternalCall for MockExternalCall { - type Address = Address; - type Hash = Hash; - type Hashing = Keccak256; - - fn not_address() -> Self::Address { - (*NOT_ADDRESS).clone() - } - fn and_address() -> Self::Address { - (*AND_ADDRESS).clone() - } - fn or_address() -> Self::Address { - (*OR_ADDRESS).clone() - } - fn for_all_address() -> Self::Address { - (*FOR_ALL_ADDRESS).clone() - } - fn there_exists_address() -> Self::Address { - (*THERE_EXISTS_ADDRESS).clone() - } - fn equal_address() -> Self::Address { - (*EQUAL_ADDRESS).clone() - } - fn is_contained_address() -> Self::Address { - (*IS_CONTAINED_ADDRESS).clone() - } - fn is_less_address() -> Self::Address { - (*IS_LESS_ADDRESS).clone() - } - fn is_stored_address() -> Self::Address { - (*IS_STORED_ADDRESS).clone() - } - fn is_valid_signature_address() -> Self::Address { - (*IS_VALID_SIGNATURE_ADDRESS).clone() - } - fn verify_inclusion_address() -> Self::Address { - (*VERIFY_INCLUAION_ADDRESS).clone() - } - fn secp256k1() -> Self::Hash { - (*SECP_256_K1).clone() - } - - fn ext_call( - &self, - to: &Self::Address, - input_data: PredicateCallInputs, - ) -> ExecResultT, Address> { - self.call_execute(to, input_data) - } - - fn ext_caller(&self) -> Self::Address { - (*CALLER_ADDRESS).clone() - } - - fn ext_address(&self) -> Self::Address { - (*PREDICATE_X_ADDRESS).clone() - } - - fn ext_is_stored(&self, address: &Self::Address, key: &[u8], value: &[u8]) -> bool { - if let Some(s) = self.mock_stored.get(address) { - if let Some(res) = s.get(&key.to_vec()) { - return res == &value.to_vec(); - } - } - false - } - - fn ext_verify(&self, hash: &Self::Hash, signature: &[u8], address: &Self::Address) -> bool { - println!("ext_verify hash : {:?}", hash); - println!("ext_verify signature: {:?}", signature); - println!("ext_verify address : {:?}", address); - if signature.len() != 65 { - return false; - } - let sig: Signature = Signature::from_slice(signature); - println!("ext_verify after : {:?}", sig); - if let Some(public) = sig.recover(hash) { - println!( - "ext_verify public : {:?}", - &MultiSigner::from(public.clone()).into_account() - ); - return address == &MultiSigner::from(public).into_account(); - } - false - } - - fn ext_verify_inclusion_with_root( - &self, - _leaf: Self::Hash, - _token_address: Self::Address, - _range: &[u8], - _inclusion_proof: &[u8], - _root: &[u8], - ) -> bool { - true - } - - fn ext_is_decided(&self, _property: &PropertyOf) -> bool { - true - } - fn ext_is_decided_by_id(&self, _id: Self::Hash) -> bool { - true - } - fn ext_get_property_id(&self, property: &PropertyOf) -> Self::Hash { - Self::hash_of(property) - } - fn ext_set_predicate_decision( - &self, - _game_id: Self::Hash, - _decision: bool, - ) -> ExecResult { - Ok(true) - } -} - -pub fn to_account_from_seed(seed: &[u8; 32]) -> Address { - to_account(ECDSAPair::from_seed(&seed).public().as_ref()) -} - -pub fn to_account(full_public: &[u8]) -> Address { - let public = sp_core::ecdsa::Public::from_full(full_public).unwrap(); - MultiSigner::from(public).into_account() -} diff --git a/ovmi/lib/src/predicates/and.rs b/ovmi/lib/src/predicates/and.rs deleted file mode 100644 index 82ae1302a4..0000000000 --- a/ovmi/lib/src/predicates/and.rs +++ /dev/null @@ -1,60 +0,0 @@ -use crate::executor::*; -use crate::predicates::*; - -pub struct AndPredicate<'a, Ext: ExternalCall> { - pub ext: &'a Ext, -} - -impl AndPredicate<'_, Ext> { - fn create_property_from_input(&self, input: Vec>) -> Property> { - Property { - predicate_address: self.ext.ext_address(), - inputs: input, - } - } -} - -impl LogicalConnectiveInterface> for AndPredicate<'_, Ext> { - /// @dev Validates a child node of And property in game tree. - fn is_valid_challenge( - &self, - inputs: Vec>, - challenge_inputs: Vec>, - challenge: Property>, - ) -> ExecResult> { - // challenge_input is index of child property - require!((&challenge_inputs).len() > 0); - let index = Ext::bytes_to_u128(&challenge_inputs[0])? as usize; - - // challenge should be not(p[index]) - // require!(_challenge.predicateAddress == not_predicateAddress); - require!(challenge.predicate_address == Ext::not_address()); - - // require!(keccak256(_inputs[index]) == keccak256(_challenge.inputs[0])); - require!(inputs.len() > index); - require!(challenge.inputs.len() > 0); - require!(inputs[index as usize] == challenge.inputs[0]); - Ok(true) - } -} - -impl DecidablePredicateInterface> for AndPredicate<'_, Ext> { - /// @dev Can decide true when all child properties are decided true - fn decide_with_witness( - &self, - inputs: Vec>, - _witness: Vec>, - ) -> ExecResult> { - for input in inputs.iter() { - let property: PropertyOf = Ext::bytes_to_property(input)?; - require_with_message!( - self.ext.ext_is_decided(&property), - "This property isn't true" - ); - } - let property = self.create_property_from_input(inputs); - let property_id = self.ext.ext_get_property_id(&property); - self.ext.ext_set_predicate_decision(property_id, true)?; - Ok(false) - } -} diff --git a/ovmi/lib/src/predicates/equal.rs b/ovmi/lib/src/predicates/equal.rs deleted file mode 100644 index 08e87390de..0000000000 --- a/ovmi/lib/src/predicates/equal.rs +++ /dev/null @@ -1,43 +0,0 @@ -use crate::executor::*; -use crate::predicates::*; - -pub struct EqualPredicate<'a, Ext: ExternalCall> { - pub ext: &'a Ext, -} - -impl AtomicPredicateInterface> for EqualPredicate<'_, Ext> { - fn decide(&self, inputs: Vec>) -> ExecResult> { - require!(inputs.len() > 1); - require_with_message!(inputs[0] == inputs[1], "2 inputs must be equal"); - Ok(true) - } -} - -impl AtomicHelperInterface> for EqualPredicate<'_, Ext> { - type Hash = HashOf; - fn ext_address(&self) -> AddressOf { - self.ext.ext_address() - } - fn ext_set_predicate_decision( - &self, - game_id: Self::Hash, - decision: bool, - ) -> ExecResult> { - self.ext.ext_set_predicate_decision(game_id, decision) - } - fn ext_get_property_id(&self, property: &Property>) -> Self::Hash { - self.ext.ext_get_property_id(property) - } -} - -impl DecidablePredicateInterface> for EqualPredicate<'_, Ext> { - fn decide_with_witness( - &self, - inputs: Vec>, - _witness: Vec>, - ) -> ExecResult> { - Self::decide(self, inputs) - } -} - -impl BaseAtomicPredicateInterface> for EqualPredicate<'_, Ext> {} diff --git a/ovmi/lib/src/predicates/executable.rs b/ovmi/lib/src/predicates/executable.rs deleted file mode 100644 index 77f60a5a6c..0000000000 --- a/ovmi/lib/src/predicates/executable.rs +++ /dev/null @@ -1,869 +0,0 @@ -//! Compiled Executable is simulated CompiledPredicate. -//! This simulate refer to https://github.com/cryptoeconomicslab/gazelle/tree/master/packages/ovm-solidity-generator/src. - -use crate::compiled_predicates::*; -use crate::executor::*; -use crate::predicates::*; -use crate::*; - -// Compiled Predicate transpiles to this structure. -pub struct CompiledExecutable<'a, Ext: ExternalCall> { - pub ext: &'a Ext, - pub payout: AddressOf, - pub code: CompiledPredicate, - pub constants: BTreeMap, VarType>, - pub address_inputs: BTreeMap, AddressOf>, - pub bytes_inputs: BTreeMap, Vec>, -} - -impl CompiledPredicateInterface> for CompiledExecutable<'_, Ext> { - fn payout_contract_address(&self) -> AddressOf { - self.payout.clone() - } - - /// @dev Validates a child node of the property in game tree. - fn is_valid_challenge( - &self, - inputs: Vec>, - challenge_inputs: Vec>, - challenge: Property>, - ) -> ExecResult> { - require_with_message!( - Ext::hash_of(&self.get_child(inputs, challenge_inputs)?) == Ext::hash_of(&challenge), - "_challenge must be valud child of game tree" - ); - Ok(true) - } - - /// @dev get valid child property of game tree with challenge_inputs - fn get_child( - &self, - inputs: Vec>, - challenge_input: Vec>, - ) -> ExecResultTOf>, Ext> { - require!(inputs.len() > 1); - if Ext::is_label(&inputs[0]) { - let intermediate = self.resolve_intermediate(&self.code.entry_point)?; - return self.get_child_intermediate(intermediate, &inputs, &challenge_input); - } - let input_0 = &Ext::get_input_value(&inputs[0]); - let sub_inputs = Ext::sub_array(&inputs, 1, inputs.len()); - - let intermediate = self.resolve_intermediate(&input_0)?; - return self.get_child_intermediate(intermediate, &sub_inputs, &challenge_input); - } - - fn decide(&self, inputs: Vec>, witness: Vec>) -> ExecResult> { - // println!("decide inputs: {:?}", inputs); - // println!("decide witness:{:?}", witness); - if !Ext::is_label(&inputs[0]) { - return Err(ExecError::Unimplemented); - } - let input_0 = &Ext::get_input_value(&inputs[0]); - let sub_inputs = Ext::sub_array(&inputs, 1, inputs.len()); - let intermediate = self.resolve_intermediate(&input_0)?; - self.decide_intermediate(&intermediate, &sub_inputs, &witness) - } - - fn decide_true( - &self, - inputs: Vec>, - witness: Vec>, - ) -> ExecResult> { - self.decide(inputs, witness) - } - - fn decide_with_witness( - &self, - inputs: Vec>, - witness: Vec>, - ) -> ExecResult> { - let result = self.decide(inputs.clone(), witness)?; - require_with_message!(result, "must be true"); - let property = Property { - predicate_address: self.ext.ext_address(), - inputs: inputs, - }; - self.ext - .ext_set_predicate_decision(self.ext.ext_get_property_id(&property), true) - } -} - -impl CompiledExecutable<'_, Ext> { - // decide_** -------------------------------------- - fn decide_intermediate( - &self, - inter: &IntermediateCompiledPredicate, - inputs: &Vec>, - witness: &Vec>, - ) -> ExecResult> { - // println!("decide_intermediate inter : {:?}", inter); - // println!("decide_intermediate inputs : {:?}", inputs); - // println!("decide_intermediate witness : {:?}", witness); - - let input_property_list = Self::get_input_property_list(inter, inputs)?; - let input_property_list_child_list = - Self::get_input_property_list_child_list(inter, &input_property_list)?; - - match &inter.connective { - LogicalConnective::And => self.decide_and( - inter, - inputs, - witness, - &input_property_list, - &input_property_list_child_list, - ), - LogicalConnective::ThereExistsSuchThat => self.decide_there_exists_such_that( - inter, - inputs, - witness, - &input_property_list, - &input_property_list_child_list, - ), - LogicalConnective::Or => self.decide_or( - inter, - inputs, - witness, - &input_property_list, - &input_property_list_child_list, - ), - _ => Ok(false), - } - } - - fn decide_and( - &self, - inter: &IntermediateCompiledPredicate, - inputs: &Vec>, - witness: &Vec>, - input_property: &Vec>, - input_property_list_child_list: &Vec>>, - ) -> ExecResult> { - require!(witness.len() >= inter.inputs.len()); - for (i, item) in inter.inputs.iter().enumerate() { - if let AtomicPropositionOrPlaceholder::AtomicProposition(item) = item { - if item.is_compiled.unwrap_or(false) { - let child_inputs = self.construct_inputs( - item, - &witness[0], - inputs, - input_property, - input_property_list_child_list, - )?; - require!(self.decide(child_inputs, Ext::bytes_to_bytes_array(&witness[i])?)?); - } - return self.decide_property( - item, - inputs, - witness, - input_property, - input_property_list_child_list, - &Ext::bytes_to_bytes_array(&witness[i])?, - ); - } - } - Ok(true) - } - - fn decide_there_exists_such_that( - &self, - inter: &IntermediateCompiledPredicate, - inputs: &Vec>, - witness: &Vec>, - input_property: &Vec>, - input_property_list_child_list: &Vec>>, - ) -> ExecResult> { - require!(inter.inputs.len() > 2); - let inner_property = match &inter.inputs[2] { - AtomicPropositionOrPlaceholder::AtomicProposition(x) => x, - _ => return Ok(true), - }; - if inner_property.is_compiled.unwrap_or(false) { - let child_inputs = self.construct_inputs( - inner_property, - &witness[0], - inputs, - input_property, - input_property_list_child_list, - )?; - require!(self.decide(child_inputs, Ext::sub_array(&witness, 1, witness.len()))?); - } else { - require!(self.decide_property( - inner_property, - inputs, - witness, - input_property, - input_property_list_child_list, - &Ext::sub_array(&witness, 1, witness.len() as usize), - )?); - } - Ok(true) - } - - fn decide_or( - &self, - inter: &IntermediateCompiledPredicate, - inputs: &Vec>, - witness: &Vec>, - input_property: &Vec>, - input_property_list_child_list: &Vec>>, - ) -> ExecResult> { - let or_index = Ext::bytes_to_u128(&witness[0])?; - for (index, item) in inter.inputs.iter().enumerate() { - if or_index as usize == index { - if let AtomicPropositionOrPlaceholder::AtomicProposition(item) = item { - if item.is_compiled.unwrap_or(false) { - let child_inputs = self.construct_inputs( - item, - &witness[0], - inputs, - input_property, - input_property_list_child_list, - )?; - require!( - self.decide(child_inputs, Ext::sub_array(witness, 1, witness.len()))? - ); - } else { - return self.decide_property( - item, - inputs, - witness, - input_property, - input_property_list_child_list, - &Ext::sub_array(witness, 1, witness.len()), - ); - } - } - } - } - Ok(true) - } - - fn decide_property( - &self, - inter: &AtomicProposition, - inputs: &Vec>, - witness: &Vec>, - input_property: &Vec>, - input_property_list_child_list: &Vec>>, - child_witnesses: &Vec>, - ) -> ExecResult> { - if let PredicateCall::InputPredicateCall(call) = &inter.predicate { - require!(inputs.len() > (call.source.input_index - 1) as usize); - if inter.inputs.len() == 0 { - require!(self.ext.ext_is_decided(&Ext::bytes_to_property( - &inputs[(call.source.input_index - 1) as usize] - )?)); - } else { - let input_predicate_property = - Ext::bytes_to_property(&inputs[(call.source.input_index - 1) as usize])?; - let mut new_inputs = input_predicate_property.inputs.clone(); - if let CompiledInput::NormalInput(normal_input) = &inter.inputs[0] { - require!(inputs.len() > (normal_input.input_index - 1) as usize); - new_inputs.push(inputs[(normal_input.input_index - 1) as usize].clone()); - let result = self.ext.ext_call( - &input_predicate_property.predicate_address, - PredicateCallInputs::CompiledPredicate( - CompiledPredicateCallInputs::Decide { - inputs: new_inputs, - witness: child_witnesses.clone(), - }, - ), - )?; - require_with_message!( - Ext::bytes_to_bool(&result)?, - "InputPredicate must be true" - ); - } - } - } else if let PredicateCall::VariablePredicateCall(_) = &inter.predicate { - // TODO: executable - // require_with_message!( - // self.ext - // .ext_is_decided(&Ext::bytes_to_property(&challenge_input)), - // "VariablePredicate must be true" - // ); - return Ok(true); - } else { - let new_inputs = self.construct_inputs( - inter, - &witness[0], - inputs, - input_property, - input_property_list_child_list, - )?; - if let PredicateCall::CompiledPredicateCall(_call) = &inter.predicate { - // This is for predicates dynamic linking. - let source = Self::get_source_str_from_inter(&inter.predicate)?; - let result = self.ext.ext_call( - &self.get_address_variable(&source)?, - PredicateCallInputs::CompiledPredicate(CompiledPredicateCallInputs::Decide { - inputs: new_inputs, - witness: child_witnesses.clone(), - }), - )?; - require_with_message!( - Ext::bytes_to_bool(&result)?, - "CompiledPredicate(property.predicate.source) must be true" - ); - } else { - let source = Self::get_source_str_from_inter(&inter.predicate)?; - let result = self.ext.ext_call( - &self.get_address_variable(&source)?, - PredicateCallInputs::AtomicPredicate(AtomicPredicateCallInputs::Decide { - inputs: new_inputs, - }), - )?; - require_with_message!( - Ext::bytes_to_bool(&result)?, - "CompiledPredicate(property.predicate.source) must be true" - ); - } - } - Ok(true) - } - - // get_child_** -------------------------------------- - fn get_child_intermediate( - &self, - inter: &IntermediateCompiledPredicate, - inputs: &Vec>, - challenge_inputs: &Vec>, - ) -> ExecResultTOf, Ext> { - // println!("get_child_intermediate inter : {:?}", inter); - // println!("get_child_intermediate inputs : {:?}", inputs); - // println!("get_child_intermediate challenge: {:?}", challenge_inputs); - let input_property_list = Self::get_input_property_list(inter, inputs)?; - let input_property_list_child_list = - Self::get_input_property_list_child_list(inter, &input_property_list)?; - - match &inter.connective { - LogicalConnective::And => self.get_child_and( - inter, - inputs, - challenge_inputs, - &input_property_list, - &input_property_list_child_list, - ), - LogicalConnective::ForAllSuchThat => self.get_child_for_all_such_that( - inter, - inputs, - challenge_inputs, - &input_property_list, - &input_property_list_child_list, - ), - LogicalConnective::Not => self.get_child_not( - inter, - inputs, - challenge_inputs, - &input_property_list, - &input_property_list_child_list, - ), - LogicalConnective::Or => self.get_child_or( - inter, - inputs, - challenge_inputs, - &input_property_list, - &input_property_list_child_list, - ), - LogicalConnective::ThereExistsSuchThat => self.get_child_there_exists_such_that( - inter, - inputs, - challenge_inputs, - &input_property_list, - &input_property_list_child_list, - ), - } - } - - fn get_child_and( - &self, - inter: &IntermediateCompiledPredicate, - inputs: &Vec>, - challenge_inputs: &Vec>, - input_property: &Vec>, - input_property_list_child_list: &Vec>>, - ) -> ExecResultTOf, Ext> { - let challenge_input: usize = Ext::bytes_to_u128(&challenge_inputs[0])? as usize; - require!(inter.inputs.len() > challenge_input as usize); - let item = &inter.inputs[challenge_input]; - match item { - AtomicPropositionOrPlaceholder::AtomicProposition(item) => { - if item.is_compiled.unwrap_or(false) { - require!(item.inputs.len() > 1); - let child_inputs = self.construct_inputs( - &item, - &challenge_inputs[0], - inputs, - input_property, - input_property_list_child_list, - )?; - return self.get_child( - child_inputs, - Ext::sub_array(challenge_inputs, 1, challenge_inputs.len()), - ); - } else if let PredicateCall::CompiledPredicateCall(pred) = &item.predicate { - let child_inputs = self.construct_inputs( - &item, - &challenge_inputs[0], - inputs, - input_property, - input_property_list_child_list, - )?; - let ret = self.ext.ext_call( - &self.get_address_variable(&pred.source)?, - PredicateCallInputs::CompiledPredicate( - CompiledPredicateCallInputs::GetChild { - inputs: child_inputs, - challenge_input: Ext::sub_array( - challenge_inputs, - 1, - challenge_inputs.len(), - ), - }, - ), - )?; - return Ok(Ext::bytes_to_property(&ret)?); - } else { - let not_inputs = vec![self - .construct_property( - &item, - false, - inputs, - challenge_inputs, - input_property, - input_property_list_child_list, - )? - .encode()]; - Ok(Property { - predicate_address: Ext::not_address(), - inputs: not_inputs, - }) - } - } - _ => Err(ExecError::Unexpected { - msg: "get_child_and must be AtomicProposition.", - }), - } - } - - fn get_child_for_all_such_that( - &self, - inter: &IntermediateCompiledPredicate, - inputs: &Vec>, - challenge_inputs: &Vec>, - input_property: &Vec>, - input_property_list_child_list: &Vec>>, - ) -> ExecResultTOf, Ext> { - require!(inter.inputs.len() > 2); - // let quantifier = &inter.inputs[0]; - let inner_property = &inter.inputs[2]; - match inner_property { - AtomicPropositionOrPlaceholder::AtomicProposition(inner_property) => { - if inner_property.is_compiled.unwrap_or(false) { - let child_inputs = self.construct_inputs( - inner_property, - &challenge_inputs[0], - inputs, - input_property, - input_property_list_child_list, - )?; - self.get_child( - child_inputs, - Ext::sub_array(challenge_inputs, 1, challenge_inputs.len()), - ) - } else { - let not_inputs = vec![self - .construct_property( - inner_property, - false, - inputs, - challenge_inputs, - input_property, - input_property_list_child_list, - )? - .encode()]; - Ok(Property { - predicate_address: Ext::not_address(), - inputs: not_inputs, - }) - } - } - _ => Err(ExecError::Unexpected { - msg: "get_child_for_all_such_that must be AtomicProposition.", - }), - } - } - - fn get_child_not( - &self, - inter: &IntermediateCompiledPredicate, - inputs: &Vec>, - challenge_inputs: &Vec>, - input_property: &Vec>, - input_property_list_child_list: &Vec>>, - ) -> ExecResultTOf, Ext> { - let inner_property = &inter.inputs[0]; - if let AtomicPropositionOrPlaceholder::AtomicProposition(inner_property) = inner_property { - return self.construct_property( - inner_property, - false, - inputs, - challenge_inputs, - input_property, - input_property_list_child_list, - ); - } - Err(ExecError::Unexpected { - msg: "get_child_not must be AtomicProposition.", - }) - } - - fn get_child_there_exists_such_that( - &self, - inter: &IntermediateCompiledPredicate, - inputs: &Vec>, - challenge_inputs: &Vec>, - input_property: &Vec>, - input_property_list_child_list: &Vec>>, - ) -> ExecResultTOf, Ext> { - if let AtomicPropositionOrPlaceholder::AtomicProposition(inner_property) = &inter.inputs[2] - { - if let AtomicPropositionOrPlaceholder::Placeholder(property_input_1) = &inter.inputs[1] - { - let not_input = - self.construct_property( - inner_property, - Ext::bytes_to_bool(&mut &self.get_bytes_variable( - &Ext::prefix_variable(&property_input_1.encode()), - )?)?, - inputs, - challenge_inputs, - input_property, - input_property_list_child_list, - )?; - let for_all_such_that_inputs = vec![ - vec![], - property_input_1.encode(), - Property { - predicate_address: Ext::not_address(), - inputs: vec![not_input.encode()], - } - .encode(), - ]; - return Ok(Property { - predicate_address: Ext::for_all_address(), - inputs: for_all_such_that_inputs, - }); - } - } - Err(ExecError::Unexpected { - msg: "get_child_there_exists_such_that must be inter.inputs[1] is Placeholder, inter.inputs[2] is AtomicProposition.", - }) - } - - fn get_child_or( - &self, - inter: &IntermediateCompiledPredicate, - inputs: &Vec>, - challenge_inputs: &Vec>, - input_property: &Vec>, - input_property_list_child_list: &Vec>>, - ) -> ExecResultTOf, Ext> { - let inputs = inter - .inputs - .iter() - .map(|item| { - if let AtomicPropositionOrPlaceholder::AtomicProposition(item) = &item { - if let PredicateCall::CompiledPredicateCall(_) = &item.predicate { - // not (compiled predicate) - let not_inputs = vec![self - .construct_property( - item, - false, - inputs, - challenge_inputs, - input_property, - input_property_list_child_list, - )? - .encode()]; - return Ok(Property { - predicate_address: Ext::not_address(), - inputs: not_inputs, - } - .encode()); - } else { - // The valid challenge of "p1 ∨ p2" is "¬(p1) ∧ ¬(p2)". - // If p1 is "¬(p1_1)", the valid challenge is "p1_1 ∧ ¬(p2)", - // then returning getChild of "¬(p1_1)" here. - let child_inputs = self.construct_inputs( - item, - &challenge_inputs[0], - inputs, - input_property, - input_property_list_child_list, - )?; - return Ok(self - .get_child(child_inputs, challenge_inputs.clone())? - .encode()); - } - } - Err(ExecError::Unexpected { - msg: "get_child_or must be all inter.inputs AtomicProposition.", - }) - }) - .collect::>, _>>()?; - Ok(Property { - predicate_address: Ext::and_address(), - inputs: inputs, - }) - } - - // helper ----------------------------------------------- - fn resolve_intermediate( - &self, - name: &Vec, - ) -> ExecResultTOf<&IntermediateCompiledPredicate, Ext> { - if let Some(index) = self - .code - .contracts - .iter() - .position(|inter| &inter.name == name) - { - return Ok(&self.code.contracts[index]); - } - Err(ExecError::Require { - msg: "Required error by: resolve_intermediate", - }) - } - - fn get_input_property_list( - inter: &IntermediateCompiledPredicate, - inputs: &Vec>, - ) -> ExecResultTOf>, Ext> { - Ok(inter - .property_inputs - .iter() - .map(|property_input| { - Ext::bytes_to_property(&inputs[(property_input.input_index - 1) as usize]) - }) - .collect::>, _>>()?) - } - - fn get_input_property_list_child_list( - inter: &IntermediateCompiledPredicate, - input_property: &Vec>, - ) -> ExecResultTOf>>, Ext> { - inter - .property_inputs - .iter() - .map(|property_input| { - let mut ret = BTreeMap::new(); - if property_input.children.len() > 0 { - require!( - input_property[property_input.input_index as usize] - .inputs - .len() - > property_input.children[0] as usize - ); - ret.insert( - property_input.children[0].clone(), - Ext::bytes_to_property( - &input_property[property_input.input_index as usize].inputs - [property_input.children[0] as usize], - )?, - ); - } - Ok(ret) - }) - .collect::>>, _>>() - } - - fn construct_inputs( - &self, - property: &AtomicProposition, - witness: &Vec, - inputs: &Vec>, - input_property: &Vec>, - input_property_list_child_list: &Vec>>, - ) -> ExecResultTOf>, Ext> { - property - .inputs - .iter() - .map(|input| { - self.construct_input( - input, - witness, - inputs, - input_property, - input_property_list_child_list, - ) - }) - .collect() - } - - fn construct_input( - &self, - compiled_input: &CompiledInput, - witness: &Vec, - inputs: &Vec>, - input_property: &Vec>, - input_property_list_child_list: &Vec>>, - ) -> ExecResultTOf, Ext> { - match compiled_input { - CompiledInput::ConstantInput(inp) => Ok(inp.name.clone()), - CompiledInput::LabelInput(inp) => { - Ok(Ext::prefix_label(&self.get_bytes_variable(&inp.label)?)) - } - CompiledInput::NormalInput(inp) => { - if inp.children.len() == 1 { - require!(input_property.len() > inp.input_index as usize); - let input_property_input = &input_property[inp.input_index as usize]; - if inp.children[0] >= 0 { - require!(input_property_input.inputs.len() > inp.children[0] as usize); - return Ok(input_property_input.inputs[inp.children[0] as usize].clone()); - } else { - return Ok(input_property_input.predicate_address.encode()); - } - } else if inp.children.len() == 2 { - require!(input_property_list_child_list.len() > inp.input_index as usize); - let input_child_list = input_property_list_child_list[inp.input_index as usize] - .get(&inp.children[0]) - .ok_or(ExecError::Require { - msg: "invalid index children[0]", - })?; - if inp.children[1] >= 0 { - return Ok(input_child_list.inputs[inp.children[1] as usize].clone()); - } else { - return Ok(input_child_list.predicate_address.encode()); - } - } - require!(inputs.len() > (inp.input_index - 1) as usize); - Ok(inputs[(inp.input_index - 1) as usize].clone()) - } - CompiledInput::VariableInput(_) => Ok(witness.clone()), - CompiledInput::SelfInput(_) => Ok(self.ext.ext_address().encode()), - } - } - - fn construct_property( - &self, - property: &AtomicProposition, - free_variable: bool, - inputs: &Vec>, - challenge_inputs: &Vec>, - input_property: &Vec>, - input_property_list_child_list: &Vec>>, - ) -> ExecResultTOf, Ext> { - match &property.predicate { - PredicateCall::InputPredicateCall(call) => { - require!(inputs.len() > (call.source.input_index - 1) as usize); - if property.inputs.len() == 0 { - return Ext::bytes_to_property(&inputs[(call.source.input_index - 1) as usize]); - } - require!(inputs.len() > (call.source.input_index - 1) as usize); - require!(challenge_inputs.len() > 0); - let input_predicate_property: PropertyOf = - Ext::bytes_to_property(&inputs[(call.source.input_index - 1) as usize])?; - let mut child_inputs_of = input_predicate_property.inputs; - child_inputs_of.push(self.construct_input( - &property.inputs[0], - &challenge_inputs[0], - inputs, - input_property, - input_property_list_child_list, - )?); - Ok(Property { - predicate_address: input_predicate_property.predicate_address, - inputs: child_inputs_of, - }) - } - PredicateCall::VariablePredicateCall(_) => { - if property.inputs.len() == 0 { - require!(challenge_inputs.len() > 0); - return Ext::bytes_to_property(&challenge_inputs[0]); - } - - let input_predicate_property: PropertyOf = - Ext::bytes_to_property(&challenge_inputs[0])?; - let mut child_inputs_of = input_predicate_property.inputs; - let property_inputs_input_index = - Self::get_input_index_from_atomic_proposition(&property.inputs[0])?; - child_inputs_of.push(inputs[(property_inputs_input_index - 1) as usize].clone()); - Ok(Property { - predicate_address: input_predicate_property.predicate_address, - inputs: child_inputs_of, - }) - } - _ => { - let witness = if free_variable { - self.get_bytes_variable(&b"freeVariable".to_vec())? - } else { - challenge_inputs[0].clone() - }; - let child_inputs_of = self.construct_inputs( - property, - &witness, - inputs, - input_property, - input_property_list_child_list, - )?; - if property.is_compiled.unwrap_or(false) { - return Ok(Property { - predicate_address: self.ext.ext_address(), - inputs: child_inputs_of, - }); - } - let predicate_address = self - .get_address_variable(&Self::get_source_str_from_inter(&property.predicate)?)?; - Ok(PropertyOf:: { - predicate_address, - inputs: child_inputs_of, - }) - } - } - } - - fn get_bytes_variable(&self, key: &Vec) -> ExecResultTOf, Ext> { - if let Some(ret) = self.bytes_inputs.get(&Ext::hash_of(&key)) { - return Ok(ret.clone()); - } - Err(ExecError::Require { - msg: "invalid bytes variable name.", - }) - } - - fn get_address_variable(&self, key: &Vec) -> ExecResultTOf, Ext> { - // println!("get_address_variable: {}", key); - if let Some(ret) = self.address_inputs.get(&Ext::hash_of(key)) { - return Ok(ret.clone()); - } - if let Some(ret) = Ext::vec_to_address(key) { - return Ok(ret); - } - Err(ExecError::Require { - msg: "invalid address a variable name.", - }) - } - - fn get_source_str_from_inter(predicate: &PredicateCall) -> ExecResultTOf, Ext> { - match predicate { - PredicateCall::AtomicPredicateCall(predicate) => Ok(predicate.source.clone()), - PredicateCall::CompiledPredicateCall(predicate) => Ok(predicate.source.clone()), - _ => Err(ExecError::Unexpected { - msg: "The intermediate must have source as bytes string.", - }), - } - } - - fn get_input_index_from_atomic_proposition( - compiled_input: &CompiledInput, - ) -> ExecResultTOf { - match compiled_input { - CompiledInput::NormalInput(normal) => Ok(normal.input_index), - _ => Err(ExecError::Unexpected { - msg: "The atomic proposition must have NormalInput and input_index.", - }), - } - } -} diff --git a/ovmi/lib/src/predicates/for_all.rs b/ovmi/lib/src/predicates/for_all.rs deleted file mode 100644 index ea181c5a0f..0000000000 --- a/ovmi/lib/src/predicates/for_all.rs +++ /dev/null @@ -1,93 +0,0 @@ -use crate::executor::*; -use crate::predicates::*; - -pub struct ForAllPredicate<'a, Ext: ExternalCall> { - pub ext: &'a Ext, -} - -impl ForAllPredicate<'_, Ext> { - /// @dev Replace placeholder by quantified in propertyBytes - fn replace_variable( - &self, - property_bytes: &Vec, - placeholder: &Vec, - quantified: &Vec, - ) -> ExecResultT, AddressOf> { - // Support property as the variable in ForAllSuchThatQuantifier. - // This code enables meta operation which we were calling eval without adding specific "eval" contract. - // For instance, we can write a property like `∀su ∈ SU: su()`. - if Ext::is_placeholder(property_bytes) { - if &Ext::get_input_value(property_bytes) == placeholder { - return Ok(quantified.clone()); - } - } - let mut property: Property> = Ext::bytes_to_property(&property_bytes)?; - if property.predicate_address == Ext::not_address() { - require!(property.inputs.len() > 0); - property.inputs[0] = - self.replace_variable(&property.inputs[0], placeholder, quantified)?; - } else if property.predicate_address == self.ext.ext_address() { - require!(property.inputs.len() > 2); - property.inputs[2] = - self.replace_variable(&property.inputs[2], placeholder, quantified)?; - } else if property.predicate_address == Ext::and_address() { - property.inputs = property - .inputs - .iter() - .map(|input| self.replace_variable(input, placeholder, quantified)) - .collect::, _>>()?; - } else { - property.inputs = property - .inputs - .iter() - .map(|input| { - if Ext::is_placeholder(input) { - if &Ext::get_input_value(input) == placeholder { - return quantified.clone(); - } - } - input.clone() - }) - .collect(); - } - Ok(property.encode()) - } -} - -impl LogicalConnectiveInterface> for ForAllPredicate<'_, Ext> { - /// @dev Validates a child node of ForAll property in game tree. - fn is_valid_challenge( - &self, - inputs: Vec>, - challenge_inputs: Vec>, - challenge: Property>, - ) -> ExecResult> { - // challenge should be not(p[quantified]) - require_with_message!( - challenge.predicate_address == Ext::not_address(), - "_challenge must be Not predicate" - ); - // check inner property - require!(inputs.len() > 2); - require!(challenge_inputs.len() > 0); - require!(challenge.inputs.len() > 0); - let replace_variabled = - self.replace_variable(&inputs[2], &inputs[1], &challenge_inputs[0])?; - require_with_message!( - replace_variabled == challenge.inputs[0], - "must be valid inner property" - ); - Ok(true) - } -} - -impl DecidablePredicateInterface> for ForAllPredicate<'_, Ext> { - /// @dev Can decide true when all child properties are decided true - fn decide_with_witness( - &self, - _inputs: Vec>, - _witness: Vec>, - ) -> ExecResult> { - Ok(false) - } -} diff --git a/ovmi/lib/src/predicates/is_contained.rs b/ovmi/lib/src/predicates/is_contained.rs deleted file mode 100644 index 4ebdf3532b..0000000000 --- a/ovmi/lib/src/predicates/is_contained.rs +++ /dev/null @@ -1,54 +0,0 @@ -use crate::executor::*; -use crate::predicates::*; -use crate::Range; - -pub struct IsContainedPredicate<'a, Ext: ExternalCall> { - pub ext: &'a Ext, -} - -impl AtomicPredicateInterface> for IsContainedPredicate<'_, Ext> { - fn decide(&self, inputs: Vec>) -> ExecResult> { - require!(inputs.len() > 1); - let range: Range = Ext::bytes_to_range(&inputs[0])?; - let sub_range: Range = Ext::bytes_to_range(&inputs[1])?; - require_with_message!( - range.start <= sub_range.start && sub_range.end <= range.end, - "range must contain subrange" - ); - Ok(true) - } -} - -impl AtomicHelperInterface> for IsContainedPredicate<'_, Ext> { - type Hash = HashOf; - fn ext_address(&self) -> AddressOf { - self.ext.ext_address() - } - fn ext_set_predicate_decision( - &self, - game_id: Self::Hash, - decision: bool, - ) -> ExecResult> { - self.ext.ext_set_predicate_decision(game_id, decision) - } - fn ext_get_property_id(&self, property: &Property>) -> Self::Hash { - self.ext.ext_get_property_id(property) - } -} - -impl DecidablePredicateInterface> - for IsContainedPredicate<'_, Ext> -{ - fn decide_with_witness( - &self, - inputs: Vec>, - _witness: Vec>, - ) -> ExecResult> { - Self::decide(self, inputs) - } -} - -impl BaseAtomicPredicateInterface> - for IsContainedPredicate<'_, Ext> -{ -} diff --git a/ovmi/lib/src/predicates/is_less.rs b/ovmi/lib/src/predicates/is_less.rs deleted file mode 100644 index 16d12cd57e..0000000000 --- a/ovmi/lib/src/predicates/is_less.rs +++ /dev/null @@ -1,48 +0,0 @@ -use crate::executor::*; -use crate::predicates::*; - -pub struct IsLessThanPredicate<'a, Ext: ExternalCall> { - pub ext: &'a Ext, -} - -impl AtomicPredicateInterface> for IsLessThanPredicate<'_, Ext> { - fn decide(&self, inputs: Vec>) -> ExecResult> { - let first: u128 = Ext::bytes_to_u128(&inputs[0])?; - let second: u128 = Ext::bytes_to_u128(&inputs[1])?; - require_with_message!(first < second, "first input is not less than second input"); - Ok(true) - } -} -impl AtomicHelperInterface> for IsLessThanPredicate<'_, Ext> { - type Hash = HashOf; - fn ext_address(&self) -> AddressOf { - self.ext.ext_address() - } - fn ext_set_predicate_decision( - &self, - game_id: Self::Hash, - decision: bool, - ) -> ExecResult> { - self.ext.ext_set_predicate_decision(game_id, decision) - } - fn ext_get_property_id(&self, property: &Property>) -> Self::Hash { - self.ext.ext_get_property_id(property) - } -} - -impl DecidablePredicateInterface> - for IsLessThanPredicate<'_, Ext> -{ - fn decide_with_witness( - &self, - inputs: Vec>, - _witness: Vec>, - ) -> ExecResult> { - Self::decide(self, inputs) - } -} - -impl BaseAtomicPredicateInterface> - for IsLessThanPredicate<'_, Ext> -{ -} diff --git a/ovmi/lib/src/predicates/is_stored.rs b/ovmi/lib/src/predicates/is_stored.rs deleted file mode 100644 index 583c7e0fdb..0000000000 --- a/ovmi/lib/src/predicates/is_stored.rs +++ /dev/null @@ -1,47 +0,0 @@ -use crate::executor::*; -use crate::predicates::*; - -pub struct IsStoredPredicate<'a, Ext: ExternalCall> { - pub ext: &'a Ext, -} - -impl AtomicPredicateInterface> for IsStoredPredicate<'_, Ext> { - fn decide(&self, inputs: Vec>) -> ExecResult> { - require!(inputs.len() > 2); - let address = Ext::bytes_to_address(&inputs[0])?; - Ok(self - .ext - .ext_is_stored(&address, &inputs[1][..], &inputs[2][..])) - } -} -impl AtomicHelperInterface> for IsStoredPredicate<'_, Ext> { - type Hash = HashOf; - fn ext_address(&self) -> AddressOf { - self.ext.ext_address() - } - fn ext_set_predicate_decision( - &self, - game_id: Self::Hash, - decision: bool, - ) -> ExecResult> { - self.ext.ext_set_predicate_decision(game_id, decision) - } - fn ext_get_property_id(&self, property: &Property>) -> Self::Hash { - self.ext.ext_get_property_id(property) - } -} - -impl DecidablePredicateInterface> for IsStoredPredicate<'_, Ext> { - fn decide_with_witness( - &self, - inputs: Vec>, - _witness: Vec>, - ) -> ExecResult> { - Self::decide(self, inputs) - } -} - -impl BaseAtomicPredicateInterface> - for IsStoredPredicate<'_, Ext> -{ -} diff --git a/ovmi/lib/src/predicates/is_valid_signature.rs b/ovmi/lib/src/predicates/is_valid_signature.rs deleted file mode 100644 index 1587a783ba..0000000000 --- a/ovmi/lib/src/predicates/is_valid_signature.rs +++ /dev/null @@ -1,62 +0,0 @@ -use crate::executor::*; -use crate::predicates::*; - -pub struct IsValidSignaturePredicate<'a, Ext: ExternalCall> { - pub ext: &'a Ext, -} - -impl AtomicPredicateInterface> - for IsValidSignaturePredicate<'_, Ext> -{ - fn decide(&self, inputs: Vec>) -> ExecResult> { - require!(inputs.len() > 3); - require_with_message!( - Ext::Hashing::hash(&inputs[3][..]) == Ext::secp256k1(), - "verifierType must be secp256k1" - ); - - let hash = Ext::Hashing::hash(&inputs[0][..]); - let address = Ext::bytes_to_address(&inputs[2])?; - require_with_message!( - self.ext.ext_verify(&hash, &inputs[1][..], &address,), - "_inputs[1] must be signature of _inputs[0] by _inputs[2]" - ); - Ok(true) - } -} - -impl AtomicHelperInterface> - for IsValidSignaturePredicate<'_, Ext> -{ - type Hash = HashOf; - fn ext_address(&self) -> AddressOf { - self.ext.ext_address() - } - fn ext_set_predicate_decision( - &self, - game_id: Self::Hash, - decision: bool, - ) -> ExecResult> { - self.ext.ext_set_predicate_decision(game_id, decision) - } - fn ext_get_property_id(&self, property: &Property>) -> Self::Hash { - self.ext.ext_get_property_id(property) - } -} - -impl DecidablePredicateInterface> - for IsValidSignaturePredicate<'_, Ext> -{ - fn decide_with_witness( - &self, - inputs: Vec>, - _witness: Vec>, - ) -> ExecResult> { - Self::decide(self, inputs) - } -} - -impl BaseAtomicPredicateInterface> - for IsValidSignaturePredicate<'_, Ext> -{ -} diff --git a/ovmi/lib/src/predicates/mod.rs b/ovmi/lib/src/predicates/mod.rs deleted file mode 100644 index 593ba25fb5..0000000000 --- a/ovmi/lib/src/predicates/mod.rs +++ /dev/null @@ -1,484 +0,0 @@ -//! # Executable Predicates. -//! Executable Predicates instanced from Compiled Predicates and Atomic Predicates. -//! -//! -use crate::executor::{AddressOf, ExecError, ExecResult, ExecResultT, ExternalCall, HashOf}; -use alloc::{collections::btree_map::BTreeMap, vec::Vec}; -use codec::{Decode, Encode}; -use core::fmt; - -mod and; -mod executable; -mod for_all; -mod not; -mod or; -mod there_exists; - -pub use and::AndPredicate; -pub use executable::CompiledExecutable; -pub use for_all::ForAllPredicate; -pub use not::NotPredicate; -pub use or::OrPredicate; -pub use there_exists::ThereExistsPredicate; - -mod equal; -mod is_contained; -mod is_less; -mod is_stored; -mod is_valid_signature; -mod verify_inclusion; -pub use equal::EqualPredicate; -pub use is_contained::IsContainedPredicate; -pub use is_less::IsLessThanPredicate; -pub use is_stored::IsStoredPredicate; -pub use is_valid_signature::IsValidSignaturePredicate; -pub use verify_inclusion::VerifyInclusionPredicate; - -pub enum AtomicExecutable<'a, Ext: ExternalCall> { - Equal(EqualPredicate<'a, Ext>), - IsContained(IsContainedPredicate<'a, Ext>), - IsLess(IsLessThanPredicate<'a, Ext>), - IsStored(IsStoredPredicate<'a, Ext>), - IsValidSignature(IsValidSignaturePredicate<'a, Ext>), - VerifyInclusion(VerifyInclusionPredicate<'a, Ext>), -} - -impl AtomicPredicateInterface> for AtomicExecutable<'_, Ext> { - fn decide(&self, inputs: Vec>) -> ExecResult> { - match self { - AtomicExecutable::Equal(p) => p.decide(inputs), - AtomicExecutable::IsContained(p) => p.decide(inputs), - AtomicExecutable::IsLess(p) => p.decide(inputs), - AtomicExecutable::IsStored(p) => p.decide(inputs), - AtomicExecutable::IsValidSignature(p) => p.decide(inputs), - AtomicExecutable::VerifyInclusion(p) => p.decide(inputs), - } - } - - fn decide_true(&self, inputs: Vec>) -> ExecResult> { - match self { - AtomicExecutable::Equal(p) => p.decide_true(inputs), - AtomicExecutable::IsContained(p) => p.decide_true(inputs), - AtomicExecutable::IsLess(p) => p.decide_true(inputs), - AtomicExecutable::IsStored(p) => p.decide_true(inputs), - AtomicExecutable::IsValidSignature(p) => p.decide_true(inputs), - AtomicExecutable::VerifyInclusion(p) => p.decide_true(inputs), - } - } -} - -impl AtomicHelperInterface> for AtomicExecutable<'_, Ext> { - type Hash = HashOf; - fn ext_address(&self) -> AddressOf { - AddressOf::::default() - } - fn ext_set_predicate_decision( - &self, - _game_id: Self::Hash, - _decision: bool, - ) -> ExecResult> { - Err(ExecError::Unimplemented) - } - fn ext_get_property_id(&self, _property: &Property>) -> Self::Hash { - Self::Hash::default() - } -} - -pub enum LogicalConnectiveExecutable<'a, Ext: ExternalCall> { - And(AndPredicate<'a, Ext>), - Not(NotPredicate<'a, Ext>), - Or(OrPredicate<'a, Ext>), - ForAll(ForAllPredicate<'a, Ext>), - ThereExists(ThereExistsPredicate<'a, Ext>), -} - -impl LogicalConnectiveInterface> - for LogicalConnectiveExecutable<'_, Ext> -{ - fn is_valid_challenge( - &self, - inputs: Vec>, - challenge_inputs: Vec>, - challenge: Property>, - ) -> ExecResult> { - match self { - LogicalConnectiveExecutable::And(and) => { - and.is_valid_challenge(inputs, challenge_inputs, challenge) - } - LogicalConnectiveExecutable::Not(not) => { - not.is_valid_challenge(inputs, challenge_inputs, challenge) - } - LogicalConnectiveExecutable::Or(or) => { - or.is_valid_challenge(inputs, challenge_inputs, challenge) - } - LogicalConnectiveExecutable::ForAll(for_all) => { - for_all.is_valid_challenge(inputs, challenge_inputs, challenge) - } - LogicalConnectiveExecutable::ThereExists(there_exists) => { - there_exists.is_valid_challenge(inputs, challenge_inputs, challenge) - } - } - } -} - -pub enum DecidableExecutable<'a, Ext: ExternalCall> { - And(AndPredicate<'a, Ext>), - Not(NotPredicate<'a, Ext>), - Or(OrPredicate<'a, Ext>), - ForAll(ForAllPredicate<'a, Ext>), - ThereExists(ThereExistsPredicate<'a, Ext>), - Equal(EqualPredicate<'a, Ext>), - IsContained(IsContainedPredicate<'a, Ext>), - IsLess(IsLessThanPredicate<'a, Ext>), - IsStored(IsStoredPredicate<'a, Ext>), - IsValidSignature(IsValidSignaturePredicate<'a, Ext>), - VerifyInclusion(VerifyInclusionPredicate<'a, Ext>), -} - -impl DecidablePredicateInterface> - for DecidableExecutable<'_, Ext> -{ - fn decide_with_witness( - &self, - inputs: Vec>, - witness: Vec>, - ) -> ExecResult> { - match self { - DecidableExecutable::And(p) => p.decide_with_witness(inputs, witness), - DecidableExecutable::Not(p) => p.decide_with_witness(inputs, witness), - DecidableExecutable::Or(p) => p.decide_with_witness(inputs, witness), - DecidableExecutable::ForAll(p) => p.decide_with_witness(inputs, witness), - DecidableExecutable::ThereExists(p) => p.decide_with_witness(inputs, witness), - DecidableExecutable::Equal(p) => p.decide_with_witness(inputs, witness), - DecidableExecutable::IsContained(p) => p.decide_with_witness(inputs, witness), - DecidableExecutable::IsLess(p) => p.decide_with_witness(inputs, witness), - DecidableExecutable::IsStored(p) => p.decide_with_witness(inputs, witness), - DecidableExecutable::IsValidSignature(p) => p.decide_with_witness(inputs, witness), - DecidableExecutable::VerifyInclusion(p) => p.decide_with_witness(inputs, witness), - } - } -} - -pub enum BaseAtomicExecutable<'a, Ext: ExternalCall> { - Equal(EqualPredicate<'a, Ext>), - IsContained(IsContainedPredicate<'a, Ext>), - IsLess(IsLessThanPredicate<'a, Ext>), - IsStored(IsStoredPredicate<'a, Ext>), - IsValidSignature(IsValidSignaturePredicate<'a, Ext>), - VerifyInclusion(VerifyInclusionPredicate<'a, Ext>), -} - -impl DecidablePredicateInterface> - for BaseAtomicExecutable<'_, Ext> -{ - fn decide_with_witness( - &self, - inputs: Vec>, - witness: Vec>, - ) -> ExecResult> { - match self { - BaseAtomicExecutable::Equal(p) => p.decide_with_witness(inputs, witness), - BaseAtomicExecutable::IsContained(p) => p.decide_with_witness(inputs, witness), - BaseAtomicExecutable::IsLess(p) => p.decide_with_witness(inputs, witness), - BaseAtomicExecutable::IsStored(p) => p.decide_with_witness(inputs, witness), - BaseAtomicExecutable::IsValidSignature(p) => p.decide_with_witness(inputs, witness), - BaseAtomicExecutable::VerifyInclusion(p) => p.decide_with_witness(inputs, witness), - } - } -} - -impl AtomicPredicateInterface> for BaseAtomicExecutable<'_, Ext> { - fn decide(&self, inputs: Vec>) -> ExecResult> { - match self { - BaseAtomicExecutable::Equal(p) => p.decide(inputs), - BaseAtomicExecutable::IsContained(p) => p.decide(inputs), - BaseAtomicExecutable::IsLess(p) => p.decide(inputs), - BaseAtomicExecutable::IsStored(p) => p.decide(inputs), - BaseAtomicExecutable::IsValidSignature(p) => p.decide(inputs), - BaseAtomicExecutable::VerifyInclusion(p) => p.decide(inputs), - } - } - - fn decide_true(&self, inputs: Vec>) -> ExecResult> { - match self { - BaseAtomicExecutable::Equal(p) => p.decide_true(inputs), - BaseAtomicExecutable::IsContained(p) => p.decide_true(inputs), - BaseAtomicExecutable::IsLess(p) => p.decide_true(inputs), - BaseAtomicExecutable::IsStored(p) => p.decide_true(inputs), - BaseAtomicExecutable::IsValidSignature(p) => p.decide_true(inputs), - BaseAtomicExecutable::VerifyInclusion(p) => p.decide_true(inputs), - } - } -} - -impl BaseAtomicPredicateInterface> - for BaseAtomicExecutable<'_, Ext> -{ -} - -impl AtomicHelperInterface> for BaseAtomicExecutable<'_, Ext> { - type Hash = HashOf; - fn ext_address(&self) -> AddressOf { - AddressOf::::default() - } - fn ext_set_predicate_decision( - &self, - _game_id: Self::Hash, - _decision: bool, - ) -> ExecResult> { - Err(ExecError::Unimplemented) - } - fn ext_get_property_id(&self, _property: &Property>) -> Self::Hash { - Self::Hash::default() - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum PredicateCallInputs
{ - AtomicPredicate(AtomicPredicateCallInputs), - DecidablePredicate(DecidablePredicateCallInputs), - LogicalConnective(LogicalConnectiveCallInputs
), - BaseAtomicPredicate(BaseAtomicPredicateCallInputs), - CompiledPredicate(CompiledPredicateCallInputs
), -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum AtomicPredicateCallInputs { - DecideTrue { inputs: Vec> }, - Decide { inputs: Vec> }, -} - -impl fmt::Display for AtomicPredicateCallInputs { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> fmt::Result { - let state = match self { - AtomicPredicateCallInputs::Decide { inputs: _ } => "Decide", - AtomicPredicateCallInputs::DecideTrue { inputs: _ } => "DecideTrue", - }; - write!(f, "{}", state) - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum DecidablePredicateCallInputs { - DecideWithWitness { - inputs: Vec>, - witness: Vec>, - }, -} - -impl fmt::Display for DecidablePredicateCallInputs { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> fmt::Result { - let state = match self { - DecidablePredicateCallInputs::DecideWithWitness { - inputs: _, - witness: _, - } => "DecideWithWitness", - }; - write!(f, "{}", state) - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum LogicalConnectiveCallInputs
{ - IsValidChallenge { - inputs: Vec>, - challenge_inputs: Vec>, - challenge: Property
, - }, -} - -impl
fmt::Display for LogicalConnectiveCallInputs
{ - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> fmt::Result { - let state = match self { - LogicalConnectiveCallInputs::IsValidChallenge { - inputs: _, - challenge_inputs: _, - challenge: _, - } => "IsValidChallenge", - }; - write!(f, "{}", state) - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum BaseAtomicPredicateCallInputs { - Decide { - inputs: Vec>, - }, - DecideWithWitness { - inputs: Vec>, - witness: Vec>, - }, - DecideTrue { - inputs: Vec>, - }, -} - -impl fmt::Display for BaseAtomicPredicateCallInputs { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> fmt::Result { - let state = match self { - BaseAtomicPredicateCallInputs::Decide { inputs: _ } => "Decide", - BaseAtomicPredicateCallInputs::DecideTrue { inputs: _ } => "DecideTrue", - BaseAtomicPredicateCallInputs::DecideWithWitness { - inputs: _, - witness: _, - } => "DecideWithWitness", - }; - write!(f, "{}", state) - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum CompiledPredicateCallInputs
{ - IsValidChallenge { - inputs: Vec>, - challenge_inputs: Vec>, - challenge: Property
, - }, - Decide { - inputs: Vec>, - witness: Vec>, - }, - DecideTrue { - inputs: Vec>, - witness: Vec>, - }, - DecideWithWitness { - inputs: Vec>, - witness: Vec>, - }, - GetChild { - inputs: Vec>, - challenge_input: Vec>, - }, -} - -impl
fmt::Display for CompiledPredicateCallInputs
{ - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> fmt::Result { - let state = match self { - CompiledPredicateCallInputs::IsValidChallenge { - inputs: _, - challenge_inputs: _, - challenge: _, - } => "IsValidChallenge", - CompiledPredicateCallInputs::Decide { - inputs: _, - witness: _, - } => "Decide", - CompiledPredicateCallInputs::DecideTrue { - inputs: _, - witness: _, - } => "DecideTrue", - CompiledPredicateCallInputs::DecideWithWitness { - inputs: _, - witness: _, - } => "DecideWithWitness", - CompiledPredicateCallInputs::GetChild { - inputs: _, - challenge_input: _, - } => "GetChild", - }; - write!(f, "{}", state) - } -} - -/// Property stands for dispute logic and we can claim every Properties to Adjudicator Contract. -/// Property has its predicate address and array of input. -#[derive(Encode, Decode, Clone, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub struct Property
{ - /// Indicates the address of Predicate. - predicate_address: Address, - /// Every input are bytes. Each Atomic Predicate decode inputs to the specific type. - inputs: Vec>, -} - -pub trait UniversalAdjudication { - fn ext_set_predicate_decision(&self, game_id: Hash, decision: bool); -} - -pub trait Utils { - fn ext_get_property_id(&self) -> Hash; -} - -pub trait BaseAtomicPredicateInterface
: - AtomicPredicateInterface
+ DecidablePredicateInterface
-{ -} - -pub trait AtomicPredicateInterface
: AtomicHelperInterface
{ - fn decide(&self, _inputs: Vec>) -> ExecResult
{ - return Ok(false); - } - - fn decide_true(&self, inputs: Vec>) -> ExecResult
{ - let result_of_decide = AtomicPredicateInterface::decide(self, inputs.clone())?; - require_with_message!(result_of_decide, "must decide true"); - let property = Property { - predicate_address: self.ext_address(), - inputs: inputs, - }; - self.ext_set_predicate_decision(self.ext_get_property_id(&property), true)?; - Ok(true) - } -} - -pub trait AtomicHelperInterface
{ - type Hash; - fn ext_address(&self) -> Address; - fn ext_set_predicate_decision( - &self, - game_id: Self::Hash, - decision: bool, - ) -> ExecResult
; - fn ext_get_property_id(&self, property: &Property
) -> Self::Hash; -} - -pub trait DecidablePredicateInterface
{ - fn decide_with_witness( - &self, - _inputs: Vec>, - _witness: Vec>, - ) -> ExecResult
; -} - -pub trait CompiledPredicateInterface
{ - fn payout_contract_address(&self) -> Address; - - fn is_valid_challenge( - &self, - _inputs: Vec>, - _challenge_inputs: Vec>, - _challenge: Property
, - ) -> ExecResult
; - - /// @dev get valid child property of game tree with challenge_inputs - fn get_child( - &self, - inputs: Vec>, - challenge_input: Vec>, - ) -> ExecResultT, Address>; - - fn decide(&self, _inputs: Vec>, _witness: Vec>) -> ExecResult
; - fn decide_true(&self, _inputs: Vec>, _witness: Vec>) -> ExecResult
; - fn decide_with_witness( - &self, - _inputs: Vec>, - _witness: Vec>, - ) -> ExecResult
; -} - -pub trait LogicalConnectiveInterface
{ - fn is_valid_challenge( - &self, - _inputs: Vec>, - _challenge_inputs: Vec>, - _challenge: Property
, - ) -> ExecResult
; -} diff --git a/ovmi/lib/src/predicates/not.rs b/ovmi/lib/src/predicates/not.rs deleted file mode 100644 index 0d017f4452..0000000000 --- a/ovmi/lib/src/predicates/not.rs +++ /dev/null @@ -1,30 +0,0 @@ -use crate::executor::*; -use crate::predicates::*; - -pub struct NotPredicate<'a, Ext: ExternalCall> { - pub ext: &'a Ext, -} - -impl<'a, Ext: ExternalCall> LogicalConnectiveInterface> for NotPredicate<'a, Ext> { - /// @dev Validates a child node of Not property in game tree. - fn is_valid_challenge( - &self, - inputs: Vec>, - _challenge_inputs: Vec>, - challenge: Property>, - ) -> ExecResult> { - // The valid challenge of not(p) is p and _inputs[0] is p here - require!(inputs.len() > 0); - Ok(Ext::hash_of(&inputs[0]) == Ext::hash_of(&challenge)) - } -} -impl<'a, Ext: ExternalCall> DecidablePredicateInterface> for NotPredicate<'a, Ext> { - /// @dev Decides true - fn decide_with_witness( - &self, - _inputs: Vec>, - _witness: Vec>, - ) -> ExecResult> { - Ok(false) - } -} diff --git a/ovmi/lib/src/predicates/or.rs b/ovmi/lib/src/predicates/or.rs deleted file mode 100644 index 7d0e7a0daf..0000000000 --- a/ovmi/lib/src/predicates/or.rs +++ /dev/null @@ -1,66 +0,0 @@ -use crate::executor::*; -use crate::predicates::*; - -pub struct OrPredicate<'a, Ext: ExternalCall> { - pub ext: &'a Ext, -} - -impl<'a, Ext: ExternalCall> LogicalConnectiveInterface> for OrPredicate<'a, Ext> { - /// @dev Validates a child node of Or property in game tree. - fn is_valid_challenge( - &self, - inputs: Vec>, - _challenge_inputs: Vec>, - challenge: Property>, - ) -> ExecResult> { - // challenge must be and(not(p[0]), not(p[1]), ...) - require_with_message!( - challenge.predicate_address == Ext::and_address(), - "challenge must be And" - ); - for (i, input) in inputs.iter().enumerate() { - let not_inputs = vec![input.clone()]; - let p = Property { - predicate_address: Ext::not_address(), - inputs: not_inputs, - }; - require!(challenge.inputs.len() > i); - require_with_message!(p.encode() == challenge.inputs[i], "inputs must be same"); - } - Ok(true) - } -} - -impl<'a, Ext: ExternalCall> DecidablePredicateInterface> for OrPredicate<'a, Ext> { - /// @dev Can decide true when all child properties are decided true - fn decide_with_witness( - &self, - inputs: Vec>, - witness: Vec>, - ) -> ExecResult> { - require!(witness.len() > 0); - let index: u128 = Ext::bytes_to_u128(&witness[0])?; - require_with_message!( - (index as usize) < inputs.len(), - "witness must be smaller than inputs length" - ); - let property_bytes = inputs[index as usize].clone(); - let property: Property> = Ext::bytes_to_property(&property_bytes)?; - - Ext::bytes_to_bool( - &self.ext.ext_call( - &property.predicate_address, - PredicateCallInputs::DecidablePredicate( - DecidablePredicateCallInputs::DecideWithWitness { - inputs: property.inputs, - witness: witness - .as_slice() - .get(1..) - .unwrap_or(vec![].as_slice()) - .to_vec(), - }, - ), - )?, - ) - } -} diff --git a/ovmi/lib/src/predicates/there_exists.rs b/ovmi/lib/src/predicates/there_exists.rs deleted file mode 100644 index e19515832c..0000000000 --- a/ovmi/lib/src/predicates/there_exists.rs +++ /dev/null @@ -1,117 +0,0 @@ -use crate::executor::*; -use crate::predicates::*; - -pub struct ThereExistsPredicate<'a, Ext: ExternalCall> { - pub ext: &'a Ext, -} - -impl<'a, Ext: ExternalCall> ThereExistsPredicate<'a, Ext> { - /// @dev Replace placeholder by quantified in propertyBytes - fn replace_variable( - &self, - property_bytes: &Vec, - placeholder: &Vec, - quantified: &Vec, - ) -> ExecResultT, AddressOf> { - // Support property as the variable in ThereExistsSuchThatQuantifier. - // This code enables meta operation which we were calling eval without adding specific "eval" contract. - // For instance, we can write a property like `∀su ∈ SU: su()`. - if Ext::is_placeholder(property_bytes) { - if &Ext::get_input_value(property_bytes) == placeholder { - return Ok(quantified.clone()); - } - } - let mut property: Property> = Ext::bytes_to_property(&property_bytes)?; - if property.predicate_address == Ext::not_address() { - require!(property.inputs.len() > 0); - property.inputs[0] = - self.replace_variable(&property.inputs[0], placeholder, quantified)?; - } else if property.predicate_address == self.ext.ext_address() { - require!(property.inputs.len() > 2); - property.inputs[2] = - self.replace_variable(&property.inputs[2], placeholder, quantified)?; - } else if property.predicate_address == Ext::and_address() - || property.predicate_address == Ext::or_address() - { - property.inputs = property - .inputs - .iter() - .map(|input| self.replace_variable(input, placeholder, quantified)) - .collect::, _>>()?; - } else { - property.inputs = property - .inputs - .iter() - .map(|input| { - if Ext::is_placeholder(input) { - if &Ext::get_input_value(input) == placeholder { - return quantified.clone(); - } - } - input.clone() - }) - .collect(); - } - Ok(property.encode()) - } -} - -impl<'a, Ext: ExternalCall> LogicalConnectiveInterface> - for ThereExistsPredicate<'a, Ext> -{ - /// @dev Validates a child node of ThereExists property in game tree. - fn is_valid_challenge( - &self, - inputs: Vec>, - _challenge_inputs: Vec>, - challenge: Property>, - ) -> ExecResult> { - // challenge must be for(, , not(p)) - require_with_message!( - challenge.predicate_address == Ext::for_all_address(), - "challenge must be ForAllSuchThat" - ); - require!(inputs.len() > 2); - let new_inputs = vec![inputs[2].clone()]; - let p = Property::> { - predicate_address: Ext::not_address().clone(), - inputs: new_inputs, - }; - - require!(challenge.inputs.len() > 2); - require_with_message!(inputs[1] == challenge.inputs[1], "variable must be same"); - require_with_message!(p.encode() == challenge.inputs[2], "inputs must be same"); - Ok(true) - } -} - -impl<'a, Ext: ExternalCall> DecidablePredicateInterface> - for ThereExistsPredicate<'a, Ext> -{ - /// @dev Can decide true when all child properties are decided true - fn decide_with_witness( - &self, - inputs: Vec>, - witness: Vec>, - ) -> ExecResult> { - require!(inputs.len() > 2); - require!(witness.len() > 0); - let property_bytes = self.replace_variable(&inputs[2], &inputs[1], &witness[0])?; - let property: Property> = Ext::bytes_to_property(&property_bytes)?; - Ok(Ext::bytes_to_bool( - &self.ext.ext_call( - &property.predicate_address, - PredicateCallInputs::DecidablePredicate( - DecidablePredicateCallInputs::DecideWithWitness { - inputs: property.inputs, - witness: witness - .as_slice() - .get(1..) - .unwrap_or(vec![].as_slice()) - .to_vec(), - }, - ), - )?, - )?) - } -} diff --git a/ovmi/lib/src/predicates/verify_inclusion.rs b/ovmi/lib/src/predicates/verify_inclusion.rs deleted file mode 100644 index b1ae2b0462..0000000000 --- a/ovmi/lib/src/predicates/verify_inclusion.rs +++ /dev/null @@ -1,57 +0,0 @@ -use crate::executor::*; -use crate::predicates::*; - -pub struct VerifyInclusionPredicate<'a, Ext: ExternalCall> { - pub ext: &'a Ext, -} - -impl<'a, Ext: ExternalCall> AtomicPredicateInterface> - for VerifyInclusionPredicate<'a, Ext> -{ - fn decide(&self, inputs: Vec>) -> ExecResult> { - require!(inputs.len() > 4); - let address = Ext::bytes_to_address(&inputs[1])?; - Ok(self.ext.ext_verify_inclusion_with_root( - Ext::hash_of(&inputs[0]), - address, - &inputs[2][..], // range - &inputs[3][..], // inclusionProof - &inputs[4][..], // bytes32 - )) - } -} -impl<'a, Ext: ExternalCall> AtomicHelperInterface> - for VerifyInclusionPredicate<'a, Ext> -{ - type Hash = HashOf; - fn ext_address(&self) -> AddressOf { - self.ext.ext_address() - } - fn ext_set_predicate_decision( - &self, - game_id: Self::Hash, - decision: bool, - ) -> ExecResult> { - self.ext.ext_set_predicate_decision(game_id, decision) - } - fn ext_get_property_id(&self, property: &Property>) -> Self::Hash { - self.ext.ext_get_property_id(property) - } -} - -impl<'a, Ext: ExternalCall> DecidablePredicateInterface> - for VerifyInclusionPredicate<'a, Ext> -{ - fn decide_with_witness( - &self, - inputs: Vec>, - _witness: Vec>, - ) -> ExecResult> { - Self::decide(self, inputs) - } -} - -impl<'a, Ext: ExternalCall> BaseAtomicPredicateInterface> - for VerifyInclusionPredicate<'a, Ext> -{ -} diff --git a/ovmi/lib/src/prepare/mod.rs b/ovmi/lib/src/prepare/mod.rs deleted file mode 100644 index 3eb5987fb3..0000000000 --- a/ovmi/lib/src/prepare/mod.rs +++ /dev/null @@ -1,189 +0,0 @@ -use crate::executor::*; -use crate::predicates::*; -use crate::*; - -#[cfg(feature = "std")] -use std::fs::File; -#[cfg(feature = "std")] -use std::io::Read; - -#[cfg(feature = "std")] -mod serializable_predicates; - -#[cfg(feature = "std")] -pub use serializable_predicates::*; - -#[cfg(test)] -mod tests; - -#[cfg(feature = "std")] -pub fn compile_from_json(json: &str) -> Result { - let ret: CompiledPredicateSerializable = serde_json::from_str(json)?; - Ok(ret.into()) -} - -#[cfg(feature = "std")] -pub fn load_predicate_json(filename: &str) -> String { - let path = ["tests/", filename].concat(); - let mut file = File::open(path).expect("file laod error"); - let mut predicate_json = String::new(); - file.read_to_string(&mut predicate_json) - .expect("something went wrong reading the file"); - println!("predicate json : {:?}", predicate_json); - predicate_json -} - -use crate::compiled_predicates::VarType; - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Debug))] -pub enum VarValue
{ - Address(Address), - Bytes(Vec), -} - -pub fn executable_from_compiled<'a, Ext: ExternalCall>( - ext: &'a Ext, - code: CompiledPredicate, - payout: AddressOf, - address_inputs: BTreeMap, AddressOf>, - bytes_inputs: BTreeMap, Vec>, -) -> CompiledExecutable<'a, Ext> { - // mapping constants[ hash(name) ] = var_type. - let constants = code.constants.clone().map_or(BTreeMap::new(), |var| { - var.iter() - .map(|con| { - ( - Ext::Hashing::hash(con.name.as_slice()), - con.var_type.clone(), - ) - }) - .collect::, VarType>>() - }); - CompiledExecutable { - ext, - payout, - code, - constants, - address_inputs, - bytes_inputs, - } -} - -pub fn logical_connective_executable_from_address<'a, Ext: ExternalCall>( - ext: &'a Ext, - address: &AddressOf, -) -> Option> where -{ - match address { - x if x == &Ext::not_address() => { - Some(LogicalConnectiveExecutable::Not(NotPredicate { ext })) - } - x if x == &Ext::and_address() => { - Some(LogicalConnectiveExecutable::And(AndPredicate { ext })) - } - x if x == &Ext::or_address() => Some(LogicalConnectiveExecutable::Or(OrPredicate { ext })), - x if x == &Ext::for_all_address() => { - Some(LogicalConnectiveExecutable::ForAll(ForAllPredicate { ext })) - } - x if x == &Ext::there_exists_address() => Some(LogicalConnectiveExecutable::ThereExists( - ThereExistsPredicate { ext }, - )), - _ => None, - } -} - -pub fn deciable_executable_from_address<'a, Ext: ExternalCall>( - ext: &'a Ext, - address: &AddressOf, -) -> Option> where -{ - match address { - x if x == &Ext::not_address() => Some(DecidableExecutable::Not(NotPredicate { ext })), - x if x == &Ext::and_address() => Some(DecidableExecutable::And(AndPredicate { ext })), - x if x == &Ext::or_address() => Some(DecidableExecutable::Or(OrPredicate { ext })), - x if x == &Ext::for_all_address() => { - Some(DecidableExecutable::ForAll(ForAllPredicate { ext })) - } - x if x == &Ext::there_exists_address() => { - Some(DecidableExecutable::ThereExists(ThereExistsPredicate { - ext, - })) - } - x if x == &Ext::equal_address() => Some(DecidableExecutable::Equal(EqualPredicate { ext })), - x if x == &Ext::is_contained_address() => { - Some(DecidableExecutable::IsContained(IsContainedPredicate { - ext, - })) - } - x if x == &Ext::is_less_address() => { - Some(DecidableExecutable::IsLess(IsLessThanPredicate { ext })) - } - x if x == &Ext::is_stored_address() => { - Some(DecidableExecutable::IsStored(IsStoredPredicate { ext })) - } - x if x == &Ext::is_valid_signature_address() => Some( - DecidableExecutable::IsValidSignature(IsValidSignaturePredicate { ext }), - ), - x if x == &Ext::verify_inclusion_address() => Some(DecidableExecutable::VerifyInclusion( - VerifyInclusionPredicate { ext }, - )), - _ => None, - } -} - -pub fn atomic_executable_from_address<'a, Ext: ExternalCall>( - ext: &'a Ext, - address: &AddressOf, -) -> Option> where -{ - match address { - x if x == &Ext::equal_address() => Some(AtomicExecutable::Equal(EqualPredicate { ext })), - x if x == &Ext::is_contained_address() => { - Some(AtomicExecutable::IsContained(IsContainedPredicate { ext })) - } - x if x == &Ext::is_less_address() => { - Some(AtomicExecutable::IsLess(IsLessThanPredicate { ext })) - } - x if x == &Ext::is_stored_address() => { - Some(AtomicExecutable::IsStored(IsStoredPredicate { ext })) - } - x if x == &Ext::is_valid_signature_address() => Some(AtomicExecutable::IsValidSignature( - IsValidSignaturePredicate { ext }, - )), - x if x == &Ext::verify_inclusion_address() => Some(AtomicExecutable::VerifyInclusion( - VerifyInclusionPredicate { ext }, - )), - _ => None, - } -} - -pub fn base_atomic_executable_from_address<'a, Ext: ExternalCall>( - ext: &'a Ext, - address: &AddressOf, -) -> Option> where -{ - match address { - x if x == &Ext::equal_address() => { - Some(BaseAtomicExecutable::Equal(EqualPredicate { ext })) - } - x if x == &Ext::is_contained_address() => { - Some(BaseAtomicExecutable::IsContained(IsContainedPredicate { - ext, - })) - } - x if x == &Ext::is_less_address() => { - Some(BaseAtomicExecutable::IsLess(IsLessThanPredicate { ext })) - } - x if x == &Ext::is_stored_address() => { - Some(BaseAtomicExecutable::IsStored(IsStoredPredicate { ext })) - } - x if x == &Ext::is_valid_signature_address() => Some( - BaseAtomicExecutable::IsValidSignature(IsValidSignaturePredicate { ext }), - ), - x if x == &Ext::verify_inclusion_address() => Some(BaseAtomicExecutable::VerifyInclusion( - VerifyInclusionPredicate { ext }, - )), - _ => None, - } -} diff --git a/ovmi/lib/src/prepare/serializable_predicates.rs b/ovmi/lib/src/prepare/serializable_predicates.rs deleted file mode 100644 index d3425ede55..0000000000 --- a/ovmi/lib/src/prepare/serializable_predicates.rs +++ /dev/null @@ -1,421 +0,0 @@ -use crate::compiled_predicates::*; -use crate::*; -use codec::{Decode, Encode}; -#[cfg(feature = "std")] -use serde::{Deserialize, Serialize}; - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -pub enum PredicateTypeSerializable { - CompiledPredicate, - IntermediateCompiledPredicate, - AtomicProposition, - AtomicPredicateCall, - InputPredicateCall, - VariablePredicateCall, - CompiledPredicateCall, - CompiledInput, - ConstantInput, - LabelInput, - NormalInput, - VariableInput, - SelfInput, -} - -impl From for PredicateType { - fn from(f: PredicateTypeSerializable) -> PredicateType { - match f { - PredicateTypeSerializable::CompiledPredicate => PredicateType::CompiledPredicate, - PredicateTypeSerializable::IntermediateCompiledPredicate => { - PredicateType::IntermediateCompiledPredicate - } - PredicateTypeSerializable::AtomicProposition => PredicateType::AtomicProposition, - PredicateTypeSerializable::AtomicPredicateCall => PredicateType::AtomicPredicateCall, - PredicateTypeSerializable::InputPredicateCall => PredicateType::InputPredicateCall, - PredicateTypeSerializable::VariablePredicateCall => { - PredicateType::VariablePredicateCall - } - PredicateTypeSerializable::CompiledPredicateCall => { - PredicateType::CompiledPredicateCall - } - PredicateTypeSerializable::CompiledInput => PredicateType::CompiledInput, - PredicateTypeSerializable::ConstantInput => PredicateType::ConstantInput, - PredicateTypeSerializable::LabelInput => PredicateType::LabelInput, - PredicateTypeSerializable::NormalInput => PredicateType::NormalInput, - PredicateTypeSerializable::VariableInput => PredicateType::VariableInput, - PredicateTypeSerializable::SelfInput => PredicateType::SelfInput, - } - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -pub enum VarTypeSerializable { - Address, - Bytes, -} - -impl From for VarType { - fn from(f: VarTypeSerializable) -> VarType { - match f { - VarTypeSerializable::Address => VarType::Address, - VarTypeSerializable::Bytes => VarType::Bytes, - } - } -} - -/// Compiled Property definition -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -pub struct CompiledPredicateSerializable { - pub r#type: PredicateTypeSerializable, - pub name: String, - pub input_defs: Vec, - pub contracts: Vec, - pub constants: Option>, - pub entry_point: String, -} - -impl From for CompiledPredicate { - fn from(f: CompiledPredicateSerializable) -> CompiledPredicate { - CompiledPredicate { - r#type: f.r#type.into(), - name: f.name.as_bytes().to_vec(), - input_defs: f.input_defs.iter().map(|a| a.as_bytes().to_vec()).collect(), - contracts: f.contracts.iter().map(|a| a.clone().into()).collect(), - constants: match f.constants { - Some(constants) => Some(constants.iter().map(|a| a.clone().into()).collect()), - None => None, - }, - entry_point: f.entry_point.as_bytes().to_vec(), - } - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -pub struct ConstantVariableSerializable { - pub var_type: VarTypeSerializable, - pub name: String, -} - -impl From for ConstantVariable { - fn from(f: ConstantVariableSerializable) -> ConstantVariable { - ConstantVariable { - var_type: f.var_type.into(), - name: f.name.as_bytes().to_vec(), - } - } -} - -/// IntermediateCompiledPredicate is core of compilation which has only atomic propositions as its inputs. -/// When we have for a in B() {Foo(a) and Bar(a)}, -/// "for a in B() {...}" and "Foo(a) and Bar(a)" are IntermediateCompiledPredicate. -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -pub struct IntermediateCompiledPredicateSerializable { - pub r#type: PredicateTypeSerializable, - pub name: String, - pub original_predicate_name: String, - // logical connective - pub connective: LogicalConnectiveSerializable, - pub input_defs: Vec, - pub inputs: Vec, - pub property_inputs: Vec, -} - -impl From for IntermediateCompiledPredicate { - fn from(f: IntermediateCompiledPredicateSerializable) -> IntermediateCompiledPredicate { - IntermediateCompiledPredicate { - r#type: f.r#type.into(), - name: f.name.as_bytes().to_vec(), - original_predicate_name: f.original_predicate_name.as_bytes().to_vec(), - connective: f.connective.into(), - input_defs: f.input_defs.iter().map(|a| a.as_bytes().to_vec()).collect(), - inputs: f.inputs.iter().map(|a| a.clone().into()).collect(), - property_inputs: f.property_inputs.iter().map(|a| a.clone().into()).collect(), - } - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -#[cfg_attr(feature = "std", serde(untagged))] -pub enum AtomicPropositionOrPlaceholderSerializable { - AtomicProposition(AtomicPropositionSerializable), - Placeholder(String), -} - -impl From for AtomicPropositionOrPlaceholder { - fn from(f: AtomicPropositionOrPlaceholderSerializable) -> AtomicPropositionOrPlaceholder { - match f { - AtomicPropositionOrPlaceholderSerializable::AtomicProposition(a) => { - AtomicPropositionOrPlaceholder::AtomicProposition(a.clone().into()) - } - AtomicPropositionOrPlaceholderSerializable::Placeholder(a) => { - AtomicPropositionOrPlaceholder::Placeholder(a.as_bytes().to_vec()) - } - } - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -pub struct AtomicPropositionSerializable { - pub r#type: PredicateTypeSerializable, - pub predicate: PredicateCallSerializable, - pub inputs: Vec, - pub is_compiled: Option, -} - -impl From for AtomicProposition { - fn from(f: AtomicPropositionSerializable) -> AtomicProposition { - AtomicProposition { - r#type: f.r#type.into(), - predicate: f.predicate.into(), - inputs: f.inputs.iter().map(|a| a.clone().into()).collect(), - is_compiled: f.is_compiled, - } - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -#[cfg_attr(feature = "std", serde(untagged))] -pub enum PredicateCallSerializable { - AtomicPredicateCall(AtomicPredicateCallSerializable), - InputPredicateCall(InputPredicateCallSerializable), - VariablePredicateCall(VariablePredicateCallSerializable), - CompiledPredicateCall(CompiledPredicateCallSerializable), -} - -impl From for PredicateCall { - fn from(f: PredicateCallSerializable) -> PredicateCall { - match f { - PredicateCallSerializable::AtomicPredicateCall(a) => { - PredicateCall::AtomicPredicateCall(a.clone().into()) - } - PredicateCallSerializable::InputPredicateCall(a) => { - PredicateCall::InputPredicateCall(a.clone().into()) - } - PredicateCallSerializable::VariablePredicateCall(a) => { - PredicateCall::VariablePredicateCall(a.clone().into()) - } - PredicateCallSerializable::CompiledPredicateCall(a) => { - PredicateCall::CompiledPredicateCall(a.clone().into()) - } - } - } -} - -/// e.g. IsValidSignature() -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -pub struct AtomicPredicateCallSerializable { - pub r#type: PredicateTypeSerializable, - pub source: String, -} - -impl From for AtomicPredicateCall { - fn from(f: AtomicPredicateCallSerializable) -> AtomicPredicateCall { - AtomicPredicateCall { - r#type: f.r#type.into(), - source: f.source.as_bytes().to_vec(), - } - } -} - -/// e.g. a() of "def Foo(a) := a()" -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -pub struct InputPredicateCallSerializable { - pub r#type: PredicateTypeSerializable, - pub source: NormalInputSerializable, -} - -impl From for InputPredicateCall { - fn from(f: InputPredicateCallSerializable) -> InputPredicateCall { - InputPredicateCall { - r#type: f.r#type.into(), - source: f.source.into(), - } - } -} - -/// e.g. su() of "def Foo(a) := with SU(a) as su {su()}" -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -pub struct VariablePredicateCallSerializable { - pub r#type: PredicateTypeSerializable, -} - -impl From for VariablePredicateCall { - fn from(f: VariablePredicateCallSerializable) -> VariablePredicateCall { - VariablePredicateCall { - r#type: f.r#type.into(), - } - } -} - -/// For predicates dynamic linking -/// e.g. Confsig() user defined predicate -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -pub struct CompiledPredicateCallSerializable { - pub r#type: PredicateTypeSerializable, - pub source: String, -} - -impl From for CompiledPredicateCall { - fn from(f: CompiledPredicateCallSerializable) -> CompiledPredicateCall { - CompiledPredicateCall { - r#type: f.r#type.into(), - source: f.source.as_bytes().to_vec(), - } - } -} - -/// CompiledInput indicates which value to pass to PredicateCall as input of predicate -/// For example,parent_property.inputs[0].inputs[1] is NormalInput andinput_index is 0 and children is [1]. -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -#[cfg_attr(feature = "std", serde(untagged))] -pub enum CompiledInputSerializable { - ConstantInput(ConstantInputSerializable), - LabelInput(LabelInputSerializable), - NormalInput(NormalInputSerializable), - VariableInput(VariableInputSerializable), - SelfInput(SelfInputSerializable), -} - -impl From for CompiledInput { - fn from(f: CompiledInputSerializable) -> CompiledInput { - match f { - CompiledInputSerializable::ConstantInput(a) => { - CompiledInput::ConstantInput(a.clone().into()) - } - CompiledInputSerializable::LabelInput(a) => CompiledInput::LabelInput(a.clone().into()), - CompiledInputSerializable::NormalInput(a) => { - CompiledInput::NormalInput(a.clone().into()) - } - CompiledInputSerializable::VariableInput(a) => { - CompiledInput::VariableInput(a.clone().into()) - } - CompiledInputSerializable::SelfInput(a) => CompiledInput::SelfInput(a.clone().into()), - } - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -pub struct ConstantInputSerializable { - pub r#type: PredicateTypeSerializable, - pub name: String, -} - -impl From for ConstantInput { - fn from(f: ConstantInputSerializable) -> ConstantInput { - ConstantInput { - r#type: f.r#type.into(), - name: f.name.as_bytes().to_vec(), - } - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -pub struct LabelInputSerializable { - pub r#type: PredicateTypeSerializable, - pub label: String, -} - -impl From for LabelInput { - fn from(f: LabelInputSerializable) -> LabelInput { - LabelInput { - r#type: f.r#type.into(), - label: f.label.as_bytes().to_vec(), - } - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -pub struct NormalInputSerializable { - pub r#type: PredicateTypeSerializable, - pub input_index: u8, - pub children: Vec, -} - -impl From for NormalInput { - fn from(f: NormalInputSerializable) -> NormalInput { - NormalInput { - r#type: f.r#type.into(), - input_index: f.input_index, - children: f.children, - } - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -pub struct VariableInputSerializable { - pub r#type: PredicateTypeSerializable, - pub placeholder: String, - pub children: Vec, -} - -impl From for VariableInput { - fn from(f: VariableInputSerializable) -> VariableInput { - VariableInput { - r#type: f.r#type.into(), - placeholder: f.placeholder.as_bytes().to_vec(), - children: f.children, - } - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -pub struct SelfInputSerializable { - pub r#type: PredicateTypeSerializable, - pub children: Vec, -} - -impl From for SelfInput { - fn from(f: SelfInputSerializable) -> SelfInput { - SelfInput { - r#type: f.r#type.into(), - children: f.children, - } - } -} - -#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] -pub enum LogicalConnectiveSerializable { - And, - ForAllSuchThat, - Not, - Or, - ThereExistsSuchThat, -} - -impl From for LogicalConnective { - fn from(f: LogicalConnectiveSerializable) -> LogicalConnective { - match f { - LogicalConnectiveSerializable::And => LogicalConnective::And, - LogicalConnectiveSerializable::ForAllSuchThat => LogicalConnective::ForAllSuchThat, - LogicalConnectiveSerializable::Not => LogicalConnective::Not, - LogicalConnectiveSerializable::Or => LogicalConnective::Or, - LogicalConnectiveSerializable::ThereExistsSuchThat => { - LogicalConnective::ThereExistsSuchThat - } - } - } -} diff --git a/ovmi/lib/src/prepare/tests.rs b/ovmi/lib/src/prepare/tests.rs deleted file mode 100644 index 53a0fe5a26..0000000000 --- a/ovmi/lib/src/prepare/tests.rs +++ /dev/null @@ -1,77 +0,0 @@ -#![cfg(test)] -use super::super::*; -use super::load_predicate_json; -use crate::compiled_predicates::*; -use codec::{Decode, Encode}; - -#[test] -fn ownership_predicate_test() { - let ownership_predicate_str = load_predicate_json("ownership.json"); - let ans = CompiledPredicate { - r#type: PredicateType::CompiledPredicate, - name: b"Ownership".to_vec(), - input_defs: vec![b"owner".to_vec(), b"tx".to_vec()], - contracts: vec![IntermediateCompiledPredicate { - r#type: PredicateType::IntermediateCompiledPredicate, - original_predicate_name: b"Ownership".to_vec(), - name: b"OwnershipT".to_vec(), - connective: LogicalConnective::ThereExistsSuchThat, - input_defs: vec![b"OwnershipT".to_vec(), b"owner".to_vec(), b"tx".to_vec()], - inputs: vec![ - AtomicPropositionOrPlaceholder::Placeholder(b"signatures,KEY,${tx}".to_vec()), - AtomicPropositionOrPlaceholder::Placeholder(b"v0".to_vec()), - AtomicPropositionOrPlaceholder::AtomicProposition(AtomicProposition { - r#type: PredicateType::AtomicProposition, - predicate: PredicateCall::AtomicPredicateCall(AtomicPredicateCall { - r#type: PredicateType::AtomicPredicateCall, - source: b"IsValidSignature".to_vec(), - }), - inputs: vec![ - CompiledInput::NormalInput(NormalInput { - r#type: PredicateType::NormalInput, - input_index: 2, - children: vec![], - }), - CompiledInput::VariableInput(VariableInput { - r#type: PredicateType::VariableInput, - placeholder: b"v0".to_vec(), - children: vec![], - }), - CompiledInput::NormalInput(NormalInput { - r#type: PredicateType::NormalInput, - input_index: 1, - children: vec![], - }), - CompiledInput::ConstantInput(ConstantInput { - r#type: PredicateType::ConstantInput, - name: b"secp256k1".to_vec(), - }), - ], - is_compiled: None, - }), - ], - property_inputs: vec![], - }], - constants: Some(vec![ConstantVariable { - var_type: VarType::Bytes, - name: b"secp256k1".to_vec(), - }]), - entry_point: b"OwnershipT".to_vec(), - }; - let res = match compile_from_json(ownership_predicate_str.as_str()) { - Ok(res) => res, - Err(err) => { - println!("ERR: {:?}", err.classify()); - assert!(false); - return; - } - }; - assert_eq!(res, ans); - let encoded_res = res.encode(); - let encoded_ans = ans.encode(); - assert_eq!(encoded_res, encoded_ans); - let decoded_res: CompiledPredicate = Decode::decode(&mut &encoded_res[..]).unwrap(); - let decoded_ans: CompiledPredicate = Decode::decode(&mut &encoded_ans[..]).unwrap(); - assert_eq!(decoded_res, decoded_ans); - assert_eq!(res, decoded_ans); -} diff --git a/ovmi/lib/src/tests.rs b/ovmi/lib/src/tests.rs deleted file mode 100644 index 6ee1c3f269..0000000000 --- a/ovmi/lib/src/tests.rs +++ /dev/null @@ -1,319 +0,0 @@ -use crate::executor::*; -use crate::mock::*; -use crate::predicates::*; -use crate::prepare::*; -use alloc::collections::btree_map::BTreeMap; -use codec::Encode; -use sp_core::{crypto::Pair, ecdsa::Pair as ECDSAPair, KeccakHasher}; - -macro_rules! assert_require { - ($res:expr, $msg:expr) => { - assert_eq!( - $res.expect_err("Exepcted Error."), - ExecError::
::Require { msg: $msg } - ) - }; -} - -fn make_decide_true(inputs: Vec>) -> PredicateCallInputs
{ - PredicateCallInputs::BaseAtomicPredicate::
(BaseAtomicPredicateCallInputs::DecideTrue { - inputs, - }) -} - -fn make_decide_true_ex( - inputs: Vec>, - witness: Vec>, -) -> PredicateCallInputs
{ - PredicateCallInputs::CompiledPredicate::
(CompiledPredicateCallInputs::DecideTrue { - inputs, - witness, - }) -} - -#[test] -fn equal_predicate_decide_true() { - let ext = MockExternalCall::init(); - let input0 = hex::decode("0000000011112222").unwrap(); - let input1 = hex::decode("0000000012345678").unwrap(); - // true case - { - let input_data = make_decide_true(vec![input0.clone(), input0.clone()]); - let res = - MockExternalCall::bytes_to_bool(&ext.call_execute(&EQUAL_ADDRESS, input_data).unwrap()) - .unwrap(); - assert!(res); - } - - // false case - { - let input_data = make_decide_true(vec![input0.clone(), input1.clone()]); - let res = ext.call_execute(&EQUAL_ADDRESS, input_data); - assert_require!(res, "2 inputs must be equal"); - } -} - -#[test] -fn is_less_than_predicate_decide_true() { - let ext = MockExternalCall::init(); - let input0: Vec = (0 as u128).encode(); - let input1: Vec = (1 as u128).encode(); - - // true case - { - let input_data = make_decide_true(vec![input0.clone(), input1.clone()]); - let res = MockExternalCall::bytes_to_bool( - &ext.call_execute(&IS_LESS_ADDRESS, input_data).unwrap(), - ) - .unwrap(); - assert!(res); - } - - // false case - { - let input_data = make_decide_true(vec![input1.clone(), input0.clone()]); - let res = ext.call_execute(&IS_LESS_ADDRESS, input_data); - assert_require!(res, "first input is not less than second input"); - } -} - -#[test] -fn is_stored_decide_true() { - let mut ext = MockExternalCall::init(); - let pair: ECDSAPair = ECDSAPair::from_seed(&[1; 32]); - let miss_pair: ECDSAPair = ECDSAPair::from_seed(&[2; 32]); - let address: Address = to_account(pair.public().as_ref()); - let miss_address: Address = to_account(miss_pair.public().as_ref()); - - let address_bytes = address.encode(); - let key = hex::decode("0000000011112222").unwrap(); - let value = hex::decode("0000000011112222").unwrap(); - let false_value = hex::decode("0000000012345678").unwrap(); - - ext.set_stored(&address, &key[..], &value[..]); - - // true case - { - let input_data = make_decide_true(vec![address_bytes.clone(), key.clone(), value.clone()]); - let res = MockExternalCall::bytes_to_bool( - &ext.call_execute(&IS_STORED_ADDRESS, input_data).unwrap(), - ) - .unwrap(); - assert!(res); - } - - // false case (value) - { - let input_data = make_decide_true(vec![address_bytes.clone(), key.clone(), false_value]); - let res = ext.call_execute(&IS_STORED_ADDRESS, input_data); - assert_require!(res, "must decide true"); - } - - // false case (address) - { - let input_data = make_decide_true(vec![miss_address.encode(), key.clone(), value]); - let res = ext.call_execute(&IS_STORED_ADDRESS, input_data); - assert_require!(res, "must decide true"); - } -} - -#[test] -fn is_valid_signature_decide_true() { - let ext = MockExternalCall::init(); - let pair: ECDSAPair = ECDSAPair::from_seed(&[1; 32]); - let miss_pair: ECDSAPair = ECDSAPair::from_seed(&[2; 32]); - let address: Address = to_account(pair.public().as_ref()); - let miss_address: Address = to_account(miss_pair.public().as_ref()); - - let address_bytes = address.encode(); - let message = b"message".to_vec(); - let message_hash = KeccakHasher::hash(&message[..]); - let signature: Vec = (pair.sign(&message_hash.0).as_ref() as &[u8]).into(); - let miss_signature: Vec = (miss_pair.sign(&message_hash.0).as_ref() as &[u8]).into(); - let verifier = b"secp256k1".to_vec(); - - // Use check by frontend. - println!("message_hash: {:?}", message_hash); - println!("signature : {:?}", message_hash); - - // true case - { - let input_data = make_decide_true(vec![ - message.clone(), - signature.clone(), - address_bytes.clone(), - verifier.clone(), - ]); - let res = MockExternalCall::bytes_to_bool( - &ext.call_execute(&IS_VALID_SIGNATURE_ADDRESS, input_data) - .unwrap(), - ) - .unwrap(); - assert!(res); - } - - // false case (value) - { - let input_data = make_decide_true(vec![ - b"no_message".to_vec(), - signature.clone(), - address_bytes.clone(), - verifier.clone(), - ]); - let res = ext.call_execute(&IS_VALID_SIGNATURE_ADDRESS, input_data); - assert_require!( - res, - "_inputs[1] must be signature of _inputs[0] by _inputs[2]" - ); - } - - // false case (address) - { - let input_data = make_decide_true(vec![ - message.clone(), - signature.clone(), - miss_address.encode(), - verifier.clone(), - ]); - let res = ext.call_execute(&IS_VALID_SIGNATURE_ADDRESS, input_data); - assert_require!( - res, - "_inputs[1] must be signature of _inputs[0] by _inputs[2]" - ); - } - - // false case (address) - { - let input_data = make_decide_true(vec![ - message.clone(), - miss_signature.clone(), - address.encode(), - verifier.clone(), - ]); - let res = ext.call_execute(&IS_VALID_SIGNATURE_ADDRESS, input_data); - assert_require!( - res, - "_inputs[1] must be signature of _inputs[0] by _inputs[2]" - ); - } -} - -#[test] -fn ownership_predicate_true() { - let mut ext = MockExternalCall::init(); - let ownership_predicate_str = load_predicate_json("ownership.json"); - let compiled_predicate = compile_from_json(ownership_predicate_str.as_str()).unwrap(); - let ownership_address = ext.deploy( - compiled_predicate, - PAY_OUT_CONTRACT_ADDRESS.clone(), - BTreeMap::new(), - BTreeMap::new(), - ); - println!("ownership address: {:?}", ownership_address); - - let pair: ECDSAPair = ECDSAPair::from_seed(&[1; 32]); - let wallet_address: Address = to_account(pair.public().as_ref()); - let label = b"LOwnershipT".encode(); - let transaction = hex!["00000000000000000000000000000000000000050000000000000000000000001080000000000000000000000000000000000000000100000000000000000000000080000000000000000000000000000000000a000000000000000000000000000000400a0000000000000000000000000000000901000000000000000000000000000000000000000200000000000000000000000004800000000000000000000000000000000000000003000000000000000000000000"].to_vec(); - let tx_hash = KeccakHasher::hash(&transaction[..]); - let signature: Vec = (pair.sign(&tx_hash.0).as_ref() as &[u8]).into(); - let signature_dummy = - hex!["2131311021311102131311021313110213131102131311021313110213131102"].to_vec(); - - println!("transaction : {:?}", transaction); - println!("signature : {:?}", signature); - println!("wallet : {:?}", wallet_address); - - // success case(address) - { - let input_data = make_decide_true_ex( - vec![label.clone(), wallet_address.encode(), transaction.clone()], - vec![signature.clone()], - ); - let res = ext.call_execute(&ownership_address, input_data); - let ret: bool = MockExternalCall::bytes_to_bool(&res.unwrap()).unwrap(); - assert!(ret); - } - - // false case (address) - { - let input_data = make_decide_true_ex( - vec![label, wallet_address.encode(), transaction], - vec![signature_dummy], - ); - let res = ext.call_execute(&ownership_address, input_data); - assert_require!( - res, - "_inputs[1] must be signature of _inputs[0] by _inputs[2]" - ); - } -} - -#[test] -fn verify_inclusion_decide_true() { - // tested in plasma module. - // let mut ext = MockExternalCall::init(); - // let address_1: Address = 88; - // let address_2: Address = 99; - // - // let leaf = b"leaf".to_vec(); - // let token = Address::default().encode(); - // let range = Range { - // start: 100, - // end: 200, - // } - // .encode(); - // let inclusion_proof: Vec<( - // (Address, u128, Vec<(Hash, Address)>), - // (u128, u128, Vec<(Hash, u128)>), - // )> = vec![( - // ( - // address_1, - // 0, - // vec![( - // Hash::from_str("dd779be20b84ced84b7cbbdc8dc98d901ecd198642313d35d32775d75d916d3a") - // .unwrap(), - // address_2, - // )], - // ), - // ( - // 0, - // 0, - // vec![ - // ( - // Hash::from_str( - // "036491cc10808eeb0ff717314df6f19ba2e232d04d5f039f6fa382cae41641da", - // ) - // .unwrap(), - // 7, - // ), - // ( - // Hash::from_str( - // "ef583c07cae62e3a002a9ad558064ae80db17162801132f9327e8bb6da16ea8a", - // ) - // .unwrap(), - // 5000, - // ), - // ], - // ), - // )]; - // let inclusion_proof_bytes = inclusion_proof.encode(); - // let root = Hash::from_str("ef583c07cae62e3a002a9ad558064ae80db0000000000000000000b6da16ea8a") - // .unwrap() - // .encode(); - // - // // true case - // { - // let input_data = make_decide_true(vec![ - // leaf.clone(), - // token.clone(), - // range.clone(), - // inclusion_proof_bytes.clone(), - // root.clone(), - // ]); - // let res = ext - // .call_execute(&VERIFY_INCLUAION_ADDRESS, input_data) - // .unwrap(); - // assert!(res); - // } -} diff --git a/ovmi/lib/tests/ownership.json b/ovmi/lib/tests/ownership.json deleted file mode 100644 index bc5ed62fb5..0000000000 --- a/ovmi/lib/tests/ownership.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "type": "CompiledPredicate", - "name": "Ownership", - "inputDefs": [ - "owner", - "tx" - ], - "contracts": [ - { - "type": "IntermediateCompiledPredicate", - "originalPredicateName": "Ownership", - "name": "OwnershipT", - "connective": "ThereExistsSuchThat", - "inputDefs": [ - "OwnershipT", - "owner", - "tx" - ], - "inputs": [ - "signatures,KEY,${tx}", - "v0", - { - "type": "AtomicProposition", - "predicate": { - "type": "AtomicPredicateCall", - "source": "IsValidSignature" - }, - "inputs": [ - { - "type": "NormalInput", - "inputIndex": 2, - "children": [] - }, - { - "type": "VariableInput", - "placeholder": "v0", - "children": [] - }, - { - "type": "NormalInput", - "inputIndex": 1, - "children": [] - }, - { - "type": "ConstantInput", - "name": "secp256k1" - } - ] - } - ], - "propertyInputs": [] - } - ], - "entryPoint": "OwnershipT", - "constants": [ - { - "varType": "bytes", - "name": "secp256k1" - } - ] -} diff --git a/third-party/nix/release.nix b/third-party/nix/release.nix index cb19db0bdc..97ef88e5f9 100644 --- a/third-party/nix/release.nix +++ b/third-party/nix/release.nix @@ -3,11 +3,10 @@ let pkgs = import { overlays = [ moz_overlay ]; }; - channel = pkgs.rustChannelOf { date = "2020-08-20"; channel = "nightly"; }; + channel = pkgs.rustChannelOf { date = "2020-12-29"; channel = "nightly"; }; in { inherit pkgs; rust-nightly = channel.rust.override { targets = [ "wasm32-unknown-unknown" ]; - extensions = [ "rustfmt-preview" ]; }; } diff --git a/third-party/nix/shell.nix b/third-party/nix/shell.nix index 933267b1fd..61f26cacfd 100644 --- a/third-party/nix/shell.nix +++ b/third-party/nix/shell.nix @@ -4,14 +4,11 @@ with release.pkgs; with llvmPackages; -stdenv.mkDerivation { - name = "plasm-nix-shell"; +mkShell { nativeBuildInputs = [ clang ]; buildInputs = [ release.rust-nightly - pkg-config - openssl - cmake + zlib ] ++ stdenv.lib.optionals stdenv.isDarwin [ darwin.apple_sdk.frameworks.Security ]; diff --git a/vendor/frontier b/vendor/frontier index 3e7fd80c7b..7e8ceba4bd 160000 --- a/vendor/frontier +++ b/vendor/frontier @@ -1 +1 @@ -Subproject commit 3e7fd80c7b96154774697af09cde41d50213911e +Subproject commit 7e8ceba4bdf1d50eccf1eb633f0193691d8a2827