From 498d5c06605ed5612426358334cb159d19162a96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Tue, 21 Mar 2017 21:26:05 +0100 Subject: [PATCH 01/11] Updating syntex et al (#4983) * Migrating to new syntex * Updating to latest syntex * Another fix for nightly --- Cargo.lock | 111 +++++++++++-------- dapps/Cargo.toml | 2 +- dapps/js-glue/Cargo.toml | 14 +-- dapps/js-glue/build.rs | 4 +- dapps/js-glue/src/build.rs | 5 +- dapps/js-glue/src/codegen.rs | 56 +++++----- dapps/js-glue/src/lib.rs | 1 - ipc/codegen/Cargo.toml | 14 +-- ipc/codegen/build.rs | 4 +- ipc/codegen/src/codegen.rs | 179 ++++++++++++++++--------------- ipc/codegen/src/lib.rs | 8 +- ipc/codegen/src/serialization.rs | 37 ++++--- js/Cargo.precompiled.toml | 4 +- js/Cargo.toml | 6 +- signer/Cargo.toml | 2 +- stratum/src/traits.rs | 4 +- 16 files changed, 240 insertions(+), 211 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 02ac8995d..e61658e16 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -102,10 +102,10 @@ dependencies = [ [[package]] name = "aster" -version = "0.17.0" +version = "0.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "syntex_syntax 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_syntax 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -455,7 +455,7 @@ dependencies = [ "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "mime 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "mime_guess 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-dapps-glue 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "parity-hash-fetch 1.7.0", "parity-reactor 0.1.0", "parity-ui 1.7.0", @@ -502,11 +502,11 @@ dependencies = [ name = "ethcore-ipc-codegen" version = "1.7.0" dependencies = [ - "aster 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", - "quasi 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "quasi_codegen 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "syntex 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", - "syntex_syntax 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", + "aster 0.41.0 (registry+https://github.com/rust-lang/crates.io-index)", + "quasi 0.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "quasi_codegen 0.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_syntax 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -671,7 +671,7 @@ dependencies = [ "ethcore-util 1.7.0", "jsonrpc-core 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-dapps-glue 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "parity-ui 1.7.0", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1598,16 +1598,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "parity-dapps-glue" -version = "1.4.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "aster 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", + "aster 0.41.0 (registry+https://github.com/rust-lang/crates.io-index)", "glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", "mime_guess 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", - "quasi 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "quasi_codegen 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "syntex 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", - "syntex_syntax 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", + "quasi 0.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "quasi_codegen 0.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_syntax 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1685,16 +1685,16 @@ dependencies = [ name = "parity-ui" version = "1.7.0" dependencies = [ - "parity-ui-dev 1.4.0", + "parity-ui-dev 1.7.0", "parity-ui-precompiled 1.4.0 (git+https://github.com/ethcore/js-precompiled.git)", "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "parity-ui-dev" -version = "1.4.0" +version = "1.7.0" dependencies = [ - "parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-dapps-glue 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1702,7 +1702,7 @@ name = "parity-ui-precompiled" version = "1.4.0" source = "git+https://github.com/ethcore/js-precompiled.git#47da49294ad958933e85a9c4f0f2bb4df5dc47de" dependencies = [ - "parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-dapps-glue 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1830,20 +1830,22 @@ dependencies = [ [[package]] name = "quasi" -version = "0.11.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "syntex_syntax 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_errors 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_syntax 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "quasi_codegen" -version = "0.11.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "aster 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", - "syntex 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", - "syntex_syntax 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", + "aster 0.41.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_errors 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_syntax 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2268,23 +2270,44 @@ dependencies = [ [[package]] name = "syntex" -version = "0.33.0" +version = "0.58.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "syntex_syntax 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_errors 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_syntax 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syntex_errors" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_pos 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", + "term 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syntex_pos" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "syntex_syntax" -version = "0.33.0" +version = "0.58.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "bitflags 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", + "bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", - "term 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_errors 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex_pos 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2311,7 +2334,7 @@ dependencies = [ [[package]] name = "term" -version = "0.2.14" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2449,11 +2472,6 @@ name = "unicode-normalization" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "unicode-xid" -version = "0.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "unicode-xid" version = "0.0.4" @@ -2587,7 +2605,7 @@ dependencies = [ "checksum antidote 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "34fde25430d87a9388dadbe6e34d7f72a462c8b43ac8d309b42b0a8505d7e2a5" "checksum app_dirs 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b7d1c0d48a81bbb13043847f957971f4d87c81542d80ece5e84ba3cba4058fd4" "checksum arrayvec 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)" = "16e3bdb2f54b3ace0285975d59a97cf8ed3855294b2b6bc651fcf22a9c352975" -"checksum aster 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)" = "07d344974f0a155f091948aa389fb1b912d3a58414fbdb9c8d446d193ee3496a" +"checksum aster 0.41.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4ccfdf7355d9db158df68f976ed030ab0f6578af811f5a7bb6dcf221ec24e0e0" "checksum base-x 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "2f59103b47307f76e03bef1633aec7fa9e29bfb5aa6daf5a334f94233c71f6c1" "checksum base32 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1b9605ba46d61df0410d8ac686b0007add8172eba90e8e909c347856fe794d8c" "checksum bigint 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2311bcd71b281e142a095311c22509f0d6bcd87b3000d7dbaa810929b9d6f6ae" @@ -2698,7 +2716,7 @@ dependencies = [ "checksum openssl-sys 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d2845e841700e7b04282ceaa115407ea84e0db918ae689ad9ceb6f06fa6046bd" "checksum order-stat 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "efa535d5117d3661134dbf1719b6f0ffe06f2375843b13935db186cd094105eb" "checksum owning_ref 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "8d91377085359426407a287ab16884a0111ba473aa6844ff01d4ec20ce3d75e7" -"checksum parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "98378dec0a185da2b7180308752f0bad73aaa949c3e0a3b0528d0e067945f7ab" +"checksum parity-dapps-glue 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e1d06f6ee0fda786df3784a96ee3f0629f529b91cbfb7d142f6410e6bcd1ce2c" "checksum parity-ui-precompiled 1.4.0 (git+https://github.com/ethcore/js-precompiled.git)" = "" "checksum parking_lot 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "e1435e7a2a00dfebededd6c6bdbd54008001e94b4a2aadd6aef0dc4c56317621" "checksum parking_lot_core 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fb1b97670a2ffadce7c397fb80a3d687c4f3060140b885621ef1653d0e5d5068" @@ -2713,8 +2731,8 @@ dependencies = [ "checksum primal-check 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "647c81b67bb9551a7b88d0bcd785ac35b7d0bf4b2f358683d7c2375d04daec51" "checksum primal-estimate 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "56ea4531dde757b56906493c8604641da14607bf9cdaa80fb9c9cabd2429f8d5" "checksum primal-sieve 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "7aa73fd87e5984a00bdb4c1b14d3d5d6d0bad01b2caaaf924c16ab7260ac946c" -"checksum quasi 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b26543b563704e7d87f3ec7cfafb713010a905c5f1b155a8ab66863af43ca578" -"checksum quasi_codegen 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0881d9a45d5f9ebe4a7e77742f8c604f3658c212baf8dd711a692dd000bc648c" +"checksum quasi 0.32.0 (registry+https://github.com/rust-lang/crates.io-index)" = "18c45c4854d6d1cf5d531db97c75880feb91c958b0720f4ec1057135fec358b3" +"checksum quasi_codegen 0.32.0 (registry+https://github.com/rust-lang/crates.io-index)" = "51b9e25fa23c044c1803f43ca59c98dac608976dd04ce799411edd58ece776d4" "checksum quick-error 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0aad603e8d7fb67da22dbdf1f4b826ce8829e406124109e73cf1b2454b93a71c" "checksum quine-mc_cluskey 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a6683b0e23d80813b1a535841f0048c1537d3f86d63c999e8373b39a9b0eb74a" "checksum quote 0.3.10 (registry+https://github.com/rust-lang/crates.io-index)" = "6732e32663c9c271bfc7c1823486b471f18c47a2dbf87c066897b7b51afc83be" @@ -2764,12 +2782,14 @@ dependencies = [ "checksum stable-heap 0.1.0 (git+https://github.com/carllerche/stable-heap?rev=3c5cd1ca47)" = "" "checksum strsim 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e4d73a2c36a4d095ed1a6df5cbeac159863173447f7a82b3f4757426844ab825" "checksum syn 0.11.4 (registry+https://github.com/rust-lang/crates.io-index)" = "f4f94368aae82bb29656c98443a7026ca931a659e8d19dcdc41d6e273054e820" -"checksum syntex 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)" = "393b6dd0889df2b064beeea954cfda6bc2571604ac460deeae0fed55a53988af" -"checksum syntex_syntax 0.33.0 (registry+https://github.com/rust-lang/crates.io-index)" = "44bded3cabafc65c90b663b1071bd2d198a9ab7515e6ce729e4570aaf53c407e" +"checksum syntex 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)" = "35f3cc9d446323ef8fefad933b65cd6de271d29fa14a2e9d036a084770c6d6d5" +"checksum syntex_errors 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3af03823ea45d420dd2c1a44bb074e13ea55f9b99afe960fd58eb4069b7f6cad" +"checksum syntex_pos 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1e502a4a904d9f37cf975dbdbb0b08f2d111322f6792bda6eb095b4112c9a24b" +"checksum syntex_syntax 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6cf936464c3863952ea3fab848860ea891eba8647b6008b04c36f0bb007192a3" "checksum take 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b157868d8ac1f56b64604539990685fa7611d8fa9e5476cf0c02cf34d32917c5" "checksum target_info 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c63f48baada5c52e65a29eef93ab4f8982681b67f9e8d29c7b05abcfec2b9ffe" "checksum tempdir 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "87974a6f5c1dfb344d733055601650059a3363de2a6104819293baff662132d6" -"checksum term 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)" = "f2077e54d38055cf1ca0fd7933a2e00cd3ec8f6fed352b2a377f06dcdaaf3281" +"checksum term 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "d168af3930b369cfe245132550579d47dfd873d69470755a19c2c6568dbbd989" "checksum termios 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "d5d9cf598a6d7ce700a4e6a9199da127e6819a61e64b68609683cc9a01b5683a" "checksum thread-id 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a9539db560102d1cef46b8b78ce737ff0bb64e7e18d35b2a5688f7d097d0ff03" "checksum thread_local 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "0694f51610ef7cfac7a1b81de7f1602ee5356e76541bcd62c40e71933338cab1" @@ -2786,7 +2806,6 @@ dependencies = [ "checksum unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "13a5906ca2b98c799f4b1ab4557b76367ebd6ae5ef14930ec841c74aed5f3764" "checksum unicode-bidi 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "c1f7ceb96afdfeedee42bade65a0d585a6a0106f681b6749c8ff4daa8df30b3f" "checksum unicode-normalization 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "26643a2f83bac55f1976fb716c10234485f9202dcd65cfbdf9da49867b271172" -"checksum unicode-xid 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "36dff09cafb4ec7c8cf0023eb0b686cb6ce65499116a12201c9e11840ca01beb" "checksum unicode-xid 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f860d7d29cf02cb2f3f359fd35991af3d30bac52c57d265a3c461074cb4dc" "checksum untrusted 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "193df64312e3515fd983ded55ad5bcaa7647a035804828ed757e832ce6029ef3" "checksum url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "afe9ec54bc4db14bc8744b7fed060d785ac756791450959b2248443319d5b119" diff --git a/dapps/Cargo.toml b/dapps/Cargo.toml index 55becf2c1..8a00f503f 100644 --- a/dapps/Cargo.toml +++ b/dapps/Cargo.toml @@ -22,7 +22,7 @@ serde = "0.9" serde_json = "0.9" serde_derive = "0.9" linked-hash-map = "0.3" -parity-dapps-glue = "1.4" +parity-dapps-glue = "1.7" base32 = "0.3" mime = "0.2" mime_guess = "1.6.1" diff --git a/dapps/js-glue/Cargo.toml b/dapps/js-glue/Cargo.toml index b53b158c7..0f4c92968 100644 --- a/dapps/js-glue/Cargo.toml +++ b/dapps/js-glue/Cargo.toml @@ -7,17 +7,17 @@ authors = ["Parity Technologies "] build = "build.rs" [build-dependencies] -quasi_codegen = { version = "0.11", optional = true } -syntex = { version = "0.33", optional = true } +quasi_codegen = { version = "0.32", optional = true } +syntex = { version = "0.58", optional = true } [dependencies] glob = { version = "0.2.11" } mime_guess = { version = "1.6.1" } -aster = { version = "0.17", default-features = false } -quasi = { version = "0.11", default-features = false } -quasi_macros = { version = "0.11", optional = true } -syntex = { version = "0.33", optional = true } -syntex_syntax = { version = "0.33", optional = true } +aster = { version = "0.41", default-features = false } +quasi = { version = "0.32", default-features = false } +quasi_macros = { version = "0.32", optional = true } +syntex = { version = "0.58", optional = true } +syntex_syntax = { version = "0.58", optional = true } clippy = { version = "0.0.90", optional = true } [features] diff --git a/dapps/js-glue/build.rs b/dapps/js-glue/build.rs index 12afa7974..442abf7df 100644 --- a/dapps/js-glue/build.rs +++ b/dapps/js-glue/build.rs @@ -25,13 +25,11 @@ mod inner { pub fn main() { let out_dir = env::var_os("OUT_DIR").unwrap(); - let mut registry = syntex::Registry::new(); - quasi_codegen::register(&mut registry); let src = Path::new("src/lib.rs.in"); let dst = Path::new(&out_dir).join("lib.rs"); - registry.expand("", &src, &dst).unwrap(); + quasi_codegen::expand(&src, &dst).unwrap(); } } diff --git a/dapps/js-glue/src/build.rs b/dapps/js-glue/src/build.rs index 86c93171b..31f27306a 100644 --- a/dapps/js-glue/src/build.rs +++ b/dapps/js-glue/src/build.rs @@ -13,9 +13,8 @@ pub mod inner { impl fold::Folder for StripAttributeFolder { fn fold_attribute(&mut self, attr: ast::Attribute) -> Option { - match attr.node.value.node { - ast::MetaItemKind::List(ref n, _) if n == &"webapp" => { return None; } - _ => {} + if &*attr.value.name.as_str() == "webapp" { + return None; } Some(attr) diff --git a/dapps/js-glue/src/codegen.rs b/dapps/js-glue/src/codegen.rs index e74ad5fbe..3d8c93460 100644 --- a/dapps/js-glue/src/codegen.rs +++ b/dapps/js-glue/src/codegen.rs @@ -22,16 +22,12 @@ use self::mime_guess::guess_mime_type; use std::path::{self, Path, PathBuf}; use std::ops::Deref; -use syntax::ast::{MetaItem, Item}; - -use syntax::ast; use syntax::attr; +use syntax::ast::{self, MetaItem, Item}; use syntax::codemap::Span; use syntax::ext::base::{Annotatable, ExtCtxt}; -use syntax::ptr::P; -use syntax::print::pprust::{lit_to_string}; -use syntax::parse::token::{InternedString}; - +use syntax::print::pprust::lit_to_string; +use syntax::symbol::InternedString; pub fn expand_webapp_implementation( cx: &mut ExtCtxt, @@ -48,7 +44,7 @@ pub fn expand_webapp_implementation( }, }; let builder = aster::AstBuilder::new().span(span); - implement_webapp(cx, &builder, &item, push); + implement_webapp(cx, &builder, item, push); } fn implement_webapp(cx: &ExtCtxt, builder: &aster::AstBuilder, item: &Item, push: &mut FnMut(Annotatable)) { @@ -117,11 +113,12 @@ fn implement_webapp(cx: &ExtCtxt, builder: &aster::AstBuilder, item: &Item, push } fn extract_path(cx: &ExtCtxt, item: &Item) -> String { - for meta_items in item.attrs().iter().filter_map(webapp_meta_items) { + for meta_items in item.attrs.iter().filter_map(webapp_meta_items) { for meta_item in meta_items { + let is_path = &*meta_item.name.as_str() == "path"; match meta_item.node { - ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"path" => { - if let Some(s) = get_str_from_lit(cx, name, lit) { + ast::MetaItemKind::NameValue(ref lit) if is_path => { + if let Some(s) = get_str_from_lit(cx, lit) { return s.deref().to_owned(); } }, @@ -134,14 +131,32 @@ fn extract_path(cx: &ExtCtxt, item: &Item) -> String { "web".to_owned() } -fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Option { +fn webapp_meta_items(attr: &ast::Attribute) -> Option> { + let is_webapp = &*attr.value.name.as_str() == "webapp"; + match attr.value.node { + ast::MetaItemKind::List(ref items) if is_webapp => { + attr::mark_used(&attr); + Some( + items.iter() + .map(|item| item.node.clone()) + .filter_map(|item| match item { + ast::NestedMetaItemKind::MetaItem(item) => Some(item), + _ => None, + }) + .collect() + ) + } + _ => None + } +} + +fn get_str_from_lit(cx: &ExtCtxt, lit: &ast::Lit) -> Option { match lit.node { - ast::LitKind::Str(ref s, _) => Some(s.clone()), + ast::LitKind::Str(ref s, _) => Some(s.clone().as_str()), _ => { cx.span_err( lit.span, - &format!("webapp annotation `{}` must be a string, not `{}`", - name, + &format!("webapp annotation path must be a string, not `{}`", lit_to_string(lit) ) ); @@ -150,16 +165,6 @@ fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Option Option<&[P]> { - match attr.node.value.node { - ast::MetaItemKind::List(ref name, ref items) if name == &"webapp" => { - attr::mark_used(&attr); - Some(items) - } - _ => None - } -} - fn as_uri(path: &Path) -> String { let mut s = String::new(); for component in path.iter() { @@ -169,7 +174,6 @@ fn as_uri(path: &Path) -> String { s[0..s.len()-1].into() } - #[test] fn should_convert_path_separators_on_all_platforms() { // given diff --git a/dapps/js-glue/src/lib.rs b/dapps/js-glue/src/lib.rs index 72f228481..143dd1fc8 100644 --- a/dapps/js-glue/src/lib.rs +++ b/dapps/js-glue/src/lib.rs @@ -22,7 +22,6 @@ extern crate syntex; #[cfg(feature = "with-syntex")] -#[macro_use] extern crate syntex_syntax as syntax; #[cfg(feature = "with-syntex")] diff --git a/ipc/codegen/Cargo.toml b/ipc/codegen/Cargo.toml index 63e0fc7c6..52016f45a 100644 --- a/ipc/codegen/Cargo.toml +++ b/ipc/codegen/Cargo.toml @@ -14,13 +14,13 @@ nightly-testing = ["clippy"] with-syntex = ["quasi/with-syntex", "quasi_codegen", "quasi_codegen/with-syntex", "syntex", "syntex_syntax"] [build-dependencies] -quasi_codegen = { version = "0.11", optional = true } -syntex = { version = "0.33", optional = true } +quasi_codegen = { version = "0.32", optional = true } +syntex = { version = "0.58", optional = true } [dependencies] -aster = { version = "0.17", default-features = false } +aster = { version = "0.41", default-features = false } clippy = { version = "^0.*", optional = true } -quasi = { version = "0.11", default-features = false } -quasi_macros = { version = "0.11", optional = true } -syntex = { version = "0.33", optional = true } -syntex_syntax = { version = "0.33", optional = true } +quasi = { version = "0.32", default-features = false } +quasi_macros = { version = "0.32", optional = true } +syntex = { version = "0.58", optional = true } +syntex_syntax = { version = "0.58", optional = true } diff --git a/ipc/codegen/build.rs b/ipc/codegen/build.rs index 12afa7974..442abf7df 100644 --- a/ipc/codegen/build.rs +++ b/ipc/codegen/build.rs @@ -25,13 +25,11 @@ mod inner { pub fn main() { let out_dir = env::var_os("OUT_DIR").unwrap(); - let mut registry = syntex::Registry::new(); - quasi_codegen::register(&mut registry); let src = Path::new("src/lib.rs.in"); let dst = Path::new(&out_dir).join("lib.rs"); - registry.expand("", &src, &dst).unwrap(); + quasi_codegen::expand(&src, &dst).unwrap(); } } diff --git a/ipc/codegen/src/codegen.rs b/ipc/codegen/src/codegen.rs index d44a8137d..2f4752d97 100644 --- a/ipc/codegen/src/codegen.rs +++ b/ipc/codegen/src/codegen.rs @@ -56,7 +56,7 @@ pub fn expand_ipc_implementation( let builder = aster::AstBuilder::new().span(span); - let interface_map = match implement_interface(cx, &builder, &item, push) { + let interface_map = match implement_interface(cx, &builder, &item, push, meta_item) { Ok(interface_map) => interface_map, Err(Error) => { return; }, }; @@ -99,9 +99,9 @@ fn push_invoke_signature_aster( let inputs = &named_signature.sig.decl.inputs; let (input_type_name, input_arg_names, input_arg_tys) = if inputs.len() > 0 { let first_field_name = field_name(builder, &inputs[0]).name.as_str(); - if first_field_name == "self" && inputs.len() == 1 { (None, vec![], vec![]) } + if &*first_field_name == "self" && inputs.len() == 1 { (None, vec![], vec![]) } else { - let skip = if first_field_name == "self" { 2 } else { 1 }; + let skip = if &*first_field_name == "self" { 2 } else { 1 }; let name_str = format!("{}_input", named_signature.ident.name.as_str()); let mut arg_names = Vec::new(); @@ -181,6 +181,7 @@ fn implement_dispatch_arm_invoke_stmt( dispatch: &Dispatch, ) -> ast::Stmt { + use ::syntax::tokenstream::TokenTree::Token; let function_name = builder.id(dispatch.function_name.as_str()); let input_args_exprs = dispatch.input_arg_names.iter().enumerate().map(|(arg_index, arg_name)| { @@ -193,56 +194,56 @@ fn implement_dispatch_arm_invoke_stmt( let ext_cx = &*cx; ::quasi::parse_stmt_panic(&mut ::syntax::parse::new_parser_from_tts( ext_cx.parse_sess(), - ext_cx.cfg(), { let _sp = ext_cx.call_site(); let mut tt = ::std::vec::Vec::new(); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Brace))); + tt.push(Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Brace))); if dispatch.return_type_ty.is_some() { - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::ModSep)); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("ipc")))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::ModSep)); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("binary")))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::ModSep)); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("serialize")))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::BinOp(::syntax::parse::token::And))); + tt.push(Token(_sp, ::syntax::parse::token::ModSep)); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("ipc")))); + tt.push(Token(_sp, ::syntax::parse::token::ModSep)); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("binary")))); + tt.push(Token(_sp, ::syntax::parse::token::ModSep)); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("serialize")))); + tt.push(Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren))); + tt.push(Token(_sp, ::syntax::parse::token::BinOp(::syntax::parse::token::And))); } - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("self")))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Dot)); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("self")))); + tt.push(Token(_sp, ::syntax::parse::token::Dot)); tt.extend(::quasi::ToTokens::to_tokens(&function_name, ext_cx).into_iter()); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren))); + tt.push(Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren))); for arg_expr in input_args_exprs { tt.extend(::quasi::ToTokens::to_tokens(&arg_expr, ext_cx).into_iter()); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Comma)); + tt.push(Token(_sp, ::syntax::parse::token::Comma)); } - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren))); + tt.push(Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren))); if dispatch.return_type_ty.is_some() { - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Dot)); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("unwrap")))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren))); + tt.push(Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren))); + tt.push(Token(_sp, ::syntax::parse::token::Dot)); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("unwrap")))); + tt.push(Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren))); + tt.push(Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren))); } else { - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Semi)); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("Vec")))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::ModSep)); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("new")))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren))); + tt.push(Token(_sp, ::syntax::parse::token::Semi)); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("Vec")))); + tt.push(Token(_sp, ::syntax::parse::token::ModSep)); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("new")))); + tt.push(Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren))); + tt.push(Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren))); } - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Brace))); + tt.push(Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Brace))); tt - })).unwrap() + } + )).unwrap() } fn implement_dispatch_arm_invoke( @@ -344,6 +345,8 @@ fn implement_client_method_body( interface_map: &InterfaceMap, ) -> P { + use ::syntax::tokenstream::TokenTree::Token; + let dispatch = &interface_map.dispatches[index as usize]; let index_ident = builder.id(format!("{}", index + RESERVED_MESSAGE_IDS).as_str()); @@ -391,26 +394,25 @@ fn implement_client_method_body( let ext_cx = &*cx; ::quasi::parse_stmt_panic(&mut ::syntax::parse::new_parser_from_tts( ext_cx.parse_sess(), - ext_cx.cfg(), { let _sp = ext_cx.call_site(); let mut tt = ::std::vec::Vec::new(); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("let")))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("payload")))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Eq)); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("Request")))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Brace))); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("let")))); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("payload")))); + tt.push(Token(_sp, ::syntax::parse::token::Eq)); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("Request")))); + tt.push(Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Brace))); for arg in dispatch.input_arg_names.iter() { - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of(arg.as_str())))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Colon)); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::BinOp(::syntax::parse::token::And))); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of(arg.as_str())))); + tt.push(Token(_sp, ::syntax::parse::token::Colon)); + tt.push(Token(_sp, ::syntax::parse::token::BinOp(::syntax::parse::token::And))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of(arg.as_str())))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Comma)); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of(arg.as_str())))); + tt.push(Token(_sp, ::syntax::parse::token::Comma)); } - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Brace))); + tt.push(Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Brace))); tt })) }); @@ -465,6 +467,8 @@ fn implement_client_method( ) -> ast::ImplItem { + use ::syntax::tokenstream::TokenTree::Token; + let dispatch = &interface_map.dispatches[index as usize]; let method_name = builder.id(dispatch.function_name.as_str()); let body = implement_client_method_body(cx, builder, index, interface_map); @@ -476,36 +480,35 @@ fn implement_client_method( let signature = ::syntax::parse::parser::Parser::parse_impl_item( &mut ::syntax::parse::new_parser_from_tts( ext_cx.parse_sess(), - ext_cx.cfg(), { let _sp = ext_cx.call_site(); let mut tt = ::std::vec::Vec::new(); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("fn")))); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("fn")))); tt.extend(::quasi::ToTokens::to_tokens(&method_name, ext_cx).into_iter()); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::BinOp(::syntax::parse::token::And))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("self")))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Comma)); + tt.push(Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren))); + tt.push(Token(_sp, ::syntax::parse::token::BinOp(::syntax::parse::token::And))); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of("self")))); + tt.push(Token(_sp, ::syntax::parse::token::Comma)); for arg_idx in 0..dispatch.input_arg_names.len() { let arg_name = dispatch.input_arg_names[arg_idx].as_str(); let arg_ty = dispatch.input_arg_tys[arg_idx].clone(); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of(arg_name)))); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Colon)); + tt.push(Token(_sp, ::syntax::parse::token::Ident(ext_cx.ident_of(arg_name)))); + tt.push(Token(_sp, ::syntax::parse::token::Colon)); tt.extend(::quasi::ToTokens::to_tokens(&arg_ty, ext_cx).into_iter()); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::Comma)); + tt.push(Token(_sp, ::syntax::parse::token::Comma)); } - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren))); + tt.push(Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren))); if let Some(ref return_ty) = dispatch.return_type_ty { - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::RArrow)); + tt.push(Token(_sp, ::syntax::parse::token::RArrow)); tt.extend(::quasi::ToTokens::to_tokens(return_ty, ext_cx).into_iter()); } - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Brace))); + tt.push(Token(_sp, ::syntax::parse::token::OpenDelim(::syntax::parse::token::Brace))); tt.extend(::quasi::ToTokens::to_tokens(&body, ext_cx).into_iter()); - tt.push(::syntax::ast::TokenTree::Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Brace))); + tt.push(Token(_sp, ::syntax::parse::token::CloseDelim(::syntax::parse::token::Brace))); tt })); @@ -526,7 +529,7 @@ fn client_generics(builder: &aster::AstBuilder, interface_map: &InterfaceMap) -> fn client_qualified_ident(cx: &ExtCtxt, builder: &aster::AstBuilder, interface_map: &InterfaceMap) -> P { let generics = client_generics(builder, interface_map); - aster::ty::TyBuilder::new().path().segment(interface_map.ident_map.client_ident(cx, builder, &interface_map.original_item)) + aster::ty::TyBuilder::new().path().segment(interface_map.ident_map.client_ident(cx, builder)) .with_generics(generics).build() .build() } @@ -542,7 +545,7 @@ fn client_phantom_ident(builder: &aster::AstBuilder, interface_map: &InterfaceMa /// for say `Service` it generates `ServiceClient` fn push_client_struct(cx: &ExtCtxt, builder: &aster::AstBuilder, interface_map: &InterfaceMap, push: &mut FnMut(Annotatable)) { let generics = client_generics(builder, interface_map); - let client_short_ident = interface_map.ident_map.client_ident(cx, builder, &interface_map.original_item); + let client_short_ident = interface_map.ident_map.client_ident(cx, builder); let phantom = client_phantom_ident(builder, interface_map); let client_struct_item = quote_item!(cx, @@ -575,7 +578,7 @@ fn push_with_socket_client_implementation( let generics = client_generics(builder, interface_map); let client_ident = client_qualified_ident(cx, builder, interface_map); let where_clause = &generics.where_clause; - let client_short_ident = interface_map.ident_map.client_ident(cx, builder, &interface_map.original_item); + let client_short_ident = interface_map.ident_map.client_ident(cx, builder); let implement = quote_item!(cx, impl $generics ::ipc::WithSocket for $client_ident $where_clause { @@ -717,33 +720,31 @@ fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit) -> Result Option<&[P]> { - match attr.node.value.node { - ast::MetaItemKind::List(ref name, ref items) if name == &"ipc" => { - Some(items) - } - _ => None - } -} - -fn client_ident_renamed(cx: &ExtCtxt, item: &ast::Item) -> Option { - for meta_items in item.attrs().iter().filter_map(get_ipc_meta_items) { - for meta_item in meta_items { - match meta_item.node { - ast::MetaItemKind::NameValue(ref name, ref lit) if name == &"client_ident" => { - if let Ok(s) = get_str_from_lit(cx, name, lit) { - return Some(s); +fn client_ident_renamed(cx: &ExtCtxt, meta_item: &MetaItem) -> Option { + if let ast::MetaItemKind::List(ref list) = meta_item.node { + for nested in list { + match nested.node { + ast::NestedMetaItemKind::MetaItem(ref meta_item) => { + let is_client_ident = &*meta_item.name.as_str() == "client_ident"; + match meta_item.node { + ast::MetaItemKind::NameValue(ref lit) if is_client_ident => { + if let Ok(s) = get_str_from_lit(cx, "client_ident", lit) { + return Some(s); + } + } + _ => { + cx.span_err( + meta_item.span, + &format!("unknown client_ident container attribute `{}`", + ::syntax::print::pprust::meta_item_to_string(&meta_item))); + } } - } - _ => { - cx.span_err( - meta_item.span, - &format!("unknown client_ident container attribute `{}`", - ::syntax::print::pprust::meta_item_to_string(meta_item))); - } + }, + _ => {}, } } } + None } @@ -759,6 +760,7 @@ struct InterfaceMap { struct IdentMap { original_path: ast::Path, + meta_item: MetaItem, } impl IdentMap { @@ -766,8 +768,8 @@ impl IdentMap { builder.id(format!("{}", ::syntax::print::pprust::path_to_string(&self.original_path))) } - fn client_ident(&self, cx: &ExtCtxt, builder: &aster::AstBuilder, item: &ast::Item) -> Ident { - if let Some(new_name) = client_ident_renamed(cx, item) { + fn client_ident(&self, cx: &ExtCtxt, builder: &aster::AstBuilder) -> Ident { + if let Some(new_name) = client_ident_renamed(cx, &self.meta_item) { builder.id(new_name) } else { @@ -776,12 +778,12 @@ impl IdentMap { } } -fn ty_ident_map(original_ty: &P) -> IdentMap { +fn ty_ident_map(original_ty: &P, meta_item: &MetaItem) -> IdentMap { let original_path = match original_ty.node { ::syntax::ast::TyKind::Path(_, ref path) => path.clone(), _ => { panic!("incompatible implementation"); } }; - let ident_map = IdentMap { original_path: original_path }; + let ident_map = IdentMap { original_path: original_path, meta_item: meta_item.clone() }; ident_map } @@ -791,6 +793,7 @@ fn implement_interface( builder: &aster::AstBuilder, item: &Item, push: &mut FnMut(Annotatable), + meta_item: &MetaItem, ) -> Result { let (generics, impl_trait, original_ty, dispatch_table) = match item.node { ast::ItemKind::Impl(_, _, ref generics, ref impl_trait, ref ty, ref impl_items) => { @@ -844,7 +847,7 @@ fn implement_interface( let (handshake_arm, handshake_arm_buf) = implement_handshake_arm(cx); - let ty = ty_ident_map(&original_ty).ident(builder); + let ty = ty_ident_map(&original_ty, meta_item).ident(builder); let (interface_endpoint, host_generics) = match impl_trait { Some(ref trait_) => (builder.id(::syntax::print::pprust::path_to_string(&trait_.path)), None), None => (ty, Some(&impl_generics)), @@ -884,7 +887,7 @@ fn implement_interface( ).unwrap(); Ok(InterfaceMap { - ident_map: ty_ident_map(&original_ty), + ident_map: ty_ident_map(&original_ty, meta_item), original_item: item.clone(), item: ipc_item, dispatches: dispatch_table, diff --git a/ipc/codegen/src/lib.rs b/ipc/codegen/src/lib.rs index 33894b485..6e7fc441b 100644 --- a/ipc/codegen/src/lib.rs +++ b/ipc/codegen/src/lib.rs @@ -66,9 +66,11 @@ struct StripAttributeFolder<'a> { #[cfg(feature = "with-syntex")] impl<'a> fold::Folder for StripAttributeFolder<'a> { fn fold_attribute(&mut self, attr: ast::Attribute) -> Option { - match attr.node.value.node { - ast::MetaItemKind::List(ref n, _) if n == self.attr_title => { return None; } - ast::MetaItemKind::Word(ref n) if n == self.attr_title => { return None; } + let is_self = &*attr.value.name.as_str() == self.attr_title; + + match attr.value.node { + ast::MetaItemKind::List(_) if is_self => { return None; } + ast::MetaItemKind::Word if is_self => { return None; } _ => {} } diff --git a/ipc/codegen/src/serialization.rs b/ipc/codegen/src/serialization.rs index cf1ec6696..fd908725c 100644 --- a/ipc/codegen/src/serialization.rs +++ b/ipc/codegen/src/serialization.rs @@ -151,7 +151,7 @@ fn binary_expr( _ => { cx.span_bug(item.span, "expected ItemStruct or ItemEnum in #[derive(Binary)]"); - Err(Error) + Err(Error) as Result }, } } @@ -184,13 +184,17 @@ fn binary_expr_struct( let size_exprs: Vec> = fields.iter().enumerate().map(|(index, field)| { let raw_ident = ::syntax::print::pprust::ty_to_string(&codegen::strip_ptr(&field.ty)); let index_ident = builder.id(format!("__field{}", index)); + let field_id = match field.ident { + Some(ident) => builder.id(ident), + None => builder.id(format!("{}", index)), + }; + match raw_ident.as_ref() { "u8" => { quote_expr!(cx, 1) }, "[u8]" => { value_ident.and_then(|x| { - let field_id = builder.id(field.ident.unwrap()); Some(quote_expr!(cx, $x. $field_id .len())) }) .unwrap_or_else(|| { @@ -207,7 +211,6 @@ fn binary_expr_struct( value_ident.and_then(|x| { - let field_id = builder.id(field.ident.unwrap()); Some(quote_expr!(cx, match $field_type_ident_qualified::len_params() { 0 => ::std::mem::size_of::<$field_type_ident>(), @@ -232,12 +235,12 @@ fn binary_expr_struct( } let mut write_stmts = Vec::::new(); - write_stmts.push(quote_stmt!(cx, let mut offset = 0usize;).unwrap()); + write_stmts.push(quote_stmt!(cx, let mut offset = 0usize;).expect("stmt1")); let mut map_stmts = Vec::::new(); let field_amount = builder.id(&format!("{}",fields.len())); - map_stmts.push(quote_stmt!(cx, let mut map = vec![0usize; $field_amount];).unwrap()); - map_stmts.push(quote_stmt!(cx, let mut total = 0usize;).unwrap()); + map_stmts.push(quote_stmt!(cx, let mut map = vec![0usize; $field_amount];).expect("stmt2")); + map_stmts.push(quote_stmt!(cx, let mut total = 0usize;).expect("stmt3")); let mut post_write_stmts = Vec::::new(); @@ -248,9 +251,12 @@ fn binary_expr_struct( let field_type_ident_qualified = builder.id( replace_qualified(&::syntax::print::pprust::ty_to_string(&codegen::strip_ptr(&field.ty)))); + let field_id = match field.ident { + Some(ident) => builder.id(ident), + None => builder.id(format!("{}", index)), + }; let member_expr = match value_ident { Some(x) => { - let field_id = builder.id(field.ident.unwrap()); quote_expr!(cx, $x . $field_id) }, None => { @@ -267,8 +273,8 @@ fn binary_expr_struct( match raw_ident.as_ref() { "u8" => { - write_stmts.push(quote_stmt!(cx, let next_line = offset + 1;).unwrap()); - write_stmts.push(quote_stmt!(cx, buffer[offset] = $member_expr; ).unwrap()); + write_stmts.push(quote_stmt!(cx, let next_line = offset + 1;).expect("stmt4")); + write_stmts.push(quote_stmt!(cx, buffer[offset] = $member_expr; ).expect("stm5")); }, "[u8]" => { write_stmts.push(quote_stmt!(cx, let size = $member_expr .len();).unwrap()); @@ -374,7 +380,7 @@ fn binary_expr_item_struct( cx.span_bug(span, &format!("#[derive(Binary)] Unsupported struct content, expected tuple/struct, found: {:?}", variant_data)); - Err(Error) + Err(Error) as Result }, } } @@ -431,13 +437,12 @@ fn fields_sequence( variant_ident: &ast::Ident, ) -> ast::Expr { use syntax::parse::token; - use syntax::ast::TokenTree::Token; + use syntax::tokenstream::TokenTree::Token; let named_members = fields.iter().any(|f| f.ident.is_some()); ::quasi::parse_expr_panic(&mut ::syntax::parse::new_parser_from_tts( ext_cx.parse_sess(), - ext_cx.cfg(), { let _sp = ext_cx.call_site(); let mut tt = ::std::vec::Vec::new(); @@ -569,11 +574,10 @@ fn named_fields_sequence( fields: &[ast::StructField], ) -> ast::Stmt { use syntax::parse::token; - use syntax::ast::TokenTree::Token; + use syntax::tokenstream::TokenTree::Token; ::quasi::parse_stmt_panic(&mut ::syntax::parse::new_parser_from_tts( ext_cx.parse_sess(), - ext_cx.cfg(), { let _sp = ext_cx.call_site(); let mut tt = ::std::vec::Vec::new(); @@ -590,7 +594,10 @@ fn named_fields_sequence( tt.push(Token(_sp, token::OpenDelim(token::Brace))); for (idx, field) in fields.iter().enumerate() { - tt.push(Token(_sp, token::Ident(field.ident.clone().expect("function is called for named fields")))); + tt.push(Token(_sp, match field.ident { + Some(ident) => token::Ident(ident), + None => token::Ident(ext_cx.ident_of(&format!("{}", idx))), + })); tt.push(Token(_sp, token::Colon)); // special case for u8, it just takes byte form sequence diff --git a/js/Cargo.precompiled.toml b/js/Cargo.precompiled.toml index 5de652037..87369005c 100644 --- a/js/Cargo.precompiled.toml +++ b/js/Cargo.precompiled.toml @@ -12,8 +12,8 @@ use-precompiled-js = ["parity-dapps-glue/use-precompiled-js"] with-syntex = ["parity-dapps-glue/with-syntex"] [build-dependencies] -parity-dapps-glue = "1.4" +parity-dapps-glue = "1.7" [dependencies] -parity-dapps-glue = "1.4" +parity-dapps-glue = "1.7" diff --git a/js/Cargo.toml b/js/Cargo.toml index 231f5fa24..71683b899 100644 --- a/js/Cargo.toml +++ b/js/Cargo.toml @@ -1,7 +1,7 @@ [package] description = "Parity built-in dapps." name = "parity-ui-dev" -version = "1.4.0" +version = "1.7.0" license = "GPL-3.0" authors = ["Parity Technologies "] build = "build.rs" @@ -11,8 +11,8 @@ default = ["with-syntex"] with-syntex = ["parity-dapps-glue/with-syntex"] [build-dependencies] -parity-dapps-glue = "1.4" +parity-dapps-glue = "1.7" [dependencies] -parity-dapps-glue = "1.4" +parity-dapps-glue = "1.7" diff --git a/signer/Cargo.toml b/signer/Cargo.toml index 3c81bfc9d..4b80cfac5 100644 --- a/signer/Cargo.toml +++ b/signer/Cargo.toml @@ -15,7 +15,7 @@ rand = "0.3.14" jsonrpc-core = { git = "https://github.com/ethcore/jsonrpc.git", branch = "parity-1.6" } log = "0.3" env_logger = "0.3" -parity-dapps-glue = { version = "1.4", optional = true } +parity-dapps-glue = { version = "1.7", optional = true } ws = { git = "https://github.com/ethcore/ws-rs.git", branch = "mio-upstream-stable" } ethcore-util = { path = "../util" } ethcore-io = { path = "../util/io" } diff --git a/stratum/src/traits.rs b/stratum/src/traits.rs index af5be2cbc..c2c522b3b 100644 --- a/stratum/src/traits.rs +++ b/stratum/src/traits.rs @@ -42,8 +42,8 @@ impl From for Error { } } -#[ipc(client_ident="RemoteJobDispatcher")] /// Interface that can provide pow/blockchain-specific responses for the clients +#[ipc(client_ident="RemoteJobDispatcher")] pub trait JobDispatcher: Send + Sync { // json for initial client handshake fn initial(&self) -> Option { None } @@ -55,8 +55,8 @@ pub trait JobDispatcher: Send + Sync { fn submit(&self, payload: Vec) -> Result<(), Error>; } -#[ipc(client_ident="RemoteWorkHandler")] /// Interface that can handle requests to push job for workers +#[ipc(client_ident="RemoteWorkHandler")] pub trait PushWorkHandler: Send + Sync { /// push the same work package for all workers (`payload`: json of pow-specific set of work specification) fn push_work_all(&self, payload: String) -> Result<(), Error>; From 63f1ca924388b44da300c10f10acb0192252bb56 Mon Sep 17 00:00:00 2001 From: GitLab Build Bot Date: Tue, 21 Mar 2017 20:48:59 +0000 Subject: [PATCH 02/11] [ci skip] js-precompiled 20170321-204617 --- Cargo.lock | 2 +- js/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e61658e16..a0ad6bede 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1700,7 +1700,7 @@ dependencies = [ [[package]] name = "parity-ui-precompiled" version = "1.4.0" -source = "git+https://github.com/ethcore/js-precompiled.git#47da49294ad958933e85a9c4f0f2bb4df5dc47de" +source = "git+https://github.com/ethcore/js-precompiled.git#24a28bd6f55c3540f18e14ec00fbb8f207be25d4" dependencies = [ "parity-dapps-glue 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)", ] diff --git a/js/package.json b/js/package.json index 1e770ac34..eac319740 100644 --- a/js/package.json +++ b/js/package.json @@ -1,6 +1,6 @@ { "name": "parity.js", - "version": "1.7.22", + "version": "1.7.23", "main": "release/index.js", "jsnext:main": "src/index.js", "author": "Parity Team ", From d530cc86f36a8fac940d4fd1c86bfbc375f0deea Mon Sep 17 00:00:00 2001 From: Marek Kotewicz Date: Wed, 22 Mar 2017 06:23:40 +0100 Subject: [PATCH 03/11] splitting part of util into smaller crates (#4956) * split path module from util * moved RotatingLogger from util to logger crate * fix tests * fix tests * use only one version of ansi_term crate --- Cargo.lock | 40 +++++++++++++++-------- Cargo.toml | 3 +- ethcore/Cargo.toml | 1 + ethcore/src/json_tests/chain.rs | 2 +- ethcore/src/json_tests/state.rs | 2 +- ethcore/src/lib.rs | 1 + ethcore/src/miner/price_info.rs | 2 +- ethcore/src/miner/transaction_queue.rs | 1 + ethcore/src/state/mod.rs | 2 +- ethcore/src/state_db.rs | 2 +- logger/Cargo.toml | 4 ++- logger/src/lib.rs | 12 +++++-- util/src/log.rs => logger/src/rotating.rs | 1 - parity/configuration.rs | 4 +-- parity/helpers.rs | 5 +-- parity/main.rs | 1 + parity/rpc_apis.rs | 2 +- parity/run.rs | 4 +-- parity/signer.rs | 2 +- rpc/Cargo.toml | 1 + rpc/src/lib.rs | 1 + rpc/src/v1/impls/light/parity.rs | 2 +- rpc/src/v1/impls/parity.rs | 3 +- rpc/src/v1/tests/mocked/parity.rs | 2 +- rpc/src/v1/types/confirmations.rs | 2 +- rpc/src/v1/types/transaction_request.rs | 2 +- stratum/Cargo.toml | 1 + stratum/src/lib.rs | 29 ++-------------- updater/Cargo.toml | 1 + updater/src/lib.rs | 1 + updater/src/updater.rs | 2 +- util/Cargo.toml | 5 ++- util/network/Cargo.toml | 4 ++- util/network/src/host.rs | 2 +- util/network/src/lib.rs | 2 ++ util/network/src/tests.rs | 2 +- util/path/Cargo.toml | 6 ++++ util/{src/path.rs => path/src/lib.rs} | 0 util/src/journaldb/earlymergedb.rs | 2 +- util/src/journaldb/overlayrecentdb.rs | 2 +- util/src/lib.rs | 8 ++--- util/src/trie/triedbmut.rs | 2 +- 42 files changed, 93 insertions(+), 80 deletions(-) rename util/src/log.rs => logger/src/rotating.rs (98%) create mode 100644 util/path/Cargo.toml rename util/{src/path.rs => path/src/lib.rs} (100%) diff --git a/Cargo.lock b/Cargo.lock index a0ad6bede..d039c1646 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,7 +2,7 @@ name = "parity" version = "1.7.0" dependencies = [ - "ansi_term 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "ansi_term 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "app_dirs 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "clippy 0.0.103 (registry+https://github.com/rust-lang/crates.io-index)", "ctrlc 1.1.1 (git+https://github.com/ethcore/rust-ctrlc.git)", @@ -39,6 +39,7 @@ dependencies = [ "parity-reactor 0.1.0", "parity-rpc-client 1.4.0", "parity-updater 1.7.0", + "path 0.1.0", "regex 0.1.68 (registry+https://github.com/rust-lang/crates.io-index)", "rlp 0.1.0", "rpassword 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -72,7 +73,7 @@ dependencies = [ [[package]] name = "ansi_term" -version = "0.7.2" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -93,10 +94,10 @@ dependencies = [ [[package]] name = "arrayvec" -version = "0.3.16" +version = "0.3.20" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "nodrop 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "nodrop 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", "odds 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -347,7 +348,7 @@ name = "eth-secp256k1" version = "0.5.6" source = "git+https://github.com/ethcore/rust-secp256k1#98ad9b9ecae44a563efdd64273bcebc6b4ed81c6" dependencies = [ - "arrayvec 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)", + "arrayvec 0.3.20 (registry+https://github.com/rust-lang/crates.io-index)", "gcc 0.3.43 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", @@ -394,6 +395,7 @@ dependencies = [ "ethcore-ipc 1.7.0", "ethcore-ipc-codegen 1.7.0", "ethcore-ipc-nano 1.7.0", + "ethcore-logger 1.7.0", "ethcore-stratum 1.7.0", "ethcore-util 1.7.0", "ethjson 0.1.0", @@ -570,11 +572,13 @@ dependencies = [ name = "ethcore-logger" version = "1.7.0" dependencies = [ + "ansi_term 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "arrayvec 0.3.20 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "ethcore-util 1.7.0", "isatty 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "regex 0.1.68 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -583,10 +587,11 @@ dependencies = [ name = "ethcore-network" version = "1.7.0" dependencies = [ - "ansi_term 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "ansi_term 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "bytes 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "ethcore-devtools 1.7.0", "ethcore-io 1.7.0", + "ethcore-logger 1.7.0", "ethcore-util 1.7.0", "ethcrypto 0.1.0", "ethkey 0.2.0", @@ -595,6 +600,7 @@ dependencies = [ "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "mio 0.6.1 (git+https://github.com/ethcore/mio)", "parking_lot 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "path 0.1.0", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "rlp 0.1.0", "rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)", @@ -615,6 +621,7 @@ dependencies = [ "ethcore-io 1.7.0", "ethcore-ipc 1.7.0", "ethcore-light 1.7.0", + "ethcore-logger 1.7.0", "ethcore-util 1.7.0", "ethcrypto 0.1.0", "ethjson 0.1.0", @@ -687,6 +694,7 @@ dependencies = [ "ethcore-ipc 1.7.0", "ethcore-ipc-codegen 1.7.0", "ethcore-ipc-nano 1.7.0", + "ethcore-logger 1.7.0", "ethcore-util 1.7.0", "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-core 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", @@ -703,8 +711,7 @@ dependencies = [ name = "ethcore-util" version = "1.7.0" dependencies = [ - "ansi_term 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", - "arrayvec 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)", + "ansi_term 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "clippy 0.0.103 (registry+https://github.com/rust-lang/crates.io-index)", "elastic-array 0.6.0 (git+https://github.com/ethcore/elastic-array)", "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -712,9 +719,9 @@ dependencies = [ "ethcore-bigint 0.1.2", "ethcore-bloom-journal 0.1.0", "ethcore-devtools 1.7.0", + "ethcore-logger 1.7.0", "heapsize 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "itertools 0.5.9 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "lru-cache 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1457,7 +1464,7 @@ dependencies = [ [[package]] name = "nodrop" -version = "0.1.6" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "odds 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1719,6 +1726,7 @@ dependencies = [ "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-hash-fetch 1.7.0", "parity-reactor 0.1.0", + "path 0.1.0", "target_info 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1743,6 +1751,10 @@ dependencies = [ "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "path" +version = "0.1.0" + [[package]] name = "phf" version = "0.7.14" @@ -2601,10 +2613,10 @@ dependencies = [ [metadata] "checksum advapi32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e06588080cb19d0acb6739808aafa5f26bfb2ca015b2b6370028b44cf7cb8a9a" "checksum aho-corasick 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "67077478f0a03952bed2e6786338d400d40c25e9836e08ad50af96607317fd03" -"checksum ansi_term 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1f46cd5b1d660c938e3f92dfe7a73d832b3281479363dd0cd9c1c2fbf60f7962" +"checksum ansi_term 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "23ac7c30002a5accbf7e8987d0632fa6de155b7c3d39d0067317a391e00a2ef6" "checksum antidote 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "34fde25430d87a9388dadbe6e34d7f72a462c8b43ac8d309b42b0a8505d7e2a5" "checksum app_dirs 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b7d1c0d48a81bbb13043847f957971f4d87c81542d80ece5e84ba3cba4058fd4" -"checksum arrayvec 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)" = "16e3bdb2f54b3ace0285975d59a97cf8ed3855294b2b6bc651fcf22a9c352975" +"checksum arrayvec 0.3.20 (registry+https://github.com/rust-lang/crates.io-index)" = "d89f1b0e242270b5b797778af0c8d182a1a2ccac5d8d6fadf414223cc0fab096" "checksum aster 0.41.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4ccfdf7355d9db158df68f976ed030ab0f6578af811f5a7bb6dcf221ec24e0e0" "checksum base-x 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "2f59103b47307f76e03bef1633aec7fa9e29bfb5aa6daf5a334f94233c71f6c1" "checksum base32 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1b9605ba46d61df0410d8ac686b0007add8172eba90e8e909c347856fe794d8c" @@ -2699,7 +2711,7 @@ dependencies = [ "checksum nix 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f05c2fc965fc1cd6b73fa57fa7b89f288178737f2f3ce9e63e4a6a141189000e" "checksum nix 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7a7bb1da2be7da3cbffda73fc681d509ffd9e665af478d2bee1907cee0bc64b2" "checksum nix 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a0d95c5fa8b641c10ad0b8887454ebaafa3c92b5cd5350f8fc693adafd178e7b" -"checksum nodrop 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "4d9a22dbcebdeef7bf275cbf444d6521d4e7a2fee187b72d80dba0817120dd8f" +"checksum nodrop 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "52cd74cd09beba596430cc6e3091b74007169a56246e1262f0ba451ea95117b2" "checksum nom 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6caab12c5f97aa316cb249725aa32115118e1522b445e26c257dd77cad5ffd4e" "checksum num 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)" = "c04bd954dbf96f76bab6e5bd6cef6f1ce1262d15268ce4f926d2b5b778fa7af2" "checksum num-bigint 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)" = "41655c8d667be847a0b72fe0888857a7b3f052f691cf40852be5fcf87b274a65" diff --git a/Cargo.toml b/Cargo.toml index 099be68e5..f62f8b42f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,7 @@ num_cpus = "1.2" number_prefix = "0.2" rpassword = "0.2.1" semver = "0.5" -ansi_term = "0.7" +ansi_term = "0.9" regex = "0.1" isatty = "0.1" toml = "0.2" @@ -50,6 +50,7 @@ parity-updater = { path = "updater" } parity-reactor = { path = "util/reactor" } parity-local-store = { path = "local-store" } ethcore-dapps = { path = "dapps", optional = true } +path = { path = "util/path" } clippy = { version = "0.0.103", optional = true} ethcore-secretstore = { path = "secret_store", optional = true } diff --git a/ethcore/Cargo.toml b/ethcore/Cargo.toml index d1c9d624b..17f79840e 100644 --- a/ethcore/Cargo.toml +++ b/ethcore/Cargo.toml @@ -43,6 +43,7 @@ rlp = { path = "../util/rlp" } ethcore-stratum = { path = "../stratum" } ethcore-bloom-journal = { path = "../util/bloom" } hardware-wallet = { path = "../hw" } +ethcore-logger = { path = "../logger" } stats = { path = "../util/stats" } num = "0.1" diff --git a/ethcore/src/json_tests/chain.rs b/ethcore/src/json_tests/chain.rs index 221fa1aba..987280bc1 100644 --- a/ethcore/src/json_tests/chain.rs +++ b/ethcore/src/json_tests/chain.rs @@ -25,7 +25,7 @@ use miner::Miner; use io::IoChannel; pub fn json_chain_test(json_data: &[u8], era: ChainEra) -> Vec { - init_log(); + ::ethcore_logger::init_log(); let tests = ethjson::blockchain::Test::load(json_data).unwrap(); let mut failed = Vec::new(); diff --git a/ethcore/src/json_tests/state.rs b/ethcore/src/json_tests/state.rs index 5a6b1ccd0..6388daf94 100644 --- a/ethcore/src/json_tests/state.rs +++ b/ethcore/src/json_tests/state.rs @@ -22,7 +22,7 @@ use ethereum; use ethjson; pub fn json_chain_test(json_data: &[u8], era: ChainEra) -> Vec { - init_log(); + ::ethcore_logger::init_log(); let tests = ethjson::state::Test::load(json_data).unwrap(); let mut failed = Vec::new(); let engine = match era { diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index 75c8a80e1..df0738997 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -106,6 +106,7 @@ extern crate ethcore_stratum; extern crate ethabi; extern crate hardware_wallet; extern crate stats; +extern crate ethcore_logger; extern crate num; #[macro_use] diff --git a/ethcore/src/miner/price_info.rs b/ethcore/src/miner/price_info.rs index 4cc6fb36b..29994afb4 100644 --- a/ethcore/src/miner/price_info.rs +++ b/ethcore/src/miner/price_info.rs @@ -110,7 +110,7 @@ impl PriceInfo { fn should_get_price_info() { use std::sync::Arc; use std::time::Duration; - use util::log::init_log; + use ethcore_logger::init_log; use util::{Condvar, Mutex}; init_log(); diff --git a/ethcore/src/miner/transaction_queue.rs b/ethcore/src/miner/transaction_queue.rs index 9a3e6af1a..81c944e4d 100644 --- a/ethcore/src/miner/transaction_queue.rs +++ b/ethcore/src/miner/transaction_queue.rs @@ -2454,6 +2454,7 @@ pub mod test { #[test] fn should_replace_same_transaction_when_has_higher_fee() { + use ethcore_logger::init_log; init_log(); // given let mut txq = TransactionQueue::default(); diff --git a/ethcore/src/state/mod.rs b/ethcore/src/state/mod.rs index c34f43041..6e2a956ab 100644 --- a/ethcore/src/state/mod.rs +++ b/ethcore/src/state/mod.rs @@ -946,7 +946,7 @@ mod tests { use env_info::EnvInfo; use spec::*; use transaction::*; - use util::log::init_log; + use ethcore_logger::init_log; use trace::{FlatTrace, TraceError, trace}; use types::executed::CallType; diff --git a/ethcore/src/state_db.rs b/ethcore/src/state_db.rs index bfd1068ca..2831d2f9b 100644 --- a/ethcore/src/state_db.rs +++ b/ethcore/src/state_db.rs @@ -457,7 +457,7 @@ mod tests { use util::{U256, H256, Address, DBTransaction}; use tests::helpers::*; use state::{Account, Backend}; - use util::log::init_log; + use ethcore_logger::init_log; #[test] fn state_db_smoke() { diff --git a/logger/Cargo.toml b/logger/Cargo.toml index e0004cd48..b505355c8 100644 --- a/logger/Cargo.toml +++ b/logger/Cargo.toml @@ -8,11 +8,13 @@ authors = ["Parity Technologies "] [dependencies] log = "0.3" env_logger = "0.3" -ethcore-util = { path = "../util" } isatty = "0.1" lazy_static = "0.2" regex = "0.1" time = "0.1" +parking_lot = "0.3" +arrayvec = "0.3" +ansi_term = "0.9" [profile.release] debug = true diff --git a/logger/src/lib.rs b/logger/src/lib.rs index f9188d928..b492f4f78 100644 --- a/logger/src/lib.rs +++ b/logger/src/lib.rs @@ -16,7 +16,7 @@ //! Logger for parity executables -extern crate ethcore_util as util; +extern crate arrayvec; extern crate log as rlog; extern crate isatty; extern crate regex; @@ -24,6 +24,10 @@ extern crate env_logger; extern crate time; #[macro_use] extern crate lazy_static; +extern crate parking_lot; +extern crate ansi_term; + +mod rotating; use std::{env, thread, fs}; use std::sync::{Weak, Arc}; @@ -31,8 +35,10 @@ use std::io::Write; use isatty::{stderr_isatty, stdout_isatty}; use env_logger::LogBuilder; use regex::Regex; -use util::{Mutex, RotatingLogger} ; -use util::log::Colour; +use ansi_term::Colour; +use parking_lot::Mutex; + +pub use rotating::{RotatingLogger, init_log}; #[derive(Debug, PartialEq, Clone)] pub struct Config { diff --git a/util/src/log.rs b/logger/src/rotating.rs similarity index 98% rename from util/src/log.rs rename to logger/src/rotating.rs index 4e537603d..2d98ebcd0 100644 --- a/util/src/log.rs +++ b/logger/src/rotating.rs @@ -20,7 +20,6 @@ use std::env; use rlog::LogLevelFilter; use env_logger::LogBuilder; use arrayvec::ArrayVec; -pub use ansi_term::{Colour, Style}; use parking_lot::{RwLock, RwLockReadGuard}; diff --git a/parity/configuration.rs b/parity/configuration.rs index 9b491143d..a9a9159e1 100644 --- a/parity/configuration.rs +++ b/parity/configuration.rs @@ -22,7 +22,7 @@ use std::cmp::max; use cli::{Args, ArgsError}; use util::{Hashable, H256, U256, Uint, Bytes, version_data, Address}; use util::journaldb::Algorithm; -use util::log::Colour; +use util::Colour; use ethsync::{NetworkConfiguration, is_valid_node_url, AllowIP}; use ethcore::ethstore::ethkey::Secret; use ethcore::client::{VMType}; @@ -824,7 +824,7 @@ impl Configuration { } fn directories(&self) -> Directories { - use util::path; + use path; let local_path = default_local_path(); let base_path = self.args.flag_base_path.as_ref().map_or_else(|| default_data_path(), |s| s.clone()); diff --git a/parity/helpers.rs b/parity/helpers.rs index d691aabc6..e98c31ab7 100644 --- a/parity/helpers.rs +++ b/parity/helpers.rs @@ -18,7 +18,7 @@ use std::{io, env}; use std::io::{Write, BufReader, BufRead}; use std::time::Duration; use std::fs::File; -use util::{clean_0x, U256, Uint, Address, path, CompactionProfile}; +use util::{clean_0x, U256, Uint, Address, CompactionProfile}; use util::journaldb::Algorithm; use ethcore::client::{Mode, BlockId, VMType, DatabaseCompactionProfile, ClientConfig, VerifierType}; use ethcore::miner::{PendingSet, GasLimit, PrioritizationStrategy}; @@ -27,6 +27,7 @@ use dir::DatabaseDirectories; use upgrade::{upgrade, upgrade_data_paths}; use migration::migrate; use ethsync::is_valid_node_url; +use path; pub fn to_duration(s: &str) -> Result { to_seconds(s).map(Duration::from_secs) @@ -465,7 +466,7 @@ but the first password is trimmed #[test] #[cfg(not(windows))] fn test_geth_ipc_path() { - use util::path; + use path; assert_eq!(geth_ipc_path(true), path::ethereum::with_testnet("geth.ipc").to_str().unwrap().to_owned()); assert_eq!(geth_ipc_path(false), path::ethereum::with_default("geth.ipc").to_str().unwrap().to_owned()); } diff --git a/parity/main.rs b/parity/main.rs index 7d22be1c3..3e499d483 100644 --- a/parity/main.rs +++ b/parity/main.rs @@ -61,6 +61,7 @@ extern crate parity_reactor; extern crate parity_updater as updater; extern crate parity_local_store as local_store; extern crate rpc_cli; +extern crate path; #[macro_use] extern crate log as rlog; diff --git a/parity/rpc_apis.rs b/parity/rpc_apis.rs index 469245c19..cc45e3f8b 100644 --- a/parity/rpc_apis.rs +++ b/parity/rpc_apis.rs @@ -33,7 +33,7 @@ use ethsync::{ManageNetwork, SyncProvider}; use hash_fetch::fetch::Client as FetchClient; use jsonrpc_core::{MetaIoHandler}; use updater::Updater; -use util::RotatingLogger; +use ethcore_logger::RotatingLogger; #[derive(Debug, PartialEq, Clone, Eq, Hash)] pub enum Api { diff --git a/parity/run.rs b/parity/run.rs index b3313c16e..f781a8774 100644 --- a/parity/run.rs +++ b/parity/run.rs @@ -20,9 +20,9 @@ use ctrlc::CtrlC; use fdlimit::raise_fd_limit; use ethcore_rpc::{NetworkSettings, informant, is_major_importing}; use ethsync::NetworkConfiguration; -use util::{Colour, version, RotatingLogger, Mutex, Condvar}; +use util::{Colour, version, Mutex, Condvar}; use io::{MayPanic, ForwardPanic, PanicHandler}; -use ethcore_logger::{Config as LogConfig}; +use ethcore_logger::{Config as LogConfig, RotatingLogger}; use ethcore::miner::{StratumOptions, Stratum}; use ethcore::client::{Client, Mode, DatabaseCompactionProfile, VMType, BlockChainClient}; use ethcore::service::ClientService; diff --git a/parity/signer.rs b/parity/signer.rs index 346276496..d69670204 100644 --- a/parity/signer.rs +++ b/parity/signer.rs @@ -29,7 +29,7 @@ use helpers::replace_home; use io::{ForwardPanic, PanicHandler}; use jsonrpc_core::reactor::{RpcHandler, Remote}; use rpc_apis; -use util::path::restrict_permissions_owner; +use path::restrict_permissions_owner; use util::H256; const CODES_FILENAME: &'static str = "authcodes"; diff --git a/rpc/Cargo.toml b/rpc/Cargo.toml index 0b3cc4b82..d18393902 100644 --- a/rpc/Cargo.toml +++ b/rpc/Cargo.toml @@ -34,6 +34,7 @@ ethsync = { path = "../sync" } ethjson = { path = "../json" } ethcore-devtools = { path = "../devtools" } ethcore-light = { path = "../ethcore/light" } +ethcore-logger = { path = "../logger" } parity-updater = { path = "../updater" } rlp = { path = "../util/rlp" } fetch = { path = "../util/fetch" } diff --git a/rpc/src/lib.rs b/rpc/src/lib.rs index 201f41c22..a00b138ac 100644 --- a/rpc/src/lib.rs +++ b/rpc/src/lib.rs @@ -34,6 +34,7 @@ extern crate ethstore; extern crate ethsync; extern crate ethash; extern crate ethcore_light as light; +extern crate ethcore_logger; extern crate transient_hashmap; extern crate jsonrpc_ipc_server as ipc; extern crate ethcore_ipc; diff --git a/rpc/src/v1/impls/light/parity.rs b/rpc/src/v1/impls/light/parity.rs index 49421fd04..545935417 100644 --- a/rpc/src/v1/impls/light/parity.rs +++ b/rpc/src/v1/impls/light/parity.rs @@ -19,7 +19,7 @@ use std::sync::Arc; use std::collections::{BTreeMap, HashSet}; use futures::{future, Future, BoxFuture}; -use util::RotatingLogger; +use ethcore_logger::RotatingLogger; use util::misc::version_data; use crypto::ecies; diff --git a/rpc/src/v1/impls/parity.rs b/rpc/src/v1/impls/parity.rs index aee4dc3fd..2a7f85aa3 100644 --- a/rpc/src/v1/impls/parity.rs +++ b/rpc/src/v1/impls/parity.rs @@ -20,7 +20,8 @@ use std::str::FromStr; use std::collections::{BTreeMap, HashSet}; use futures::{future, Future, BoxFuture}; -use util::{RotatingLogger, Address}; +use ethcore_logger::RotatingLogger; +use util::Address; use util::misc::version_data; use crypto::ecies; diff --git a/rpc/src/v1/tests/mocked/parity.rs b/rpc/src/v1/tests/mocked/parity.rs index 59cde8594..8acedc2d4 100644 --- a/rpc/src/v1/tests/mocked/parity.rs +++ b/rpc/src/v1/tests/mocked/parity.rs @@ -15,7 +15,7 @@ // along with Parity. If not, see . use std::sync::Arc; -use util::log::RotatingLogger; +use ethcore_logger::RotatingLogger; use util::Address; use ethsync::ManageNetwork; use ethcore::account_provider::AccountProvider; diff --git a/rpc/src/v1/types/confirmations.rs b/rpc/src/v1/types/confirmations.rs index dd44e5750..f749df449 100644 --- a/rpc/src/v1/types/confirmations.rs +++ b/rpc/src/v1/types/confirmations.rs @@ -18,7 +18,7 @@ use std::fmt; use serde::{Serialize, Serializer}; -use util::log::Colour; +use util::Colour; use util::bytes::ToPretty; use v1::types::{U256, TransactionRequest, RichRawTransaction, H160, H256, H520, Bytes, TransactionCondition, Origin}; diff --git a/rpc/src/v1/types/transaction_request.rs b/rpc/src/v1/types/transaction_request.rs index 5839a0de8..242c02360 100644 --- a/rpc/src/v1/types/transaction_request.rs +++ b/rpc/src/v1/types/transaction_request.rs @@ -18,7 +18,7 @@ use v1::types::{Bytes, H160, U256, TransactionCondition}; use v1::helpers; -use util::log::Colour; +use util::Colour; use std::fmt; diff --git a/stratum/Cargo.toml b/stratum/Cargo.toml index 1b309985a..df984bef1 100644 --- a/stratum/Cargo.toml +++ b/stratum/Cargo.toml @@ -24,6 +24,7 @@ semver = "0.5" ethcore-ipc-nano = { path = "../ipc/nano" } futures = "0.1" tokio-core = "0.1" +ethcore-logger = { path = "../logger" } [profile.release] debug = true diff --git a/stratum/src/lib.rs b/stratum/src/lib.rs index 59964773c..5a7d50613 100644 --- a/stratum/src/lib.rs +++ b/stratum/src/lib.rs @@ -24,6 +24,7 @@ extern crate ethcore_util as util; extern crate ethcore_ipc as ipc; extern crate semver; extern crate futures; +extern crate ethcore_logger; #[cfg(test)] extern crate tokio_core; extern crate ethcore_devtools as devtools; @@ -323,6 +324,8 @@ mod tests { use tokio_core::io; use futures::{Future, future}; + use ethcore_logger::init_log; + pub struct VoidManager; impl JobDispatcher for VoidManager { @@ -331,32 +334,6 @@ mod tests { } } - lazy_static! { - static ref LOG_DUMMY: bool = { - use log::LogLevelFilter; - use env_logger::LogBuilder; - use std::env; - - let mut builder = LogBuilder::new(); - builder.filter(None, LogLevelFilter::Info); - - if let Ok(log) = env::var("RUST_LOG") { - builder.parse(&log); - } - - if let Ok(_) = builder.init() { - println!("logger initialized"); - } - true - }; - } - - /// Intialize log with default settings - #[cfg(test)] - fn init_log() { - let _ = *LOG_DUMMY; - } - fn dummy_request(addr: &SocketAddr, data: &str) -> Vec { let mut core = Core::new().expect("Tokio Core should be created with no errors"); let mut buffer = vec![0u8; 2048]; diff --git a/updater/Cargo.toml b/updater/Cargo.toml index c0738cc59..53088d030 100644 --- a/updater/Cargo.toml +++ b/updater/Cargo.toml @@ -20,6 +20,7 @@ parity-hash-fetch = { path = "../hash-fetch" } ipc-common-types = { path = "../ipc-common-types" } ethcore-ipc = { path = "../ipc/rpc" } parity-reactor = { path = "../util/reactor" } +path = { path = "../util/path" } [profile.release] debug = true diff --git a/updater/src/lib.rs b/updater/src/lib.rs index 7d7146d7e..730af956d 100644 --- a/updater/src/lib.rs +++ b/updater/src/lib.rs @@ -26,6 +26,7 @@ extern crate ethsync; extern crate ethcore_ipc as ipc; extern crate target_info; extern crate parity_reactor; +extern crate path; mod updater; mod operations; diff --git a/updater/src/updater.rs b/updater/src/updater.rs index c2bc98273..5a4e2e1c9 100644 --- a/updater/src/updater.rs +++ b/updater/src/updater.rs @@ -21,7 +21,7 @@ use std::path::{PathBuf}; use target_info::Target; use util::misc; use ipc_common_types::{VersionInfo, ReleaseTrack}; -use util::path::restrict_permissions_owner; +use path::restrict_permissions_owner; use util::{Address, H160, H256, Mutex, Bytes}; use ethsync::{SyncProvider}; use ethcore::client::{BlockId, BlockChainClient, ChainNotify}; diff --git a/util/Cargo.toml b/util/Cargo.toml index d32d2519a..df34ccbfb 100644 --- a/util/Cargo.toml +++ b/util/Cargo.toml @@ -11,11 +11,9 @@ build = "build.rs" log = "0.3" env_logger = "0.3" rustc-serialize = "0.3" -arrayvec = "0.3" rand = "0.3.12" time = "0.1.34" rocksdb = { git = "https://github.com/ethcore/rust-rocksdb" } -lazy_static = "0.2" eth-secp256k1 = { git = "https://github.com/ethcore/rust-secp256k1" } rust-crypto = "0.2.34" elastic-array = { git = "https://github.com/ethcore/elastic-array" } @@ -32,11 +30,12 @@ ethcore-bigint = { path = "bigint" } parking_lot = "0.3" using_queue = { path = "using_queue" } table = { path = "table" } -ansi_term = "0.7" +ansi_term = "0.9" tiny-keccak= "1.0" ethcore-bloom-journal = { path = "bloom" } regex = "0.1" lru-cache = "0.1.0" +ethcore-logger = { path = "../logger" } [features] default = [] diff --git a/util/network/Cargo.toml b/util/network/Cargo.toml index 7fced467a..2f1ac81d3 100644 --- a/util/network/Cargo.toml +++ b/util/network/Cargo.toml @@ -19,7 +19,7 @@ clippy = { version = "0.0.103", optional = true} igd = "0.5.0" libc = "0.2.7" parking_lot = "0.3" -ansi_term = "0.7" +ansi_term = "0.9" rustc-serialize = "0.3" ethcore-io = { path = "../io" } ethcore-util = { path = ".." } @@ -27,6 +27,8 @@ ethcore-devtools = { path = "../../devtools" } ethkey = { path = "../../ethkey" } ethcrypto = { path = "../../ethcrypto" } rlp = { path = "../rlp" } +path = { path = "../path" } +ethcore-logger = { path ="../../logger" } [features] default = [] diff --git a/util/network/src/host.rs b/util/network/src/host.rs index b64301369..bb4b4fb1e 100644 --- a/util/network/src/host.rs +++ b/util/network/src/host.rs @@ -40,7 +40,7 @@ use node_table::*; use stats::NetworkStats; use discovery::{Discovery, TableUpdates, NodeEntry}; use ip_utils::{map_external_address, select_public_address}; -use util::path::restrict_permissions_owner; +use path::restrict_permissions_owner; use parking_lot::{Mutex, RwLock}; type Slab = ::slab::Slab; diff --git a/util/network/src/lib.rs b/util/network/src/lib.rs index 862200fa3..c4cc524f4 100644 --- a/util/network/src/lib.rs +++ b/util/network/src/lib.rs @@ -71,6 +71,8 @@ extern crate ethkey; extern crate ethcrypto as crypto; extern crate rlp; extern crate bytes; +extern crate path; +extern crate ethcore_logger; #[macro_use] extern crate log; diff --git a/util/network/src/tests.rs b/util/network/src/tests.rs index fba8f6eb4..692dd94a0 100644 --- a/util/network/src/tests.rs +++ b/util/network/src/tests.rs @@ -98,7 +98,7 @@ fn net_service() { #[test] fn net_connect() { - ::util::log::init_log(); + ::ethcore_logger::init_log(); let key1 = Random.generate().unwrap(); let mut config1 = NetworkConfiguration::new_local(); config1.use_secret = Some(key1.secret().clone()); diff --git a/util/path/Cargo.toml b/util/path/Cargo.toml new file mode 100644 index 000000000..7df3917b1 --- /dev/null +++ b/util/path/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "path" +version = "0.1.0" +authors = ["debris "] + +[dependencies] diff --git a/util/src/path.rs b/util/path/src/lib.rs similarity index 100% rename from util/src/path.rs rename to util/path/src/lib.rs diff --git a/util/src/journaldb/earlymergedb.rs b/util/src/journaldb/earlymergedb.rs index f484a623a..bd05d5fc1 100644 --- a/util/src/journaldb/earlymergedb.rs +++ b/util/src/journaldb/earlymergedb.rs @@ -553,7 +553,7 @@ mod tests { use hashdb::{HashDB, DBValue}; use super::*; use super::super::traits::JournalDB; - use log::init_log; + use ethcore_logger::init_log; use kvdb::{DatabaseConfig}; #[test] diff --git a/util/src/journaldb/overlayrecentdb.rs b/util/src/journaldb/overlayrecentdb.rs index 90f7acfcf..e8095e71e 100644 --- a/util/src/journaldb/overlayrecentdb.rs +++ b/util/src/journaldb/overlayrecentdb.rs @@ -456,7 +456,7 @@ mod tests { use common::*; use super::*; use hashdb::{HashDB, DBValue}; - use log::init_log; + use ethcore_logger::init_log; use journaldb::JournalDB; use kvdb::Database; diff --git a/util/src/lib.rs b/util/src/lib.rs index 4e46dbc24..93e03c8b1 100644 --- a/util/src/lib.rs +++ b/util/src/lib.rs @@ -93,7 +93,6 @@ extern crate rocksdb; extern crate env_logger; extern crate crypto as rcrypto; extern crate secp256k1; -extern crate arrayvec; extern crate elastic_array; extern crate time; extern crate ethcore_devtools as devtools; @@ -108,9 +107,8 @@ extern crate regex; extern crate lru_cache; extern crate heapsize; extern crate itertools; +extern crate ethcore_logger; -#[macro_use] -extern crate lazy_static; #[macro_use] extern crate log as rlog; @@ -137,8 +135,6 @@ pub mod trie; pub mod nibbleslice; pub mod nibblevec; pub mod semantic_version; -pub mod log; -pub mod path; pub mod snappy; pub mod cache; mod timer; @@ -153,9 +149,9 @@ pub use triehash::*; pub use trie::{Trie, TrieMut, TrieDB, TrieDBMut, TrieFactory, TrieError, SecTrieDB, SecTrieDBMut}; pub use nibbleslice::*; pub use semantic_version::*; -pub use log::*; pub use kvdb::*; pub use timer::*; +pub use ansi_term::{Colour, Style}; /// 160-bit integer representing account address pub type Address = H160; diff --git a/util/src/trie/triedbmut.rs b/util/src/trie/triedbmut.rs index 10d7f3aa6..c5f2a739b 100644 --- a/util/src/trie/triedbmut.rs +++ b/util/src/trie/triedbmut.rs @@ -958,7 +958,7 @@ mod tests { #[test] fn playpen() { - ::log::init_log(); + ::ethcore_logger::init_log(); let mut seed = H256::new(); for test_i in 0..10 { From 7e87e9e8ad14bbb9c93d7ce5589cff439e13d8c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Wed, 22 Mar 2017 07:02:14 +0100 Subject: [PATCH 04/11] Updating JSON-RPC crates (#4934) * New version of jsonrpc. * Better invalid encoding messages * Fixing deprecated methods of tokio_core * Using dedicated branch for jsonrpc * Bump --- Cargo.lock | 397 +++++++++++++-------- Cargo.toml | 6 +- dapps/Cargo.toml | 29 +- dapps/src/api/api.rs | 49 ++- dapps/src/lib.rs | 92 ++--- dapps/src/router/host_validation.rs | 15 +- dapps/src/router/mod.rs | 30 +- dapps/src/rpc.rs | 52 ++- dapps/src/tests/api.rs | 46 +-- dapps/src/tests/helpers/fetch.rs | 2 +- dapps/src/tests/helpers/mod.rs | 38 +- dapps/src/tests/redirection.rs | 22 +- dapps/src/tests/rpc.rs | 5 +- ethcore/Cargo.toml | 5 +- ethcore/light/src/on_demand/mod.rs | 21 +- ethcore/src/spec/spec.rs | 2 +- ipfs/Cargo.toml | 3 +- ipfs/src/error.rs | 8 +- ipfs/src/lib.rs | 83 ++--- json/src/hash.rs | 8 +- json/src/uint.rs | 10 +- parity/dapps.rs | 27 +- parity/ipfs.rs | 69 ++-- parity/rpc.rs | 43 ++- parity/run.rs | 3 - parity/signer.rs | 17 +- rpc/Cargo.toml | 21 +- rpc/src/lib.rs | 113 +++--- rpc/src/v1/helpers/mod.rs | 1 + rpc/src/v1/helpers/oneshot.rs | 67 ++++ rpc/src/v1/impls/signing.rs | 45 ++- rpc/src/v1/tests/helpers/fetch.rs | 2 +- rpc/src/v1/tests/mocked/eth.rs | 6 +- rpc/src/v1/tests/mocked/parity.rs | 8 +- rpc/src/v1/tests/mocked/parity_accounts.rs | 2 +- rpc/src/v1/tests/mocked/traces.rs | 6 +- rpc/src/v1/types/hash.rs | 9 +- rpc/src/v1/types/uint.rs | 16 +- rpc_client/Cargo.toml | 8 +- rpc_client/src/client.rs | 20 +- signer/Cargo.toml | 5 +- signer/src/lib.rs | 11 +- signer/src/tests/mod.rs | 9 +- signer/src/ws_server/mod.rs | 26 +- signer/src/ws_server/session.rs | 21 +- stratum/Cargo.toml | 7 +- stratum/src/lib.rs | 28 +- util/reactor/src/lib.rs | 11 +- 48 files changed, 847 insertions(+), 677 deletions(-) create mode 100644 rpc/src/v1/helpers/oneshot.rs diff --git a/Cargo.lock b/Cargo.lock index d039c1646..819226c00 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5,7 +5,7 @@ dependencies = [ "ansi_term 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "app_dirs 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "clippy 0.0.103 (registry+https://github.com/rust-lang/crates.io-index)", - "ctrlc 1.1.1 (git+https://github.com/ethcore/rust-ctrlc.git)", + "ctrlc 1.1.1 (git+https://github.com/paritytech/rust-ctrlc.git)", "daemonize 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "docopt 0.6.80 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -27,9 +27,9 @@ dependencies = [ "ethsync 1.7.0", "evmbin 0.1.0", "fdlimit 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.10.0-a.0 (git+https://github.com/ethcore/hyper)", + "hyper 0.10.0-a.0 (git+https://github.com/paritytech/hyper)", "isatty 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-core 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", + "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "num_cpus 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "number_prefix 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -194,6 +194,15 @@ dependencies = [ "stable-heap 0.1.0 (git+https://github.com/carllerche/stable-heap?rev=3c5cd1ca47)", ] +[[package]] +name = "bytes" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byteorder 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "iovec 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "cfg-if" version = "0.1.0" @@ -283,7 +292,7 @@ dependencies = [ [[package]] name = "ctrlc" version = "1.1.1" -source = "git+https://github.com/ethcore/rust-ctrlc.git#f4927770f89eca80ec250911eea3adcbf579ac48" +source = "git+https://github.com/paritytech/rust-ctrlc.git#b523017108bb2d571a7a69bd97bc406e63bc7a9d" dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", @@ -403,7 +412,7 @@ dependencies = [ "ethstore 0.1.0", "evmjit 1.7.0", "hardware-wallet 1.7.0", - "hyper 0.10.0-a.0 (git+https://github.com/ethcore/hyper)", + "hyper 0.10.0-a.0 (git+https://github.com/paritytech/hyper)", "lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "linked-hash-map 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", @@ -449,10 +458,10 @@ dependencies = [ "ethcore-rpc 1.7.0", "ethcore-util 1.7.0", "fetch 0.1.0", - "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.10.0-a.0 (git+https://github.com/ethcore/hyper)", - "jsonrpc-core 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", - "jsonrpc-http-server 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", + "jsonrpc-http-server 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", + "jsonrpc-server-utils 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "linked-hash-map 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "mime 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -558,7 +567,7 @@ dependencies = [ "ethcore-ipc-codegen 1.7.0", "ethcore-network 1.7.0", "ethcore-util 1.7.0", - "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", "itertools 0.5.9 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", @@ -629,11 +638,11 @@ dependencies = [ "ethstore 0.1.0", "ethsync 1.7.0", "fetch 0.1.0", - "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-core 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", - "jsonrpc-http-server 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", - "jsonrpc-ipc-server 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", - "jsonrpc-macros 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", + "jsonrpc-http-server 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", + "jsonrpc-ipc-server 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", + "jsonrpc-macros 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "order-stat 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "parity-reactor 0.1.0", @@ -660,7 +669,7 @@ dependencies = [ "ethcore-util 1.7.0", "ethcrypto 0.1.0", "ethkey 0.2.0", - "hyper 0.10.4 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.5 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -676,13 +685,14 @@ dependencies = [ "ethcore-io 1.7.0", "ethcore-rpc 1.7.0", "ethcore-util 1.7.0", - "jsonrpc-core 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", + "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", + "jsonrpc-server-utils 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-dapps-glue 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "parity-ui 1.7.0", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", - "ws 0.5.3 (git+https://github.com/ethcore/ws-rs.git?branch=mio-upstream-stable)", + "ws 0.5.3 (git+https://github.com/paritytech/ws-rs.git?branch=mio-upstream-stable)", ] [[package]] @@ -696,15 +706,14 @@ dependencies = [ "ethcore-ipc-nano 1.7.0", "ethcore-logger 1.7.0", "ethcore-util 1.7.0", - "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-core 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", - "jsonrpc-macros 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", - "jsonrpc-tcp-server 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", + "jsonrpc-macros 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", + "jsonrpc-tcp-server 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.5.1 (git+https://github.com/ethcore/mio?branch=v0.5.x)", "semver 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-core 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "tokio-core 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -858,7 +867,7 @@ dependencies = [ name = "fetch" version = "0.1.0" dependencies = [ - "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", "futures-cpupool 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "mime 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -877,11 +886,8 @@ dependencies = [ [[package]] name = "futures" -version = "0.1.10" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", -] [[package]] name = "futures-cpupool" @@ -889,7 +895,7 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "crossbeam 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", "num_cpus 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -985,7 +991,7 @@ dependencies = [ [[package]] name = "hyper" version = "0.10.0-a.0" -source = "git+https://github.com/ethcore/hyper#453c683b52208fefc32d29e4ac7c863439b2321f" +source = "git+https://github.com/paritytech/hyper#453c683b52208fefc32d29e4ac7c863439b2321f" dependencies = [ "cookie 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "httparse 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1003,7 +1009,7 @@ dependencies = [ [[package]] name = "hyper" -version = "0.10.4" +version = "0.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "httparse 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1014,7 +1020,7 @@ dependencies = [ "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", - "traitobject 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "traitobject 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "typeable 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1026,7 +1032,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "antidote 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.10.4 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.5 (registry+https://github.com/rust-lang/crates.io-index)", "native-tls 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1057,6 +1063,15 @@ name = "integer-encoding" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "iovec" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "ipc-common-types" version = "1.7.0" @@ -1092,67 +1107,82 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "jsonrpc-core" -version = "6.0.0" -source = "git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6#86d7a89c85f324b5f6671315d9b71010ca995300" +version = "7.0.0" +source = "git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7#707cf73a7b72f2eecbf3665c53b4159ec867cbed" dependencies = [ - "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.9.6 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 0.9.6 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 0.9.5 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-core 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "jsonrpc-http-server" -version = "6.0.0" -source = "git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6#86d7a89c85f324b5f6671315d9b71010ca995300" +version = "7.0.0" +source = "git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7#707cf73a7b72f2eecbf3665c53b4159ec867cbed" dependencies = [ - "hyper 0.10.0-a.0 (git+https://github.com/ethcore/hyper)", - "jsonrpc-core 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", + "hyper 0.10.0-a.0 (git+https://github.com/paritytech/hyper)", + "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", + "jsonrpc-server-utils 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-core 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "jsonrpc-ipc-server" -version = "6.0.0" -source = "git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6#86d7a89c85f324b5f6671315d9b71010ca995300" +version = "7.0.0" +source = "git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7#707cf73a7b72f2eecbf3665c53b4159ec867cbed" dependencies = [ - "bytes 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-core 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", - "lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", + "jsonrpc-server-utils 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", - "slab 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-tokio-ipc 0.1.0 (git+https://github.com/nikvolf/parity-tokio-ipc)", + "tokio-service 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "jsonrpc-macros" -version = "6.0.0" -source = "git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6#86d7a89c85f324b5f6671315d9b71010ca995300" +version = "7.0.0" +source = "git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7#707cf73a7b72f2eecbf3665c53b4159ec867cbed" dependencies = [ - "jsonrpc-core 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", + "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", + "jsonrpc-pubsub 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "serde 0.9.6 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "jsonrpc-tcp-server" -version = "6.0.0" -source = "git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6#86d7a89c85f324b5f6671315d9b71010ca995300" +name = "jsonrpc-pubsub" +version = "7.0.0" +source = "git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7#707cf73a7b72f2eecbf3665c53b4159ec867cbed" dependencies = [ - "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-core 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", - "lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "jsonrpc-server-utils" +version = "7.0.0" +source = "git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7#707cf73a7b72f2eecbf3665c53b4159ec867cbed" +dependencies = [ + "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", + "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "tokio-core 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", + "tokio-io 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "jsonrpc-tcp-server" +version = "7.0.0" +source = "git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7#707cf73a7b72f2eecbf3665c53b4159ec867cbed" +dependencies = [ + "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", + "jsonrpc-server-utils 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", + "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 0.9.5 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-core 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-proto 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "tokio-service 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1180,6 +1210,11 @@ name = "lazycell" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "lazycell" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "libc" version = "0.2.21" @@ -1268,38 +1303,6 @@ dependencies = [ "libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "mio" -version = "0.5.1" -source = "git+https://github.com/ethcore/mio?branch=v0.5.x#3842d3b250ffd7bd9b16f9586b875ddcbac2b0dd" -dependencies = [ - "bytes 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", - "nix 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "slab 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "mio" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bytes 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", - "nix 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "slab 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "mio" version = "0.6.0-dev" @@ -1308,7 +1311,7 @@ dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", + "miow 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", "nix 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "slab 0.2.0 (git+https://github.com/carllerche/slab?rev=5476efcafb)", @@ -1318,13 +1321,13 @@ dependencies = [ [[package]] name = "mio" version = "0.6.1" -source = "git+https://github.com/ethcore/mio#ef182bae193a9c7457cd2cf661fcaffb226e3eef" +source = "git+https://github.com/ethcore/mio#15a577039bed3c72f2952459f8ad687a56f63e29" dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "lazycell 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", + "miow 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", "nix 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "slab 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1333,23 +1336,56 @@ dependencies = [ [[package]] name = "mio" -version = "0.6.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "lazycell 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", + "miow 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", "nix 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "slab 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "mio-named-pipes" +version = "0.1.4" +source = "git+https://github.com/alexcrichton/mio-named-pipes#903dc2f7eac6700c62bfdda258a599db13a9228f" +dependencies = [ + "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "lazycell 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "mio 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", + "miow 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "mio-uds" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", + "mio 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "miow" -version = "0.1.3" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", + "ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "miow" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1427,15 +1463,6 @@ dependencies = [ "ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "nix" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "nix" version = "0.6.0" @@ -1624,7 +1651,7 @@ dependencies = [ "ethabi 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "ethcore-util 1.7.0", "fetch 0.1.0", - "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "mime 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "mime_guess 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1640,8 +1667,7 @@ dependencies = [ "cid 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "ethcore 1.7.0", "ethcore-util 1.7.0", - "hyper 0.10.0-a.0 (git+https://github.com/ethcore/hyper)", - "jsonrpc-http-server 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", + "jsonrpc-http-server 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "mime 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "multihash 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "rlp 0.1.0", @@ -1666,8 +1692,8 @@ dependencies = [ name = "parity-reactor" version = "0.1.0" dependencies = [ - "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-core 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "tokio-core 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1677,15 +1703,31 @@ dependencies = [ "ethcore-rpc 1.7.0", "ethcore-signer 1.7.0", "ethcore-util 1.7.0", - "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-core 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.9.6 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 0.9.5 (registry+https://github.com/rust-lang/crates.io-index)", "tempdir 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "ws 0.5.3 (git+https://github.com/ethcore/ws-rs.git?branch=mio-upstream-stable)", + "ws 0.5.3 (git+https://github.com/paritytech/ws-rs.git?branch=mio-upstream-stable)", +] + +[[package]] +name = "parity-tokio-ipc" +version = "0.1.0" +source = "git+https://github.com/nikvolf/parity-tokio-ipc#3d4234de6bdc78688ef803935111003080fd5375" +dependencies = [ + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "mio-named-pipes 0.1.4 (git+https://github.com/alexcrichton/mio-named-pipes)", + "miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", + "tokio-core 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", + "tokio-line 0.1.0 (git+https://github.com/tokio-rs/tokio-line)", + "tokio-named-pipes 0.1.0 (git+https://github.com/alexcrichton/tokio-named-pipes)", + "tokio-uds 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1916,7 +1958,7 @@ name = "reqwest" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "hyper 0.10.4 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.5 (registry+https://github.com/rust-lang/crates.io-index)", "hyper-native-tls 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.9.6 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2005,7 +2047,7 @@ dependencies = [ "ethcore-bigint 0.1.2", "ethcore-rpc 1.7.0", "ethcore-util 1.7.0", - "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", "parity-rpc-client 1.4.0", "rpassword 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -2205,11 +2247,6 @@ name = "siphasher" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "slab" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "slab" version = "0.2.0" @@ -2395,29 +2432,60 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "tokio-core" -version = "0.1.2" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mio 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", "scoped-tls 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "slab 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "tokio-io" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bytes 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "tokio-line" +version = "0.1.0" +source = "git+https://github.com/tokio-rs/tokio-line#482614ae0c82daf584727ae65a80d854fe861f81" +dependencies = [ + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "tokio-core 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", + "tokio-proto 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "tokio-service 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "tokio-named-pipes" +version = "0.1.0" +source = "git+https://github.com/alexcrichton/tokio-named-pipes#3a22f8fc9a441b548aec25bd5df3b1e0ab99fabe" +dependencies = [ + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "mio-named-pipes 0.1.4 (git+https://github.com/alexcrichton/mio-named-pipes)", + "tokio-core 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "tokio-proto" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "slab 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "smallvec 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "take 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-core 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "tokio-core 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", "tokio-service 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -2426,7 +2494,19 @@ name = "tokio-service" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "tokio-uds" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "mio 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", + "mio-uds 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", + "tokio-core 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2450,6 +2530,11 @@ name = "traitobject" version = "0.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "traitobject" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "transient-hashmap" version = "0.4.0" @@ -2557,7 +2642,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "ws" version = "0.5.3" -source = "git+https://github.com/ethcore/ws-rs.git?branch=mio-upstream-stable#f5c0b35d660244d1b7500693c8cc28277ce1d418" +source = "git+https://github.com/paritytech/ws-rs.git?branch=mio-upstream-stable#f5c0b35d660244d1b7500693c8cc28277ce1d418" dependencies = [ "bytes 0.4.0-dev (git+https://github.com/carllerche/bytes)", "httparse 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2632,6 +2717,7 @@ dependencies = [ "checksum byteorder 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c40977b0ee6b9885c9013cd41d9feffdd22deb3bb4dc3a71d901cc7a77de18c8" "checksum bytes 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c129aff112dcc562970abb69e2508b40850dd24c274761bb50fb8a0067ba6c27" "checksum bytes 0.4.0-dev (git+https://github.com/carllerche/bytes)" = "" +"checksum bytes 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "46112a0060ae15e3a3f9a445428a53e082b91215b744fa27a1948842f4a64b96" "checksum cfg-if 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "de1e760d7b6535af4241fca8bd8adf68e2e7edacc6b29f5d399050c5e48cf88c" "checksum cid 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "e53e6cdfa5ca294863e8c8a32a7cdb4dc0a442c8971d47a0e75b6c27ea268a6a" "checksum clippy 0.0.103 (registry+https://github.com/rust-lang/crates.io-index)" = "5b4fabf979ddf6419a313c1c0ada4a5b95cfd2049c56e8418d622d27b4b6ff32" @@ -2642,7 +2728,7 @@ dependencies = [ "checksum core-foundation-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "05eed248dc504a5391c63794fe4fb64f46f071280afaa1b73308f3c0ce4574c5" "checksum crossbeam 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)" = "0c5ea215664ca264da8a9d9c3be80d2eaf30923c259d03e870388eb927508f97" "checksum crypt32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e34988f7e069e0b2f3bfc064295161e489b2d4e04a2e4248fb94360cdf00b4ec" -"checksum ctrlc 1.1.1 (git+https://github.com/ethcore/rust-ctrlc.git)" = "" +"checksum ctrlc 1.1.1 (git+https://github.com/paritytech/rust-ctrlc.git)" = "" "checksum daemonize 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "271ec51b7e0bee92f0d04601422c73eb76ececf197026711c97ad25038a010cf" "checksum deque 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1614659040e711785ed8ea24219140654da1729f3ec8a47a9719d041112fe7bf" "checksum docopt 0.6.80 (registry+https://github.com/rust-lang/crates.io-index)" = "4cc0acb4ce0828c6a5a11d47baa432fe885881c27428c3a4e473e454ffe57a76" @@ -2654,7 +2740,7 @@ dependencies = [ "checksum ethabi 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5d8f6cc4c1acd005f48e1d17b06a461adac8fb6eeeb331fbf19a0e656fba91cd" "checksum fdlimit 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b1ee15a7050e5580b3712877157068ea713b245b080ff302ae2ca973cfcd9baa" "checksum flate2 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)" = "3eeb481e957304178d2e782f2da1257f1434dfecbae883bafb61ada2a9fea3bb" -"checksum futures 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "c1913eb7083840b1bbcbf9631b7fda55eaf35fe7ead13cca034e8946f9e2bc41" +"checksum futures 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "8e51e7f9c150ba7fd4cee9df8bf6ea3dea5b63b68955ddad19ccd35b71dcfb4d" "checksum futures-cpupool 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "bb982bb25cd8fa5da6a8eb3a460354c984ff1113da82bcb4f0b0862b5795db82" "checksum gcc 0.3.43 (registry+https://github.com/rust-lang/crates.io-index)" = "c07c758b972368e703a562686adb39125707cc1ef3399da8c019fc6c2498a75d" "checksum gdi32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0912515a8ff24ba900422ecda800b52f4016a56251922d397c576bf92c690518" @@ -2664,25 +2750,29 @@ dependencies = [ "checksum hidapi 0.3.1 (git+https://github.com/ethcore/hidapi-rs)" = "" "checksum hpack 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3d2da7d3a34cf6406d9d700111b8eafafe9a251de41ae71d8052748259343b58" "checksum httparse 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "46534074dbb80b070d60a5cb8ecadd8963a00a438ae1a95268850a7ef73b67ae" -"checksum hyper 0.10.0-a.0 (git+https://github.com/ethcore/hyper)" = "" -"checksum hyper 0.10.4 (registry+https://github.com/rust-lang/crates.io-index)" = "220407e5a263f110ec30a071787c9535918fdfc97def5680c90013c3f30c38c1" +"checksum hyper 0.10.0-a.0 (git+https://github.com/paritytech/hyper)" = "" +"checksum hyper 0.10.5 (registry+https://github.com/rust-lang/crates.io-index)" = "43a15e3273b2133aaac0150478ab443fb89f15c3de41d8d93d8f3bb14bf560f6" "checksum hyper 0.9.18 (registry+https://github.com/rust-lang/crates.io-index)" = "1b9bf64f730d6ee4b0528a5f0a316363da9d8104318731509d4ccc86248f82b3" "checksum hyper-native-tls 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "afe68f772f0497a7205e751626bb8e1718568b58534b6108c73a74ef80483409" "checksum idna 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1053236e00ce4f668aeca4a769a09b3bf5a682d802abd6f3cb39374f6b162c11" "checksum igd 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c8c12b1795b8b168f577c45fa10379b3814dcb11b7ab702406001f0d63f40484" "checksum integer-encoding 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a053c9c7dcb7db1f2aa012c37dc176c62e4cdf14898dee0eecc606de835b8acb" +"checksum iovec 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "29d062ee61fccdf25be172e70f34c9f6efc597e1fb8f6526e8437b2046ab26be" "checksum isatty 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7408a548dc0e406b7912d9f84c261cc533c1866e047644a811c133c56041ac0c" "checksum itertools 0.5.9 (registry+https://github.com/rust-lang/crates.io-index)" = "d95557e7ba6b71377b0f2c3b3ae96c53f1b75a926a6901a500f557a370af730a" "checksum itoa 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "91fd9dc2c587067de817fec4ad355e3818c3d893a78cab32a0a474c7a15bb8d5" -"checksum jsonrpc-core 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)" = "" -"checksum jsonrpc-http-server 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)" = "" -"checksum jsonrpc-ipc-server 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)" = "" -"checksum jsonrpc-macros 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)" = "" -"checksum jsonrpc-tcp-server 6.0.0 (git+https://github.com/ethcore/jsonrpc.git?branch=parity-1.6)" = "" +"checksum jsonrpc-core 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)" = "" +"checksum jsonrpc-http-server 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)" = "" +"checksum jsonrpc-ipc-server 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)" = "" +"checksum jsonrpc-macros 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)" = "" +"checksum jsonrpc-pubsub 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)" = "" +"checksum jsonrpc-server-utils 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)" = "" +"checksum jsonrpc-tcp-server 7.0.0 (git+https://github.com/paritytech/jsonrpc.git?branch=parity-1.7)" = "" "checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" "checksum language-tags 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a91d884b6667cd606bb5a69aa0c99ba811a115fc68915e7056ec08a46e93199a" "checksum lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "49247ec2a285bb3dcb23cbd9c35193c025e7251bfce77c1d5da97e6362dffe7f" "checksum lazycell 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ce12306c4739d86ee97c23139f3a34ddf0387bbf181bc7929d287025a8c3ef6b" +"checksum lazycell 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ec38a5c22f1ef3e30d2642aa875620d60edeef36cef43c4739d86215ce816331" "checksum libc 0.2.21 (registry+https://github.com/rust-lang/crates.io-index)" = "88ee81885f9f04bff991e306fea7c1c60a5f0f9e409e99f6b40e3311a3363135" "checksum libusb 0.3.0 (git+https://github.com/ethcore/libusb-rs)" = "" "checksum libusb-sys 0.2.3 (git+https://github.com/ethcore/libusb-sys)" = "" @@ -2695,12 +2785,13 @@ dependencies = [ "checksum mime 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a74cc2587bf97c49f3f5bab62860d6abf3902ca73b66b51d9b049fbdcd727bd2" "checksum mime_guess 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5e50bf542f81754ef69e5cea856946a3819f7c09ea97b4903c8bc8a89f74e7b6" "checksum miniz-sys 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "9d1f4d337a01c32e1f2122510fed46393d53ca35a7f429cb0450abaedfa3ed54" -"checksum mio 0.5.1 (git+https://github.com/ethcore/mio?branch=v0.5.x)" = "" -"checksum mio 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a637d1ca14eacae06296a008fa7ad955347e34efcb5891cfd8ba05491a37907e" "checksum mio 0.6.0-dev (git+https://github.com/ethcore/mio?branch=timer-fix)" = "" "checksum mio 0.6.1 (git+https://github.com/ethcore/mio)" = "" -"checksum mio 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "410a1a0ff76f5a226f1e4e3ff1756128e65cd30166e39c3892283e2ac09d5b67" -"checksum miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d5bfc6782530ac8ace97af10a540054a37126b63b0702ddaaa243b73b5745b9a" +"checksum mio 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "5b493dc9fd96bd2077f2117f178172b0765db4dfda3ea4d8000401e6d65d3e80" +"checksum mio-named-pipes 0.1.4 (git+https://github.com/alexcrichton/mio-named-pipes)" = "" +"checksum mio-uds 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "78437f00d9615c366932cbfe79790b5c2945706ba67cf78378ffacc0069ed9de" +"checksum miow 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "3e690c5df6b2f60acd45d56378981e827ff8295562fc8d34f573deb267a59cd1" +"checksum miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919" "checksum msdos_time 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "c04b68cc63a8480fb2550343695f7be72effdec953a9d4508161c3e69041c7d8" "checksum multibase 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b9c35dac080fd6e16a99924c8dfdef0af89d797dd851adab25feaffacf7850d6" "checksum multihash 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c9f70f2402fa07c16c40be8fd0a748a39257c5dc3ff5c857cbbde2f39135c505" @@ -2708,7 +2799,6 @@ dependencies = [ "checksum nanomsg-sys 0.5.0 (git+https://github.com/ethcore/nanomsg.rs.git?branch=parity-1.7)" = "" "checksum native-tls 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "aa4e52995154bb6f0b41e4379a279482c9387c1632e3798ba4e511ef8c54ee09" "checksum net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)" = "6a816012ca11cb47009693c1e0c6130e26d39e4d97ee2a13c50e868ec83e3204" -"checksum nix 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f05c2fc965fc1cd6b73fa57fa7b89f288178737f2f3ce9e63e4a6a141189000e" "checksum nix 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7a7bb1da2be7da3cbffda73fc681d509ffd9e665af478d2bee1907cee0bc64b2" "checksum nix 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a0d95c5fa8b641c10ad0b8887454ebaafa3c92b5cd5350f8fc693adafd178e7b" "checksum nodrop 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "52cd74cd09beba596430cc6e3091b74007169a56246e1262f0ba451ea95117b2" @@ -2729,6 +2819,7 @@ dependencies = [ "checksum order-stat 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "efa535d5117d3661134dbf1719b6f0ffe06f2375843b13935db186cd094105eb" "checksum owning_ref 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "8d91377085359426407a287ab16884a0111ba473aa6844ff01d4ec20ce3d75e7" "checksum parity-dapps-glue 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e1d06f6ee0fda786df3784a96ee3f0629f529b91cbfb7d142f6410e6bcd1ce2c" +"checksum parity-tokio-ipc 0.1.0 (git+https://github.com/nikvolf/parity-tokio-ipc)" = "" "checksum parity-ui-precompiled 1.4.0 (git+https://github.com/ethcore/js-precompiled.git)" = "" "checksum parking_lot 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "e1435e7a2a00dfebededd6c6bdbd54008001e94b4a2aadd6aef0dc4c56317621" "checksum parking_lot_core 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fb1b97670a2ffadce7c397fb80a3d687c4f3060140b885621ef1653d0e5d5068" @@ -2782,7 +2873,6 @@ dependencies = [ "checksum sha1 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "cc30b1e1e8c40c121ca33b86c23308a090d19974ef001b4bf6e61fd1a0fb095c" "checksum shell32-sys 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "72f20b8f3c060374edb8046591ba28f62448c369ccbdc7b02075103fb3a9e38d" "checksum siphasher 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5c44e42fa187b5a8782489cf7740cc27c3125806be2bf33563cf5e02e9533fcd" -"checksum slab 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d807fd58c4181bbabed77cb3b891ba9748241a552bcc5be698faaebefc54f46e" "checksum slab 0.2.0 (git+https://github.com/carllerche/slab?rev=5476efcafb)" = "" "checksum slab 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6dbdd334bd28d328dad1c41b0ea662517883d8880d8533895ef96c8003dec9c4" "checksum slab 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "17b4fcaed89ab08ef143da37bc52adbcc04d4a69014f4c1208d6b51f0c47bc23" @@ -2807,12 +2897,17 @@ dependencies = [ "checksum thread_local 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "0694f51610ef7cfac7a1b81de7f1602ee5356e76541bcd62c40e71933338cab1" "checksum time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)" = "3c7ec6d62a20df54e07ab3b78b9a3932972f4b7981de295563686849eb3989af" "checksum tiny-keccak 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "f7aef43048292ca0bae4ab32180e85f6202cf2816c2a210c396a84b99dab9270" -"checksum tokio-core 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "52416b3e937abac22a543a7f1c66bd37feb60137ff1ab42390fa02df85347e58" +"checksum tokio-core 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "3d1be481b55126f02ef88ff86748086473cb537a949fc4a8f4be403a530ae54b" +"checksum tokio-io 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6a278fde45f1be68e44995227d426aaa4841e0980bb0a21b981092f28c3c8473" +"checksum tokio-line 0.1.0 (git+https://github.com/tokio-rs/tokio-line)" = "" +"checksum tokio-named-pipes 0.1.0 (git+https://github.com/alexcrichton/tokio-named-pipes)" = "" "checksum tokio-proto 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7c0d6031f94d78d7b4d509d4a7c5e1cdf524a17e7b08d1c188a83cf720e69808" "checksum tokio-service 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "24da22d077e0f15f55162bdbdc661228c1581892f52074fb242678d015b45162" +"checksum tokio-uds 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "ffc7b5fc8e19e220b29566d1750949224a518478eab9cebc8df60583242ca30a" "checksum toml 0.1.28 (registry+https://github.com/rust-lang/crates.io-index)" = "fcd27a04ca509aff336ba5eb2abc58d456f52c4ff64d9724d88acb85ead560b6" "checksum toml 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a442dfc13508e603c3f763274361db7f79d7469a0e95c411cde53662ab30fc72" "checksum traitobject 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "07eaeb7689bb7fca7ce15628319635758eda769fed481ecfe6686ddef2600616" +"checksum traitobject 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "efd1f82c56340fdf16f2a953d7bda4f8fdffba13d93b00844c25572110b26079" "checksum transient-hashmap 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "715254c8f0811be1a79ad3ea5e6fa3c8eddec2b03d7f5ba78cf093e56d79c24f" "checksum typeable 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1410f6f91f21d1612654e7cc69193b0334f909dcf2c790c4826254fbb86f8887" "checksum unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "13a5906ca2b98c799f4b1ab4557b76367ebd6ae5ef14930ec841c74aed5f3764" @@ -2828,7 +2923,7 @@ dependencies = [ "checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" "checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" "checksum winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" -"checksum ws 0.5.3 (git+https://github.com/ethcore/ws-rs.git?branch=mio-upstream-stable)" = "" +"checksum ws 0.5.3 (git+https://github.com/paritytech/ws-rs.git?branch=mio-upstream-stable)" = "" "checksum ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" "checksum xdg 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "77b831a5ba77110f438f0ac5583aafeb087f70432998ba6b7dcb1d32185db453" "checksum xml-rs 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "65e74b96bd3179209dc70a980da6df843dff09e46eee103a0376c0949257e3ef" diff --git a/Cargo.toml b/Cargo.toml index f62f8b42f..f0978f420 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,9 +24,9 @@ serde = "0.9" serde_json = "0.9" app_dirs = "1.1.1" fdlimit = "0.1" -hyper = { default-features = false, git = "https://github.com/ethcore/hyper" } -ctrlc = { git = "https://github.com/ethcore/rust-ctrlc.git" } -jsonrpc-core = { git = "https://github.com/ethcore/jsonrpc.git", branch = "parity-1.6" } +hyper = { default-features = false, git = "https://github.com/paritytech/hyper" } +ctrlc = { git = "https://github.com/paritytech/rust-ctrlc.git" } +jsonrpc-core = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } ethsync = { path = "sync" } ethcore = { path = "ethcore" } ethcore-util = { path = "util" } diff --git a/dapps/Cargo.toml b/dapps/Cargo.toml index 8a00f503f..27a786cb3 100644 --- a/dapps/Cargo.toml +++ b/dapps/Cargo.toml @@ -8,33 +8,36 @@ authors = ["Parity Technologies "] [lib] [dependencies] -rand = "0.3" -log = "0.3" +base32 = "0.3" env_logger = "0.3" futures = "0.1" -jsonrpc-core = { git = "https://github.com/ethcore/jsonrpc.git", branch = "parity-1.6" } -jsonrpc-http-server = { git = "https://github.com/ethcore/jsonrpc.git", branch = "parity-1.6" } -hyper = { default-features = false, git = "https://github.com/ethcore/hyper" } -unicase = "1.3" -url = "1.0" -rustc-serialize = "0.3" -serde = "0.9" -serde_json = "0.9" -serde_derive = "0.9" linked-hash-map = "0.3" +log = "0.3" parity-dapps-glue = "1.7" -base32 = "0.3" mime = "0.2" mime_guess = "1.6.1" +rand = "0.3" +rustc-serialize = "0.3" +serde = "0.9" +serde_derive = "0.9" +serde_json = "0.9" time = "0.1.35" +unicase = "1.3" +url = "1.0" zip = { version = "0.1", default-features = false } + +jsonrpc-core = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } +jsonrpc-http-server = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } +# TODO [ToDr] Temporary solution, server should be merged with RPC. +jsonrpc-server-utils = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } + ethcore-devtools = { path = "../devtools" } ethcore-rpc = { path = "../rpc" } ethcore-util = { path = "../util" } fetch = { path = "../util/fetch" } -parity-ui = { path = "./ui" } parity-hash-fetch = { path = "../hash-fetch" } parity-reactor = { path = "../util/reactor" } +parity-ui = { path = "./ui" } clippy = { version = "0.0.103", optional = true} diff --git a/dapps/src/api/api.rs b/dapps/src/api/api.rs index 9106e0d70..e07bd4535 100644 --- a/dapps/src/api/api.rs +++ b/dapps/src/api/api.rs @@ -19,7 +19,6 @@ use unicase::UniCase; use hyper::{server, net, Decoder, Encoder, Next, Control}; use hyper::header; use hyper::method::Method; -use hyper::header::AccessControlAllowOrigin; use api::types::{App, ApiError}; use api::response; @@ -27,23 +26,20 @@ use apps::fetcher::Fetcher; use handlers::extract_url; use endpoint::{Endpoint, Endpoints, Handler, EndpointPath}; -use jsonrpc_http_server::cors; +use jsonrpc_http_server; +use jsonrpc_server_utils::cors; #[derive(Clone)] pub struct RestApi { - cors_domains: Option>, + cors_domains: Option>, endpoints: Arc, fetcher: Arc, } impl RestApi { - pub fn new(cors_domains: Vec, endpoints: Arc, fetcher: Arc) -> Box { + pub fn new(cors_domains: Vec, endpoints: Arc, fetcher: Arc) -> Box { Box::new(RestApi { - cors_domains: Some(cors_domains.into_iter().map(|domain| match domain.as_ref() { - "all" | "*" | "any" => AccessControlAllowOrigin::Any, - "null" => AccessControlAllowOrigin::Null, - other => AccessControlAllowOrigin::Value(other.into()), - }).collect()), + cors_domains: Some(cors_domains), endpoints: endpoints, fetcher: fetcher, }) @@ -64,7 +60,7 @@ impl Endpoint for RestApi { struct RestApiRouter { api: RestApi, - origin: Option, + cors_header: Option, path: Option, control: Option, handler: Box, @@ -74,7 +70,7 @@ impl RestApiRouter { fn new(api: RestApi, path: EndpointPath, control: Control) -> Self { RestApiRouter { path: Some(path), - origin: None, + cors_header: None, control: Some(control), api: api, handler: response::as_json_error(&ApiError { @@ -95,21 +91,22 @@ impl RestApiRouter { } /// Returns basic headers for a response (it may be overwritten by the handler) - fn response_headers(&self) -> header::Headers { + fn response_headers(cors_header: Option) -> header::Headers { let mut headers = header::Headers::new(); - headers.set(header::AccessControlAllowCredentials); - headers.set(header::AccessControlAllowMethods(vec![ - Method::Options, - Method::Post, - Method::Get, - ])); - headers.set(header::AccessControlAllowHeaders(vec![ - UniCase("origin".to_owned()), - UniCase("content-type".to_owned()), - UniCase("accept".to_owned()), - ])); - if let Some(cors_header) = cors::get_cors_header(&self.api.cors_domains, &self.origin) { + if let Some(cors_header) = cors_header { + headers.set(header::AccessControlAllowCredentials); + headers.set(header::AccessControlAllowMethods(vec![ + Method::Options, + Method::Post, + Method::Get, + ])); + headers.set(header::AccessControlAllowHeaders(vec![ + UniCase("origin".to_owned()), + UniCase("content-type".to_owned()), + UniCase("accept".to_owned()), + ])); + headers.set(cors_header); } @@ -120,7 +117,7 @@ impl RestApiRouter { impl server::Handler for RestApiRouter { fn on_request(&mut self, request: server::Request) -> Next { - self.origin = cors::read_origin(&request); + self.cors_header = jsonrpc_http_server::cors_header(&request, &self.api.cors_domains).into(); if let Method::Options = *request.method() { self.handler = response::empty(); @@ -164,7 +161,7 @@ impl server::Handler for RestApiRouter { } fn on_response(&mut self, res: &mut server::Response) -> Next { - *res.headers_mut() = self.response_headers(); + *res.headers_mut() = Self::response_headers(self.cors_header.take()); self.handler.on_response(res) } diff --git a/dapps/src/lib.rs b/dapps/src/lib.rs index 30c62a031..252e1c3bb 100644 --- a/dapps/src/lib.rs +++ b/dapps/src/lib.rs @@ -20,25 +20,27 @@ #![cfg_attr(feature="nightly", plugin(clippy))] extern crate base32; -extern crate hyper; -extern crate time; -extern crate url as url_lib; -extern crate unicase; +extern crate futures; +extern crate linked_hash_map; +extern crate mime_guess; +extern crate rand; +extern crate rustc_serialize; extern crate serde; extern crate serde_json; +extern crate time; +extern crate unicase; +extern crate url as url_lib; extern crate zip; -extern crate rand; + extern crate jsonrpc_core; extern crate jsonrpc_http_server; -extern crate mime_guess; -extern crate rustc_serialize; +extern crate jsonrpc_server_utils; + extern crate ethcore_rpc; extern crate ethcore_util as util; -extern crate parity_hash_fetch as hash_fetch; -extern crate linked_hash_map; extern crate fetch; extern crate parity_dapps_glue as parity_dapps; -extern crate futures; +extern crate parity_hash_fetch as hash_fetch; extern crate parity_reactor; #[macro_use] @@ -68,17 +70,20 @@ mod web; mod tests; use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::net::SocketAddr; use std::collections::HashMap; -use ethcore_rpc::{Metadata}; +use jsonrpc_core::{Middleware, MetaIoHandler}; +use jsonrpc_http_server::tokio_core::reactor::Remote as TokioRemote; +pub use jsonrpc_http_server::{DomainsValidation, Host, AccessControlAllowOrigin}; +pub use jsonrpc_http_server::hyper; + +use ethcore_rpc::Metadata; use fetch::{Fetch, Client as FetchClient}; use hash_fetch::urlhint::ContractClient; -use jsonrpc_core::Middleware; -use jsonrpc_core::reactor::RpcHandler; -use router::auth::{Authorization, NoAuth, HttpBasicAuth}; use parity_reactor::Remote; +use router::auth::{Authorization, NoAuth, HttpBasicAuth}; use self::apps::{HOME_PAGE, DAPPS_DOMAIN}; @@ -110,8 +115,8 @@ pub struct ServerBuilder { sync_status: Arc, web_proxy_tokens: Arc, signer_address: Option<(String, u16)>, - allowed_hosts: Option>, - extra_cors: Option>, + allowed_hosts: Option>, + extra_cors: Option>, remote: Remote, fetch: Option, } @@ -172,15 +177,15 @@ impl ServerBuilder { /// Change allowed hosts. /// `None` - All hosts are allowed /// `Some(whitelist)` - Allow only whitelisted hosts (+ listen address) - pub fn allowed_hosts(mut self, allowed_hosts: Option>) -> Self { - self.allowed_hosts = allowed_hosts; + pub fn allowed_hosts(mut self, allowed_hosts: DomainsValidation) -> Self { + self.allowed_hosts = allowed_hosts.into(); self } /// Extra cors headers. /// `None` - no additional CORS URLs - pub fn extra_cors_headers(mut self, cors: Option>) -> Self { - self.extra_cors = cors; + pub fn extra_cors_headers(mut self, cors: DomainsValidation) -> Self { + self.extra_cors = cors.into(); self } @@ -192,7 +197,7 @@ impl ServerBuilder { /// Asynchronously start server with no authentication, /// returns result with `Server` handle on success or an error. - pub fn start_unsecured_http>(self, addr: &SocketAddr, handler: RpcHandler) -> Result { + pub fn start_unsecured_http>(self, addr: &SocketAddr, handler: MetaIoHandler, tokio_remote: TokioRemote) -> Result { let fetch = self.fetch_client()?; Server::start_http( addr, @@ -207,13 +212,14 @@ impl ServerBuilder { self.sync_status, self.web_proxy_tokens, self.remote, + tokio_remote, fetch, ) } /// Asynchronously start server with `HTTP Basic Authentication`, /// return result with `Server` handle on success or an error. - pub fn start_basic_auth_http>(self, addr: &SocketAddr, username: &str, password: &str, handler: RpcHandler) -> Result { + pub fn start_basic_auth_http>(self, addr: &SocketAddr, username: &str, password: &str, handler: MetaIoHandler, tokio_remote: TokioRemote) -> Result { let fetch = self.fetch_client()?; Server::start_http( addr, @@ -228,6 +234,7 @@ impl ServerBuilder { self.sync_status, self.web_proxy_tokens, self.remote, + tokio_remote, fetch, ) } @@ -243,12 +250,11 @@ impl ServerBuilder { /// Webapps HTTP server. pub struct Server { server: Option, - panic_handler: Arc () + Send>>>>, } impl Server { /// Returns a list of allowed hosts or `None` if all hosts are allowed. - fn allowed_hosts(hosts: Option>, bind_address: String) -> Option> { + fn allowed_hosts(hosts: Option>, bind_address: String) -> Option> { let mut allowed = Vec::new(); match hosts { @@ -263,16 +269,19 @@ impl Server { } /// Returns a list of CORS domains for API endpoint. - fn cors_domains(signer_address: Option<(String, u16)>, extra_cors: Option>) -> Vec { + fn cors_domains( + signer_address: Option<(String, u16)>, + extra_cors: Option>, + ) -> Vec { let basic_cors = match signer_address { - Some(signer_address) => vec![ + Some(signer_address) => [ format!("http://{}{}", HOME_PAGE, DAPPS_DOMAIN), format!("http://{}{}:{}", HOME_PAGE, DAPPS_DOMAIN, signer_address.1), format!("http://{}", address(&signer_address)), format!("https://{}{}", HOME_PAGE, DAPPS_DOMAIN), format!("https://{}{}:{}", HOME_PAGE, DAPPS_DOMAIN, signer_address.1), format!("https://{}", address(&signer_address)), - ], + ].into_iter().map(|val| AccessControlAllowOrigin::Value(val.into())).collect(), None => vec![], }; @@ -284,10 +293,10 @@ impl Server { fn start_http>( addr: &SocketAddr, - hosts: Option>, - extra_cors: Option>, + hosts: Option>, + extra_cors: Option>, authorization: A, - handler: RpcHandler, + handler: MetaIoHandler, dapps_path: PathBuf, extra_dapps: Vec, signer_address: Option<(String, u16)>, @@ -295,9 +304,9 @@ impl Server { sync_status: Arc, web_proxy_tokens: Arc, remote: Remote, + tokio_remote: TokioRemote, fetch: F, ) -> Result { - let panic_handler = Arc::new(Mutex::new(None)); let authorization = Arc::new(authorization); let content_fetcher = Arc::new(apps::fetcher::ContentFetcher::new( hash_fetch::urlhint::URLHintContract::new(registrar), @@ -318,7 +327,7 @@ impl Server { let special = Arc::new({ let mut special = HashMap::new(); - special.insert(router::SpecialEndpoint::Rpc, rpc::rpc(handler, cors_domains.clone(), panic_handler.clone())); + special.insert(router::SpecialEndpoint::Rpc, rpc::rpc(handler, tokio_remote, cors_domains.clone())); special.insert(router::SpecialEndpoint::Utils, apps::utils()); special.insert( router::SpecialEndpoint::Api, @@ -346,17 +355,11 @@ impl Server { Server { server: Some(l), - panic_handler: panic_handler, } }) .map_err(ServerError::from) } - /// Set callback for panics. - pub fn set_panic_handler(&self, handler: F) where F : Fn() -> () + Send + 'static { - *self.panic_handler.lock().unwrap() = Some(Box::new(handler)); - } - #[cfg(test)] /// Returns address that this server is bound to. pub fn addr(&self) -> &SocketAddr { @@ -408,6 +411,7 @@ fn address(address: &(String, u16)) -> String { #[cfg(test)] mod util_tests { use super::Server; + use jsonrpc_http_server::AccessControlAllowOrigin; #[test] fn should_return_allowed_hosts() { @@ -432,18 +436,18 @@ mod util_tests { // when let none = Server::cors_domains(None, None); let some = Server::cors_domains(Some(("127.0.0.1".into(), 18180)), None); - let extra = Server::cors_domains(None, Some(vec!["all".to_owned()])); + let extra = Server::cors_domains(None, Some(vec!["all".into()])); // then - assert_eq!(none, Vec::::new()); + assert_eq!(none, Vec::::new()); assert_eq!(some, vec![ - "http://parity.web3.site".to_owned(), + "http://parity.web3.site".into(), "http://parity.web3.site:18180".into(), "http://127.0.0.1:18180".into(), "https://parity.web3.site".into(), "https://parity.web3.site:18180".into(), - "https://127.0.0.1:18180".into() + "https://127.0.0.1:18180".into(), ]); - assert_eq!(extra, vec!["all".to_owned()]); + assert_eq!(extra, vec![AccessControlAllowOrigin::Any]); } } diff --git a/dapps/src/router/host_validation.rs b/dapps/src/router/host_validation.rs index 9f40c177e..e5fcedd94 100644 --- a/dapps/src/router/host_validation.rs +++ b/dapps/src/router/host_validation.rs @@ -19,18 +19,13 @@ use apps::DAPPS_DOMAIN; use hyper::{server, header, StatusCode}; use hyper::net::HttpStream; -use jsonrpc_http_server::{is_host_header_valid}; use handlers::ContentHandler; +use jsonrpc_http_server; +use jsonrpc_server_utils::hosts; -pub fn is_valid(request: &server::Request, allowed_hosts: &[String], endpoints: Vec) -> bool { - let mut endpoints = endpoints.iter() - .map(|endpoint| format!("{}{}", endpoint, DAPPS_DOMAIN)) - .collect::>(); - endpoints.extend_from_slice(allowed_hosts); - - let header_valid = is_host_header_valid(request, &endpoints); - - match (header_valid, request.headers().get::()) { +pub fn is_valid(req: &server::Request, allowed_hosts: &Option>) -> bool { + let header_valid = jsonrpc_http_server::is_host_allowed(req, allowed_hosts); + match (header_valid, req.headers().get::()) { (true, _) => true, (_, Some(host)) => host.hostname.ends_with(DAPPS_DOMAIN), _ => false, diff --git a/dapps/src/router/mod.rs b/dapps/src/router/mod.rs index f34151552..0b4e632a6 100644 --- a/dapps/src/router/mod.rs +++ b/dapps/src/router/mod.rs @@ -24,14 +24,16 @@ use address; use std::cmp; use std::sync::Arc; use std::collections::HashMap; + use url::{Url, Host}; use hyper::{self, server, header, Next, Encoder, Decoder, Control, StatusCode}; use hyper::net::HttpStream; +use jsonrpc_server_utils::hosts; + use apps::{self, DAPPS_DOMAIN}; use apps::fetcher::Fetcher; use endpoint::{Endpoint, Endpoints, EndpointPath}; use handlers::{self, Redirection, ContentHandler}; -use self::auth::{Authorization, Authorized}; /// Special endpoints are accessible on every domain (every dapp) #[derive(Debug, PartialEq, Hash, Eq)] @@ -42,18 +44,18 @@ pub enum SpecialEndpoint { None, } -pub struct Router { +pub struct Router { control: Option, signer_address: Option<(String, u16)>, endpoints: Arc, fetch: Arc, special: Arc>>, authorization: Arc, - allowed_hosts: Option>, + allowed_hosts: Option>, handler: Box + Send>, } -impl server::Handler for Router { +impl server::Handler for Router { fn on_request(&mut self, req: server::Request) -> Next { // Choose proper handler depending on path / domain @@ -66,20 +68,18 @@ impl server::Handler for Router { trace!(target: "dapps", "Routing request to {:?}. Details: {:?}", url, req); // Validate Host header - if let Some(ref hosts) = self.allowed_hosts { - trace!(target: "dapps", "Validating host headers against: {:?}", hosts); - let is_valid = is_utils || host_validation::is_valid(&req, hosts, self.endpoints.keys().cloned().collect()); - if !is_valid { - debug!(target: "dapps", "Rejecting invalid host header."); - self.handler = host_validation::host_invalid_response(); - return self.handler.on_request(req); - } + trace!(target: "dapps", "Validating host headers against: {:?}", self.allowed_hosts); + let is_valid = is_utils || host_validation::is_valid(&req, &self.allowed_hosts); + if !is_valid { + debug!(target: "dapps", "Rejecting invalid host header."); + self.handler = host_validation::host_invalid_response(); + return self.handler.on_request(req); } trace!(target: "dapps", "Checking authorization."); // Check authorization let auth = self.authorization.is_authorized(&req); - if let Authorized::No(handler) = auth { + if let auth::Authorized::No(handler) = auth { debug!(target: "dapps", "Authorization denied."); self.handler = handler; return self.handler.on_request(req); @@ -181,7 +181,7 @@ impl server::Handler for Router { } } -impl Router { +impl Router { pub fn new( control: Control, signer_address: Option<(String, u16)>, @@ -189,7 +189,7 @@ impl Router { endpoints: Arc, special: Arc>>, authorization: Arc, - allowed_hosts: Option>, + allowed_hosts: Option>, ) -> Self { let handler = special.get(&SpecialEndpoint::Utils) diff --git a/dapps/src/rpc.rs b/dapps/src/rpc.rs index cc6f4d81a..6ddb31db0 100644 --- a/dapps/src/rpc.rs +++ b/dapps/src/rpc.rs @@ -14,55 +14,69 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use hyper; use ethcore_rpc::{Metadata, Origin}; -use jsonrpc_core::Middleware; -use jsonrpc_core::reactor::RpcHandler; -use jsonrpc_http_server::{Rpc, ServerHandler, PanicHandler, AccessControlAllowOrigin, HttpMetaExtractor}; +use jsonrpc_core::{Middleware, MetaIoHandler}; +use jsonrpc_http_server::{self as http, AccessControlAllowOrigin, HttpMetaExtractor}; +use jsonrpc_http_server::tokio_core::reactor::Remote; use endpoint::{Endpoint, EndpointPath, Handler}; pub fn rpc>( - handler: RpcHandler, - cors_domains: Vec, - panic_handler: Arc () + Send>>>>, + handler: MetaIoHandler, + remote: Remote, + cors_domains: Vec, ) -> Box { Box::new(RpcEndpoint { - handler: handler, + handler: Arc::new(handler), + remote: remote, meta_extractor: Arc::new(MetadataExtractor), - panic_handler: panic_handler, - cors_domain: Some(cors_domains.into_iter().map(AccessControlAllowOrigin::Value).collect()), + cors_domain: Some(cors_domains), // NOTE [ToDr] We don't need to do any hosts validation here. It's already done in router. allowed_hosts: None, }) } struct RpcEndpoint> { - handler: RpcHandler, + handler: Arc>, + remote: Remote, meta_extractor: Arc>, - panic_handler: Arc () + Send>>>>, cors_domain: Option>, - allowed_hosts: Option>, + allowed_hosts: Option>, } + impl> Endpoint for RpcEndpoint { fn to_async_handler(&self, _path: EndpointPath, control: hyper::Control) -> Box { - let panic_handler = PanicHandler { handler: self.panic_handler.clone() }; - Box::new(ServerHandler::new( - Rpc::new(self.handler.clone(), self.meta_extractor.clone()), + Box::new(http::ServerHandler::new( + http::Rpc { + handler: self.handler.clone(), + remote: self.remote.clone(), + extractor: self.meta_extractor.clone(), + }, self.cors_domain.clone(), self.allowed_hosts.clone(), - panic_handler, + Arc::new(NoopMiddleware), control, )) } } +#[derive(Default)] +struct NoopMiddleware; +impl http::RequestMiddleware for NoopMiddleware { + fn on_request(&self, request: &http::hyper::server::Request) -> http::RequestMiddlewareAction { + http::RequestMiddlewareAction::Proceed { + should_continue_on_invalid_cors: request.headers().get::().is_none(), + } + } +} + struct MetadataExtractor; impl HttpMetaExtractor for MetadataExtractor { - fn read_metadata(&self, request: &hyper::server::Request) -> Metadata { - let dapp_id = request.headers().get::() + fn read_metadata(&self, request: &http::hyper::server::Request) -> Metadata { + let dapp_id = request.headers().get::() .map(|origin| format!("{}://{}", origin.scheme, origin.host)) .or_else(|| { // fallback to custom header, but only if origin is null diff --git a/dapps/src/tests/api.rs b/dapps/src/tests/api.rs index 1b9f64b7f..73467e854 100644 --- a/dapps/src/tests/api.rs +++ b/dapps/src/tests/api.rs @@ -33,8 +33,8 @@ fn should_return_error() { ); // then - assert_eq!(response.status, "HTTP/1.1 404 Not Found".to_owned()); - assert_eq!(response.headers.get(3).unwrap(), "Content-Type: application/json"); + response.assert_status("HTTP/1.1 404 Not Found"); + response.assert_header("Content-Type", "application/json"); assert_eq!(response.body, format!("58\n{}\n0\n\n", r#"{"code":"404","title":"Not Found","detail":"Resource you requested has not been found."}"#)); assert_security_headers(&response.headers); } @@ -56,8 +56,8 @@ fn should_serve_apps() { ); // then - assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); - assert_eq!(response.headers.get(3).unwrap(), "Content-Type: application/json"); + response.assert_status("HTTP/1.1 200 OK"); + response.assert_header("Content-Type", "application/json"); assert!(response.body.contains("Parity UI"), response.body); assert_security_headers(&response.headers); } @@ -79,8 +79,8 @@ fn should_handle_ping() { ); // then - assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); - assert_eq!(response.headers.get(3).unwrap(), "Content-Type: application/json"); + response.assert_status("HTTP/1.1 200 OK"); + response.assert_header("Content-Type", "application/json"); assert_eq!(response.body, "0\n\n".to_owned()); assert_security_headers(&response.headers); } @@ -102,7 +102,7 @@ fn should_try_to_resolve_dapp() { ); // then - assert_eq!(response.status, "HTTP/1.1 404 Not Found".to_owned()); + response.assert_status("HTTP/1.1 404 Not Found"); assert_eq!(registrar.calls.lock().len(), 2); assert_security_headers(&response.headers); } @@ -125,12 +125,8 @@ fn should_return_signer_port_cors_headers() { ); // then - assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); - assert!( - response.headers_raw.contains("Access-Control-Allow-Origin: http://127.0.0.1:18180"), - "CORS header for signer missing: {:?}", - response.headers - ); + response.assert_status("HTTP/1.1 200 OK"); + response.assert_header("Access-Control-Allow-Origin", "http://127.0.0.1:18180"); } #[test] @@ -151,12 +147,8 @@ fn should_return_signer_port_cors_headers_for_home_parity() { ); // then - assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); - assert!( - response.headers_raw.contains("Access-Control-Allow-Origin: http://parity.web3.site"), - "CORS header for parity.web3.site missing: {:?}", - response.headers - ); + response.assert_status("HTTP/1.1 200 OK"); + response.assert_header("Access-Control-Allow-Origin", "http://parity.web3.site"); } @@ -178,12 +170,8 @@ fn should_return_signer_port_cors_headers_for_home_parity_with_https() { ); // then - assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); - assert!( - response.headers_raw.contains("Access-Control-Allow-Origin: https://parity.web3.site"), - "CORS header for parity.web3.site missing: {:?}", - response.headers - ); + response.assert_status("HTTP/1.1 200 OK"); + response.assert_header("Access-Control-Allow-Origin", "https://parity.web3.site"); } #[test] @@ -204,12 +192,8 @@ fn should_return_signer_port_cors_headers_for_home_parity_with_port() { ); // then - assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); - assert!( - response.headers_raw.contains("Access-Control-Allow-Origin: http://parity.web3.site:18180"), - "CORS header for parity.web3.site missing: {:?}", - response.headers - ); + response.assert_status("HTTP/1.1 200 OK"); + response.assert_header("Access-Control-Allow-Origin", "http://parity.web3.site:18180"); } #[test] diff --git a/dapps/src/tests/helpers/fetch.rs b/dapps/src/tests/helpers/fetch.rs index fcfd4db9c..e6e875c51 100644 --- a/dapps/src/tests/helpers/fetch.rs +++ b/dapps/src/tests/helpers/fetch.rs @@ -114,7 +114,7 @@ impl Fetch for FakeFetch { let data = response.lock().take().unwrap_or(b"Some content"); let cursor = io::Cursor::new(data); - tx.complete(fetch::Response::from_reader(cursor)); + tx.send(fetch::Response::from_reader(cursor)).unwrap(); }); rx.map_err(|_| fetch::Error::Aborted).boxed() diff --git a/dapps/src/tests/helpers/mod.rs b/dapps/src/tests/helpers/mod.rs index d1a1e9900..d1466c77c 100644 --- a/dapps/src/tests/helpers/mod.rs +++ b/dapps/src/tests/helpers/mod.rs @@ -21,13 +21,12 @@ use std::sync::Arc; use env_logger::LogBuilder; use ethcore_rpc::Metadata; use jsonrpc_core::MetaIoHandler; -use jsonrpc_core::reactor::RpcEventLoop; use ServerBuilder; use Server; use fetch::Fetch; use devtools::http_client; -use parity_reactor::Remote; +use parity_reactor::{EventLoop, Remote}; mod registrar; mod fetch; @@ -48,7 +47,7 @@ fn init_logger() { pub struct ServerLoop { pub server: Server, - pub event_loop: RpcEventLoop, + pub event_loop: EventLoop, } impl Deref for ServerLoop { @@ -70,13 +69,12 @@ pub fn init_server(process: F, io: MetaIoHandler, remote: Remote // TODO [ToDr] When https://github.com/ethcore/jsonrpc/issues/26 is resolved // this additional EventLoop wouldn't be needed, we should be able to re-use remote. - let event_loop = RpcEventLoop::spawn(); - let handler = event_loop.handler(Arc::new(io)); + let event_loop = EventLoop::spawn(); let server = process(ServerBuilder::new( &dapps_path, registrar.clone(), remote, )) .signer_address(Some(("127.0.0.1".into(), SIGNER_PORT))) - .start_unsecured_http(&"127.0.0.1:0".parse().unwrap(), handler).unwrap(); + .start_unsecured_http(&"127.0.0.1:0".parse().unwrap(), io, event_loop.raw_remote()).unwrap(); ( ServerLoop { server: server, event_loop: event_loop }, registrar, @@ -89,12 +87,12 @@ pub fn serve_with_auth(user: &str, pass: &str) -> ServerLoop { let mut dapps_path = env::temp_dir(); dapps_path.push("non-existent-dir-to-prevent-fs-files-from-loading"); - let event_loop = RpcEventLoop::spawn(); - let handler = event_loop.handler(Arc::new(MetaIoHandler::default())); - let server = ServerBuilder::new(&dapps_path, registrar, Remote::new(event_loop.remote())) + let event_loop = EventLoop::spawn(); + let io = MetaIoHandler::default(); + let server = ServerBuilder::new(&dapps_path, registrar, event_loop.remote()) .signer_address(Some(("127.0.0.1".into(), SIGNER_PORT))) - .allowed_hosts(None) - .start_basic_auth_http(&"127.0.0.1:0".parse().unwrap(), user, pass, handler).unwrap(); + .allowed_hosts(None.into()) + .start_basic_auth_http(&"127.0.0.1:0".parse().unwrap(), user, pass, io, event_loop.raw_remote()).unwrap(); ServerLoop { server: server, event_loop: event_loop, @@ -102,26 +100,28 @@ pub fn serve_with_auth(user: &str, pass: &str) -> ServerLoop { } pub fn serve_with_rpc(io: MetaIoHandler) -> ServerLoop { - init_server(|builder| builder.allowed_hosts(None), io, Remote::new_sync()).0 + init_server(|builder| builder.allowed_hosts(None.into()), io, Remote::new_sync()).0 } pub fn serve_hosts(hosts: Option>) -> ServerLoop { - init_server(|builder| builder.allowed_hosts(hosts), Default::default(), Remote::new_sync()).0 + let hosts = hosts.map(|hosts| hosts.into_iter().map(Into::into).collect()); + init_server(|builder| builder.allowed_hosts(hosts.into()), Default::default(), Remote::new_sync()).0 } pub fn serve_extra_cors(extra_cors: Option>) -> ServerLoop { - init_server(|builder| builder.allowed_hosts(None).extra_cors_headers(extra_cors), Default::default(), Remote::new_sync()).0 + let extra_cors = extra_cors.map(|cors| cors.into_iter().map(Into::into).collect()); + init_server(|builder| builder.allowed_hosts(None.into()).extra_cors_headers(extra_cors.into()), Default::default(), Remote::new_sync()).0 } pub fn serve_with_registrar() -> (ServerLoop, Arc) { - init_server(|builder| builder.allowed_hosts(None), Default::default(), Remote::new_sync()) + init_server(|builder| builder.allowed_hosts(None.into()), Default::default(), Remote::new_sync()) } pub fn serve_with_registrar_and_sync() -> (ServerLoop, Arc) { init_server(|builder| { builder .sync_status(Arc::new(|| true)) - .allowed_hosts(None) + .allowed_hosts(None.into()) }, Default::default(), Remote::new_sync()) } @@ -133,7 +133,7 @@ pub fn serve_with_registrar_and_fetch_and_threads(multi_threaded: bool) -> (Serv let fetch = FakeFetch::default(); let f = fetch.clone(); let (server, reg) = init_server(move |builder| { - builder.allowed_hosts(None).fetch(f.clone()) + builder.allowed_hosts(None.into()).fetch(f.clone()) }, Default::default(), if multi_threaded { Remote::new_thread_per_future() } else { Remote::new_sync() }); (server, fetch, reg) @@ -144,7 +144,7 @@ pub fn serve_with_fetch(web_token: &'static str) -> (ServerLoop, FakeFetch) { let f = fetch.clone(); let (server, _) = init_server(move |builder| { builder - .allowed_hosts(None) + .allowed_hosts(None.into()) .fetch(f.clone()) .web_proxy_tokens(Arc::new(move |token| &token == web_token)) }, Default::default(), Remote::new_sync()); @@ -153,7 +153,7 @@ pub fn serve_with_fetch(web_token: &'static str) -> (ServerLoop, FakeFetch) { } pub fn serve() -> ServerLoop { - init_server(|builder| builder.allowed_hosts(None), Default::default(), Remote::new_sync()).0 + init_server(|builder| builder.allowed_hosts(None.into()), Default::default(), Remote::new_sync()).0 } pub fn request(server: ServerLoop, request: &str) -> http_client::Response { diff --git a/dapps/src/tests/redirection.rs b/dapps/src/tests/redirection.rs index 8b529a851..4e3fff4dc 100644 --- a/dapps/src/tests/redirection.rs +++ b/dapps/src/tests/redirection.rs @@ -32,7 +32,7 @@ fn should_redirect_to_home() { ); // then - assert_eq!(response.status, "HTTP/1.1 302 Found".to_owned()); + response.assert_status("HTTP/1.1 302 Found"); assert_eq!(response.headers.get(0).unwrap(), "Location: http://127.0.0.1:18180"); } @@ -52,7 +52,7 @@ fn should_redirect_to_home_when_trailing_slash_is_missing() { ); // then - assert_eq!(response.status, "HTTP/1.1 302 Found".to_owned()); + response.assert_status("HTTP/1.1 302 Found"); assert_eq!(response.headers.get(0).unwrap(), "Location: http://127.0.0.1:18180"); } @@ -72,7 +72,7 @@ fn should_redirect_to_home_for_users_with_cached_redirection() { ); // then - assert_eq!(response.status, "HTTP/1.1 302 Found".to_owned()); + response.assert_status("HTTP/1.1 302 Found"); assert_eq!(response.headers.get(0).unwrap(), "Location: http://127.0.0.1:18180"); } @@ -92,7 +92,7 @@ fn should_display_404_on_invalid_dapp() { ); // then - assert_eq!(response.status, "HTTP/1.1 404 Not Found".to_owned()); + response.assert_status("HTTP/1.1 404 Not Found"); assert_security_headers_for_embed(&response.headers); } @@ -112,7 +112,7 @@ fn should_display_404_on_invalid_dapp_with_domain() { ); // then - assert_eq!(response.status, "HTTP/1.1 404 Not Found".to_owned()); + response.assert_status("HTTP/1.1 404 Not Found"); assert_security_headers_for_embed(&response.headers); } @@ -134,8 +134,8 @@ fn should_serve_rpc() { ); // then - assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); - assert_eq!(response.body, format!("58\n{}\n\n0\n\n", r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":null},"id":null}"#)); + response.assert_status("HTTP/1.1 200 OK"); + assert_eq!(response.body, format!("4C\n{}\n\n0\n\n", r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"},"id":null}"#)); } #[test] @@ -156,8 +156,8 @@ fn should_serve_rpc_at_slash_rpc() { ); // then - assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); - assert_eq!(response.body, format!("58\n{}\n\n0\n\n", r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":null},"id":null}"#)); + response.assert_status("HTTP/1.1 200 OK"); + assert_eq!(response.body, format!("4C\n{}\n\n0\n\n", r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"},"id":null}"#)); } @@ -178,7 +178,7 @@ fn should_serve_proxy_pac() { ); // then - assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); + response.assert_status("HTTP/1.1 200 OK"); assert_eq!(response.body, "DD\n\nfunction FindProxyForURL(url, host) {\n\tif (shExpMatch(host, \"parity.web3.site\"))\n\t{\n\t\treturn \"PROXY 127.0.0.1:18180\";\n\t}\n\n\tif (shExpMatch(host, \"*.web3.site\"))\n\t{\n\t\treturn \"PROXY 127.0.0.1:8080\";\n\t}\n\n\treturn \"DIRECT\";\n}\n\n0\n\n".to_owned()); assert_security_headers(&response.headers); } @@ -200,7 +200,7 @@ fn should_serve_utils() { ); // then - assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned()); + response.assert_status("HTTP/1.1 200 OK"); assert_eq!(response.body.contains("function(){"), true); assert_security_headers(&response.headers); } diff --git a/dapps/src/tests/rpc.rs b/dapps/src/tests/rpc.rs index 0dbba384c..2cc4ccb24 100644 --- a/dapps/src/tests/rpc.rs +++ b/dapps/src/tests/rpc.rs @@ -55,8 +55,8 @@ fn should_extract_metadata() { // given let mut io = MetaIoHandler::default(); io.add_method_with_meta("rpc_test", |_params, meta: Metadata| { - assert_eq!(meta.origin, Origin::Dapps("https://parity.io/".into())); - assert_eq!(meta.dapp_id(), "https://parity.io/".into()); + assert_eq!(meta.origin, Origin::Dapps("".into())); + assert_eq!(meta.dapp_id(), "".into()); future::ok(Value::String("Hello World!".into())).boxed() }); let server = serve_with_rpc(io); @@ -68,7 +68,6 @@ fn should_extract_metadata() { POST /rpc/ HTTP/1.1\r\n\ Host: 127.0.0.1:8080\r\n\ Connection: close\r\n\ - Origin: https://parity.io/\r\n\ X-Parity-Origin: https://this.should.be.ignored\r\n\ Content-Type: application/json\r\n\ Content-Length: {}\r\n\ diff --git a/ethcore/Cargo.toml b/ethcore/Cargo.toml index 17f79840e..d910f9a56 100644 --- a/ethcore/Cargo.toml +++ b/ethcore/Cargo.toml @@ -45,12 +45,9 @@ ethcore-bloom-journal = { path = "../util/bloom" } hardware-wallet = { path = "../hw" } ethcore-logger = { path = "../logger" } stats = { path = "../util/stats" } +hyper = { git = "https://github.com/paritytech/hyper", default-features = false } num = "0.1" -[dependencies.hyper] -git = "https://github.com/ethcore/hyper" -default-features = false - [features] jit = ["evmjit"] evm-debug = ["slow-blocks"] diff --git a/ethcore/light/src/on_demand/mod.rs b/ethcore/light/src/on_demand/mod.rs index 2ef01a0b1..488535568 100644 --- a/ethcore/light/src/on_demand/mod.rs +++ b/ethcore/light/src/on_demand/mod.rs @@ -18,6 +18,9 @@ //! The request service is implemented using Futures. Higher level request handlers //! will take the raw data received here and extract meaningful results from it. +// TODO [ToDr] Suppressing deprecation warnings. Rob will fix the API anyway. +#![allow(deprecated)] + use std::collections::HashMap; use std::sync::Arc; @@ -74,6 +77,8 @@ pub struct OnDemand { orphaned_requests: RwLock>, } +const RECEIVER_IN_SCOPE: &'static str = "Receiver is still in scope, so it's not dropped; qed"; + impl OnDemand { /// Create a new `OnDemand` service with the given cache. pub fn new(cache: Arc>) -> Self { @@ -95,7 +100,7 @@ impl OnDemand { }; match cached { - Some(hdr) => sender.complete(hdr), + Some(hdr) => sender.send(hdr).expect(RECEIVER_IN_SCOPE), None => self.dispatch_header_by_number(ctx, req, ChtProofSender::Header(sender)), } receiver @@ -111,7 +116,7 @@ impl OnDemand { }; match cached { - Some(score) => sender.complete(score), + Some(score) => sender.send(score).expect(RECEIVER_IN_SCOPE), None => self.dispatch_header_by_number(ctx, req, ChtProofSender::ChainScore(sender)), } @@ -132,7 +137,7 @@ impl OnDemand { }; match cached { - (Some(hdr), Some(score)) => sender.complete((hdr, score)), + (Some(hdr), Some(score)) => sender.send((hdr, score)).expect(RECEIVER_IN_SCOPE), _ => self.dispatch_header_by_number(ctx, req, ChtProofSender::Both(sender)), } @@ -183,7 +188,7 @@ impl OnDemand { pub fn header_by_hash(&self, ctx: &BasicContext, req: request::HeaderByHash) -> Receiver { let (sender, receiver) = oneshot::channel(); match self.cache.lock().block_header(&req.0) { - Some(hdr) => sender.complete(hdr), + Some(hdr) => sender.send(hdr).expect(RECEIVER_IN_SCOPE), None => self.dispatch_header_by_hash(ctx, req, sender), } receiver @@ -241,7 +246,7 @@ impl OnDemand { stream.begin_list(0); stream.begin_list(0); - sender.complete(encoded::Block::new(stream.out())) + sender.send(encoded::Block::new(stream.out())).expect(RECEIVER_IN_SCOPE) } else { match self.cache.lock().block_body(&req.hash) { Some(body) => { @@ -293,10 +298,10 @@ impl OnDemand { // fast path for empty receipts. if req.0.receipts_root() == SHA3_NULL_RLP { - sender.complete(Vec::new()) + sender.send(Vec::new()).expect(RECEIVER_IN_SCOPE) } else { match self.cache.lock().block_receipts(&req.0.hash()) { - Some(receipts) => sender.complete(receipts), + Some(receipts) => sender.send(receipts).expect(RECEIVER_IN_SCOPE), None => self.dispatch_block_receipts(ctx, req, sender), } } @@ -381,7 +386,7 @@ impl OnDemand { // fast path for no code. if req.code_hash == ::util::sha3::SHA3_EMPTY { - sender.complete(Vec::new()) + sender.send(Vec::new()).expect(RECEIVER_IN_SCOPE) } else { self.dispatch_code(ctx, req, sender); } diff --git a/ethcore/src/spec/spec.rs b/ethcore/src/spec/spec.rs index 1bc693a4f..76eefa3a6 100644 --- a/ethcore/src/spec/spec.rs +++ b/ethcore/src/spec/spec.rs @@ -326,7 +326,7 @@ impl Spec { pub fn load(reader: R) -> Result where R: Read { match ethjson::spec::Spec::load(reader) { Ok(spec) => Ok(spec.into()), - _ => Err("Spec json is invalid".into()), + Err(e) => Err(format!("Spec json is invalid: {}", e)), } } diff --git a/ipfs/Cargo.toml b/ipfs/Cargo.toml index 6ce5518c3..c6241a7aa 100644 --- a/ipfs/Cargo.toml +++ b/ipfs/Cargo.toml @@ -8,9 +8,8 @@ authors = ["Parity Technologies "] [dependencies] ethcore = { path = "../ethcore" } ethcore-util = { path = "../util" } -jsonrpc-http-server = { git = "https://github.com/ethcore/jsonrpc.git", branch = "parity-1.6" } +jsonrpc-http-server = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } rlp = { path = "../util/rlp" } mime = "0.2" -hyper = { default-features = false, git = "https://github.com/ethcore/hyper" } cid = "0.2.1" multihash = "0.5" diff --git a/ipfs/src/error.rs b/ipfs/src/error.rs index 1cbd54f1c..fadd75b9b 100644 --- a/ipfs/src/error.rs +++ b/ipfs/src/error.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use {multihash, cid, hyper}; +use {multihash, cid, http}; use route::Out; pub type Result = ::std::result::Result; @@ -25,7 +25,7 @@ pub enum ServerError { /// Wrapped `std::io::Error` IoError(::std::io::Error), /// Other `hyper` error - Other(hyper::error::Error), + Other(http::hyper::error::Error), /// Invalid --ipfs-api-interface InvalidInterface } @@ -80,8 +80,8 @@ impl From<::std::io::Error> for ServerError { } } -impl From for ServerError { - fn from(err: hyper::error::Error) -> ServerError { +impl From for ServerError { + fn from(err: http::hyper::error::Error) -> ServerError { ServerError::Other(err) } } diff --git a/ipfs/src/lib.rs b/ipfs/src/lib.rs index 80e910f9e..df03b6cd7 100644 --- a/ipfs/src/lib.rs +++ b/ipfs/src/lib.rs @@ -16,14 +16,13 @@ #[macro_use] extern crate mime; -extern crate hyper; extern crate multihash; extern crate cid; extern crate rlp; extern crate ethcore; extern crate ethcore_util as util; -extern crate jsonrpc_http_server; +extern crate jsonrpc_http_server as http; pub mod error; mod route; @@ -33,13 +32,13 @@ use std::sync::Arc; use std::net::{SocketAddr, IpAddr}; use error::ServerError; use route::Out; -use jsonrpc_http_server::cors; -use hyper::server::{Listening, Handler, Request, Response}; -use hyper::net::HttpStream; -use hyper::header::{Vary, ContentLength, ContentType, AccessControlAllowOrigin}; -use hyper::{Next, Encoder, Decoder, Method, RequestUri, StatusCode}; +use http::hyper::server::{Listening, Handler, Request, Response}; +use http::hyper::net::HttpStream; +use http::hyper::header::{self, Vary, ContentLength, ContentType}; +use http::hyper::{Next, Encoder, Decoder, Method, RequestUri, StatusCode}; use ethcore::client::BlockChainClient; +pub use http::{AccessControlAllowOrigin, Host, DomainsValidation}; /// Request/response handler pub struct IpfsHandler { @@ -47,12 +46,12 @@ pub struct IpfsHandler { out: Out, /// How many bytes from the response have been written out_progress: usize, - /// Origin request header - origin: Option, + /// CORS response header + cors_header: Option, /// Allowed CORS domains cors_domains: Option>, /// Hostnames allowed in the `Host` request header - allowed_hosts: Option>, + allowed_hosts: Option>, /// Reference to the Blockchain Client client: Arc, } @@ -62,50 +61,16 @@ impl IpfsHandler { &*self.client } - pub fn new(cors: Option>, hosts: Option>, client: Arc) -> Self { - fn origin_to_header(origin: String) -> AccessControlAllowOrigin { - match origin.as_str() { - "*" => AccessControlAllowOrigin::Any, - "null" | "" => AccessControlAllowOrigin::Null, - _ => AccessControlAllowOrigin::Value(origin), - } - } - + pub fn new(cors: DomainsValidation, hosts: DomainsValidation, client: Arc) -> Self { IpfsHandler { out: Out::Bad("Invalid Request"), out_progress: 0, - origin: None, - cors_domains: cors.map(|vec| vec.into_iter().map(origin_to_header).collect()), - allowed_hosts: hosts, + cors_header: None, + cors_domains: cors.into(), + allowed_hosts: hosts.into(), client: client, } } - - fn is_host_allowed(&self, req: &Request) -> bool { - match self.allowed_hosts { - Some(ref hosts) => jsonrpc_http_server::is_host_header_valid(&req, hosts), - None => true, - } - } - - fn is_origin_allowed(&self) -> bool { - // Check origin header first, no header passed is good news - let origin = match self.origin { - Some(ref origin) => origin, - None => return true, - }; - - let cors_domains = match self.cors_domains { - Some(ref domains) => domains, - None => return false, - }; - - cors_domains.iter().any(|domain| match *domain { - AccessControlAllowOrigin::Value(ref allowed) => origin == allowed, - AccessControlAllowOrigin::Any => true, - AccessControlAllowOrigin::Null => origin == "", - }) - } } /// Implement Hyper's HTTP handler @@ -115,19 +80,20 @@ impl Handler for IpfsHandler { return Next::write(); } - self.origin = cors::read_origin(&req); - if !self.is_host_allowed(&req) { + if !http::is_host_allowed(&req, &self.allowed_hosts) { self.out = Out::Bad("Disallowed Host header"); return Next::write(); } - if !self.is_origin_allowed() { + let cors_header = http::cors_header(&req, &self.cors_domains); + if cors_header == http::CorsHeader::Invalid { self.out = Out::Bad("Disallowed Origin header"); return Next::write(); } + self.cors_header = cors_header.into(); let (path, query) = match *req.uri() { RequestUri::AbsolutePath { ref path, ref query } => (path, query.as_ref().map(AsRef::as_ref)), @@ -176,7 +142,7 @@ impl Handler for IpfsHandler { } } - if let Some(cors_header) = cors::get_cors_header(&self.cors_domains, &self.origin) { + if let Some(cors_header) = self.cors_header.take() { res.headers_mut().set(cors_header); res.headers_mut().set(Vary::Items(vec!["Origin".into()])); } @@ -219,11 +185,11 @@ fn write_chunk(transport: &mut W, progress: &mut usize, data: &[u8]) - } /// Add current interface (default: "127.0.0.1:5001") to list of allowed hosts -fn include_current_interface(mut hosts: Vec, interface: String, port: u16) -> Vec { +fn include_current_interface(mut hosts: Vec, interface: String, port: u16) -> Vec { hosts.push(match port { 80 => interface, _ => format!("{}:{}", interface, port), - }); + }.into()); hosts } @@ -231,17 +197,18 @@ fn include_current_interface(mut hosts: Vec, interface: String, port: u1 pub fn start_server( port: u16, interface: String, - cors: Option>, - hosts: Option>, + cors: DomainsValidation, + hosts: DomainsValidation, client: Arc ) -> Result { let ip: IpAddr = interface.parse().map_err(|_| ServerError::InvalidInterface)?; let addr = SocketAddr::new(ip, port); - let hosts = hosts.map(move |hosts| include_current_interface(hosts, interface, port)); + let hosts: Option> = hosts.into(); + let hosts: DomainsValidation<_> = hosts.map(move |hosts| include_current_interface(hosts, interface, port)).into(); Ok( - hyper::Server::http(&addr)? + http::hyper::Server::http(&addr)? .handle(move |_| IpfsHandler::new(cors.clone(), hosts.clone(), client.clone())) .map(|(listening, srv)| { diff --git a/json/src/hash.rs b/json/src/hash.rs index ae6ba1a81..78fa77bd9 100644 --- a/json/src/hash.rs +++ b/json/src/hash.rs @@ -59,11 +59,11 @@ macro_rules! impl_hash { let value = match value.len() { 0 => $inner::from(0), 2 if value == "0x" => $inner::from(0), - _ if value.starts_with("0x") => $inner::from_str(&value[2..]).map_err(|_| { - Error::custom(format!("Invalid hex value {}.", value).as_str()) + _ if value.starts_with("0x") => $inner::from_str(&value[2..]).map_err(|e| { + Error::custom(format!("Invalid hex value {}: {}", value, e).as_str()) })?, - _ => $inner::from_str(value).map_err(|_| { - Error::custom(format!("Invalid hex value {}.", value).as_str()) + _ => $inner::from_str(value).map_err(|e| { + Error::custom(format!("Invalid hex value {}: {}", value, e).as_str()) })?, }; diff --git a/json/src/uint.rs b/json/src/uint.rs index 281820d78..6b206b380 100644 --- a/json/src/uint.rs +++ b/json/src/uint.rs @@ -63,7 +63,7 @@ impl Visitor for UintVisitor { type Value = Uint; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "a hex encoded uint") + write!(formatter, "a hex encoded or decimal uint") } fn visit_u64(self, value: u64) -> Result where E: Error { @@ -74,11 +74,11 @@ impl Visitor for UintVisitor { let value = match value.len() { 0 => U256::from(0), 2 if value.starts_with("0x") => U256::from(0), - _ if value.starts_with("0x") => U256::from_str(&value[2..]).map_err(|_| { - Error::custom(format!("Invalid hex value {}.", value).as_str()) + _ if value.starts_with("0x") => U256::from_str(&value[2..]).map_err(|e| { + Error::custom(format!("Invalid hex value {}: {}", value, e).as_str()) })?, - _ => U256::from_dec_str(value).map_err(|_| { - Error::custom(format!("Invalid decimal value {}.", value).as_str()) + _ => U256::from_dec_str(value).map_err(|e| { + Error::custom(format!("Invalid decimal value {}: {:?}", value, e).as_str()) })? }; diff --git a/parity/dapps.rs b/parity/dapps.rs index b9094c16d..bbd5f4960 100644 --- a/parity/dapps.rs +++ b/parity/dapps.rs @@ -23,9 +23,8 @@ use ethcore_rpc::informant::RpcStats; use ethsync::SyncProvider; use hash_fetch::fetch::Client as FetchClient; use helpers::replace_home; -use io::PanicHandler; -use jsonrpc_core::reactor::Remote; use rpc_apis::{self, SignerService}; +use parity_reactor; #[derive(Debug, PartialEq, Clone)] pub struct Configuration { @@ -60,11 +59,10 @@ impl Default for Configuration { } pub struct Dependencies { - pub panic_handler: Arc, pub apis: Arc, pub client: Arc, pub sync: Arc, - pub remote: Remote, + pub remote: parity_reactor::TokioRemote, pub fetch: FetchClient, pub signer: Arc, pub stats: Arc, @@ -137,9 +135,9 @@ mod server { use ansi_term::Colour; use ethcore::transaction::{Transaction, Action}; use ethcore::client::{Client, BlockChainClient, BlockId}; + use ethcore_dapps::{AccessControlAllowOrigin, Host}; use ethcore_rpc::is_major_importing; use hash_fetch::urlhint::ContractClient; - use jsonrpc_core::reactor::RpcHandler; use parity_reactor; use rpc_apis; @@ -162,6 +160,8 @@ mod server { Arc::new(Registrar { client: deps.client.clone() }), parity_reactor::Remote::new(deps.remote.clone()), ); + let allowed_hosts: Option> = allowed_hosts.map(|hosts| hosts.into_iter().map(Host::from).collect()); + let cors: Option> = cors.map(|cors| cors.into_iter().map(AccessControlAllowOrigin::from).collect()); let sync = deps.sync.clone(); let client = deps.client.clone(); @@ -172,8 +172,8 @@ mod server { .web_proxy_tokens(Arc::new(move |token| signer.is_valid_web_proxy_access_token(&token))) .extra_dapps(&extra_dapps) .signer_address(deps.signer.address()) - .allowed_hosts(allowed_hosts) - .extra_cors_headers(cors); + .allowed_hosts(allowed_hosts.into()) + .extra_cors_headers(cors.into()); let api_set = if all_apis { warn!("{}", Colour::Red.bold().paint("*** INSECURE *** Running Dapps with all APIs exposed.")); @@ -183,13 +183,12 @@ mod server { rpc_apis::ApiSet::UnsafeContext }; let apis = rpc_apis::setup_rpc(deps.stats, deps.apis.clone(), api_set); - let handler = RpcHandler::new(Arc::new(apis), deps.remote); let start_result = match auth { None => { - server.start_unsecured_http(url, handler) + server.start_unsecured_http(url, apis, deps.remote) }, Some((username, password)) => { - server.start_basic_auth_http(url, &username, &password, handler) + server.start_basic_auth_http(url, &username, &password, apis, deps.remote) }, }; @@ -199,13 +198,7 @@ mod server { _ => Err(format!("WebApps io error: {}", err)), }, Err(e) => Err(format!("WebApps error: {:?}", e)), - Ok(server) => { - let ph = deps.panic_handler; - server.set_panic_handler(move || { - ph.notify_all("Panic in WebApp thread.".to_owned()); - }); - Ok(server) - }, + Ok(server) => Ok(server), } } diff --git a/parity/ipfs.rs b/parity/ipfs.rs index e33dcf68b..760868f91 100644 --- a/parity/ipfs.rs +++ b/parity/ipfs.rs @@ -1,40 +1,59 @@ +// Copyright 2015-2017 Parity Technologies (UK) Ltd. +// This file is part of Parity. + +// Parity 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. + +// Parity 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 Parity. If not, see . + use std::sync::Arc; -use parity_ipfs_api; +use parity_ipfs_api::{self, AccessControlAllowOrigin, Host}; use parity_ipfs_api::error::ServerError; use ethcore::client::BlockChainClient; use hyper::server::Listening; #[derive(Debug, PartialEq, Clone)] pub struct Configuration { - pub enabled: bool, - pub port: u16, - pub interface: String, - pub cors: Option>, - pub hosts: Option>, + pub enabled: bool, + pub port: u16, + pub interface: String, + pub cors: Option>, + pub hosts: Option>, } impl Default for Configuration { - fn default() -> Self { - Configuration { - enabled: false, - port: 5001, - interface: "127.0.0.1".into(), - cors: None, - hosts: Some(Vec::new()), - } - } + fn default() -> Self { + Configuration { + enabled: false, + port: 5001, + interface: "127.0.0.1".into(), + cors: None, + hosts: Some(Vec::new()), + } + } } pub fn start_server(conf: Configuration, client: Arc) -> Result, ServerError> { - if !conf.enabled { - return Ok(None); - } + if !conf.enabled { + return Ok(None); + } - parity_ipfs_api::start_server( - conf.port, - conf.interface, - conf.cors, - conf.hosts, - client - ).map(Some) + let cors = conf.cors.map(|cors| cors.into_iter().map(AccessControlAllowOrigin::from).collect()); + let hosts = conf.hosts.map(|hosts| hosts.into_iter().map(Host::from).collect()); + + parity_ipfs_api::start_server( + conf.port, + conf.interface, + cors.into(), + hosts.into(), + client + ).map(Some) } diff --git a/parity/rpc.rs b/parity/rpc.rs index 49bd94699..a435f24db 100644 --- a/parity/rpc.rs +++ b/parity/rpc.rs @@ -18,19 +18,18 @@ use std::fmt; use std::sync::Arc; use std::net::SocketAddr; use std::io; -use io::PanicHandler; use dir::default_data_path; -use ethcore_rpc::{self as rpc, RpcServerError, IpcServerError, Metadata, Origin}; +use ethcore_rpc::{self as rpc, HttpServerError, Metadata, Origin, AccessControlAllowOrigin, Host}; use ethcore_rpc::informant::{RpcStats, Middleware}; use helpers::parity_ipc_path; use hyper; use jsonrpc_core::MetaIoHandler; -use jsonrpc_core::reactor::{RpcHandler, Remote}; use rpc_apis; use rpc_apis::ApiSet; +use parity_reactor::TokioRemote; -pub use ethcore_rpc::{IpcServer, Server as HttpServer}; +pub use ethcore_rpc::{IpcServer, HttpServer}; #[derive(Debug, PartialEq)] pub struct HttpConfiguration { @@ -84,9 +83,8 @@ impl fmt::Display for IpcConfiguration { } pub struct Dependencies { - pub panic_handler: Arc, pub apis: Arc, - pub remote: Remote, + pub remote: TokioRemote, pub stats: Arc, } @@ -102,6 +100,15 @@ impl rpc::HttpMetaExtractor for RpcExtractor { } } +impl rpc::IpcMetaExtractor for RpcExtractor { + fn extract(&self, _req: &rpc::IpcRequestContext) -> Metadata { + let mut metadata = Metadata::default(); + // TODO [ToDr] Extract proper session id when it's available in context. + metadata.origin = Origin::Ipc(1.into()); + metadata + } +} + pub fn new_http(conf: HttpConfiguration, deps: &Dependencies) -> Result, String> { if !conf.enabled { return Ok(None); @@ -123,12 +130,13 @@ pub fn setup_http_rpc_server( allowed_hosts: Option>, apis: ApiSet ) -> Result { - let apis = setup_apis(apis, dependencies); - let handler = RpcHandler::new(Arc::new(apis), dependencies.remote.clone()); - let ph = dependencies.panic_handler.clone(); - let start_result = rpc::start_http(url, cors_domains, allowed_hosts, ph, handler, RpcExtractor); + let handler = setup_apis(apis, dependencies); + let remote = dependencies.remote.clone(); + let cors_domains: Option> = cors_domains.map(|domains| domains.into_iter().map(AccessControlAllowOrigin::from).collect()); + let allowed_hosts: Option> = allowed_hosts.map(|hosts| hosts.into_iter().map(Host::from).collect()); + let start_result = rpc::start_http(url, cors_domains.into(), allowed_hosts.into(), handler, remote, RpcExtractor); match start_result { - Err(RpcServerError::IoError(err)) => match err.kind() { + Err(HttpServerError::IoError(err)) => match err.kind() { io::ErrorKind::AddrInUse => Err(format!("RPC address {} is already in use, make sure that another instance of an Ethereum client is not running or change the address using the --jsonrpc-port and --jsonrpc-interface options.", url)), _ => Err(format!("RPC io error: {}", err)), }, @@ -137,17 +145,16 @@ pub fn setup_http_rpc_server( } } -pub fn new_ipc(conf: IpcConfiguration, deps: &Dependencies) -> Result>, String> { +pub fn new_ipc(conf: IpcConfiguration, deps: &Dependencies) -> Result, String> { if !conf.enabled { return Ok(None); } Ok(Some(setup_ipc_rpc_server(deps, &conf.socket_addr, conf.apis)?)) } -pub fn setup_ipc_rpc_server(dependencies: &Dependencies, addr: &str, apis: ApiSet) -> Result, String> { - let apis = setup_apis(apis, dependencies); - let handler = RpcHandler::new(Arc::new(apis), dependencies.remote.clone()); - match rpc::start_ipc(addr, handler) { - Err(IpcServerError::Io(io_error)) => Err(format!("RPC io error: {}", io_error)), - Err(any_error) => Err(format!("Rpc error: {:?}", any_error)), +pub fn setup_ipc_rpc_server(dependencies: &Dependencies, addr: &str, apis: ApiSet) -> Result { + let handler = setup_apis(apis, dependencies); + let remote = dependencies.remote.clone(); + match rpc::start_ipc(addr, handler, remote, RpcExtractor) { + Err(io_error) => Err(format!("RPC io error: {}", io_error)), Ok(server) => Ok(server) } } diff --git a/parity/run.rs b/parity/run.rs index f781a8774..86702edfc 100644 --- a/parity/run.rs +++ b/parity/run.rs @@ -435,7 +435,6 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc) -> R }); let dependencies = rpc::Dependencies { - panic_handler: panic_handler.clone(), apis: deps_for_rpc_apis.clone(), remote: event_loop.raw_remote(), stats: rpc_stats.clone(), @@ -447,7 +446,6 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc) -> R // the dapps server let dapps_deps = dapps::Dependencies { - panic_handler: panic_handler.clone(), apis: deps_for_rpc_apis.clone(), client: client.clone(), sync: sync_provider.clone(), @@ -460,7 +458,6 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc) -> R // the signer server let signer_deps = signer::Dependencies { - panic_handler: panic_handler.clone(), apis: deps_for_rpc_apis.clone(), remote: event_loop.raw_remote(), rpc_stats: rpc_stats.clone(), diff --git a/parity/signer.rs b/parity/signer.rs index d69670204..664a0e6e4 100644 --- a/parity/signer.rs +++ b/parity/signer.rs @@ -26,8 +26,7 @@ use ethcore_rpc::informant::RpcStats; use ethcore_rpc; use ethcore_signer as signer; use helpers::replace_home; -use io::{ForwardPanic, PanicHandler}; -use jsonrpc_core::reactor::{RpcHandler, Remote}; +use parity_reactor::TokioRemote; use rpc_apis; use path::restrict_permissions_owner; use util::H256; @@ -57,9 +56,8 @@ impl Default for Configuration { } pub struct Dependencies { - pub panic_handler: Arc, pub apis: Arc, - pub remote: Remote, + pub remote: TokioRemote, pub rpc_stats: Arc, } @@ -143,9 +141,9 @@ fn do_start(conf: Configuration, deps: Dependencies) -> Result Result Err(format!("Trusted Signer io error: {}", err)), }, Err(e) => Err(format!("Trusted Signer Error: {:?}", e)), - Ok(server) => { - deps.panic_handler.forward_from(&server); - Ok(server) - }, + Ok(server) => Ok(server), } } diff --git a/rpc/Cargo.toml b/rpc/Cargo.toml index d18393902..08f813f68 100644 --- a/rpc/Cargo.toml +++ b/rpc/Cargo.toml @@ -10,18 +10,20 @@ authors = ["Parity Technologies "] [dependencies] futures = "0.1" log = "0.3" +order-stat = "0.1" +rustc-serialize = "0.3" semver = "0.5" serde = "0.9" -serde_json = "0.9" serde_derive = "0.9" -rustc-serialize = "0.3" +serde_json = "0.9" time = "0.1" transient-hashmap = "0.4" -order-stat = "0.1" -jsonrpc-core = { git = "https://github.com/ethcore/jsonrpc.git", branch = "parity-1.6" } -jsonrpc-http-server = { git = "https://github.com/ethcore/jsonrpc.git", branch = "parity-1.6" } -jsonrpc-ipc-server = { git = "https://github.com/ethcore/jsonrpc.git", branch = "parity-1.6" } -jsonrpc-macros = { git = "https://github.com/ethcore/jsonrpc.git", branch = "parity-1.6" } + +jsonrpc-core = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } +jsonrpc-http-server = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } +jsonrpc-ipc-server = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } +jsonrpc-macros = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } + ethcore-io = { path = "../util/io" } ethcore-ipc = { path = "../ipc/rpc" } ethcore-util = { path = "../util" } @@ -36,11 +38,12 @@ ethcore-devtools = { path = "../devtools" } ethcore-light = { path = "../ethcore/light" } ethcore-logger = { path = "../logger" } parity-updater = { path = "../updater" } +parity-reactor = { path = "../util/reactor" } rlp = { path = "../util/rlp" } fetch = { path = "../util/fetch" } -parity-reactor = { path = "../util/reactor" } -clippy = { version = "0.0.103", optional = true} stats = { path = "../util/stats" } +clippy = { version = "0.0.103", optional = true} + [features] dev = ["clippy", "ethcore/dev", "ethcore-util/dev", "ethsync/dev"] diff --git a/rpc/src/lib.rs b/rpc/src/lib.rs index a00b138ac..abc51f2ed 100644 --- a/rpc/src/lib.rs +++ b/rpc/src/lib.rs @@ -19,32 +19,33 @@ #![cfg_attr(feature="nightly", feature(plugin))] #![cfg_attr(feature="nightly", plugin(clippy))] -extern crate semver; -extern crate rustc_serialize; -extern crate serde; -extern crate serde_json; -extern crate jsonrpc_core; -extern crate jsonrpc_http_server; - -extern crate ethcore_io as io; -extern crate ethcore; -extern crate ethkey; -extern crate ethcrypto as crypto; -extern crate ethstore; -extern crate ethsync; -extern crate ethash; -extern crate ethcore_light as light; -extern crate ethcore_logger; -extern crate transient_hashmap; -extern crate jsonrpc_ipc_server as ipc; -extern crate ethcore_ipc; -extern crate time; -extern crate rlp; -extern crate fetch; extern crate futures; extern crate order_stat; -extern crate parity_updater as updater; +extern crate rustc_serialize; +extern crate semver; +extern crate serde; +extern crate serde_json; +extern crate time; +extern crate transient_hashmap; + +extern crate jsonrpc_core; +pub extern crate jsonrpc_http_server as http; +pub extern crate jsonrpc_ipc_server as ipc; + +extern crate ethash; +extern crate ethcore; +extern crate ethcore_io as io; +extern crate ethcore_ipc; +extern crate ethcore_light as light; +extern crate ethcrypto as crypto; +extern crate ethkey; +extern crate ethstore; +extern crate ethsync; +extern crate ethcore_logger; +extern crate fetch; extern crate parity_reactor; +extern crate parity_updater as updater; +extern crate rlp; extern crate stats; #[macro_use] @@ -61,57 +62,53 @@ extern crate ethjson; #[cfg(test)] extern crate ethcore_devtools as devtools; -use std::sync::Arc; -use std::net::SocketAddr; -use io::PanicHandler; -use jsonrpc_core::reactor::RpcHandler; - -pub use ipc::{Server as IpcServer, Error as IpcServerError}; -pub use jsonrpc_http_server::{ServerBuilder, Server, RpcServerError, HttpMetaExtractor}; pub mod v1; + +pub use ipc::{Server as IpcServer, MetaExtractor as IpcMetaExtractor, RequestContext as IpcRequestContext}; +pub use http::{HttpMetaExtractor, Server as HttpServer, Error as HttpServerError, AccessControlAllowOrigin, Host}; + pub use v1::{SigningQueue, SignerService, ConfirmationsQueue, NetworkSettings, Metadata, Origin, informant, dispatch}; pub use v1::block_import::is_major_importing; +use std::net::SocketAddr; +use http::tokio_core; + /// Start http server asynchronously and returns result with `Server` handle on success or an error. -pub fn start_http( +pub fn start_http( addr: &SocketAddr, - cors_domains: Option>, - allowed_hosts: Option>, - panic_handler: Arc, - handler: RpcHandler, + cors_domains: http::DomainsValidation, + allowed_hosts: http::DomainsValidation, + handler: H, + remote: tokio_core::reactor::Remote, extractor: T, -) -> Result where +) -> Result where M: jsonrpc_core::Metadata, S: jsonrpc_core::Middleware, + H: Into>, T: HttpMetaExtractor, { - - let cors_domains = cors_domains.map(|domains| { - domains.into_iter() - .map(|v| match v.as_str() { - "*" => jsonrpc_http_server::AccessControlAllowOrigin::Any, - "null" => jsonrpc_http_server::AccessControlAllowOrigin::Null, - v => jsonrpc_http_server::AccessControlAllowOrigin::Value(v.into()), - }) - .collect() - }); - - ServerBuilder::with_rpc_handler(handler) - .meta_extractor(Arc::new(extractor)) + http::ServerBuilder::new(handler) + .event_loop_remote(remote) + .meta_extractor(extractor) .cors(cors_domains.into()) .allowed_hosts(allowed_hosts.into()) - .panic_handler(move || { - panic_handler.notify_all("Panic in RPC thread.".to_owned()); - }) .start_http(addr) } /// Start ipc server asynchronously and returns result with `Server` handle on success or an error. -pub fn start_ipc>( +pub fn start_ipc( addr: &str, - handler: RpcHandler, -) -> Result, ipc::Error> { - let server = ipc::Server::with_rpc_handler(addr, handler)?; - server.run_async()?; - Ok(server) + handler: H, + remote: tokio_core::reactor::Remote, + extractor: T, +) -> ::std::io::Result where + M: jsonrpc_core::Metadata, + S: jsonrpc_core::Middleware, + H: Into>, + T: IpcMetaExtractor, +{ + ipc::ServerBuilder::new(handler) + .event_loop_remote(remote) + .session_metadata_extractor(extractor) + .start(addr) } diff --git a/rpc/src/v1/helpers/mod.rs b/rpc/src/v1/helpers/mod.rs index 76d34abdf..bc99b65ff 100644 --- a/rpc/src/v1/helpers/mod.rs +++ b/rpc/src/v1/helpers/mod.rs @@ -21,6 +21,7 @@ pub mod block_import; pub mod dispatch; pub mod fake_sign; pub mod informant; +pub mod oneshot; mod network_settings; mod poll_manager; diff --git a/rpc/src/v1/helpers/oneshot.rs b/rpc/src/v1/helpers/oneshot.rs new file mode 100644 index 000000000..c128ccf55 --- /dev/null +++ b/rpc/src/v1/helpers/oneshot.rs @@ -0,0 +1,67 @@ +// Copyright 2015-2017 Parity Technologies (UK) Ltd. +// This file is part of Parity. + +// Parity 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. + +// Parity 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 Parity. If not, see . + +use jsonrpc_core::Error; +use futures::{self, Future}; +use futures::sync::oneshot; +use v1::helpers::errors; + +pub type Res = Result; + +pub struct Sender { + sender: oneshot::Sender>, +} + +impl Sender { + pub fn send(self, data: Res) { + let res = self.sender.send(data); + if let Err(_) = res { + debug!(target: "rpc", "Responding to a no longer active request."); + } + } +} + +pub struct Receiver { + receiver: oneshot::Receiver>, +} + +impl Future for Receiver { + type Item = T; + type Error = Error; + + fn poll(&mut self) -> futures::Poll { + let res = self.receiver.poll(); + match res { + Ok(futures::Async::NotReady) => Ok(futures::Async::NotReady), + Ok(futures::Async::Ready(Ok(res))) => Ok(futures::Async::Ready(res)), + Ok(futures::Async::Ready(Err(err))) => Err(err), + Err(e) => { + debug!(target: "rpc", "Responding to a canceled request: {:?}", e); + Err(errors::internal("Request was canceled by client.", e)) + }, + } + } +} + +pub fn oneshot() -> (Sender, Receiver) { + let (tx, rx) = futures::oneshot(); + + (Sender { + sender: tx, + }, Receiver { + receiver: rx, + }) +} diff --git a/rpc/src/v1/impls/signing.rs b/rpc/src/v1/impls/signing.rs index dcda6fa9e..598b98763 100644 --- a/rpc/src/v1/impls/signing.rs +++ b/rpc/src/v1/impls/signing.rs @@ -22,10 +22,10 @@ use util::{U256, Mutex}; use ethcore::account_provider::AccountProvider; -use futures::{self, future, BoxFuture, Future}; +use futures::{future, BoxFuture, Future}; use jsonrpc_core::Error; use v1::helpers::{ - errors, + errors, oneshot, DefaultAccount, SIGNING_QUEUE_LIMIT, SigningQueue, ConfirmationPromise, ConfirmationResult, SignerService }; @@ -188,21 +188,20 @@ impl ParitySigning for SigningQueueClient { meta.origin, ); - let (ready, p) = futures::oneshot(); + let (ready, p) = oneshot::oneshot(); // when dispatch is complete res.then(move |res| { // register callback via the oneshot sender. handle_dispatch(res, move |response| { match response { - Ok(RpcConfirmationResponse::Decrypt(data)) => ready.complete(Ok(data)), - Err(e) => ready.complete(Err(e)), - e => ready.complete(Err(errors::internal("Unexpected result.", e))), + Ok(RpcConfirmationResponse::Decrypt(data)) => ready.send(Ok(data)), + Err(e) => ready.send(Err(e)), + e => ready.send(Err(errors::internal("Unexpected result.", e))), } }); - // and wait for that to resolve. - p.then(|result| futures::done(result.expect("Ready is never dropped nor canceled."))) + p }).boxed() } } @@ -217,18 +216,18 @@ impl EthSigning for SigningQueueClient { meta.origin, ); - let (ready, p) = futures::oneshot(); + let (ready, p) = oneshot::oneshot(); res.then(move |res| { handle_dispatch(res, move |response| { match response { - Ok(RpcConfirmationResponse::Signature(sig)) => ready.complete(Ok(sig)), - Err(e) => ready.complete(Err(e)), - e => ready.complete(Err(errors::internal("Unexpected result.", e))), + Ok(RpcConfirmationResponse::Signature(sig)) => ready.send(Ok(sig)), + Err(e) => ready.send(Err(e)), + e => ready.send(Err(errors::internal("Unexpected result.", e))), } }); - p.then(|result| futures::done(result.expect("Ready is never dropped nor canceled."))) + p }).boxed() } @@ -239,18 +238,18 @@ impl EthSigning for SigningQueueClient { meta.origin, ); - let (ready, p) = futures::oneshot(); + let (ready, p) = oneshot::oneshot(); res.then(move |res| { handle_dispatch(res, move |response| { match response { - Ok(RpcConfirmationResponse::SendTransaction(hash)) => ready.complete(Ok(hash)), - Err(e) => ready.complete(Err(e)), - e => ready.complete(Err(errors::internal("Unexpected result.", e))), + Ok(RpcConfirmationResponse::SendTransaction(hash)) => ready.send(Ok(hash)), + Err(e) => ready.send(Err(e)), + e => ready.send(Err(errors::internal("Unexpected result.", e))), } }); - p.then(|result| futures::done(result.expect("Ready is never dropped nor canceled."))) + p }).boxed() } @@ -261,18 +260,18 @@ impl EthSigning for SigningQueueClient { meta.origin, ); - let (ready, p) = futures::oneshot(); + let (ready, p) = oneshot::oneshot(); res.then(move |res| { handle_dispatch(res, move |response| { match response { - Ok(RpcConfirmationResponse::SignTransaction(tx)) => ready.complete(Ok(tx)), - Err(e) => ready.complete(Err(e)), - e => ready.complete(Err(errors::internal("Unexpected result.", e))), + Ok(RpcConfirmationResponse::SignTransaction(tx)) => ready.send(Ok(tx)), + Err(e) => ready.send(Err(e)), + e => ready.send(Err(errors::internal("Unexpected result.", e))), } }); - p.then(|result| futures::done(result.expect("Ready is never dropped nor canceled."))) + p }).boxed() } } diff --git a/rpc/src/v1/tests/helpers/fetch.rs b/rpc/src/v1/tests/helpers/fetch.rs index 58ac96bcb..236dae91b 100644 --- a/rpc/src/v1/tests/helpers/fetch.rs +++ b/rpc/src/v1/tests/helpers/fetch.rs @@ -35,7 +35,7 @@ impl Fetch for TestFetch { let (tx, rx) = futures::oneshot(); thread::spawn(move || { let cursor = io::Cursor::new(b"Some content"); - tx.complete(fetch::Response::from_reader(cursor)); + tx.send(fetch::Response::from_reader(cursor)).unwrap(); }); rx.map_err(|_| fetch::Error::Aborted).boxed() diff --git a/rpc/src/v1/tests/mocked/eth.rs b/rpc/src/v1/tests/mocked/eth.rs index 146444c21..ee27c27ba 100644 --- a/rpc/src/v1/tests/mocked/eth.rs +++ b/rpc/src/v1/tests/mocked/eth.rs @@ -901,7 +901,7 @@ fn rpc_eth_send_transaction_with_bad_to() { "id": 1 }"#; - let response = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid length.","data":null},"id":1}"#; + let response = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params: expected a hex-encoded hash with 0x prefix."},"id":1}"#; assert_eq!(tester.io.handle_request_sync(&request), Some(response.into())); } @@ -1084,7 +1084,7 @@ fn rpc_get_work_returns_no_work_if_cant_mine() { eth_tester.client.set_queue_size(10); let request = r#"{"jsonrpc": "2.0", "method": "eth_getWork", "params": [], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","error":{"code":-32001,"message":"Still syncing.","data":null},"id":1}"#; + let response = r#"{"jsonrpc":"2.0","error":{"code":-32001,"message":"Still syncing."},"id":1}"#; assert_eq!(eth_tester.io.handle_request_sync(request), Some(response.to_owned())); } @@ -1142,6 +1142,6 @@ fn rpc_get_work_should_timeout() { // Request with timeout of 10 seconds. This should fail. let request = r#"{"jsonrpc": "2.0", "method": "eth_getWork", "params": ["10"], "id": 1}"#; - let err_response = r#"{"jsonrpc":"2.0","error":{"code":-32003,"message":"Work has not changed.","data":null},"id":1}"#; + let err_response = r#"{"jsonrpc":"2.0","error":{"code":-32003,"message":"Work has not changed."},"id":1}"#; assert_eq!(eth_tester.io.handle_request_sync(request), Some(err_response.to_owned())); } diff --git a/rpc/src/v1/tests/mocked/parity.rs b/rpc/src/v1/tests/mocked/parity.rs index 8acedc2d4..3af627037 100644 --- a/rpc/src/v1/tests/mocked/parity.rs +++ b/rpc/src/v1/tests/mocked/parity.rs @@ -357,7 +357,7 @@ fn rpc_parity_unsigned_transactions_count_when_signer_disabled() { let io = deps.default_client(); let request = r#"{"jsonrpc": "2.0", "method": "parity_unsignedTransactionsCount", "params":[], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"Trusted Signer is disabled. This API is not available.","data":null},"id":1}"#; + let response = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"Trusted Signer is disabled. This API is not available."},"id":1}"#; assert_eq!(io.handle_request_sync(request), Some(response.to_owned())); } @@ -393,7 +393,7 @@ fn rpc_parity_signer_port() { // when let request = r#"{"jsonrpc": "2.0", "method": "parity_signerPort", "params": [], "id": 1}"#; let response1 = r#"{"jsonrpc":"2.0","result":18180,"id":1}"#; - let response2 = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"Trusted Signer is disabled. This API is not available.","data":null},"id":1}"#; + let response2 = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"Trusted Signer is disabled. This API is not available."},"id":1}"#; // then assert_eq!(io1.handle_request_sync(request), Some(response1.to_owned())); @@ -411,7 +411,7 @@ fn rpc_parity_dapps_port() { // when let request = r#"{"jsonrpc": "2.0", "method": "parity_dappsPort", "params": [], "id": 1}"#; let response1 = r#"{"jsonrpc":"2.0","result":18080,"id":1}"#; - let response2 = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"Dapps Server is disabled. This API is not available.","data":null},"id":1}"#; + let response2 = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"Dapps Server is disabled. This API is not available."},"id":1}"#; // then assert_eq!(io1.handle_request_sync(request), Some(response1.to_owned())); @@ -429,7 +429,7 @@ fn rpc_parity_dapps_interface() { // when let request = r#"{"jsonrpc": "2.0", "method": "parity_dappsInterface", "params": [], "id": 1}"#; let response1 = r#"{"jsonrpc":"2.0","result":"127.0.0.1","id":1}"#; - let response2 = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"Dapps Server is disabled. This API is not available.","data":null},"id":1}"#; + let response2 = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"Dapps Server is disabled. This API is not available."},"id":1}"#; // then assert_eq!(io1.handle_request_sync(request), Some(response1.to_owned())); diff --git a/rpc/src/v1/tests/mocked/parity_accounts.rs b/rpc/src/v1/tests/mocked/parity_accounts.rs index 304ffd45e..ae4f74b49 100644 --- a/rpc/src/v1/tests/mocked/parity_accounts.rs +++ b/rpc/src/v1/tests/mocked/parity_accounts.rs @@ -230,7 +230,7 @@ fn should_be_able_to_kill_account() { let address = accounts[0]; let request = format!(r#"{{"jsonrpc": "2.0", "method": "parity_killAccount", "params": ["0xf00baba2f00baba2f00baba2f00baba2f00baba2"], "id": 1}}"#); - let response = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"invalid length 1, expected a tuple of size 2","data":null},"id":1}"#; + let response = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params: invalid length 1, expected a tuple of size 2."},"id":1}"#; let res = tester.io.handle_request_sync(&request); assert_eq!(res, Some(response.into())); diff --git a/rpc/src/v1/tests/mocked/traces.rs b/rpc/src/v1/tests/mocked/traces.rs index 83a266d2f..369cf726a 100644 --- a/rpc/src/v1/tests/mocked/traces.rs +++ b/rpc/src/v1/tests/mocked/traces.rs @@ -174,7 +174,7 @@ fn rpc_trace_call_state_pruned() { *tester.client.execution_result.write() = Some(Err(CallError::StatePruned)); let request = r#"{"jsonrpc":"2.0","method":"trace_call","params":[{}, ["stateDiff", "vmTrace", "trace"]],"id":1}"#; - let response = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"This request is not supported because your node is running with state pruning. Run with --pruning=archive.","data":null},"id":1}"#; + let response = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"This request is not supported because your node is running with state pruning. Run with --pruning=archive."},"id":1}"#; assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); } @@ -195,7 +195,7 @@ fn rpc_trace_raw_transaction_state_pruned() { *tester.client.execution_result.write() = Some(Err(CallError::StatePruned)); let request = r#"{"jsonrpc":"2.0","method":"trace_rawTransaction","params":["0xf869018609184e72a0008276c094d46e8dd67c5d32be8058bb8eb970870f07244567849184e72a801ba0617f39c1a107b63302449c476d96a6cb17a5842fc98ff0c5bcf4d5c4d8166b95a009fdb6097c6196b9bbafc3a59f02f38d91baeef23d0c60a8e4f23c7714cea3a9", ["stateDiff", "vmTrace", "trace"]],"id":1}"#; - let response = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"This request is not supported because your node is running with state pruning. Run with --pruning=archive.","data":null},"id":1}"#; + let response = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"This request is not supported because your node is running with state pruning. Run with --pruning=archive."},"id":1}"#; assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); } @@ -216,7 +216,7 @@ fn rpc_trace_replay_transaction_state_pruned() { *tester.client.execution_result.write() = Some(Err(CallError::StatePruned)); let request = r#"{"jsonrpc":"2.0","method":"trace_replayTransaction","params":["0x0000000000000000000000000000000000000000000000000000000000000005", ["trace", "stateDiff", "vmTrace"]],"id":1}"#; - let response = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"This request is not supported because your node is running with state pruning. Run with --pruning=archive.","data":null},"id":1}"#; + let response = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"This request is not supported because your node is running with state pruning. Run with --pruning=archive."},"id":1}"#; assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); } diff --git a/rpc/src/v1/types/hash.rs b/rpc/src/v1/types/hash.rs index c96a3433b..2f230510d 100644 --- a/rpc/src/v1/types/hash.rs +++ b/rpc/src/v1/types/hash.rs @@ -124,13 +124,16 @@ macro_rules! impl_hash { type Value = $name; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "a 0x-prefixed, padded, hex-encoded hash of type {}", stringify!($name)) + write!(formatter, "a 0x-prefixed, padded, hex-encoded hash with length {}", $size * 2) } fn visit_str(self, value: &str) -> Result where E: serde::de::Error { + if value.len() < 2 || &value[0..2] != "0x" { + return Err(E::custom("expected a hex-encoded hash with 0x prefix")); + } if value.len() != 2 + $size * 2 { - return Err(E::custom("Invalid length.")); + return Err(E::invalid_length(value.len() - 2, &self)); } match value[2..].from_hex() { @@ -139,7 +142,7 @@ macro_rules! impl_hash { result.copy_from_slice(v); Ok($name(result)) }, - _ => Err(E::custom("Invalid hex value.")) + Err(e) => Err(E::custom(format!("invalid hex value: {:?}", e))), } } diff --git a/rpc/src/v1/types/uint.rs b/rpc/src/v1/types/uint.rs index ba3b83fa7..e61f0ab41 100644 --- a/rpc/src/v1/types/uint.rs +++ b/rpc/src/v1/types/uint.rs @@ -74,20 +74,20 @@ macro_rules! impl_uint { type Value = $name; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "a 0x-prefixed, hex-encoded number of type {}", stringify!($name)) + write!(formatter, "a 0x-prefixed, hex-encoded number of length {}", $size*16) } fn visit_str(self, value: &str) -> Result where E: serde::de::Error { + if value.len() < 2 || &value[0..2] != "0x" { + return Err(E::custom("expected a hex-encoded numbers with 0x prefix")) + } + // 0x + len - if value.len() > 2 + $size * 16 || value.len() < 2 { - return Err(E::custom("Invalid length.")); + if value.len() > 2 + $size * 16 { + return Err(E::invalid_length(value.len() - 2, &self)); } - if &value[0..2] != "0x" { - return Err(E::custom("Use hex encoded numbers with 0x prefix.")) - } - - $other::from_str(&value[2..]).map($name).map_err(|_| E::custom("Invalid hex value.")) + $other::from_str(&value[2..]).map($name).map_err(|e| E::custom(&format!("invalid hex value: {:?}", e))) } fn visit_string(self, value: String) -> Result where E: serde::de::Error { diff --git a/rpc_client/Cargo.toml b/rpc_client/Cargo.toml index 77f9c3edf..eb4a0ecff 100644 --- a/rpc_client/Cargo.toml +++ b/rpc_client/Cargo.toml @@ -1,7 +1,7 @@ [package] -authors = ["Ethcore "] +authors = ["Ethcore "] description = "Parity Rpc Client" -homepage = "http://ethcore.io" +homepage = "http://parity.io" license = "GPL-3.0" name = "parity-rpc-client" version = "1.4.0" @@ -14,8 +14,8 @@ serde = "0.9" serde_json = "0.9" tempdir = "0.3.5" url = "1.2.0" -jsonrpc-core = { git = "https://github.com/ethcore/jsonrpc.git", branch = "parity-1.6" } -ws = { git = "https://github.com/ethcore/ws-rs.git", branch = "mio-upstream-stable" } +jsonrpc-core = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } +ws = { git = "https://github.com/paritytech/ws-rs.git", branch = "mio-upstream-stable" } ethcore-rpc = { path = "../rpc" } ethcore-signer = { path = "../signer" } ethcore-util = { path = "../util" } diff --git a/rpc_client/src/client.rs b/rpc_client/src/client.rs index 5a4568d9e..3ef7ad7ce 100644 --- a/rpc_client/src/client.rs +++ b/rpc_client/src/client.rs @@ -83,18 +83,24 @@ impl Handler for RpcHandler { } fn on_error(&mut self, err: WsError) { match self.complete.take() { - Some(c) => c.complete(Err(RpcError::WsError(err))), - None => println!("unexpected error: {}", err), + Some(c) => match c.send(Err(RpcError::WsError(err))) { + Ok(_) => {}, + Err(_) => warn!(target: "rpc-client", "Unable to notify about error."), + }, + None => warn!(target: "rpc-client", "unexpected error: {}", err), } } fn on_open(&mut self, _: Handshake) -> WsResult<()> { match (self.complete.take(), self.out.take()) { (Some(c), Some(out)) => { - c.complete(Ok(Rpc { + let res = c.send(Ok(Rpc { out: out, counter: AtomicUsize::new(0), pending: self.pending.clone(), })); + if let Err(_) = res { + warn!(target: "rpc-client", "Unable to open a connection.") + } Ok(()) }, _ => { @@ -137,9 +143,9 @@ impl Handler for RpcHandler { } match self.pending.remove(response_id) { - Some(c) => c.complete(ret.map_err(|err| { - RpcError::JsonRpc(err) - })), + Some(c) => if let Err(_) = c.send(ret.map_err(|err| RpcError::JsonRpc(err))) { + warn!(target: "rpc-client", "Unable to send response.") + }, None => warn!( target: "rpc-client", "warning: unexpected id: {}", @@ -225,7 +231,7 @@ impl Rpc { // both fail and succeed. let c = once.take() .expect("connection closure called only once"); - c.complete(Err(RpcError::WsError(err))); + let _ = c.send(Err(RpcError::WsError(err))); }, // c will complete on the `on_open` event in the Handler _ => () diff --git a/signer/Cargo.toml b/signer/Cargo.toml index 4b80cfac5..2ed4df5be 100644 --- a/signer/Cargo.toml +++ b/signer/Cargo.toml @@ -12,11 +12,12 @@ rustc_version = "0.1" [dependencies] rand = "0.3.14" -jsonrpc-core = { git = "https://github.com/ethcore/jsonrpc.git", branch = "parity-1.6" } +jsonrpc-core = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } +jsonrpc-server-utils = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } log = "0.3" env_logger = "0.3" +ws = { git = "https://github.com/paritytech/ws-rs.git", branch = "mio-upstream-stable" } parity-dapps-glue = { version = "1.7", optional = true } -ws = { git = "https://github.com/ethcore/ws-rs.git", branch = "mio-upstream-stable" } ethcore-util = { path = "../util" } ethcore-io = { path = "../util/io" } ethcore-rpc = { path = "../rpc" } diff --git a/signer/src/lib.rs b/signer/src/lib.rs index 5cc103ba8..d211e2eac 100644 --- a/signer/src/lib.rs +++ b/signer/src/lib.rs @@ -30,21 +30,23 @@ //! //! ``` //! extern crate jsonrpc_core; +//! extern crate jsonrpc_server_utils; //! extern crate ethcore_signer; //! extern crate ethcore_rpc; //! //! use std::sync::Arc; //! use jsonrpc_core::IoHandler; -//! use jsonrpc_core::reactor::RpcEventLoop; +//! use jsonrpc_server_utils::reactor::RpcEventLoop; //! use ethcore_signer::ServerBuilder; //! use ethcore_rpc::ConfirmationsQueue; //! //! fn main() { //! let queue = Arc::new(ConfirmationsQueue::default()); -//! let io = Arc::new(IoHandler::new().into()); -//! let event_loop = RpcEventLoop::spawn(); +//! let io = IoHandler::default(); +//! let event_loop = RpcEventLoop::spawn().unwrap(); +//! let remote = event_loop.remote(); //! let _server = ServerBuilder::new(queue, "/tmp/authcodes".into()) -//! .start("127.0.0.1:8084".parse().unwrap(), event_loop.handler(io)); +//! .start("127.0.0.1:8084".parse().unwrap(), io, remote); //! } //! ``` @@ -57,6 +59,7 @@ extern crate ethcore_util as util; extern crate ethcore_rpc as rpc; extern crate ethcore_io as io; extern crate jsonrpc_core; +extern crate jsonrpc_server_utils; extern crate ws; extern crate ethcore_devtools as devtools; diff --git a/signer/src/tests/mod.rs b/signer/src/tests/mod.rs index 7de3a167a..bc90a6cd3 100644 --- a/signer/src/tests/mod.rs +++ b/signer/src/tests/mod.rs @@ -22,7 +22,7 @@ use devtools::RandomTempPath; use rpc::ConfirmationsQueue; use jsonrpc_core::IoHandler; -use jsonrpc_core::reactor::RpcEventLoop; +use jsonrpc_server_utils::reactor::RpcEventLoop; use rand; use ServerBuilder; @@ -70,9 +70,10 @@ pub fn serve() -> (ServerLoop, usize, GuardedAuthCodes) { let queue = Arc::new(ConfirmationsQueue::default()); let builder = ServerBuilder::new(queue, path.to_path_buf()); let port = 35000 + rand::random::() % 10000; - let event_loop = RpcEventLoop::spawn(); - let handler = event_loop.handler(Arc::new(IoHandler::default().into())); - let server = builder.start(format!("127.0.0.1:{}", port).parse().unwrap(), handler).unwrap(); + let event_loop = RpcEventLoop::spawn().unwrap(); + let io = IoHandler::default(); + let remote = event_loop.remote(); + let server = builder.start(format!("127.0.0.1:{}", port).parse().unwrap(), io, remote).unwrap(); let res = ServerLoop { server: server, event_loop: event_loop, diff --git a/signer/src/ws_server/mod.rs b/signer/src/ws_server/mod.rs index b799b0f66..314351938 100644 --- a/signer/src/ws_server/mod.rs +++ b/signer/src/ws_server/mod.rs @@ -26,8 +26,8 @@ use std::thread; use std; use io::{PanicHandler, OnPanicListener, MayPanic}; -use jsonrpc_core::{Metadata, Middleware}; -use jsonrpc_core::reactor::RpcHandler; +use jsonrpc_core::{Metadata, Middleware, MetaIoHandler}; +use jsonrpc_server_utils::tokio_core::reactor::Remote; use rpc::{ConfirmationsQueue}; use rpc::informant::RpcStats; @@ -92,21 +92,28 @@ impl ServerBuilder { /// Starts a new `WebSocket` server in separate thread. /// Returns a `Server` handle which closes the server when droped. - pub fn start>(self, addr: SocketAddr, handler: RpcHandler) -> Result { - self.start_with_extractor(addr, handler, NoopExtractor) + pub fn start, H: Into>>( + self, + addr: SocketAddr, + handler: H, + remote: Remote, + ) -> Result { + self.start_with_extractor(addr, handler, remote, NoopExtractor) } /// Starts a new `WebSocket` server in separate thread. /// Returns a `Server` handle which closes the server when droped. - pub fn start_with_extractor, T: session::MetaExtractor>( + pub fn start_with_extractor, H: Into>, T: session::MetaExtractor>( self, addr: SocketAddr, - handler: RpcHandler, + handler: H, + remote: Remote, meta_extractor: T, ) -> Result { Server::start( addr, - handler, + handler.into(), + remote, self.queue, self.authcodes_path, self.skip_origin_validation, @@ -136,7 +143,8 @@ impl Server { /// Returns a `Server` handle which closes the server when droped. fn start, T: session::MetaExtractor>( addr: SocketAddr, - handler: RpcHandler, + handler: MetaIoHandler, + remote: Remote, queue: Arc, authcodes_path: PathBuf, skip_origin_validation: bool, @@ -156,7 +164,7 @@ impl Server { let origin = format!("{}", addr); let port = addr.port(); let ws = ws::Builder::new().with_settings(config).build( - session::Factory::new(handler, origin, port, authcodes_path, skip_origin_validation, stats, meta_extractor) + session::Factory::new(handler, remote, origin, port, authcodes_path, skip_origin_validation, stats, meta_extractor) )?; let panic_handler = PanicHandler::new_in_arc(); diff --git a/signer/src/ws_server/session.rs b/signer/src/ws_server/session.rs index 5194855ab..91984ff05 100644 --- a/signer/src/ws_server/session.rs +++ b/signer/src/ws_server/session.rs @@ -21,8 +21,9 @@ use std::sync::Arc; use std::str::FromStr; use authcode_store::AuthCodes; -use jsonrpc_core::{Metadata, Middleware}; -use jsonrpc_core::reactor::RpcHandler; +use jsonrpc_core::{Metadata, Middleware, MetaIoHandler}; +use jsonrpc_core::futures::Future; +use jsonrpc_server_utils::tokio_core::reactor::Remote; use rpc::informant::RpcStats; use util::{H256, version}; use ws; @@ -145,7 +146,8 @@ pub struct Session, T> { self_origin: String, self_port: u16, authcodes_path: PathBuf, - handler: RpcHandler, + handler: Arc>, + remote: Remote, file_handler: Arc, stats: Option>, meta_extractor: T, @@ -237,7 +239,7 @@ impl, T: MetaExtractor> ws::Handler for Session // TODO [ToDr] Move to on_connect let metadata = self.meta_extractor.extract_metadata(&self.session_id); - self.handler.handle_request(req, metadata, move |response| { + let future = self.handler.handle_request(req, metadata).map(move |response| { if let Some(result) = response { let res = out.send(result); if let Err(e) = res { @@ -245,12 +247,14 @@ impl, T: MetaExtractor> ws::Handler for Session } } }); + self.remote.spawn(move |_| future); Ok(()) } } pub struct Factory, T> { - handler: RpcHandler, + handler: Arc>, + remote: Remote, skip_origin_validation: bool, self_origin: String, self_port: u16, @@ -262,7 +266,8 @@ pub struct Factory, T> { impl, T> Factory { pub fn new( - handler: RpcHandler, + handler: MetaIoHandler, + remote: Remote, self_origin: String, self_port: u16, authcodes_path: PathBuf, @@ -271,7 +276,8 @@ impl, T> Factory { meta_extractor: T, ) -> Self { Factory { - handler: handler, + handler: Arc::new(handler), + remote: remote, skip_origin_validation: skip_origin_validation, self_origin: self_origin, self_port: self_port, @@ -293,6 +299,7 @@ impl, T: MetaExtractor> ws::Factory for Factory session_id: 0.into(), out: sender, handler: self.handler.clone(), + remote: self.remote.clone(), skip_origin_validation: self.skip_origin_validation, self_origin: self.self_origin.clone(), self_port: self.self_port, diff --git a/stratum/Cargo.toml b/stratum/Cargo.toml index df984bef1..83d101b76 100644 --- a/stratum/Cargo.toml +++ b/stratum/Cargo.toml @@ -11,10 +11,9 @@ ethcore-ipc-codegen = { path = "../ipc/codegen" } [dependencies] log = "0.3" -jsonrpc-core = { git = "https://github.com/ethcore/jsonrpc.git", branch = "parity-1.6" } -jsonrpc-macros = { git = "https://github.com/ethcore/jsonrpc.git", branch = "parity-1.6" } -jsonrpc-tcp-server = { git = "https://github.com/ethcore/jsonrpc.git", branch = "parity-1.6" } -mio = { git = "https://github.com/ethcore/mio", branch = "v0.5.x" } +jsonrpc-core = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } +jsonrpc-macros = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } +jsonrpc-tcp-server = { git = "https://github.com/paritytech/jsonrpc.git", branch = "parity-1.7" } ethcore-util = { path = "../util" } ethcore-devtools = { path = "../devtools" } lazy_static = "0.2" diff --git a/stratum/src/lib.rs b/stratum/src/lib.rs index 5a7d50613..0042ab1e9 100644 --- a/stratum/src/lib.rs +++ b/stratum/src/lib.rs @@ -45,8 +45,8 @@ pub use traits::{ }; use jsonrpc_tcp_server::{ - Server as JsonRpcServer, RequestContext, MetaExtractor, Dispatcher, - PushMessageError + Server as JsonRpcServer, ServerBuilder as JsonRpcServerBuilder, + RequestContext, MetaExtractor, Dispatcher, PushMessageError, }; use jsonrpc_core::{MetaIoHandler, Params, to_value, Value, Metadata, Compatibility}; use jsonrpc_macros::IoDelegate; @@ -58,6 +58,8 @@ use util::{H256, Hashable, RwLock, RwLockReadGuard}; type RpcResult = BoxFuture; +const NOTIFY_COUNTER_INITIAL: u32 = 16; + struct StratumRpc { stratum: RwLock>>, } @@ -113,7 +115,7 @@ impl MetaExtractor for PeerMetaExtractor { } pub struct Stratum { - rpc_server: JsonRpcServer, + rpc_server: Option, /// Subscribed clients subscribers: RwLock>, /// List of workers supposed to receive job update @@ -130,7 +132,11 @@ pub struct Stratum { tcp_dispatcher: Dispatcher, } -const NOTIFY_COUNTER_INITIAL: u32 = 16; +impl Drop for Stratum { + fn drop(&mut self) { + self.rpc_server.take().map(|server| server.close()); + } +} impl Stratum { pub fn start( @@ -149,12 +155,14 @@ impl Stratum { let mut handler = MetaIoHandler::::with_compatibility(Compatibility::Both); handler.extend_with(delegate); - let server = JsonRpcServer::new(addr.clone(), Arc::new(handler)) - .extractor(Arc::new(PeerMetaExtractor) as Arc>); + let server = JsonRpcServerBuilder::new(handler) + .session_meta_extractor(PeerMetaExtractor); + let tcp_dispatcher = server.dispatcher(); + let server = server.start(addr)?; let stratum = Arc::new(Stratum { - tcp_dispatcher: server.dispatcher(), - rpc_server: server, + tcp_dispatcher: tcp_dispatcher, + rpc_server: Some(server), subscribers: RwLock::new(Vec::new()), job_que: RwLock::new(HashSet::new()), dispatcher: dispatcher, @@ -163,10 +171,6 @@ impl Stratum { notify_counter: RwLock::new(NOTIFY_COUNTER_INITIAL), }); *rpc.stratum.write() = Some(stratum.clone()); - - let running_stratum = stratum.clone(); - ::std::thread::spawn(move || running_stratum.rpc_server.run()); - Ok(stratum) } diff --git a/util/reactor/src/lib.rs b/util/reactor/src/lib.rs index 73ce9e404..e5f04d652 100644 --- a/util/reactor/src/lib.rs +++ b/util/reactor/src/lib.rs @@ -24,7 +24,7 @@ use std::thread; use std::sync::mpsc; use std::time::Duration; use futures::{Future, IntoFuture}; -use self::tokio_core::reactor::{Remote as TokioRemote, Timeout}; +pub use tokio_core::reactor::{Remote as TokioRemote, Timeout}; /// Event Loop for futures. /// Wrapper around `tokio::reactor::Core`. @@ -47,7 +47,7 @@ impl EventLoop { let remote = rx.recv().expect("tx is transfered to a newly spawned thread."); EventLoop { - remote: Remote{ + remote: Remote { inner: Mode::Tokio(remote), }, handle: EventLoopHandle { @@ -190,7 +190,7 @@ impl From for EventLoopHandle { impl Drop for EventLoopHandle { fn drop(&mut self) { - self.close.take().map(|v| v.complete(())); + self.close.take().map(|v| v.send(())); } } @@ -203,7 +203,8 @@ impl EventLoopHandle { /// Finishes this event loop. pub fn close(mut self) { - self.close.take() - .expect("Close is taken only in `close` and `drop`. `close` is consuming; qed").complete(()) + let _ = self.close.take() + .expect("Close is taken only in `close` and `drop`. `close` is consuming; qed") + .send(()); } } From e1f2ccd138c38bcaf0a5d41e78bfc299590b7dcc Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Wed, 22 Mar 2017 10:36:41 +0100 Subject: [PATCH 05/11] Extend api.util (#4979) * cleanupValue * abiUnencode & abiSignature * Export new functions --- js/src/api/util/encode.js | 31 +++++++++++++++++++++++++++++++ js/src/api/util/encode.spec.js | 31 +++++++++++++++++++++++++++++-- js/src/api/util/format.js | 32 ++++++++++++++++++++++++++++++++ js/src/api/util/format.spec.js | 24 +++++++++++++++++++++++- js/src/api/util/index.js | 7 +++++-- 5 files changed, 120 insertions(+), 5 deletions(-) diff --git a/js/src/api/util/encode.js b/js/src/api/util/encode.js index 5b5fb5eac..f18fbbe2b 100644 --- a/js/src/api/util/encode.js +++ b/js/src/api/util/encode.js @@ -17,6 +17,10 @@ import Abi from '~/abi'; import Func from '~/abi/spec/function'; +import { abiDecode } from './decode'; +import { cleanupValue } from './format'; +import { sha3 } from './sha3'; + export function encodeMethodCallAbi (methodAbi = {}, values = []) { const func = new Func(methodAbi); const tokens = Abi.encodeTokens(func.inputParamTypes(), values); @@ -36,3 +40,30 @@ export function abiEncode (methodName, inputTypes, data) { return result; } + +export function abiUnencode (abi, data) { + const callsig = data.substr(2, 8); + const op = abi.find((field) => { + return field.type === 'function' && + abiSignature(field.name, field.inputs.map((input) => input.type)).substr(2, 8) === callsig; + }); + + if (!op) { + console.warn(`Unknown function ID: ${callsig}`); + return null; + } + + let argsByIndex = abiDecode(op.inputs.map((field) => field.type), '0x' + data.substr(10)) + .map((value, index) => cleanupValue(value, op.inputs[index].type)); + const argsByName = op.inputs.reduce((result, field, index) => { + result[field.name] = argsByIndex[index]; + + return result; + }, {}); + + return [op.name, argsByName, argsByIndex]; +} + +export function abiSignature (name, inputs) { + return sha3(`${name}(${inputs.join()})`); +} diff --git a/js/src/api/util/encode.spec.js b/js/src/api/util/encode.spec.js index 6fead2ed5..7847f06ec 100644 --- a/js/src/api/util/encode.spec.js +++ b/js/src/api/util/encode.spec.js @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -import { abiEncode, encodeMethodCallAbi } from './encode'; +import { abiEncode, abiUnencode, abiSignature, encodeMethodCallAbi } from './encode'; const ABI = { type: 'function', @@ -51,7 +51,11 @@ describe('api/util/encode', () => { }); it('encodes variable values', () => { - expect(abiEncode('hintUrl', ['bytes32', 'string'], ['0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470', 'http://foo.bar/'])).to.equal(`0x${VARIABLE}`); + expect( + abiEncode( + 'hintUrl', ['bytes32', 'string'], ['0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470', 'http://foo.bar/'] + ) + ).to.equal(`0x${VARIABLE}`); }); it('encodes only the data with null name', () => { @@ -60,4 +64,27 @@ describe('api/util/encode', () => { ).to.equal(`0x${RESULT.substr(8)}`); }); }); + + describe('abiUnencode', () => { + it('decodes data correctly from abi', () => { + expect( + abiUnencode([{ + name: 'test', + type: 'function', + inputs: [ + { type: 'uint', name: 'arga' } + ] + }], '0x1acb6f7700000000000000000000000000000038') + ).to.deep.equal(['test', { arga: 56 }, [56]]); + }); + }); + + // Same example as in abi/util/signature.spec.js + describe('abiSignature', () => { + it('encodes baz(uint32,bool) correctly', () => { + expect( + abiSignature('baz', ['uint32', 'bool']) + ).to.equal('0xcdcd77c0992ec5bbfc459984220f8c45084cc24d9b6efed1fae540db8de801d2'); + }); + }); }); diff --git a/js/src/api/util/format.js b/js/src/api/util/format.js index c1fac8fff..c7594b692 100644 --- a/js/src/api/util/format.js +++ b/js/src/api/util/format.js @@ -20,6 +20,38 @@ export function bytesToHex (bytes) { return '0x' + bytes.map((b) => ('0' + b.toString(16)).slice(-2)).join(''); } +export function cleanupValue (value, type) { + // TODO: make work with arbitrary depth arrays + if (value instanceof Array && type.match(/bytes[0-9]+/)) { + // figure out if it's an ASCII string hiding in there: + let ascii = ''; + + for (let index = 0, ended = false; index < value.length && ascii !== null; ++index) { + const val = value[index]; + + if (val === 0) { + ended = true; + } else { + ascii += String.fromCharCode(val); + } + + if ((ended && val !== 0) || (!ended && (val < 32 || val >= 128))) { + ascii = null; + } + } + + value = ascii === null + ? bytesToHex(value) + : ascii; + } + + if (type.substr(0, 4) === 'uint' && +type.substr(4) <= 48) { + value = +value; + } + + return value; +} + export function hexToBytes (hex) { const raw = toHex(hex).slice(2); const bytes = []; diff --git a/js/src/api/util/format.spec.js b/js/src/api/util/format.spec.js index 8a89c0862..c37205569 100644 --- a/js/src/api/util/format.spec.js +++ b/js/src/api/util/format.spec.js @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -import { bytesToHex, hexToBytes, hexToAscii, bytesToAscii, asciiToHex } from './format'; +import { bytesToHex, cleanupValue, hexToBytes, hexToAscii, bytesToAscii, asciiToHex } from './format'; describe('api/util/format', () => { describe('bytesToHex', () => { @@ -27,6 +27,28 @@ describe('api/util/format', () => { }); }); + describe('cleanupValue', () => { + it('returns unknown values as the original', () => { + expect(cleanupValue('original', 'unknown')).to.equal('original'); + }); + + it('returns ascii arrays as ascii', () => { + expect(cleanupValue([97, 115, 99, 105, 105, 0], 'bytes32')).to.equal('ascii'); + }); + + it('returns non-ascii arrays as hex strings', () => { + expect(cleanupValue([97, 200, 0, 0], 'bytes4')).to.equal('0x61c80000'); + }); + + it('returns uint (>48) as the original', () => { + expect(cleanupValue('original', 'uint49')).to.equal('original'); + }); + + it('returns uint (<=48) as the number value', () => { + expect(cleanupValue('12345', 'uint48')).to.equal(12345); + }); + }); + describe('hexToBytes', () => { it('correctly converts an empty string', () => { expect(hexToBytes('')).to.deep.equal([]); diff --git a/js/src/api/util/index.js b/js/src/api/util/index.js index 254b97c74..cc8fc9b93 100644 --- a/js/src/api/util/index.js +++ b/js/src/api/util/index.js @@ -16,8 +16,8 @@ import { isAddress as isAddressValid, toChecksumAddress } from '../../abi/util/address'; import { abiDecode, decodeCallData, decodeMethodInput, methodToAbi } from './decode'; -import { abiEncode, encodeMethodCallAbi } from './encode'; -import { bytesToHex, hexToAscii, asciiToHex } from './format'; +import { abiEncode, abiUnencode, abiSignature, encodeMethodCallAbi } from './encode'; +import { bytesToHex, hexToAscii, asciiToHex, cleanupValue } from './format'; import { fromWei, toWei } from './wei'; import { sha3 } from './sha3'; import { isArray, isFunction, isHex, isInstanceOf, isString } from './types'; @@ -26,6 +26,9 @@ import { createIdentityImg } from './identity'; export default { abiDecode, abiEncode, + abiUnencode, + abiSignature, + cleanupValue, isAddressValid, isArray, isFunction, From b725829bfd799be8a86c66652c340771838621d5 Mon Sep 17 00:00:00 2001 From: GitLab Build Bot Date: Wed, 22 Mar 2017 09:57:28 +0000 Subject: [PATCH 06/11] [ci skip] js-precompiled 20170322-095443 --- Cargo.lock | 2 +- js/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 819226c00..66694c7fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1749,7 +1749,7 @@ dependencies = [ [[package]] name = "parity-ui-precompiled" version = "1.4.0" -source = "git+https://github.com/ethcore/js-precompiled.git#24a28bd6f55c3540f18e14ec00fbb8f207be25d4" +source = "git+https://github.com/ethcore/js-precompiled.git#69e44266d3b2e434dfcd99d5cba1ac0cbc01a0eb" dependencies = [ "parity-dapps-glue 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)", ] diff --git a/js/package.json b/js/package.json index eac319740..23b2ac804 100644 --- a/js/package.json +++ b/js/package.json @@ -1,6 +1,6 @@ { "name": "parity.js", - "version": "1.7.23", + "version": "1.7.24", "main": "release/index.js", "jsnext:main": "src/index.js", "author": "Parity Team ", From a028e445fe8818f6e0b921e49a87676a8159bbde Mon Sep 17 00:00:00 2001 From: Nicolas Gotchac Date: Wed, 22 Mar 2017 11:56:52 +0100 Subject: [PATCH 07/11] Fixes to the Registry dapp (#4984) * Don't show fee warning when there is none * Hide Warning in Registry onclick * Use the default account in the Registry * Fix Etherscan links in Regsitry --- js/src/api/subscriptions/personal.js | 2 +- js/src/dapps/registry/Accounts/accounts.css | 20 +---- js/src/dapps/registry/Accounts/accounts.js | 83 ++++++------------- js/src/dapps/registry/Accounts/actions.js | 23 +++++ .../registry/Application/application.css | 5 +- .../dapps/registry/Application/application.js | 43 +++++++++- js/src/dapps/registry/Names/actions.js | 14 ++-- js/src/dapps/registry/Records/actions.js | 8 +- js/src/dapps/registry/Reverse/actions.js | 16 ++-- .../registry/addresses/accounts-reducer.js | 4 +- js/src/dapps/registry/util/etherscan-url.js | 2 +- 11 files changed, 118 insertions(+), 102 deletions(-) diff --git a/js/src/api/subscriptions/personal.js b/js/src/api/subscriptions/personal.js index 15b037b42..fa7ae823c 100644 --- a/js/src/api/subscriptions/personal.js +++ b/js/src/api/subscriptions/personal.js @@ -42,7 +42,7 @@ export default class Personal { // FIXME: Because of the different API instances, the "wait for valid changes" approach // doesn't work. Since the defaultAccount is critical to operation, we poll in exactly - // same way we do in ../eth (ala same as eth_blockNumber) and update. This should be moved + // same way we do in ../eth (ala eth_blockNumber) and update. This should be moved // to pub-sub as it becomes available _defaultAccount = (timerDisabled = false) => { const nextTimeout = (timeout = 1000) => { diff --git a/js/src/dapps/registry/Accounts/accounts.css b/js/src/dapps/registry/Accounts/accounts.css index d69c25e2b..d886138f0 100644 --- a/js/src/dapps/registry/Accounts/accounts.css +++ b/js/src/dapps/registry/Accounts/accounts.css @@ -15,24 +15,10 @@ /* along with Parity. If not, see . */ -.button { - /* TODO remove !important once material design lite is used */ - padding: 0 !important; -} - .icon { /* TODO remove !important once material design lite is used */ - margin: 0 !important; - width: 30px !important; height: 30px !important; -} - -.menuIcon { - display: inline-block; - vertical-align: middle; -} -.menuText { - display: inline-block; - line-height: 24px; - vertical-align: top; + margin: 0 !important; + padding: 0 !important; + width: 30px !important; } diff --git a/js/src/dapps/registry/Accounts/accounts.js b/js/src/dapps/registry/Accounts/accounts.js index 0651f6857..b17ad63b1 100644 --- a/js/src/dapps/registry/Accounts/accounts.js +++ b/js/src/dapps/registry/Accounts/accounts.js @@ -17,83 +17,50 @@ import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; -import IconMenu from 'material-ui/IconMenu'; -import IconButton from 'material-ui/IconButton/IconButton'; import AccountIcon from 'material-ui/svg-icons/action/account-circle'; -import MenuItem from 'material-ui/MenuItem'; +import { init } from './actions'; import IdentityIcon from '../IdentityIcon'; -import Address from '../ui/address'; -import { select } from './actions'; import styles from './accounts.css'; class Accounts extends Component { static propTypes = { - all: PropTypes.object.isRequired, - selected: PropTypes.object, + selected: PropTypes.oneOfType([ + PropTypes.oneOf([ null ]), + PropTypes.string + ]), + onInit: PropTypes.func.isRequired + }; - select: PropTypes.func.isRequired + componentWillMount () { + this.props.onInit(); } render () { - const { all, selected } = this.props; + const { selected } = this.props; - const origin = { horizontal: 'right', vertical: 'top' }; - - const accountsButton = ( - - { selected - ? ( - - ) : ( - - ) - } - ); + if (!selected) { + return ( + + ); + } return ( - - { Object.values(all).map(this.renderAccount) } - + ); } - - renderAccount = (account) => { - const { selected } = this.props; - const isSelected = selected && selected.address === account.address; - - return ( - -
- - ); - }; - - onAccountSelect = (e, address) => { - this.props.select(address); - }; } const mapStateToProps = (state) => state.accounts; -const mapDispatchToProps = (dispatch) => bindActionCreators({ select }, dispatch); +const mapDispatchToProps = (dispatch) => bindActionCreators({ + onInit: init +}, dispatch); export default connect(mapStateToProps, mapDispatchToProps)(Accounts); diff --git a/js/src/dapps/registry/Accounts/actions.js b/js/src/dapps/registry/Accounts/actions.js index bacd85f2e..7f38de579 100644 --- a/js/src/dapps/registry/Accounts/actions.js +++ b/js/src/dapps/registry/Accounts/actions.js @@ -14,4 +14,27 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . +import { api } from '../parity'; + export const select = (address) => ({ type: 'accounts select', address }); + +export const init = () => (dispatch) => { + api.subscribe('parity_defaultAccount', (error, accountAddress) => { + if (error) { + return console.error(error); + } + + if (accountAddress) { + dispatch(select(accountAddress)); + } + }); + + return api.parity + .defaultAccount() + .then((accountAddress) => { + dispatch(select(accountAddress)); + }) + .catch((error) => { + console.error(error); + }); +}; diff --git a/js/src/dapps/registry/Application/application.css b/js/src/dapps/registry/Application/application.css index e4fc21a26..b9fac12ae 100644 --- a/js/src/dapps/registry/Application/application.css +++ b/js/src/dapps/registry/Application/application.css @@ -16,9 +16,11 @@ */ .header { + align-items: center; display: flex; justify-content: space-between; - margin: 0; padding: .3em 1em; + margin: 0; + padding: 0.3em 1em; color: #fff; background-color: #333; } @@ -54,6 +56,7 @@ background: #f80; bottom: 0; color: #fff; + cursor: pointer; left: 0; opacity: 1; padding: 1.5em; diff --git a/js/src/dapps/registry/Application/application.js b/js/src/dapps/registry/Application/application.js index 33b3662b1..7857b1ad1 100644 --- a/js/src/dapps/registry/Application/application.js +++ b/js/src/dapps/registry/Application/application.js @@ -49,6 +49,10 @@ export default class Application extends Component { fee: nullableProptype(PropTypes.object.isRequired) }; + state = { + showWarning: true + }; + render () { const { contract, fee } = this.props; let warning = null; @@ -65,9 +69,7 @@ export default class Application extends Component { { this.renderActions() } -
- WARNING: The name registry is experimental. Please ensure that you understand the risks, benefits & consequences of registering a name before doing so. A non-refundable fee of { api.util.fromWei(fee).toFormat(3) }ETH is required for all registrations. -
+ { this.renderWarning() } ) : ( @@ -98,4 +100,39 @@ export default class Application extends Component { ); } + + renderWarning () { + const { showWarning } = this.state; + const { fee } = this.props; + + if (!showWarning) { + return null; + } + + return ( +
+ + WARNING: The name registry is experimental. Please ensure that you understand the risks, + benefits & consequences of registering a name before doing so. + + { + fee && api.util.fromWei(fee).gt(0) + ? ( + +  A non-refundable fee of { api.util.fromWei(fee).toFormat(3) } ETH +  is required for all registrations. + + ) + : null + } +
+ ); + } + + handleHideWarning = () => { + this.setState({ showWarning: false }); + } } diff --git a/js/src/dapps/registry/Names/actions.js b/js/src/dapps/registry/Names/actions.js index 8bc981d0d..9e5ff4fc6 100644 --- a/js/src/dapps/registry/Names/actions.js +++ b/js/src/dapps/registry/Names/actions.js @@ -33,11 +33,11 @@ export const reserveFail = (name, error) => ({ type: 'names reserve fail', name, export const reserve = (name) => (dispatch, getState) => { const state = getState(); - const account = state.accounts.selected; + const accountAddress = state.accounts.selected; const contract = state.contract; const fee = state.fee; - if (!contract || !account) { + if (!contract || !accountAddress) { return; } @@ -58,7 +58,7 @@ export const reserve = (name) => (dispatch, getState) => { const { reserve } = contract.instance; const options = { - from: account.address, + from: accountAddress, value: fee }; const values = [ @@ -88,10 +88,10 @@ export const dropFail = (name, error) => ({ type: 'names drop fail', name, error export const drop = (name) => (dispatch, getState) => { const state = getState(); - const account = state.accounts.selected; + const accountAddress = state.accounts.selected; const contract = state.contract; - if (!contract || !account) { + if (!contract || !accountAddress) { return; } @@ -105,14 +105,14 @@ export const drop = (name) => (dispatch, getState) => { return getOwner(contract, name) .then((owner) => { - if (owner.toLowerCase() !== account.address.toLowerCase()) { + if (owner.toLowerCase() !== accountAddress.toLowerCase()) { throw new Error(`you are not the owner of "${name}"`); } const { drop } = contract.instance; const options = { - from: account.address + from: accountAddress }; const values = [ diff --git a/js/src/dapps/registry/Records/actions.js b/js/src/dapps/registry/Records/actions.js index 9f0d1beff..4b7ef51d1 100644 --- a/js/src/dapps/registry/Records/actions.js +++ b/js/src/dapps/registry/Records/actions.js @@ -30,10 +30,10 @@ export const fail = (error) => ({ type: 'records update fail', error }); export const update = (name, key, value) => (dispatch, getState) => { const state = getState(); - const account = state.accounts.selected; + const accountAddress = state.accounts.selected; const contract = state.contract; - if (!contract || !account) { + if (!contract || !accountAddress) { return; } @@ -42,7 +42,7 @@ export const update = (name, key, value) => (dispatch, getState) => { return getOwner(contract, name) .then((owner) => { - if (owner.toLowerCase() !== account.address.toLowerCase()) { + if (owner.toLowerCase() !== accountAddress.toLowerCase()) { throw new Error(`you are not the owner of "${name}"`); } @@ -51,7 +51,7 @@ export const update = (name, key, value) => (dispatch, getState) => { : contract.instance.setData || contract.instance.set; const options = { - from: account.address + from: accountAddress }; const values = [ diff --git a/js/src/dapps/registry/Reverse/actions.js b/js/src/dapps/registry/Reverse/actions.js index 6effa9f10..f78ff3434 100644 --- a/js/src/dapps/registry/Reverse/actions.js +++ b/js/src/dapps/registry/Reverse/actions.js @@ -30,10 +30,10 @@ export const fail = (action, error) => ({ type: `reverse ${action} fail`, error export const propose = (name, address) => (dispatch, getState) => { const state = getState(); - const account = state.accounts.selected; + const accountAddress = state.accounts.selected; const contract = state.contract; - if (!contract || !account) { + if (!contract || !accountAddress) { return; } @@ -42,14 +42,14 @@ export const propose = (name, address) => (dispatch, getState) => { return getOwner(contract, name) .then((owner) => { - if (owner.toLowerCase() !== account.address.toLowerCase()) { + if (owner.toLowerCase() !== accountAddress.toLowerCase()) { throw new Error(`you are not the owner of "${name}"`); } const { proposeReverse } = contract.instance; const options = { - from: account.address + from: accountAddress }; const values = [ @@ -74,10 +74,10 @@ export const propose = (name, address) => (dispatch, getState) => { export const confirm = (name) => (dispatch, getState) => { const state = getState(); - const account = state.accounts.selected; + const accountAddress = state.accounts.selected; const contract = state.contract; - if (!contract || !account) { + if (!contract || !accountAddress) { return; } @@ -86,14 +86,14 @@ export const confirm = (name) => (dispatch, getState) => { return getOwner(contract, name) .then((owner) => { - if (owner.toLowerCase() !== account.address.toLowerCase()) { + if (owner.toLowerCase() !== accountAddress.toLowerCase()) { throw new Error(`you are not the owner of "${name}"`); } const { confirmReverse } = contract.instance; const options = { - from: account.address + from: accountAddress }; const values = [ diff --git a/js/src/dapps/registry/addresses/accounts-reducer.js b/js/src/dapps/registry/addresses/accounts-reducer.js index 5be0421ec..2ff11ae27 100644 --- a/js/src/dapps/registry/addresses/accounts-reducer.js +++ b/js/src/dapps/registry/addresses/accounts-reducer.js @@ -31,8 +31,8 @@ export default (state = initialState, action) => { return { ...state, all: accounts }; } - if (action.type === 'accounts select' && state.all[action.address]) { - return { ...state, selected: state.all[action.address] }; + if (action.type === 'accounts select') { + return { ...state, selected: action.address }; } return state; diff --git a/js/src/dapps/registry/util/etherscan-url.js b/js/src/dapps/registry/util/etherscan-url.js index bb4e2fe98..68e765c17 100644 --- a/js/src/dapps/registry/util/etherscan-url.js +++ b/js/src/dapps/registry/util/etherscan-url.js @@ -22,7 +22,7 @@ const etherscanUrl = (hash, isTestnet, netVersion) => { hash = hash.toLowerCase().replace(leading0x, ''); const type = hash.length === 40 ? 'address' : 'tx'; - return `https://${externalUrl(isTestnet, netVersion)}/${type}/0x${hash}`; + return `${externalUrl(isTestnet, netVersion)}/${type}/0x${hash}`; }; export default etherscanUrl; From 67c225f971ada7c9c9b28c67d3c1fa11c7048f6f Mon Sep 17 00:00:00 2001 From: Nicolas Gotchac Date: Wed, 22 Mar 2017 12:12:21 +0100 Subject: [PATCH 08/11] Double click to select account creation type (#4986) * Extend links to whole container * Add doubleClick to Account Creator --- .../CreationType/creationType.js | 8 ++++++ js/src/ui/Container/container.js | 9 +++++-- js/src/ui/SelectionList/selectionList.js | 26 ++++++++++++++----- 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/js/src/modals/CreateAccount/CreationType/creationType.js b/js/src/modals/CreateAccount/CreationType/creationType.js index 392db7445..a7d23a667 100644 --- a/js/src/modals/CreateAccount/CreationType/creationType.js +++ b/js/src/modals/CreateAccount/CreationType/creationType.js @@ -145,6 +145,7 @@ export default class CreationType extends Component { items={ TYPES } noStretch onSelectClick={ this.onChange } + onSelectDoubleClick={ this.onSelect } renderItem={ this.renderItem } /> ); @@ -180,4 +181,11 @@ export default class CreationType extends Component { store.setCreateType(item.key); } + + onSelect = (item) => { + const { store } = this.props; + + store.setCreateType(item.key); + store.nextStage(); + } } diff --git a/js/src/ui/Container/container.js b/js/src/ui/Container/container.js index ef26a3ad8..81e48f7f3 100644 --- a/js/src/ui/Container/container.js +++ b/js/src/ui/Container/container.js @@ -82,11 +82,16 @@ export default class Container extends Component { to={ link } > { card } + { this.renderHover() } ) - : card + : ( +
+ { card } + { this.renderHover() } +
+ ) } - { this.renderHover() } ); } diff --git a/js/src/ui/SelectionList/selectionList.js b/js/src/ui/SelectionList/selectionList.js index b8ee1fee6..a7375581d 100644 --- a/js/src/ui/SelectionList/selectionList.js +++ b/js/src/ui/SelectionList/selectionList.js @@ -14,6 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . +import { noop } from 'lodash'; import React, { Component, PropTypes } from 'react'; import { StarIcon } from '~/ui/Icons'; @@ -29,8 +30,13 @@ export default class SelectionList extends Component { noStretch: PropTypes.bool, onDefaultClick: PropTypes.func, onSelectClick: PropTypes.func.isRequired, + onSelectDoubleClick: PropTypes.func, renderItem: PropTypes.func.isRequired - } + }; + + static defaultProps = { + onSelectDoubleClick: noop + }; render () { const { items, noStretch } = this.props; @@ -45,23 +51,28 @@ export default class SelectionList extends Component { } renderItem = (item, index) => { - const { isChecked, onDefaultClick, onSelectClick, renderItem } = this.props; + const { isChecked, onDefaultClick, onSelectClick, onSelectDoubleClick, renderItem } = this.props; const isSelected = isChecked ? isChecked(item) : item.checked; - const makeDefault = () => { - onDefaultClick(item); + const handleClick = () => { + onSelectClick(item); return false; }; - const selectItem = () => { - onSelectClick(item); + const handleDoubleClick = () => { + onSelectDoubleClick(item); return false; }; let defaultIcon = null; if (onDefaultClick) { + const makeDefault = () => { + onDefaultClick(item); + return false; + }; + defaultIcon = (
{ @@ -85,7 +96,8 @@ export default class SelectionList extends Component {
{ renderItem(item, index) }
From 07ee7a341b86251d9bab09339ad348b257f092e9 Mon Sep 17 00:00:00 2001 From: GitLab Build Bot Date: Wed, 22 Mar 2017 11:18:36 +0000 Subject: [PATCH 09/11] [ci skip] js-precompiled 20170322-111524 --- Cargo.lock | 2 +- js/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 66694c7fd..91918a115 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1749,7 +1749,7 @@ dependencies = [ [[package]] name = "parity-ui-precompiled" version = "1.4.0" -source = "git+https://github.com/ethcore/js-precompiled.git#69e44266d3b2e434dfcd99d5cba1ac0cbc01a0eb" +source = "git+https://github.com/ethcore/js-precompiled.git#2a4710a12e4bdebfd4240891ad81c469b9cd6642" dependencies = [ "parity-dapps-glue 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)", ] diff --git a/js/package.json b/js/package.json index 23b2ac804..1e1488a0d 100644 --- a/js/package.json +++ b/js/package.json @@ -1,6 +1,6 @@ { "name": "parity.js", - "version": "1.7.24", + "version": "1.7.25", "main": "release/index.js", "jsnext:main": "src/index.js", "author": "Parity Team ", From b6f9cf4ba78ec98870f9efe366f6e521d59f5f21 Mon Sep 17 00:00:00 2001 From: GitLab Build Bot Date: Wed, 22 Mar 2017 11:32:23 +0000 Subject: [PATCH 10/11] [ci skip] js-precompiled 20170322-112932 --- Cargo.lock | 2 +- js/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 91918a115..458e3cae5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1749,7 +1749,7 @@ dependencies = [ [[package]] name = "parity-ui-precompiled" version = "1.4.0" -source = "git+https://github.com/ethcore/js-precompiled.git#2a4710a12e4bdebfd4240891ad81c469b9cd6642" +source = "git+https://github.com/ethcore/js-precompiled.git#9651995aa0fa718b9b9b58f1c7281900643bdf8f" dependencies = [ "parity-dapps-glue 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)", ] diff --git a/js/package.json b/js/package.json index 1e1488a0d..54cc076fe 100644 --- a/js/package.json +++ b/js/package.json @@ -1,6 +1,6 @@ { "name": "parity.js", - "version": "1.7.25", + "version": "1.7.26", "main": "release/index.js", "jsnext:main": "src/index.js", "author": "Parity Team ", From 044d070667c924652ec6c5997eadd0d30e538afb Mon Sep 17 00:00:00 2001 From: Marek Kotewicz Date: Wed, 22 Mar 2017 14:41:46 +0100 Subject: [PATCH 11/11] rlp deserialization refactor, 30% faster (#4901) * fixed naming of rlp modules * RlpStream cleanup * appending short rlp lists (0...55 bytes) is 25% faster * RlpStream does not use bytes module, nor trait Stream * removed unused code from rlp module * compiling ethcore-util with new rlp serialization * compiling parity with new rlp serialization * fixed compiling ethcore-light with new rlp serialization * fixed compiling ethsync with new rlp serialization * moved rlp benches and rlp tests * rlp deserialization refactor, 30% faster * removed redundant comment, print * fixed compiling parity with new rlp deserialization * removed redundant double-space * fixed failing test * updated rlp docs, removed unused traits * fixed rlp benchmarks * replace usage of WriteBytesExt with ByteOrder * removed unused, commented out code * fixed merge conflict --- ethcore/light/src/cht.rs | 2 +- ethcore/light/src/net/mod.rs | 4 +- ethcore/light/src/net/request_credits.rs | 6 +- ethcore/light/src/net/status.rs | 10 +- ethcore/light/src/on_demand/request.rs | 2 +- ethcore/src/block.rs | 15 +- ethcore/src/blockchain/extras.rs | 22 ++- ethcore/src/blooms/bloom.rs | 4 +- ethcore/src/blooms/bloom_group.rs | 4 +- ethcore/src/client/client.rs | 4 +- ethcore/src/engines/authority_round.rs | 2 +- ethcore/src/engines/basic_authority.rs | 2 +- ethcore/src/engines/tendermint/message.rs | 9 +- ethcore/src/engines/tendermint/mod.rs | 2 +- ethcore/src/ethereum/ethash.rs | 2 +- ethcore/src/header.rs | 6 +- ethcore/src/json_tests/transaction.rs | 2 +- ethcore/src/migrations/blocks/v8.rs | 2 +- ethcore/src/migrations/state/v7.rs | 5 +- ethcore/src/migrations/v9.rs | 2 +- ethcore/src/snapshot/account.rs | 4 +- ethcore/src/snapshot/block.rs | 8 +- ethcore/src/snapshot/io.rs | 16 +- ethcore/src/snapshot/mod.rs | 10 +- ethcore/src/spec/spec.rs | 2 +- ethcore/src/state/account.rs | 2 +- ethcore/src/tests/client.rs | 1 - ethcore/src/trace/bloom.rs | 8 +- ethcore/src/types/basic_account.rs | 3 +- ethcore/src/types/encoded.rs | 2 +- ethcore/src/types/executed.rs | 4 +- ethcore/src/types/log_entry.rs | 9 +- ethcore/src/types/receipt.rs | 19 +- ethcore/src/types/snapshot_manifest.rs | 4 +- ethcore/src/types/trace_types/error.rs | 6 +- ethcore/src/types/trace_types/flat.rs | 13 +- ethcore/src/types/trace_types/trace.rs | 122 ++++++------- ethcore/src/types/transaction.rs | 10 +- ethcore/src/verification/verification.rs | 5 +- ethcore/src/views/block.rs | 6 +- ethcore/src/views/body.rs | 6 +- ethcore/src/views/header.rs | 2 +- ethcore/src/views/transaction.rs | 2 +- local-store/src/lib.rs | 2 +- parity/informant.rs | 1 - rpc/src/v1/impls/eth.rs | 2 +- rpc/src/v1/impls/light/eth.rs | 2 +- rpc/src/v1/impls/signer.rs | 2 +- rpc/src/v1/impls/traces.rs | 2 +- rpc/src/v1/tests/mocked/eth.rs | 2 +- sync/src/block_sync.rs | 6 +- sync/src/chain.rs | 24 +-- sync/src/light_sync/response.rs | 2 +- util/network/src/discovery.rs | 2 +- util/network/src/session.rs | 9 +- util/{ => rlp}/benches/rlp.rs | 20 +-- util/rlp/src/bytes.rs | 148 ---------------- util/rlp/src/compression.rs | 8 +- util/rlp/src/error.rs | 9 - util/rlp/src/impls.rs | 159 ++++++++++++++++- util/rlp/src/lib.rs | 19 +- util/rlp/src/rlpin.rs | 201 ++++++++++++++++----- util/rlp/src/traits.rs | 204 +--------------------- util/rlp/src/untrusted_rlp.rs | 185 +++++--------------- util/rlp/{src => tests}/tests.rs | 56 +++--- util/src/journaldb/earlymergedb.rs | 6 +- util/src/journaldb/overlayrecentdb.rs | 2 +- util/src/journaldb/refcounteddb.rs | 2 +- util/src/kvdb.rs | 2 +- util/src/trie/lookup.rs | 2 +- util/src/trie/triedbmut.rs | 2 +- 71 files changed, 618 insertions(+), 834 deletions(-) rename util/{ => rlp}/benches/rlp.rs (85%) delete mode 100644 util/rlp/src/bytes.rs rename util/rlp/{src => tests}/tests.rs (90%) diff --git a/ethcore/light/src/cht.rs b/ethcore/light/src/cht.rs index 94b9946c0..7c749b44f 100644 --- a/ethcore/light/src/cht.rs +++ b/ethcore/light/src/cht.rs @@ -23,7 +23,7 @@ use ethcore::ids::BlockId; use util::{Bytes, H256, U256, HashDB, MemoryDB}; use util::trie::{self, TrieMut, TrieDBMut, Trie, TrieDB, Recorder}; -use rlp::{RlpStream, UntrustedRlp, View}; +use rlp::{RlpStream, UntrustedRlp}; // encode a key. macro_rules! key { diff --git a/ethcore/light/src/net/mod.rs b/ethcore/light/src/net/mod.rs index 4749dc281..3830dde4b 100644 --- a/ethcore/light/src/net/mod.rs +++ b/ethcore/light/src/net/mod.rs @@ -24,7 +24,7 @@ use ethcore::receipt::Receipt; use io::TimerToken; use network::{NetworkProtocolHandler, NetworkContext, PeerId}; -use rlp::{RlpStream, UntrustedRlp, View}; +use rlp::{RlpStream, UntrustedRlp}; use util::hash::H256; use util::{Bytes, DBValue, Mutex, RwLock, U256}; use time::{Duration, SteadyTime}; @@ -953,7 +953,7 @@ impl LightProtocol { let id_guard = self.pre_verify_response(peer, request::Kind::Receipts, &raw)?; let raw_receipts: Vec> = raw.at(2)? .iter() - .map(|x| x.as_val()) + .map(|x| x.as_list()) .collect::>()?; let req_id = id_guard.defuse(); diff --git a/ethcore/light/src/net/request_credits.rs b/ethcore/light/src/net/request_credits.rs index 7f1960fc5..f35c6662f 100644 --- a/ethcore/light/src/net/request_credits.rs +++ b/ethcore/light/src/net/request_credits.rs @@ -126,10 +126,8 @@ impl Encodable for CostTable { } } -impl RlpDecodable for CostTable { - fn decode(decoder: &D) -> Result where D: Decoder { - let rlp = decoder.as_rlp(); - +impl Decodable for CostTable { + fn decode(rlp: &UntrustedRlp) -> Result { let mut headers = None; let mut bodies = None; let mut receipts = None; diff --git a/ethcore/light/src/net/status.rs b/ethcore/light/src/net/status.rs index f5464c036..732826430 100644 --- a/ethcore/light/src/net/status.rs +++ b/ethcore/light/src/net/status.rs @@ -16,7 +16,7 @@ //! Peer status and capabilities. -use rlp::{DecoderError, RlpDecodable, Encodable, RlpStream, UntrustedRlp, View}; +use rlp::{DecoderError, Encodable, Decodable, RlpStream, UntrustedRlp}; use util::{H256, U256}; use super::request_credits::FlowParams; @@ -91,7 +91,7 @@ struct Parser<'a> { impl<'a> Parser<'a> { // expect a specific next key, and decode the value. // error on unexpected key or invalid value. - fn expect(&mut self, key: Key) -> Result { + fn expect(&mut self, key: Key) -> Result { self.expect_raw(key).and_then(|item| item.as_val()) } @@ -110,7 +110,7 @@ impl<'a> Parser<'a> { // get the next key and value RLP. fn get_next(&mut self) -> Result)>, DecoderError> { - while self.pos < self.rlp.item_count() { + while self.pos < self.rlp.item_count()? { let pair = self.rlp.at(self.pos)?; let k: String = pair.val_at(0)?; @@ -374,7 +374,7 @@ mod tests { use super::*; use super::super::request_credits::FlowParams; use util::{U256, H256}; - use rlp::{RlpStream, UntrustedRlp, View}; + use rlp::{RlpStream, UntrustedRlp}; #[test] fn full_handshake() { @@ -474,7 +474,7 @@ mod tests { let handshake = write_handshake(&status, &capabilities, Some(&flow_params)); let interleaved = { let handshake = UntrustedRlp::new(&handshake); - let mut stream = RlpStream::new_list(handshake.item_count() * 3); + let mut stream = RlpStream::new_list(handshake.item_count().unwrap_or(0) * 3); for item in handshake.iter() { stream.append_raw(item.as_raw(), 1); diff --git a/ethcore/light/src/on_demand/request.rs b/ethcore/light/src/on_demand/request.rs index 0b16d091c..1db796982 100644 --- a/ethcore/light/src/on_demand/request.rs +++ b/ethcore/light/src/on_demand/request.rs @@ -26,7 +26,7 @@ use ethcore::receipt::Receipt; use ethcore::state::{self, ProvedExecution}; use ethcore::transaction::SignedTransaction; -use rlp::{RlpStream, UntrustedRlp, View}; +use rlp::{RlpStream, UntrustedRlp}; use util::{Address, Bytes, DBValue, HashDB, H256, U256}; use util::memorydb::MemoryDB; use util::sha3::Hashable; diff --git a/ethcore/src/block.rs b/ethcore/src/block.rs index c0ae90bb4..38278af05 100644 --- a/ethcore/src/block.rs +++ b/ethcore/src/block.rs @@ -20,7 +20,7 @@ use std::cmp; use std::sync::Arc; use std::collections::HashSet; -use rlp::{UntrustedRlp, RlpStream, Encodable, Decodable, Decoder, DecoderError, View}; +use rlp::{UntrustedRlp, RlpStream, Encodable, Decodable, DecoderError}; use util::{Bytes, Address, Uint, Hashable, U256, H256, ordered_trie_root, SHA3_NULL_RLP}; use util::error::{Mismatch, OutOfBounds}; @@ -67,18 +67,17 @@ impl Block { impl Decodable for Block { - fn decode(decoder: &D) -> Result where D: Decoder { - if decoder.as_raw().len() != decoder.as_rlp().payload_info()?.total() { + fn decode(rlp: &UntrustedRlp) -> Result { + if rlp.as_raw().len() != rlp.payload_info()?.total() { return Err(DecoderError::RlpIsTooBig); } - let d = decoder.as_rlp(); - if d.item_count() != 3 { + if rlp.item_count()? != 3 { return Err(DecoderError::RlpIncorrectListLen); } Ok(Block { - header: d.val_at(0)?, - transactions: d.val_at(1)?, - uncles: d.val_at(2)?, + header: rlp.val_at(0)?, + transactions: rlp.list_at(1)?, + uncles: rlp.list_at(2)?, }) } } diff --git a/ethcore/src/blockchain/extras.rs b/ethcore/src/blockchain/extras.rs index 3122a78d7..0c8616a45 100644 --- a/ethcore/src/blockchain/extras.rs +++ b/ethcore/src/blockchain/extras.rs @@ -154,13 +154,12 @@ impl HeapSizeOf for BlockDetails { } impl Decodable for BlockDetails { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { let details = BlockDetails { - number: d.val_at(0)?, - total_difficulty: d.val_at(1)?, - parent: d.val_at(2)?, - children: d.val_at(3)?, + number: rlp.val_at(0)?, + total_difficulty: rlp.val_at(1)?, + parent: rlp.val_at(2)?, + children: rlp.list_at(3)?, }; Ok(details) } @@ -190,11 +189,10 @@ impl HeapSizeOf for TransactionAddress { } impl Decodable for TransactionAddress { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { let tx_address = TransactionAddress { - block_hash: d.val_at(0)?, - index: d.val_at(1)?, + block_hash: rlp.val_at(0)?, + index: rlp.val_at(1)?, }; Ok(tx_address) @@ -224,9 +222,9 @@ impl BlockReceipts { } impl Decodable for BlockReceipts { - fn decode(decoder: &D) -> Result where D: Decoder { + fn decode(rlp: &UntrustedRlp) -> Result { Ok(BlockReceipts { - receipts: Decodable::decode(decoder)? + receipts: rlp.as_list()?, }) } } diff --git a/ethcore/src/blooms/bloom.rs b/ethcore/src/blooms/bloom.rs index a3584f739..cac9ff448 100644 --- a/ethcore/src/blooms/bloom.rs +++ b/ethcore/src/blooms/bloom.rs @@ -44,8 +44,8 @@ impl Into for Bloom { } impl Decodable for Bloom { - fn decode(decoder: &D) -> Result where D: Decoder { - Decodable::decode(decoder).map(Bloom) + fn decode(rlp: &UntrustedRlp) -> Result { + LogBloom::decode(rlp).map(Bloom) } } diff --git a/ethcore/src/blooms/bloom_group.rs b/ethcore/src/blooms/bloom_group.rs index 6d8c40f75..087f20b6f 100644 --- a/ethcore/src/blooms/bloom_group.rs +++ b/ethcore/src/blooms/bloom_group.rs @@ -52,8 +52,8 @@ impl Into for BloomGroup { } impl Decodable for BloomGroup { - fn decode(decoder: &D) -> Result where D: Decoder { - let blooms = Decodable::decode(decoder)?; + fn decode(rlp: &UntrustedRlp) -> Result { + let blooms = rlp.as_list()?; let group = BloomGroup { blooms: blooms }; diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index 06889a538..d284954e7 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -66,7 +66,7 @@ use evm::{Factory as EvmFactory, Schedule}; use miner::{Miner, MinerService, TransactionImportResult}; use snapshot::{self, io as snapshot_io}; use factory::Factories; -use rlp::{View, UntrustedRlp}; +use rlp::UntrustedRlp; use state_db::StateDB; use rand::OsRng; use client::registry::Registry; @@ -539,7 +539,7 @@ impl Client { )?; // Commit results - let receipts = ::rlp::decode(&receipts_bytes); + let receipts = ::rlp::decode_list(&receipts_bytes); let mut batch = DBTransaction::new(); chain.insert_unordered_block(&mut batch, &block_bytes, receipts, None, false, true); // Final commit to the DB diff --git a/ethcore/src/engines/authority_round.rs b/ethcore/src/engines/authority_round.rs index 03b5d785f..2a18c748d 100644 --- a/ethcore/src/engines/authority_round.rs +++ b/ethcore/src/engines/authority_round.rs @@ -21,7 +21,7 @@ use std::sync::Weak; use std::time::{UNIX_EPOCH, Duration}; use util::*; use ethkey::{verify_address, Signature}; -use rlp::{UntrustedRlp, View, encode}; +use rlp::{UntrustedRlp, encode}; use account_provider::AccountProvider; use block::*; use spec::CommonParams; diff --git a/ethcore/src/engines/basic_authority.rs b/ethcore/src/engines/basic_authority.rs index 34b89b2d6..d8a1df947 100644 --- a/ethcore/src/engines/basic_authority.rs +++ b/ethcore/src/engines/basic_authority.rs @@ -138,7 +138,7 @@ impl Engine for BasicAuthority { } fn verify_block_family(&self, header: &Header, parent: &Header, _block: Option<&[u8]>) -> result::Result<(), Error> { - use rlp::{UntrustedRlp, View}; + use rlp::UntrustedRlp; // Check if the signature belongs to a validator, can depend on parent state. let sig = UntrustedRlp::new(&header.seal()[0]).as_val::()?; let signer = public_to_address(&recover(&sig.into(), &header.bare_hash())?); diff --git a/ethcore/src/engines/tendermint/message.rs b/ethcore/src/engines/tendermint/message.rs index ead58ba98..0649ea050 100644 --- a/ethcore/src/engines/tendermint/message.rs +++ b/ethcore/src/engines/tendermint/message.rs @@ -20,7 +20,7 @@ use util::*; use super::{Height, View, BlockHash, Step}; use error::Error; use header::Header; -use rlp::{Rlp, UntrustedRlp, RlpStream, Encodable, Decodable, Decoder, DecoderError, View as RlpView}; +use rlp::{Rlp, UntrustedRlp, RlpStream, Encodable, Decodable, DecoderError}; use ethkey::{recover, public_to_address}; use super::super::vote_collector::Message; @@ -150,8 +150,8 @@ impl Step { } impl Decodable for Step { - fn decode(decoder: &D) -> Result where D: Decoder { - match decoder.as_rlp().as_val()? { + fn decode(rlp: &UntrustedRlp) -> Result { + match rlp.as_val()? { 0u8 => Ok(Step::Propose), 1 => Ok(Step::Prevote), 2 => Ok(Step::Precommit), @@ -168,8 +168,7 @@ impl Encodable for Step { /// (signature, (height, view, step, block_hash)) impl Decodable for ConsensusMessage { - fn decode(decoder: &D) -> Result where D: Decoder { - let rlp = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { let m = rlp.at(1)?; let block_message: H256 = m.val_at(3)?; Ok(ConsensusMessage { diff --git a/ethcore/src/engines/tendermint/mod.rs b/ethcore/src/engines/tendermint/mod.rs index 2d2714e97..46e67a2a8 100644 --- a/ethcore/src/engines/tendermint/mod.rs +++ b/ethcore/src/engines/tendermint/mod.rs @@ -33,7 +33,7 @@ use error::{Error, BlockError}; use header::Header; use builtin::Builtin; use env_info::EnvInfo; -use rlp::{UntrustedRlp, View as RlpView}; +use rlp::UntrustedRlp; use ethkey::{recover, public_to_address, Signature}; use account_provider::AccountProvider; use block::*; diff --git a/ethcore/src/ethereum/ethash.rs b/ethcore/src/ethereum/ethash.rs index fbb9c8a5c..b1907971c 100644 --- a/ethcore/src/ethereum/ethash.rs +++ b/ethcore/src/ethereum/ethash.rs @@ -27,7 +27,7 @@ use transaction::UnverifiedTransaction; use engines::Engine; use evm::Schedule; use ethjson; -use rlp::{self, UntrustedRlp, View}; +use rlp::{self, UntrustedRlp}; /// Parity tries to round block.gas_limit to multiple of this constant pub const PARITY_GAS_LIMIT_DETERMINANT: U256 = U256([37, 0, 0, 0]); diff --git a/ethcore/src/header.rs b/ethcore/src/header.rs index 60b9dcb46..4517c5764 100644 --- a/ethcore/src/header.rs +++ b/ethcore/src/header.rs @@ -261,9 +261,7 @@ impl Header { } impl Decodable for Header { - fn decode(decoder: &D) -> Result where D: Decoder { - let r = decoder.as_rlp(); - + fn decode(r: &UntrustedRlp) -> Result { let mut blockheader = Header { parent_hash: r.val_at(0)?, uncles_hash: r.val_at(1)?, @@ -283,7 +281,7 @@ impl Decodable for Header { bare_hash: RefCell::new(None), }; - for i in 13..r.item_count() { + for i in 13..r.item_count()? { blockheader.seal.push(r.at(i)?.as_raw().to_vec()) } diff --git a/ethcore/src/json_tests/transaction.rs b/ethcore/src/json_tests/transaction.rs index 5c8ac710a..f400180ee 100644 --- a/ethcore/src/json_tests/transaction.rs +++ b/ethcore/src/json_tests/transaction.rs @@ -17,7 +17,7 @@ use super::test_common::*; use evm; use ethjson; -use rlp::{UntrustedRlp, View}; +use rlp::UntrustedRlp; use transaction::{Action, UnverifiedTransaction}; use ethstore::ethkey::public_to_address; diff --git a/ethcore/src/migrations/blocks/v8.rs b/ethcore/src/migrations/blocks/v8.rs index 2c1d955e0..2514db702 100644 --- a/ethcore/src/migrations/blocks/v8.rs +++ b/ethcore/src/migrations/blocks/v8.rs @@ -17,7 +17,7 @@ //! This migration compresses the state db. use util::migration::{SimpleMigration, Progress}; -use rlp::{Compressible, UntrustedRlp, View, RlpType}; +use rlp::{Compressible, UntrustedRlp, RlpType}; /// Compressing migration. #[derive(Default)] diff --git a/ethcore/src/migrations/state/v7.rs b/ethcore/src/migrations/state/v7.rs index 9e2d3c110..e9da80c31 100644 --- a/ethcore/src/migrations/state/v7.rs +++ b/ethcore/src/migrations/state/v7.rs @@ -26,8 +26,7 @@ use util::migration::{Batch, Config, Error, Migration, SimpleMigration, Progress use util::sha3::Hashable; use std::sync::Arc; -use rlp::{decode, Rlp, RlpStream, View}; - +use rlp::{decode, Rlp, RlpStream}; // attempt to migrate a key, value pair. None if migration not possible. fn attempt_migrate(mut key_h: H256, val: &[u8]) -> Option { @@ -184,7 +183,7 @@ impl OverlayRecentV7 { } // migrate all deleted keys. - let mut deleted_keys: Vec = rlp.val_at(2); + let mut deleted_keys: Vec = rlp.list_at(2); for old_key in &mut deleted_keys { if let Some(new) = self.migrated_keys.get(&*old_key) { *old_key = new.clone(); diff --git a/ethcore/src/migrations/v9.rs b/ethcore/src/migrations/v9.rs index 7e469fb7b..9a6eb5088 100644 --- a/ethcore/src/migrations/v9.rs +++ b/ethcore/src/migrations/v9.rs @@ -17,7 +17,7 @@ //! This migration consolidates all databases into single one using Column Families. -use rlp::{Rlp, RlpStream, View}; +use rlp::{Rlp, RlpStream}; use util::kvdb::Database; use util::migration::{Batch, Config, Error, Migration, Progress}; use std::sync::Arc; diff --git a/ethcore/src/snapshot/account.rs b/ethcore/src/snapshot/account.rs index 62ee28f89..c086b5c44 100644 --- a/ethcore/src/snapshot/account.rs +++ b/ethcore/src/snapshot/account.rs @@ -22,7 +22,7 @@ use snapshot::Error; use util::{U256, H256, Bytes, HashDB, SHA3_EMPTY, SHA3_NULL_RLP}; use util::trie::{TrieDB, Trie}; -use rlp::{RlpStream, UntrustedRlp, View}; +use rlp::{RlpStream, UntrustedRlp}; use std::collections::HashSet; @@ -180,7 +180,7 @@ mod tests { use util::sha3::{SHA3_EMPTY, SHA3_NULL_RLP}; use util::{Address, H256, HashDB, DBValue}; - use rlp::{UntrustedRlp, View}; + use rlp::UntrustedRlp; use std::collections::HashSet; diff --git a/ethcore/src/snapshot/block.rs b/ethcore/src/snapshot/block.rs index 0eee05575..b5144b23d 100644 --- a/ethcore/src/snapshot/block.rs +++ b/ethcore/src/snapshot/block.rs @@ -20,7 +20,7 @@ use block::Block; use header::Header; use views::BlockView; -use rlp::{DecoderError, RlpStream, UntrustedRlp, View}; +use rlp::{DecoderError, RlpStream, UntrustedRlp}; use util::{Bytes, Hashable, H256}; use util::triehash::ordered_trie_root; @@ -101,8 +101,8 @@ impl AbridgedBlock { header.set_timestamp(rlp.val_at(6)?); header.set_extra_data(rlp.val_at(7)?); - let transactions = rlp.val_at(8)?; - let uncles: Vec
= rlp.val_at(9)?; + let transactions = rlp.list_at(8)?; + let uncles: Vec
= rlp.list_at(9)?; header.set_transactions_root(ordered_trie_root( rlp.at(8)?.iter().map(|r| r.as_raw().to_owned()) @@ -114,7 +114,7 @@ impl AbridgedBlock { header.set_uncles_hash(uncles_rlp.as_raw().sha3()); let mut seal_fields = Vec::new(); - for i in (HEADER_FIELDS + BLOCK_FIELDS)..rlp.item_count() { + for i in (HEADER_FIELDS + BLOCK_FIELDS)..rlp.item_count()? { let seal_rlp = rlp.at(i)?; seal_fields.push(seal_rlp.as_raw().to_owned()); } diff --git a/ethcore/src/snapshot/io.rs b/ethcore/src/snapshot/io.rs index 45f3ec4df..e8f11efd1 100644 --- a/ethcore/src/snapshot/io.rs +++ b/ethcore/src/snapshot/io.rs @@ -27,7 +27,7 @@ use std::path::{Path, PathBuf}; use util::Bytes; use util::hash::H256; -use rlp::{self, Encodable, RlpStream, UntrustedRlp, View}; +use rlp::{self, Encodable, RlpStream, UntrustedRlp}; use super::ManifestData; @@ -57,12 +57,10 @@ impl Encodable for ChunkInfo { } impl rlp::Decodable for ChunkInfo { - fn decode(decoder: &D) -> Result { - let d = decoder.as_rlp(); - - let hash = d.val_at(0)?; - let len = d.val_at(1)?; - let off = d.val_at(2)?; + fn decode(rlp: &UntrustedRlp) -> Result { + let hash = rlp.val_at(0)?; + let len = rlp.val_at(1)?; + let off = rlp.val_at(2)?; Ok(ChunkInfo(hash, len, off)) } } @@ -257,8 +255,8 @@ impl PackedReader { let rlp = UntrustedRlp::new(&manifest_buf); - let state: Vec = rlp.val_at(0)?; - let blocks: Vec = rlp.val_at(1)?; + let state: Vec = rlp.list_at(0)?; + let blocks: Vec = rlp.list_at(1)?; let manifest = ManifestData { state_hashes: state.iter().map(|c| c.0).collect(), diff --git a/ethcore/src/snapshot/mod.rs b/ethcore/src/snapshot/mod.rs index 473c91e4d..d496139ff 100644 --- a/ethcore/src/snapshot/mod.rs +++ b/ethcore/src/snapshot/mod.rs @@ -37,7 +37,7 @@ use util::journaldb::{self, Algorithm, JournalDB}; use util::kvdb::Database; use util::trie::{TrieDB, TrieDBMut, Trie, TrieMut}; use util::sha3::SHA3_NULL_RLP; -use rlp::{RlpStream, UntrustedRlp, View}; +use rlp::{RlpStream, UntrustedRlp}; use bloom_journal::Bloom; use self::block::AbridgedBlock; @@ -408,10 +408,10 @@ impl StateRebuilder { pub fn feed(&mut self, chunk: &[u8], flag: &AtomicBool) -> Result<(), ::error::Error> { let rlp = UntrustedRlp::new(chunk); let empty_rlp = StateAccount::new_basic(U256::zero(), U256::zero()).rlp(); - let mut pairs = Vec::with_capacity(rlp.item_count()); + let mut pairs = Vec::with_capacity(rlp.item_count()?); // initialize the pairs vector with empty values so we have slots to write into. - pairs.resize(rlp.item_count(), (H256::new(), Vec::new())); + pairs.resize(rlp.item_count()?, (H256::new(), Vec::new())); let status = rebuild_accounts( self.db.as_hashdb_mut(), @@ -601,7 +601,7 @@ impl BlockRebuilder { use util::triehash::ordered_trie_root; let rlp = UntrustedRlp::new(chunk); - let item_count = rlp.item_count(); + let item_count = rlp.item_count()?; let num_blocks = (item_count - 3) as u64; trace!(target: "snapshot", "restoring block chunk with {} blocks.", item_count - 3); @@ -621,7 +621,7 @@ impl BlockRebuilder { let pair = rlp.at(idx)?; let abridged_rlp = pair.at(0)?.as_raw().to_owned(); let abridged_block = AbridgedBlock::from_raw(abridged_rlp); - let receipts: Vec<::receipt::Receipt> = pair.val_at(1)?; + let receipts: Vec<::receipt::Receipt> = pair.list_at(1)?; let receipts_root = ordered_trie_root( pair.at(1)?.iter().map(|r| r.as_raw().to_owned()) ); diff --git a/ethcore/src/spec/spec.rs b/ethcore/src/spec/spec.rs index 76eefa3a6..21c07c9a3 100644 --- a/ethcore/src/spec/spec.rs +++ b/ethcore/src/spec/spec.rs @@ -34,7 +34,7 @@ use super::genesis::Genesis; use super::seal::Generic as GenericSeal; use ethereum; use ethjson; -use rlp::{Rlp, RlpStream, View}; +use rlp::{Rlp, RlpStream}; /// Parameters common to all engines. #[derive(Debug, PartialEq, Clone, Default)] diff --git a/ethcore/src/state/account.rs b/ethcore/src/state/account.rs index ebdf36d89..9e762979b 100644 --- a/ethcore/src/state/account.rs +++ b/ethcore/src/state/account.rs @@ -461,7 +461,7 @@ impl fmt::Debug for Account { #[cfg(test)] mod tests { - use rlp::{UntrustedRlp, RlpType, View, Compressible}; + use rlp::{UntrustedRlp, RlpType, Compressible}; use util::*; use super::*; use account_db::*; diff --git a/ethcore/src/tests/client.rs b/ethcore/src/tests/client.rs index 3734c5520..e61edd478 100644 --- a/ethcore/src/tests/client.rs +++ b/ethcore/src/tests/client.rs @@ -25,7 +25,6 @@ use types::filter::Filter; use util::*; use devtools::*; use miner::Miner; -use rlp::View; use spec::Spec; use views::BlockView; use ethkey::{KeyPair, Secret}; diff --git a/ethcore/src/trace/bloom.rs b/ethcore/src/trace/bloom.rs index e0a32d5ae..561a83719 100644 --- a/ethcore/src/trace/bloom.rs +++ b/ethcore/src/trace/bloom.rs @@ -60,8 +60,8 @@ impl Into for BlockTracesBloomGroup { } impl Decodable for BlockTracesBloom { - fn decode(decoder: &D) -> Result where D: Decoder { - Decodable::decode(decoder).map(BlockTracesBloom) + fn decode(rlp: &UntrustedRlp) -> Result { + LogBloom::decode(rlp).map(BlockTracesBloom) } } @@ -72,8 +72,8 @@ impl Encodable for BlockTracesBloom { } impl Decodable for BlockTracesBloomGroup { - fn decode(decoder: &D) -> Result where D: Decoder { - let blooms = Decodable::decode(decoder)?; + fn decode(rlp: &UntrustedRlp) -> Result { + let blooms = rlp.as_list()?; let group = BlockTracesBloomGroup { blooms: blooms }; diff --git a/ethcore/src/types/basic_account.rs b/ethcore/src/types/basic_account.rs index de091827f..c071040cf 100644 --- a/ethcore/src/types/basic_account.rs +++ b/ethcore/src/types/basic_account.rs @@ -43,8 +43,7 @@ impl Encodable for BasicAccount { } impl Decodable for BasicAccount { - fn decode(decoder: &D) -> Result where D: Decoder { - let rlp = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { Ok(BasicAccount { nonce: rlp.val_at(0)?, balance: rlp.val_at(1)?, diff --git a/ethcore/src/types/encoded.rs b/ethcore/src/types/encoded.rs index 49f83f0b7..0a4164044 100644 --- a/ethcore/src/types/encoded.rs +++ b/ethcore/src/types/encoded.rs @@ -29,7 +29,7 @@ use transaction::UnverifiedTransaction; use views; use util::{Address, Hashable, H256, H2048, U256, HeapSizeOf}; -use rlp::{Rlp, View}; +use rlp::Rlp; /// Owning header view. #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/ethcore/src/types/executed.rs b/ethcore/src/types/executed.rs index 4301044ce..f18bd1bee 100644 --- a/ethcore/src/types/executed.rs +++ b/ethcore/src/types/executed.rs @@ -51,8 +51,8 @@ impl Encodable for CallType { } impl Decodable for CallType { - fn decode(decoder: &D) -> Result where D: Decoder { - decoder.as_rlp().as_val().and_then(|v| Ok(match v { + fn decode(rlp: &UntrustedRlp) -> Result { + rlp.as_val().and_then(|v| Ok(match v { 0u32 => CallType::None, 1 => CallType::Call, 2 => CallType::CallCode, diff --git a/ethcore/src/types/log_entry.rs b/ethcore/src/types/log_entry.rs index 3eac1dad5..f3260c114 100644 --- a/ethcore/src/types/log_entry.rs +++ b/ethcore/src/types/log_entry.rs @@ -47,12 +47,11 @@ impl Encodable for LogEntry { } impl Decodable for LogEntry { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { let entry = LogEntry { - address: d.val_at(0)?, - topics: d.val_at(1)?, - data: d.val_at(2)?, + address: rlp.val_at(0)?, + topics: rlp.list_at(1)?, + data: rlp.val_at(2)?, }; Ok(entry) } diff --git a/ethcore/src/types/receipt.rs b/ethcore/src/types/receipt.rs index 5db74b0b6..fc082d40b 100644 --- a/ethcore/src/types/receipt.rs +++ b/ethcore/src/types/receipt.rs @@ -65,21 +65,20 @@ impl Encodable for Receipt { } impl Decodable for Receipt { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); - if d.item_count() == 3 { + fn decode(rlp: &UntrustedRlp) -> Result { + if rlp.item_count()? == 3 { Ok(Receipt { state_root: None, - gas_used: d.val_at(0)?, - log_bloom: d.val_at(1)?, - logs: d.val_at(2)?, + gas_used: rlp.val_at(0)?, + log_bloom: rlp.val_at(1)?, + logs: rlp.list_at(2)?, }) } else { Ok(Receipt { - state_root: Some(d.val_at(0)?), - gas_used: d.val_at(1)?, - log_bloom: d.val_at(2)?, - logs: d.val_at(3)?, + state_root: Some(rlp.val_at(0)?), + gas_used: rlp.val_at(1)?, + log_bloom: rlp.val_at(2)?, + logs: rlp.list_at(3)?, }) } } diff --git a/ethcore/src/types/snapshot_manifest.rs b/ethcore/src/types/snapshot_manifest.rs index 910a038bd..84ca05822 100644 --- a/ethcore/src/types/snapshot_manifest.rs +++ b/ethcore/src/types/snapshot_manifest.rs @@ -53,8 +53,8 @@ impl ManifestData { pub fn from_rlp(raw: &[u8]) -> Result { let decoder = UntrustedRlp::new(raw); - let state_hashes: Vec = decoder.val_at(0)?; - let block_hashes: Vec = decoder.val_at(1)?; + let state_hashes: Vec = decoder.list_at(0)?; + let block_hashes: Vec = decoder.list_at(1)?; let state_root: H256 = decoder.val_at(2)?; let block_number: u64 = decoder.val_at(3)?; let block_hash: H256 = decoder.val_at(4)?; diff --git a/ethcore/src/types/trace_types/error.rs b/ethcore/src/types/trace_types/error.rs index 33ccf2bb7..58657d7aa 100644 --- a/ethcore/src/types/trace_types/error.rs +++ b/ethcore/src/types/trace_types/error.rs @@ -17,7 +17,7 @@ //! Trace errors. use std::fmt; -use rlp::{Encodable, RlpStream, Decodable, Decoder, DecoderError, View}; +use rlp::{Encodable, RlpStream, Decodable, DecoderError, UntrustedRlp}; use evm::Error as EvmError; /// Trace evm errors. @@ -91,9 +91,9 @@ impl Encodable for Error { } impl Decodable for Error { - fn decode(decoder: &D) -> Result where D: Decoder { + fn decode(rlp: &UntrustedRlp) -> Result { use self::Error::*; - let value: u8 = decoder.as_rlp().as_val()?; + let value: u8 = rlp.as_val()?; match value { 0 => Ok(OutOfGas), 1 => Ok(BadJumpDestination), diff --git a/ethcore/src/types/trace_types/flat.rs b/ethcore/src/types/trace_types/flat.rs index 832e7d055..90b770beb 100644 --- a/ethcore/src/types/trace_types/flat.rs +++ b/ethcore/src/types/trace_types/flat.rs @@ -64,9 +64,8 @@ impl Encodable for FlatTrace { } impl Decodable for FlatTrace { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); - let v: Vec = d.val_at(3)?; + fn decode(d: &UntrustedRlp) -> Result { + let v: Vec = d.list_at(3)?; let res = FlatTrace { action: d.val_at(0)?, result: d.val_at(1)?, @@ -108,8 +107,8 @@ impl Encodable for FlatTransactionTraces { } impl Decodable for FlatTransactionTraces { - fn decode(decoder: &D) -> Result where D: Decoder { - Ok(FlatTransactionTraces(Decodable::decode(decoder)?)) + fn decode(rlp: &UntrustedRlp) -> Result { + Ok(FlatTransactionTraces(rlp.as_list()?)) } } @@ -149,8 +148,8 @@ impl Encodable for FlatBlockTraces { } impl Decodable for FlatBlockTraces { - fn decode(decoder: &D) -> Result where D: Decoder { - Ok(FlatBlockTraces(Decodable::decode(decoder)?)) + fn decode(rlp: &UntrustedRlp) -> Result { + Ok(FlatBlockTraces(rlp.as_list()?)) } } diff --git a/ethcore/src/types/trace_types/trace.rs b/ethcore/src/types/trace_types/trace.rs index 9c3377dac..ed5dfb9f1 100644 --- a/ethcore/src/types/trace_types/trace.rs +++ b/ethcore/src/types/trace_types/trace.rs @@ -45,11 +45,10 @@ impl Encodable for CallResult { } impl Decodable for CallResult { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { let res = CallResult { - gas_used: d.val_at(0)?, - output: d.val_at(1)?, + gas_used: rlp.val_at(0)?, + output: rlp.val_at(1)?, }; Ok(res) @@ -78,12 +77,11 @@ impl Encodable for CreateResult { } impl Decodable for CreateResult { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { let res = CreateResult { - gas_used: d.val_at(0)?, - code: d.val_at(1)?, - address: d.val_at(2)?, + gas_used: rlp.val_at(0)?, + code: rlp.val_at(1)?, + address: rlp.val_at(2)?, }; Ok(res) @@ -141,15 +139,14 @@ impl Encodable for Call { } impl Decodable for Call { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { let res = Call { - from: d.val_at(0)?, - to: d.val_at(1)?, - value: d.val_at(2)?, - gas: d.val_at(3)?, - input: d.val_at(4)?, - call_type: d.val_at(5)?, + from: rlp.val_at(0)?, + to: rlp.val_at(1)?, + value: rlp.val_at(2)?, + gas: rlp.val_at(3)?, + input: rlp.val_at(4)?, + call_type: rlp.val_at(5)?, }; Ok(res) @@ -201,13 +198,12 @@ impl Encodable for Create { } impl Decodable for Create { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { let res = Create { - from: d.val_at(0)?, - value: d.val_at(1)?, - gas: d.val_at(2)?, - init: d.val_at(3)?, + from: rlp.val_at(0)?, + value: rlp.val_at(1)?, + gas: rlp.val_at(2)?, + init: rlp.val_at(3)?, }; Ok(res) @@ -252,12 +248,11 @@ impl Encodable for Suicide { } impl Decodable for Suicide { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { let res = Suicide { - address: d.val_at(0)?, - refund_address: d.val_at(1)?, - balance: d.val_at(2)?, + address: rlp.val_at(0)?, + refund_address: rlp.val_at(1)?, + balance: rlp.val_at(2)?, }; Ok(res) @@ -298,13 +293,12 @@ impl Encodable for Action { } impl Decodable for Action { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); - let action_type: u8 = d.val_at(0)?; + fn decode(rlp: &UntrustedRlp) -> Result { + let action_type: u8 = rlp.val_at(0)?; match action_type { - 0 => d.val_at(1).map(Action::Call), - 1 => d.val_at(1).map(Action::Create), - 2 => d.val_at(1).map(Action::Suicide), + 0 => rlp.val_at(1).map(Action::Call), + 1 => rlp.val_at(1).map(Action::Create), + 2 => rlp.val_at(1).map(Action::Suicide), _ => Err(DecoderError::Custom("Invalid action type.")), } } @@ -369,14 +363,13 @@ impl Encodable for Res { } impl Decodable for Res { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); - let action_type: u8 = d.val_at(0)?; + fn decode(rlp: &UntrustedRlp) -> Result { + let action_type: u8 = rlp.val_at(0)?; match action_type { - 0 => d.val_at(1).map(Res::Call), - 1 => d.val_at(1).map(Res::Create), - 2 => d.val_at(1).map(Res::FailedCall), - 3 => d.val_at(1).map(Res::FailedCreate), + 0 => rlp.val_at(1).map(Res::Call), + 1 => rlp.val_at(1).map(Res::Create), + 2 => rlp.val_at(1).map(Res::FailedCall), + 3 => rlp.val_at(1).map(Res::FailedCreate), 4 => Ok(Res::None), _ => Err(DecoderError::Custom("Invalid result type.")), } @@ -420,11 +413,10 @@ impl Encodable for MemoryDiff { } impl Decodable for MemoryDiff { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { Ok(MemoryDiff { - offset: d.val_at(0)?, - data: d.val_at(1)?, + offset: rlp.val_at(0)?, + data: rlp.val_at(1)?, }) } } @@ -448,11 +440,10 @@ impl Encodable for StorageDiff { } impl Decodable for StorageDiff { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { Ok(StorageDiff { - location: d.val_at(0)?, - value: d.val_at(1)?, + location: rlp.val_at(0)?, + value: rlp.val_at(1)?, }) } } @@ -482,13 +473,12 @@ impl Encodable for VMExecutedOperation { } impl Decodable for VMExecutedOperation { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { Ok(VMExecutedOperation { - gas_used: d.val_at(0)?, - stack_push: d.val_at(1)?, - mem_diff: d.val_at(2)?, - store_diff: d.val_at(3)?, + gas_used: rlp.val_at(0)?, + stack_push: rlp.list_at(1)?, + mem_diff: rlp.val_at(2)?, + store_diff: rlp.val_at(3)?, }) } } @@ -518,13 +508,12 @@ impl Encodable for VMOperation { } impl Decodable for VMOperation { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { let res = VMOperation { - pc: d.val_at(0)?, - instruction: d.val_at(1)?, - gas_cost: d.val_at(2)?, - executed: d.val_at(3)?, + pc: rlp.val_at(0)?, + instruction: rlp.val_at(1)?, + gas_cost: rlp.val_at(2)?, + executed: rlp.val_at(3)?, }; Ok(res) @@ -557,13 +546,12 @@ impl Encodable for VMTrace { } impl Decodable for VMTrace { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { let res = VMTrace { - parent_step: d.val_at(0)?, - code: d.val_at(1)?, - operations: d.val_at(2)?, - subs: d.val_at(3)?, + parent_step: rlp.val_at(0)?, + code: rlp.val_at(1)?, + operations: rlp.list_at(2)?, + subs: rlp.list_at(3)?, }; Ok(res) diff --git a/ethcore/src/types/transaction.rs b/ethcore/src/types/transaction.rs index 506bf001e..79e27d97d 100644 --- a/ethcore/src/types/transaction.rs +++ b/ethcore/src/types/transaction.rs @@ -42,8 +42,7 @@ impl Default for Action { } impl Decodable for Action { - fn decode(decoder: &D) -> Result where D: Decoder { - let rlp = decoder.as_rlp(); + fn decode(rlp: &UntrustedRlp) -> Result { if rlp.is_empty() { Ok(Action::Create) } else { @@ -243,12 +242,11 @@ impl Deref for UnverifiedTransaction { } impl Decodable for UnverifiedTransaction { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); - if d.item_count() != 9 { + fn decode(d: &UntrustedRlp) -> Result { + if d.item_count()? != 9 { return Err(DecoderError::RlpIncorrectListLen); } - let hash = decoder.as_raw().sha3(); + let hash = d.as_raw().sha3(); Ok(UnverifiedTransaction { unsigned: Transaction { nonce: d.val_at(0)?, diff --git a/ethcore/src/verification/verification.rs b/ethcore/src/verification/verification.rs index 7fbeb29bb..ab21ef6c2 100644 --- a/ethcore/src/verification/verification.rs +++ b/ethcore/src/verification/verification.rs @@ -26,7 +26,7 @@ use engines::Engine; use error::{BlockError, Error}; use blockchain::*; use header::{BlockNumber, Header}; -use rlp::{UntrustedRlp, View}; +use rlp::UntrustedRlp; use transaction::SignedTransaction; use views::BlockView; use time::get_time; @@ -101,7 +101,7 @@ pub fn verify_block_family(header: &Header, bytes: &[u8], engine: &Engine, bc: & verify_parent(&header, &parent)?; engine.verify_block_family(&header, &parent, Some(bytes))?; - let num_uncles = UntrustedRlp::new(bytes).at(2)?.item_count(); + let num_uncles = UntrustedRlp::new(bytes).at(2)?.item_count()?; if num_uncles != 0 { if num_uncles > engine.maximum_uncle_count() { return Err(From::from(BlockError::TooManyUncles(OutOfBounds { min: None, max: Some(engine.maximum_uncle_count()), found: num_uncles }))); @@ -264,7 +264,6 @@ mod tests { use transaction::*; use tests::helpers::*; use types::log_entry::{LogEntry, LocalizedLogEntry}; - use rlp::View; use time::get_time; use encoded; diff --git a/ethcore/src/views/block.rs b/ethcore/src/views/block.rs index a03151d40..463eb7240 100644 --- a/ethcore/src/views/block.rs +++ b/ethcore/src/views/block.rs @@ -20,7 +20,7 @@ use util::*; use header::*; use transaction::*; use super::{TransactionView, HeaderView}; -use rlp::{Rlp, View}; +use rlp::Rlp; /// View onto block rlp. pub struct BlockView<'a> { @@ -69,7 +69,7 @@ impl<'a> BlockView<'a> { /// Return List of transactions in given block. pub fn transactions(&self) -> Vec { - self.rlp.val_at(1) + self.rlp.list_at(1) } /// Return List of transactions with additional localization info. @@ -125,7 +125,7 @@ impl<'a> BlockView<'a> { /// Return list of uncles of given block. pub fn uncles(&self) -> Vec
{ - self.rlp.val_at(2) + self.rlp.list_at(2) } /// Return number of uncles in given block, without deserializing them. diff --git a/ethcore/src/views/body.rs b/ethcore/src/views/body.rs index f3ae0da37..c32796628 100644 --- a/ethcore/src/views/body.rs +++ b/ethcore/src/views/body.rs @@ -20,7 +20,7 @@ use util::*; use header::*; use transaction::*; use super::{TransactionView, HeaderView}; -use rlp::{Rlp, View}; +use rlp::Rlp; /// View onto block rlp. pub struct BodyView<'a> { @@ -49,7 +49,7 @@ impl<'a> BodyView<'a> { /// Return List of transactions in given block. pub fn transactions(&self) -> Vec { - self.rlp.val_at(0) + self.rlp.list_at(0) } /// Return List of transactions with additional localization info. @@ -99,7 +99,7 @@ impl<'a> BodyView<'a> { /// Return list of uncles of given block. pub fn uncles(&self) -> Vec
{ - self.rlp.val_at(1) + self.rlp.list_at(1) } /// Return number of uncles in given block, without deserializing them. diff --git a/ethcore/src/views/header.rs b/ethcore/src/views/header.rs index 9fa07ccc8..618728525 100644 --- a/ethcore/src/views/header.rs +++ b/ethcore/src/views/header.rs @@ -17,7 +17,7 @@ //! View onto block header rlp use util::{U256, Bytes, Hashable, H256, Address, H2048}; -use rlp::{Rlp, View}; +use rlp::Rlp; use header::BlockNumber; /// View onto block header rlp. diff --git a/ethcore/src/views/transaction.rs b/ethcore/src/views/transaction.rs index 72f4e808d..0b5b2e1ff 100644 --- a/ethcore/src/views/transaction.rs +++ b/ethcore/src/views/transaction.rs @@ -16,7 +16,7 @@ //! View onto transaction rlp use util::{U256, Bytes, Hashable, H256}; -use rlp::{Rlp, View}; +use rlp::Rlp; /// View onto transaction rlp. pub struct TransactionView<'a> { diff --git a/local-store/src/lib.rs b/local-store/src/lib.rs index f9e5fe385..d21ca031d 100644 --- a/local-store/src/lib.rs +++ b/local-store/src/lib.rs @@ -25,7 +25,7 @@ use ethcore::transaction::{ }; use ethcore::service::ClientIoMessage; use io::IoHandler; -use rlp::{UntrustedRlp, View}; +use rlp::UntrustedRlp; use util::kvdb::KeyValueDB; extern crate ethcore; diff --git a/parity/informant.rs b/parity/informant.rs index 2fa95db9a..4145b0282 100644 --- a/parity/informant.rs +++ b/parity/informant.rs @@ -32,7 +32,6 @@ use ethcore::snapshot::{RestorationStatus, SnapshotService as SS}; use number_prefix::{binary_prefix, Standalone, Prefixed}; use ethcore_rpc::{is_major_importing}; use ethcore_rpc::informant::RpcStats; -use rlp::View; pub struct Informant { report: RwLock>, diff --git a/rpc/src/v1/impls/eth.rs b/rpc/src/v1/impls/eth.rs index 52bc2de71..811d5aa90 100644 --- a/rpc/src/v1/impls/eth.rs +++ b/rpc/src/v1/impls/eth.rs @@ -21,7 +21,7 @@ use std::time::{Instant, Duration}; use std::sync::{Arc, Weak}; use futures::{self, future, BoxFuture, Future}; -use rlp::{self, UntrustedRlp, View}; +use rlp::{self, UntrustedRlp}; use time::get_time; use util::{H160, H256, Address, U256, H64}; use util::sha3::Hashable; diff --git a/rpc/src/v1/impls/light/eth.rs b/rpc/src/v1/impls/light/eth.rs index 1c3d8fffd..c6f0d709d 100644 --- a/rpc/src/v1/impls/light/eth.rs +++ b/rpc/src/v1/impls/light/eth.rs @@ -36,7 +36,7 @@ use ethcore::executed::{Executed, ExecutionError}; use ethcore::ids::BlockId; use ethcore::transaction::{Action, SignedTransaction, Transaction as EthTransaction}; use ethsync::LightSync; -use rlp::{UntrustedRlp, View}; +use rlp::UntrustedRlp; use util::sha3::{SHA3_NULL_RLP, SHA3_EMPTY_LIST_RLP}; use util::{RwLock, Mutex, Uint, U256}; diff --git a/rpc/src/v1/impls/signer.rs b/rpc/src/v1/impls/signer.rs index ffd9f4108..f418a6760 100644 --- a/rpc/src/v1/impls/signer.rs +++ b/rpc/src/v1/impls/signer.rs @@ -18,7 +18,7 @@ use std::sync::{Arc, Weak}; -use rlp::{UntrustedRlp, View}; +use rlp::UntrustedRlp; use ethcore::account_provider::AccountProvider; use ethcore::transaction::{SignedTransaction, PendingTransaction}; use futures::{future, BoxFuture, Future, IntoFuture}; diff --git a/rpc/src/v1/impls/traces.rs b/rpc/src/v1/impls/traces.rs index b4be40a56..466dbb88c 100644 --- a/rpc/src/v1/impls/traces.rs +++ b/rpc/src/v1/impls/traces.rs @@ -18,7 +18,7 @@ use std::sync::{Weak, Arc}; -use rlp::{UntrustedRlp, View}; +use rlp::UntrustedRlp; use ethcore::client::{MiningBlockChainClient, CallAnalytics, TransactionId, TraceId}; use ethcore::miner::MinerService; use ethcore::transaction::SignedTransaction; diff --git a/rpc/src/v1/tests/mocked/eth.rs b/rpc/src/v1/tests/mocked/eth.rs index ee27c27ba..dfd64d38d 100644 --- a/rpc/src/v1/tests/mocked/eth.rs +++ b/rpc/src/v1/tests/mocked/eth.rs @@ -940,7 +940,7 @@ fn rpc_eth_send_raw_transaction_error() { ], "id": 1 }"#; - let res = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid RLP.","data":"RlpIncorrectListLen"},"id":1}"#.into(); + let res = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid RLP.","data":"RlpExpectedToBeList"},"id":1}"#.into(); assert_eq!(tester.io.handle_request_sync(&req), Some(res)); } diff --git a/sync/src/block_sync.rs b/sync/src/block_sync.rs index 50df6a0c0..e7192d525 100644 --- a/sync/src/block_sync.rs +++ b/sync/src/block_sync.rs @@ -214,7 +214,7 @@ impl BlockDownloader { /// Add new block headers. pub fn import_headers(&mut self, io: &mut SyncIo, r: &UntrustedRlp, expected_hash: Option) -> Result { - let item_count = r.item_count(); + let item_count = r.item_count().unwrap_or(0); if self.state == State::Idle { trace!(target: "sync", "Ignored unexpected block headers"); return Ok(DownloadAction::None) @@ -314,7 +314,7 @@ impl BlockDownloader { /// Called by peer once it has new block bodies pub fn import_bodies(&mut self, _io: &mut SyncIo, r: &UntrustedRlp) -> Result<(), BlockDownloaderImportError> { - let item_count = r.item_count(); + let item_count = r.item_count().unwrap_or(0); if item_count == 0 { return Err(BlockDownloaderImportError::Useless); } @@ -340,7 +340,7 @@ impl BlockDownloader { /// Called by peer once it has new block bodies pub fn import_receipts(&mut self, _io: &mut SyncIo, r: &UntrustedRlp) -> Result<(), BlockDownloaderImportError> { - let item_count = r.item_count(); + let item_count = r.item_count().unwrap_or(0); if item_count == 0 { return Err(BlockDownloaderImportError::Useless); } diff --git a/sync/src/chain.rs b/sync/src/chain.rs index 415b44a39..47ddf6ab1 100644 --- a/sync/src/chain.rs +++ b/sync/src/chain.rs @@ -659,7 +659,7 @@ impl ChainSync { let confirmed = match self.peers.get_mut(&peer_id) { Some(ref mut peer) if peer.asking == PeerAsking::ForkHeader => { peer.asking = PeerAsking::Nothing; - let item_count = r.item_count(); + let item_count = r.item_count()?; let (fork_number, fork_hash) = self.fork_block.expect("ForkHeader request is sent only fork block is Some; qed").clone(); if item_count == 0 || item_count != 1 { trace!(target: "sync", "{}: Chain is too short to confirm the block", peer_id); @@ -696,7 +696,7 @@ impl ChainSync { self.continue_sync(io); return Ok(()); } - let item_count = r.item_count(); + let item_count = r.item_count()?; trace!(target: "sync", "{} -> BlockHeaders ({} entries), state = {:?}, set = {:?}", peer_id, item_count, self.state, block_set); if (self.state == SyncState::Idle || self.state == SyncState::WaitingPeers) && self.old_blocks.is_none() { trace!(target: "sync", "Ignored unexpected block headers"); @@ -764,7 +764,7 @@ impl ChainSync { self.continue_sync(io); return Ok(()); } - let item_count = r.item_count(); + let item_count = r.item_count()?; trace!(target: "sync", "{} -> BlockBodies ({} entries), set = {:?}", peer_id, item_count, block_set); if item_count == 0 { self.deactivate_peer(io, peer_id); @@ -818,7 +818,7 @@ impl ChainSync { self.continue_sync(io); return Ok(()); } - let item_count = r.item_count(); + let item_count = r.item_count()?; trace!(target: "sync", "{} -> BlockReceipts ({} entries)", peer_id, item_count); if item_count == 0 { self.deactivate_peer(io, peer_id); @@ -954,7 +954,7 @@ impl ChainSync { self.continue_sync(io); return Ok(()); } - trace!(target: "sync", "{} -> NewHashes ({} entries)", peer_id, r.item_count()); + trace!(target: "sync", "{} -> NewHashes ({} entries)", peer_id, r.item_count()?); let mut max_height: BlockNumber = 0; let mut new_hashes = Vec::new(); let last_imported_number = self.new_blocks.last_imported_block_number(); @@ -1439,7 +1439,7 @@ impl ChainSync { trace!(target: "sync", "{} Ignoring transactions from unconfirmed/unknown peer", peer_id); } - let mut item_count = r.item_count(); + let mut item_count = r.item_count()?; trace!(target: "sync", "{:02} -> Transactions ({} entries)", peer_id, item_count); item_count = min(item_count, MAX_TX_TO_IMPORT); let mut transactions = Vec::with_capacity(item_count); @@ -1557,7 +1557,7 @@ impl ChainSync { /// Respond to GetBlockBodies request fn return_block_bodies(io: &SyncIo, r: &UntrustedRlp, peer_id: PeerId) -> RlpResponseResult { - let mut count = r.item_count(); + let mut count = r.item_count().unwrap_or(0); if count == 0 { debug!(target: "sync", "Empty GetBlockBodies request, ignoring."); return Ok(None); @@ -1579,7 +1579,7 @@ impl ChainSync { /// Respond to GetNodeData request fn return_node_data(io: &SyncIo, r: &UntrustedRlp, peer_id: PeerId) -> RlpResponseResult { - let mut count = r.item_count(); + let mut count = r.item_count().unwrap_or(0); trace!(target: "sync", "{} -> GetNodeData: {} entries", peer_id, count); if count == 0 { debug!(target: "sync", "Empty GetNodeData request, ignoring."); @@ -1603,7 +1603,7 @@ impl ChainSync { } fn return_receipts(io: &SyncIo, rlp: &UntrustedRlp, peer_id: PeerId) -> RlpResponseResult { - let mut count = rlp.item_count(); + let mut count = rlp.item_count().unwrap_or(0); trace!(target: "sync", "{} -> GetReceipts: {} entries", peer_id, count); if count == 0 { debug!(target: "sync", "Empty GetReceipts request, ignoring."); @@ -1628,7 +1628,7 @@ impl ChainSync { /// Respond to GetSnapshotManifest request fn return_snapshot_manifest(io: &SyncIo, r: &UntrustedRlp, peer_id: PeerId) -> RlpResponseResult { - let count = r.item_count(); + let count = r.item_count().unwrap_or(0); trace!(target: "sync", "{} -> GetSnapshotManifest", peer_id); if count != 0 { debug!(target: "sync", "Invalid GetSnapshotManifest request, ignoring."); @@ -2177,7 +2177,7 @@ mod tests { use util::sha3::Hashable; use util::hash::H256; use util::bytes::Bytes; - use rlp::{Rlp, RlpStream, UntrustedRlp, View}; + use rlp::{Rlp, RlpStream, UntrustedRlp}; use super::*; use ::SyncConfig; use super::{PeerInfo, PeerAsking}; @@ -2746,7 +2746,7 @@ mod tests { } let rlp = UntrustedRlp::new(&*p.data); - let item_count = rlp.item_count(); + let item_count = rlp.item_count().unwrap_or(0); if item_count != 1 { return None; } diff --git a/sync/src/light_sync/response.rs b/sync/src/light_sync/response.rs index cb95824ce..0629da956 100644 --- a/sync/src/light_sync/response.rs +++ b/sync/src/light_sync/response.rs @@ -20,7 +20,7 @@ use std::fmt; use ethcore::header::Header; use light::request::{HashOrNumber, Headers as HeadersRequest}; -use rlp::{DecoderError, UntrustedRlp, View}; +use rlp::{DecoderError, UntrustedRlp}; use util::{Bytes, H256}; /// Errors found when decoding headers and verifying with basic constraints. diff --git a/util/network/src/discovery.rs b/util/network/src/discovery.rs index ae4c7e565..ad995188d 100644 --- a/util/network/src/discovery.rs +++ b/util/network/src/discovery.rs @@ -481,7 +481,7 @@ impl Discovery { fn on_neighbours(&mut self, rlp: &UntrustedRlp, _node: &NodeId, from: &SocketAddr) -> Result, NetworkError> { // TODO: validate packet let mut added = HashMap::new(); - trace!(target: "discovery", "Got {} Neighbours from {:?}", rlp.at(0)?.item_count(), &from); + trace!(target: "discovery", "Got {} Neighbours from {:?}", rlp.at(0)?.item_count()?, &from); for r in rlp.at(0)?.iter() { let endpoint = NodeEndpoint::from_rlp(&r)?; if !endpoint.is_valid() { diff --git a/util/network/src/session.rs b/util/network/src/session.rs index bc416b8d8..59eac6e5d 100644 --- a/util/network/src/session.rs +++ b/util/network/src/session.rs @@ -116,9 +116,8 @@ pub struct PeerCapabilityInfo { } impl Decodable for PeerCapabilityInfo { - fn decode(decoder: &D) -> Result where D: Decoder { - let c = decoder.as_rlp(); - let p: Vec = c.val_at(0)?; + fn decode(rlp: &UntrustedRlp) -> Result { + let p: Vec = rlp.val_at(0)?; if p.len() != 3 { return Err(DecoderError::Custom("Invalid subprotocol string length. Should be 3")); } @@ -126,7 +125,7 @@ impl Decodable for PeerCapabilityInfo { p2.clone_from_slice(&p); Ok(PeerCapabilityInfo { protocol: p2, - version: c.val_at(1)? + version: rlp.val_at(1)? }) } } @@ -473,7 +472,7 @@ impl Session { where Message: Send + Sync + Clone { let protocol = rlp.val_at::(0)?; let client_version = rlp.val_at::(1)?; - let peer_caps = rlp.val_at::>(2)?; + let peer_caps: Vec = rlp.list_at(2)?; let id = rlp.val_at::(4)?; // Intersect with host capabilities diff --git a/util/benches/rlp.rs b/util/rlp/benches/rlp.rs similarity index 85% rename from util/benches/rlp.rs rename to util/rlp/benches/rlp.rs index d5aac0d22..3f8166ec4 100644 --- a/util/benches/rlp.rs +++ b/util/rlp/benches/rlp.rs @@ -23,13 +23,12 @@ #![feature(test)] extern crate test; +extern crate ethcore_bigint as bigint; extern crate rlp; -extern crate ethcore_util as util; use test::Bencher; -use std::str::FromStr; -use rlp::*; -use util::U256; +use bigint::prelude::U256; +use rlp::{RlpStream, Rlp}; #[bench] fn bench_stream_u64_value(b: &mut Bencher) { @@ -56,9 +55,8 @@ fn bench_stream_u256_value(b: &mut Bencher) { b.iter(|| { // u256 let mut stream = RlpStream::new(); - stream.append(&U256::from_str("8090a0b0c0d0e0f009102030405060770000000000000001000000000\ - 00012f0") - .unwrap()); + let uint: U256 = "8090a0b0c0d0e0f00910203040506077000000000000000100000000000012f0".into(); + stream.append(&uint); let _ = stream.out(); }); } @@ -93,11 +91,11 @@ fn bench_decode_nested_empty_lists(b: &mut Bencher) { // [ [], [[]], [ [], [[]] ] ] let data = vec![0xc7, 0xc0, 0xc1, 0xc0, 0xc3, 0xc0, 0xc1, 0xc0]; let rlp = Rlp::new(&data); - let _v0: Vec = rlp.val_at(0); - let _v1: Vec> = rlp.val_at(1); + let _v0: Vec = rlp.at(0).as_list(); + let _v1: Vec = rlp.at(1).at(0).as_list(); let nested_rlp = rlp.at(2); - let _v2a: Vec = nested_rlp.val_at(0); - let _v2b: Vec> = nested_rlp.val_at(1); + let _v2a: Vec = nested_rlp.at(0).as_list(); + let _v2b: Vec = nested_rlp.at(1).at(0).as_list(); }); } diff --git a/util/rlp/src/bytes.rs b/util/rlp/src/bytes.rs deleted file mode 100644 index e5f266f92..000000000 --- a/util/rlp/src/bytes.rs +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2015-2017 Parity Technologies (UK) Ltd. -// This file is part of Parity. - -// Parity 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. - -// Parity 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 Parity. If not, see . - -//! Unified interfaces for RLP bytes operations on basic types -//! - -use std::{mem, fmt, cmp}; -use std::error::Error as StdError; -use bigint::prelude::{U128, U256, H64, H128, H160, H256, H512, H520, H2048}; - -/// Error returned when `FromBytes` conversation goes wrong -#[derive(Debug, PartialEq, Eq)] -pub enum FromBytesError { - /// Expected more RLP data - DataIsTooShort, - /// Extra bytes after the end of the last item - DataIsTooLong, - /// Integer-representation is non-canonically prefixed with zero byte(s). - ZeroPrefixedInt, - /// String representation is not utf-8 - InvalidUtf8, -} - -impl StdError for FromBytesError { - fn description(&self) -> &str { "from_bytes error" } -} - -impl fmt::Display for FromBytesError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Debug::fmt(&self, f) - } -} - -/// Alias for the result of `FromBytes` trait -pub type FromBytesResult = Result; - -/// Converts to given type from its bytes representation -/// -/// TODO: check size of bytes before conversation and return appropriate error -pub trait FromBytes: Sized { - /// Create a value from bytes - fn from_bytes(bytes: &[u8]) -> FromBytesResult; -} - -impl FromBytes for String { - fn from_bytes(bytes: &[u8]) -> FromBytesResult { - ::std::str::from_utf8(bytes).map(|s| s.to_owned()).map_err(|_| FromBytesError::InvalidUtf8) - } -} - -macro_rules! impl_uint_from_bytes { - ($to: ident) => { - impl FromBytes for $to { - fn from_bytes(bytes: &[u8]) -> FromBytesResult<$to> { - match bytes.len() { - 0 => Ok(0), - l if l <= mem::size_of::<$to>() => { - if bytes[0] == 0 { - return Err(FromBytesError::ZeroPrefixedInt) - } - let mut res = 0 as $to; - for i in 0..l { - let shift = (l - 1 - i) * 8; - res = res + ((bytes[i] as $to) << shift); - } - Ok(res) - } - _ => Err(FromBytesError::DataIsTooLong) - } - } - } - } -} - -impl FromBytes for bool { - fn from_bytes(bytes: &[u8]) -> FromBytesResult { - match bytes.len() { - 0 => Ok(false), - 1 => Ok(bytes[0] != 0), - _ => Err(FromBytesError::DataIsTooLong), - } - } -} - -//impl_uint_from_bytes!(u8); -impl_uint_from_bytes!(u16); -impl_uint_from_bytes!(u32); -impl_uint_from_bytes!(u64); -impl_uint_from_bytes!(usize); - -macro_rules! impl_uint_from_bytes { - ($name: ident, $size: expr) => { - impl FromBytes for $name { - fn from_bytes(bytes: &[u8]) -> FromBytesResult<$name> { - if !bytes.is_empty() && bytes[0] == 0 { - Err(FromBytesError::ZeroPrefixedInt) - } else if bytes.len() <= $size { - Ok($name::from(bytes)) - } else { - Err(FromBytesError::DataIsTooLong) - } - } - } - } -} - -impl_uint_from_bytes!(U256, 32); -impl_uint_from_bytes!(U128, 16); - -macro_rules! impl_hash_from_bytes { - ($name: ident, $size: expr) => { - impl FromBytes for $name { - fn from_bytes(bytes: &[u8]) -> FromBytesResult<$name> { - match bytes.len().cmp(&$size) { - cmp::Ordering::Less => Err(FromBytesError::DataIsTooShort), - cmp::Ordering::Greater => Err(FromBytesError::DataIsTooLong), - cmp::Ordering::Equal => { - let mut t = [0u8; $size]; - t.copy_from_slice(bytes); - Ok($name(t)) - } - } - } - } - } -} - -impl_hash_from_bytes!(H64, 8); -impl_hash_from_bytes!(H128, 16); -impl_hash_from_bytes!(H160, 20); -impl_hash_from_bytes!(H256, 32); -impl_hash_from_bytes!(H512, 64); -impl_hash_from_bytes!(H520, 65); -impl_hash_from_bytes!(H2048, 256); - diff --git a/util/rlp/src/compression.rs b/util/rlp/src/compression.rs index b7cf72a4f..7a9c5a917 100644 --- a/util/rlp/src/compression.rs +++ b/util/rlp/src/compression.rs @@ -17,7 +17,7 @@ use std::collections::HashMap; use elastic_array::ElasticArray1024; use common::{BLOCKS_RLP_SWAPPER, SNAPSHOT_RLP_SWAPPER}; -use {UntrustedRlp, View, Compressible, encode, RlpStream}; +use {UntrustedRlp, Compressible, encode, RlpStream}; /// Stores RLPs used for compression pub struct InvalidRlpSwapper<'a> { @@ -69,7 +69,7 @@ fn to_elastic(slice: &[u8]) -> ElasticArray1024 { fn map_rlp(rlp: &UntrustedRlp, f: F) -> Option> where F: Fn(&UntrustedRlp) -> Option> { match rlp.iter() - .fold((false, RlpStream::new_list(rlp.item_count())), + .fold((false, RlpStream::new_list(rlp.item_count().unwrap_or(0))), |(is_some, mut acc), subrlp| { let new = f(&subrlp); if let Some(ref insert) = new { @@ -138,7 +138,7 @@ fn deep_decompress(rlp: &UntrustedRlp, swapper: &InvalidRlpSwapper) -> Option rlp.at(1).ok().map_or(simple_swap(), @@ -169,7 +169,7 @@ impl<'a> Compressible for UntrustedRlp<'a> { #[cfg(test)] mod tests { use compression::InvalidRlpSwapper; - use {UntrustedRlp, Compressible, View, RlpType}; + use {UntrustedRlp, Compressible, RlpType}; #[test] fn invalid_rlp_swapper() { diff --git a/util/rlp/src/error.rs b/util/rlp/src/error.rs index f3b43f850..4ad754dd0 100644 --- a/util/rlp/src/error.rs +++ b/util/rlp/src/error.rs @@ -16,13 +16,10 @@ use std::fmt; use std::error::Error as StdError; -use bytes::FromBytesError; #[derive(Debug, PartialEq, Eq)] /// Error concerning the RLP decoder. pub enum DecoderError { - /// Couldn't convert given bytes to an instance of required type. - FromBytesError(FromBytesError), /// Data has additional bytes at the end of the valid RLP fragment. RlpIsTooBig, /// Data has too few bytes for valid RLP. @@ -56,9 +53,3 @@ impl fmt::Display for DecoderError { fmt::Debug::fmt(&self, f) } } - -impl From for DecoderError { - fn from(err: FromBytesError) -> DecoderError { - DecoderError::FromBytesError(err) - } -} diff --git a/util/rlp/src/impls.rs b/util/rlp/src/impls.rs index affac1ddc..909f3bd63 100644 --- a/util/rlp/src/impls.rs +++ b/util/rlp/src/impls.rs @@ -1,7 +1,26 @@ +use std::{cmp, mem, str}; use byteorder::{ByteOrder, BigEndian}; use bigint::prelude::{Uint, U128, U256, H64, H128, H160, H256, H512, H520, H2048}; -use traits::Encodable; +use traits::{Encodable, Decodable}; use stream::RlpStream; +use {UntrustedRlp, DecoderError}; + +pub fn decode_usize(bytes: &[u8]) -> Result { + match bytes.len() { + l if l <= mem::size_of::() => { + if bytes[0] == 0 { + return Err(DecoderError::RlpInvalidIndirection); + } + let mut res = 0usize; + for i in 0..l { + let shift = (l - 1 - i) * 8; + res = res + ((bytes[i] as usize) << shift); + } + Ok(res) + } + _ => Err(DecoderError::RlpIsTooBig), + } +} impl Encodable for bool { fn rlp_append(&self, s: &mut RlpStream) { @@ -13,6 +32,18 @@ impl Encodable for bool { } } +impl Decodable for bool { + fn decode(rlp: &UntrustedRlp) -> Result { + rlp.decoder().decode_value(|bytes| { + match bytes.len() { + 0 => Ok(false), + 1 => Ok(bytes[0] != 0), + _ => Err(DecoderError::RlpIsTooBig), + } + }) + } +} + impl<'a> Encodable for &'a [u8] { fn rlp_append(&self, s: &mut RlpStream) { s.encoder().encode_value(self); @@ -25,6 +56,14 @@ impl Encodable for Vec { } } +impl Decodable for Vec { + fn decode(rlp: &UntrustedRlp) -> Result { + rlp.decoder().decode_value(|bytes| { + Ok(bytes.to_vec()) + }) + } +} + impl Encodable for Option where T: Encodable { fn rlp_append(&self, s: &mut RlpStream) { match *self { @@ -39,6 +78,17 @@ impl Encodable for Option where T: Encodable { } } +impl Decodable for Option where T: Decodable { + fn decode(rlp: &UntrustedRlp) -> Result { + let items = rlp.item_count()?; + match items { + 1 => rlp.val_at(0).map(Some), + 0 => Ok(None), + _ => Err(DecoderError::RlpIncorrectListLen), + } + } +} + impl Encodable for u8 { fn rlp_append(&self, s: &mut RlpStream) { if *self != 0 { @@ -49,6 +99,19 @@ impl Encodable for u8 { } } +impl Decodable for u8 { + fn decode(rlp: &UntrustedRlp) -> Result { + rlp.decoder().decode_value(|bytes| { + match bytes.len() { + 1 if bytes[0] != 0 => Ok(bytes[0]), + 0 => Ok(0), + 1 => Err(DecoderError::RlpInvalidIndirection), + _ => Err(DecoderError::RlpIsTooBig), + } + }) + } +} + macro_rules! impl_encodable_for_u { ($name: ident, $func: ident, $size: expr) => { impl Encodable for $name { @@ -62,16 +125,52 @@ macro_rules! impl_encodable_for_u { } } +macro_rules! impl_decodable_for_u { + ($name: ident) => { + impl Decodable for $name { + fn decode(rlp: &UntrustedRlp) -> Result { + rlp.decoder().decode_value(|bytes| { + match bytes.len() { + 0 | 1 => u8::decode(rlp).map(|v| v as $name), + l if l <= mem::size_of::<$name>() => { + if bytes[0] == 0 { + return Err(DecoderError::RlpInvalidIndirection); + } + let mut res = 0 as $name; + for i in 0..l { + let shift = (l - 1 - i) * 8; + res = res + ((bytes[i] as $name) << shift); + } + Ok(res) + } + _ => Err(DecoderError::RlpIsTooBig), + } + }) + } + } + } +} + impl_encodable_for_u!(u16, write_u16, 2); impl_encodable_for_u!(u32, write_u32, 4); impl_encodable_for_u!(u64, write_u64, 8); +impl_decodable_for_u!(u16); +impl_decodable_for_u!(u32); +impl_decodable_for_u!(u64); + impl Encodable for usize { fn rlp_append(&self, s: &mut RlpStream) { (*self as u64).rlp_append(s); } } +impl Decodable for usize { + fn decode(rlp: &UntrustedRlp) -> Result { + u64::decode(rlp).map(|value| value as usize) + } +} + macro_rules! impl_encodable_for_hash { ($name: ident) => { impl Encodable for $name { @@ -82,6 +181,24 @@ macro_rules! impl_encodable_for_hash { } } +macro_rules! impl_decodable_for_hash { + ($name: ident, $size: expr) => { + impl Decodable for $name { + fn decode(rlp: &UntrustedRlp) -> Result { + rlp.decoder().decode_value(|bytes| match bytes.len().cmp(&$size) { + cmp::Ordering::Less => Err(DecoderError::RlpIsTooShort), + cmp::Ordering::Greater => Err(DecoderError::RlpIsTooBig), + cmp::Ordering::Equal => { + let mut t = [0u8; $size]; + t.copy_from_slice(bytes); + Ok($name(t)) + } + }) + } + } + } +} + impl_encodable_for_hash!(H64); impl_encodable_for_hash!(H128); impl_encodable_for_hash!(H160); @@ -90,6 +207,14 @@ impl_encodable_for_hash!(H512); impl_encodable_for_hash!(H520); impl_encodable_for_hash!(H2048); +impl_decodable_for_hash!(H64, 8); +impl_decodable_for_hash!(H128, 16); +impl_decodable_for_hash!(H160, 20); +impl_decodable_for_hash!(H256, 32); +impl_decodable_for_hash!(H512, 64); +impl_decodable_for_hash!(H520, 65); +impl_decodable_for_hash!(H2048, 256); + macro_rules! impl_encodable_for_uint { ($name: ident, $size: expr) => { impl Encodable for $name { @@ -103,9 +228,30 @@ macro_rules! impl_encodable_for_uint { } } +macro_rules! impl_decodable_for_uint { + ($name: ident, $size: expr) => { + impl Decodable for $name { + fn decode(rlp: &UntrustedRlp) -> Result { + rlp.decoder().decode_value(|bytes| { + if !bytes.is_empty() && bytes[0] == 0 { + Err(DecoderError::RlpInvalidIndirection) + } else if bytes.len() <= $size { + Ok($name::from(bytes)) + } else { + Err(DecoderError::RlpIsTooBig) + } + }) + } + } + } +} + impl_encodable_for_uint!(U256, 32); impl_encodable_for_uint!(U128, 16); +impl_decodable_for_uint!(U256, 32); +impl_decodable_for_uint!(U128, 16); + impl<'a> Encodable for &'a str { fn rlp_append(&self, s: &mut RlpStream) { s.encoder().encode_value(self.as_bytes()); @@ -118,3 +264,14 @@ impl Encodable for String { } } +impl Decodable for String { + fn decode(rlp: &UntrustedRlp) -> Result { + rlp.decoder().decode_value(|bytes| { + match str::from_utf8(bytes) { + Ok(s) => Ok(s.to_owned()), + // consider better error type here + Err(_err) => Err(DecoderError::RlpExpectedToBeData), + } + }) + } +} diff --git a/util/rlp/src/lib.rs b/util/rlp/src/lib.rs index 406501b1e..4b01691e3 100644 --- a/util/rlp/src/lib.rs +++ b/util/rlp/src/lib.rs @@ -61,17 +61,13 @@ mod untrusted_rlp; mod stream; mod compression; mod common; -mod bytes; mod impls; -#[cfg(test)] -mod tests; - use std::borrow::Borrow; use elastic_array::ElasticArray1024; pub use error::DecoderError; -pub use traits::{Decoder, Decodable, View, Encodable, RlpDecodable, Compressible}; +pub use traits::{Decodable, Encodable, Compressible}; pub use untrusted_rlp::{UntrustedRlp, UntrustedRlpIterator, PayloadInfo, Prototype}; pub use rlpin::{Rlp, RlpIterator}; pub use stream::RlpStream; @@ -88,16 +84,21 @@ pub const EMPTY_LIST_RLP: [u8; 1] = [0xC0; 1]; /// extern crate rlp; /// /// fn main () { -/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; -/// let animals: Vec = rlp::decode(&data); -/// assert_eq!(animals, vec!["cat".to_string(), "dog".to_string()]); +/// let data = vec![0x83, b'c', b'a', b't']; +/// let animal: String = rlp::decode(&data); +/// assert_eq!(animal, "cat".to_owned()); /// } /// ``` -pub fn decode(bytes: &[u8]) -> T where T: RlpDecodable { +pub fn decode(bytes: &[u8]) -> T where T: Decodable { let rlp = Rlp::new(bytes); rlp.as_val() } +pub fn decode_list(bytes: &[u8]) -> Vec where T: Decodable { + let rlp = Rlp::new(bytes); + rlp.as_list() +} + /// Shortcut function to encode structure into rlp. /// /// ```rust diff --git a/util/rlp/src/rlpin.rs b/util/rlp/src/rlpin.rs index 7ae715649..c7c054aa2 100644 --- a/util/rlp/src/rlpin.rs +++ b/util/rlp/src/rlpin.rs @@ -15,8 +15,7 @@ // along with Parity. If not, see . use std::fmt; -use rustc_serialize::hex::ToHex; -use {View, DecoderError, UntrustedRlp, PayloadInfo, Prototype, RlpDecodable}; +use {UntrustedRlp, PayloadInfo, Prototype, Decodable}; impl<'a> From> for Rlp<'a> { fn from(rlp: UntrustedRlp<'a>) -> Rlp<'a> { @@ -39,95 +38,215 @@ impl<'a> fmt::Display for Rlp<'a> { } } -impl<'a, 'view> View<'a, 'view> for Rlp<'a> where 'a: 'view { - type Prototype = Prototype; - type PayloadInfo = PayloadInfo; - type Data = &'a [u8]; - type Item = Rlp<'a>; - type Iter = RlpIterator<'a, 'view>; - +impl<'a, 'view> Rlp<'a> where 'a: 'view { /// Create a new instance of `Rlp` - fn new(bytes: &'a [u8]) -> Rlp<'a> { + pub fn new(bytes: &'a [u8]) -> Rlp<'a> { Rlp { rlp: UntrustedRlp::new(bytes) } } - fn as_raw(&'view self) -> &'a [u8] { + /// The raw data of the RLP as slice. + /// + /// ```rust + /// extern crate rlp; + /// use rlp::*; + /// + /// fn main () { + /// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; + /// let rlp = Rlp::new(&data); + /// let dog = rlp.at(1).as_raw(); + /// assert_eq!(dog, &[0x83, b'd', b'o', b'g']); + /// } + /// ``` + pub fn as_raw(&'view self) -> &'a [u8] { self.rlp.as_raw() } - fn prototype(&self) -> Self::Prototype { + /// Get the prototype of the RLP. + pub fn prototype(&self) -> Prototype { self.rlp.prototype().unwrap() } - fn payload_info(&self) -> Self::PayloadInfo { + /// Get payload info. + pub fn payload_info(&self) -> PayloadInfo { self.rlp.payload_info().unwrap() } - fn data(&'view self) -> Self::Data { + /// Get underlieing data. + pub fn data(&'view self) -> &'a [u8] { self.rlp.data().unwrap() } - fn item_count(&self) -> usize { - self.rlp.item_count() + /// Returns number of RLP items. + /// + /// ```rust + /// extern crate rlp; + /// use rlp::*; + /// + /// fn main () { + /// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; + /// let rlp = Rlp::new(&data); + /// assert_eq!(rlp.item_count(), 2); + /// let view = rlp.at(1); + /// assert_eq!(view.item_count(), 0); + /// } + /// ``` + pub fn item_count(&self) -> usize { + self.rlp.item_count().unwrap_or(0) } - fn size(&self) -> usize { + /// Returns the number of bytes in the data, or zero if it isn't data. + /// + /// ```rust + /// extern crate rlp; + /// use rlp::*; + /// + /// fn main () { + /// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; + /// let rlp = Rlp::new(&data); + /// assert_eq!(rlp.size(), 0); + /// let view = rlp.at(1); + /// assert_eq!(view.size(), 3); + /// } + /// ``` + pub fn size(&self) -> usize { self.rlp.size() } - fn at(&'view self, index: usize) -> Self::Item { + /// Get view onto RLP-slice at index. + /// + /// Caches offset to given index, so access to successive + /// slices is faster. + /// + /// ```rust + /// extern crate rlp; + /// use rlp::*; + /// + /// fn main () { + /// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; + /// let rlp = Rlp::new(&data); + /// let dog: String = rlp.at(1).as_val(); + /// assert_eq!(dog, "dog".to_string()); + /// } + /// ``` + pub fn at(&'view self, index: usize) -> Rlp<'a> { From::from(self.rlp.at(index).unwrap()) } - fn is_null(&self) -> bool { + /// No value + /// + /// ```rust + /// extern crate rlp; + /// use rlp::*; + /// + /// fn main () { + /// let data = vec![]; + /// let rlp = Rlp::new(&data); + /// assert!(rlp.is_null()); + /// } + /// ``` + pub fn is_null(&self) -> bool { self.rlp.is_null() } - fn is_empty(&self) -> bool { + /// Contains a zero-length string or zero-length list. + /// + /// ```rust + /// extern crate rlp; + /// use rlp::*; + /// + /// fn main () { + /// let data = vec![0xc0]; + /// let rlp = Rlp::new(&data); + /// assert!(rlp.is_empty()); + /// } + /// ``` + pub fn is_empty(&self) -> bool { self.rlp.is_empty() } - fn is_list(&self) -> bool { + /// List value + /// + /// ```rust + /// extern crate rlp; + /// use rlp::*; + /// + /// fn main () { + /// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; + /// let rlp = Rlp::new(&data); + /// assert!(rlp.is_list()); + /// } + /// ``` + pub fn is_list(&self) -> bool { self.rlp.is_list() } - fn is_data(&self) -> bool { + /// String value + /// + /// ```rust + /// extern crate rlp; + /// use rlp::*; + /// + /// fn main () { + /// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; + /// let rlp = Rlp::new(&data); + /// assert!(rlp.at(1).is_data()); + /// } + /// ``` + pub fn is_data(&self) -> bool { self.rlp.is_data() } - fn is_int(&self) -> bool { + /// Int value + /// + /// ```rust + /// extern crate rlp; + /// use rlp::*; + /// + /// fn main () { + /// let data = vec![0xc1, 0x10]; + /// let rlp = Rlp::new(&data); + /// assert_eq!(rlp.is_int(), false); + /// assert_eq!(rlp.at(0).is_int(), true); + /// } + /// ``` + pub fn is_int(&self) -> bool { self.rlp.is_int() } - fn iter(&'view self) -> Self::Iter { + /// Get iterator over rlp-slices + /// + /// ```rust + /// extern crate rlp; + /// use rlp::*; + /// + /// fn main () { + /// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; + /// let rlp = Rlp::new(&data); + /// let strings: Vec = rlp.iter().map(| i | i.as_val()).collect(); + /// } + /// ``` + pub fn iter(&'view self) -> RlpIterator<'a, 'view> { self.into_iter() } - fn as_val(&self) -> Result where T: RlpDecodable { - self.rlp.as_val() + /// Decode data into an object + pub fn as_val(&self) -> T where T: Decodable { + self.rlp.as_val().expect("Unexpected rlp error") } - fn val_at(&self, index: usize) -> Result where T: RlpDecodable { - self.at(index).rlp.as_val() - } -} - -impl <'a, 'view> Rlp<'a> where 'a: 'view { - fn view_as_val(r: &'view R) -> T where R: View<'a, 'view>, T: RlpDecodable { - let res: Result = r.as_val(); - res.unwrap_or_else(|e| panic!("DecodeError: {}, {}", e, r.as_raw().to_hex())) + pub fn as_list(&self) -> Vec where T: Decodable { + self.iter().map(|rlp| rlp.as_val()).collect() } - /// Decode into an object - pub fn as_val(&self) -> T where T: RlpDecodable { - Self::view_as_val(self) + /// Decode data at given list index into an object + pub fn val_at(&self, index: usize) -> T where T: Decodable { + self.at(index).as_val() } - /// Decode list item at given index into an object - pub fn val_at(&self, index: usize) -> T where T: RlpDecodable { - Self::view_as_val(&self.at(index)) + pub fn list_at(&self, index: usize) -> Vec where T: Decodable { + self.at(index).as_list() } } diff --git a/util/rlp/src/traits.rs b/util/rlp/src/traits.rs index 3f79e9cab..33c5ae548 100644 --- a/util/rlp/src/traits.rs +++ b/util/rlp/src/traits.rs @@ -16,212 +16,12 @@ //! Common RLP traits use elastic_array::ElasticArray1024; -use stream::RlpStream; -use {DecoderError, UntrustedRlp}; - -/// Type is able to decode RLP. -pub trait Decoder: Sized { - /// Read a value from the RLP into a given type. - fn read_value(&self, f: &F) -> Result - where F: Fn(&[u8]) -> Result; - - /// Get underlying `UntrustedRLP` object. - fn as_rlp(&self) -> &UntrustedRlp; - /// Get underlying raw bytes slice. - fn as_raw(&self) -> &[u8]; -} +use {DecoderError, UntrustedRlp, RlpStream}; /// RLP decodable trait pub trait Decodable: Sized { /// Decode a value from RLP bytes - fn decode(decoder: &D) -> Result where D: Decoder; -} - -/// Internal helper trait. Implement `Decodable` for custom types. -pub trait RlpDecodable: Sized { - /// Decode a value from RLP bytes - fn decode(decoder: &D) -> Result where D: Decoder; -} - -/// A view into RLP encoded data -pub trait View<'a, 'view>: Sized { - /// RLP prototype type - type Prototype; - /// Payload info type - type PayloadInfo; - /// Data type - type Data; - /// Item type - type Item; - /// Iterator type - type Iter; - - /// Creates a new instance of `Rlp` reader - fn new(bytes: &'a [u8]) -> Self; - - /// The raw data of the RLP as slice. - /// - /// ```rust - /// extern crate rlp; - /// use rlp::*; - /// - /// fn main () { - /// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; - /// let rlp = Rlp::new(&data); - /// let dog = rlp.at(1).as_raw(); - /// assert_eq!(dog, &[0x83, b'd', b'o', b'g']); - /// } - /// ``` - fn as_raw(&'view self) -> &'a [u8]; - - /// Get the prototype of the RLP. - fn prototype(&self) -> Self::Prototype; - - /// Get payload info. - fn payload_info(&self) -> Self::PayloadInfo; - - /// Get underlieing data. - fn data(&'view self) -> Self::Data; - - /// Returns number of RLP items. - /// - /// ```rust - /// extern crate rlp; - /// use rlp::*; - /// - /// fn main () { - /// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; - /// let rlp = Rlp::new(&data); - /// assert_eq!(rlp.item_count(), 2); - /// let view = rlp.at(1); - /// assert_eq!(view.item_count(), 0); - /// } - /// ``` - fn item_count(&self) -> usize; - - /// Returns the number of bytes in the data, or zero if it isn't data. - /// - /// ```rust - /// extern crate rlp; - /// use rlp::*; - /// - /// fn main () { - /// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; - /// let rlp = Rlp::new(&data); - /// assert_eq!(rlp.size(), 0); - /// let view = rlp.at(1); - /// assert_eq!(view.size(), 3); - /// } - /// ``` - fn size(&self) -> usize; - - /// Get view onto RLP-slice at index. - /// - /// Caches offset to given index, so access to successive - /// slices is faster. - /// - /// ```rust - /// extern crate rlp; - /// use rlp::*; - /// - /// fn main () { - /// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; - /// let rlp = Rlp::new(&data); - /// let dog: String = rlp.at(1).as_val(); - /// assert_eq!(dog, "dog".to_string()); - /// } - fn at(&'view self, index: usize) -> Self::Item; - - /// No value - /// - /// ```rust - /// extern crate rlp; - /// use rlp::*; - /// - /// fn main () { - /// let data = vec![]; - /// let rlp = Rlp::new(&data); - /// assert!(rlp.is_null()); - /// } - /// ``` - fn is_null(&self) -> bool; - - /// Contains a zero-length string or zero-length list. - /// - /// ```rust - /// extern crate rlp; - /// use rlp::*; - /// - /// fn main () { - /// let data = vec![0xc0]; - /// let rlp = Rlp::new(&data); - /// assert!(rlp.is_empty()); - /// } - /// ``` - fn is_empty(&self) -> bool; - - /// List value - /// - /// ```rust - /// extern crate rlp; - /// use rlp::*; - /// - /// fn main () { - /// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; - /// let rlp = Rlp::new(&data); - /// assert!(rlp.is_list()); - /// } - /// ``` - fn is_list(&self) -> bool; - - /// String value - /// - /// ```rust - /// extern crate rlp; - /// use rlp::*; - /// - /// fn main () { - /// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; - /// let rlp = Rlp::new(&data); - /// assert!(rlp.at(1).is_data()); - /// } - /// ``` - fn is_data(&self) -> bool; - - /// Int value - /// - /// ```rust - /// extern crate rlp; - /// use rlp::*; - /// - /// fn main () { - /// let data = vec![0xc1, 0x10]; - /// let rlp = Rlp::new(&data); - /// assert_eq!(rlp.is_int(), false); - /// assert_eq!(rlp.at(0).is_int(), true); - /// } - /// ``` - fn is_int(&self) -> bool; - - /// Get iterator over rlp-slices - /// - /// ```rust - /// extern crate rlp; - /// use rlp::*; - /// - /// fn main () { - /// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']; - /// let rlp = Rlp::new(&data); - /// let strings: Vec = rlp.iter().map(| i | i.as_val()).collect(); - /// } - /// ``` - fn iter(&'view self) -> Self::Iter; - - /// Decode data into an object - fn as_val(&self) -> Result where T: RlpDecodable; - - /// Decode data at given list index into an object - fn val_at(&self, index: usize) -> Result where T: RlpDecodable; + fn decode(rlp: &UntrustedRlp) -> Result; } /// Structure encodable to RLP diff --git a/util/rlp/src/untrusted_rlp.rs b/util/rlp/src/untrusted_rlp.rs index e111fde18..8f46bb690 100644 --- a/util/rlp/src/untrusted_rlp.rs +++ b/util/rlp/src/untrusted_rlp.rs @@ -17,9 +17,8 @@ use std::cell::Cell; use std::fmt; use rustc_serialize::hex::ToHex; - -use bytes::{FromBytes, FromBytesResult, FromBytesError}; -use ::{View, Decoder, Decodable, DecoderError, RlpDecodable}; +use impls::decode_usize; +use {Decodable, DecoderError}; /// rlp offset #[derive(Copy, Clone, Debug)] @@ -64,7 +63,7 @@ fn calculate_payload_info(header_bytes: &[u8], len_of_len: usize) -> Result (), } if header_bytes.len() < header_len { return Err(DecoderError::RlpIsTooShort); } - let value_len = usize::from_bytes(&header_bytes[1..header_len])?; + let value_len = decode_usize(&header_bytes[1..header_len])?; Ok(PayloadInfo::new(header_len, value_len)) } @@ -141,15 +140,8 @@ impl<'a> fmt::Display for UntrustedRlp<'a> { } } -impl<'a, 'view> View<'a, 'view> for UntrustedRlp<'a> where 'a: 'view { - type Prototype = Result; - type PayloadInfo = Result; - type Data = Result<&'a [u8], DecoderError>; - type Item = Result, DecoderError>; - type Iter = UntrustedRlpIterator<'a, 'view>; - - //returns new instance of `UntrustedRlp` - fn new(bytes: &'a [u8]) -> UntrustedRlp<'a> { +impl<'a, 'view> UntrustedRlp<'a> where 'a: 'view { + pub fn new(bytes: &'a [u8]) -> UntrustedRlp<'a> { UntrustedRlp { bytes: bytes, offset_cache: Cell::new(OffsetCache::new(usize::max_value(), 0)), @@ -157,45 +149,45 @@ impl<'a, 'view> View<'a, 'view> for UntrustedRlp<'a> where 'a: 'view { } } - fn as_raw(&'view self) -> &'a [u8] { + pub fn as_raw(&'view self) -> &'a [u8] { self.bytes } - fn prototype(&self) -> Self::Prototype { + pub fn prototype(&self) -> Result { // optimize? && return appropriate errors if self.is_data() { Ok(Prototype::Data(self.size())) } else if self.is_list() { - Ok(Prototype::List(self.item_count())) + self.item_count().map(Prototype::List) } else { Ok(Prototype::Null) } } - fn payload_info(&self) -> Self::PayloadInfo { + pub fn payload_info(&self) -> Result { BasicDecoder::payload_info(self.bytes) } - fn data(&'view self) -> Self::Data { + pub fn data(&'view self) -> Result<&'a [u8], DecoderError> { let pi = BasicDecoder::payload_info(self.bytes)?; Ok(&self.bytes[pi.header_len..(pi.header_len + pi.value_len)]) } - fn item_count(&self) -> usize { + pub fn item_count(&self) -> Result { match self.is_list() { true => match self.count_cache.get() { - Some(c) => c, + Some(c) => Ok(c), None => { let c = self.iter().count(); self.count_cache.set(Some(c)); - c + Ok(c) } }, - false => 0 + false => Err(DecoderError::RlpExpectedToBeList), } } - fn size(&self) -> usize { + pub fn size(&self) -> usize { match self.is_data() { // TODO: No panic on malformed data, but ideally would Err on no PayloadInfo. true => BasicDecoder::payload_info(self.bytes).map(|b| b.value_len).unwrap_or(0), @@ -203,7 +195,7 @@ impl<'a, 'view> View<'a, 'view> for UntrustedRlp<'a> where 'a: 'view { } } - fn at(&'view self, index: usize) -> Self::Item { + pub fn at(&'view self, index: usize) -> Result, DecoderError> { if !self.is_list() { return Err(DecoderError::RlpExpectedToBeList); } @@ -213,7 +205,7 @@ impl<'a, 'view> View<'a, 'view> for UntrustedRlp<'a> where 'a: 'view { let c = self.offset_cache.get(); let (mut bytes, to_skip) = match c.index <= index { true => (UntrustedRlp::consume(self.bytes, c.offset)?, index - c.index), - false => (self.consume_list_prefix()?, index), + false => (self.consume_list_payload()?, index), }; // skip up to x items @@ -227,23 +219,23 @@ impl<'a, 'view> View<'a, 'view> for UntrustedRlp<'a> where 'a: 'view { Ok(UntrustedRlp::new(&bytes[0..found.header_len + found.value_len])) } - fn is_null(&self) -> bool { + pub fn is_null(&self) -> bool { self.bytes.len() == 0 } - fn is_empty(&self) -> bool { + pub fn is_empty(&self) -> bool { !self.is_null() && (self.bytes[0] == 0xc0 || self.bytes[0] == 0x80) } - fn is_list(&self) -> bool { + pub fn is_list(&self) -> bool { !self.is_null() && self.bytes[0] >= 0xc0 } - fn is_data(&self) -> bool { + pub fn is_data(&self) -> bool { !self.is_null() && self.bytes[0] < 0xc0 } - fn is_int(&self) -> bool { + pub fn is_int(&self) -> bool { if self.is_null() { return false; } @@ -256,23 +248,32 @@ impl<'a, 'view> View<'a, 'view> for UntrustedRlp<'a> where 'a: 'view { } } - fn iter(&'view self) -> Self::Iter { + pub fn iter(&'view self) -> UntrustedRlpIterator<'a, 'view> { self.into_iter() } - fn as_val(&self) -> Result where T: RlpDecodable { - // optimize, so it doesn't use clone (although This clone is cheap) - T::decode(&BasicDecoder::new(self.clone())) + pub fn as_val(&self) -> Result where T: Decodable { + T::decode(self) } - fn val_at(&self, index: usize) -> Result where T: RlpDecodable { + pub fn as_list(&self) -> Result, DecoderError> where T: Decodable { + self.iter().map(|rlp| rlp.as_val()).collect() + } + + pub fn val_at(&self, index: usize) -> Result where T: Decodable { self.at(index)?.as_val() } -} -impl<'a> UntrustedRlp<'a> { + pub fn list_at(&self, index: usize) -> Result, DecoderError> where T: Decodable { + self.at(index)?.as_list() + } + + pub fn decoder(&self) -> BasicDecoder { + BasicDecoder::new(self.clone()) + } + /// consumes first found prefix - fn consume_list_prefix(&self) -> Result<&'a [u8], DecoderError> { + fn consume_list_payload(&self) -> Result<&'a [u8], DecoderError> { let item = BasicDecoder::payload_info(self.bytes)?; let bytes = UntrustedRlp::consume(self.bytes, item.header_len)?; Ok(bytes) @@ -327,7 +328,7 @@ impl<'a, 'view> Iterator for UntrustedRlpIterator<'a, 'view> { } } -struct BasicDecoder<'a> { +pub struct BasicDecoder<'a> { rlp: UntrustedRlp<'a> } @@ -346,10 +347,8 @@ impl<'a> BasicDecoder<'a> { _ => Err(DecoderError::RlpIsTooShort), } } -} -impl<'a> Decoder for BasicDecoder<'a> { - fn read_value(&self, f: &F) -> Result + pub fn decode_value(&self, f: F) -> Result where F: Fn(&[u8]) -> Result { let bytes = self.rlp.as_raw(); @@ -378,7 +377,7 @@ impl<'a> Decoder for BasicDecoder<'a> { if bytes.len() < begin_of_value { return Err(DecoderError::RlpInconsistentLengthAndData); } - let len = usize::from_bytes(&bytes[1..begin_of_value])?; + let len = decode_usize(&bytes[1..begin_of_value])?; let last_index_of_value = begin_of_value + len; if bytes.len() < last_index_of_value { @@ -390,108 +389,12 @@ impl<'a> Decoder for BasicDecoder<'a> { _ => Err(DecoderError::RlpExpectedToBeData) } } - - fn as_raw(&self) -> &[u8] { - self.rlp.as_raw() - } - - fn as_rlp(&self) -> &UntrustedRlp { - &self.rlp - } -} - -impl Decodable for T where T: FromBytes { - fn decode(decoder: &D) -> Result where D: Decoder { - decoder.read_value(&|bytes: &[u8]| Ok(T::from_bytes(bytes)?)) - } -} - -impl Decodable for Vec where T: Decodable { - fn decode(decoder: &D) -> Result where D: Decoder { - decoder.as_rlp().iter().map(|d| T::decode(&BasicDecoder::new(d))).collect() - } -} - -impl Decodable for Option where T: Decodable { - fn decode(decoder: &D) -> Result where D: Decoder { - decoder.as_rlp().iter().map(|d| T::decode(&BasicDecoder::new(d))).collect::, DecoderError>>().map(|mut a| a.pop()) - } -} - -impl Decodable for Vec { - fn decode(decoder: &D) -> Result where D: Decoder { - decoder.read_value(&|bytes: &[u8]| Ok(bytes.to_vec())) - } -} - -macro_rules! impl_array_decodable { - ($index_type:ty, $len:expr ) => ( - impl Decodable for [T; $len] where T: Decodable { - fn decode(decoder: &D) -> Result where D: Decoder { - let decoders = decoder.as_rlp(); - - let mut result: [T; $len] = unsafe { ::std::mem::uninitialized() }; - if decoders.item_count() != $len { - return Err(DecoderError::RlpIncorrectListLen); - } - - for i in 0..decoders.item_count() { - result[i] = T::decode(&BasicDecoder::new(decoders.at(i)?))?; - } - - Ok(result) - } - } - ) -} - -macro_rules! impl_array_decodable_recursive { - ($index_type:ty, ) => (); - ($index_type:ty, $len:expr, $($more:expr,)*) => ( - impl_array_decodable!($index_type, $len); - impl_array_decodable_recursive!($index_type, $($more,)*); - ); -} - -impl_array_decodable_recursive!( - u8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, - 32, 40, 48, 56, 64, 72, 96, 128, 160, 192, 224, -); - -impl RlpDecodable for T where T: Decodable { - fn decode(decoder: &D) -> Result where D: Decoder { - Decodable::decode(decoder) - } -} - -struct DecodableU8 (u8); - -impl FromBytes for DecodableU8 { - fn from_bytes(bytes: &[u8]) -> FromBytesResult { - match bytes.len() { - 0 => Ok(DecodableU8(0u8)), - 1 => { - if bytes[0] == 0 { - return Err(FromBytesError::ZeroPrefixedInt) - } - Ok(DecodableU8(bytes[0])) - } - _ => Err(FromBytesError::DataIsTooLong) - } - } -} - -impl RlpDecodable for u8 { - fn decode(decoder: &D) -> Result where D: Decoder { - let u: DecodableU8 = Decodable::decode(decoder)?; - Ok(u.0) - } } #[cfg(test)] mod tests { - use ::{UntrustedRlp, View}; + use UntrustedRlp; + #[test] fn test_rlp_display() { use rustc_serialize::hex::FromHex; diff --git a/util/rlp/src/tests.rs b/util/rlp/tests/tests.rs similarity index 90% rename from util/rlp/src/tests.rs rename to util/rlp/tests/tests.rs index bd3abfe63..1c996caac 100644 --- a/util/rlp/src/tests.rs +++ b/util/rlp/tests/tests.rs @@ -14,9 +14,12 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . +extern crate ethcore_bigint as bigint; +extern crate rlp; + use std::{fmt, cmp}; use bigint::prelude::U256; -use {Encodable, RlpDecodable, UntrustedRlp, RlpStream, View, DecoderError}; +use rlp::{Encodable, Decodable, UntrustedRlp, RlpStream, DecoderError}; #[test] fn rlp_at() { @@ -24,7 +27,7 @@ fn rlp_at() { { let rlp = UntrustedRlp::new(&data); assert!(rlp.is_list()); - let animals: Vec = rlp.as_val().unwrap(); + let animals: Vec = rlp.as_list().unwrap(); assert_eq!(animals, vec!["cat".to_owned(), "dog".to_owned()]); let cat = rlp.at(0).unwrap(); @@ -89,7 +92,7 @@ fn run_encode_tests(tests: Vec>) where T: Encodable { for t in &tests { - let res = super::encode(&t.0); + let res = rlp::encode(&t.0); assert_eq!(&res[..], &t.1[..]); } } @@ -100,7 +103,7 @@ fn run_encode_tests_list(tests: Vec>) where T: Encodable { for t in &tests { - let res = super::encode_list(&t.0); + let res = rlp::encode_list(&t.0); assert_eq!(&res[..], &t.1[..]); } } @@ -210,11 +213,20 @@ fn encode_vector_str() { run_encode_tests_list(tests); } -struct DTestPair(T, Vec) where T: RlpDecodable + fmt::Debug + cmp::Eq; +struct DTestPair(T, Vec) where T: Decodable + fmt::Debug + cmp::Eq; -fn run_decode_tests(tests: Vec>) where T: RlpDecodable + fmt::Debug + cmp::Eq { +struct VDTestPair(Vec, Vec) where T: Decodable + fmt::Debug + cmp::Eq; + +fn run_decode_tests(tests: Vec>) where T: Decodable + fmt::Debug + cmp::Eq { for t in &tests { - let res: T = super::decode(&t.1); + let res: T = rlp::decode(&t.1); + assert_eq!(res, t.0); + } +} + +fn run_decode_tests_list(tests: Vec>) where T: Decodable + fmt::Debug + cmp::Eq { + for t in &tests { + let res: Vec = rlp::decode_list(&t.1); assert_eq!(res, t.0); } } @@ -318,35 +330,19 @@ fn decode_untrusted_address() { #[test] fn decode_untrusted_vector_u64() { let tests = vec![ - DTestPair(vec![], vec![0xc0]), - DTestPair(vec![15u64], vec![0xc1, 0x0f]), - DTestPair(vec![1, 2, 3, 7, 0xff], vec![0xc6, 1, 2, 3, 7, 0x81, 0xff]), - DTestPair(vec![0xffffffff, 1, 2, 3, 7, 0xff], vec![0xcb, 0x84, 0xff, 0xff, 0xff, 0xff, 1, 2, 3, 7, 0x81, 0xff]), + VDTestPair(vec![], vec![0xc0]), + VDTestPair(vec![15u64], vec![0xc1, 0x0f]), + VDTestPair(vec![1, 2, 3, 7, 0xff], vec![0xc6, 1, 2, 3, 7, 0x81, 0xff]), + VDTestPair(vec![0xffffffff, 1, 2, 3, 7, 0xff], vec![0xcb, 0x84, 0xff, 0xff, 0xff, 0xff, 1, 2, 3, 7, 0x81, 0xff]), ]; - run_decode_tests(tests); + run_decode_tests_list(tests); } #[test] fn decode_untrusted_vector_str() { - let tests = vec![DTestPair(vec!["cat".to_owned(), "dog".to_owned()], + let tests = vec![VDTestPair(vec!["cat".to_owned(), "dog".to_owned()], vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'])]; - run_decode_tests(tests); -} - -#[test] -fn decode_untrusted_vector_of_vectors_str() { - let tests = vec![DTestPair(vec![vec!["cat".to_owned()]], - vec![0xc5, 0xc4, 0x83, b'c', b'a', b't'])]; - run_decode_tests(tests); -} - -#[test] -fn test_decoding_array() { - let v = vec![5u16, 2u16]; - let res = super::encode_list(&v); - let arr: [u16; 2] = super::decode(&res); - assert_eq!(arr[0], 5); - assert_eq!(arr[1], 2); + run_decode_tests_list(tests); } #[test] diff --git a/util/src/journaldb/earlymergedb.rs b/util/src/journaldb/earlymergedb.rs index bd05d5fc1..66e5a1cfd 100644 --- a/util/src/journaldb/earlymergedb.rs +++ b/util/src/journaldb/earlymergedb.rs @@ -290,7 +290,7 @@ impl EarlyMergeDB { &r.drain() }).expect("Low-level database error.") { let rlp = Rlp::new(&rlp_data); - let inserts: Vec = rlp.val_at(1); + let inserts: Vec = rlp.list_at(1); Self::replay_keys(&inserts, db, col, &mut refs); index += 1; }; @@ -466,11 +466,11 @@ impl JournalDB for EarlyMergeDB { &last })? { let rlp = Rlp::new(&rlp_data); - let inserts: Vec = rlp.val_at(1); + let inserts: Vec = rlp.list_at(1); if canon_id == &rlp.val_at::(0) { // Collect keys to be removed. Canon block - remove the (enacted) deletes. - let deletes: Vec = rlp.val_at(2); + let deletes: Vec = rlp.list_at(2); trace!(target: "jdb.ops", " Expunging: {:?}", deletes); Self::remove_keys(&deletes, &mut refs, batch, self.column, RemoveFrom::Archive, trace); diff --git a/util/src/journaldb/overlayrecentdb.rs b/util/src/journaldb/overlayrecentdb.rs index e8095e71e..7eeabf6df 100644 --- a/util/src/journaldb/overlayrecentdb.rs +++ b/util/src/journaldb/overlayrecentdb.rs @@ -155,7 +155,7 @@ impl OverlayRecentDB { let rlp = Rlp::new(&rlp_data); let id: H256 = rlp.val_at(0); let insertions = rlp.at(1); - let deletions: Vec = rlp.val_at(2); + let deletions: Vec = rlp.list_at(2); let mut inserted_keys = Vec::new(); for r in insertions.iter() { let k: H256 = r.val_at(0); diff --git a/util/src/journaldb/refcounteddb.rs b/util/src/journaldb/refcounteddb.rs index b18954eb3..13c2189c8 100644 --- a/util/src/journaldb/refcounteddb.rs +++ b/util/src/journaldb/refcounteddb.rs @@ -171,7 +171,7 @@ impl JournalDB for RefCountedDB { } { let rlp = Rlp::new(&rlp_data); let our_id: H256 = rlp.val_at(0); - let to_remove: Vec = rlp.val_at(if *canon_id == our_id {2} else {1}); + let to_remove: Vec = rlp.list_at(if *canon_id == our_id {2} else {1}); trace!(target: "rcdb", "delete journal for time #{}.{}=>{}, (canon was {}): deleting {:?}", end_era, index, our_id, canon_id, to_remove); for i in &to_remove { self.forward.remove(i); diff --git a/util/src/kvdb.rs b/util/src/kvdb.rs index 043b3d983..7de8dc910 100644 --- a/util/src/kvdb.rs +++ b/util/src/kvdb.rs @@ -23,7 +23,7 @@ use std::path::PathBuf; use common::*; use elastic_array::*; use hashdb::DBValue; -use rlp::{UntrustedRlp, RlpType, View, Compressible}; +use rlp::{UntrustedRlp, RlpType, Compressible}; use rocksdb::{DB, Writable, WriteBatch, WriteOptions, IteratorMode, DBIterator, Options, DBCompactionStyle, BlockBasedOptions, Direction, Cache, Column, ReadOptions}; #[cfg(target_os = "linux")] diff --git a/util/src/trie/lookup.rs b/util/src/trie/lookup.rs index 30e021527..d24a82e16 100644 --- a/util/src/trie/lookup.rs +++ b/util/src/trie/lookup.rs @@ -18,7 +18,7 @@ use hashdb::HashDB; use nibbleslice::NibbleSlice; -use rlp::{Rlp, View}; +use rlp::Rlp; use ::{H256}; use super::{TrieError, Query}; diff --git a/util/src/trie/triedbmut.rs b/util/src/trie/triedbmut.rs index c5f2a739b..2c2e556c5 100644 --- a/util/src/trie/triedbmut.rs +++ b/util/src/trie/triedbmut.rs @@ -24,7 +24,7 @@ use super::node::NodeKey; use ::{HashDB, H256}; use ::bytes::ToPretty; use ::nibbleslice::NibbleSlice; -use ::rlp::{Rlp, RlpStream, View}; +use ::rlp::{Rlp, RlpStream}; use ::sha3::SHA3_NULL_RLP; use hashdb::DBValue;