diff --git a/substrate/.gitlab-ci.yml b/substrate/.gitlab-ci.yml index e4226ee8ad..439fda5fab 100644 --- a/substrate/.gitlab-ci.yml +++ b/substrate/.gitlab-ci.yml @@ -148,7 +148,6 @@ test-linux-stable: &test-linux test-dependency-rules: &test-linux stage: test <<: *docker-env - allow_failure: true except: variables: - $DEPLOY_TAG diff --git a/substrate/.maintain/ensure-deps.sh b/substrate/.maintain/ensure-deps.sh index d8383cd313..7087200cef 100755 --- a/substrate/.maintain/ensure-deps.sh +++ b/substrate/.maintain/ensure-deps.sh @@ -3,36 +3,41 @@ # The script is meant to check if the rules regarding packages # dependencies are satisfied. # The general format is: -# [top-lvl-dir]<[crate-name-prefix] +# [top-lvl-dir] MESSAGE/[other-top-dir] # For instance no crate within `./client` directory # is allowed to import any crate with a directory path containing `frame`. -# Such rule is just: `client /dev/null +} + +for rule in "${MUST_NOT[@]}" +do + check_rule "$rule"; +done + +# Only the MUST NOT will be counted towards failure +HARD_VIOLATIONS=${#VIOLATIONS[@]} + + +for rule in "${PLEASE_DONT[@]}" +do + check_rule "$rule"; done # Display violations and fail @@ -58,4 +77,4 @@ EOF I=$I+1 done -exit ${#VIOLATIONS[@]} +exit $HARD_VIOLATIONS diff --git a/substrate/Cargo.lock b/substrate/Cargo.lock index 42401f8ad0..317215e5b6 100644 --- a/substrate/Cargo.lock +++ b/substrate/Cargo.lock @@ -1328,22 +1328,6 @@ dependencies = [ "syn 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "frame-support-rpc" -version = "2.0.0" -dependencies = [ - "frame-support 2.0.0", - "frame-system 2.0.0", - "futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-client-transports 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-core 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", - "substrate-primitives-storage 2.0.0", - "substrate-rpc-api 2.0.0", - "tokio 0.1.22 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "frame-support-test" version = "2.0.0" @@ -1377,26 +1361,6 @@ dependencies = [ "substrate-primitives 2.0.0", ] -[[package]] -name = "frame-system-rpc" -version = "2.0.0" -dependencies = [ - "env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", - "frame-system-rpc-runtime-api 2.0.0", - "futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-core 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-core-client 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-derive 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", - "sr-primitives 2.0.0", - "substrate-client 2.0.0", - "substrate-primitives 2.0.0", - "substrate-test-runtime-client 2.0.0", - "substrate-transaction-pool 2.0.0", -] - [[package]] name = "frame-system-rpc-runtime-api" version = "2.0.0" @@ -3041,6 +3005,7 @@ dependencies = [ "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "sc-transaction-pool 2.0.0", "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", "sp-finality-tracker 2.0.0", "sp-timestamp 2.0.0", @@ -3071,7 +3036,6 @@ dependencies = [ "substrate-service 2.0.0", "substrate-service-test 2.0.0", "substrate-telemetry 2.0.0", - "substrate-transaction-pool 2.0.0", "tempfile 3.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "tokio 0.1.22 (registry+https://github.com/rust-lang/crates.io-index)", "transaction-factory 0.0.1", @@ -3124,15 +3088,15 @@ dependencies = [ name = "node-rpc" version = "2.0.0" dependencies = [ - "frame-system-rpc 2.0.0", "jsonrpc-core 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", "node-primitives 2.0.0", "node-runtime 2.0.0", "pallet-contracts-rpc 2.0.0", "pallet-transaction-payment-rpc 2.0.0", + "sc-transaction-pool 2.0.0", "sr-primitives 2.0.0", "substrate-client 2.0.0", - "substrate-transaction-pool 2.0.0", + "substrate-frame-rpc-system 2.0.0", ] [[package]] @@ -3217,6 +3181,7 @@ dependencies = [ "node-template-runtime 2.0.0", "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sc-transaction-pool 2.0.0", "sr-io 2.0.0", "sr-primitives 2.0.0", "substrate-basic-authorship 2.0.0", @@ -3232,7 +3197,6 @@ dependencies = [ "substrate-network 2.0.0", "substrate-primitives 2.0.0", "substrate-service 2.0.0", - "substrate-transaction-pool 2.0.0", "tokio 0.1.22 (registry+https://github.com/rust-lang/crates.io-index)", "trie-root 0.15.2 (registry+https://github.com/rust-lang/crates.io-index)", "vergen 3.0.4 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3607,8 +3571,8 @@ dependencies = [ "pallet-contracts-rpc-runtime-api 2.0.0", "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-primitives 2.0.0", - "substrate-client 2.0.0", "substrate-primitives 2.0.0", "substrate-rpc-primitives 2.0.0", ] @@ -3672,6 +3636,7 @@ dependencies = [ "sr-std 2.0.0", "substrate-phragmen 2.0.0", "substrate-primitives 2.0.0", + "substrate-test-utils 2.0.0", ] [[package]] @@ -3909,6 +3874,7 @@ dependencies = [ "substrate-keyring 2.0.0", "substrate-phragmen 2.0.0", "substrate-primitives 2.0.0", + "substrate-test-utils 2.0.0", ] [[package]] @@ -3978,8 +3944,8 @@ dependencies = [ "pallet-transaction-payment-rpc-runtime-api 2.0.0", "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-primitives 2.0.0", - "substrate-client 2.0.0", "substrate-primitives 2.0.0", "substrate-rpc-primitives 2.0.0", ] @@ -4863,6 +4829,63 @@ dependencies = [ "winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "sc-rpc-api" +version = "2.0.0" +dependencies = [ + "derive_more 0.99.2 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-core 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-core-client 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-derive 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-pubsub 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sc-transaction-graph 2.0.0", + "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.41 (registry+https://github.com/rust-lang/crates.io-index)", + "sr-version 2.0.0", + "substrate-primitives 2.0.0", + "substrate-rpc-primitives 2.0.0", +] + +[[package]] +name = "sc-transaction-graph" +version = "2.0.0" +dependencies = [ + "assert_matches 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "criterion 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "derive_more 0.99.2 (registry+https://github.com/rust-lang/crates.io-index)", + "env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", + "sr-primitives 2.0.0", + "substrate-primitives 2.0.0", + "substrate-test-runtime 2.0.0", +] + +[[package]] +name = "sc-transaction-pool" +version = "2.0.0" +dependencies = [ + "derive_more 0.99.2 (registry+https://github.com/rust-lang/crates.io-index)", + "futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sc-transaction-graph 2.0.0", + "sr-api 2.0.0", + "sr-primitives 2.0.0", + "substrate-keyring 2.0.0", + "substrate-primitives 2.0.0", + "substrate-test-runtime-client 2.0.0", + "substrate-transaction-pool-runtime-api 2.0.0", +] + [[package]] name = "schannel" version = "0.1.16" @@ -5166,6 +5189,21 @@ dependencies = [ "substrate-inherents 2.0.0", ] +[[package]] +name = "sp-blockchain" +version = "2.0.0" +dependencies = [ + "derive_more 0.99.2 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", + "lru 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sr-primitives 2.0.0", + "substrate-block-builder-runtime-api 2.0.0", + "substrate-consensus-common 2.0.0", + "substrate-state-machine 2.0.0", +] + [[package]] name = "sp-finality-tracker" version = "2.0.0" @@ -5228,6 +5266,7 @@ version = "2.0.0" dependencies = [ "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "rustversion 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-api 2.0.0", "sr-primitives 2.0.0", "sr-version 2.0.0", @@ -5452,6 +5491,7 @@ dependencies = [ "prost 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", "prost-build 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.41 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-api 2.0.0", "sr-primitives 2.0.0", "substrate-authority-discovery-primitives 2.0.0", @@ -5482,6 +5522,8 @@ dependencies = [ "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sc-transaction-pool 2.0.0", + "sp-blockchain 2.0.0", "sr-primitives 2.0.0", "substrate-block-builder 2.0.0", "substrate-client 2.0.0", @@ -5491,7 +5533,6 @@ dependencies = [ "substrate-primitives 2.0.0", "substrate-telemetry 2.0.0", "substrate-test-runtime-client 2.0.0", - "substrate-transaction-pool 2.0.0", "tokio-executor 0.2.0-alpha.6 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -5511,6 +5552,7 @@ name = "substrate-block-builder" version = "2.0.0" dependencies = [ "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-api 2.0.0", "sr-primitives 2.0.0", "substrate-block-builder-runtime-api 2.0.0", @@ -5576,10 +5618,10 @@ dependencies = [ "regex 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "rpassword 4.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.41 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-primitives 2.0.0", "structopt 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", "substrate-client-api 2.0.0", - "substrate-header-metadata 2.0.0", "substrate-keyring 2.0.0", "substrate-network 2.0.0", "substrate-panic-handler 2.0.0", @@ -5608,6 +5650,7 @@ dependencies = [ "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-api 2.0.0", "sr-primitives 2.0.0", "sr-std 2.0.0", @@ -5618,7 +5661,6 @@ dependencies = [ "substrate-consensus-common 2.0.0", "substrate-executor 2.0.0", "substrate-externalities 2.0.0", - "substrate-header-metadata 2.0.0", "substrate-inherents 2.0.0", "substrate-keyring 2.0.0", "substrate-panic-handler 2.0.0", @@ -5645,6 +5687,7 @@ dependencies = [ "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-api 2.0.0", "sr-primitives 2.0.0", "sr-std 2.0.0", @@ -5654,7 +5697,6 @@ dependencies = [ "substrate-consensus-common 2.0.0", "substrate-executor 2.0.0", "substrate-externalities 2.0.0", - "substrate-header-metadata 2.0.0", "substrate-inherents 2.0.0", "substrate-keyring 2.0.0", "substrate-panic-handler 2.0.0", @@ -5681,12 +5723,12 @@ dependencies = [ "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "quickcheck 0.8.5 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-primitives 2.0.0", "substrate-client 2.0.0", "substrate-client-api 2.0.0", "substrate-consensus-common 2.0.0", "substrate-executor 2.0.0", - "substrate-header-metadata 2.0.0", "substrate-keyring 2.0.0", "substrate-primitives 2.0.0", "substrate-state-db 2.0.0", @@ -5707,6 +5749,7 @@ dependencies = [ "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sp-timestamp 2.0.0", "sr-api 2.0.0", "sr-io 2.0.0", @@ -5765,6 +5808,7 @@ dependencies = [ "pdqselect 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", "schnorrkel 0.8.5 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sp-timestamp 2.0.0", "sr-api 2.0.0", "sr-io 2.0.0", @@ -5780,7 +5824,6 @@ dependencies = [ "substrate-consensus-slots 2.0.0", "substrate-consensus-uncles 2.0.0", "substrate-executor 2.0.0", - "substrate-header-metadata 2.0.0", "substrate-inherents 2.0.0", "substrate-keyring 2.0.0", "substrate-keystore 2.0.0", @@ -5835,6 +5878,7 @@ dependencies = [ "futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sp-timestamp 2.0.0", "sr-primitives 2.0.0", "substrate-block-builder-runtime-api 2.0.0", @@ -5865,6 +5909,7 @@ dependencies = [ "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-primitives 2.0.0", "substrate-client-api 2.0.0", "substrate-consensus-common 2.0.0", @@ -5960,6 +6005,7 @@ dependencies = [ "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.41 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sp-finality-tracker 2.0.0", "sr-api 2.0.0", "sr-primitives 2.0.0", @@ -5968,7 +6014,6 @@ dependencies = [ "substrate-consensus-babe-primitives 2.0.0", "substrate-consensus-common 2.0.0", "substrate-finality-grandpa-primitives 2.0.0", - "substrate-header-metadata 2.0.0", "substrate-inherents 2.0.0", "substrate-keyring 2.0.0", "substrate-keystore 2.0.0", @@ -5996,12 +6041,40 @@ dependencies = [ ] [[package]] -name = "substrate-header-metadata" +name = "substrate-frame-rpc-support" version = "2.0.0" dependencies = [ - "lru 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "frame-support 2.0.0", + "frame-system 2.0.0", + "futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-client-transports 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-core 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "sc-rpc-api 2.0.0", + "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", + "substrate-primitives-storage 2.0.0", + "tokio 0.1.22 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "substrate-frame-rpc-system" +version = "2.0.0" +dependencies = [ + "env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "frame-system-rpc-runtime-api 2.0.0", + "futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-core 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-core-client 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-derive 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "sc-transaction-graph 2.0.0", + "sc-transaction-pool 2.0.0", + "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-primitives 2.0.0", + "substrate-primitives 2.0.0", + "substrate-test-runtime-client 2.0.0", ] [[package]] @@ -6070,6 +6143,7 @@ dependencies = [ "slog 2.5.2 (registry+https://github.com/rust-lang/crates.io-index)", "slog_derive 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "smallvec 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-arithmetic 2.0.0", "sr-primitives 2.0.0", "substrate-block-builder 2.0.0", @@ -6077,7 +6151,6 @@ dependencies = [ "substrate-client-api 2.0.0", "substrate-consensus-babe-primitives 2.0.0", "substrate-consensus-common 2.0.0", - "substrate-header-metadata 2.0.0", "substrate-keyring 2.0.0", "substrate-peerset 2.0.0", "substrate-primitives 2.0.0", @@ -6109,6 +6182,7 @@ dependencies = [ "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "sc-transaction-pool 2.0.0", "sr-api 2.0.0", "sr-primitives 2.0.0", "substrate-client-api 2.0.0", @@ -6118,7 +6192,6 @@ dependencies = [ "substrate-offchain-primitives 2.0.0", "substrate-primitives 2.0.0", "substrate-test-runtime-client 2.0.0", - "substrate-transaction-pool 2.0.0", "threadpool 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "tokio 0.1.22 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -6154,12 +6227,12 @@ dependencies = [ name = "substrate-phragmen" version = "2.0.0" dependencies = [ - "frame-support 2.0.0", "rand 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 2.0.0", "sr-primitives 2.0.0", "sr-std 2.0.0", + "substrate-test-utils 2.0.0", ] [[package]] @@ -6229,7 +6302,10 @@ dependencies = [ "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "sc-rpc-api 2.0.0", + "sc-transaction-pool 2.0.0", "serde_json 1.0.41 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-api 2.0.0", "sr-io 2.0.0", "sr-primitives 2.0.0", @@ -6240,36 +6316,13 @@ dependencies = [ "substrate-keystore 2.0.0", "substrate-network 2.0.0", "substrate-primitives 2.0.0", - "substrate-rpc-api 2.0.0", "substrate-rpc-primitives 2.0.0", "substrate-session 2.0.0", "substrate-state-machine 2.0.0", "substrate-test-runtime-client 2.0.0", - "substrate-transaction-pool 2.0.0", "tokio 0.1.22 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "substrate-rpc-api" -version = "2.0.0" -dependencies = [ - "derive_more 0.99.2 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-core 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-core-client 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-derive 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-pubsub 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.41 (registry+https://github.com/rust-lang/crates.io-index)", - "sr-version 2.0.0", - "substrate-primitives 2.0.0", - "substrate-rpc-primitives 2.0.0", - "substrate-transaction-graph 2.0.0", -] - [[package]] name = "substrate-rpc-primitives" version = "2.0.0" @@ -6370,15 +6423,14 @@ dependencies = [ "grafana-data-source 2.0.0", "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "node-executor 2.0.0", - "node-primitives 2.0.0", - "node-runtime 2.0.0", "parity-multiaddr 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sc-transaction-pool 2.0.0", "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.41 (registry+https://github.com/rust-lang/crates.io-index)", "slog 2.5.2 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-api 2.0.0", "sr-io 2.0.0", "sr-primitives 2.0.0", @@ -6402,7 +6454,6 @@ dependencies = [ "substrate-telemetry 2.0.0", "substrate-test-runtime-client 2.0.0", "substrate-tracing 2.0.0", - "substrate-transaction-pool 2.0.0", "substrate-transaction-pool-runtime-api 2.0.0", "sysinfo 0.9.6 (registry+https://github.com/rust-lang/crates.io-index)", "target_info 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -6498,6 +6549,7 @@ dependencies = [ "futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "hash-db 0.15.2 (registry+https://github.com/rust-lang/crates.io-index)", "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-primitives 2.0.0", "substrate-client 2.0.0", "substrate-client-api 2.0.0", @@ -6565,6 +6617,7 @@ name = "substrate-test-runtime-client" version = "2.0.0" dependencies = [ "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-primitives 2.0.0", "substrate-block-builder 2.0.0", "substrate-client 2.0.0", @@ -6574,6 +6627,10 @@ dependencies = [ "substrate-test-runtime 2.0.0", ] +[[package]] +name = "substrate-test-utils" +version = "2.0.0" + [[package]] name = "substrate-tracing" version = "2.0.0" @@ -6586,42 +6643,6 @@ dependencies = [ "tracing-core 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "substrate-transaction-graph" -version = "2.0.0" -dependencies = [ - "assert_matches 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "criterion 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "derive_more 0.99.2 (registry+https://github.com/rust-lang/crates.io-index)", - "env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", - "sr-primitives 2.0.0", - "substrate-primitives 2.0.0", - "substrate-test-runtime 2.0.0", -] - -[[package]] -name = "substrate-transaction-pool" -version = "2.0.0" -dependencies = [ - "derive_more 0.99.2 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sr-api 2.0.0", - "sr-primitives 2.0.0", - "substrate-keyring 2.0.0", - "substrate-primitives 2.0.0", - "substrate-test-runtime-client 2.0.0", - "substrate-transaction-graph 2.0.0", - "substrate-transaction-pool-runtime-api 2.0.0", -] - [[package]] name = "substrate-transaction-pool-runtime-api" version = "2.0.0" @@ -7194,6 +7215,7 @@ version = "0.0.1" dependencies = [ "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-blockchain 2.0.0", "sr-api 2.0.0", "sr-primitives 2.0.0", "substrate-block-builder-runtime-api 2.0.0", diff --git a/substrate/Cargo.toml b/substrate/Cargo.toml index d398fd78b2..84fbb2430b 100644 --- a/substrate/Cargo.toml +++ b/substrate/Cargo.toml @@ -27,11 +27,11 @@ members = [ "client/executor", "client/executor/runtime-test", "client/finality-grandpa", - "client/header-metadata", "client/tracing", "client/keystore", "client/network", "client/offchain", + "client/peerset", "client/rpc-servers", "client/rpc", "client/rpc/api", @@ -79,10 +79,8 @@ members = [ "frame/support/procedural", "frame/support/procedural/tools", "frame/support/procedural/tools/derive", - "frame/support/rpc", "frame/support/test", "frame/system", - "frame/system/rpc", "frame/system/rpc/runtime-api", "frame/timestamp", "frame/transaction-payment", @@ -94,6 +92,7 @@ members = [ "primitives/authority-discovery", "primitives/authorship", "primitives/block-builder/runtime-api", + "primitives/blockchain", "primitives/consensus/aura", "primitives/consensus/babe", "primitives/consensus/common", @@ -108,7 +107,6 @@ members = [ "primitives/keyring", "primitives/offchain", "primitives/panic-handler", - "primitives/peerset", "primitives/phragmen", "primitives/rpc", "primitives/runtime-interface", @@ -139,6 +137,8 @@ members = [ "test/utils/transaction-factory", "utils/build-script-utils", "utils/fork-tree", + "utils/frame/rpc/support", + "utils/frame/rpc/system", "utils/wasm-builder", ] diff --git a/substrate/bin/node-template/Cargo.toml b/substrate/bin/node-template/Cargo.toml index 11373e8d71..5e0ee24547 100644 --- a/substrate/bin/node-template/Cargo.toml +++ b/substrate/bin/node-template/Cargo.toml @@ -24,7 +24,7 @@ primitives = { package = "substrate-primitives", path = "../../primitives/core" substrate-executor = { path = "../../client/executor" } substrate-service = { path = "../../client/service" } inherents = { package = "substrate-inherents", path = "../../primitives/inherents" } -transaction-pool = { package = "substrate-transaction-pool", path = "../../client/transaction-pool" } +transaction-pool = { package = "sc-transaction-pool", path = "../../client/transaction-pool" } network = { package = "substrate-network", path = "../../client/network" } aura = { package = "substrate-consensus-aura", path = "../../client/consensus/aura" } aura-primitives = { package = "substrate-consensus-aura-primitives", path = "../../primitives/consensus/aura" } diff --git a/substrate/bin/node/cli/Cargo.toml b/substrate/bin/node/cli/Cargo.toml index 01d7b1a48b..e9705f52dc 100644 --- a/substrate/bin/node/cli/Cargo.toml +++ b/substrate/bin/node/cli/Cargo.toml @@ -49,7 +49,7 @@ runtime-io = { package = "sr-io", path = "../../../primitives/sr-io" } client-api = { package = "substrate-client-api", path = "../../../client/api" } client = { package = "substrate-client", path = "../../../client/" } chain-spec = { package = "substrate-chain-spec", path = "../../../client/chain-spec" } -transaction_pool = { package = "substrate-transaction-pool", path = "../../../client/transaction-pool" } +transaction_pool = { package = "sc-transaction-pool", path = "../../../client/transaction-pool" } network = { package = "substrate-network", path = "../../../client/network" } babe = { package = "substrate-consensus-babe", path = "../../../client/consensus/babe" } grandpa = { package = "substrate-finality-grandpa", path = "../../../client/finality-grandpa" } diff --git a/substrate/bin/node/rpc/Cargo.toml b/substrate/bin/node/rpc/Cargo.toml index e9889854ee..d267118c12 100644 --- a/substrate/bin/node/rpc/Cargo.toml +++ b/substrate/bin/node/rpc/Cargo.toml @@ -12,5 +12,5 @@ node-runtime = { path = "../runtime" } sr-primitives = { path = "../../../primitives/sr-primitives" } pallet-contracts-rpc = { path = "../../../frame/contracts/rpc/" } pallet-transaction-payment-rpc = { path = "../../../frame/transaction-payment/rpc/" } -frame-system-rpc = { path = "../../../frame/system/rpc/" } -transaction_pool = { package = "substrate-transaction-pool", path = "../../../client/transaction-pool" } +substrate-frame-rpc-system = { path = "../../../utils/frame/rpc/system" } +transaction_pool = { package = "sc-transaction-pool", path = "../../../client/transaction-pool" } diff --git a/substrate/bin/node/rpc/src/lib.rs b/substrate/bin/node/rpc/src/lib.rs index 7f19af45e4..cb7aee283b 100644 --- a/substrate/bin/node/rpc/src/lib.rs +++ b/substrate/bin/node/rpc/src/lib.rs @@ -41,13 +41,13 @@ pub fn create(client: Arc, pool: Arc>) -> jsonrpc_core::IoHa C: ProvideRuntimeApi, C: client::blockchain::HeaderBackend, C: Send + Sync + 'static, - C::Api: frame_system_rpc::AccountNonceApi, + C::Api: substrate_frame_rpc_system::AccountNonceApi, C::Api: pallet_contracts_rpc::ContractsRuntimeApi, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, P: ChainApi + Sync + Send + 'static, M: jsonrpc_core::Metadata + Default, { - use frame_system_rpc::{System, SystemApi}; + use substrate_frame_rpc_system::{System, SystemApi}; use pallet_contracts_rpc::{Contracts, ContractsApi}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; diff --git a/substrate/client/Cargo.toml b/substrate/client/Cargo.toml index d7270dff37..b78812d882 100644 --- a/substrate/client/Cargo.toml +++ b/substrate/client/Cargo.toml @@ -15,7 +15,6 @@ externalities = { package = "substrate-externalities", path = "../primitives/ext fnv = { version = "1.0.6" } futures = { version = "0.3.1", features = ["compat"] } hash-db = { version = "0.15.2" } -header-metadata = { package = "substrate-header-metadata", path = "header-metadata" } hex-literal = { version = "0.2.1" } inherents = { package = "substrate-inherents", path = "../primitives/inherents" } keyring = { package = "substrate-keyring", path = "../primitives/keyring" } @@ -27,6 +26,7 @@ rstd = { package = "sr-std", path = "../primitives/sr-std" } runtime-version = { package = "sr-version", path = "../primitives/sr-version" } sr-api = { path = "../primitives/sr-api" } sr-primitives = { path = "../primitives/sr-primitives" } +sp-blockchain = { path = "../primitives/blockchain" } state-machine = { package = "substrate-state-machine", path = "../primitives/state-machine" } substrate-telemetry = { path = "telemetry" } trie = { package = "substrate-trie", path = "../primitives/trie" } diff --git a/substrate/client/api/Cargo.toml b/substrate/client/api/Cargo.toml index 6af1086586..ff83aa412b 100644 --- a/substrate/client/api/Cargo.toml +++ b/substrate/client/api/Cargo.toml @@ -14,7 +14,7 @@ externalities = { package = "substrate-externalities", path = "../../primitives/ fnv = { version = "1.0.6" } futures = { version = "0.3.1" } hash-db = { version = "0.15.2", default-features = false } -header-metadata = { package = "substrate-header-metadata", path = "../header-metadata" } +sp-blockchain = { path = "../../primitives/blockchain" } hex-literal = { version = "0.2.1" } inherents = { package = "substrate-inherents", path = "../../primitives/inherents", default-features = false } keyring = { package = "substrate-keyring", path = "../../primitives/keyring" } diff --git a/substrate/client/api/src/backend.rs b/substrate/client/api/src/backend.rs index e44325f088..220aede2f5 100644 --- a/substrate/client/api/src/backend.rs +++ b/substrate/client/api/src/backend.rs @@ -28,9 +28,9 @@ use crate::{ blockchain::{ Backend as BlockchainBackend, well_known_cache_keys }, - error, light::RemoteBlockchain, }; +use sp_blockchain; use consensus::BlockOrigin; use hash_db::Hasher; use parking_lot::RwLock; @@ -116,7 +116,7 @@ pub trait BlockImportOperation where /// Returns pending state. /// /// Returns None for backends with locally-unavailable state data. - fn state(&self) -> error::Result>; + fn state(&self) -> sp_blockchain::Result>; /// Append block data to the transaction. fn set_block_data( @@ -125,37 +125,37 @@ pub trait BlockImportOperation where body: Option>, justification: Option, state: NewBlockState, - ) -> error::Result<()>; + ) -> sp_blockchain::Result<()>; /// Update cached data. fn update_cache(&mut self, cache: HashMap>); /// Inject storage data into the database. - fn update_db_storage(&mut self, update: >::Transaction) -> error::Result<()>; + fn update_db_storage(&mut self, update: >::Transaction) -> sp_blockchain::Result<()>; /// Inject storage data into the database replacing any existing data. - fn reset_storage(&mut self, top: StorageOverlay, children: ChildrenStorageOverlay) -> error::Result; + fn reset_storage(&mut self, top: StorageOverlay, children: ChildrenStorageOverlay) -> sp_blockchain::Result; /// Set storage changes. fn update_storage( &mut self, update: StorageCollection, child_update: ChildStorageCollection, - ) -> error::Result<()>; + ) -> sp_blockchain::Result<()>; /// Inject changes trie data into the database. - fn update_changes_trie(&mut self, update: ChangesTrieTransaction>) -> error::Result<()>; + fn update_changes_trie(&mut self, update: ChangesTrieTransaction>) -> sp_blockchain::Result<()>; /// Insert auxiliary keys. /// /// Values are `None` if should be deleted. - fn insert_aux(&mut self, ops: I) -> error::Result<()> + fn insert_aux(&mut self, ops: I) -> sp_blockchain::Result<()> where I: IntoIterator, Option>)>; /// Mark a block as finalized. - fn mark_finalized(&mut self, id: BlockId, justification: Option) -> error::Result<()>; + fn mark_finalized(&mut self, id: BlockId, justification: Option) -> sp_blockchain::Result<()>; /// Mark a block as new head. If both block import and set head are specified, set head overrides block import's best block rule. - fn mark_head(&mut self, id: BlockId) -> error::Result<()>; + fn mark_head(&mut self, id: BlockId) -> sp_blockchain::Result<()>; } /// Finalize Facilities @@ -175,7 +175,7 @@ pub trait Finalizer, B: Backend, justification: Option, notify: bool, - ) -> error::Result<()>; + ) -> sp_blockchain::Result<()>; /// Finalize a block. @@ -196,7 +196,7 @@ pub trait Finalizer, B: Backend, justification: Option, notify: bool, - ) -> error::Result<()>; + ) -> sp_blockchain::Result<()>; } @@ -211,10 +211,10 @@ pub trait AuxStore { 'c: 'a, I: IntoIterator, D: IntoIterator, - >(&self, insert: I, delete: D) -> error::Result<()>; + >(&self, insert: I, delete: D) -> sp_blockchain::Result<()>; /// Query auxiliary data from key-value store. - fn get_aux(&self, key: &[u8]) -> error::Result>>; + fn get_aux(&self, key: &[u8]) -> sp_blockchain::Result>>; } /// Client backend. @@ -245,18 +245,18 @@ pub trait Backend: AuxStore + Send + Sync where /// Begin a new block insertion transaction with given parent block id. /// /// When constructing the genesis, this is called with all-zero hash. - fn begin_operation(&self) -> error::Result; + fn begin_operation(&self) -> sp_blockchain::Result; /// Note an operation to contain state transition. - fn begin_state_operation(&self, operation: &mut Self::BlockImportOperation, block: BlockId) -> error::Result<()>; + fn begin_state_operation(&self, operation: &mut Self::BlockImportOperation, block: BlockId) -> sp_blockchain::Result<()>; /// Commit block insertion. - fn commit_operation(&self, transaction: Self::BlockImportOperation) -> error::Result<()>; + fn commit_operation(&self, transaction: Self::BlockImportOperation) -> sp_blockchain::Result<()>; /// Finalize block with given Id. /// /// This should only be called if the parent of the given block has been finalized. - fn finalize_block(&self, block: BlockId, justification: Option) -> error::Result<()>; + fn finalize_block(&self, block: BlockId, justification: Option) -> sp_blockchain::Result<()>; /// Returns reference to blockchain backend. fn blockchain(&self) -> &Self::Blockchain; @@ -276,17 +276,17 @@ pub trait Backend: AuxStore + Send + Sync where } /// Returns state backend with post-state of given block. - fn state_at(&self, block: BlockId) -> error::Result; + fn state_at(&self, block: BlockId) -> sp_blockchain::Result; /// Destroy state and save any useful data, such as cache. - fn destroy_state(&self, _state: Self::State) -> error::Result<()> { + fn destroy_state(&self, _state: Self::State) -> sp_blockchain::Result<()> { Ok(()) } /// Attempts to revert the chain by `n` blocks. /// /// Returns the number of blocks that were successfully reverted. - fn revert(&self, n: NumberFor) -> error::Result>; + fn revert(&self, n: NumberFor) -> sp_blockchain::Result>; /// Insert auxiliary data into key-value store. fn insert_aux< @@ -295,12 +295,12 @@ pub trait Backend: AuxStore + Send + Sync where 'c: 'a, I: IntoIterator, D: IntoIterator, - >(&self, insert: I, delete: D) -> error::Result<()> + >(&self, insert: I, delete: D) -> sp_blockchain::Result<()> { AuxStore::insert_aux(self, insert, delete) } /// Query auxiliary data from key-value store. - fn get_aux(&self, key: &[u8]) -> error::Result>> { + fn get_aux(&self, key: &[u8]) -> sp_blockchain::Result>> { AuxStore::get_aux(self, key) } diff --git a/substrate/client/api/src/call_executor.rs b/substrate/client/api/src/call_executor.rs index 7327333633..11a18d2e01 100644 --- a/substrate/client/api/src/call_executor.rs +++ b/substrate/client/api/src/call_executor.rs @@ -31,7 +31,7 @@ use hash_db::Hasher; use primitives::{Blake2Hasher, NativeOrEncoded}; use sr_api::{ProofRecorder, InitializeBlock}; -use crate::error; +use sp_blockchain; /// Method call executor. pub trait CallExecutor @@ -53,7 +53,7 @@ where call_data: &[u8], strategy: ExecutionStrategy, extensions: Option, - ) -> Result, error::Error>; + ) -> Result, sp_blockchain::Error>; /// Execute a contextual call on top of state in a block of a given hash. /// @@ -62,7 +62,7 @@ where /// of the execution context. fn contextual_call< 'a, - IB: Fn() -> error::Result<()>, + IB: Fn() -> sp_blockchain::Result<()>, EM: Fn( Result, Self::Error>, Result, Self::Error> @@ -81,12 +81,12 @@ where native_call: Option, proof_recorder: &Option>, extensions: Option, - ) -> error::Result> where ExecutionManager: Clone; + ) -> sp_blockchain::Result> where ExecutionManager: Clone; /// Extract RuntimeVersion of given block /// /// No changes are made. - fn runtime_version(&self, id: &BlockId) -> Result; + fn runtime_version(&self, id: &BlockId) -> Result; /// Execute a call to a contract on top of given state. /// @@ -113,7 +113,7 @@ where (S::Transaction, H::Out), Option>> ), - error::Error, + sp_blockchain::Error, >; /// Execute a call to a contract on top of given state, gathering execution proof. @@ -125,7 +125,7 @@ where overlay: &mut OverlayedChanges, method: &str, call_data: &[u8] - ) -> Result<(Vec, StorageProof), error::Error> { + ) -> Result<(Vec, StorageProof), sp_blockchain::Error> { let trie_state = state.as_trie_backend() .ok_or_else(|| Box::new(state_machine::ExecutionError::UnableToGenerateProof) @@ -143,7 +143,7 @@ where overlay: &mut OverlayedChanges, method: &str, call_data: &[u8] - ) -> Result<(Vec, StorageProof), error::Error>; + ) -> Result<(Vec, StorageProof), sp_blockchain::Error>; /// Get runtime version if supported. fn native_runtime_version(&self) -> Option<&NativeVersion>; diff --git a/substrate/client/api/src/client.rs b/substrate/client/api/src/client.rs index 8b4343c327..73ce4f1080 100644 --- a/substrate/client/api/src/client.rs +++ b/substrate/client/api/src/client.rs @@ -27,7 +27,7 @@ use consensus::BlockOrigin; use crate::blockchain::Info; use crate::notifications::StorageEventStream; -use crate::error; +use sp_blockchain; /// Type that implements `futures::Stream` of block import events. pub type ImportNotifications = mpsc::UnboundedReceiver>; @@ -63,7 +63,7 @@ pub trait BlockchainEvents { &self, filter_keys: Option<&[StorageKey]>, child_filter_keys: Option<&[(StorageKey, Option>)]>, - ) -> error::Result>; + ) -> sp_blockchain::Result>; } /// Fetch block body by ID. @@ -71,14 +71,14 @@ pub trait BlockBody { /// Get block body by ID. Returns `None` if the body is not stored. fn block_body(&self, id: &BlockId - ) -> error::Result::Extrinsic>>>; + ) -> sp_blockchain::Result::Extrinsic>>>; } /// Provide a list of potential uncle headers for a given block. pub trait ProvideUncles { /// Gets the uncles of the block with `target_hash` going back `max_generation` ancestors. fn uncles(&self, target_hash: Block::Hash, max_generation: NumberFor) - -> error::Result>; + -> sp_blockchain::Result>; } /// Client info diff --git a/substrate/client/api/src/lib.rs b/substrate/client/api/src/lib.rs index 04abc86308..97d7fb2a02 100644 --- a/substrate/client/api/src/lib.rs +++ b/substrate/client/api/src/lib.rs @@ -18,20 +18,17 @@ #![warn(missing_docs)] pub mod backend; -pub mod blockchain; pub mod call_executor; pub mod client; -pub mod error; pub mod execution_extensions; pub mod light; pub mod notifications; -// TODO: avoid re-exports +pub use sp_blockchain as blockchain; pub use backend::*; -pub use blockchain::*; +pub use notifications::*; pub use call_executor::*; pub use client::*; -pub use error::*; pub use light::*; pub use notifications::*; @@ -40,9 +37,7 @@ pub use state_machine::{StorageProof, ExecutionStrategy}; /// Utility methods for the client. pub mod utils { - use super::HeaderBackend; - use header_metadata::HeaderMetadata; - use crate::error; + use sp_blockchain::{HeaderBackend, HeaderMetadata, Error}; use primitives::H256; use sr_primitives::traits::{Block as BlockT}; use std::borrow::Borrow; @@ -56,8 +51,8 @@ pub mod utils { pub fn is_descendent_of<'a, Block: BlockT, T, H: Borrow + 'a>( client: &'a T, current: Option<(H, H)>, - ) -> impl Fn(&H256, &H256) -> Result + 'a - where T: HeaderBackend + HeaderMetadata, + ) -> impl Fn(&H256, &H256) -> Result + 'a + where T: HeaderBackend + HeaderMetadata, { move |base, hash| { if base == hash { return Ok(false); } @@ -76,7 +71,7 @@ pub mod utils { } } - let ancestor = header_metadata::lowest_common_ancestor(client, *hash, *base)?; + let ancestor = sp_blockchain::lowest_common_ancestor(client, *hash, *base)?; Ok(ancestor.hash == *base) } diff --git a/substrate/client/api/src/light.rs b/substrate/client/api/src/light.rs index 433d1dbec1..d0206dbc40 100644 --- a/substrate/client/api/src/light.rs +++ b/substrate/client/api/src/light.rs @@ -28,16 +28,11 @@ use sr_primitives::{ }; use primitives::{ChangesTrieConfiguration}; use state_machine::StorageProof; -use header_metadata::HeaderMetadata; -use crate::{ - backend::{ - AuxStore, NewBlockState, - }, - blockchain::{ - well_known_cache_keys, HeaderBackend, Cache as BlockchainCache, - }, - error::{ Error as ClientError, Result as ClientResult }, +use sp_blockchain::{ + HeaderMetadata, well_known_cache_keys, HeaderBackend, Cache as BlockchainCache, + Error as ClientError, Result as ClientResult, }; +use crate::backend::{ AuxStore, NewBlockState }; /// Remote call request. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct RemoteCallRequest { @@ -288,7 +283,7 @@ pub trait RemoteBlockchain: Send + Sync { pub mod tests { use futures::future::Ready; use parking_lot::Mutex; - use crate::error::Error as ClientError; + use sp_blockchain::Error as ClientError; use test_primitives::{Block, Header, Extrinsic}; use super::*; diff --git a/substrate/client/authority-discovery/Cargo.toml b/substrate/client/authority-discovery/Cargo.toml index 5447119dc7..81cf48a720 100644 --- a/substrate/client/authority-discovery/Cargo.toml +++ b/substrate/client/authority-discovery/Cargo.toml @@ -21,12 +21,13 @@ libp2p = { version = "0.13.0", default-features = false, features = ["secp256k1" log = "0.4.8" network = { package = "substrate-network", path = "../network" } primitives = { package = "substrate-primitives", path = "../../primitives/core" } +sp-blockchain = { path = "../../primitives/blockchain" } prost = "0.5.0" serde_json = "1.0.41" sr-primitives = { path = "../../primitives/sr-primitives" } [dev-dependencies] parking_lot = "0.9.0" -peerset = { package = "substrate-peerset", path = "../../primitives/peerset" } +peerset = { package = "substrate-peerset", path = "../peerset" } test-client = { package = "substrate-test-runtime-client", path = "../../test/utils/runtime/client" } sr-api = { path = "../../primitives/sr-api" } diff --git a/substrate/client/authority-discovery/src/error.rs b/substrate/client/authority-discovery/src/error.rs index a05bc3b680..fdbd5b31fe 100644 --- a/substrate/client/authority-discovery/src/error.rs +++ b/substrate/client/authority-discovery/src/error.rs @@ -27,7 +27,7 @@ pub enum Error { /// Failed to hash the authority id to be used as a dht key. HashingAuthorityId(libp2p::core::multiaddr::multihash::EncodeError), /// Failed calling into the Substrate runtime. - CallingRuntime(client_api::error::Error), + CallingRuntime(sp_blockchain::Error), /// From the Dht we only get the hashed authority id. In order to retrieve the actual authority id and to ensure it /// is actually an authority, we match the hash against the hash of the authority id of all other authorities. This /// error is the result of the above failing. diff --git a/substrate/client/authority-discovery/src/lib.rs b/substrate/client/authority-discovery/src/lib.rs index 0c9d8e59ac..f404ad3c43 100644 --- a/substrate/client/authority-discovery/src/lib.rs +++ b/substrate/client/authority-discovery/src/lib.rs @@ -117,7 +117,7 @@ where Block: BlockT + Unpin + 'static, Network: NetworkProvider, Client: ProvideRuntimeApi + Send + Sync + 'static + HeaderBackend, - ::Api: AuthorityDiscoveryApi, + ::Api: AuthorityDiscoveryApi, Self: Future, { /// Return a new authority discovery. @@ -358,7 +358,7 @@ where Block: BlockT + Unpin + 'static, Network: NetworkProvider, Client: ProvideRuntimeApi + Send + Sync + 'static + HeaderBackend, - ::Api: AuthorityDiscoveryApi, + ::Api: AuthorityDiscoveryApi, { type Output = (); @@ -500,7 +500,7 @@ mod tests { fn header( &self, _id: BlockId, - ) -> std::result::Result, client_api::error::Error> { + ) -> std::result::Result, sp_blockchain::Error> { Ok(None) } @@ -517,21 +517,21 @@ mod tests { fn status( &self, _id: BlockId, - ) -> std::result::Result { + ) -> std::result::Result { Ok(client_api::blockchain::BlockStatus::Unknown) } fn number( &self, _hash: Block::Hash, - ) -> std::result::Result>, client_api::error::Error> { + ) -> std::result::Result>, sp_blockchain::Error> { Ok(None) } fn hash( &self, _number: NumberFor, - ) -> std::result::Result, client_api::error::Error> { + ) -> std::result::Result, sp_blockchain::Error> { Ok(None) } } @@ -547,7 +547,7 @@ mod tests { _: ExecutionContext, _: Option<()>, _: Vec, - ) -> std::result::Result, client_api::error::Error> { + ) -> std::result::Result, sp_blockchain::Error> { unimplemented!("Not required for testing!") } @@ -557,7 +557,7 @@ mod tests { _: ExecutionContext, _: Option<(Block)>, _: Vec, - ) -> std::result::Result, client_api::error::Error> { + ) -> std::result::Result, sp_blockchain::Error> { unimplemented!("Not required for testing!") } @@ -567,13 +567,13 @@ mod tests { _: ExecutionContext, _: Option<&::Header>, _: Vec, - ) -> std::result::Result, client_api::error::Error> { + ) -> std::result::Result, sp_blockchain::Error> { unimplemented!("Not required for testing!") } } impl ApiExt for RuntimeApi { - type Error = client_api::error::Error; + type Error = sp_blockchain::Error; fn map_api_result std::result::Result, R, E>( &self, @@ -585,7 +585,7 @@ mod tests { fn runtime_version_at( &self, _: &BlockId, - ) -> std::result::Result { + ) -> std::result::Result { unimplemented!("Not required for testing!") } @@ -605,7 +605,7 @@ mod tests { _: ExecutionContext, _: Option<()>, _: Vec, - ) -> std::result::Result>, client_api::error::Error> { + ) -> std::result::Result>, sp_blockchain::Error> { return Ok(NativeOrEncoded::Native(self.authorities.clone())); } } diff --git a/substrate/client/basic-authorship/Cargo.toml b/substrate/client/basic-authorship/Cargo.toml index 3732065f8c..852a9bbe78 100644 --- a/substrate/client/basic-authorship/Cargo.toml +++ b/substrate/client/basic-authorship/Cargo.toml @@ -10,12 +10,13 @@ futures = "0.3.1" codec = { package = "parity-scale-codec", version = "1.0.0" } sr-primitives = { path = "../../primitives/sr-primitives" } primitives = { package = "substrate-primitives", path = "../../primitives/core" } +sp-blockchain = { path = "../../primitives/blockchain" } client = { package = "substrate-client", path = "../" } client-api = { package = "substrate-client-api", path = "../api" } consensus_common = { package = "substrate-consensus-common", path = "../../primitives/consensus/common" } inherents = { package = "substrate-inherents", path = "../../primitives/inherents" } substrate-telemetry = { path = "../telemetry" } -transaction_pool = { package = "substrate-transaction-pool", path = "../transaction-pool" } +transaction_pool = { package = "sc-transaction-pool", path = "../../client/transaction-pool" } block-builder = { package = "substrate-block-builder", path = "../block-builder" } tokio-executor = { version = "0.2.0-alpha.6", features = ["blocking"] } diff --git a/substrate/client/basic-authorship/src/basic_authorship.rs b/substrate/client/basic-authorship/src/basic_authorship.rs index 10b3b2b1a1..46494ef4bb 100644 --- a/substrate/client/basic-authorship/src/basic_authorship.rs +++ b/substrate/client/basic-authorship/src/basic_authorship.rs @@ -19,7 +19,8 @@ // FIXME #1021 move this into substrate-consensus-common use std::{time, sync::Arc}; -use client_api::{error, CallExecutor}; +use client_api::CallExecutor; +use sp_blockchain; use client::Client as SubstrateClient; use codec::Decode; use consensus_common::{evaluation}; @@ -53,13 +54,13 @@ where RA: Send + Sync + 'static, SubstrateClient: ProvideRuntimeApi, as ProvideRuntimeApi>::Api: - BlockBuilderApi, + BlockBuilderApi, { pub fn init_with_now( &mut self, parent_header: &::Header, now: Box time::Instant + Send + Sync>, - ) -> Result, A>, error::Error> { + ) -> Result, A>, sp_blockchain::Error> { let parent_hash = parent_header.hash(); let id = BlockId::hash(parent_hash); @@ -91,15 +92,15 @@ where RA: Send + Sync + 'static, SubstrateClient: ProvideRuntimeApi, as ProvideRuntimeApi>::Api: - BlockBuilderApi, + BlockBuilderApi, { type Proposer = Proposer, A>; - type Error = error::Error; + type Error = sp_blockchain::Error; fn init( &mut self, parent_header: &::Header, - ) -> Result { + ) -> Result { self.init_with_now(parent_header, Box::new(time::Instant::now)) } } @@ -129,10 +130,10 @@ where RA: Send + Sync + 'static, SubstrateClient: ProvideRuntimeApi, as ProvideRuntimeApi>::Api: - BlockBuilderApi, + BlockBuilderApi, { - type Create = tokio_executor::blocking::Blocking>; - type Error = error::Error; + type Create = tokio_executor::blocking::Blocking>; + type Error = sp_blockchain::Error; fn propose( &mut self, @@ -157,14 +158,14 @@ impl ProposerInner, RA: Send + Sync + 'static, SubstrateClient: ProvideRuntimeApi, as ProvideRuntimeApi>::Api: - BlockBuilderApi, + BlockBuilderApi, { fn propose_with( &self, inherent_data: InherentData, inherent_digests: DigestFor, deadline: time::Instant, - ) -> Result { + ) -> Result { /// If the block is full we will attempt to push at most /// this number of transactions before quitting for real. /// It allows us to increase block utilization. @@ -202,7 +203,8 @@ impl ProposerInner, Ok(()) => { debug!("[{:?}] Pushed to the block.", pending.hash); } - Err(error::Error::ApplyExtrinsicFailed(e)) if e.exhausted_resources() => { + Err(sp_blockchain::Error::ApplyExtrinsicFailed(sp_blockchain::ApplyExtrinsicFailed::Validity(e))) + if e.exhausted_resources() => { if is_first { debug!("[{:?}] Invalid transaction: FullBlock on empty block", pending.hash); unqueue_invalid.push(pending.hash.clone()); diff --git a/substrate/client/block-builder/Cargo.toml b/substrate/client/block-builder/Cargo.toml index 34bfac17bf..7b39643aa5 100644 --- a/substrate/client/block-builder/Cargo.toml +++ b/substrate/client/block-builder/Cargo.toml @@ -7,6 +7,7 @@ edition = "2018" [dependencies] state-machine = { package = "substrate-state-machine", path = "../../primitives/state-machine" } sr-primitives = { path = "../../primitives/sr-primitives" } +sp-blockchain = { path = "../../primitives/blockchain" } primitives = { package = "substrate-primitives", path = "../../primitives/core" } codec = { package = "parity-scale-codec", version = "1.0.6", features = ["derive"] } runtime_api = { package = "substrate-block-builder-runtime-api", path = "../../primitives/block-builder/runtime-api" } diff --git a/substrate/client/block-builder/src/lib.rs b/substrate/client/block-builder/src/lib.rs index f6e793dce7..6978473645 100644 --- a/substrate/client/block-builder/src/lib.rs +++ b/substrate/client/block-builder/src/lib.rs @@ -17,7 +17,7 @@ //! Substrate block builder //! //! This crate provides the [`BlockBuilder`] utility and the corresponding runtime api -//! [`BlockBuilder`](api::BlockBuilder). +//! [`BlockBuilder`](api::BlockBuilder).Error //! //! The block builder utility is used in the node as an abstraction over the runtime api to //! initialize a block, to push extrinsics and to finalize a block. @@ -31,42 +31,15 @@ use sr_primitives::{ traits::{ Header as HeaderT, Hash, Block as BlockT, HashFor, ProvideRuntimeApi, ApiRef, DigestFor, NumberFor, One, - }, - transaction_validity::TransactionValidityError, + } }; - +use sp_blockchain::{ApplyExtrinsicFailed, Error}; use primitives::ExecutionContext; use state_machine::StorageProof; use sr_api::{Core, ApiExt, ApiErrorFor}; -#[allow(deprecated)] -use runtime_api::compatability_v3; - pub use runtime_api::BlockBuilder as BlockBuilderApi; -/// Error when the runtime failed to apply an extrinsic. -pub enum ApplyExtrinsicFailed { - /// The transaction cannot be included into the current block. - /// - /// This doesn't necessary mean that the transaction itself is invalid, but it might be just - /// unappliable onto the current block. - Validity(TransactionValidityError), - /// This is used for miscelanious errors that can be represented by string and not handleable. - /// - /// This will become obsolete with complete migration to v4 APIs. - Msg(String), -} - -#[allow(deprecated)] -impl From for ApplyExtrinsicFailed { - fn from(e: compatability_v3::ApplyError) -> Self { - use self::compatability_v3::ApplyError::*; - match e { - Validity(tx_validity) => Self::Validity(tx_validity), - e => Self::Msg(format!("Apply extrinsic failed: {:?}", e)), - } - } -} /// Utility for building new (valid) blocks from a stream of extrinsics. pub struct BlockBuilder<'a, Block: BlockT, A: ProvideRuntimeApi> { @@ -81,7 +54,7 @@ where Block: BlockT, A: ProvideRuntimeApi + 'a, A::Api: BlockBuilderApi, - ApiErrorFor: From, + ApiErrorFor: From, { /// Create a new instance of builder based on the given `parent_hash` and `parent_number`. /// @@ -149,7 +122,7 @@ where extrinsics.push(xt); Ok(()) } - Err(e) => Err(ApplyExtrinsicFailed::from(e))?, + Err(e) => Err(ApplyExtrinsicFailed::from(e).into())?, } }) } else { @@ -163,7 +136,7 @@ where extrinsics.push(xt); Ok(()) } - Err(tx_validity) => Err(ApplyExtrinsicFailed::Validity(tx_validity))?, + Err(tx_validity) => Err(ApplyExtrinsicFailed::Validity(tx_validity).into())?, } }) } diff --git a/substrate/client/cli/Cargo.toml b/substrate/client/cli/Cargo.toml index a2b5940e74..ef6134822e 100644 --- a/substrate/client/cli/Cargo.toml +++ b/substrate/client/cli/Cargo.toml @@ -23,7 +23,7 @@ fdlimit = "0.1.1" serde_json = "1.0.41" panic-handler = { package = "substrate-panic-handler", path = "../../primitives/panic-handler" } client-api = { package = "substrate-client-api", path = "../api" } -header-metadata = { package = "substrate-header-metadata", path = "../header-metadata" } +sp-blockchain = { path = "../../primitives/blockchain" } network = { package = "substrate-network", path = "../network" } sr-primitives = { path = "../../primitives/sr-primitives" } primitives = { package = "substrate-primitives", path = "../../primitives/core" } diff --git a/substrate/client/cli/src/error.rs b/substrate/client/cli/src/error.rs index ab07c0e842..bec3aa1ec7 100644 --- a/substrate/client/cli/src/error.rs +++ b/substrate/client/cli/src/error.rs @@ -16,8 +16,6 @@ //! Initialization errors. -use client_api; - /// Result type alias for the CLI. pub type Result = std::result::Result; @@ -31,7 +29,7 @@ pub enum Error { /// Service error Service(service::Error), /// Client error - Client(client_api::error::Error), + Client(sp_blockchain::Error), /// Input error #[from(ignore)] Input(String), diff --git a/substrate/client/cli/src/informant.rs b/substrate/client/cli/src/informant.rs index 2f32f95b67..46dca3e54c 100644 --- a/substrate/client/cli/src/informant.rs +++ b/substrate/client/cli/src/informant.rs @@ -50,7 +50,7 @@ pub fn build(service: &impl AbstractService) -> impl futures::Future, + C::Api: AuraApi, { slots::SlotDuration::get_or_compute(client, |a, b| a.slot_duration(b)).map(Self) } @@ -340,7 +343,7 @@ enum Error { BadSignature(B::Hash), #[display(fmt = "Rejecting block too far in future")] TooFarInFuture, - Client(client::error::Error), + Client(sp_blockchain::Error), DataProvider(String), Runtime(String), } @@ -448,7 +451,7 @@ impl AuraVerifier inherent_data: InherentData, timestamp_now: u64, ) -> Result<(), Error> - where C: ProvideRuntimeApi, C::Api: BlockBuilderApi + where C: ProvideRuntimeApi, C::Api: BlockBuilderApi { const MAX_TIMESTAMP_DRIFT_SECS: u64 = 60; @@ -495,7 +498,7 @@ impl AuraVerifier #[forbid(deprecated)] impl Verifier for AuraVerifier where C: ProvideRuntimeApi + Send + Sync + client_api::backend::AuxStore + ProvideCache + BlockOf, - C::Api: BlockBuilderApi + AuraApi> + ApiExt, + C::Api: BlockBuilderApi + AuraApi> + ApiExt, DigestItemFor: CompatibleDigestItem

, P: Pair + Send + Sync + 'static, P::Public: Send + Sync + Hash + Eq + Clone + Decode + Encode + Debug + 'static, @@ -682,7 +685,7 @@ pub fn import_queue( ) -> Result, consensus_common::Error> where B: BlockT, C: 'static + ProvideRuntimeApi + BlockOf + ProvideCache + Send + Sync + AuxStore, - C::Api: BlockBuilderApi + AuraApi> + ApiExt, + C::Api: BlockBuilderApi + AuraApi> + ApiExt, DigestItemFor: CompatibleDigestItem

, P: Pair + Send + Sync + 'static, P::Public: Clone + Eq + Send + Sync + Hash + Debug + Encode + Decode, @@ -721,7 +724,7 @@ mod tests { use test_client; use aura_primitives::sr25519::AuthorityPair; - type Error = client::error::Error; + type Error = sp_blockchain::Error; type TestClient = client::Client< test_client::Backend, diff --git a/substrate/client/consensus/babe/Cargo.toml b/substrate/client/consensus/babe/Cargo.toml index 2baf4835d8..a9dd0c5890 100644 --- a/substrate/client/consensus/babe/Cargo.toml +++ b/substrate/client/consensus/babe/Cargo.toml @@ -23,7 +23,7 @@ client-api = { package = "substrate-client-api", path = "../../api" } client = { package = "substrate-client", path = "../../" } sr-api = { path = "../../../primitives/sr-api" } block-builder-api = { package = "substrate-block-builder-runtime-api", path = "../../../primitives/block-builder/runtime-api" } -header-metadata = { package = "substrate-header-metadata", path = "../../header-metadata" } +sp-blockchain = { path = "../../../primitives/blockchain" } consensus-common = { package = "substrate-consensus-common", path = "../../../primitives/consensus/common" } uncles = { package = "substrate-consensus-uncles", path = "../uncles" } slots = { package = "substrate-consensus-slots", path = "../slots" } diff --git a/substrate/client/consensus/babe/src/aux_schema.rs b/substrate/client/consensus/babe/src/aux_schema.rs index 04e9f81e5c..288f20db97 100644 --- a/substrate/client/consensus/babe/src/aux_schema.rs +++ b/substrate/client/consensus/babe/src/aux_schema.rs @@ -19,10 +19,8 @@ use log::info; use codec::{Decode, Encode}; -use client_api::{ - backend::AuxStore, - error::{Result as ClientResult, Error as ClientError}, -}; +use client_api::backend::AuxStore; +use sp_blockchain::{Result as ClientResult, Error as ClientError}; use sr_primitives::traits::Block as BlockT; use babe_primitives::BabeBlockWeight; diff --git a/substrate/client/consensus/babe/src/epoch_changes.rs b/substrate/client/consensus/babe/src/epoch_changes.rs index a5621efcd1..a07235c4ff 100644 --- a/substrate/client/consensus/babe/src/epoch_changes.rs +++ b/substrate/client/consensus/babe/src/epoch_changes.rs @@ -25,12 +25,8 @@ use fork_tree::ForkTree; use parking_lot::{Mutex, MutexGuard}; use sr_primitives::traits::{Block as BlockT, NumberFor, One, Zero}; use codec::{Encode, Decode}; -use client_api::{ - error::Error as ClientError, - utils::is_descendent_of, - blockchain::HeaderBackend -}; -use header_metadata::HeaderMetadata; +use client_api::utils::is_descendent_of; +use sp_blockchain::{HeaderMetadata, HeaderBackend, Error as ClientError}; use primitives::H256; use std::ops::Add; diff --git a/substrate/client/consensus/babe/src/lib.rs b/substrate/client/consensus/babe/src/lib.rs index 5d327bcedf..3fd1e526d4 100644 --- a/substrate/client/consensus/babe/src/lib.rs +++ b/substrate/client/consensus/babe/src/lib.rs @@ -90,8 +90,6 @@ use consensus_common::import_queue::{Verifier, BasicQueue, CacheKeyId}; use client_api::{ backend::{AuxStore, Backend}, call_executor::CallExecutor, - error::{Result as ClientResult, Error as ClientError}, - blockchain::{self, HeaderBackend, ProvideCache}, BlockchainEvents, ProvideUncles, }; use client::Client; @@ -103,7 +101,10 @@ use futures::prelude::*; use log::{warn, debug, info, trace}; use slots::{SlotWorker, SlotData, SlotInfo, SlotCompatible}; use epoch_changes::descendent_query; -use header_metadata::HeaderMetadata; +use sp_blockchain::{ + Result as ClientResult, Error as ClientError, + HeaderBackend, ProvideCache, HeaderMetadata +}; use schnorrkel::SignatureError; use sr_api::ApiExt; @@ -157,11 +158,11 @@ enum Error { #[display(fmt = "VRF verification failed: {:?}", _0)] VRFVerificationFailed(SignatureError), #[display(fmt = "Could not fetch parent header: {:?}", _0)] - FetchParentHeader(client_api::error::Error), + FetchParentHeader(sp_blockchain::Error), #[display(fmt = "Expected epoch change to happen at {:?}, s{}", _0, _1)] ExpectedEpochChange(B::Hash, u64), #[display(fmt = "Could not look up epoch: {:?}", _0)] - CouldNotLookUpEpoch(Box>), + CouldNotLookUpEpoch(Box>), #[display(fmt = "Block {} is not valid under any epoch.", _0)] BlockNotValid(B::Hash), #[display(fmt = "Unexpected epoch change")] @@ -170,9 +171,9 @@ enum Error { ParentBlockNoAssociatedWeight(B::Hash), #[display(fmt = "Checking inherents failed: {}", _0)] CheckInherents(String), - Client(client_api::error::Error), + Client(sp_blockchain::Error), Runtime(inherents::Error), - ForkTree(Box>), + ForkTree(Box>), } impl std::convert::From> for String { @@ -206,7 +207,7 @@ impl Config { /// Either fetch the slot duration from disk or compute it from the genesis /// state. pub fn get_or_compute(client: &C) -> ClientResult where - C: AuxStore + ProvideRuntimeApi, C::Api: BabeApi, + C: AuxStore + ProvideRuntimeApi, C::Api: BabeApi, { trace!(target: "babe", "Getting slot duration"); match slots::SlotDuration::get_or_compute(client, |a, b| a.configuration(b)).map(Self) { @@ -558,7 +559,7 @@ impl BabeVerifier { block_id: BlockId, inherent_data: InherentData, ) -> Result<(), Error> - where PRA: ProvideRuntimeApi, PRA::Api: BlockBuilderApi + where PRA: ProvideRuntimeApi, PRA::Api: BlockBuilderApi { let inherent_res = self.api.runtime_api().check_inherents( &block_id, @@ -627,8 +628,8 @@ impl Verifier for BabeVerifier + 'static + Clone + Send + Sync, RA: Send + Sync, PRA: ProvideRuntimeApi + Send + Sync + AuxStore + ProvideCache, - PRA::Api: BlockBuilderApi - + BabeApi, + PRA::Api: BlockBuilderApi + + BabeApi, { fn verify( &mut self, @@ -851,8 +852,8 @@ impl BlockImport for BabeBlockImport return Ok(ImportResult::AlreadyInChain), - Ok(blockchain::BlockStatus::Unknown) => {}, + Ok(sp_blockchain::BlockStatus::InChain) => return Ok(ImportResult::AlreadyInChain), + Ok(sp_blockchain::BlockStatus::Unknown) => {}, Err(e) => return Err(ConsensusError::ClientImport(e.to_string())), } @@ -907,7 +908,7 @@ impl BlockImport for BabeBlockImport| ConsensusError::ChainLookup( + .map_err(|e: fork_tree::Error| ConsensusError::ChainLookup( babe_err(Error::::CouldNotLookUpEpoch(Box::new(e))).into() ))? .ok_or_else(|| ConsensusError::ClientImport( @@ -1146,7 +1147,7 @@ pub fn import_queue, I, RA, PRA>( E: CallExecutor + Clone + Send + Sync + 'static, RA: Send + Sync + 'static, PRA: ProvideRuntimeApi + ProvideCache + Send + Sync + AuxStore + 'static, - PRA::Api: BlockBuilderApi + BabeApi + ApiExt, + PRA::Api: BlockBuilderApi + BabeApi + ApiExt, { register_babe_inherent_data_provider(&inherent_data_providers, babe_link.config.slot_duration)?; diff --git a/substrate/client/consensus/babe/src/tests.rs b/substrate/client/consensus/babe/src/tests.rs index 19c5844511..4695eb721f 100644 --- a/substrate/client/consensus/babe/src/tests.rs +++ b/substrate/client/consensus/babe/src/tests.rs @@ -41,7 +41,7 @@ use std::{time::Duration, cell::RefCell}; type Item = DigestItem; -type Error = client::error::Error; +type Error = sp_blockchain::Error; type TestClient = client::Client< test_client::Backend, diff --git a/substrate/client/consensus/pow/Cargo.toml b/substrate/client/consensus/pow/Cargo.toml index 8ed1af9923..acdfb9e843 100644 --- a/substrate/client/consensus/pow/Cargo.toml +++ b/substrate/client/consensus/pow/Cargo.toml @@ -8,6 +8,7 @@ edition = "2018" [dependencies] codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] } primitives = { package = "substrate-primitives", path = "../../../primitives/core" } +sp-blockchain = { path = "../../../primitives/blockchain" } sr-primitives = { path = "../../../primitives/sr-primitives" } client-api = { package = "substrate-client-api", path = "../../api" } block-builder-api = { package = "substrate-block-builder-runtime-api", path = "../../../primitives/block-builder/runtime-api" } diff --git a/substrate/client/consensus/pow/src/lib.rs b/substrate/client/consensus/pow/src/lib.rs index cb3f23fbf5..1daa9c4eae 100644 --- a/substrate/client/consensus/pow/src/lib.rs +++ b/substrate/client/consensus/pow/src/lib.rs @@ -32,10 +32,8 @@ use std::sync::Arc; use std::thread; use std::collections::HashMap; -use client_api::{ - BlockOf, blockchain::{HeaderBackend, ProvideCache}, backend::AuxStore, - well_known_cache_keys::Id as CacheKeyId, -}; +use client_api::{BlockOf, backend::AuxStore}; +use sp_blockchain::{HeaderBackend, ProvideCache, well_known_cache_keys::Id as CacheKeyId}; use block_builder_api::BlockBuilder as BlockBuilderApi; use sr_primitives::{Justification, RuntimeString}; use sr_primitives::generic::{BlockId, Digest, DigestItem}; @@ -66,7 +64,7 @@ pub enum Error { #[display(fmt = "Fetching best header failed using select chain: {:?}", _0)] BestHeaderSelectChain(ConsensusError), #[display(fmt = "Fetching best header failed: {:?}", _0)] - BestHeader(client_api::error::Error), + BestHeader(sp_blockchain::Error), #[display(fmt = "Best header does not exist")] NoBestHeader, #[display(fmt = "Block proposing error: {:?}", _0)] @@ -79,7 +77,7 @@ pub enum Error { CreateInherents(inherents::Error), #[display(fmt = "Checking inherents failed: {}", _0)] CheckInherents(String), - Client(client_api::error::Error), + Client(sp_blockchain::Error), Codec(codec::Error), Environment(String), Runtime(RuntimeString) @@ -211,7 +209,7 @@ impl, C, S, Algorithm> PowVerifier { inherent_data: InherentData, timestamp_now: u64, ) -> Result<(), Error> where - C: ProvideRuntimeApi, C::Api: BlockBuilderApi + C: ProvideRuntimeApi, C::Api: BlockBuilderApi { const MAX_TIMESTAMP_DRIFT_SECS: u64 = 60; @@ -249,7 +247,7 @@ impl, C, S, Algorithm> PowVerifier { impl, C, S, Algorithm> Verifier for PowVerifier where C: ProvideRuntimeApi + Send + Sync + HeaderBackend + AuxStore + ProvideCache + BlockOf, - C::Api: BlockBuilderApi, + C::Api: BlockBuilderApi, S: SelectChain, Algorithm: PowAlgorithm + Send + Sync, { @@ -341,7 +339,7 @@ pub fn import_queue( B: BlockT, C: ProvideRuntimeApi + HeaderBackend + BlockOf + ProvideCache + AuxStore, C: Send + Sync + AuxStore + 'static, - C::Api: BlockBuilderApi, + C::Api: BlockBuilderApi, Algorithm: PowAlgorithm + Send + Sync + 'static, S: SelectChain + 'static, { diff --git a/substrate/client/consensus/slots/Cargo.toml b/substrate/client/consensus/slots/Cargo.toml index 6218d965c7..083ecdae11 100644 --- a/substrate/client/consensus/slots/Cargo.toml +++ b/substrate/client/consensus/slots/Cargo.toml @@ -10,6 +10,7 @@ build = "build.rs" codec = { package = "parity-scale-codec", version = "1.0.0" } client-api = { package = "substrate-client-api", path = "../../api" } primitives = { package = "substrate-primitives", path = "../../../primitives/core" } +sp-blockchain = { path = "../../../primitives/blockchain" } sr-primitives = { path = "../../../primitives/sr-primitives" } substrate-telemetry = { path = "../../telemetry" } consensus_common = { package = "substrate-consensus-common", path = "../../../primitives/consensus/common" } diff --git a/substrate/client/consensus/slots/src/aux_schema.rs b/substrate/client/consensus/slots/src/aux_schema.rs index 1e777f35a1..21e4d1256f 100644 --- a/substrate/client/consensus/slots/src/aux_schema.rs +++ b/substrate/client/consensus/slots/src/aux_schema.rs @@ -18,7 +18,7 @@ use codec::{Encode, Decode}; use client_api::backend::AuxStore; -use client_api::error::{Result as ClientResult, Error as ClientError}; +use sp_blockchain::{Result as ClientResult, Error as ClientError}; use sr_primitives::traits::Header; const SLOT_HEADER_MAP_KEY: &[u8] = b"slot_header_map"; diff --git a/substrate/client/consensus/slots/src/lib.rs b/substrate/client/consensus/slots/src/lib.rs index e3001ce050..a26f8ec6b9 100644 --- a/substrate/client/consensus/slots/src/lib.rs +++ b/substrate/client/consensus/slots/src/lib.rs @@ -401,17 +401,17 @@ impl SlotDuration { /// /// `slot_key` is marked as `'static`, as it should really be a /// compile-time constant. - pub fn get_or_compute(client: &C, cb: CB) -> client_api::error::Result where + pub fn get_or_compute(client: &C, cb: CB) -> sp_blockchain::Result where C: client_api::backend::AuxStore, C: ProvideRuntimeApi, - CB: FnOnce(ApiRef, &BlockId) -> client_api::error::Result, + CB: FnOnce(ApiRef, &BlockId) -> sp_blockchain::Result, T: SlotData + Encode + Decode + Debug, { match client.get_aux(T::SLOT_KEY)? { Some(v) => ::decode(&mut &v[..]) .map(SlotDuration) .map_err(|_| { - client_api::error::Error::Backend({ + sp_blockchain::Error::Backend({ error!(target: "slots", "slot duration kept in invalid format"); "slot duration kept in invalid format".to_string() }) diff --git a/substrate/client/db/Cargo.toml b/substrate/client/db/Cargo.toml index bafeee970b..67372757a6 100644 --- a/substrate/client/db/Cargo.toml +++ b/substrate/client/db/Cargo.toml @@ -23,7 +23,7 @@ executor = { package = "substrate-executor", path = "../executor" } state_db = { package = "substrate-state-db", path = "../state-db" } trie = { package = "substrate-trie", path = "../../primitives/trie" } consensus_common = { package = "substrate-consensus-common", path = "../../primitives/consensus/common" } -header_metadata = { package = "substrate-header-metadata", path = "../header-metadata" } +sp-blockchain = { path = "../../primitives/blockchain" } [dev-dependencies] substrate-keyring = { path = "../../primitives/keyring" } diff --git a/substrate/client/db/src/cache/list_cache.rs b/substrate/client/db/src/cache/list_cache.rs index a51e6045c0..a36321df16 100644 --- a/substrate/client/db/src/cache/list_cache.rs +++ b/substrate/client/db/src/cache/list_cache.rs @@ -43,7 +43,7 @@ use std::collections::{BTreeSet, BTreeMap}; use log::warn; -use client_api::error::{Error as ClientError, Result as ClientResult}; +use sp_blockchain::{Error as ClientError, Result as ClientResult}; use sr_primitives::traits::{ Block as BlockT, NumberFor, Zero, Bounded, CheckedSub }; diff --git a/substrate/client/db/src/cache/list_entry.rs b/substrate/client/db/src/cache/list_entry.rs index afb2899362..b596863061 100644 --- a/substrate/client/db/src/cache/list_entry.rs +++ b/substrate/client/db/src/cache/list_entry.rs @@ -16,7 +16,7 @@ //! List-cache storage entries. -use client_api::error::Result as ClientResult; +use sp_blockchain::Result as ClientResult; use sr_primitives::traits::{Block as BlockT, NumberFor}; use codec::{Encode, Decode}; diff --git a/substrate/client/db/src/cache/list_storage.rs b/substrate/client/db/src/cache/list_storage.rs index d689619053..0615ae6aee 100644 --- a/substrate/client/db/src/cache/list_storage.rs +++ b/substrate/client/db/src/cache/list_storage.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use kvdb::{KeyValueDB, DBTransaction}; -use client_api::error::{Error as ClientError, Result as ClientResult}; +use sp_blockchain::{Error as ClientError, Result as ClientResult}; use codec::{Encode, Decode}; use sr_primitives::generic::BlockId; use sr_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor}; diff --git a/substrate/client/db/src/cache/mod.rs b/substrate/client/db/src/cache/mod.rs index b3ff1a4ea6..068acb37ec 100644 --- a/substrate/client/db/src/cache/mod.rs +++ b/substrate/client/db/src/cache/mod.rs @@ -22,7 +22,7 @@ use parking_lot::RwLock; use kvdb::{KeyValueDB, DBTransaction}; use client_api::blockchain::{well_known_cache_keys::{self, Id as CacheKeyId}, Cache as BlockchainCache}; -use client_api::error::Result as ClientResult; +use sp_blockchain::Result as ClientResult; use codec::{Encode, Decode}; use sr_primitives::generic::BlockId; use sr_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor, Zero}; @@ -211,7 +211,7 @@ impl<'a, Block: BlockT> DbCacheTransaction<'a, Block> { .cloned() .collect::>(); - let mut insert_op = |name: CacheKeyId, value: Option>| -> Result<(), client_api::error::Error> { + let mut insert_op = |name: CacheKeyId, value: Option>| -> Result<(), sp_blockchain::Error> { let cache = self.cache.get_cache(name); let op = cache.on_block_insert( &mut self::list_storage::DbStorageTransaction::new( diff --git a/substrate/client/db/src/children.rs b/substrate/client/db/src/children.rs index f6dd7299e4..db0469098b 100644 --- a/substrate/client/db/src/children.rs +++ b/substrate/client/db/src/children.rs @@ -18,7 +18,7 @@ use kvdb::{KeyValueDB, DBTransaction}; use codec::{Encode, Decode}; -use client_api::error; +use sp_blockchain; use std::hash::Hash; @@ -26,13 +26,13 @@ use std::hash::Hash; pub fn read_children< K: Eq + Hash + Clone + Encode + Decode, V: Eq + Hash + Clone + Encode + Decode, ->(db: &dyn KeyValueDB, column: Option, prefix: &[u8], parent_hash: K) -> error::Result> { +>(db: &dyn KeyValueDB, column: Option, prefix: &[u8], parent_hash: K) -> sp_blockchain::Result> { let mut buf = prefix.to_vec(); parent_hash.using_encoded(|s| buf.extend(s)); let raw_val_opt = match db.get(column, &buf[..]) { Ok(raw_val_opt) => raw_val_opt, - Err(_) => return Err(error::Error::Backend("Error reading value from database".into())), + Err(_) => return Err(sp_blockchain::Error::Backend("Error reading value from database".into())), }; let raw_val = match raw_val_opt { @@ -42,7 +42,7 @@ pub fn read_children< let children: Vec = match Decode::decode(&mut &raw_val[..]) { Ok(children) => children, - Err(_) => return Err(error::Error::Backend("Error decoding children".into())), + Err(_) => return Err(sp_blockchain::Error::Backend("Error decoding children".into())), }; Ok(children) diff --git a/substrate/client/db/src/lib.rs b/substrate/client/db/src/lib.rs index 1de3eea9b9..dceffc852a 100644 --- a/substrate/client/db/src/lib.rs +++ b/substrate/client/db/src/lib.rs @@ -39,12 +39,13 @@ use std::path::PathBuf; use std::io; use std::collections::{HashMap, HashSet}; -use client_api::ForkBlocks; +use client_api::{execution_extensions::ExecutionExtensions, ForkBlocks}; use client_api::backend::NewBlockState; use client_api::backend::{StorageCollection, ChildStorageCollection}; -use client_api::blockchain::{well_known_cache_keys, HeaderBackend}; -use client_api::error::{Result as ClientResult, Error as ClientError}; -use client_api::execution_extensions::ExecutionExtensions; +use sp_blockchain::{ + Result as ClientResult, Error as ClientError, + well_known_cache_keys, HeaderBackend, +}; use codec::{Decode, Encode}; use hash_db::{Hasher, Prefix}; use kvdb::{KeyValueDB, DBTransaction}; @@ -67,7 +68,7 @@ use state_machine::{ use crate::utils::{Meta, db_err, meta_keys, read_db, read_meta}; use client::leaves::{LeafSet, FinalizationDisplaced}; use state_db::StateDb; -use header_metadata::{CachedHeaderMetadata, HeaderMetadata, HeaderMetadataCache}; +use sp_blockchain::{CachedHeaderMetadata, HeaderMetadata, HeaderMetadataCache}; use crate::storage_cache::{CachingState, SharedCache, new_shared_cache}; use log::{trace, debug, warn}; pub use state_db::PruningMode; @@ -239,7 +240,7 @@ pub fn new_client( >, Arc>, ), - client::error::Error, + sp_blockchain::Error, > where Block: BlockT, @@ -381,7 +382,7 @@ impl client::blockchain::Backend for BlockchainDb { match read_db(&*self.db, columns::KEY_LOOKUP, columns::BODY, id)? { Some(body) => match Decode::decode(&mut &body[..]) { Ok(body) => Ok(Some(body)), - Err(err) => return Err(client::error::Error::Backend( + Err(err) => return Err(sp_blockchain::Error::Backend( format!("Error decoding body: {}", err) )), } @@ -393,7 +394,7 @@ impl client::blockchain::Backend for BlockchainDb { match read_db(&*self.db, columns::KEY_LOOKUP, columns::JUSTIFICATION, id)? { Some(justification) => match Decode::decode(&mut &justification[..]) { Ok(justification) => Ok(Some(justification)), - Err(err) => return Err(client::error::Error::Backend( + Err(err) => return Err(sp_blockchain::Error::Backend( format!("Error decoding justification: {}", err) )), } @@ -425,7 +426,7 @@ impl client::blockchain::ProvideCache for BlockchainDb HeaderMetadata for BlockchainDb { - type Error = client::error::Error; + type Error = sp_blockchain::Error; fn header_metadata(&self, hash: Block::Hash) -> Result, Self::Error> { self.header_metadata_cache.header_metadata(hash).or_else(|_| { @@ -517,12 +518,12 @@ impl client_api::backend::BlockImportOperation ) -> ClientResult { if top.iter().any(|(k, _)| well_known_keys::is_child_storage_key(k)) { - return Err(client::error::Error::GenesisInvalid.into()); + return Err(sp_blockchain::Error::GenesisInvalid.into()); } for child_key in children.keys() { if !well_known_keys::is_child_storage_key(&child_key) { - return Err(client::error::Error::GenesisInvalid.into()); + return Err(sp_blockchain::Error::GenesisInvalid.into()); } } @@ -823,7 +824,7 @@ impl> Backend { let is_archive_pruning = config.pruning.is_archive(); let blockchain = BlockchainDb::new(db.clone())?; let meta = blockchain.meta.clone(); - let map_e = |e: state_db::Error| ::client::error::Error::from(format!("State database error: {:?}", e)); + let map_e = |e: state_db::Error| ::sp_blockchain::Error::from(format!("State database error: {:?}", e)); let state_db: StateDb<_, _> = StateDb::new(config.pruning.clone(), &StateMetaDb(&*db)).map_err(map_e)?; let storage_db = StorageDb { db: db.clone(), @@ -948,7 +949,7 @@ impl> Backend { // cannot find tree route with empty DB. if meta.best_hash != Default::default() { - let tree_route = header_metadata::tree_route( + let tree_route = sp_blockchain::tree_route( &self.blockchain, meta.best_hash, route_to, @@ -963,7 +964,7 @@ impl> Backend { (&r.number, &r.hash) ); - return Err(::client::error::Error::NotInFinalizedChain.into()); + return Err(::sp_blockchain::Error::NotInFinalizedChain.into()); } retracted.push(r.hash.clone()); @@ -1005,7 +1006,7 @@ impl> Backend { ) -> ClientResult<()> { let last_finalized = last_finalized.unwrap_or_else(|| self.blockchain.meta.read().finalized_hash); if *header.parent_hash() != last_finalized { - return Err(::client::error::Error::NonSequentialFinalization( + return Err(::sp_blockchain::Error::NonSequentialFinalization( format!("Last finalized {:?} not parent of {:?}", last_finalized, header.hash()), ).into()); } @@ -1068,7 +1069,7 @@ impl> Backend { trace!(target: "db", "Canonicalize block #{} ({:?})", new_canonical, hash); let commit = self.storage.state_db.canonicalize_block(&hash) - .map_err(|e: state_db::Error| client::error::Error::from(format!("State database error: {:?}", e)))?; + .map_err(|e: state_db::Error| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?; apply_state_commit(transaction, commit); }; @@ -1152,7 +1153,7 @@ impl> Backend { } let number_u64 = number.saturated_into::(); let commit = self.storage.state_db.insert_block(&hash, number_u64, &pending_block.header.parent_hash(), changeset) - .map_err(|e: state_db::Error| client::error::Error::from(format!("State database error: {:?}", e)))?; + .map_err(|e: state_db::Error| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?; apply_state_commit(&mut transaction, commit); // Check if need to finalize. Genesis is always finalized instantly. @@ -1217,7 +1218,7 @@ impl> Backend { meta_updates.push((hash, *number, true, false)); Some((enacted, retracted)) } else { - return Err(client::error::Error::UnknownBlock(format!("Cannot set head {:?}", set_head))) + return Err(sp_blockchain::Error::UnknownBlock(format!("Cannot set head {:?}", set_head))) } } else { None @@ -1288,7 +1289,7 @@ impl> Backend { transaction.put(columns::META, meta_keys::FINALIZED_BLOCK, &lookup_key); let commit = self.storage.state_db.canonicalize_block(&f_hash) - .map_err(|e: state_db::Error| client::error::Error::from(format!("State database error: {:?}", e)))?; + .map_err(|e: state_db::Error| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?; apply_state_commit(transaction, commit); let changes_trie_config = self.changes_trie_config(parent_hash)?; @@ -1451,12 +1452,12 @@ impl client_api::backend::Backend for Backend Some(commit) => { apply_state_commit(&mut transaction, commit); let removed = self.blockchain.header(BlockId::Number(best))?.ok_or_else( - || client::error::Error::UnknownBlock( + || sp_blockchain::Error::UnknownBlock( format!("Error reverting to {}. Block hash not found.", best)))?; best -= One::one(); // prev block let hash = self.blockchain.hash(best)?.ok_or_else( - || client::error::Error::UnknownBlock( + || sp_blockchain::Error::UnknownBlock( format!("Error reverting to {}. Block hash not found.", best)))?; let key = utils::number_and_hash_to_lookup_key(best.clone(), &hash)?; transaction.put(columns::META, meta_keys::BEST_BLOCK, &key); @@ -1500,7 +1501,7 @@ impl client_api::backend::Backend for Backend Ok(Some(ref hdr)) => { let hash = hdr.hash(); if !self.have_state_at(&hash, *hdr.number()) { - return Err(client::error::Error::UnknownBlock(format!("State already discarded for {:?}", block))) + return Err(sp_blockchain::Error::UnknownBlock(format!("State already discarded for {:?}", block))) } if let Ok(()) = self.storage.state_db.pin(&hash) { let root = H256::from_slice(hdr.state_root().as_ref()); @@ -1508,10 +1509,10 @@ impl client_api::backend::Backend for Backend let state = RefTrackingState::new(db_state, self.storage.clone(), Some(hash.clone())); Ok(CachingState::new(state, self.shared_cache.clone(), Some(hash))) } else { - Err(client::error::Error::UnknownBlock(format!("State already discarded for {:?}", block))) + Err(sp_blockchain::Error::UnknownBlock(format!("State already discarded for {:?}", block))) } }, - Ok(None) => Err(client::error::Error::UnknownBlock(format!("Unknown state for block {:?}", block))), + Ok(None) => Err(sp_blockchain::Error::UnknownBlock(format!("Unknown state for block {:?}", block))), Err(e) => Err(e), } } @@ -1561,7 +1562,7 @@ mod tests { use sr_primitives::testing::{Header, Block as RawBlock, ExtrinsicWrapper}; use sr_primitives::traits::{Hash, BlakeTwo256}; use state_machine::{TrieMut, TrieDBMut, ChangesTrieRootsStorage, ChangesTrieStorage}; - use header_metadata::{lowest_common_ancestor, tree_route}; + use sp_blockchain::{lowest_common_ancestor, tree_route}; use test_client; diff --git a/substrate/client/db/src/light.rs b/substrate/client/db/src/light.rs index bdce0e6384..72f0d96986 100644 --- a/substrate/client/db/src/light.rs +++ b/substrate/client/db/src/light.rs @@ -24,18 +24,20 @@ use kvdb::{KeyValueDB, DBTransaction}; use client_api::backend::{AuxStore, NewBlockState}; use client::blockchain::{ - BlockStatus, Cache as BlockchainCache, - HeaderBackend as BlockchainHeaderBackend, Info as BlockchainInfo, - well_known_cache_keys, + BlockStatus, Cache as BlockchainCache,Info as BlockchainInfo, }; use client::cht; -use client::error::{Error as ClientError, Result as ClientResult}; +use sp_blockchain::{ + CachedHeaderMetadata, HeaderMetadata, HeaderMetadataCache, + Error as ClientError, Result as ClientResult, + HeaderBackend as BlockchainHeaderBackend, + well_known_cache_keys, +}; use client::light::blockchain::Storage as LightBlockchainStorage; use codec::{Decode, Encode}; use primitives::Blake2Hasher; use sr_primitives::generic::{DigestItem, BlockId}; use sr_primitives::traits::{Block as BlockT, Header as HeaderT, Zero, One, NumberFor}; -use header_metadata::{CachedHeaderMetadata, HeaderMetadata, HeaderMetadataCache}; use crate::cache::{DbCacheSync, DbCache, ComplexBlockId, EntryType as CacheEntryType}; use crate::utils::{self, meta_keys, Meta, db_err, read_db, block_id_to_lookup_key, read_meta}; use crate::DatabaseSettings; @@ -235,7 +237,7 @@ impl LightStorage { // handle reorg. let meta = self.meta.read(); if meta.best_hash != Default::default() { - let tree_route = header_metadata::tree_route(self, meta.best_hash, route_to)?; + let tree_route = sp_blockchain::tree_route(self, meta.best_hash, route_to)?; // update block number to hash lookup entries. for retracted in tree_route.retracted() { @@ -282,7 +284,7 @@ impl LightStorage { ) -> ClientResult<()> { let meta = self.meta.read(); if &meta.finalized_hash != header.parent_hash() { - return Err(::client::error::Error::NonSequentialFinalization( + return Err(::sp_blockchain::Error::NonSequentialFinalization( format!("Last finalized {:?} not parent of {:?}", meta.finalized_hash, hash), ).into()) @@ -560,7 +562,7 @@ pub(crate) mod tests { use client::cht; use sr_primitives::generic::DigestItem; use sr_primitives::testing::{H256 as Hash, Header, Block as RawBlock, ExtrinsicWrapper}; - use header_metadata::{lowest_common_ancestor, tree_route}; + use sp_blockchain::{lowest_common_ancestor, tree_route}; use super::*; type Block = RawBlock>; diff --git a/substrate/client/db/src/utils.rs b/substrate/client/db/src/utils.rs index 516f3d11b0..b16a7ecdaa 100644 --- a/substrate/client/db/src/utils.rs +++ b/substrate/client/db/src/utils.rs @@ -25,7 +25,6 @@ use kvdb::{KeyValueDB, DBTransaction}; use kvdb_rocksdb::{Database, DatabaseConfig}; use log::debug; -use client; use codec::Decode; use trie::DBValue; use sr_primitives::generic::BlockId; @@ -82,9 +81,9 @@ pub type NumberIndexKey = [u8; 4]; /// /// In the current database schema, this kind of key is only used for /// lookups into an index, NOT for storing header data or others. -pub fn number_index_key>(n: N) -> client::error::Result { +pub fn number_index_key>(n: N) -> sp_blockchain::Result { let n = n.try_into().map_err(|_| - client::error::Error::Backend("Block number cannot be converted to u32".into()) + sp_blockchain::Error::Backend("Block number cannot be converted to u32".into()) )?; Ok([ @@ -100,7 +99,7 @@ pub fn number_index_key>(n: N) -> client::error::Result( number: N, hash: H, -) -> client::error::Result> where +) -> sp_blockchain::Result> where N: TryInto, H: AsRef<[u8]>, { @@ -111,11 +110,11 @@ pub fn number_and_hash_to_lookup_key( /// Convert block lookup key into block number. /// all block lookup keys start with the block number. -pub fn lookup_key_to_number(key: &[u8]) -> client::error::Result where +pub fn lookup_key_to_number(key: &[u8]) -> sp_blockchain::Result where N: From { if key.len() < 4 { - return Err(client::error::Error::Backend("Invalid block key".into())); + return Err(sp_blockchain::Error::Backend("Invalid block key".into())); } Ok((key[0] as u32) << 24 | (key[1] as u32) << 16 @@ -128,7 +127,7 @@ pub fn remove_number_to_key_mapping>( transaction: &mut DBTransaction, key_lookup_col: Option, number: N, -) -> client::error::Result<()> { +) -> sp_blockchain::Result<()> { transaction.delete(key_lookup_col, number_index_key(number)?.as_ref()); Ok(()) } @@ -139,7 +138,7 @@ pub fn remove_key_mappings, H: AsRef<[u8]>>( key_lookup_col: Option, number: N, hash: H, -) -> client::error::Result<()> { +) -> sp_blockchain::Result<()> { remove_number_to_key_mapping(transaction, key_lookup_col, number)?; transaction.delete(key_lookup_col, hash.as_ref()); Ok(()) @@ -152,7 +151,7 @@ pub fn insert_number_to_key_mapping + Clone, H: AsRef<[u8]>>( key_lookup_col: Option, number: N, hash: H, -) -> client::error::Result<()> { +) -> sp_blockchain::Result<()> { transaction.put_vec( key_lookup_col, number_index_key(number.clone())?.as_ref(), @@ -167,7 +166,7 @@ pub fn insert_hash_to_key_mapping, H: AsRef<[u8]> + Clone>( key_lookup_col: Option, number: N, hash: H, -) -> client::error::Result<()> { +) -> sp_blockchain::Result<()> { transaction.put_vec( key_lookup_col, hash.clone().as_ref(), @@ -183,7 +182,7 @@ pub fn block_id_to_lookup_key( db: &dyn KeyValueDB, key_lookup_col: Option, id: BlockId -) -> Result>, client::error::Error> where +) -> Result>, sp_blockchain::Error> where Block: BlockT, ::sr_primitives::traits::NumberFor: UniqueSaturatedFrom + UniqueSaturatedInto, { @@ -199,8 +198,8 @@ pub fn block_id_to_lookup_key( } /// Maps database error to client error -pub fn db_err(err: io::Error) -> client::error::Error { - client::error::Error::Backend(format!("{}", err)) +pub fn db_err(err: io::Error) -> sp_blockchain::Error { + sp_blockchain::Error::Backend(format!("{}", err)) } /// Open RocksDB database. @@ -208,7 +207,7 @@ pub fn open_database( config: &DatabaseSettings, col_meta: Option, db_type: &str -) -> client::error::Result> { +) -> sp_blockchain::Result> { let db: Arc = match &config.source { #[cfg(feature = "kvdb-rocksdb")] DatabaseSettingsSrc::Path { path, cache_size } => { @@ -230,13 +229,13 @@ pub fn open_database( db_config.memory_budget = memory_budget; } let path = path.to_str() - .ok_or_else(|| client::error::Error::Backend("Invalid database path".into()))?; + .ok_or_else(|| sp_blockchain::Error::Backend("Invalid database path".into()))?; Arc::new(Database::open(&db_config, &path).map_err(db_err)?) }, #[cfg(not(feature = "kvdb-rocksdb"))] DatabaseSettingsSrc::Path { .. } => { let msg = "Try to open RocksDB database with RocksDB disabled".into(); - return Err(client::error::Error::Backend(msg)); + return Err(sp_blockchain::Error::Backend(msg)); }, DatabaseSettingsSrc::Custom(db) => db.clone(), }; @@ -245,7 +244,7 @@ pub fn open_database( match db.get(col_meta, meta_keys::TYPE).map_err(db_err)? { Some(stored_type) => { if db_type.as_bytes() != &*stored_type { - return Err(client::error::Error::Backend( + return Err(sp_blockchain::Error::Backend( format!("Unexpected database type. Expected: {}", db_type)).into()); } }, @@ -265,7 +264,7 @@ pub fn read_db( col_index: Option, col: Option, id: BlockId -) -> client::error::Result> +) -> sp_blockchain::Result> where Block: BlockT, { @@ -281,12 +280,12 @@ pub fn read_header( col_index: Option, col: Option, id: BlockId, -) -> client::error::Result> { +) -> sp_blockchain::Result> { match read_db(db, col_index, col, id)? { Some(header) => match Block::Header::decode(&mut &header[..]) { Ok(header) => Ok(Some(header)), Err(_) => return Err( - client::error::Error::Backend("Error decoding header".into()) + sp_blockchain::Error::Backend("Error decoding header".into()) ), } None => Ok(None), @@ -299,15 +298,15 @@ pub fn require_header( col_index: Option, col: Option, id: BlockId, -) -> client::error::Result { +) -> sp_blockchain::Result { read_header(db, col_index, col, id) - .and_then(|header| header.ok_or_else(|| client::error::Error::UnknownBlock(format!("{}", id)))) + .and_then(|header| header.ok_or_else(|| sp_blockchain::Error::UnknownBlock(format!("{}", id)))) } /// Read meta from the database. pub fn read_meta(db: &dyn KeyValueDB, col_meta: Option, col_header: Option) -> Result< Meta<<::Header as HeaderT>::Number, Block::Hash>, - client::error::Error, + sp_blockchain::Error, > where Block: BlockT, @@ -315,7 +314,7 @@ pub fn read_meta(db: &dyn KeyValueDB, col_meta: Option, col_header: let genesis_hash: Block::Hash = match db.get(col_meta, meta_keys::GENESIS_HASH).map_err(db_err)? { Some(h) => match Decode::decode(&mut &h[..]) { Ok(h) => h, - Err(err) => return Err(client::error::Error::Backend( + Err(err) => return Err(sp_blockchain::Error::Backend( format!("Error decoding genesis hash: {}", err) )), }, @@ -328,7 +327,7 @@ pub fn read_meta(db: &dyn KeyValueDB, col_meta: Option, col_header: }), }; - let load_meta_block = |desc, key| -> Result<_, client::error::Error> { + let load_meta_block = |desc, key| -> Result<_, sp_blockchain::Error> { if let Some(Some(header)) = db.get(col_meta, key).and_then(|id| match id { Some(id) => db.get(col_header, &id).map(|h| h.map(|b| Block::Header::decode(&mut &b[..]).ok())), diff --git a/substrate/client/finality-grandpa/Cargo.toml b/substrate/client/finality-grandpa/Cargo.toml index 7bc381d3ad..71460966ad 100644 --- a/substrate/client/finality-grandpa/Cargo.toml +++ b/substrate/client/finality-grandpa/Cargo.toml @@ -22,8 +22,8 @@ keystore = { package = "substrate-keystore", path = "../keystore" } serde_json = "1.0.41" client-api = { package = "substrate-client-api", path = "../api" } client = { package = "substrate-client", path = "../" } -header-metadata = { package = "substrate-header-metadata", path = "../header-metadata" } inherents = { package = "substrate-inherents", path = "../../primitives/inherents" } +sp-blockchain = { path = "../../primitives/blockchain" } network = { package = "substrate-network", path = "../network" } sp-finality-tracker = { path = "../../primitives/finality-tracker" } fg_primitives = { package = "substrate-finality-grandpa-primitives", path = "../../primitives/finality-grandpa" } diff --git a/substrate/client/finality-grandpa/src/aux_schema.rs b/substrate/client/finality-grandpa/src/aux_schema.rs index 9857367dc9..cac8e566d2 100644 --- a/substrate/client/finality-grandpa/src/aux_schema.rs +++ b/substrate/client/finality-grandpa/src/aux_schema.rs @@ -20,7 +20,7 @@ use std::fmt::Debug; use std::sync::Arc; use codec::{Encode, Decode}; use client_api::backend::AuxStore; -use client_api::error::{Result as ClientResult, Error as ClientError}; +use sp_blockchain::{Result as ClientResult, Error as ClientError}; use fork_tree::ForkTree; use grandpa::round::State as RoundState; use sr_primitives::traits::{Block as BlockT, NumberFor}; diff --git a/substrate/client/finality-grandpa/src/consensus_changes.rs b/substrate/client/finality-grandpa/src/consensus_changes.rs index e276b287dd..5f7828f02b 100644 --- a/substrate/client/finality-grandpa/src/consensus_changes.rs +++ b/substrate/client/finality-grandpa/src/consensus_changes.rs @@ -47,11 +47,11 @@ impl ConsensusChanges { /// Finalize all pending consensus changes that are finalized by given block. /// Returns true if there any changes were finalized. - pub(crate) fn finalize ::client_api::error::Result>>( + pub(crate) fn finalize ::sp_blockchain::Result>>( &mut self, block: (N, H), canonical_at_height: F, - ) -> ::client_api::error::Result<(bool, bool)> { + ) -> ::sp_blockchain::Result<(bool, bool)> { let (split_idx, has_finalized_changes) = self.pending_changes.iter() .enumerate() .take_while(|(_, &(at_height, _))| at_height <= block.0) diff --git a/substrate/client/finality-grandpa/src/environment.rs b/substrate/client/finality-grandpa/src/environment.rs index 214e8bc798..af6e03743a 100644 --- a/substrate/client/finality-grandpa/src/environment.rs +++ b/substrate/client/finality-grandpa/src/environment.rs @@ -24,13 +24,13 @@ use codec::{Decode, Encode}; use futures::prelude::*; use tokio_timer::Delay; use parking_lot::RwLock; +use sp_blockchain::{HeaderBackend, Error as ClientError}; use client_api::{ - HeaderBackend, BlockchainEvents, + BlockchainEvents, backend::{Backend}, Finalizer, call_executor::CallExecutor, - error::Error as ClientError, utils::is_descendent_of, }; use client::{ @@ -534,7 +534,7 @@ pub(crate) fn ancestry, E, RA>( { if base == block { return Err(GrandpaError::NotDescendent) } - let tree_route_res = header_metadata::tree_route(client, block, base); + let tree_route_res = sp_blockchain::tree_route(client, block, base); let tree_route = match tree_route_res { Ok(tree_route) => tree_route, diff --git a/substrate/client/finality-grandpa/src/finality_proof.rs b/substrate/client/finality-grandpa/src/finality_proof.rs index c675a4d1f3..209eb974b0 100644 --- a/substrate/client/finality-grandpa/src/finality_proof.rs +++ b/substrate/client/finality-grandpa/src/finality_proof.rs @@ -38,11 +38,10 @@ use std::iter; use std::sync::Arc; use log::{trace, warn}; +use sp_blockchain::{Backend as BlockchainBackend, Error as ClientError, Result as ClientResult}; use client_api::{ - backend::Backend, blockchain::Backend as BlockchainBackend, CallExecutor, - error::{Error as ClientError, Result as ClientResult}, + backend::Backend, CallExecutor, StorageProof, light::{FetchChecker, RemoteReadRequest}, - StorageProof, }; use client::Client; use codec::{Encode, Decode}; @@ -259,7 +258,7 @@ pub(crate) fn prove_finality, B: BlockchainBackend ::client_api::error::Result>> +) -> ::sp_blockchain::Result>> where J: ProvableJustification, { diff --git a/substrate/client/finality-grandpa/src/import.rs b/substrate/client/finality-grandpa/src/import.rs index d6a3ea6e94..2c18600ae9 100644 --- a/substrate/client/finality-grandpa/src/import.rs +++ b/substrate/client/finality-grandpa/src/import.rs @@ -21,11 +21,8 @@ use codec::Encode; use futures::sync::mpsc; use parking_lot::RwLockWriteGuard; -use client_api::{ - backend::Backend, blockchain, - CallExecutor, blockchain::HeaderBackend, well_known_cache_keys, - utils::is_descendent_of, -}; +use sp_blockchain::{HeaderBackend, BlockStatus, well_known_cache_keys}; +use client_api::{backend::Backend, CallExecutor, utils::is_descendent_of}; use client::Client; use consensus_common::{ BlockImport, Error as ConsensusError, @@ -403,8 +400,8 @@ impl, RA, SC> BlockImport // early exit if block already in chain, otherwise the check for // authority changes will error when trying to re-import a change block match self.inner.status(BlockId::Hash(hash)) { - Ok(blockchain::BlockStatus::InChain) => return Ok(ImportResult::AlreadyInChain), - Ok(blockchain::BlockStatus::Unknown) => {}, + Ok(BlockStatus::InChain) => return Ok(ImportResult::AlreadyInChain), + Ok(BlockStatus::Unknown) => {}, Err(e) => return Err(ConsensusError::ClientImport(e.to_string()).into()), } diff --git a/substrate/client/finality-grandpa/src/justification.rs b/substrate/client/finality-grandpa/src/justification.rs index eff06776bd..807a785ca8 100644 --- a/substrate/client/finality-grandpa/src/justification.rs +++ b/substrate/client/finality-grandpa/src/justification.rs @@ -17,7 +17,8 @@ use std::collections::{HashMap, HashSet}; use client::Client; -use client_api::{CallExecutor, backend::Backend, error::Error as ClientError}; +use client_api::{CallExecutor, backend::Backend}; +use sp_blockchain::Error as ClientError; use codec::{Encode, Decode}; use grandpa::voter_set::VoterSet; use grandpa::{Error as GrandpaError}; diff --git a/substrate/client/finality-grandpa/src/lib.rs b/substrate/client/finality-grandpa/src/lib.rs index 8355f7c93e..2b83488d59 100644 --- a/substrate/client/finality-grandpa/src/lib.rs +++ b/substrate/client/finality-grandpa/src/lib.rs @@ -55,10 +55,8 @@ use futures::prelude::*; use log::{debug, error, info}; use futures::sync::mpsc; -use client_api::{ - BlockchainEvents, CallExecutor, backend::Backend, error::Error as ClientError, - ExecutionStrategy, HeaderBackend -}; +use client_api::{BlockchainEvents, CallExecutor, backend::Backend, ExecutionStrategy}; +use sp_blockchain::{HeaderBackend, Error as ClientError}; use client::Client; use codec::{Decode, Encode}; use sr_primitives::generic::BlockId; @@ -546,7 +544,7 @@ pub struct GrandpaParams, N, RA, SC, VR, X> { /// block import worker that has already been instantiated with `block_import`. pub fn run_grandpa_voter, N, RA, SC, VR, X>( grandpa_params: GrandpaParams, -) -> client_api::error::Result + Send + 'static> where +) -> sp_blockchain::Result + Send + 'static> where Block::Hash: Ord, B: Backend + 'static, E: CallExecutor + Send + Sync + 'static, @@ -880,7 +878,7 @@ where #[deprecated(since = "1.1.0", note = "Please switch to run_grandpa_voter.")] pub fn run_grandpa, N, RA, SC, VR, X>( grandpa_params: GrandpaParams, -) -> ::client_api::error::Result + Send + 'static> where +) -> ::sp_blockchain::Result + Send + 'static> where Block::Hash: Ord, B: Backend + 'static, E: CallExecutor + Send + Sync + 'static, diff --git a/substrate/client/finality-grandpa/src/light_import.rs b/substrate/client/finality-grandpa/src/light_import.rs index 6212f853e8..6b5fbb3489 100644 --- a/substrate/client/finality-grandpa/src/light_import.rs +++ b/substrate/client/finality-grandpa/src/light_import.rs @@ -19,13 +19,8 @@ use std::sync::Arc; use log::{info, trace, warn}; use parking_lot::RwLock; use client::Client; -use client_api::{ - CallExecutor, - backend::{AuxStore, Backend, Finalizer}, - blockchain::HeaderBackend, - error::Error as ClientError, - well_known_cache_keys, -}; +use client_api::{CallExecutor, backend::{AuxStore, Backend, Finalizer}}; +use sp_blockchain::{HeaderBackend, Error as ClientError, well_known_cache_keys}; use codec::{Encode, Decode}; use consensus_common::{ import_queue::Verifier, diff --git a/substrate/client/finality-grandpa/src/observer.rs b/substrate/client/finality-grandpa/src/observer.rs index b182eaaaa5..83c2fac275 100644 --- a/substrate/client/finality-grandpa/src/observer.rs +++ b/substrate/client/finality-grandpa/src/observer.rs @@ -156,7 +156,7 @@ pub fn run_grandpa_observer, N, RA, SC>( link: LinkHalf, network: N, on_exit: impl Future + Clone + Send + 'static, -) -> ::client_api::error::Result + Send + 'static> where +) -> ::sp_blockchain::Result + Send + 'static> where B: Backend + 'static, E: CallExecutor + Send + Sync + 'static, N: Network + Send + Sync + 'static, diff --git a/substrate/client/finality-grandpa/src/tests.rs b/substrate/client/finality-grandpa/src/tests.rs index abcd44635c..fde730e298 100644 --- a/substrate/client/finality-grandpa/src/tests.rs +++ b/substrate/client/finality-grandpa/src/tests.rs @@ -26,7 +26,7 @@ use futures03::{StreamExt as _, TryStreamExt as _}; use tokio::runtime::current_thread; use keyring::Ed25519Keyring; use client::LongestChain; -use client_api::error::Result; +use sp_blockchain::Result; use sr_api::{Core, RuntimeVersion, ApiExt, StorageProof}; use test_client::{self, runtime::BlockNumber}; use consensus_common::{BlockOrigin, ForkChoiceStrategy, ImportedAux, BlockImportParams, ImportResult}; @@ -242,7 +242,7 @@ impl Core for RuntimeApi { } impl ApiExt for RuntimeApi { - type Error = client_api::error::Error; + type Error = sp_blockchain::Error; fn map_api_result result::Result, R, E>( &self, diff --git a/substrate/client/header-metadata/Cargo.toml b/substrate/client/header-metadata/Cargo.toml deleted file mode 100644 index b321685c6c..0000000000 --- a/substrate/client/header-metadata/Cargo.toml +++ /dev/null @@ -1,10 +0,0 @@ -[package] -name = "substrate-header-metadata" -version = "2.0.0" -authors = ["Parity Technologies "] -edition = "2018" - -[dependencies] -lru = { version = "0.4.0" } -parking_lot = { version = "0.9.0" } -sr-primitives = { path = "../../primitives/sr-primitives" } diff --git a/substrate/client/network/Cargo.toml b/substrate/client/network/Cargo.toml index 9691cd5c3c..a536623d39 100644 --- a/substrate/client/network/Cargo.toml +++ b/substrate/client/network/Cargo.toml @@ -27,13 +27,13 @@ fork-tree = { path = "../../utils/fork-tree" } consensus = { package = "substrate-consensus-common", path = "../../primitives/consensus/common" } client = { package = "substrate-client", path = "../" } client-api = { package = "substrate-client-api", path = "../api" } -header_metadata = { package = "substrate-header-metadata", path = "../header-metadata" } +sp-blockchain = { path = "../../primitives/blockchain" } sr-primitives = { path = "../../primitives/sr-primitives" } sr-arithmetic = { path = "../../primitives/sr-arithmetic" } primitives = { package = "substrate-primitives", path = "../../primitives/core" } block-builder = { package = "substrate-block-builder", path = "../block-builder" } codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] } -peerset = { package = "substrate-peerset", path = "../../primitives/peerset" } +peerset = { package = "substrate-peerset", path = "../peerset" } serde = { version = "1.0.101", features = ["derive"] } serde_json = "1.0.41" slog = { version = "2.5.2", features = ["nested-values"] } diff --git a/substrate/client/network/src/chain.rs b/substrate/client/network/src/chain.rs index 5207a24bf9..ac883987cd 100644 --- a/substrate/client/network/src/chain.rs +++ b/substrate/client/network/src/chain.rs @@ -17,7 +17,7 @@ //! Blockchain access trait use client::Client as SubstrateClient; -use client_api::error::Error; +use sp_blockchain::Error; use client_api::{ChangesProof, StorageProof, ClientInfo, CallExecutor}; use consensus::{BlockImport, BlockStatus, Error as ConsensusError}; use sr_primitives::traits::{Block as BlockT, Header as HeaderT}; @@ -162,7 +162,7 @@ impl Client for SubstrateClient where return Ok(false); } - let ancestor = header_metadata::lowest_common_ancestor(self, *block, *base)?; + let ancestor = sp_blockchain::lowest_common_ancestor(self, *block, *base)?; Ok(ancestor.hash == *base) } diff --git a/substrate/client/network/src/error.rs b/substrate/client/network/src/error.rs index a33f0280ab..8f15e318ce 100644 --- a/substrate/client/network/src/error.rs +++ b/substrate/client/network/src/error.rs @@ -16,8 +16,6 @@ //! Substrate network possible errors. -use client_api; - use libp2p::{PeerId, Multiaddr}; use std::fmt; @@ -31,7 +29,7 @@ pub enum Error { /// Io error Io(std::io::Error), /// Client error - Client(client_api::error::Error), + Client(sp_blockchain::Error), /// The same bootnode (based on address) is registered with two different peer ids. #[display( fmt = "The same bootnode (`{}`) is registered with two different peer ids: `{}` and `{}`", diff --git a/substrate/client/network/src/on_demand_layer.rs b/substrate/client/network/src/on_demand_layer.rs index 4a5ec4adcf..82c5ed6940 100644 --- a/substrate/client/network/src/on_demand_layer.rs +++ b/substrate/client/network/src/on_demand_layer.rs @@ -22,7 +22,7 @@ use std::sync::Arc; use futures::{prelude::*, sync::mpsc, sync::oneshot}; use futures03::compat::{Compat01As03, Future01CompatExt as _}; use parking_lot::Mutex; -use client_api::error::Error as ClientError; +use sp_blockchain::Error as ClientError; use client_api::{Fetcher, FetchChecker, RemoteHeaderRequest, RemoteCallRequest, RemoteReadRequest, RemoteChangesRequest, RemoteReadChildRequest, RemoteBodyRequest}; diff --git a/substrate/client/network/src/protocol/light_dispatch.rs b/substrate/client/network/src/protocol/light_dispatch.rs index 280495c0c4..afc7ac563b 100644 --- a/substrate/client/network/src/protocol/light_dispatch.rs +++ b/substrate/client/network/src/protocol/light_dispatch.rs @@ -25,7 +25,7 @@ use std::time::{Instant, Duration}; use log::{trace, info}; use futures::sync::oneshot::{Sender as OneShotSender}; use linked_hash_map::{Entry, LinkedHashMap}; -use client_api::error::Error as ClientError; +use sp_blockchain::Error as ClientError; use client_api::{FetchChecker, RemoteHeaderRequest, RemoteCallRequest, RemoteReadRequest, RemoteChangesRequest, ChangesProof, RemoteReadChildRequest, RemoteBodyRequest, StorageProof}; @@ -677,7 +677,7 @@ pub mod tests { use std::time::Instant; use futures::{Future, sync::oneshot}; use sr_primitives::traits::{Block as BlockT, NumberFor, Header as HeaderT}; - use client_api::{error::{Error as ClientError, Result as ClientResult}}; + use sp_blockchain::{Error as ClientError, Result as ClientResult}; use client_api::{FetchChecker, RemoteHeaderRequest, ChangesProof, RemoteCallRequest, RemoteReadRequest, RemoteReadChildRequest, RemoteChangesRequest, RemoteBodyRequest}; diff --git a/substrate/client/network/src/protocol/sync.rs b/substrate/client/network/src/protocol/sync.rs index 6f1255cd8a..3ee26deab3 100644 --- a/substrate/client/network/src/protocol/sync.rs +++ b/substrate/client/network/src/protocol/sync.rs @@ -28,7 +28,8 @@ //! use blocks::BlockCollection; -use client_api::{ClientInfo, error::Error as ClientError}; +use client_api::ClientInfo; +use sp_blockchain::Error as ClientError; use consensus::{BlockOrigin, BlockStatus, block_validation::{BlockAnnounceValidator, Validation}, import_queue::{IncomingBlock, BlockImportResult, BlockImportError} diff --git a/substrate/client/network/src/protocol/sync/extra_requests.rs b/substrate/client/network/src/protocol/sync/extra_requests.rs index 5bfeeba2a5..a96f855776 100644 --- a/substrate/client/network/src/protocol/sync/extra_requests.rs +++ b/substrate/client/network/src/protocol/sync/extra_requests.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Substrate. If not, see . -use client_api::error::Error as ClientError; +use sp_blockchain::Error as ClientError; use crate::protocol::sync::{PeerSync, PeerSyncState}; use fork_tree::ForkTree; use libp2p::PeerId; @@ -283,7 +283,7 @@ impl<'a, B: BlockT> Matcher<'a, B> { #[cfg(test)] mod tests { use crate::protocol::sync::PeerSync; - use client_api::error::Error as ClientError; + use sp_blockchain::Error as ClientError; use quickcheck::{Arbitrary, Gen, QuickCheck, StdThreadGen}; use rand::Rng; use std::collections::{HashMap, HashSet}; diff --git a/substrate/client/network/src/test/mod.rs b/substrate/client/network/src/test/mod.rs index 964f27051a..e7cc1b103b 100644 --- a/substrate/client/network/src/test/mod.rs +++ b/substrate/client/network/src/test/mod.rs @@ -27,12 +27,13 @@ use std::sync::Arc; use crate::config::build_multiaddr; use log::trace; use crate::chain::FinalityProofProvider; +use sp_blockchain::{ + Result as ClientResult, well_known_cache_keys::{self, Id as CacheKeyId}, +}; use client_api::{ ClientInfo, BlockchainEvents, BlockImportNotification, FinalityNotifications, ImportNotifications, FinalityNotification, - error::Result as ClientResult, - well_known_cache_keys::{self, Id as CacheKeyId}, backend::{AuxStore, Backend, Finalizer} }; use block_builder::BlockBuilder; diff --git a/substrate/client/offchain/Cargo.toml b/substrate/client/offchain/Cargo.toml index 0f78b6804b..afec2af4fd 100644 --- a/substrate/client/offchain/Cargo.toml +++ b/substrate/client/offchain/Cargo.toml @@ -35,7 +35,7 @@ client-db = { package = "substrate-client-db", path = "../db/", default-features env_logger = "0.7.0" test-client = { package = "substrate-test-runtime-client", path = "../../test/utils/runtime/client" } tokio = "0.1.22" -transaction_pool = { package = "substrate-transaction-pool", path = "../transaction-pool" } +transaction_pool = { package = "sc-transaction-pool", path = "../../client/transaction-pool" } [features] default = [] diff --git a/substrate/primitives/peerset/Cargo.toml b/substrate/client/peerset/Cargo.toml similarity index 100% rename from substrate/primitives/peerset/Cargo.toml rename to substrate/client/peerset/Cargo.toml diff --git a/substrate/primitives/peerset/src/lib.rs b/substrate/client/peerset/src/lib.rs similarity index 100% rename from substrate/primitives/peerset/src/lib.rs rename to substrate/client/peerset/src/lib.rs diff --git a/substrate/primitives/peerset/src/peersstate.rs b/substrate/client/peerset/src/peersstate.rs similarity index 100% rename from substrate/primitives/peerset/src/peersstate.rs rename to substrate/client/peerset/src/peersstate.rs diff --git a/substrate/primitives/peerset/tests/fuzz.rs b/substrate/client/peerset/tests/fuzz.rs similarity index 100% rename from substrate/primitives/peerset/tests/fuzz.rs rename to substrate/client/peerset/tests/fuzz.rs diff --git a/substrate/client/rpc/Cargo.toml b/substrate/client/rpc/Cargo.toml index f8eaac0af0..a42ada7205 100644 --- a/substrate/client/rpc/Cargo.toml +++ b/substrate/client/rpc/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -api = { package = "substrate-rpc-api", path = "./api" } +api = { package = "sc-rpc-api", path = "./api" } client-api = { package = "substrate-client-api", path = "../api" } client = { package = "substrate-client", path = "../" } sr-api = { path = "../../primitives/sr-api" } @@ -23,7 +23,8 @@ rpc-primitives = { package = "substrate-rpc-primitives", path = "../../primitive state_machine = { package = "substrate-state-machine", path = "../../primitives/state-machine" } substrate-executor = { path = "../executor" } substrate-keystore = { path = "../keystore" } -transaction_pool = { package = "substrate-transaction-pool", path = "../transaction-pool" } +transaction_pool = { package = "sc-transaction-pool", path = "../../client/transaction-pool" } +sp-blockchain = { path = "../../primitives/blockchain" } hash-db = { version = "0.15.2", default-features = false } parking_lot = { version = "0.9.0" } diff --git a/substrate/client/rpc/api/Cargo.toml b/substrate/client/rpc/api/Cargo.toml index 621d487f3a..9d88aae9a0 100644 --- a/substrate/client/rpc/api/Cargo.toml +++ b/substrate/client/rpc/api/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "substrate-rpc-api" +name = "sc-rpc-api" version = "2.0.0" authors = ["Parity Technologies "] edition = "2018" @@ -18,5 +18,5 @@ primitives = { package = "substrate-primitives", path = "../../../primitives/cor runtime_version = { package = "sr-version", path = "../../../primitives/sr-version" } serde = { version = "1.0.101", features = ["derive"] } serde_json = "1.0.41" -txpool = { package = "substrate-transaction-graph", path = "../../transaction-pool/graph" } +txpool = { package = "sc-transaction-graph", path = "../../../client/transaction-pool/graph" } rpc-primitives = { package = "substrate-rpc-primitives", path = "../../../primitives/rpc" } diff --git a/substrate/client/rpc/src/author/mod.rs b/substrate/client/rpc/src/author/mod.rs index 29be7b8d88..920331d9ae 100644 --- a/substrate/client/rpc/src/author/mod.rs +++ b/substrate/client/rpc/src/author/mod.rs @@ -24,7 +24,7 @@ use futures::future::{FutureExt, TryFutureExt}; use log::warn; use client::Client; -use client_api::error::Error as ClientError; +use sp_blockchain::Error as ClientError; use rpc::futures::{ Sink, Future, diff --git a/substrate/client/rpc/src/chain/mod.rs b/substrate/client/rpc/src/chain/mod.rs index c420360576..8c35df0bf7 100644 --- a/substrate/client/rpc/src/chain/mod.rs +++ b/substrate/client/rpc/src/chain/mod.rs @@ -288,6 +288,6 @@ fn subscribe_headers( }); } -fn client_err(err: client::error::Error) -> Error { +fn client_err(err: sp_blockchain::Error) -> Error { Error::Client(Box::new(err)) } diff --git a/substrate/client/rpc/src/state/mod.rs b/substrate/client/rpc/src/state/mod.rs index 8e15c48807..491ea33969 100644 --- a/substrate/client/rpc/src/state/mod.rs +++ b/substrate/client/rpc/src/state/mod.rs @@ -184,7 +184,7 @@ pub fn new_full( RA: Send + Sync + 'static, Client: ProvideRuntimeApi, as ProvideRuntimeApi>::Api: - Metadata, + Metadata, { State { backend: Box::new(self::state_full::FullState::new(client, subscriptions)), @@ -332,6 +332,6 @@ impl StateApi for State } } -fn client_err(err: client::error::Error) -> Error { +fn client_err(err: sp_blockchain::Error) -> Error { Error::Client(Box::new(err)) } diff --git a/substrate/client/rpc/src/state/state_full.rs b/substrate/client/rpc/src/state/state_full.rs index dcb876c846..55b6e65d48 100644 --- a/substrate/client/rpc/src/state/state_full.rs +++ b/substrate/client/rpc/src/state/state_full.rs @@ -28,7 +28,8 @@ use rpc::{ }; use api::Subscriptions; -use client_api::{backend::Backend, error::Result as ClientResult}; +use client_api::backend::Backend; +use sp_blockchain::Result as ClientResult; use client::{ Client, CallExecutor, BlockchainEvents, }; @@ -232,7 +233,7 @@ impl StateBackend for FullState: ProvideRuntimeApi, as ProvideRuntimeApi>::Api: - Metadata, + Metadata, { fn call( &self, diff --git a/substrate/client/rpc/src/state/state_light.rs b/substrate/client/rpc/src/state/state_light.rs index c3155ef4a9..c761d3bfe4 100644 --- a/substrate/client/rpc/src/state/state_light.rs +++ b/substrate/client/rpc/src/state/state_light.rs @@ -40,9 +40,9 @@ use rpc::{ use api::Subscriptions; use client_api::backend::Backend; +use sp_blockchain::Error as ClientError; use client::{ - BlockchainEvents, Client, CallExecutor, - error::Error as ClientError, + BlockchainEvents, Client, CallExecutor, light::{ blockchain::{future_header, RemoteBlockchain}, fetcher::{Fetcher, RemoteCallRequest, RemoteReadRequest, RemoteReadChildRequest}, diff --git a/substrate/client/service/Cargo.toml b/substrate/client/service/Cargo.toml index f1c3669c47..2c19c57a31 100644 --- a/substrate/client/service/Cargo.toml +++ b/substrate/client/service/Cargo.toml @@ -31,6 +31,7 @@ target_info = "0.1.0" keystore = { package = "substrate-keystore", path = "../keystore" } sr-io = { path = "../../primitives/sr-io" } sr-primitives = { path = "../../primitives/sr-primitives" } +sp-blockchain = { path = "../../primitives/blockchain" } primitives = { package = "substrate-primitives", path = "../../primitives/core" } session = { package = "substrate-session", path = "../../primitives/session" } app-crypto = { package = "substrate-application-crypto", path = "../../primitives/application-crypto" } @@ -44,7 +45,7 @@ tx-pool-api = { package = "substrate-transaction-pool-runtime-api", path = "../. client_db = { package = "substrate-client-db", path = "../db" } codec = { package = "parity-scale-codec", version = "1.0.0" } substrate-executor = { path = "../executor" } -transaction_pool = { package = "substrate-transaction-pool", path = "../transaction-pool" } +transaction_pool = { package = "sc-transaction-pool", path = "../../client/transaction-pool" } rpc-servers = { package = "substrate-rpc-servers", path = "../rpc-servers" } rpc = { package = "substrate-rpc", path = "../rpc" } tel = { package = "substrate-telemetry", path = "../telemetry" } @@ -56,9 +57,6 @@ tracing = "0.1.10" [dev-dependencies] substrate-test-runtime-client = { path = "../../test/utils/runtime/client" } -node-executor = { path = "../../bin/node/executor" } -node-primitives = { path = "../../bin/node/primitives" } -node-runtime = { path = "../../bin/node/runtime" } babe-primitives = { package = "substrate-consensus-babe-primitives", path = "../../primitives/consensus/babe" } grandpa = { package = "substrate-finality-grandpa", path = "../finality-grandpa" } grandpa-primitives = { package = "substrate-finality-grandpa-primitives", path = "../../primitives/finality-grandpa" } diff --git a/substrate/client/service/src/builder.rs b/substrate/client/service/src/builder.rs index 6d8bc53822..ef3403e6d8 100644 --- a/substrate/client/service/src/builder.rs +++ b/substrate/client/service/src/builder.rs @@ -54,6 +54,7 @@ use std::{ use sysinfo::{get_current_pid, ProcessExt, System, SystemExt}; use tel::{telemetry, SUBSTRATE_INFO}; use transaction_pool::txpool::{self, ChainApi, Pool as TransactionPool}; +use sp_blockchain; use grafana_data_source::{self, record_metrics}; /// Aggregator for the components required to build a service. @@ -765,7 +766,7 @@ ServiceBuilder< offchain::OffchainWorkerApi + tx_pool_api::TaggedTransactionQueue + session::SessionKeys + - sr_api::ApiExt, + sr_api::ApiExt, TBl: BlockT::Out>, TRtApi: 'static + Send + Sync, TCfg: Default, diff --git a/substrate/client/service/src/error.rs b/substrate/client/service/src/error.rs index 85a6892b26..cd2fce6bde 100644 --- a/substrate/client/service/src/error.rs +++ b/substrate/client/service/src/error.rs @@ -16,10 +16,10 @@ //! Errors that can occur during the service operation. -use client; use network; use keystore; use consensus_common; +use sp_blockchain; /// Service Result typedef. pub type Result = std::result::Result; @@ -28,7 +28,7 @@ pub type Result = std::result::Result; #[derive(Debug, derive_more::Display, derive_more::From)] pub enum Error { /// Client error. - Client(client::error::Error), + Client(sp_blockchain::Error), /// IO error. Io(std::io::Error), /// Consensus error. diff --git a/substrate/client/src/call_executor.rs b/substrate/client/src/call_executor.rs index d37d2b0068..787e00a84d 100644 --- a/substrate/client/src/call_executor.rs +++ b/substrate/client/src/call_executor.rs @@ -31,9 +31,7 @@ use primitives::{ traits::CodeExecutor, }; use sr_api::{ProofRecorder, InitializeBlock}; -use client_api::{ - error, backend, call_executor::CallExecutor, -}; +use client_api::{backend, call_executor::CallExecutor}; /// Call executor that executes methods locally, querying all required /// data from local backend. @@ -79,7 +77,7 @@ where call_data: &[u8], strategy: ExecutionStrategy, extensions: Option, - ) -> error::Result> { + ) -> sp_blockchain::Result> { let mut changes = OverlayedChanges::default(); let state = self.backend.state_at(*id)?; let return_data = StateMachine::new( @@ -105,7 +103,7 @@ where fn contextual_call< 'a, - IB: Fn() -> error::Result<()>, + IB: Fn() -> sp_blockchain::Result<()>, EM: Fn( Result, Self::Error>, Result, Self::Error> @@ -124,7 +122,7 @@ where native_call: Option, recorder: &Option>, extensions: Option, - ) -> Result, error::Error> where ExecutionManager: Clone { + ) -> Result, sp_blockchain::Error> where ExecutionManager: Clone { match initialize_block { InitializeBlock::Do(ref init_block) if init_block.borrow().as_ref().map(|id| id != at).unwrap_or(true) => { @@ -189,7 +187,7 @@ where Ok(result) } - fn runtime_version(&self, id: &BlockId) -> error::Result { + fn runtime_version(&self, id: &BlockId) -> sp_blockchain::Result { let mut overlay = OverlayedChanges::default(); let state = self.backend.state_at(*id)?; @@ -204,7 +202,7 @@ where let _lock = self.backend.get_import_lock().read(); self.backend.destroy_state(state)?; } - version.ok_or(error::Error::VersionInvalid.into()) + version.ok_or(sp_blockchain::Error::VersionInvalid.into()) } fn call_at_state< @@ -223,7 +221,7 @@ where manager: ExecutionManager, native_call: Option, extensions: Option, - ) -> error::Result<( + ) -> sp_blockchain::Result<( NativeOrEncoded, (S::Transaction, ::Out), Option>>, @@ -255,7 +253,7 @@ where overlay: &mut OverlayedChanges, method: &str, call_data: &[u8] - ) -> Result<(Vec, StorageProof), error::Error> { + ) -> Result<(Vec, StorageProof), sp_blockchain::Error> { state_machine::prove_execution_on_trie_backend( trie_state, overlay, diff --git a/substrate/client/src/cht.rs b/substrate/client/src/cht.rs index 874ea02c2a..dc49069f0a 100644 --- a/substrate/client/src/cht.rs +++ b/substrate/client/src/cht.rs @@ -33,7 +33,7 @@ use state_machine::backend::InMemory as InMemoryState; use state_machine::{MemoryDB, TrieBackend, Backend as StateBackend, StorageProof, prove_read_on_trie_backend, read_proof_check, read_proof_check_on_proving_backend}; -use client_api::error::{Error as ClientError, Result as ClientResult}; +use sp_blockchain::{Error as ClientError, Result as ClientResult}; /// The size of each CHT. This value is passed to every CHT-related function from /// production code. Other values are passed from tests. diff --git a/substrate/client/src/client.rs b/substrate/client/src/client.rs index b7b704ce78..ea30948458 100644 --- a/substrate/client/src/client.rs +++ b/substrate/client/src/client.rs @@ -52,7 +52,12 @@ use consensus::{ ImportResult, BlockOrigin, ForkChoiceStrategy, SelectChain, self, }; -use header_metadata::{HeaderMetadata, CachedHeaderMetadata}; +use sp_blockchain::{self as blockchain, + Backend as ChainBackend, + HeaderBackend as ChainHeaderBackend, ProvideCache, Cache, + well_known_cache_keys::Id as CacheKeyId, + HeaderMetadata, CachedHeaderMetadata, +}; use sr_api::{CallRuntimeAt, ConstructRuntimeApi, Core as CoreApi, ProofRecorder, InitializeBlock}; use block_builder::BlockBuilderApi; @@ -62,11 +67,6 @@ pub use client_api::{ self, BlockImportOperation, PrunableStateChangesTrieStorage, ClientImportOperation, Finalizer, ImportSummary, NewBlockState, }, - blockchain::{ - self, Backend as ChainBackend, - HeaderBackend as ChainHeaderBackend, ProvideCache, Cache, - well_known_cache_keys::Id as CacheKeyId, - }, client::{ ImportNotifications, FinalityNotification, FinalityNotifications, BlockImportNotification, ClientInfo, BlockchainEvents, BlockBody, ProvideUncles, ForkBlocks, @@ -74,10 +74,9 @@ pub use client_api::{ }, execution_extensions::{ExecutionExtensions, ExecutionStrategies}, notifications::{StorageNotifications, StorageEventStream}, - error::Error, - error, CallExecutor, }; +use sp_blockchain::Error; use crate::{ call_executor::LocalCallExecutor, @@ -146,7 +145,7 @@ pub fn new_in_mem( executor: E, genesis_storage: S, keystore: Option, -) -> error::Result sp_blockchain::Result, LocalCallExecutor, E>, Block, @@ -166,7 +165,7 @@ pub fn new_with_backend( executor: E, build_genesis_storage: S, keystore: Option, -) -> error::Result, Block, RA>> +) -> sp_blockchain::Result, Block, RA>> where E: CodeExecutor + RuntimeInfo, S: BuildStorage, @@ -198,7 +197,7 @@ impl Client where build_genesis_storage: S, fork_blocks: ForkBlocks, execution_extensions: ExecutionExtensions, - ) -> error::Result { + ) -> sp_blockchain::Result { if backend.blockchain().header(BlockId::Number(Zero::zero()))?.is_none() { let (genesis_storage, children_genesis_storage) = build_genesis_storage.build_storage()?; let mut op = backend.begin_operation()?; @@ -237,29 +236,29 @@ impl Client where } /// Get a reference to the state at a given block. - pub fn state_at(&self, block: &BlockId) -> error::Result { + pub fn state_at(&self, block: &BlockId) -> sp_blockchain::Result { self.backend.state_at(*block) } /// Given a `BlockId` and a key prefix, return the matching child storage keys in that block. - pub fn storage_keys(&self, id: &BlockId, key_prefix: &StorageKey) -> error::Result> { + pub fn storage_keys(&self, id: &BlockId, key_prefix: &StorageKey) -> sp_blockchain::Result> { let keys = self.state_at(id)?.keys(&key_prefix.0).into_iter().map(StorageKey).collect(); Ok(keys) } /// Given a `BlockId` and a key, return the value under the key in that block. - pub fn storage(&self, id: &BlockId, key: &StorageKey) -> error::Result> { + pub fn storage(&self, id: &BlockId, key: &StorageKey) -> sp_blockchain::Result> { Ok(self.state_at(id)? - .storage(&key.0).map_err(|e| error::Error::from_state(Box::new(e)))? + .storage(&key.0).map_err(|e| sp_blockchain::Error::from_state(Box::new(e)))? .map(StorageData) ) } /// Given a `BlockId` and a key, return the value under the hash in that block. pub fn storage_hash(&self, id: &BlockId, key: &StorageKey) - -> error::Result> { + -> sp_blockchain::Result> { Ok(self.state_at(id)? - .storage_hash(&key.0).map_err(|e| error::Error::from_state(Box::new(e)))? + .storage_hash(&key.0).map_err(|e| sp_blockchain::Error::from_state(Box::new(e)))? ) } @@ -269,7 +268,7 @@ impl Client where id: &BlockId, child_storage_key: &StorageKey, key_prefix: &StorageKey - ) -> error::Result> { + ) -> sp_blockchain::Result> { let keys = self.state_at(id)? .child_keys(&child_storage_key.0, &key_prefix.0) .into_iter() @@ -284,9 +283,9 @@ impl Client where id: &BlockId, child_storage_key: &StorageKey, key: &StorageKey - ) -> error::Result> { + ) -> sp_blockchain::Result> { Ok(self.state_at(id)? - .child_storage(&child_storage_key.0, &key.0).map_err(|e| error::Error::from_state(Box::new(e)))? + .child_storage(&child_storage_key.0, &key.0).map_err(|e| sp_blockchain::Error::from_state(Box::new(e)))? .map(StorageData)) } @@ -296,21 +295,21 @@ impl Client where id: &BlockId, child_storage_key: &StorageKey, key: &StorageKey - ) -> error::Result> { + ) -> sp_blockchain::Result> { Ok(self.state_at(id)? - .child_storage_hash(&child_storage_key.0, &key.0).map_err(|e| error::Error::from_state(Box::new(e)))? + .child_storage_hash(&child_storage_key.0, &key.0).map_err(|e| sp_blockchain::Error::from_state(Box::new(e)))? ) } /// Get the code at a given block. - pub fn code_at(&self, id: &BlockId) -> error::Result> { + pub fn code_at(&self, id: &BlockId) -> sp_blockchain::Result> { Ok(self.storage(id, &StorageKey(well_known_keys::CODE.to_vec()))? .expect("None is returned if there's no value stored for the given key;\ ':code' key is always defined; qed").0) } /// Get the RuntimeVersion at a given block. - pub fn runtime_version_at(&self, id: &BlockId) -> error::Result { + pub fn runtime_version_at(&self, id: &BlockId) -> sp_blockchain::Result { self.executor.runtime_version(id) } @@ -320,7 +319,7 @@ impl Client where } /// Reads storage value at a given block + key, returning read proof. - pub fn read_proof(&self, id: &BlockId, keys: I) -> error::Result where + pub fn read_proof(&self, id: &BlockId, keys: I) -> sp_blockchain::Result where I: IntoIterator, I::Item: AsRef<[u8]>, { @@ -336,7 +335,7 @@ impl Client where id: &BlockId, storage_key: &[u8], keys: I, - ) -> error::Result where + ) -> sp_blockchain::Result where I: IntoIterator, I::Item: AsRef<[u8]>, { @@ -353,21 +352,21 @@ impl Client where id: &BlockId, method: &str, call_data: &[u8] - ) -> error::Result<(Vec, StorageProof)> { + ) -> sp_blockchain::Result<(Vec, StorageProof)> { let state = self.state_at(id)?; let header = self.prepare_environment_block(id)?; prove_execution(state, header, &self.executor, method, call_data) } /// Reads given header and generates CHT-based header proof. - pub fn header_proof(&self, id: &BlockId) -> error::Result<(Block::Header, StorageProof)> { + pub fn header_proof(&self, id: &BlockId) -> sp_blockchain::Result<(Block::Header, StorageProof)> { self.header_proof_with_cht_size(id, cht::size()) } /// Get block hash by number. pub fn block_hash(&self, block_number: <::Header as HeaderT>::Number - ) -> error::Result> { + ) -> sp_blockchain::Result> { self.backend.blockchain().hash(block_number) } @@ -376,8 +375,8 @@ impl Client where &self, id: &BlockId, cht_size: NumberFor, - ) -> error::Result<(Block::Header, StorageProof)> { - let proof_error = || error::Error::Backend(format!("Failed to generate header proof for {:?}", id)); + ) -> sp_blockchain::Result<(Block::Header, StorageProof)> { + let proof_error = || sp_blockchain::Error::Backend(format!("Failed to generate header proof for {:?}", id)); let header = self.backend.blockchain().expect_header(*id)?; let block_num = *header.number(); let cht_num = cht::block_to_cht_number(cht_size, block_num).ok_or_else(proof_error)?; @@ -401,14 +400,14 @@ impl Client where &self, first: NumberFor, last: BlockId, - ) -> error::Result, BlockId)>> { + ) -> sp_blockchain::Result, BlockId)>> { let (config, storage) = match self.require_changes_trie().ok() { Some((config, storage)) => (config, storage), None => return Ok(None), }; let last_num = self.backend.blockchain().expect_block_number_from_id(&last)?; if first > last_num { - return Err(error::Error::ChangesTrieAccessFailed("Invalid changes trie range".into())); + return Err(sp_blockchain::Error::ChangesTrieAccessFailed("Invalid changes trie range".into())); } let finalized_number = self.backend.blockchain().info().finalized_number; let oldest = storage.oldest_changes_trie_block(&config, finalized_number); @@ -426,7 +425,7 @@ impl Client where last: BlockId, storage_key: Option<&StorageKey>, key: &StorageKey - ) -> error::Result, u32)>> { + ) -> sp_blockchain::Result, u32)>> { let (config, storage) = self.require_changes_trie()?; let last_number = self.backend.blockchain().expect_block_number_from_id(&last)?; let last_hash = self.backend.blockchain().expect_block_hash_from_id(&last)?; @@ -450,7 +449,7 @@ impl Client where storage_key.as_ref().map(|sk| sk.0.as_slice()), &key.0) .and_then(|r| r.map(|r| r.map(|(block, tx)| (block, tx))).collect::>()) - .map_err(|err| error::Error::ChangesTrieAccessFailed(err)) + .map_err(|err| sp_blockchain::Error::ChangesTrieAccessFailed(err)) } /// Get proof for computation of (block, extrinsic) pairs where key has been changed at given blocks range. @@ -467,7 +466,7 @@ impl Client where max: Block::Hash, storage_key: Option<&StorageKey>, key: &StorageKey, - ) -> error::Result> { + ) -> sp_blockchain::Result> { self.key_changes_proof_with_cht_size( first, last, @@ -489,7 +488,7 @@ impl Client where storage_key: Option<&StorageKey>, key: &StorageKey, cht_size: NumberFor, - ) -> error::Result> { + ) -> sp_blockchain::Result> { struct AccessedRootsRecorder<'a, Block: BlockT> { storage: &'a dyn ChangesTrieStorage>, min: NumberFor, @@ -575,7 +574,7 @@ impl Client where storage_key.as_ref().map(|sk| sk.0.as_slice()), &key.0, ) - .map_err(|err| error::Error::from(error::Error::ChangesTrieAccessFailed(err)))?; + .map_err(|err| sp_blockchain::Error::from(sp_blockchain::Error::ChangesTrieAccessFailed(err)))?; // now gather proofs for all changes tries roots that were touched during key_changes_proof // execution AND are unknown (i.e. replaced with CHT) to the requester @@ -595,7 +594,7 @@ impl Client where &self, cht_size: NumberFor, blocks: I - ) -> error::Result { + ) -> sp_blockchain::Result { // most probably we have touched several changes tries that are parts of the single CHT // => GroupBy changes tries by CHT number and then gather proof for the whole group at once let mut proofs = Vec::new(); @@ -615,7 +614,7 @@ impl Client where cht_size: NumberFor, cht_num: NumberFor, blocks: Vec> - ) -> error::Result { + ) -> sp_blockchain::Result { let cht_start = cht::start_number(cht_size, cht_num); let mut current_num = cht_start; let cht_range = ::std::iter::from_fn(|| { @@ -631,12 +630,12 @@ impl Client where } /// Returns changes trie configuration and storage or an error if it is not supported. - fn require_changes_trie(&self) -> error::Result<(ChangesTrieConfiguration, &B::ChangesTrieStorage)> { + fn require_changes_trie(&self) -> sp_blockchain::Result<(ChangesTrieConfiguration, &B::ChangesTrieStorage)> { let config = self.changes_trie_config()?; let storage = self.backend.changes_trie_storage(); match (config, storage) { (Some(config), Some(storage)) => Ok((config, storage)), - _ => Err(error::Error::ChangesTriesNotSupported.into()), + _ => Err(sp_blockchain::Error::ChangesTriesNotSupported.into()), } } @@ -644,7 +643,7 @@ impl Client where pub fn new_block( &self, inherent_digests: DigestFor, - ) -> error::Result> where + ) -> sp_blockchain::Result> where E: Clone + Send + Sync, RA: Send + Sync, Self: ProvideRuntimeApi, @@ -665,7 +664,7 @@ impl Client where &self, parent: &BlockId, inherent_digests: DigestFor, - ) -> error::Result> where + ) -> sp_blockchain::Result> where E: Clone + Send + Sync, RA: Send + Sync, Self: ProvideRuntimeApi, @@ -689,7 +688,7 @@ impl Client where &self, parent: &BlockId, inherent_digests: DigestFor, - ) -> error::Result> where + ) -> sp_blockchain::Result> where E: Clone + Send + Sync, RA: Send + Sync, Self: ProvideRuntimeApi, @@ -707,7 +706,7 @@ impl Client where /// Lock the import lock, and run operations inside. pub fn lock_import_and_run(&self, f: F) -> Result where F: FnOnce(&mut ClientImportOperation) -> Result, - Err: From, + Err: From, { let inner = || { let _import_lock = self.backend.get_import_lock().write(); @@ -744,7 +743,7 @@ impl Client where operation: &mut ClientImportOperation, import_block: BlockImportParams, new_cache: HashMap>, - ) -> error::Result where + ) -> sp_blockchain::Result where E: CallExecutor + Send + Sync + Clone, { let BlockImportParams { @@ -829,7 +828,7 @@ impl Client where aux: Vec<(Vec, Option>)>, fork_choice: ForkChoiceStrategy, enact_state: bool, - ) -> error::Result where + ) -> sp_blockchain::Result where E: CallExecutor + Send + Sync + Clone, { let parent_hash = import_headers.post().parent_hash().clone(); @@ -843,7 +842,7 @@ impl Client where // the block is lower than our last finalized block so it must revert // finality, refusing import. if *import_headers.post().number() <= info.finalized_number { - return Err(error::Error::NotInFinalizedChain); + return Err(sp_blockchain::Error::NotInFinalizedChain); } // this is a fairly arbitrary choice of where to draw the line on making notifications, @@ -902,7 +901,7 @@ impl Client where }; let retracted = if is_new_best { - let route_from_best = header_metadata::tree_route( + let route_from_best = sp_blockchain::tree_route( self.backend.blockchain(), info.best_hash, parent_hash, @@ -948,7 +947,7 @@ impl Client where origin: BlockOrigin, hash: Block::Hash, body: &[Block::Extrinsic], - ) -> error::Result<( + ) -> sp_blockchain::Result<( Option>, Option>>, Option<( @@ -1009,7 +1008,7 @@ impl Client where let (top, children) = overlay.into_committed(); let children = children.map(|(sk, it)| (sk, it.collect())).collect(); if import_headers.post().state_root() != &storage_update.1 { - return Err(error::Error::InvalidStateRoot); + return Err(sp_blockchain::Error::InvalidStateRoot); } Ok((Some(storage_update.0), Some(changes_update), Some((top.collect(), children)))) @@ -1025,7 +1024,7 @@ impl Client where justification: Option, best_block: Block::Hash, notify: bool, - ) -> error::Result<()> { + ) -> sp_blockchain::Result<()> { // find tree route from last finalized to given block. let last_finalized = self.backend.blockchain().last_finalized()?; @@ -1034,16 +1033,16 @@ impl Client where return Ok(()); } - let route_from_finalized = header_metadata::tree_route(self.backend.blockchain(), last_finalized, block)?; + let route_from_finalized = sp_blockchain::tree_route(self.backend.blockchain(), last_finalized, block)?; if let Some(retracted) = route_from_finalized.retracted().get(0) { warn!("Safety violation: attempted to revert finalized block {:?} which is not in the \ same chain as last finalized {:?}", retracted, last_finalized); - return Err(error::Error::NotInFinalizedChain); + return Err(sp_blockchain::Error::NotInFinalizedChain); } - let route_from_best = header_metadata::tree_route(self.backend.blockchain(), best_block, block)?; + let route_from_best = sp_blockchain::tree_route(self.backend.blockchain(), best_block, block)?; // if the block is not a direct ancestor of the current best chain, // then some other block is the common ancestor. @@ -1083,7 +1082,7 @@ impl Client where fn notify_finalized( &self, notify_finalized: Vec, - ) -> error::Result<()> { + ) -> sp_blockchain::Result<()> { let mut sinks = self.finality_notification_sinks.lock(); for finalized_hash in notify_finalized { @@ -1106,7 +1105,7 @@ impl Client where Ok(()) } - fn notify_imported(&self, notify_import: ImportSummary) -> error::Result<()> { + fn notify_imported(&self, notify_import: ImportSummary) -> sp_blockchain::Result<()> { if let Some(storage_changes) = notify_import.storage_changes { // TODO [ToDr] How to handle re-orgs? Should we re-emit all storage changes? self.storage_notifications.lock() @@ -1133,7 +1132,7 @@ impl Client where /// Attempts to revert the chain by `n` blocks. Returns the number of blocks that were /// successfully reverted. - pub fn revert(&self, n: NumberFor) -> error::Result> { + pub fn revert(&self, n: NumberFor) -> sp_blockchain::Result> { Ok(self.backend.revert(n)?) } @@ -1147,7 +1146,7 @@ impl Client where } /// Get block status. - pub fn block_status(&self, id: &BlockId) -> error::Result { + pub fn block_status(&self, id: &BlockId) -> sp_blockchain::Result { // this can probably be implemented more efficiently if let BlockId::Hash(ref h) = id { if self.importing_block.read().as_ref().map_or(false, |importing| h == importing) { @@ -1171,23 +1170,23 @@ impl Client where } /// Get block header by id. - pub fn header(&self, id: &BlockId) -> error::Result::Header>> { + pub fn header(&self, id: &BlockId) -> sp_blockchain::Result::Header>> { self.backend.blockchain().header(*id) } /// Get block body by id. - pub fn body(&self, id: &BlockId) -> error::Result::Extrinsic>>> { + pub fn body(&self, id: &BlockId) -> sp_blockchain::Result::Extrinsic>>> { self.backend.blockchain().body(*id) } /// Get block justification set by id. - pub fn justification(&self, id: &BlockId) -> error::Result> { + pub fn justification(&self, id: &BlockId) -> sp_blockchain::Result> { self.backend.blockchain().justification(*id) } /// Get full block by id. pub fn block(&self, id: &BlockId) - -> error::Result>> + -> sp_blockchain::Result>> { Ok(match (self.header(id)?, self.body(id)?, self.justification(id)?) { (Some(header), Some(extrinsics), justification) => @@ -1197,8 +1196,8 @@ impl Client where } /// Gets the uncles of the block with `target_hash` going back `max_generation` ancestors. - pub fn uncles(&self, target_hash: Block::Hash, max_generation: NumberFor) -> error::Result> { - let load_header = |id: Block::Hash| -> error::Result { + pub fn uncles(&self, target_hash: Block::Hash, max_generation: NumberFor) -> sp_blockchain::Result> { + let load_header = |id: Block::Hash| -> sp_blockchain::Result { match self.backend.blockchain().header(BlockId::Hash(id))? { Some(hdr) => Ok(hdr), None => Err(Error::UnknownBlock(format!("{:?}", id))), @@ -1230,12 +1229,12 @@ impl Client where fn changes_trie_config(&self) -> Result, Error> { Ok(self.backend.state_at(BlockId::Number(self.backend.blockchain().info().best_number))? .storage(well_known_keys::CHANGES_TRIE_CONFIG) - .map_err(|e| error::Error::from_state(Box::new(e)))? + .map_err(|e| sp_blockchain::Error::from_state(Box::new(e)))? .and_then(|c| Decode::decode(&mut &*c).ok())) } /// Prepare in-memory header that is used in execution environment. - fn prepare_environment_block(&self, parent: &BlockId) -> error::Result { + fn prepare_environment_block(&self, parent: &BlockId) -> sp_blockchain::Result { let parent_header = self.backend.blockchain().expect_header(*parent)?; Ok(<::Header as HeaderT>::new( self.backend.blockchain().expect_block_number_from_id(parent)? + One::one(), @@ -1252,7 +1251,7 @@ impl HeaderMetadata for Client where E: CallExecutor, Block: BlockT, { - type Error = error::Error; + type Error = sp_blockchain::Error; fn header_metadata(&self, hash: Block::Hash) -> Result, Self::Error> { self.backend.blockchain().header_metadata(hash) @@ -1272,7 +1271,7 @@ impl ProvideUncles for Client where E: CallExecutor, Block: BlockT, { - fn uncles(&self, target_hash: Block::Hash, max_generation: NumberFor) -> error::Result> { + fn uncles(&self, target_hash: Block::Hash, max_generation: NumberFor) -> sp_blockchain::Result> { Ok(Client::uncles(self, target_hash, max_generation)? .into_iter() .filter_map(|hash| Client::header(self, &BlockId::Hash(hash)).unwrap_or(None)) @@ -1287,7 +1286,7 @@ impl ChainHeaderBackend for Client wher Block: BlockT, RA: Send + Sync, { - fn header(&self, id: BlockId) -> error::Result> { + fn header(&self, id: BlockId) -> sp_blockchain::Result> { self.backend.blockchain().header(id) } @@ -1295,15 +1294,15 @@ impl ChainHeaderBackend for Client wher self.backend.blockchain().info() } - fn status(&self, id: BlockId) -> error::Result { + fn status(&self, id: BlockId) -> sp_blockchain::Result { self.backend.blockchain().status(id) } - fn number(&self, hash: Block::Hash) -> error::Result::Header as HeaderT>::Number>> { + fn number(&self, hash: Block::Hash) -> sp_blockchain::Result::Header as HeaderT>::Number>> { self.backend.blockchain().number(hash) } - fn hash(&self, number: NumberFor) -> error::Result> { + fn hash(&self, number: NumberFor) -> sp_blockchain::Result> { self.backend.blockchain().hash(number) } } @@ -1316,11 +1315,11 @@ impl sr_primitives::traits::BlockIdTo for Client) -> error::Result> { + fn to_hash(&self, block_id: &BlockId) -> sp_blockchain::Result> { self.block_hash_from_id(block_id) } - fn to_number(&self, block_id: &BlockId) -> error::Result>> { + fn to_number(&self, block_id: &BlockId) -> sp_blockchain::Result>> { self.block_number_from_id(block_id) } } @@ -1331,7 +1330,7 @@ impl ChainHeaderBackend for &Client whe Block: BlockT, RA: Send + Sync, { - fn header(&self, id: BlockId) -> error::Result> { + fn header(&self, id: BlockId) -> sp_blockchain::Result> { (**self).backend.blockchain().header(id) } @@ -1339,15 +1338,15 @@ impl ChainHeaderBackend for &Client whe (**self).backend.blockchain().info() } - fn status(&self, id: BlockId) -> error::Result { + fn status(&self, id: BlockId) -> sp_blockchain::Result { (**self).status(id) } - fn number(&self, hash: Block::Hash) -> error::Result::Header as HeaderT>::Number>> { + fn number(&self, hash: Block::Hash) -> sp_blockchain::Result::Header as HeaderT>::Number>> { (**self).number(hash) } - fn hash(&self, number: NumberFor) -> error::Result> { + fn hash(&self, number: NumberFor) -> sp_blockchain::Result> { (**self).hash(number) } } @@ -1397,7 +1396,7 @@ impl CallRuntimeAt for Client where native_call: Option, context: ExecutionContext, recorder: &Option>, - ) -> error::Result> { + ) -> sp_blockchain::Result> { let (manager, extensions) = self.execution_extensions.manager_and_extensions(at, context); self.executor.contextual_call::<_, fn(_,_) -> _,_,_>( || core_api.initialize_block(at, &self.prepare_environment_block(at)?), @@ -1413,7 +1412,7 @@ impl CallRuntimeAt for Client where ) } - fn runtime_version_at(&self, at: &BlockId) -> error::Result { + fn runtime_version_at(&self, at: &BlockId) -> sp_blockchain::Result { self.runtime_version_at(at) } } @@ -1529,13 +1528,13 @@ impl Finalizer for Client, justification: Option, notify: bool, - ) -> error::Result<()> { + ) -> sp_blockchain::Result<()> { let last_best = self.backend.blockchain().info().best_hash; let to_finalize_hash = self.backend.blockchain().expect_block_hash_from_id(&id)?; self.apply_finality_with_block_hash(operation, to_finalize_hash, justification, last_best, notify) } - fn finalize_block(&self, id: BlockId, justification: Option, notify: bool) -> error::Result<()> { + fn finalize_block(&self, id: BlockId, justification: Option, notify: bool) -> sp_blockchain::Result<()> { self.lock_import_and_run(|operation| { self.apply_finality(operation, id, justification, notify) }) @@ -1553,11 +1552,11 @@ impl Finalizer for &Client, justification: Option, notify: bool, - ) -> error::Result<()> { + ) -> sp_blockchain::Result<()> { (**self).apply_finality(operation, id, justification, notify) } - fn finalize_block(&self, id: BlockId, justification: Option, notify: bool) -> error::Result<()> { + fn finalize_block(&self, id: BlockId, justification: Option, notify: bool) -> sp_blockchain::Result<()> { (**self).finalize_block(id, justification, notify) } } @@ -1585,7 +1584,7 @@ where &self, filter_keys: Option<&[StorageKey]>, child_filter_keys: Option<&[(StorageKey, Option>)]>, - ) -> error::Result> { + ) -> sp_blockchain::Result> { Ok(self.storage_notifications.lock().listen(filter_keys, child_filter_keys)) } } @@ -1620,7 +1619,7 @@ where } } - fn best_block_header(&self) -> error::Result<::Header> { + fn best_block_header(&self) -> sp_blockchain::Result<::Header> { let info = self.backend.blockchain().info(); let import_lock = self.backend.get_import_lock(); let best_hash = self.backend.blockchain().best_containing(info.best_hash, None, import_lock)? @@ -1630,7 +1629,7 @@ where .expect("given block hash was fetched from block in db; qed")) } - fn leaves(&self) -> Result::Hash>, error::Error> { + fn leaves(&self) -> Result::Hash>, sp_blockchain::Error> { self.backend.blockchain().leaves() } } @@ -1670,7 +1669,7 @@ impl BlockBody for Client E: CallExecutor, Block: BlockT, { - fn block_body(&self, id: &BlockId) -> error::Result::Extrinsic>>> { + fn block_body(&self, id: &BlockId) -> sp_blockchain::Result::Extrinsic>>> { self.body(id) } } @@ -1688,7 +1687,7 @@ impl backend::AuxStore for Client 'c: 'a, I: IntoIterator, D: IntoIterator, - >(&self, insert: I, delete: D) -> error::Result<()> { + >(&self, insert: I, delete: D) -> sp_blockchain::Result<()> { // Import is locked here because we may have other block import // operations that tries to set aux data. Note that for consensus // layer, one can always use atomic operations to make sure @@ -1698,7 +1697,7 @@ impl backend::AuxStore for Client }) } /// Query auxiliary data from key-value store. - fn get_aux(&self, key: &[u8]) -> error::Result>> { + fn get_aux(&self, key: &[u8]) -> sp_blockchain::Result>> { backend::AuxStore::get_aux(&*self.backend, key) } } @@ -1717,11 +1716,11 @@ impl backend::AuxStore for &Client 'c: 'a, I: IntoIterator, D: IntoIterator, - >(&self, insert: I, delete: D) -> error::Result<()> { + >(&self, insert: I, delete: D) -> sp_blockchain::Result<()> { (**self).insert_aux(insert, delete) } - fn get_aux(&self, key: &[u8]) -> error::Result>> { + fn get_aux(&self, key: &[u8]) -> sp_blockchain::Result>> { (**self).get_aux(key) } } @@ -1731,7 +1730,7 @@ pub fn apply_aux<'a, 'b: 'a, 'c: 'a, B, Block, H, D, I>( operation: &mut ClientImportOperation, insert: I, delete: D -) -> error::Result<()> +) -> sp_blockchain::Result<()> where Block: BlockT, H: Hasher, @@ -2702,7 +2701,7 @@ pub(crate) mod tests { let import_err = client.import(BlockOrigin::Own, b3).err().unwrap(); let expected_err = ConsensusError::ClientImport( - error::Error::NotInFinalizedChain.to_string() + sp_blockchain::Error::NotInFinalizedChain.to_string() ); assert_eq!( @@ -2725,7 +2724,7 @@ pub(crate) mod tests { let import_err = client.import(BlockOrigin::Own, c1).err().unwrap(); let expected_err = ConsensusError::ClientImport( - error::Error::NotInFinalizedChain.to_string() + sp_blockchain::Error::NotInFinalizedChain.to_string() ); assert_eq!( diff --git a/substrate/client/src/in_mem.rs b/substrate/client/src/in_mem.rs index d56c3f2b07..e6140e6d74 100644 --- a/substrate/client/src/in_mem.rs +++ b/substrate/client/src/in_mem.rs @@ -30,10 +30,9 @@ use state_machine::backend::{Backend as StateBackend, InMemory}; use state_machine::{self, InMemoryChangesTrieStorage, ChangesTrieAnchorBlockId, ChangesTrieTransaction}; use hash_db::{Hasher, Prefix}; use trie::MemoryDB; -use header_metadata::{CachedHeaderMetadata, HeaderMetadata}; +use sp_blockchain::{CachedHeaderMetadata, HeaderMetadata}; use client_api::{ - error, backend::{self, NewBlockState, StorageCollection, ChildStorageCollection}, blockchain::{ self, BlockStatus, HeaderBackend, well_known_cache_keys::Id as CacheKeyId @@ -158,7 +157,7 @@ impl Blockchain { justification: Option, body: Option::Extrinsic>>, new_state: NewBlockState, - ) -> client_api::error::Result<()> { + ) -> sp_blockchain::Result<()> { let number = header.number().clone(); if new_state.is_best() { self.apply_head(&header)?; @@ -208,16 +207,16 @@ impl Blockchain { } /// Set an existing block as head. - pub fn set_head(&self, id: BlockId) -> error::Result<()> { + pub fn set_head(&self, id: BlockId) -> sp_blockchain::Result<()> { let header = match self.header(id)? { Some(h) => h, - None => return Err(error::Error::UnknownBlock(format!("{}", id))), + None => return Err(sp_blockchain::Error::UnknownBlock(format!("{}", id))), }; self.apply_head(&header) } - fn apply_head(&self, header: &::Header) -> error::Result<()> { + fn apply_head(&self, header: &::Header) -> sp_blockchain::Result<()> { let hash = header.hash(); let number = header.number(); @@ -228,7 +227,7 @@ impl Blockchain { if &best_hash == header.parent_hash() { None } else { - let route = header_metadata::tree_route(self, best_hash, *header.parent_hash())?; + let route = sp_blockchain::tree_route(self, best_hash, *header.parent_hash())?; Some(route) } }; @@ -255,10 +254,10 @@ impl Blockchain { Ok(()) } - fn finalize_header(&self, id: BlockId, justification: Option) -> error::Result<()> { + fn finalize_header(&self, id: BlockId, justification: Option) -> sp_blockchain::Result<()> { let hash = match self.header(id)? { Some(h) => h.hash(), - None => return Err(error::Error::UnknownBlock(format!("{}", id))), + None => return Err(sp_blockchain::Error::UnknownBlock(format!("{}", id))), }; let mut storage = self.storage.write(); @@ -290,7 +289,7 @@ impl Blockchain { } impl HeaderBackend for Blockchain { - fn header(&self, id: BlockId) -> error::Result::Header>> { + fn header(&self, id: BlockId) -> sp_blockchain::Result::Header>> { Ok(self.id(id).and_then(|hash| { self.storage.read().blocks.get(&hash).map(|b| b.header().clone()) })) @@ -307,28 +306,28 @@ impl HeaderBackend for Blockchain { } } - fn status(&self, id: BlockId) -> error::Result { + fn status(&self, id: BlockId) -> sp_blockchain::Result { match self.id(id).map_or(false, |hash| self.storage.read().blocks.contains_key(&hash)) { true => Ok(BlockStatus::InChain), false => Ok(BlockStatus::Unknown), } } - fn number(&self, hash: Block::Hash) -> error::Result>> { + fn number(&self, hash: Block::Hash) -> sp_blockchain::Result>> { Ok(self.storage.read().blocks.get(&hash).map(|b| *b.header().number())) } - fn hash(&self, number: <::Header as HeaderT>::Number) -> error::Result> { + fn hash(&self, number: <::Header as HeaderT>::Number) -> sp_blockchain::Result> { Ok(self.id(BlockId::Number(number))) } } impl HeaderMetadata for Blockchain { - type Error = error::Error; + type Error = sp_blockchain::Error; fn header_metadata(&self, hash: Block::Hash) -> Result, Self::Error> { self.header(BlockId::hash(hash))?.map(|header| CachedHeaderMetadata::from(&header)) - .ok_or(error::Error::UnknownBlock(format!("header not found: {}", hash))) + .ok_or(sp_blockchain::Error::UnknownBlock(format!("header not found: {}", hash))) } fn insert_header_metadata(&self, _hash: Block::Hash, _metadata: CachedHeaderMetadata) { @@ -340,20 +339,20 @@ impl HeaderMetadata for Blockchain { } impl blockchain::Backend for Blockchain { - fn body(&self, id: BlockId) -> error::Result::Extrinsic>>> { + fn body(&self, id: BlockId) -> sp_blockchain::Result::Extrinsic>>> { Ok(self.id(id).and_then(|hash| { self.storage.read().blocks.get(&hash) .and_then(|b| b.extrinsics().map(|x| x.to_vec())) })) } - fn justification(&self, id: BlockId) -> error::Result> { + fn justification(&self, id: BlockId) -> sp_blockchain::Result> { Ok(self.id(id).and_then(|hash| self.storage.read().blocks.get(&hash).and_then(|b| b.justification().map(|x| x.clone())) )) } - fn last_finalized(&self) -> error::Result { + fn last_finalized(&self) -> sp_blockchain::Result { Ok(self.storage.read().finalized_hash.clone()) } @@ -361,11 +360,11 @@ impl blockchain::Backend for Blockchain { None } - fn leaves(&self) -> error::Result> { + fn leaves(&self) -> sp_blockchain::Result> { Ok(self.storage.read().leaves.hashes()) } - fn children(&self, _parent_hash: Block::Hash) -> error::Result> { + fn children(&self, _parent_hash: Block::Hash) -> sp_blockchain::Result> { unimplemented!() } } @@ -383,7 +382,7 @@ impl backend::AuxStore for Blockchain { 'c: 'a, I: IntoIterator, D: IntoIterator, - >(&self, insert: I, delete: D) -> error::Result<()> { + >(&self, insert: I, delete: D) -> sp_blockchain::Result<()> { let mut storage = self.storage.write(); for (k, v) in insert { storage.aux.insert(k.to_vec(), v.to_vec()); @@ -394,7 +393,7 @@ impl backend::AuxStore for Blockchain { Ok(()) } - fn get_aux(&self, key: &[u8]) -> error::Result>> { + fn get_aux(&self, key: &[u8]) -> sp_blockchain::Result>> { Ok(self.storage.read().aux.get(key).cloned()) } } @@ -409,7 +408,7 @@ impl client_api::light::Storage for Blockchain _cache: HashMap>, state: NewBlockState, aux_ops: Vec<(Vec, Option>)>, - ) -> error::Result<()> { + ) -> sp_blockchain::Result<()> { let hash = header.hash(); self.insert(hash, header, None, None, state)?; @@ -417,15 +416,15 @@ impl client_api::light::Storage for Blockchain Ok(()) } - fn set_head(&self, id: BlockId) -> error::Result<()> { + fn set_head(&self, id: BlockId) -> sp_blockchain::Result<()> { Blockchain::set_head(self, id) } - fn last_finalized(&self) -> error::Result { + fn last_finalized(&self) -> sp_blockchain::Result { Ok(self.storage.read().finalized_hash.clone()) } - fn finalize_header(&self, id: BlockId) -> error::Result<()> { + fn finalize_header(&self, id: BlockId) -> sp_blockchain::Result<()> { Blockchain::finalize_header(self, id, None) } @@ -433,18 +432,18 @@ impl client_api::light::Storage for Blockchain &self, _cht_size: NumberFor, block: NumberFor, - ) -> error::Result { + ) -> sp_blockchain::Result { self.storage.read().header_cht_roots.get(&block).cloned() - .ok_or_else(|| error::Error::Backend(format!("Header CHT for block {} not exists", block))) + .ok_or_else(|| sp_blockchain::Error::Backend(format!("Header CHT for block {} not exists", block))) } fn changes_trie_cht_root( &self, _cht_size: NumberFor, block: NumberFor, - ) -> error::Result { + ) -> sp_blockchain::Result { self.storage.read().changes_trie_cht_roots.get(&block).cloned() - .ok_or_else(|| error::Error::Backend(format!("Changes trie CHT for block {} not exists", block))) + .ok_or_else(|| sp_blockchain::Error::Backend(format!("Changes trie CHT for block {} not exists", block))) } fn cache(&self) -> Option>> { @@ -473,7 +472,7 @@ where { type State = InMemory; - fn state(&self) -> error::Result> { + fn state(&self) -> sp_blockchain::Result> { Ok(Some(&self.old_state)) } @@ -483,7 +482,7 @@ where body: Option::Extrinsic>>, justification: Option, state: NewBlockState, - ) -> error::Result<()> { + ) -> sp_blockchain::Result<()> { assert!(self.pending_block.is_none(), "Only one block per operation is allowed"); self.pending_block = Some(PendingBlock { block: StoredBlock::new(header, body, justification), @@ -496,17 +495,17 @@ where self.pending_cache = cache; } - fn update_db_storage(&mut self, update: as StateBackend>::Transaction) -> error::Result<()> { + fn update_db_storage(&mut self, update: as StateBackend>::Transaction) -> sp_blockchain::Result<()> { self.new_state = Some(self.old_state.update(update)); Ok(()) } - fn update_changes_trie(&mut self, update: ChangesTrieTransaction>) -> error::Result<()> { + fn update_changes_trie(&mut self, update: ChangesTrieTransaction>) -> sp_blockchain::Result<()> { self.changes_trie_update = Some(update.0); Ok(()) } - fn reset_storage(&mut self, top: StorageOverlay, children: ChildrenStorageOverlay) -> error::Result { + fn reset_storage(&mut self, top: StorageOverlay, children: ChildrenStorageOverlay) -> sp_blockchain::Result { check_genesis_storage(&top, &children)?; let child_delta = children.into_iter() @@ -522,7 +521,7 @@ where Ok(root) } - fn insert_aux(&mut self, ops: I) -> error::Result<()> + fn insert_aux(&mut self, ops: I) -> sp_blockchain::Result<()> where I: IntoIterator, Option>)> { self.aux.append(&mut ops.into_iter().collect()); @@ -533,16 +532,16 @@ where &mut self, _update: StorageCollection, _child_update: ChildStorageCollection, - ) -> error::Result<()> { + ) -> sp_blockchain::Result<()> { Ok(()) } - fn mark_finalized(&mut self, block: BlockId, justification: Option) -> error::Result<()> { + fn mark_finalized(&mut self, block: BlockId, justification: Option) -> sp_blockchain::Result<()> { self.finalized_blocks.push((block, justification)); Ok(()) } - fn mark_head(&mut self, block: BlockId) -> error::Result<()> { + fn mark_head(&mut self, block: BlockId) -> sp_blockchain::Result<()> { assert!(self.pending_block.is_none(), "Only one set block per operation is allowed"); self.set_head = Some(block); Ok(()) @@ -594,11 +593,11 @@ where 'c: 'a, I: IntoIterator, D: IntoIterator, - >(&self, insert: I, delete: D) -> error::Result<()> { + >(&self, insert: I, delete: D) -> sp_blockchain::Result<()> { self.blockchain.insert_aux(insert, delete) } - fn get_aux(&self, key: &[u8]) -> error::Result>> { + fn get_aux(&self, key: &[u8]) -> sp_blockchain::Result>> { self.blockchain.get_aux(key) } } @@ -615,7 +614,7 @@ where type ChangesTrieStorage = ChangesTrieStorage; type OffchainStorage = OffchainStorage; - fn begin_operation(&self) -> error::Result { + fn begin_operation(&self) -> sp_blockchain::Result { let old_state = self.state_at(BlockId::Hash(Default::default()))?; Ok(BlockImportOperation { pending_block: None, @@ -629,12 +628,12 @@ where }) } - fn begin_state_operation(&self, operation: &mut Self::BlockImportOperation, block: BlockId) -> error::Result<()> { + fn begin_state_operation(&self, operation: &mut Self::BlockImportOperation, block: BlockId) -> sp_blockchain::Result<()> { operation.old_state = self.state_at(block)?; Ok(()) } - fn commit_operation(&self, operation: Self::BlockImportOperation) -> error::Result<()> { + fn commit_operation(&self, operation: Self::BlockImportOperation) -> sp_blockchain::Result<()> { if !operation.finalized_blocks.is_empty() { for (block, justification) in operation.finalized_blocks { self.blockchain.finalize_header(block, justification)?; @@ -674,7 +673,7 @@ where Ok(()) } - fn finalize_block(&self, block: BlockId, justification: Option) -> error::Result<()> { + fn finalize_block(&self, block: BlockId, justification: Option) -> sp_blockchain::Result<()> { self.blockchain.finalize_header(block, justification) } @@ -694,7 +693,7 @@ where None } - fn state_at(&self, block: BlockId) -> error::Result { + fn state_at(&self, block: BlockId) -> sp_blockchain::Result { match block { BlockId::Hash(h) if h == Default::default() => { return Ok(Self::State::default()); @@ -704,11 +703,11 @@ where match self.blockchain.id(block).and_then(|id| self.states.read().get(&id).cloned()) { Some(state) => Ok(state), - None => Err(error::Error::UnknownBlock(format!("{}", block))), + None => Err(sp_blockchain::Error::UnknownBlock(format!("{}", block))), } } - fn revert(&self, _n: NumberFor) -> error::Result> { + fn revert(&self, _n: NumberFor) -> sp_blockchain::Result> { Ok(Zero::zero()) } @@ -797,13 +796,13 @@ impl state_machine::ChangesTrieStorage> for Change } /// Check that genesis storage is valid. -pub fn check_genesis_storage(top: &StorageOverlay, children: &ChildrenStorageOverlay) -> error::Result<()> { +pub fn check_genesis_storage(top: &StorageOverlay, children: &ChildrenStorageOverlay) -> sp_blockchain::Result<()> { if top.iter().any(|(k, _)| well_known_keys::is_child_storage_key(k)) { - return Err(error::Error::GenesisInvalid.into()); + return Err(sp_blockchain::Error::GenesisInvalid.into()); } if children.keys().any(|child_key| !well_known_keys::is_child_storage_key(&child_key)) { - return Err(error::Error::GenesisInvalid.into()); + return Err(sp_blockchain::Error::GenesisInvalid.into()); } Ok(()) diff --git a/substrate/client/src/leaves.rs b/substrate/client/src/leaves.rs index bc42e83a66..83cfa59896 100644 --- a/substrate/client/src/leaves.rs +++ b/substrate/client/src/leaves.rs @@ -21,7 +21,7 @@ use std::cmp::Reverse; use kvdb::{KeyValueDB, DBTransaction}; use sr_primitives::traits::SimpleArithmetic; use codec::{Encode, Decode}; -use client_api::error; +use sp_blockchain::{Error, Result}; #[derive(Debug, Clone, PartialEq, Eq)] struct LeafSetItem { @@ -77,7 +77,7 @@ impl LeafSet where } /// Read the leaf list from the DB, using given prefix for keys. - pub fn read_from_db(db: &dyn KeyValueDB, column: Option, prefix: &[u8]) -> error::Result { + pub fn read_from_db(db: &dyn KeyValueDB, column: Option, prefix: &[u8]) -> Result { let mut storage = BTreeMap::new(); for (key, value) in db.iter_from_prefix(column, prefix) { @@ -85,11 +85,11 @@ impl LeafSet where let raw_hash = &mut &key[prefix.len()..]; let hash = match Decode::decode(raw_hash) { Ok(hash) => hash, - Err(_) => return Err(error::Error::Backend("Error decoding hash".into())), + Err(_) => return Err(Error::Backend("Error decoding hash".into())), }; let number = match Decode::decode(&mut &value[..]) { Ok(number) => number, - Err(_) => return Err(error::Error::Backend("Error decoding number".into())), + Err(_) => return Err(Error::Backend("Error decoding number".into())), }; storage.entry(Reverse(number)).or_insert_with(Vec::new).push(hash); } diff --git a/substrate/client/src/lib.rs b/substrate/client/src/lib.rs index 71127d3cb0..1bbfbe0270 100644 --- a/substrate/client/src/lib.rs +++ b/substrate/client/src/lib.rs @@ -84,7 +84,6 @@ mod call_executor; mod client; pub use client_api::{ - error, blockchain, blockchain::well_known_cache_keys, blockchain::Info as ChainInfo, diff --git a/substrate/client/src/light/backend.rs b/substrate/client/src/light/backend.rs index 8b0d965149..da21ebf9e8 100644 --- a/substrate/client/src/light/backend.rs +++ b/substrate/client/src/light/backend.rs @@ -26,6 +26,7 @@ use primitives::offchain::storage::InMemOffchainStorage; use sr_primitives::{generic::BlockId, Justification, StorageOverlay, ChildrenStorageOverlay}; use sr_primitives::traits::{Block as BlockT, NumberFor, Zero, Header}; use crate::in_mem::{self, check_genesis_storage}; +use sp_blockchain::{ Error as ClientError, Result as ClientResult }; use client_api::{ backend::{ AuxStore, Backend as ClientBackend, BlockImportOperation, RemoteBackend, NewBlockState, @@ -34,9 +35,6 @@ use client_api::{ blockchain::{ HeaderBackend as BlockchainHeaderBackend, well_known_cache_keys, }, - error::{ - Error as ClientError, Result as ClientResult - }, light::Storage as BlockchainStorage, }; use crate::light::blockchain::Blockchain; diff --git a/substrate/client/src/light/blockchain.rs b/substrate/client/src/light/blockchain.rs index b9003c6a29..11982e4529 100644 --- a/substrate/client/src/light/blockchain.rs +++ b/substrate/client/src/light/blockchain.rs @@ -23,7 +23,10 @@ use std::sync::Arc; use sr_primitives::{Justification, generic::BlockId}; use sr_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor, Zero}; -use header_metadata::{HeaderMetadata, CachedHeaderMetadata}; +use sp_blockchain::{ + HeaderMetadata, CachedHeaderMetadata, + Error as ClientError, Result as ClientResult, +}; pub use client_api::{ backend::{ AuxStore, NewBlockState @@ -33,9 +36,6 @@ pub use client_api::{ HeaderBackend as BlockchainHeaderBackend, Info as BlockchainInfo, ProvideCache, well_known_cache_keys, }, - error::{ - Error as ClientError, Result as ClientResult - }, light::{ RemoteBlockchain, LocalOrRemote, Storage } diff --git a/substrate/client/src/light/call_executor.rs b/substrate/client/src/light/call_executor.rs index 29b9ca46af..c998ac0e45 100644 --- a/substrate/client/src/light/call_executor.rs +++ b/substrate/client/src/light/call_executor.rs @@ -38,9 +38,10 @@ use hash_db::Hasher; use sr_api::{ProofRecorder, InitializeBlock}; +use sp_blockchain::{Error as ClientError, Result as ClientResult}; + use client_api::{ backend::RemoteBackend, - error::{Error as ClientError, Result as ClientResult}, light::RemoteCallRequest, call_executor::CallExecutor }; @@ -450,7 +451,7 @@ mod tests { ), ); match execution_result { - Err(client_api::error::Error::Execution(_)) => (), + Err(sp_blockchain::Error::Execution(_)) => (), _ => panic!("Unexpected execution result: {:?}", execution_result), } } diff --git a/substrate/client/src/light/fetcher.rs b/substrate/client/src/light/fetcher.rs index e8b88e93b9..d3f9436262 100644 --- a/substrate/client/src/light/fetcher.rs +++ b/substrate/client/src/light/fetcher.rs @@ -33,12 +33,10 @@ use state_machine::{ read_child_proof_check, }; pub use state_machine::StorageProof; +use sp_blockchain::{Error as ClientError, Result as ClientResult}; use crate::cht; pub use client_api::{ - error::{ - Error as ClientError, Result as ClientResult - }, light::{ RemoteCallRequest, RemoteHeaderRequest, RemoteReadRequest, RemoteReadChildRequest, RemoteChangesRequest, ChangesProof, RemoteBodyRequest, Fetcher, FetchChecker, @@ -329,10 +327,8 @@ pub mod tests { use codec::Decode; use crate::client::tests::prepare_client_with_key_changes; use executor::{NativeExecutor, WasmExecutionMethod}; - use client_api::{ - backend::NewBlockState, - error::Error as ClientError, - }; + use sp_blockchain::Error as ClientError; + use client_api::backend::NewBlockState; use test_client::{ self, ClientExt, blockchain::HeaderBackend, AccountKeyring, runtime::{self, Hash, Block, Header, Extrinsic} diff --git a/substrate/client/src/light/mod.rs b/substrate/client/src/light/mod.rs index 787e48e449..e9dec286f6 100644 --- a/substrate/client/src/light/mod.rs +++ b/substrate/client/src/light/mod.rs @@ -27,11 +27,11 @@ use executor::RuntimeInfo; use primitives::{H256, Blake2Hasher, traits::CodeExecutor}; use sr_primitives::BuildStorage; use sr_primitives::traits::Block as BlockT; +use sp_blockchain::Result as ClientResult; use crate::call_executor::LocalCallExecutor; use crate::client::Client; use client_api::{ - error::Result as ClientResult, light::Storage as BlockchainStorage, }; use crate::light::backend::Backend; diff --git a/substrate/client/transaction-pool/Cargo.toml b/substrate/client/transaction-pool/Cargo.toml index de19d9d19a..241c7beb23 100644 --- a/substrate/client/transaction-pool/Cargo.toml +++ b/substrate/client/transaction-pool/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "substrate-transaction-pool" +name = "sc-transaction-pool" version = "2.0.0" authors = ["Parity Technologies "] edition = "2018" @@ -14,7 +14,7 @@ primitives = { package = "substrate-primitives", path = "../../primitives/core" sr-api = { path = "../../primitives/sr-api" } sr-primitives = { path = "../../primitives/sr-primitives" } tx-runtime-api = { package = "substrate-transaction-pool-runtime-api", path = "../../primitives/transaction-pool/runtime-api" } -txpool = { package = "substrate-transaction-graph", path = "./graph" } +txpool = { package = "sc-transaction-graph", path = "./graph" } [dev-dependencies] keyring = { package = "substrate-keyring", path = "../../primitives/keyring" } diff --git a/substrate/client/transaction-pool/graph/Cargo.toml b/substrate/client/transaction-pool/graph/Cargo.toml index 63b1c54aac..685a2f6ff9 100644 --- a/substrate/client/transaction-pool/graph/Cargo.toml +++ b/substrate/client/transaction-pool/graph/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "substrate-transaction-graph" +name = "sc-transaction-graph" version = "2.0.0" authors = ["Parity Technologies "] edition = "2018" diff --git a/substrate/client/transaction-pool/graph/benches/basics.rs b/substrate/client/transaction-pool/graph/benches/basics.rs index dcd725ce46..1ddd27df96 100644 --- a/substrate/client/transaction-pool/graph/benches/basics.rs +++ b/substrate/client/transaction-pool/graph/benches/basics.rs @@ -17,7 +17,7 @@ use criterion::{criterion_group, criterion_main, Criterion}; use futures::executor::block_on; -use substrate_transaction_graph::*; +use sc_transaction_graph::*; use sr_primitives::transaction_validity::{ValidTransaction, InvalidTransaction}; use codec::Encode; use test_runtime::{Block, Extrinsic, Transfer, H256, AccountId}; diff --git a/substrate/frame/contracts/rpc/Cargo.toml b/substrate/frame/contracts/rpc/Cargo.toml index 06c8776ece..a06353831c 100644 --- a/substrate/frame/contracts/rpc/Cargo.toml +++ b/substrate/frame/contracts/rpc/Cargo.toml @@ -5,11 +5,11 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -client = { package = "substrate-client", path = "../../../client/" } codec = { package = "parity-scale-codec", version = "1.0.0" } jsonrpc-core = "14.0.3" jsonrpc-core-client = "14.0.3" jsonrpc-derive = "14.0.3" +sp-blockchain = { path = "../../../primitives/blockchain" } primitives = { package = "substrate-primitives", path = "../../../primitives/core" } rpc-primitives = { package = "substrate-rpc-primitives", path = "../../../primitives/rpc" } serde = { version = "1.0.101", features = ["derive"] } diff --git a/substrate/frame/contracts/rpc/src/lib.rs b/substrate/frame/contracts/rpc/src/lib.rs index 9cc1aef938..e330e9efcc 100644 --- a/substrate/frame/contracts/rpc/src/lib.rs +++ b/substrate/frame/contracts/rpc/src/lib.rs @@ -18,7 +18,7 @@ use std::sync::Arc; -use client::blockchain::HeaderBackend; +use sp_blockchain::HeaderBackend; use codec::Codec; use jsonrpc_core::{Error, ErrorCode, Result}; use jsonrpc_derive::rpc; diff --git a/substrate/frame/elections-phragmen/Cargo.toml b/substrate/frame/elections-phragmen/Cargo.toml index bf17df628d..fbbc49380e 100644 --- a/substrate/frame/elections-phragmen/Cargo.toml +++ b/substrate/frame/elections-phragmen/Cargo.toml @@ -17,6 +17,7 @@ runtime_io = { package = "sr-io", path = "../../primitives/sr-io" } hex-literal = "0.2.1" balances = { package = "pallet-balances", path = "../balances" } primitives = { package = "substrate-primitives", path = "../../primitives/core" } +substrate-test-utils = { path = "../../test/utils" } serde = { version = "1.0.101" } [features] diff --git a/substrate/frame/elections-phragmen/src/lib.rs b/substrate/frame/elections-phragmen/src/lib.rs index c9d515423e..4ae237e378 100644 --- a/substrate/frame/elections-phragmen/src/lib.rs +++ b/substrate/frame/elections-phragmen/src/lib.rs @@ -743,7 +743,8 @@ impl Module { mod tests { use super::*; use std::cell::RefCell; - use support::{assert_ok, assert_noop, parameter_types, assert_eq_uvec}; + use support::{assert_ok, assert_noop, parameter_types}; + use substrate_test_utils::assert_eq_uvec; use primitives::H256; use sr_primitives::{ Perbill, testing::Header, BuildStorage, diff --git a/substrate/frame/staking/Cargo.toml b/substrate/frame/staking/Cargo.toml index 3ad4b68c83..005b45da76 100644 --- a/substrate/frame/staking/Cargo.toml +++ b/substrate/frame/staking/Cargo.toml @@ -24,6 +24,7 @@ primitives = { package = "substrate-primitives", path = "../../primitives/core" balances = { package = "pallet-balances", path = "../balances" } timestamp = { package = "pallet-timestamp", path = "../timestamp" } pallet-staking-reward-curve = { path = "../staking/reward-curve"} +substrate-test-utils = { path = "../../test/utils" } [features] equalize = [] diff --git a/substrate/frame/staking/src/tests.rs b/substrate/frame/staking/src/tests.rs index aef5a26a04..7c16091d06 100644 --- a/substrate/frame/staking/src/tests.rs +++ b/substrate/frame/staking/src/tests.rs @@ -20,7 +20,8 @@ use super::*; use mock::*; use sr_primitives::{assert_eq_error_rate, traits::OnInitialize}; use sr_staking_primitives::offence::{OffenceDetails, OnOffenceHandler}; -use support::{assert_ok, assert_noop, assert_eq_uvec, traits::{Currency, ReservableCurrency}}; +use support::{assert_ok, assert_noop, traits::{Currency, ReservableCurrency}}; +use substrate_test_utils::assert_eq_uvec; #[test] fn force_unstake_works() { diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs index 916ffbdfa3..ad599fac83 100644 --- a/substrate/frame/support/src/lib.rs +++ b/substrate/frame/support/src/lib.rs @@ -185,47 +185,6 @@ macro_rules! assert_ok { } } -/// Panic when the vectors are different, without taking the order into account. -/// -/// # Examples -/// -/// ```rust -/// #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::{assert_eq_uvec}; -/// # fn main() { -/// assert_eq_uvec!(vec![1,2], vec![2,1]); -/// # } -/// ``` -/// -/// ```rust,should_panic -/// #[macro_use] -/// # extern crate frame_support; -/// # use frame_support::{assert_eq_uvec}; -/// # fn main() { -/// assert_eq_uvec!(vec![1,2,3], vec![2,1]); -/// # } -/// ``` -#[macro_export] -#[cfg(feature = "std")] -macro_rules! assert_eq_uvec { - ( $x:expr, $y:expr ) => { - $crate::__assert_eq_uvec!($x, $y); - $crate::__assert_eq_uvec!($y, $x); - } -} - -#[macro_export] -#[doc(hidden)] -#[cfg(feature = "std")] -macro_rules! __assert_eq_uvec { - ( $x:expr, $y:expr ) => { - $x.iter().for_each(|e| { - if !$y.contains(e) { panic!(format!("vectors not equal: {:?} != {:?}", $x, $y)); } - }); - } -} - /// The void type - it cannot exist. // Oh rust, you crack me up... #[derive(Clone, Eq, PartialEq, RuntimeDebug)] diff --git a/substrate/frame/system/rpc/Cargo.toml b/substrate/frame/system/rpc/Cargo.toml deleted file mode 100644 index c916287e91..0000000000 --- a/substrate/frame/system/rpc/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "frame-system-rpc" -version = "2.0.0" -authors = ["Parity Technologies "] -edition = "2018" - -[dependencies] -client = { package = "substrate-client", path = "../../../client/" } -codec = { package = "parity-scale-codec", version = "1.0.0" } -jsonrpc-core = "14.0.3" -jsonrpc-core-client = "14.0.3" -jsonrpc-derive = "14.0.3" -log = "0.4.8" -serde = { version = "1.0.101", features = ["derive"] } -sr-primitives = { path = "../../../primitives/sr-primitives" } -frame-system-rpc-runtime-api = { path = "./runtime-api" } -substrate-primitives = { path = "../../../primitives/core" } -transaction_pool = { package = "substrate-transaction-pool", path = "../../../client/transaction-pool" } - -[dev-dependencies] -test-client = { package = "substrate-test-runtime-client", path = "../../../test/utils/runtime/client" } -env_logger = "0.7.0" -futures = "0.3.1" diff --git a/substrate/frame/transaction-payment/rpc/Cargo.toml b/substrate/frame/transaction-payment/rpc/Cargo.toml index 92bbda3220..5ae6eafc19 100644 --- a/substrate/frame/transaction-payment/rpc/Cargo.toml +++ b/substrate/frame/transaction-payment/rpc/Cargo.toml @@ -5,7 +5,6 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -client = { package = "substrate-client", path = "../../../client/" } codec = { package = "parity-scale-codec", version = "1.0.0" } jsonrpc-core = "14.0.3" jsonrpc-core-client = "14.0.3" @@ -14,4 +13,5 @@ primitives = { package = "substrate-primitives", path = "../../../primitives/co rpc-primitives = { package = "substrate-rpc-primitives", path = "../../../primitives/rpc" } serde = { version = "1.0.101", features = ["derive"] } sr-primitives = { path = "../../../primitives/sr-primitives" } +sp-blockchain = { path = "../../../primitives/blockchain" } pallet-transaction-payment-rpc-runtime-api = { path = "./runtime-api" } diff --git a/substrate/frame/transaction-payment/rpc/src/lib.rs b/substrate/frame/transaction-payment/rpc/src/lib.rs index 54ec16f032..527bfc424a 100644 --- a/substrate/frame/transaction-payment/rpc/src/lib.rs +++ b/substrate/frame/transaction-payment/rpc/src/lib.rs @@ -18,7 +18,7 @@ use std::sync::Arc; use codec::{Codec, Decode}; -use client::blockchain::HeaderBackend; +use sp_blockchain::HeaderBackend; use jsonrpc_core::{Error as RpcError, ErrorCode, Result}; use jsonrpc_derive::rpc; use sr_primitives::{ diff --git a/substrate/primitives/blockchain/Cargo.toml b/substrate/primitives/blockchain/Cargo.toml new file mode 100644 index 0000000000..812c1dd668 --- /dev/null +++ b/substrate/primitives/blockchain/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "sp-blockchain" +version = "2.0.0" +authors = ["Parity Technologies "] +edition = "2018" + +[dependencies] +log = "0.4.8" +lru = "0.4.0" +parking_lot = "0.9.0" +derive_more = "0.99.2" +parity-scale-codec = { version = "1.0.0", default-features = false, features = ["derive"] } +sp_consensus = { package = "substrate-consensus-common", path = "../consensus/common" } +sr-primitives = { path = "../sr-primitives" } +sp-block-builder-runtime-api = { package = "substrate-block-builder-runtime-api", path = "../block-builder/runtime-api" } +sp-state-machine = { package = "substrate-state-machine", path = "../state-machine" } + diff --git a/substrate/client/api/src/blockchain.rs b/substrate/primitives/blockchain/src/backend.rs similarity index 98% rename from substrate/client/api/src/blockchain.rs rename to substrate/primitives/blockchain/src/backend.rs index b28a1060b9..c28a75f620 100644 --- a/substrate/client/api/src/blockchain.rs +++ b/substrate/primitives/blockchain/src/backend.rs @@ -24,7 +24,7 @@ use sr_primitives::Justification; use log::warn; use parking_lot::RwLock; -use header_metadata::HeaderMetadata; +use crate::header_metadata::HeaderMetadata; use crate::error::{Error, Result}; @@ -262,7 +262,7 @@ pub enum BlockStatus { /// A list of all well known keys in the blockchain cache. pub mod well_known_cache_keys { /// The type representing cache keys. - pub type Id = consensus::import_queue::CacheKeyId; + pub type Id = sp_consensus::import_queue::CacheKeyId; /// A list of authorities. pub const AUTHORITIES: Id = *b"auth"; diff --git a/substrate/client/api/src/error.rs b/substrate/primitives/blockchain/src/error.rs similarity index 77% rename from substrate/client/api/src/error.rs rename to substrate/primitives/blockchain/src/error.rs index 871a1091c6..73b2422498 100644 --- a/substrate/client/api/src/error.rs +++ b/substrate/primitives/blockchain/src/error.rs @@ -17,20 +17,40 @@ //! Substrate client possible errors. use std::{self, error, result}; -use state_machine; +use sp_state_machine; use sr_primitives::transaction_validity::TransactionValidityError; -use consensus; +#[allow(deprecated)] +use sp_block_builder_runtime_api::compatability_v3; +use sp_consensus; use derive_more::{Display, From}; +use parity_scale_codec::Error as CodecError; /// Client Result type alias pub type Result = result::Result; + +/// Error when the runtime failed to apply an extrinsic. +#[derive(Debug, Display)] +pub enum ApplyExtrinsicFailed { + /// The transaction cannot be included into the current block. + /// + /// This doesn't necessary mean that the transaction itself is invalid, but it might be just + /// unappliable onto the current block. + #[display(fmt = "Extrinsic is not valid: {:?}", _0)] + Validity(TransactionValidityError), + /// This is used for miscelanious errors that can be represented by string and not handleable. + /// + /// This will become obsolete with complete migration to v4 APIs. + #[display(fmt = "Extrinsic failed: {:?}", _0)] + Msg(String), +} + /// Substrate Client error #[derive(Debug, Display, From)] pub enum Error { /// Consensus Error #[display(fmt = "Consensus: {}", _0)] - Consensus(consensus::Error), + Consensus(sp_consensus::Error), /// Backend error. #[display(fmt = "Backend error: {}", _0)] #[from(ignore)] @@ -40,11 +60,11 @@ pub enum Error { #[from(ignore)] UnknownBlock(String), /// The `apply_extrinsic` is not valid due to the given `TransactionValidityError`. - #[display(fmt = "Extrinsic is not valid: {:?}", _0)] - ApplyExtrinsicFailed(TransactionValidityError), + #[display(fmt = "{:?}", _0)] + ApplyExtrinsicFailed(ApplyExtrinsicFailed), /// Execution error. #[display(fmt = "Execution: {}", _0)] - Execution(Box), + Execution(Box), /// Blockchain error. #[display(fmt = "Blockchain: {}", _0)] Blockchain(Box), @@ -78,7 +98,7 @@ pub enum Error { RemoteFetchFailed, /// Error decoding call result. #[display(fmt = "Error decoding call result of {}: {}", _0, _1)] - CallResultDecode(&'static str, codec::Error), + CallResultDecode(&'static str, CodecError), /// Error converting a parameter between runtime and node. #[display(fmt = "Error converting `{}` between runtime and node", _0)] #[from(ignore)] @@ -131,14 +151,14 @@ impl<'a> From<&'a str> for Error { } } -impl From for Error { - fn from(err: block_builder::ApplyExtrinsicFailed) -> Self { - use block_builder::ApplyExtrinsicFailed; - match err { - ApplyExtrinsicFailed::Validity(tx_validity) => Self::ApplyExtrinsicFailed(tx_validity), - ApplyExtrinsicFailed::Msg(msg) => Self::Msg(msg), +#[allow(deprecated)] +impl From for ApplyExtrinsicFailed { + fn from(e: compatability_v3::ApplyError) -> Self { + use self::compatability_v3::ApplyError::*; + match e { + Validity(tx_validity) => Self::Validity(tx_validity), + e => Self::Msg(format!("Apply extrinsic failed: {:?}", e)), } - } } @@ -149,7 +169,7 @@ impl Error { } /// Chain a state error. - pub fn from_state(e: Box) -> Self { + pub fn from_state(e: Box) -> Self { Error::Execution(e) } } diff --git a/substrate/client/header-metadata/src/lib.rs b/substrate/primitives/blockchain/src/header_metadata.rs similarity index 100% rename from substrate/client/header-metadata/src/lib.rs rename to substrate/primitives/blockchain/src/header_metadata.rs diff --git a/substrate/primitives/blockchain/src/lib.rs b/substrate/primitives/blockchain/src/lib.rs new file mode 100644 index 0000000000..2a8a7c96fe --- /dev/null +++ b/substrate/primitives/blockchain/src/lib.rs @@ -0,0 +1,25 @@ +// Copyright 2019 Parity Technologies (UK) Ltd. +// This file is part of Substrate. + +// Substrate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Substrate is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Substrate. If not, see . + +//! Substrate blockchain traits and primtives + +mod backend; +mod header_metadata; +mod error; + +pub use error::*; +pub use backend::*; +pub use header_metadata::*; diff --git a/substrate/primitives/phragmen/Cargo.toml b/substrate/primitives/phragmen/Cargo.toml index c1465628e5..18dc3c29fb 100644 --- a/substrate/primitives/phragmen/Cargo.toml +++ b/substrate/primitives/phragmen/Cargo.toml @@ -10,8 +10,8 @@ rstd = { package = "sr-std", path = "../sr-std", default-features = false } sr-primitives = { path = "../../primitives/sr-primitives", default-features = false } [dev-dependencies] +substrate-test-utils = { path = "../../test/utils" } runtime-io ={ package = "sr-io", path = "../../primitives/sr-io" } -support = { package = "frame-support", path = "../../frame/support" } rand = "0.7.2" [features] diff --git a/substrate/primitives/phragmen/src/lib.rs b/substrate/primitives/phragmen/src/lib.rs index 67ea6077ad..d027bcfa8d 100644 --- a/substrate/primitives/phragmen/src/lib.rs +++ b/substrate/primitives/phragmen/src/lib.rs @@ -38,7 +38,9 @@ use sr_primitives::RuntimeDebug; use sr_primitives::{helpers_128bit::multiply_by_rational, Perbill, Rational128}; use sr_primitives::traits::{Zero, Convert, Member, SimpleArithmetic, Saturating, Bounded}; +#[cfg(test)] mod mock; +#[cfg(test)] mod tests; /// A type in which performing operations on balances and stakes of candidates and voters are safe. diff --git a/substrate/primitives/phragmen/src/tests.rs b/substrate/primitives/phragmen/src/tests.rs index aaeac27c14..8aaa45dce0 100644 --- a/substrate/primitives/phragmen/src/tests.rs +++ b/substrate/primitives/phragmen/src/tests.rs @@ -20,7 +20,7 @@ use crate::mock::*; use crate::{elect, PhragmenResult}; -use support::assert_eq_uvec; +use substrate_test_utils::assert_eq_uvec; use sr_primitives::Perbill; #[test] diff --git a/substrate/primitives/sr-api/test/Cargo.toml b/substrate/primitives/sr-api/test/Cargo.toml index 7915266cca..5cdbdc861e 100644 --- a/substrate/primitives/sr-api/test/Cargo.toml +++ b/substrate/primitives/sr-api/test/Cargo.toml @@ -9,6 +9,7 @@ sr-api = { path = "../" } test-client = { package = "substrate-test-runtime-client", path = "../../../test/utils/runtime/client" } sr-version = { path = "../../sr-version" } sr-primitives = { path = "../../sr-primitives" } +sp-blockchain = { path = "../../blockchain" } consensus_common = { package = "substrate-consensus-common", path = "../../../primitives/consensus/common" } codec = { package = "parity-scale-codec", version = "1.0.0" } state-machine = { package = "substrate-state-machine", path = "../../../primitives/state-machine" } diff --git a/substrate/primitives/sr-api/test/tests/decl_and_impl.rs b/substrate/primitives/sr-api/test/tests/decl_and_impl.rs index 91863e1865..6bc5ea908c 100644 --- a/substrate/primitives/sr-api/test/tests/decl_and_impl.rs +++ b/substrate/primitives/sr-api/test/tests/decl_and_impl.rs @@ -18,7 +18,8 @@ use sr_api::{RuntimeApiInfo, decl_runtime_apis, impl_runtime_apis}; use sr_primitives::{traits::{GetNodeBlockType, Block as BlockT}, generic::BlockId}; -use test_client::{client::error::Result, runtime::Block}; +use test_client::runtime::Block; +use sp_blockchain::Result; /// The declaration of the `Runtime` type and the implementation of the `GetNodeBlockType` /// trait are done by the `construct_runtime!` macro in a real runtime. diff --git a/substrate/test/utils/Cargo.toml b/substrate/test/utils/Cargo.toml new file mode 100644 index 0000000000..ac4c995419 --- /dev/null +++ b/substrate/test/utils/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "substrate-test-utils" +version = "2.0.0" +authors = ["Parity Technologies "] +edition = "2018" diff --git a/substrate/test/utils/client/Cargo.toml b/substrate/test/utils/client/Cargo.toml index d0ba0eca7c..e153604603 100644 --- a/substrate/test/utils/client/Cargo.toml +++ b/substrate/test/utils/client/Cargo.toml @@ -16,4 +16,5 @@ keyring = { package = "substrate-keyring", path = "../../../primitives/keyring" codec = { package = "parity-scale-codec", version = "1.0.0" } primitives = { package = "substrate-primitives", path = "../../../primitives/core" } sr-primitives = { path = "../../../primitives/sr-primitives" } +sp-blockchain = { path = "../../../primitives/blockchain" } state_machine = { package = "substrate-state-machine", path = "../../../primitives/state-machine" } diff --git a/substrate/test/utils/client/src/client_ext.rs b/substrate/test/utils/client/src/client_ext.rs index d7ae5097a3..78ed619a0d 100644 --- a/substrate/test/utils/client/src/client_ext.rs +++ b/substrate/test/utils/client/src/client_ext.rs @@ -56,7 +56,7 @@ pub trait ClientExt: Sized { &self, id: BlockId, justification: Option, - ) -> client::error::Result<()>; + ) -> sp_blockchain::Result<()>; /// Returns hash of the genesis block. fn genesis_hash(&self) -> ::Hash; @@ -152,7 +152,7 @@ impl ClientExt for Client &self, id: BlockId, justification: Option, - ) -> client::error::Result<()> { + ) -> sp_blockchain::Result<()> { Finalizer::finalize_block(self, id, justification, true) } diff --git a/substrate/test/utils/primitives/Cargo.toml b/substrate/test/utils/primitives/Cargo.toml index d82226d347..92917fdd26 100644 --- a/substrate/test/utils/primitives/Cargo.toml +++ b/substrate/test/utils/primitives/Cargo.toml @@ -7,31 +7,9 @@ edition = "2018" [dependencies] app-crypto = { package = "substrate-application-crypto", path = "../../../primitives/application-crypto", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -# aura-primitives = { package = "substrate-consensus-aura-primitives", path = "../../../primitives/consensus/aura", default-features = false } -# babe-primitives = { package = "substrate-consensus-babe-primitives", path = "../../../primitives/consensus/babe", default-features = false } -# block-builder-api = { package = "substrate-block-builder-runtime-api", path = "../../../primitives/block-builder/runtime-api", default-features = false } -# inherents = { package = "substrate-inherents", path = "../../../primitives/inherents", default-features = false } -# log = { version = "0.4.8", optional = true } -# memory-db = { version = "0.15.2", default-features = false } -# offchain-primitives = { package = "substrate-offchain-primitives", path = "../../../primitives/offchain", default-features = false} primitives = { package = "substrate-primitives", path = "../../../primitives/core", default-features = false } -# rstd = { package = "sr-std", path = "../../../primitives/sr-std", default-features = false } -# runtime-interface = { package = "substrate-runtime-interface", path = "../../../primitives/runtime-interface", default-features = false} -# runtime_io = { package = "sr-io", path = "../../../primitives/sr-io", default-features = false } -# runtime_support = { package = "frame-support", path = "../../../frame/support", default-features = false } -# runtime_version = { package = "sr-version", path = "../../../primitives/sr-version", default-features = false } serde = { version = "1.0.101", optional = true, features = ["derive"] } -# session = { package = "substrate-session", path = "../../../primitives/session", default-features = false } -# sr-api = { path = "../../../primitives/sr-api", default-features = false } sr-primitives = { path = "../../../primitives/sr-primitives", default-features = false } -# pallet-babe = { path = "../../../frame/babe", default-features = false } -# frame-system = { path = "../../../frame/system", default-features = false } -# frame-system-rpc-runtime-api = { path = "../../../frame/system/rpc/runtime-api", default-features = false } -# pallet-timestamp = { path = "../../../frame/timestamp", default-features = false } -# substrate-client = { path = "../../../client", optional = true } -# substrate-trie = { path = "../../../primitives/trie", default-features = false } -# transaction-pool-api = { package = "substrate-transaction-pool-runtime-api", path = "../../../primitives/transaction-pool/runtime-api", default-features = false } -# trie-db = { version = "0.15.2", default-features = false } [features] default = [ @@ -39,33 +17,5 @@ default = [ ] std = [ "app-crypto/std", - # "aura-primitives/std", - # "babe-primitives/std", - # "block-builder-api/std", - # "codec/std", - # "executive/std", - # "inherents/std", - # "keyring", - # "log", - # "memory-db/std", - # "offchain-primitives/std", - # "primitives/std", - # "primitives/std", - # "rstd/std", - # "runtime-interface/std", - # "runtime_io/std", - # "runtime_support/std", - # "runtime_version/std", "serde", - # "session/std", - # "sr-api/std", - # "sr-primitives/std", - # "pallet-babe/std", - # "frame-system-rpc-runtime-api/std", - # "frame-system/std", - # "pallet-timestamp/std", - # "substrate-client", - # "substrate-trie/std", - # "transaction-pool-api/std", - # "trie-db/std", ] diff --git a/substrate/test/utils/runtime/client/Cargo.toml b/substrate/test/utils/runtime/client/Cargo.toml index 68f5820062..83e5edb246 100644 --- a/substrate/test/utils/runtime/client/Cargo.toml +++ b/substrate/test/utils/runtime/client/Cargo.toml @@ -10,6 +10,7 @@ generic-test-client = { package = "substrate-test-client", path = "../../client" primitives = { package = "substrate-primitives", path = "../../../../primitives/core" } runtime = { package = "substrate-test-runtime", path = "../../runtime" } sr-primitives = { path = "../../../../primitives/sr-primitives" } +sp-blockchain = { path = "../../../../primitives/blockchain" } codec = { package = "parity-scale-codec", version = "1.0.0" } client-api = { package = "substrate-client-api", path = "../../../../client/api" } client = { package = "substrate-client", path = "../../../../client/" } diff --git a/substrate/test/utils/runtime/client/src/block_builder_ext.rs b/substrate/test/utils/runtime/client/src/block_builder_ext.rs index 6bd3ed18eb..e6e8ac3249 100644 --- a/substrate/test/utils/runtime/client/src/block_builder_ext.rs +++ b/substrate/test/utils/runtime/client/src/block_builder_ext.rs @@ -18,27 +18,26 @@ use runtime; use sr_primitives::traits::ProvideRuntimeApi; -use generic_test_client::client; use block_builder::BlockBuilderApi; /// Extension trait for test block builder. pub trait BlockBuilderExt { /// Add transfer extrinsic to the block. - fn push_transfer(&mut self, transfer: runtime::Transfer) -> Result<(), client::error::Error>; + fn push_transfer(&mut self, transfer: runtime::Transfer) -> Result<(), sp_blockchain::Error>; /// Add storage change extrinsic to the block. fn push_storage_change( &mut self, key: Vec, value: Option>, - ) -> Result<(), client::error::Error>; + ) -> Result<(), sp_blockchain::Error>; } impl<'a, A> BlockBuilderExt for block_builder::BlockBuilder<'a, runtime::Block, A> where A: ProvideRuntimeApi + 'a, - A::Api: BlockBuilderApi, + A::Api: BlockBuilderApi, { - fn push_transfer(&mut self, transfer: runtime::Transfer) -> Result<(), client::error::Error> { + fn push_transfer(&mut self, transfer: runtime::Transfer) -> Result<(), sp_blockchain::Error> { self.push(transfer.into_signed_tx()) } @@ -46,7 +45,7 @@ impl<'a, A> BlockBuilderExt for block_builder::BlockBuilder<'a, runtime::Block, &mut self, key: Vec, value: Option>, - ) -> Result<(), client::error::Error> { + ) -> Result<(), sp_blockchain::Error> { self.push(runtime::Extrinsic::StorageChange(key, value)) } } diff --git a/substrate/test/utils/src/lib.rs b/substrate/test/utils/src/lib.rs new file mode 100644 index 0000000000..f79a5da5c6 --- /dev/null +++ b/substrate/test/utils/src/lib.rs @@ -0,0 +1,54 @@ +// Copyright 2017-2019 Parity Technologies (UK) Ltd. +// This file is part of Substrate. + +// Substrate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Substrate is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Substrate. If not, see . + +//! Test utils + +/// Panic when the vectors are different, without taking the order into account. +/// +/// # Examples +/// +/// ```rust +/// #[macro_use] +/// # use substrate_test_utils::{assert_eq_uvec}; +/// # fn main() { +/// assert_eq_uvec!(vec![1,2], vec![2,1]); +/// # } +/// ``` +/// +/// ```rust,should_panic +/// #[macro_use] +/// # use substrate_test_utils::{assert_eq_uvec}; +/// # fn main() { +/// assert_eq_uvec!(vec![1,2,3], vec![2,1]); +/// # } +/// ``` +#[macro_export] +macro_rules! assert_eq_uvec { + ( $x:expr, $y:expr ) => { + $crate::__assert_eq_uvec!($x, $y); + $crate::__assert_eq_uvec!($y, $x); + } +} + +#[macro_export] +#[doc(hidden)] +macro_rules! __assert_eq_uvec { + ( $x:expr, $y:expr ) => { + $x.iter().for_each(|e| { + if !$y.contains(e) { panic!(format!("vectors not equal: {:?} != {:?}", $x, $y)); } + }); + } +} diff --git a/substrate/test/utils/transaction-factory/Cargo.toml b/substrate/test/utils/transaction-factory/Cargo.toml index fdd948a6f2..5c15a887c6 100644 --- a/substrate/test/utils/transaction-factory/Cargo.toml +++ b/substrate/test/utils/transaction-factory/Cargo.toml @@ -16,4 +16,5 @@ primitives = { package = "substrate-primitives", path = "../../../primitives/cor sr-api = { path = "../../../primitives/sr-api" } sr-primitives = { path = "../../../primitives/sr-primitives" } substrate-service = { path = "../../../client/service" } +sp-blockchain = { path = "../../../primitives/blockchain" } diff --git a/substrate/test/utils/transaction-factory/src/complex_mode.rs b/substrate/test/utils/transaction-factory/src/complex_mode.rs index 086698ffc3..bbc01c19ba 100644 --- a/substrate/test/utils/transaction-factory/src/complex_mode.rs +++ b/substrate/test/utils/transaction-factory/src/complex_mode.rs @@ -64,7 +64,7 @@ where Backend: client_api::backend::Backend + Send, Client: ProvideRuntimeApi, as ProvideRuntimeApi>::Api: - BlockBuilder, + BlockBuilder, RtApi: ConstructRuntimeApi> + Send + Sync, RA: RuntimeAdapter, { diff --git a/substrate/test/utils/transaction-factory/src/lib.rs b/substrate/test/utils/transaction-factory/src/lib.rs index 357e8067f3..f6f895fd22 100644 --- a/substrate/test/utils/transaction-factory/src/lib.rs +++ b/substrate/test/utils/transaction-factory/src/lib.rs @@ -105,7 +105,7 @@ where Backend: client_api::backend::Backend + Send, Client: ProvideRuntimeApi, as ProvideRuntimeApi>::Api: - BlockBuilder, + BlockBuilder, RtApi: ConstructRuntimeApi> + Send + Sync, Sc: SelectChain, RA: RuntimeAdapter, @@ -165,7 +165,7 @@ where Client: ProvideRuntimeApi, RtApi: ConstructRuntimeApi> + Send + Sync, as ProvideRuntimeApi>::Api: - BlockBuilder, + BlockBuilder, RA: RuntimeAdapter, { let mut block = client.new_block(Default::default()).expect("Failed to create new block"); diff --git a/substrate/test/utils/transaction-factory/src/simple_modes.rs b/substrate/test/utils/transaction-factory/src/simple_modes.rs index f869201b46..973de45c7e 100644 --- a/substrate/test/utils/transaction-factory/src/simple_modes.rs +++ b/substrate/test/utils/transaction-factory/src/simple_modes.rs @@ -59,7 +59,7 @@ where Backend: client_api::backend::Backend + Send, Client: ProvideRuntimeApi, as ProvideRuntimeApi>::Api: - BlockBuilder, + BlockBuilder, RtApi: ConstructRuntimeApi> + Send + Sync, RA: RuntimeAdapter, { diff --git a/substrate/frame/support/rpc/Cargo.toml b/substrate/utils/frame/rpc/support/Cargo.toml similarity index 54% rename from substrate/frame/support/rpc/Cargo.toml rename to substrate/utils/frame/rpc/support/Cargo.toml index 15e9fee7f0..937acb8295 100644 --- a/substrate/frame/support/rpc/Cargo.toml +++ b/substrate/utils/frame/rpc/support/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "frame-support-rpc" +name = "substrate-frame-rpc-support" version = "2.0.0" authors = ["Parity Technologies ", "Andrew Dirksen "] edition = "2018" @@ -10,10 +10,10 @@ jsonrpc-client-transports = "14" jsonrpc-core = "14" parity-scale-codec = "1" serde = "1" -frame-support = { path = "../" } -substrate-primitives-storage = { path = "../../../primitives/core/storage" } -substrate-rpc-api = { path = "../../../client/rpc/api" } +frame-support = { path = "../../../../frame/support" } +substrate-primitives-storage = { path = "../../../../primitives/core/storage" } +sc-rpc-api = { path = "../../../../client/rpc/api" } [dev-dependencies] -frame-system = { path = "../../system" } +frame-system = { path = "../../../../frame/system" } tokio = "0.1" diff --git a/substrate/frame/support/rpc/src/lib.rs b/substrate/utils/frame/rpc/support/src/lib.rs similarity index 95% rename from substrate/frame/support/rpc/src/lib.rs rename to substrate/utils/frame/rpc/support/src/lib.rs index e248e0c9fe..ef594b687e 100644 --- a/substrate/frame/support/rpc/src/lib.rs +++ b/substrate/utils/frame/rpc/support/src/lib.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Substrate. If not, see . -//! Combines [substrate_rpc_api::state::StateClient] with [frame_support::storage::generator] traits +//! Combines [sc_rpc_api::state::StateClient] with [frame_support::storage::generator] traits //! to provide strongly typed chain state queries over rpc. #![warn(missing_docs)] @@ -28,7 +28,7 @@ use frame_support::storage::generator::{ StorageDoubleMap, StorageLinkedMap, StorageMap, StorageValue }; use substrate_primitives_storage::{StorageData, StorageKey}; -use substrate_rpc_api::state::StateClient; +use sc_rpc_api::state::StateClient; /// A typed query on chain state usable from an RPC client. /// @@ -40,9 +40,9 @@ use substrate_rpc_api::state::StateClient; /// # use jsonrpc_client_transports::transports::http; /// # use parity_scale_codec::Encode; /// # use frame_support::{decl_storage, decl_module}; -/// # use frame_support_rpc::StorageQuery; +/// # use substrate_frame_rpc_support::StorageQuery; /// # use frame_system::Trait; -/// # use substrate_rpc_api::state::StateClient; +/// # use sc_rpc_api::state::StateClient; /// # /// # // Hash would normally be ::Hash, but we don't have /// # // frame_system::Trait implemented for TestRuntime. Here we just pretend. diff --git a/substrate/utils/frame/rpc/system/Cargo.toml b/substrate/utils/frame/rpc/system/Cargo.toml new file mode 100644 index 0000000000..a4b6d21693 --- /dev/null +++ b/substrate/utils/frame/rpc/system/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "substrate-frame-rpc-system" +version = "2.0.0" +authors = ["Parity Technologies "] +edition = "2018" + +[dependencies] +codec = { package = "parity-scale-codec", version = "1.0.0" } +jsonrpc-core = "14.0.3" +jsonrpc-core-client = "14.0.3" +jsonrpc-derive = "14.0.3" +log = "0.4.8" +serde = { version = "1.0.101", features = ["derive"] } +sr-primitives = { path = "../../../../primitives/sr-primitives" } +frame-system-rpc-runtime-api = { path = "../../../../frame/system/rpc/runtime-api" } +substrate-primitives = { path = "../../../../primitives/core" } +sp-blockchain = { path = "../../../../primitives/blockchain" } +sc-transaction-graph = { path = "../../../../client/transaction-pool/graph" } + +[dev-dependencies] +test-client = { package = "substrate-test-runtime-client", path = "../../../../test/utils/runtime/client" } +sc-transaction-pool = { path = "../../../../client/transaction-pool" } +env_logger = "0.7.0" +futures = "0.3.1" diff --git a/substrate/frame/system/rpc/src/lib.rs b/substrate/utils/frame/rpc/system/src/lib.rs similarity index 93% rename from substrate/frame/system/rpc/src/lib.rs rename to substrate/utils/frame/rpc/system/src/lib.rs index 10c416c798..63b91c3cd2 100644 --- a/substrate/frame/system/rpc/src/lib.rs +++ b/substrate/utils/frame/rpc/system/src/lib.rs @@ -19,7 +19,7 @@ use std::sync::Arc; use codec::{self, Codec, Encode}; -use client::blockchain::HeaderBackend; +use sp_blockchain::HeaderBackend; use jsonrpc_core::{Result, Error, ErrorCode}; use jsonrpc_derive::rpc; use sr_primitives::{ @@ -27,7 +27,7 @@ use sr_primitives::{ traits, }; use substrate_primitives::hexdisplay::HexDisplay; -use transaction_pool::txpool::{self, Pool}; +use sc_transaction_graph::{self, ChainApi, Pool}; pub use frame_system_rpc_runtime_api::AccountNonceApi; pub use self::gen_client::Client as SystemClient; @@ -47,13 +47,13 @@ pub trait SystemApi { const RUNTIME_ERROR: i64 = 1; /// An implementation of System-specific RPC methods. -pub struct System { +pub struct System { client: Arc, pool: Arc>, _marker: std::marker::PhantomData, } -impl System { +impl System { /// Create new `System` given client and transaction pool. pub fn new(client: Arc, pool: Arc>) -> Self { System { @@ -70,7 +70,7 @@ where C: HeaderBackend, C: Send + Sync + 'static, C::Api: AccountNonceApi, - P: txpool::ChainApi + Sync + Send + 'static, + P: ChainApi + Sync + Send + 'static, Block: traits::Block, AccountId: Clone + std::fmt::Display + Codec, Index: Clone + std::fmt::Display + Codec + traits::SimpleArithmetic, @@ -118,6 +118,7 @@ where #[cfg(test)] mod tests { use super::*; + use sc_transaction_pool; use futures::executor::block_on; use test_client::{ @@ -130,7 +131,7 @@ mod tests { // given let _ = env_logger::try_init(); let client = Arc::new(test_client::new()); - let pool = Arc::new(Pool::new(Default::default(), transaction_pool::FullChainApi::new(client.clone()))); + let pool = Arc::new(Pool::new(Default::default(), sc_transaction_pool::FullChainApi::new(client.clone()))); let new_transaction = |nonce: u64| { let t = Transfer {