diff --git a/substrate/Cargo.lock b/substrate/Cargo.lock index febe287964..6dc6440056 100644 --- a/substrate/Cargo.lock +++ b/substrate/Cargo.lock @@ -843,7 +843,7 @@ dependencies = [ "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1933,6 +1933,7 @@ dependencies = [ "substrate-client 0.1.0", "substrate-consensus-aura 0.1.0", "substrate-finality-grandpa 0.1.0", + "substrate-inherents 0.1.0", "substrate-keystore 0.1.0", "substrate-network 0.1.0", "substrate-primitives 0.1.0", @@ -1977,7 +1978,7 @@ name = "node-primitives" version = "0.1.0" dependencies = [ "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "pretty_assertions 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1995,7 +1996,7 @@ dependencies = [ "integer-sqrt 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "node-primitives 0.1.0", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2165,12 +2166,12 @@ dependencies = [ [[package]] name = "parity-codec-derive" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)", "quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.15.24 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2637,7 +2638,7 @@ dependencies = [ "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2967,7 +2968,7 @@ dependencies = [ "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.34 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3002,7 +3003,7 @@ version = "0.1.0" dependencies = [ "impl-serde 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-primitives 0.1.0", @@ -3015,7 +3016,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", @@ -3032,7 +3033,7 @@ dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -3043,6 +3044,7 @@ dependencies = [ "srml-support 0.1.0", "srml-system 0.1.0", "srml-timestamp 0.1.0", + "substrate-inherents 0.1.0", "substrate-primitives 0.1.0", ] @@ -3052,7 +3054,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -3070,13 +3072,14 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", "sr-std 0.1.0", "srml-support 0.1.0", "srml-system 0.1.0", + "substrate-inherents 0.1.0", "substrate-primitives 0.1.0", ] @@ -3087,7 +3090,7 @@ dependencies = [ "assert_matches 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parity-wasm 0.31.3 (registry+https://github.com/rust-lang/crates.io-index)", "pwasm-utils 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3108,7 +3111,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -3127,7 +3130,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -3145,7 +3148,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", @@ -3162,7 +3165,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", @@ -3180,7 +3183,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -3199,7 +3202,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "ref_thread_local 0.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3217,7 +3220,7 @@ name = "srml-metadata" version = "0.1.0" dependencies = [ "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-std 0.1.0", @@ -3230,7 +3233,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -3249,7 +3252,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -3271,7 +3274,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", @@ -3290,7 +3293,7 @@ dependencies = [ "mashup 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", "once_cell 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "pretty_assertions 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3299,6 +3302,7 @@ dependencies = [ "sr-std 0.1.0", "srml-metadata 0.1.0", "srml-support-procedural 0.1.0", + "substrate-inherents 0.1.0", ] [[package]] @@ -3337,7 +3341,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -3353,6 +3357,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", @@ -3360,6 +3365,7 @@ dependencies = [ "srml-consensus 0.1.0", "srml-support 0.1.0", "srml-system 0.1.0", + "substrate-inherents 0.1.0", "substrate-primitives 0.1.0", ] @@ -3369,7 +3375,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", @@ -3386,7 +3392,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", @@ -3520,6 +3526,7 @@ dependencies = [ "substrate-client 0.1.0", "substrate-consensus-aura-primitives 0.1.0", "substrate-consensus-common 0.1.0", + "substrate-inherents 0.1.0", "substrate-primitives 0.1.0", "substrate-transaction-pool 0.1.0", ] @@ -3577,6 +3584,7 @@ dependencies = [ "sr-version 0.1.0", "substrate-consensus-common 0.1.0", "substrate-executor 0.1.0", + "substrate-inherents 0.1.0", "substrate-keyring 0.1.0", "substrate-primitives 0.1.0", "substrate-state-machine 0.1.0", @@ -3596,7 +3604,7 @@ dependencies = [ "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "lru-cache 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "sr-primitives 0.1.0", "substrate-client 0.1.0", @@ -3622,12 +3630,14 @@ dependencies = [ "sr-io 0.1.0", "sr-primitives 0.1.0", "sr-version 0.1.0", + "srml-aura 0.1.0", "srml-consensus 0.1.0", "srml-support 0.1.0", "substrate-client 0.1.0", "substrate-consensus-aura-primitives 0.1.0", "substrate-consensus-common 0.1.0", "substrate-executor 0.1.0", + "substrate-inherents 0.1.0", "substrate-keyring 0.1.0", "substrate-network 0.1.0", "substrate-primitives 0.1.0", @@ -3657,10 +3667,11 @@ dependencies = [ "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "sr-primitives 0.1.0", "sr-version 0.1.0", + "substrate-inherents 0.1.0", "substrate-primitives 0.1.0", "substrate-test-client 0.1.0", "tokio 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3675,7 +3686,7 @@ dependencies = [ "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "rhododendron 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -3727,7 +3738,7 @@ dependencies = [ "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", "sr-primitives 0.1.0", @@ -3747,13 +3758,24 @@ name = "substrate-finality-grandpa-primitives" version = "0.1.0" dependencies = [ "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "sr-primitives 0.1.0", "sr-std 0.1.0", "substrate-client 0.1.0", "substrate-primitives 0.1.0", ] +[[package]] +name = "substrate-inherents" +version = "0.1.0" +dependencies = [ + "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "sr-primitives 0.1.0", + "sr-std 0.1.0", +] + [[package]] name = "substrate-keyring" version = "0.1.0" @@ -3790,7 +3812,7 @@ dependencies = [ "linked-hash-map 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3840,7 +3862,7 @@ dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "impl-serde 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "pretty_assertions 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", "primitive-types 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", "ring 0.13.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3961,7 +3983,7 @@ dependencies = [ "env_logger 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "substrate-primitives 0.1.0", ] @@ -4018,7 +4040,7 @@ dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -4029,6 +4051,7 @@ dependencies = [ "substrate-client 0.1.0", "substrate-consensus-aura-primitives 0.1.0", "substrate-executor 0.1.0", + "substrate-inherents 0.1.0", "substrate-keyring 0.1.0", "substrate-primitives 0.1.0", ] @@ -4112,16 +4135,6 @@ dependencies = [ "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "syn" -version = "0.14.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "syn" version = "0.15.24" @@ -5105,7 +5118,7 @@ dependencies = [ "checksum owning_ref 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "49a4b8ea2179e6a2e27411d3bca09ca6dd630821cf6894c6c7c8467a8ee7ef13" "checksum parity-bytes 0.1.0 (git+https://github.com/paritytech/parity-common?rev=b0317f649ab2c665b7987b8475878fc4d2e1f81d)" = "" "checksum parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e7b6a1290fe78aa6bbb5f3338ecede3062687a98b9e40cd1dbcaa47261d44097" -"checksum parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ffa42c2cb493b60b12c75b26e8c94cb734af4df4d7f2cc229dc04c1953dac189" +"checksum parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2632f530f37c8b939c7c194636a82ecbe41ab115e74e88f947ad41e483bbf19" "checksum parity-crypto 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8adf489acb31f1922db0ce43803b6f48a425241a8473611be3cc625a8e4a4c47" "checksum parity-multiaddr 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9a8e5d637787fe097ec1bfca2aa3eb687396518003df991c6c7216d86682d5ff" "checksum parity-multihash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3e8eab0287ccde7821e337a124dc5a4f1d6e4c25d10cc91e3f9361615dd95076" @@ -5210,7 +5223,6 @@ dependencies = [ "checksum subtle 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "702662512f3ddeb74a64ce2fbbf3707ee1b6bb663d28bb054e0779bbc720d926" "checksum syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)" = "d3b891b9015c88c576343b9b3e41c2c11a51c219ef067b264bd9c8aa9b441dad" "checksum syn 0.13.11 (registry+https://github.com/rust-lang/crates.io-index)" = "14f9bf6292f3a61d2c716723fdb789a41bbe104168e6f496dc6497e531ea1b9b" -"checksum syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)" = "261ae9ecaa397c42b960649561949d69311f08eeaea86a65696e6e46517cf741" "checksum syn 0.15.24 (registry+https://github.com/rust-lang/crates.io-index)" = "734ecc29cd36e8123850d9bf21dfd62ef8300aaa8f879aabaa899721808be37c" "checksum synom 0.11.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a393066ed9010ebaed60b9eafa373d4b1baac186dd7e008555b0f702b51945b6" "checksum synstructure 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "73687139bf99285483c96ac0add482c3776528beac1d97d444f6e91f203a2015" diff --git a/substrate/Cargo.toml b/substrate/Cargo.toml index d67f32ed3c..5d38f53648 100644 --- a/substrate/Cargo.toml +++ b/substrate/Cargo.toml @@ -49,6 +49,7 @@ members = [ "core/keystore", "core/transaction-pool", "core/transaction-pool/graph", + "core/inherents", "srml/support", "srml/support/procedural", "srml/support/procedural/tools", diff --git a/substrate/core/basic-authorship/Cargo.toml b/substrate/core/basic-authorship/Cargo.toml index 6a5ef1087d..0c09c84e78 100644 --- a/substrate/core/basic-authorship/Cargo.toml +++ b/substrate/core/basic-authorship/Cargo.toml @@ -6,9 +6,10 @@ authors = ["Parity Technologies "] [dependencies] log = "0.4" parity-codec = "2.2" -sr-primitives = { path = "../../core/sr-primitives" } -substrate-client = { path = "../../core/client" } -substrate-consensus-aura-primitives = { path = "../../core/consensus/aura/primitives" } -substrate-consensus-common = { path = "../../core/consensus/common" } -substrate-primitives = { path = "../../core/primitives" } -substrate-transaction-pool = { path = "../../core/transaction-pool" } +sr-primitives = { path = "../sr-primitives" } +substrate-client = { path = "../client" } +substrate-consensus-aura-primitives = { path = "../consensus/aura/primitives" } +substrate-consensus-common = { path = "../consensus/common" } +substrate-primitives = { path = "../primitives" } +substrate-inherents = { path = "../inherents" } +substrate-transaction-pool = { path = "../transaction-pool" } diff --git a/substrate/core/basic-authorship/src/basic_authorship.rs b/substrate/core/basic-authorship/src/basic_authorship.rs index d3b6421e6a..a666d48ba4 100644 --- a/substrate/core/basic-authorship/src/basic_authorship.rs +++ b/substrate/core/basic-authorship/src/basic_authorship.rs @@ -18,9 +18,7 @@ // FIXME: move this into substrate-consensus-common - https://github.com/paritytech/substrate/issues/1021 -use std::sync::Arc; -use std::time; -use std; +use std::{sync::Arc, self}; use client::{ self, error, Client as SubstrateClient, CallExecutor, @@ -29,13 +27,12 @@ use client::{ use codec::{Decode, Encode}; use consensus_common::{self, evaluation}; use primitives::{H256, Blake2Hasher}; -use runtime_primitives::traits::{Block as BlockT, Hash as HashT, Header as HeaderT, ProvideRuntimeApi, AuthorityIdFor}; +use runtime_primitives::traits::{ + Block as BlockT, Hash as HashT, Header as HeaderT, ProvideRuntimeApi, AuthorityIdFor +}; use runtime_primitives::generic::BlockId; -use runtime_primitives::BasicInherentData; use transaction_pool::txpool::{self, Pool as TransactionPool}; -use aura_primitives::AuraConsensusData; - -type Timestamp = u64; +use inherents::InherentData; // block size limit. const MAX_TRANSACTIONS_SIZE: usize = 4 * 1024 * 1024; @@ -59,20 +56,20 @@ pub trait AuthoringApi: Send + Sync + ProvideRuntimeApi where fn build_block) -> ()>( &self, at: &BlockId, - inherent_data: BasicInherentData, + inherent_data: InherentData, build_ctx: F, ) -> Result; } impl<'a, B, E, Block, RA> BlockBuilder - for client::block_builder::BlockBuilder<'a, Block, BasicInherentData, SubstrateClient> + for client::block_builder::BlockBuilder<'a, Block, SubstrateClient> where B: client::backend::Backend + 'static, E: CallExecutor + Send + Sync + Clone + 'static, Block: BlockT, RA: Send + Sync + 'static, SubstrateClient : ProvideRuntimeApi, - as ProvideRuntimeApi>::Api: BlockBuilderApi, + as ProvideRuntimeApi>::Api: BlockBuilderApi, { fn push_extrinsic(&mut self, extrinsic: ::Extrinsic) -> Result<(), error::Error> { client::block_builder::BlockBuilder::push(self, extrinsic).map_err(Into::into) @@ -85,7 +82,7 @@ impl AuthoringApi for SubstrateClient where Block: BlockT, RA: Send + Sync + 'static, SubstrateClient : ProvideRuntimeApi, - as ProvideRuntimeApi>::Api: BlockBuilderApi, + as ProvideRuntimeApi>::Api: BlockBuilderApi, { type Block = Block; type Error = client::error::Error; @@ -93,13 +90,13 @@ impl AuthoringApi for SubstrateClient where fn build_block) -> ()>( &self, at: &BlockId, - inherent_data: BasicInherentData, + inherent_data: InherentData, mut build_ctx: F, ) -> Result { let mut block_builder = self.new_block_at(at)?; let runtime_api = self.runtime_api(); - if runtime_api.has_api::>(at)? { + if runtime_api.has_api::>(at)? { runtime_api.inherent_extrinsics(at, inherent_data)? .into_iter().try_for_each(|i| block_builder.push(i))?; } @@ -118,12 +115,12 @@ pub struct ProposerFactory where A: txpool::ChainApi { pub transaction_pool: Arc>, } -impl consensus_common::Environment<::Block, ConsensusData> for ProposerFactory where +impl consensus_common::Environment<::Block> for ProposerFactory where C: AuthoringApi, - ::Api: BlockBuilderApi<::Block, BasicInherentData>, + ::Api: BlockBuilderApi<::Block>, A: txpool::ChainApi::Block>, client::error::Error: From<::Error>, - Proposer<::Block, C, A>: consensus_common::Proposer<::Block, ConsensusData>, + Proposer<::Block, C, A>: consensus_common::Proposer<::Block>, { type Proposer = Proposer<::Block, C, A>; type Error = error::Error; @@ -151,10 +148,6 @@ impl consensus_common::Environment<::Blo } } -struct ConsensusData { - timestamp: Option, -} - /// The proposer logic. pub struct Proposer { client: Arc, @@ -164,53 +157,35 @@ pub struct Proposer { transaction_pool: Arc>, } -impl consensus_common::Proposer<::Block, AuraConsensusData> for Proposer where +impl consensus_common::Proposer<::Block> for Proposer where Block: BlockT, C: AuthoringApi, - ::Api: BlockBuilderApi, + ::Api: BlockBuilderApi, A: txpool::ChainApi, client::error::Error: From<::Error> { type Create = Result<::Block, error::Error>; type Error = error::Error; - fn propose(&self, consensus_data: AuraConsensusData) + fn propose(&self, inherent_data: InherentData) -> Result<::Block, error::Error> { - self.propose_with(ConsensusData { timestamp: Some(consensus_data.timestamp) }) - } -} - -impl consensus_common::Proposer<::Block, ()> for Proposer where - Block: BlockT, - C: AuthoringApi, - ::Api: BlockBuilderApi, - A: txpool::ChainApi, - client::error::Error: From<::Error> -{ - type Create = Result<::Block, error::Error>; - type Error = error::Error; - - fn propose(&self, _consensus_data: ()) -> Result<::Block, error::Error> { - self.propose_with(ConsensusData { timestamp: None }) + self.propose_with(inherent_data) } } impl Proposer where Block: BlockT, C: AuthoringApi, - ::Api: BlockBuilderApi, + ::Api: BlockBuilderApi, A: txpool::ChainApi, client::error::Error: From<::Error>, { - fn propose_with(&self, consensus_data: ConsensusData) + fn propose_with(&self, inherent_data: InherentData) -> Result<::Block, error::Error> { use runtime_primitives::traits::BlakeTwo256; - let timestamp = consensus_data.timestamp.unwrap_or_else(current_timestamp); - let inherent_data = BasicInherentData::new(timestamp, 0); - let block = self.client.build_block( &self.parent_id, inherent_data, @@ -261,9 +236,3 @@ impl Proposer where Ok(substrate_block) } } - -fn current_timestamp() -> Timestamp { - time::SystemTime::now().duration_since(time::UNIX_EPOCH) - .expect("now always later than unix epoch; qed") - .as_secs() -} diff --git a/substrate/core/basic-authorship/src/lib.rs b/substrate/core/basic-authorship/src/lib.rs index 0d7e310750..aafb2d0535 100644 --- a/substrate/core/basic-authorship/src/lib.rs +++ b/substrate/core/basic-authorship/src/lib.rs @@ -18,13 +18,13 @@ #![warn(unused_extern_crates)] -extern crate substrate_consensus_aura_primitives as aura_primitives; extern crate substrate_primitives as primitives; extern crate sr_primitives as runtime_primitives; extern crate substrate_consensus_common as consensus_common; extern crate substrate_client as client; extern crate parity_codec as codec; extern crate substrate_transaction_pool as transaction_pool; +extern crate substrate_inherents as inherents; #[macro_use] extern crate log; diff --git a/substrate/core/client/Cargo.toml b/substrate/core/client/Cargo.toml index e06139cc11..e1bafb0f09 100644 --- a/substrate/core/client/Cargo.toml +++ b/substrate/core/client/Cargo.toml @@ -22,11 +22,12 @@ substrate-telemetry = { path = "../telemetry", optional = true } hash-db = { version = "0.9" , optional = true } kvdb = { git = "https://github.com/paritytech/parity-common", optional = true, rev="b0317f649ab2c665b7987b8475878fc4d2e1f81d" } -codec = { package = "parity-codec", version = "2.1", default-features = false } +codec = { package = "parity-codec", version = "2.2", default-features = false } primitives = { package = "substrate-primitives", path = "../primitives", default-features = false } runtime-primitives = { package = "sr-primitives", path = "../sr-primitives", default-features = false } runtime-version = { package = "sr-version", path = "../sr-version", default-features = false } rstd = { package = "sr-std", path = "../sr-std", default-features = false } +inherents = { package = "substrate-inherents", path = "../inherents", default-features = false } sr-api-macros = { path = "../sr-api-macros" } [dev-dependencies] @@ -39,6 +40,7 @@ std = [ "codec/std", "consensus", "primitives/std", + "inherents/std", "parking_lot", "error-chain", "fnv", diff --git a/substrate/core/client/src/block_builder/api.rs b/substrate/core/client/src/block_builder/api.rs index 540c135de2..72cfea309f 100644 --- a/substrate/core/client/src/block_builder/api.rs +++ b/substrate/core/client/src/block_builder/api.rs @@ -16,13 +16,14 @@ //! The runtime api for building blocks. -use runtime_primitives::{traits::Block as BlockT, ApplyResult, CheckInherentError}; +use runtime_primitives::{traits::Block as BlockT, ApplyResult}; use rstd::vec::Vec; use sr_api_macros::decl_runtime_apis; +pub use inherents::{InherentData, CheckInherentsResult}; decl_runtime_apis! { /// The `BlockBuilder` api trait that provides required functions for building a block for a runtime. - pub trait BlockBuilder { + pub trait BlockBuilder { /// Apply the given extrinsics. fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyResult; /// Finish the current block. @@ -30,7 +31,7 @@ decl_runtime_apis! { /// Generate inherent extrinsics. The inherent data will vary from chain to chain. fn inherent_extrinsics(inherent: InherentData) -> Vec<::Extrinsic>; /// Check that the inherents are valid. The inherent data will vary from chain to chain. - fn check_inherents(block: Block, data: InherentData) -> Result<(), CheckInherentError>; + fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult; /// Generate a random seed. fn random_seed() -> ::Hash; } diff --git a/substrate/core/client/src/block_builder/block_builder.rs b/substrate/core/client/src/block_builder/block_builder.rs index a0e9d67827..4df12d94e2 100644 --- a/substrate/core/client/src/block_builder/block_builder.rs +++ b/substrate/core/client/src/block_builder/block_builder.rs @@ -16,7 +16,6 @@ use super::api::BlockBuilder as BlockBuilderApi; use std::vec::Vec; -use std::marker::PhantomData; use codec::Encode; use crate::blockchain::HeaderBackend; use runtime_primitives::traits::{ @@ -30,19 +29,18 @@ use runtime_primitives::ApplyOutcome; /// Utility for building new (valid) blocks from a stream of extrinsics. -pub struct BlockBuilder<'a, Block, InherentData, A: ProvideRuntimeApi> where Block: BlockT { +pub struct BlockBuilder<'a, Block, A: ProvideRuntimeApi> where Block: BlockT { header: ::Header, extrinsics: Vec<::Extrinsic>, api: ApiRef<'a, A::Api>, block_id: BlockId, - _marker: PhantomData, } -impl<'a, Block, A, InherentData> BlockBuilder<'a, Block, InherentData, A> +impl<'a, Block, A> BlockBuilder<'a, Block, A> where Block: BlockT, A: ProvideRuntimeApi + HeaderBackend + 'a, - A::Api: BlockBuilderApi, + A::Api: BlockBuilderApi, { /// Create a new instance of builder from the given client, building on the latest block. pub fn new(api: &'a A) -> error::Result { @@ -75,7 +73,6 @@ where extrinsics: Vec::new(), api, block_id: *block_id, - _marker: PhantomData, }) } diff --git a/substrate/core/client/src/client.rs b/substrate/core/client/src/client.rs index 67052ff7f1..87a91de3d9 100644 --- a/substrate/core/client/src/client.rs +++ b/substrate/core/client/src/client.rs @@ -47,7 +47,9 @@ use state_machine::{ }; use crate::backend::{self, BlockImportOperation, PrunableStateChangesTrieStorage}; -use crate::blockchain::{self, Info as ChainInfo, Backend as ChainBackend, HeaderBackend as ChainHeaderBackend}; +use crate::blockchain::{ + self, Info as ChainInfo, Backend as ChainBackend, HeaderBackend as ChainHeaderBackend +}; use crate::call_executor::{CallExecutor, LocalCallExecutor}; use executor::{RuntimeVersion, RuntimeInfo}; use crate::notifications::{StorageNotifications, StorageEventStream}; @@ -78,7 +80,8 @@ pub struct Client where Block: BlockT { import_notification_sinks: Mutex>>>, finality_notification_sinks: Mutex>>>, import_lock: Mutex<()>, - importing_block: RwLock>, // holds the block hash currently being imported. TODO: replace this with block queue + // holds the block hash currently being imported. TODO: replace this with block queue + importing_block: RwLock>, block_execution_strategy: ExecutionStrategy, api_execution_strategy: ExecutionStrategy, _phantom: PhantomData, @@ -557,25 +560,25 @@ impl Client where } /// Create a new block, built on the head of the chain. - pub fn new_block( + pub fn new_block( &self - ) -> error::Result> where + ) -> error::Result> where E: Clone + Send + Sync, RA: Send + Sync, Self: ProvideRuntimeApi, - ::Api: BlockBuilderAPI + ::Api: BlockBuilderAPI { block_builder::BlockBuilder::new(self) } /// Create a new block, built on top of `parent`. - pub fn new_block_at( + pub fn new_block_at( &self, parent: &BlockId - ) -> error::Result> where + ) -> error::Result> where E: Clone + Send + Sync, RA: Send + Sync, Self: ProvideRuntimeApi, - ::Api: BlockBuilderAPI + ::Api: BlockBuilderAPI { block_builder::BlockBuilder::at_block(parent, &self) } diff --git a/substrate/core/consensus/aura/Cargo.toml b/substrate/core/consensus/aura/Cargo.toml index 2cc5c6cfa3..d0ab6f8d4c 100644 --- a/substrate/core/consensus/aura/Cargo.toml +++ b/substrate/core/consensus/aura/Cargo.toml @@ -13,8 +13,9 @@ sr-primitives = { path = "../../sr-primitives" } sr-version = { path = "../../sr-version" } sr-io = { path = "../../sr-io" } substrate-consensus-aura-primitives = { path = "primitives" } - +substrate-inherents = { path = "../../inherents" } srml-consensus = { path = "../../../srml/consensus" } +srml-aura = { path = "../../../srml/aura" } futures = "0.1.17" tokio = "0.1.7" parking_lot = "0.7.1" diff --git a/substrate/core/consensus/aura/src/lib.rs b/substrate/core/consensus/aura/src/lib.rs index 374c4d613f..8aed003c51 100644 --- a/substrate/core/consensus/aura/src/lib.rs +++ b/substrate/core/consensus/aura/src/lib.rs @@ -33,6 +33,8 @@ extern crate srml_support as runtime_support; extern crate sr_io as runtime_io; extern crate sr_primitives as runtime_primitives; extern crate substrate_consensus_aura_primitives as aura_primitives; +extern crate srml_aura; +extern crate substrate_inherents as inherents; extern crate substrate_consensus_common as consensus_common; extern crate tokio; @@ -57,24 +59,33 @@ extern crate env_logger; mod slots; -use std::sync::Arc; -use std::time::Duration; +use std::{sync::{Arc, mpsc}, time::Duration, thread}; use codec::Encode; -use consensus_common::{Authorities, BlockImport, Environment, Error as ConsensusError, Proposer, ForkChoiceStrategy}; +use consensus_common::{ + Authorities, BlockImport, Environment, Error as ConsensusError, Proposer, ForkChoiceStrategy +}; use consensus_common::import_queue::{Verifier, BasicQueue}; use client::ChainHead; use client::block_builder::api::BlockBuilder as BlockBuilderApi; use consensus_common::{ImportBlock, BlockOrigin}; -use runtime_primitives::{generic, generic::BlockId, Justification, BasicInherentData}; -use runtime_primitives::traits::{Block, Header, Digest, DigestItemFor, DigestItem, ProvideRuntimeApi}; +use runtime_primitives::{generic, generic::BlockId, Justification}; +use runtime_primitives::traits::{ + Block, Header, Digest, DigestItemFor, DigestItem, ProvideRuntimeApi +}; use primitives::{Ed25519AuthorityId, ed25519}; +use inherents::{InherentDataProviders, InherentData, RuntimeString}; use futures::{Stream, Future, IntoFuture, future::{self, Either}}; use tokio::timer::Timeout; use api::AuraApi; use slots::Slots; +use srml_aura::{ + InherentType as AuraInherent, AuraInherentData, + timestamp::{TimestampInherentData, InherentType as TimestampInherent, InherentError as TIError} +}; + pub use aura_primitives::*; pub use consensus_common::SyncOracle; @@ -114,18 +125,23 @@ fn duration_now() -> Option { }).ok() } -fn timestamp_and_slot_now(slot_duration: u64) -> Option<(u64, u64)> { - duration_now().map(|s| { - let s = s.as_secs(); - (s, s / slot_duration) - }) -} - /// Get the slot for now. fn slot_now(slot_duration: u64) -> Option { duration_now().map(|s| s.as_secs() / slot_duration) } +fn extract_timestamp_and_slot( + data: &InherentData +) -> Result<(TimestampInherent, AuraInherent), consensus_common::Error> { + data.timestamp_inherent_data() + .and_then(|t| data.aura_inherent_data().map(|a| (t, a))) + .map_err(inherent_to_common_error) +} + +fn inherent_to_common_error(err: RuntimeString) -> consensus_common::Error { + consensus_common::ErrorKind::InherentData(err.into()).into() +} + /// A digest item which is usable with aura consensus. pub trait CompatibleDigestItem: Sized { /// Construct a digest item which is a slot number and a signature on the @@ -160,11 +176,12 @@ pub fn start_aura_thread( env: Arc, sync_oracle: SO, on_exit: impl Future + Send + 'static, -) where + inherent_data_providers: InherentDataProviders, +) -> Result<(), consensus_common::Error> where B: Block + 'static, C: Authorities + ChainHead + Send + Sync + 'static, - E: Environment + Send + Sync + 'static, - E::Proposer: Proposer + 'static, + E: Environment + Send + Sync + 'static, + E::Proposer: Proposer + 'static, I: BlockImport + Send + Sync + 'static, Error: From + From + 'static, SO: SyncOracle + Send + Clone + 'static, @@ -173,7 +190,9 @@ pub fn start_aura_thread( { use tokio::runtime::current_thread::Runtime; - ::std::thread::spawn(move || { + let (result_sender, result_recv) = mpsc::channel(); + + thread::spawn(move || { let mut runtime = match Runtime::new() { Ok(r) => r, Err(e) => { @@ -182,7 +201,7 @@ pub fn start_aura_thread( } }; - let _ = runtime.block_on(start_aura( + let aura_future = match start_aura( slot_duration, local_key, client, @@ -190,8 +209,26 @@ pub fn start_aura_thread( env, sync_oracle, on_exit, - )); + inherent_data_providers, + ) { + Ok(aura_future) => { + result_sender + .send(Ok(())) + .expect("Receive is not dropped before receiving a result; qed"); + aura_future + }, + Err(e) => { + result_sender + .send(Err(e)) + .expect("Receive is not dropped before receiving a result; qed"); + return; + } + }; + + let _ = runtime.block_on(aura_future); }); + + result_recv.recv().expect("Aura start thread result sender dropped") } /// Start the aura worker. The returned future should be run in a tokio runtime. @@ -203,17 +240,20 @@ pub fn start_aura( env: Arc, sync_oracle: SO, on_exit: impl Future, -) -> impl Future where + inherent_data_providers: InherentDataProviders, +) -> Result, consensus_common::Error> where B: Block, C: Authorities + ChainHead, - E: Environment, - E::Proposer: Proposer, + E: Environment, + E::Proposer: Proposer, I: BlockImport, Error: From + From, SO: SyncOracle + Send + Clone, DigestItemFor: CompatibleDigestItem + DigestItem, Error: ::std::error::Error + Send + 'static + From<::consensus_common::Error>, { + register_aura_inherent_data_provider(&inherent_data_providers, slot_duration.0)?; + let make_authorship = move || { let client = client.clone(); @@ -222,9 +262,10 @@ pub fn start_aura( let env = env.clone(); let sync_oracle = sync_oracle.clone(); let SlotDuration(slot_duration) = slot_duration; + let inherent_data_providers = inherent_data_providers.clone(); // rather than use a timer interval, we schedule our waits ourselves - Slots::new(slot_duration) + Slots::new(slot_duration, inherent_data_providers) .map_err(|e| debug!(target: "aura", "Faulty timer: {:?}", e)) .for_each(move |slot_info| { let client = client.clone(); @@ -244,7 +285,7 @@ pub fn start_aura( let chain_head = match client.best_block_header() { Ok(x) => x, Err(e) => { - warn!(target:"aura", "Unable to author block in slot {}. \ + warn!(target: "aura", "Unable to author block in slot {}. \ no best block header: {:?}", slot_num, e); return Either::B(future::ok(())) } @@ -253,8 +294,11 @@ pub fn start_aura( let authorities = match client.authorities(&BlockId::Hash(chain_head.hash())) { Ok(authorities) => authorities, Err(e) => { - warn!("Unable to fetch authorities at\ - block {:?}: {:?}", chain_head.hash(), e); + warn!( + "Unable to fetch authorities at block {:?}: {:?}", + chain_head.hash(), + e + ); return Either::B(future::ok(())); } }; @@ -262,8 +306,11 @@ pub fn start_aura( let proposal_work = match slot_author(slot_num, &authorities) { None => return Either::B(future::ok(())), Some(author) => if author.0 == public_key.0 { - debug!(target: "aura", "Starting authorship at slot {}; timestamp = {}", - slot_num, timestamp); + debug!( + target: "aura", "Starting authorship at slot {}; timestamp = {}", + slot_num, + timestamp + ); // we are the slot author. make a block and sign it. let proposer = match env.init(&chain_head, &authorities) { @@ -274,17 +321,12 @@ pub fn start_aura( } }; - let consensus_data = AuraConsensusData { - timestamp, - slot: slot_num, - slot_duration, - }; - + let remaining_duration = slot_info.remaining_duration(); // deadline our production to approx. the end of the // slot Timeout::new( - proposer.propose(consensus_data).into_future(), - slot_info.remaining_duration(), + proposer.propose(slot_info.inherent_data).into_future(), + remaining_duration, ) } else { return Either::B(future::ok(())); @@ -298,8 +340,10 @@ pub fn start_aura( // that is actually set by the proposer. let slot_after_building = slot_now(slot_duration); if slot_after_building != Some(slot_num) { - info!("Discarding proposal for slot {}; block production took too long", - slot_num); + info!( + "Discarding proposal for slot {}; block production took too long", + slot_num + ); return } @@ -363,7 +407,7 @@ pub fn start_aura( }) }); - work.select(on_exit).then(|_| Ok(())) + Ok(work.select(on_exit).then(|_| Ok(()))) } // a header which has been checked @@ -431,11 +475,58 @@ pub trait ExtraVerification: Send + Sync { } /// A verifier for Aura blocks. -pub struct AuraVerifier { - slot_duration: SlotDuration, +pub struct AuraVerifier { client: Arc, - make_inherent: MakeInherent, extra: E, + inherent_data_providers: inherents::InherentDataProviders, +} + +impl AuraVerifier +{ + fn check_inherents( + &self, + block: B, + block_id: BlockId, + inherent_data: InherentData, + timestamp_now: u64, + ) -> Result<(), String> + where C: ProvideRuntimeApi, C::Api: BlockBuilderApi + { + const MAX_TIMESTAMP_DRIFT_SECS: u64 = 60; + + let inherent_res = self.client.runtime_api().check_inherents( + &block_id, + block, + inherent_data, + ).map_err(|e| format!("{:?}", e))?; + + if !inherent_res.ok() { + inherent_res + .into_errors() + .try_for_each(|(i, e)| match TIError::try_from(&i, &e) { + Some(TIError::ValidAtTimestamp(timestamp)) => { + // halt import until timestamp is valid. + // reject when too far ahead. + if timestamp > timestamp_now + MAX_TIMESTAMP_DRIFT_SECS { + return Err("Rejecting block too far in future".into()); + } + + let diff = timestamp.saturating_sub(timestamp_now); + info!( + target: "aura", + "halting for block {} seconds in the future", + diff + ); + thread::sleep(Duration::from_secs(diff)); + Ok(()) + }, + Some(TIError::Other(e)) => Err(e.into()), + None => Err(self.inherent_data_providers.error_to_string(&i, &e)), + }) + } else { + Ok(()) + } + } } /// No-op extra verification. @@ -450,12 +541,11 @@ impl ExtraVerification for NothingExtra { } } -impl Verifier for AuraVerifier where +impl Verifier for AuraVerifier where C: Authorities + BlockImport + ProvideRuntimeApi + Send + Sync, - C::Api: BlockBuilderApi, + C::Api: BlockBuilderApi, DigestItemFor: CompatibleDigestItem + DigestItem, E: ExtraVerification, - MakeInherent: Fn(u64, u64) -> Inherent + Send + Sync, { fn verify( &self, @@ -464,11 +554,9 @@ impl Verifier for AuraVerifier, mut body: Option>, ) -> Result<(ImportBlock, Option>), String> { - use runtime_primitives::CheckInherentError; - const MAX_TIMESTAMP_DRIFT_SECS: u64 = 60; - - let (timestamp_now, slot_now) = timestamp_and_slot_now(self.slot_duration.0) - .ok_or("System time is before UnixTime?".to_owned())?; + let mut inherent_data = self.inherent_data_providers.create_inherent_data().map_err(String::from)?; + let (timestamp_now, slot_now) = extract_timestamp_and_slot(&inherent_data) + .map_err(|e| format!("Could not extract timestamp and slot: {:?}", e))?; let hash = header.hash(); let parent_hash = *header.parent_hash(); let authorities = self.client.authorities(&BlockId::Hash(parent_hash)) @@ -491,30 +579,15 @@ impl Verifier for AuraVerifier {} - Err(CheckInherentError::ValidAtTimestamp(timestamp)) => { - // halt import until timestamp is valid. - // reject when too far ahead. - if timestamp > timestamp_now + MAX_TIMESTAMP_DRIFT_SECS { - return Err("Rejecting block too far in future".into()); - } - - let diff = timestamp.saturating_sub(timestamp_now); - info!(target: "aura", "halting for block {} seconds in the future", diff); - ::std::thread::sleep(Duration::from_secs(diff)); - }, - Err(CheckInherentError::Other(s)) => return Err(s.into_owned()), - } + BlockId::Hash(parent_hash), + inherent_data, + timestamp_now, + )?; let (_, inner_body) = block.deconstruct(); body = Some(inner_body); @@ -546,16 +619,8 @@ impl Verifier for AuraVerifier BasicInherentData { - BasicInherentData::new(timestamp, slot_now) -} - -/// A type for a function which produces inherent. -pub type InherentProducingFn = fn(u64, u64) -> I; - /// The Aura import queue type. -pub type AuraImportQueue = BasicQueue>; +pub type AuraImportQueue = BasicQueue>; /// A slot duration. Create with `get_or_compute`. // The internal member should stay private here. @@ -584,8 +649,10 @@ impl SlotDuration { let genesis_slot_duration = client.runtime_api() .slot_duration(&BlockId::number(Zero::zero()))?; - info!("Loaded block-time = {:?} seconds from genesis on first-launch", - genesis_slot_duration); + info!( + "Loaded block-time = {:?} seconds from genesis on first-launch", + genesis_slot_duration + ); genesis_slot_duration.using_encoded(|s| { client.insert_aux(&[(SLOT_KEY, &s[..])], &[]) @@ -597,22 +664,39 @@ impl SlotDuration { } } +/// Register the aura inherent data provider, if not registered already. +fn register_aura_inherent_data_provider( + inherent_data_providers: &InherentDataProviders, + slot_duration: u64, +) -> Result<(), consensus_common::Error> { + if !inherent_data_providers.has_provider(&srml_aura::INHERENT_IDENTIFIER) { + inherent_data_providers + .register_provider(srml_aura::InherentDataProvider::new(slot_duration)) + .map_err(inherent_to_common_error) + } else { + Ok(()) + } +} + /// Start an import queue for the Aura consensus algorithm. -pub fn import_queue( +pub fn import_queue( slot_duration: SlotDuration, client: Arc, extra: E, - make_inherent: MakeInherent, -) -> AuraImportQueue where + inherent_data_providers: InherentDataProviders, +) -> Result, consensus_common::Error> where B: Block, - C: Authorities + BlockImport + ProvideRuntimeApi + Send + Sync, - C::Api: BlockBuilderApi, + C: Authorities + BlockImport + ProvideRuntimeApi + Send + Sync, + C::Api: BlockBuilderApi, DigestItemFor: CompatibleDigestItem + DigestItem, E: ExtraVerification, - MakeInherent: Fn(u64, u64) -> Inherent + Send + Sync, { - let verifier = Arc::new(AuraVerifier { slot_duration, client: client.clone(), extra, make_inherent }); - BasicQueue::new(verifier, client) + register_aura_inherent_data_provider(&inherent_data_providers, slot_duration.0)?; + + let verifier = Arc::new( + AuraVerifier { client: client.clone(), extra, inherent_data_providers } + ); + Ok(BasicQueue::new(verifier, client)) } #[cfg(test)] @@ -636,7 +720,7 @@ mod tests { struct DummyFactory(Arc); struct DummyProposer(u64, Arc); - impl Environment for DummyFactory { + impl Environment for DummyFactory { type Proposer = DummyProposer; type Error = Error; @@ -647,11 +731,11 @@ mod tests { } } - impl Proposer for DummyProposer { + impl Proposer for DummyProposer { type Error = Error; type Create = Result; - fn propose(&self, _consensus_data: AuraConsensusData) -> Result { + fn propose(&self, _: InherentData) -> Result { self.1.new_block().unwrap().bake().map_err(|e| e.into()) } } @@ -663,36 +747,38 @@ mod tests { peers: Vec, >, ()>>>, - started: bool + started: bool, } impl TestNetFactory for AuraTestNet { - type Verifier = AuraVerifier>; + type Verifier = AuraVerifier; type PeerData = (); /// Create new test network with peers and given config. fn from_config(_config: &ProtocolConfig) -> Self { AuraTestNet { peers: Vec::new(), - started: false + started: false, } } fn make_verifier(&self, client: Arc, _cfg: &ProtocolConfig) -> Arc { - fn make_inherent(_: u64, _: u64) { () } let slot_duration = SlotDuration::get_or_compute(&*client) .expect("slot duration available"); + let inherent_data_providers = InherentDataProviders::new(); + register_aura_inherent_data_provider( + &inherent_data_providers, + slot_duration.0 + ).expect("Registers aura inherent data provider"); assert_eq!(slot_duration.0, SLOT_DURATION); Arc::new(AuraVerifier { client, - slot_duration, extra: NothingExtra, - make_inherent: make_inherent as _, + inherent_data_providers, }) } @@ -748,6 +834,11 @@ mod tests { let slot_duration = SlotDuration::get_or_compute(&*client) .expect("slot duration available"); + let inherent_data_providers = InherentDataProviders::new(); + register_aura_inherent_data_provider( + &inherent_data_providers, slot_duration.0 + ).expect("Registers aura inherent data provider"); + let aura = start_aura( slot_duration, Arc::new(key.clone().into()), @@ -756,7 +847,8 @@ mod tests { environ.clone(), DummyOracle, futures::empty(), - ); + inherent_data_providers, + ).expect("Starts aura"); runtime.spawn(aura); } diff --git a/substrate/core/consensus/aura/src/slots.rs b/substrate/core/consensus/aura/src/slots.rs index 37db3b1763..faf966e329 100644 --- a/substrate/core/consensus/aura/src/slots.rs +++ b/substrate/core/consensus/aura/src/slots.rs @@ -22,6 +22,10 @@ use std::time::{Instant, Duration}; use tokio::timer::Delay; use futures::prelude::*; +use inherents::{InherentDataProviders, InherentData}; + +use consensus_common::{Error, ErrorKind}; + /// Returns the duration until the next slot, based on current duration since pub(crate) fn time_until_next(now: Duration, slot_duration: u64) -> Duration { let remaining_full_secs = slot_duration - (now.as_secs() % slot_duration) - 1; @@ -30,7 +34,6 @@ pub(crate) fn time_until_next(now: Duration, slot_duration: u64) -> Duration { } /// Information about a slot. -#[derive(Debug, Clone)] pub(crate) struct SlotInfo { /// The slot number. pub(crate) number: u64, @@ -38,6 +41,8 @@ pub(crate) struct SlotInfo { pub(crate) timestamp: u64, /// The instant at which the slot ends. pub(crate) ends_at: Instant, + /// The inherent data. + pub(crate) inherent_data: InherentData, } impl SlotInfo { @@ -57,22 +62,24 @@ pub(crate) struct Slots { last_slot: u64, slot_duration: u64, inner_delay: Option, + inherent_data_providers: InherentDataProviders, } impl Slots { - /// Create a new `slots` stream. - pub(crate) fn new(slot_duration: u64) -> Self { + /// Create a new `Slots` stream. + pub(crate) fn new(slot_duration: u64, inherent_data_providers: InherentDataProviders) -> Self { Slots { last_slot: 0, slot_duration, inner_delay: None, + inherent_data_providers, } } } impl Stream for Slots { type Item = SlotInfo; - type Error = tokio::timer::Error; + type Error = Error; fn poll(&mut self) -> Poll, Self::Error> { let slot_duration = self.slot_duration; @@ -90,30 +97,33 @@ impl Stream for Slots { }; if let Some(ref mut inner_delay) = self.inner_delay { - try_ready!(inner_delay.poll()); + try_ready!(inner_delay.poll().map_err(|e| Error::from(ErrorKind::FaultyTimer(e)))); } // timeout has fired. - let (timestamp, slot_num) = match ::timestamp_and_slot_now(slot_duration) { - None => return Ok(Async::Ready(None)), - Some(x) => x, - }; + let inherent_data = self.inherent_data_providers.create_inherent_data() + .map_err(::inherent_to_common_error)?; + let (timestamp, slot_num) = ::extract_timestamp_and_slot(&inherent_data)?; // reschedule delay for next slot. - let ends_at = Instant::now() - + time_until_next(Duration::from_secs(timestamp), slot_duration); + let ends_at = Instant::now() + time_until_next(Duration::from_secs(timestamp), slot_duration); self.inner_delay = Some(Delay::new(ends_at)); // never yield the same slot twice. if slot_num > self.last_slot { self.last_slot = slot_num; - Ok(Async::Ready(Some(SlotInfo { - number: slot_num, - timestamp, - ends_at, - }))) + Ok( + Async::Ready( + Some(SlotInfo { + number: slot_num, + timestamp, + ends_at, + inherent_data, + }) + ) + ) } else { // re-poll until we get a new slot. self.poll() diff --git a/substrate/core/consensus/common/Cargo.toml b/substrate/core/consensus/common/Cargo.toml index f8ae47d70f..1c3f335207 100644 --- a/substrate/core/consensus/common/Cargo.toml +++ b/substrate/core/consensus/common/Cargo.toml @@ -8,6 +8,7 @@ description = "Common utilities for substrate consensus" log = "0.4" parking_lot = "0.7.1" substrate-primitives = { path= "../../primitives" } +substrate-inherents = { path= "../../inherents" } error-chain = "0.12" futures = "0.1" sr-version = { path = "../../sr-version" } diff --git a/substrate/core/consensus/common/src/error.rs b/substrate/core/consensus/common/src/error.rs index ec378d24cb..caf325eeb3 100644 --- a/substrate/core/consensus/common/src/error.rs +++ b/substrate/core/consensus/common/src/error.rs @@ -37,6 +37,12 @@ error_chain! { display("Timer error: {}", e), } + /// Error while working with inherent data. + InherentData(e: String) { + description("InherentData error"), + display("InherentData error: {}", e), + } + /// Unable to propose a block. CannotPropose { description("Unable to create block proposal."), diff --git a/substrate/core/consensus/common/src/lib.rs b/substrate/core/consensus/common/src/lib.rs index 453b684430..861eaf9554 100644 --- a/substrate/core/consensus/common/src/lib.rs +++ b/substrate/core/consensus/common/src/lib.rs @@ -27,6 +27,7 @@ #![recursion_limit="128"] extern crate substrate_primitives as primitives; +extern crate substrate_inherents as inherents; extern crate futures; extern crate parking_lot; extern crate sr_version as runtime_version; @@ -47,6 +48,7 @@ use std::sync::Arc; use runtime_primitives::generic::BlockId; use runtime_primitives::traits::{AuthorityIdFor, Block}; use futures::prelude::*; +pub use inherents::InherentData; pub mod offline_tracker; pub mod error; @@ -67,9 +69,9 @@ pub trait Authorities { } /// Environment producer for a Consensus instance. Creates proposer instance and communication streams. -pub trait Environment { +pub trait Environment { /// The proposer type this creates. - type Proposer: Proposer; + type Proposer: Proposer; /// Error which can occur upon creation. type Error: From; @@ -85,13 +87,13 @@ pub trait Environment { /// block. /// /// Proposers are generic over bits of "consensus data" which are engine-specific. -pub trait Proposer { +pub trait Proposer { /// Error type which can occur when proposing or evaluating. type Error: From + ::std::fmt::Debug + 'static; /// Future that resolves to a committed proposal. - type Create: IntoFuture; + type Create: IntoFuture; /// Create a proposal. - fn propose(&self, consensus_data: ConsensusData) -> Self::Create; + fn propose(&self, inherent_data: InherentData) -> Self::Create; } /// An oracle for when major synchronization work is being undertaken. diff --git a/substrate/core/inherents/Cargo.toml b/substrate/core/inherents/Cargo.toml new file mode 100644 index 0000000000..7820926a8a --- /dev/null +++ b/substrate/core/inherents/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "substrate-inherents" +version = "0.1.0" +authors = ["Parity Technologies "] +edition = "2018" + +[dependencies] +parking_lot = { version = "0.7", optional = true } +rstd = { package = "sr-std", path = "../sr-std", default-features = false } +parity-codec = { version = "2.2", default-features = false } +parity-codec-derive = { version = "2.2", default-features = false } +runtime_primitives = { package = "sr-primitives", path = "../sr-primitives", default-features = false } + +[features] +default = [ "std" ] +std = [ + "parking_lot", + "rstd/std", + "parity-codec/std", + "runtime_primitives/std", +] diff --git a/substrate/core/inherents/src/lib.rs b/substrate/core/inherents/src/lib.rs new file mode 100644 index 0000000000..16910fd4ab --- /dev/null +++ b/substrate/core/inherents/src/lib.rs @@ -0,0 +1,575 @@ +// 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 . + +//! Provides types and traits for creating and checking inherents. +//! +//! Each inherent is added to a produced block. Each runtime decides on which inherents its +//! want to attach to its blocks. All data that is required for the runtime to create the inherents +//! is stored in the `InherentData`. This `InherentData` is constructed by the node and given to +//! the runtime. +//! +//! Types that provide data for inherents, should implement `InherentDataProvider` and need to be +//! registered at `InherentDataProviders`. +//! +//! In the runtime, modules need to implement `ProvideInherent` when they can create and/or check +//! inherents. By implementing `ProvideInherent`, a module is not enforced to create an inherent. +//! A module can also just check given inherents. For using a module as inherent provider, it needs +//! to be registered by the `construct_runtime!` macro. The macro documentation gives more +//! information on how that is done. + +#![cfg_attr(not(feature = "std"), no_std)] + +extern crate parity_codec as codec; + +use parity_codec_derive::{Encode, Decode}; + +use rstd::{collections::btree_map::{BTreeMap, IntoIter, Entry}, vec::Vec}; + +#[cfg(feature = "std")] +use parking_lot::RwLock; + +#[cfg(feature = "std")] +use std::{sync::Arc, format}; + +pub use runtime_primitives::RuntimeString; + +/// An identifier for an inherent. +pub type InherentIdentifier = [u8; 8]; + +/// Inherent data to include in a block. +pub struct InherentData { + /// All inherent data encoded with parity-codec and an identifier. + data: BTreeMap> +} + +impl InherentData { + /// Create a new instance. + pub fn new() -> Self { + Self { + data: Default::default(), + } + } + + /// Put data for an inherent into the internal storage. + /// + /// # Return + /// + /// Returns `Ok(())` if the data could be inserted an no data for an inherent with the same + /// identifier existed, otherwise an error is returned. + /// + /// Inherent identifiers need to be unique, otherwise decoding of these values will not work! + pub fn put_data( + &mut self, + identifier: InherentIdentifier, + inherent: &I, + ) -> Result<(), RuntimeString> { + match self.data.entry(identifier) { + Entry::Vacant(entry) => { + entry.insert(inherent.encode()); + Ok(()) + }, + Entry::Occupied(_) => { + Err("Inherent with same identifier already exists!".into()) + } + } + } + + /// Replace the data for an inherent. + /// + /// If it does not exist, the data is just inserted. + pub fn replace_data( + &mut self, + identifier: InherentIdentifier, + inherent: &I, + ) { + self.data.insert(identifier, inherent.encode()); + } + + /// Returns the data for the requested inherent. + /// + /// # Return + /// + /// - `Ok(Some(I))` if the data could be found and deserialized. + /// - `Ok(None)` if the data could not be found. + /// - `Err(_)` if the data could be found, but deserialization did not work. + pub fn get_data( + &self, + identifier: &InherentIdentifier, + ) -> Result, RuntimeString> { + match self.data.get(identifier) { + Some(inherent) => + I::decode(&mut &inherent[..]) + .ok_or_else(|| "Could not decode requested inherent type!".into()) + .map(Some), + None => Ok(None) + } + } +} + +impl codec::Encode for InherentData { + fn encode(&self) -> Vec { + let keys = self.data.keys().collect::>(); + let values = self.data.values().collect::>(); + + let mut encoded = keys.encode(); + encoded.extend(values.encode()); + encoded + } +} + +impl codec::Decode for InherentData { + fn decode(value: &mut I) -> Option { + Vec::::decode(value) + .and_then(|i| Vec::>::decode(value).map(|v| (i, v))) + .and_then(|(i, v)| { + if i.len() == v.len() { + Some(Self { + data: i.into_iter().zip(v.into_iter()).collect() + }) + } else { + None + } + }) + } +} + +/// The result of checking inherents. +/// +/// It either returns okay for all checks, stores all occurred errors or just one fatal error. +/// +/// When a fatal error occurres, all other errors are removed and the implementation needs to +/// abbort checking inherents. +#[derive(Encode, Decode)] +pub struct CheckInherentsResult { + /// Did the check succeed? + okay: bool, + /// Did we encounter a fatal error? + fatal_error: bool, + /// We use the `InherentData` to store our errors. + errors: InherentData, +} + +impl CheckInherentsResult { + /// Create a new instance. + pub fn new() -> Self { + Self { + okay: true, + errors: InherentData::new(), + fatal_error: false, + } + } + + /// Put an error into the result. + /// + /// This makes this result resolve to `ok() == false`. + /// + /// # Parameters + /// + /// - identifier - The identifier of the inherent that generated the error. + /// - error - The error that will be encoded. + pub fn put_error( + &mut self, + identifier: InherentIdentifier, + error: &E, + ) -> Result<(), RuntimeString> { + // Don't accept any other error + if self.fatal_error { + return Err("No other errors are accepted after an hard error!".into()) + } + + if error.is_fatal_error() { + // remove the other errors. + self.errors.data.clear(); + } + + self.errors.put_data(identifier, error)?; + + self.okay = false; + self.fatal_error = error.is_fatal_error(); + Ok(()) + } + + /// Get an error out of the result. + /// + /// # Return + /// + /// - `Ok(Some(I))` if the error could be found and deserialized. + /// - `Ok(None)` if the error could not be found. + /// - `Err(_)` if the error could be found, but deserialization did not work. + pub fn get_error( + &self, + identifier: &InherentIdentifier, + ) -> Result, RuntimeString> { + self.errors.get_data(identifier) + } + + /// Convert into an iterator over all contained errors. + pub fn into_errors(self) -> IntoIter> { + self.errors.data.into_iter() + } + + /// Is this result ok? + pub fn ok(&self) -> bool { + self.okay + } + + /// Is this a fatal error? + pub fn fatal_error(&self) -> bool { + self.fatal_error + } +} + +#[cfg(feature = "std")] +impl PartialEq for CheckInherentsResult { + fn eq(&self, other: &Self) -> bool { + self.fatal_error == other.fatal_error && + self.okay == other.okay && + self.errors.data == other.errors.data + } +} + +/// All `InherentData` providers. +#[cfg(feature = "std")] +#[derive(Clone)] +pub struct InherentDataProviders { + providers: Arc>>>, +} + +#[cfg(feature = "std")] +impl InherentDataProviders { + /// Create a new instance. + pub fn new() -> Self { + Self { + providers: Default::default(), + } + } + + /// Register an `InherentData` provider. + /// + /// The registration order is preserved and this order will also be used when creating the + /// inherent data. + /// + /// # Result + /// + /// Will return an error, if a provider with the same identifier already exists. + pub fn register_provider( + &self, + provider: P, + ) -> Result<(), RuntimeString> { + if self.has_provider(&provider.inherent_identifier()) { + Err( + format!( + "Inherent data provider with identifier {:?} already exists!", + &provider.inherent_identifier() + ).into() + ) + } else { + provider.on_register(self)?; + self.providers.write().push(Box::new(provider)); + Ok(()) + } + } + + /// Returns if a provider for the given identifier exists. + pub fn has_provider(&self, identifier: &InherentIdentifier) -> bool { + self.providers.read().iter().any(|p| p.inherent_identifier() == identifier) + } + + /// Create inherent data. + pub fn create_inherent_data(&self) -> Result { + let mut data = InherentData::new(); + self.providers.read().iter().try_for_each(|p| { + p.provide_inherent_data(&mut data) + .map_err(|e| format!("Error for `{:?}`: {:?}", p.inherent_identifier(), e)) + })?; + Ok(data) + } + + /// Converts a given encoded error into a `String`. + /// + /// Useful if the implementation encouters an error for an identifier it does not know. + pub fn error_to_string(&self, identifier: &InherentIdentifier, error: &[u8]) -> String { + let res = self.providers.read().iter().filter_map(|p| + if p.inherent_identifier() == identifier { + Some( + p.error_to_string(error) + .unwrap_or_else(|| error_to_string_fallback(identifier)) + ) + } else { + None + } + ).next(); + + match res { + Some(res) => res, + None => format!( + "Error while checking inherent of type \"{}\", but this inherent type is unknown.", + String::from_utf8_lossy(identifier) + ) + } + } +} + +/// Something that provides inherent data. +#[cfg(feature = "std")] +pub trait ProvideInherentData { + /// Is called when this inherent data provider is registered at the given + /// `InherentDataProviders`. + fn on_register(&self, _: &InherentDataProviders) -> Result<(), RuntimeString> { + Ok(()) + } + + /// The identifier of the inherent for that data will be provided. + fn inherent_identifier(&self) -> &'static InherentIdentifier; + + /// Provide inherent data that should be included in a block. + /// + /// The data should be stored in the given `InherentData` structure. + fn provide_inherent_data(&self, inherent_data: &mut InherentData) -> Result<(), RuntimeString>; + + /// Convert the given encoded error to a string. + /// + /// If the given error could not be decoded, `None` should be returned. + fn error_to_string(&self, error: &[u8]) -> Option; +} + +/// A fallback function, if the decoding of an error fails. +#[cfg(feature = "std")] +fn error_to_string_fallback(identifier: &InherentIdentifier) -> String { + format!( + "Error while checking inherent of type \"{}\", but error could not be decoded.", + String::from_utf8_lossy(identifier) + ) +} + +/// Did we encounter a fatal error while checking an inherent? +/// +/// A fatal error is everything that fails while checking an inherent error, e.g. the inherent +/// was not found, could not be decoded etc. +/// Then there are cases where you not want the inherent check to fail, but report that there is an +/// action required. For example a timestamp of a block is in the future, the timestamp is still +/// correct, but it is required to verify the block at a later time again and then the inherent +/// check will succeed. +pub trait IsFatalError { + /// Is this a fatal error? + fn is_fatal_error(&self) -> bool; +} + +/// Auxiliary to make any given error resolve to `is_fatal_error() == true`. +#[derive(Encode)] +pub struct MakeFatalError(E); + +impl From for MakeFatalError { + fn from(err: E) -> Self { + MakeFatalError(err) + } +} + +impl IsFatalError for MakeFatalError { + fn is_fatal_error(&self) -> bool { + true + } +} + +/// A module that provides an inherent and may also verifies it. +pub trait ProvideInherent { + /// The call type of the module. + type Call; + /// The error returned by `check_inherent`. + type Error: codec::Encode + IsFatalError; + /// The inherent identifier used by this inherent. + const INHERENT_IDENTIFIER: self::InherentIdentifier; + + /// Create an inherent out of the given `InherentData`. + fn create_inherent(data: &InherentData) -> Option; + + /// Check the given inherent if it is valid. + /// Checking the inherent is optional and can be ommitted. + fn check_inherent(_: &Self::Call, _: &InherentData) -> Result<(), Self::Error> { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use codec::{Encode, Decode}; + + const TEST_INHERENT_0: InherentIdentifier = *b"testinh0"; + const TEST_INHERENT_1: InherentIdentifier = *b"testinh1"; + + #[derive(Encode)] + struct NoFatalError(E); + impl IsFatalError for NoFatalError { + fn is_fatal_error(&self) -> bool { + false + } + } + + #[test] + fn inherent_data_encodes_and_decodes() { + let inherent_0 = vec![1, 2, 3]; + let inherent_1: u32 = 7; + + let mut data = InherentData::new(); + data.put_data(TEST_INHERENT_0, &inherent_0).unwrap(); + data.put_data(TEST_INHERENT_1, &inherent_1).unwrap(); + + let encoded = data.encode(); + + let decoded = InherentData::decode(&mut &encoded[..]).unwrap(); + + assert_eq!(decoded.get_data::>(&TEST_INHERENT_0).unwrap().unwrap(), inherent_0); + assert_eq!(decoded.get_data::(&TEST_INHERENT_1).unwrap().unwrap(), inherent_1); + } + + #[test] + fn adding_same_inherent_returns_an_error() { + let mut data = InherentData::new(); + data.put_data(TEST_INHERENT_0, &8).unwrap(); + assert!(data.put_data(TEST_INHERENT_0, &10).is_err()); + } + + #[derive(Clone)] + struct TestInherentDataProvider { + registered: Arc>, + } + + impl TestInherentDataProvider { + fn new() -> Self { + let inst = Self { + registered: Default::default(), + }; + + // just make sure + assert!(!inst.is_registered()); + + inst + } + + fn is_registered(&self) -> bool { + *self.registered.read() + } + } + + const ERROR_TO_STRING: &str = "Found error!"; + + impl ProvideInherentData for TestInherentDataProvider { + fn on_register(&self, _: &InherentDataProviders) -> Result<(), RuntimeString> { + *self.registered.write() = true; + Ok(()) + } + + fn inherent_identifier(&self) -> &'static InherentIdentifier { + &TEST_INHERENT_0 + } + + fn provide_inherent_data(&self, data: &mut InherentData) -> Result<(), RuntimeString> { + data.put_data(TEST_INHERENT_0, &42) + } + + fn error_to_string(&self, _: &[u8]) -> Option { + Some(ERROR_TO_STRING.into()) + } + } + + #[test] + fn registering_inherent_provider() { + let provider = TestInherentDataProvider::new(); + let providers = InherentDataProviders::new(); + + providers.register_provider(provider.clone()).unwrap(); + assert!(provider.is_registered()); + assert!(providers.has_provider(provider.inherent_identifier())); + + // Second time should fail + assert!(providers.register_provider(provider.clone()).is_err()); + } + + #[test] + fn create_inherent_data_from_all_providers() { + let provider = TestInherentDataProvider::new(); + let providers = InherentDataProviders::new(); + + providers.register_provider(provider.clone()).unwrap(); + assert!(provider.is_registered()); + + let inherent_data = providers.create_inherent_data().unwrap(); + + assert_eq!( + inherent_data.get_data::(provider.inherent_identifier()).unwrap().unwrap(), + 42u32 + ); + } + + #[test] + fn encoded_error_to_string() { + let provider = TestInherentDataProvider::new(); + let providers = InherentDataProviders::new(); + + providers.register_provider(provider.clone()).unwrap(); + assert!(provider.is_registered()); + + assert_eq!( + &providers.error_to_string(&TEST_INHERENT_0, &[1, 2]), ERROR_TO_STRING + ); + + assert!( + providers + .error_to_string(&TEST_INHERENT_1, &[1, 2]) + .contains("inherent type is unknown") + ); + } + + #[test] + fn check_inherents_result_encodes_and_decodes() { + let mut result = CheckInherentsResult::new(); + assert!(result.ok()); + + result.put_error(TEST_INHERENT_0, &NoFatalError(2u32)).unwrap(); + assert!(!result.ok()); + assert!(!result.fatal_error()); + + let encoded = result.encode(); + + let decoded = CheckInherentsResult::decode(&mut &encoded[..]).unwrap(); + + assert_eq!(decoded.get_error::(&TEST_INHERENT_0).unwrap().unwrap(), 2); + assert!(!decoded.ok()); + assert!(!decoded.fatal_error()); + } + + #[test] + fn check_inherents_result_removes_other_errors_on_fatal_error() { + let mut result = CheckInherentsResult::new(); + assert!(result.ok()); + + result.put_error(TEST_INHERENT_0, &NoFatalError(2u32)).unwrap(); + assert!(!result.ok()); + assert!(!result.fatal_error()); + + result.put_error(TEST_INHERENT_1, &MakeFatalError(4u32)).unwrap(); + assert!(!result.ok()); + assert!(result.fatal_error()); + + assert!(result.put_error(TEST_INHERENT_0, &NoFatalError(5u32)).is_err()); + + result.into_errors().for_each(|(i, e)| match i { + TEST_INHERENT_1 => assert_eq!(u32::decode(&mut &e[..]).unwrap(), 4), + _ => panic!("There should be no other error!"), + }); + } +} diff --git a/substrate/core/network/src/test/mod.rs b/substrate/core/network/src/test/mod.rs index 3e45188544..13fc86d1a5 100644 --- a/substrate/core/network/src/test/mod.rs +++ b/substrate/core/network/src/test/mod.rs @@ -406,7 +406,7 @@ impl, D> Peer { /// Add blocks to the peer -- edit the block before adding pub fn generate_blocks(&self, count: usize, origin: BlockOrigin, mut edit_block: F) - where F: FnMut(BlockBuilder) -> Block + where F: FnMut(BlockBuilder) -> Block { for _ in 0..count { let builder = self.client.new_block().unwrap(); @@ -493,7 +493,6 @@ pub trait TestNetFactory: Sized { fn from_config(config: &ProtocolConfig) -> Self; fn make_verifier(&self, client: Arc, config: &ProtocolConfig) -> Arc; - /// Get reference to peer. fn peer(&self, i: usize) -> &Peer; fn peers(&self) -> &Vec>>; diff --git a/substrate/core/service/src/chain_ops.rs b/substrate/core/service/src/chain_ops.rs index 75d4688669..522f60a5cf 100644 --- a/substrate/core/service/src/chain_ops.rs +++ b/substrate/core/service/src/chain_ops.rs @@ -32,7 +32,14 @@ use error; use chain_spec::ChainSpec; /// Export a range of blocks to a binary stream. -pub fn export_blocks(config: FactoryFullConfiguration, exit: E, mut output: W, from: FactoryBlockNumber, to: Option>, json: bool) -> error::Result<()> +pub fn export_blocks( + config: FactoryFullConfiguration, + exit: E, + mut output: W, + from: FactoryBlockNumber, + to: Option>, + json: bool +) -> error::Result<()> where F: ServiceFactory, E: Future + Send + 'static, @@ -68,7 +75,8 @@ pub fn export_blocks(config: FactoryFullConfiguration, exit: E, mut match client.block(&BlockId::number(block))? { Some(block) => { if json { - serde_json::to_writer(&mut output, &block).map_err(|e| format!("Eror writing JSON: {}", e))?; + serde_json::to_writer(&mut output, &block) + .map_err(|e| format!("Eror writing JSON: {}", e))?; } else { output.write(&block.encode())?; } @@ -87,7 +95,11 @@ pub fn export_blocks(config: FactoryFullConfiguration, exit: E, mut } /// Import blocks from a binary stream. -pub fn import_blocks(mut config: FactoryFullConfiguration, exit: E, mut input: R) -> error::Result<()> +pub fn import_blocks( + mut config: FactoryFullConfiguration, + exit: E, + mut input: R +) -> error::Result<()> where F: ServiceFactory, E: Future + Send + 'static, R: Read, { struct DummyLink; @@ -148,7 +160,10 @@ pub fn import_blocks(mut config: FactoryFullConfiguration, exit: E, } /// Revert the chain. -pub fn revert_chain(config: FactoryFullConfiguration, blocks: FactoryBlockNumber) -> error::Result<()> +pub fn revert_chain( + config: FactoryFullConfiguration, + blocks: FactoryBlockNumber +) -> error::Result<()> where F: ServiceFactory, { let client = new_client::(&config)?; diff --git a/substrate/core/service/src/components.rs b/substrate/core/service/src/components.rs index 8756f58009..0cdf11cc88 100644 --- a/substrate/core/service/src/components.rs +++ b/substrate/core/service/src/components.rs @@ -27,7 +27,9 @@ use consensus_common::import_queue::ImportQueue; use network::{self, OnDemand}; use substrate_executor::{NativeExecutor, NativeExecutionDispatch}; use transaction_pool::txpool::{self, Options as TransactionPoolOptions, Pool as TransactionPool}; -use runtime_primitives::{BuildStorage, traits::{Block as BlockT, Header as HeaderT, ProvideRuntimeApi}, generic::BlockId}; +use runtime_primitives::{ + BuildStorage, traits::{Block as BlockT, Header as HeaderT, ProvideRuntimeApi}, generic::BlockId +}; use config::Configuration; use primitives::{Blake2Hasher, H256}; use rpc::{self, apis::system::SystemInfo}; diff --git a/substrate/core/service/src/error.rs b/substrate/core/service/src/error.rs index c3bacd1980..f346db434a 100644 --- a/substrate/core/service/src/error.rs +++ b/substrate/core/service/src/error.rs @@ -19,6 +19,7 @@ use client; use network; use keystore; +use consensus_common; error_chain! { foreign_links { @@ -27,6 +28,7 @@ error_chain! { links { Client(client::error::Error, client::error::ErrorKind) #[doc="Client error"]; + Consensus(consensus_common::Error, consensus_common::ErrorKind) #[doc="Consesus error"]; Network(network::error::Error, network::error::ErrorKind) #[doc="Network error"]; Keystore(keystore::Error, keystore::ErrorKind) #[doc="Keystore error"]; } diff --git a/substrate/core/service/src/lib.rs b/substrate/core/service/src/lib.rs index 2eeaff6385..170f38fd4e 100644 --- a/substrate/core/service/src/lib.rs +++ b/substrate/core/service/src/lib.rs @@ -77,7 +77,9 @@ use codec::{Encode, Decode}; pub use self::error::{ErrorKind, Error}; pub use config::{Configuration, Roles, PruningMode}; pub use chain_spec::{ChainSpec, Properties}; -pub use transaction_pool::txpool::{self, Pool as TransactionPool, Options as TransactionPoolOptions, ChainApi, IntoPoolError}; +pub use transaction_pool::txpool::{ + self, Pool as TransactionPool, Options as TransactionPoolOptions, ChainApi, IntoPoolError +}; pub use client::{ExecutionStrategy, FinalityNotifications}; pub use components::{ServiceFactory, FullBackend, FullExecutor, LightBackend, @@ -294,7 +296,8 @@ impl Service { properties: config.chain_spec.properties(), }; let rpc = Components::RPC::start_rpc( - client.clone(), network.clone(), has_bootnodes, system_info, config.rpc_http, config.rpc_ws, task_executor.clone(), transaction_pool.clone(), + client.clone(), network.clone(), has_bootnodes, system_info, config.rpc_http, + config.rpc_ws, task_executor.clone(), transaction_pool.clone(), )?; // Telemetry @@ -392,8 +395,8 @@ impl Drop for Service where Components: components::Comp } } -fn maybe_start_server(address: Option, start: F) -> Result, io::Error> where - F: Fn(&SocketAddr) -> Result, +fn maybe_start_server(address: Option, start: F) -> Result, io::Error> + where F: Fn(&SocketAddr) -> Result, { Ok(match address { Some(mut address) => Some(start(&address) @@ -428,7 +431,9 @@ impl TransactionPoolAdapter { } } -impl network::TransactionPool, ComponentBlock> for TransactionPoolAdapter where ::RuntimeApi: Send + Sync{ +impl network::TransactionPool, ComponentBlock> for + TransactionPoolAdapter where ::RuntimeApi: Send + Sync +{ fn transactions(&self) -> Vec<(ComponentExHash, ComponentExtrinsic)> { self.pool.ready() .map(|t| { diff --git a/substrate/core/service/test/src/lib.rs b/substrate/core/service/test/src/lib.rs index cc0947372c..c179a8f562 100644 --- a/substrate/core/service/test/src/lib.rs +++ b/substrate/core/service/test/src/lib.rs @@ -182,7 +182,7 @@ impl TestNet { } } -pub fn connectivity(spec: FactoryChainSpec) { +pub fn connectivity(spec: FactoryChainSpec) { const NUM_NODES: u32 = 10; { let temp = TempDir::new("substrate-connectivity-test").expect("Error creating test dir"); diff --git a/substrate/core/sr-primitives/Cargo.toml b/substrate/core/sr-primitives/Cargo.toml index 81fb8eddff..e5a2c2576f 100644 --- a/substrate/core/sr-primitives/Cargo.toml +++ b/substrate/core/sr-primitives/Cargo.toml @@ -30,5 +30,3 @@ std = [ "parity-codec/std", "substrate-primitives/std", ] -api-for-runtime = [] - diff --git a/substrate/core/sr-primitives/src/lib.rs b/substrate/core/sr-primitives/src/lib.rs index 01ef2f171f..c0480591cb 100644 --- a/substrate/core/sr-primitives/src/lib.rs +++ b/substrate/core/sr-primitives/src/lib.rs @@ -511,57 +511,6 @@ macro_rules! impl_outer_log { }; } -//TODO: https://github.com/paritytech/substrate/issues/1022 -/// Basic Inherent data to include in a block; used by simple runtimes. -#[derive(Encode, Decode)] -pub struct BasicInherentData { - /// Current timestamp. - pub timestamp: u64, - /// Blank report. - pub consensus: (), - /// Aura expected slot. Can take any value during block construction. - pub aura_expected_slot: u64, -} - -impl BasicInherentData { - /// Create a new `BasicInherentData` instance. - pub fn new(timestamp: u64, expected_slot: u64) -> Self { - Self { - timestamp, - consensus: (), - aura_expected_slot: expected_slot, - } - } -} - -//TODO: https://github.com/paritytech/substrate/issues/1022 -/// Error type used while checking inherents. -#[derive(Encode, PartialEq)] -#[cfg_attr(feature = "std", derive(Decode))] -pub enum CheckInherentError { - /// The inherents are generally valid but a delay until the given timestamp - /// is required. - ValidAtTimestamp(u64), - /// Some other error has occurred. - Other(RuntimeString), -} - -impl CheckInherentError { - /// Combine two results, taking the "worse" of the two. - pub fn combine_results Result<(), Self>>(this: Result<(), Self>, other: F) -> Result<(), Self> { - match this { - Ok(()) => other(), - Err(CheckInherentError::Other(s)) => Err(CheckInherentError::Other(s)), - Err(CheckInherentError::ValidAtTimestamp(x)) => match other() { - Ok(()) => Err(CheckInherentError::ValidAtTimestamp(x)), - Err(CheckInherentError::ValidAtTimestamp(y)) - => Err(CheckInherentError::ValidAtTimestamp(rstd::cmp::max(x, y))), - Err(CheckInherentError::Other(s)) => Err(CheckInherentError::Other(s)), - } - } - } -} - /// Simple blob to hold an extrinsic without commiting to its format and ensure it is serialized /// correctly. #[derive(PartialEq, Eq, Clone, Default, Encode, Decode)] diff --git a/substrate/core/sr-primitives/src/traits.rs b/substrate/core/sr-primitives/src/traits.rs index 8723dbec91..623d04a938 100644 --- a/substrate/core/sr-primitives/src/traits.rs +++ b/substrate/core/sr-primitives/src/traits.rs @@ -621,26 +621,6 @@ pub trait DigestItem: Codec + Member + MaybeSerializeDebugButNotDeserialize { fn as_changes_trie_root(&self) -> Option<&Self::Hash>; } -/// Something that provides an inherent for a runtime. -pub trait ProvideInherent { - /// The inherent that is provided. - type Inherent: Encode + MaybeDecode; - /// The call for setting the inherent. - type Call: Encode + MaybeDecode; - - /// Create the inherent extrinsics. - /// - /// # Return - /// - /// Returns a vector with tuples containing the index for the extrinsic and the extrinsic itself. - fn create_inherent_extrinsics(data: Self::Inherent) -> Vec<(u32, Self::Call)>; - - /// Check that the given inherent is valid. - fn check_inherent Option<&Self::Call>>( - block: &Block, data: Self::Inherent, extract_function: &F - ) -> Result<(), super::CheckInherentError>; -} - /// Auxiliary wrapper that holds an api instance and binds it to the given lifetime. pub struct ApiRef<'a, T>(T, rstd::marker::PhantomData<&'a ()>); diff --git a/substrate/core/test-client/src/block_builder_ext.rs b/substrate/core/test-client/src/block_builder_ext.rs index 5803c5303d..f2febf8836 100644 --- a/substrate/core/test-client/src/block_builder_ext.rs +++ b/substrate/core/test-client/src/block_builder_ext.rs @@ -29,9 +29,9 @@ pub trait BlockBuilderExt { fn push_transfer(&mut self, transfer: runtime::Transfer) -> Result<(), client::error::Error>; } -impl<'a, A> BlockBuilderExt for client::block_builder::BlockBuilder<'a, runtime::Block, (), A> where +impl<'a, A> BlockBuilderExt for client::block_builder::BlockBuilder<'a, runtime::Block, A> where A: ProvideRuntimeApi + client::blockchain::HeaderBackend + 'a, - A::Api: BlockBuilder + A::Api: BlockBuilder { fn push_transfer(&mut self, transfer: runtime::Transfer) -> Result<(), client::error::Error> { self.push(sign_tx(transfer)) @@ -39,6 +39,9 @@ impl<'a, A> BlockBuilderExt for client::block_builder::BlockBuilder<'a, runtime: } fn sign_tx(transfer: runtime::Transfer) -> runtime::Extrinsic { - let signature = keyring::Keyring::from_raw_public(transfer.from.to_fixed_bytes()).unwrap().sign(&codec::Encode::encode(&transfer)).into(); + let signature = keyring::Keyring::from_raw_public(transfer.from.to_fixed_bytes()) + .unwrap() + .sign(&codec::Encode::encode(&transfer)) + .into(); runtime::Extrinsic::Transfer(transfer, signature) } diff --git a/substrate/core/test-runtime/Cargo.toml b/substrate/core/test-runtime/Cargo.toml index f7838450cc..d1e8135049 100644 --- a/substrate/core/test-runtime/Cargo.toml +++ b/substrate/core/test-runtime/Cargo.toml @@ -13,6 +13,7 @@ parity-codec-derive = { version = "2.1", default-features = false } substrate-keyring = { path = "../keyring", optional = true } substrate-client = { path = "../client", default-features = false } substrate-primitives = { path = "../primitives", default-features = false } +substrate-inherents = { path = "../inherents", default-features = false } substrate-consensus-aura-primitives = { path = "../consensus/aura/primitives", default-features = false } sr-std = { path = "../sr-std", default-features = false } sr-io = { path = "../sr-io", default-features = false } @@ -37,6 +38,7 @@ std = [ "sr-io/std", "srml-support/std", "substrate-primitives/std", + "substrate-inherents/std", "sr-primitives/std", "sr-version/std", "substrate-consensus-aura-primitives/std", diff --git a/substrate/core/test-runtime/src/lib.rs b/substrate/core/test-runtime/src/lib.rs index fd87782e38..e60025de31 100644 --- a/substrate/core/test-runtime/src/lib.rs +++ b/substrate/core/test-runtime/src/lib.rs @@ -24,6 +24,7 @@ extern crate serde; extern crate sr_std as rstd; extern crate parity_codec as codec; extern crate sr_primitives as runtime_primitives; +extern crate substrate_inherents as inherents; extern crate substrate_consensus_aura_primitives as consensus_aura; #[macro_use] @@ -59,7 +60,7 @@ use runtime_primitives::{ traits::{ BlindCheckable, BlakeTwo256, Block as BlockT, Extrinsic as ExtrinsicT, GetNodeBlockType, GetRuntimeBlockType - }, CheckInherentError + } }; use runtime_version::RuntimeVersion; pub use primitives::hash::H256; @@ -67,6 +68,7 @@ use primitives::{Ed25519AuthorityId, OpaqueMetadata}; #[cfg(any(feature = "std", test))] use runtime_version::NativeVersion; use consensus_aura::api as aura_api; +use inherents::{CheckInherentsResult, InherentData}; /// Test runtime version. pub const VERSION: RuntimeVersion = RuntimeVersion { @@ -238,7 +240,7 @@ impl_runtime_apis! { } } - impl block_builder_api::BlockBuilder for Runtime { + impl block_builder_api::BlockBuilder for Runtime { fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyResult { system::execute_transaction(extrinsic) } @@ -247,12 +249,12 @@ impl_runtime_apis! { system::finalise_block() } - fn inherent_extrinsics(_data: ()) -> Vec<::Extrinsic> { + fn inherent_extrinsics(_data: InherentData) -> Vec<::Extrinsic> { unimplemented!() } - fn check_inherents(_block: Block, _data: ()) -> Result<(), CheckInherentError> { - Ok(()) + fn check_inherents(_block: Block, _data: InherentData) -> CheckInherentsResult { + CheckInherentsResult::new() } fn random_seed() -> ::Hash { diff --git a/substrate/core/test-runtime/wasm/Cargo.lock b/substrate/core/test-runtime/wasm/Cargo.lock index d8aad89ba7..0c20da9c2b 100644 --- a/substrate/core/test-runtime/wasm/Cargo.lock +++ b/substrate/core/test-runtime/wasm/Cargo.lock @@ -542,12 +542,12 @@ dependencies = [ [[package]] name = "parity-codec-derive" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)", "quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.15.22 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -914,7 +914,7 @@ dependencies = [ "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -935,7 +935,7 @@ version = "0.1.0" dependencies = [ "impl-serde 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-primitives 0.1.0", @@ -947,7 +947,7 @@ name = "srml-metadata" version = "0.1.0" dependencies = [ "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-std 0.1.0", @@ -969,6 +969,7 @@ dependencies = [ "sr-std 0.1.0", "srml-metadata 0.1.0", "srml-support-procedural 0.1.0", + "substrate-inherents 0.1.0", ] [[package]] @@ -1032,6 +1033,7 @@ dependencies = [ "sr-version 0.1.0", "substrate-consensus-common 0.1.0", "substrate-executor 0.1.0", + "substrate-inherents 0.1.0", "substrate-keyring 0.1.0", "substrate-primitives 0.1.0", "substrate-state-machine 0.1.0", @@ -1060,10 +1062,11 @@ dependencies = [ "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "sr-primitives 0.1.0", "sr-version 0.1.0", + "substrate-inherents 0.1.0", "substrate-primitives 0.1.0", "tokio 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1090,6 +1093,17 @@ dependencies = [ "wasmi 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "substrate-inherents" +version = "0.1.0" +dependencies = [ + "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "sr-primitives 0.1.0", + "sr-std 0.1.0", +] + [[package]] name = "substrate-keyring" version = "0.1.0" @@ -1111,7 +1125,7 @@ dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "impl-serde 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "primitive-types 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", "ring 0.13.5 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1168,7 +1182,7 @@ dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -1178,6 +1192,7 @@ dependencies = [ "srml-support 0.1.0", "substrate-client 0.1.0", "substrate-consensus-aura-primitives 0.1.0", + "substrate-inherents 0.1.0", "substrate-keyring 0.1.0", "substrate-primitives 0.1.0", ] @@ -1200,16 +1215,6 @@ dependencies = [ "trie-root 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "syn" -version = "0.14.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "syn" version = "0.15.22" @@ -1625,7 +1630,7 @@ dependencies = [ "checksum owning_ref 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "49a4b8ea2179e6a2e27411d3bca09ca6dd630821cf6894c6c7c8467a8ee7ef13" "checksum parity-bytes 0.1.0 (git+https://github.com/paritytech/parity-common?rev=b0317f649ab2c665b7987b8475878fc4d2e1f81d)" = "" "checksum parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e7b6a1290fe78aa6bbb5f3338ecede3062687a98b9e40cd1dbcaa47261d44097" -"checksum parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ffa42c2cb493b60b12c75b26e8c94cb734af4df4d7f2cc229dc04c1953dac189" +"checksum parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2632f530f37c8b939c7c194636a82ecbe41ab115e74e88f947ad41e483bbf19" "checksum parity-wasm 0.31.3 (registry+https://github.com/rust-lang/crates.io-index)" = "511379a8194230c2395d2f5fa627a5a7e108a9f976656ce723ae68fca4097bfc" "checksum parking_lot 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)" = "f0802bff09003b291ba756dc7e79313e51cc31667e94afbe847def490424cde5" "checksum parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ab41b4aed082705d1056416ae4468b6ea99d52599ecf3169b00088d43113e337" @@ -1669,7 +1674,6 @@ dependencies = [ "checksum smallvec 0.6.7 (registry+https://github.com/rust-lang/crates.io-index)" = "b73ea3738b47563803ef814925e69be00799a8c07420be8b996f8e98fb2336db" "checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8" "checksum static_assertions 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "c19be23126415861cb3a23e501d34a708f7f9b2183c5252d690941c2e69199d5" -"checksum syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)" = "261ae9ecaa397c42b960649561949d69311f08eeaea86a65696e6e46517cf741" "checksum syn 0.15.22 (registry+https://github.com/rust-lang/crates.io-index)" = "ae8b29eb5210bc5cf63ed6149cbf9adfc82ac0be023d8735c176ee74a2db4da7" "checksum take_mut 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f764005d11ee5f36500a149ace24e00e3da98b0158b3e2d53a7495660d3f4d60" "checksum thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b" diff --git a/substrate/core/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.compact.wasm b/substrate/core/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.compact.wasm index 4cc222f456..204a87d33d 100644 Binary files a/substrate/core/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.compact.wasm and b/substrate/core/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.compact.wasm differ diff --git a/substrate/core/trie/src/node_header.rs b/substrate/core/trie/src/node_header.rs index e337661bfd..99b1241cab 100644 --- a/substrate/core/trie/src/node_header.rs +++ b/substrate/core/trie/src/node_header.rs @@ -34,10 +34,10 @@ impl Encode for NodeHeader { fn encode_to(&self, output: &mut T) { match self { NodeHeader::Null => output.push_byte(EMPTY_TRIE), - + NodeHeader::Branch(true) => output.push_byte(BRANCH_NODE_WITH_VALUE), NodeHeader::Branch(false) => output.push_byte(BRANCH_NODE_NO_VALUE), - + NodeHeader::Leaf(nibble_count) if *nibble_count < LEAF_NODE_THRESHOLD as usize => output.push_byte(LEAF_NODE_OFFSET + *nibble_count as u8), NodeHeader::Leaf(nibble_count) => { @@ -72,7 +72,6 @@ impl Decode for NodeHeader { BRANCH_NODE_NO_VALUE => NodeHeader::Branch(false), // 254 BRANCH_NODE_WITH_VALUE => NodeHeader::Branch(true), // 255 - _ => unreachable!(), }) } diff --git a/substrate/node/cli/Cargo.toml b/substrate/node/cli/Cargo.toml index f0d570a8d2..04fa67b4ad 100644 --- a/substrate/node/cli/Cargo.toml +++ b/substrate/node/cli/Cargo.toml @@ -16,6 +16,7 @@ slog = "^2" sr-io = { path = "../../core/sr-io" } substrate-client = { path = "../../core/client" } substrate-primitives = { path = "../../core/primitives" } +substrate-inherents = { path = "../../core/inherents" } node-runtime = { path = "../runtime" } node-primitives = { path = "../primitives" } hex-literal = "0.1" diff --git a/substrate/node/cli/src/chain_spec.rs b/substrate/node/cli/src/chain_spec.rs index 78e6d92341..825df6f8e0 100644 --- a/substrate/node/cli/src/chain_spec.rs +++ b/substrate/node/cli/src/chain_spec.rs @@ -318,6 +318,6 @@ mod tests { #[test] fn test_connectivity() { - service_test::connectivity::(integration_test_config()); + service_test::connectivity::(integration_test_config()); } } diff --git a/substrate/node/cli/src/lib.rs b/substrate/node/cli/src/lib.rs index 55ab1822ea..65c74bebd7 100644 --- a/substrate/node/cli/src/lib.rs +++ b/substrate/node/cli/src/lib.rs @@ -40,6 +40,7 @@ extern crate node_primitives; extern crate substrate_service; extern crate node_executor; extern crate substrate_keystore; +extern crate substrate_inherents as inherents; #[macro_use] extern crate log; diff --git a/substrate/node/cli/src/service.rs b/substrate/node/cli/src/service.rs index 38f34aedf5..dd2b14e74e 100644 --- a/substrate/node/cli/src/service.rs +++ b/substrate/node/cli/src/service.rs @@ -26,13 +26,14 @@ use consensus::{import_queue, start_aura, AuraImportQueue, SlotDuration, Nothing use grandpa; use node_executor; use primitives::ed25519::Pair; -use node_primitives::{Block, InherentData}; +use node_primitives::Block; use node_runtime::{GenesisConfig, RuntimeApi}; use substrate_service::{ FactoryFullConfiguration, LightComponents, FullComponents, FullBackend, - FullClient, LightClient, LightBackend, FullExecutor, LightExecutor, TaskExecutor + FullClient, LightClient, LightBackend, FullExecutor, LightExecutor, TaskExecutor, }; use transaction_pool::{self, txpool::{Pool as TransactionPool}}; +use inherents::InherentDataProviders; construct_simple_protocol! { /// Demo protocol attachment for substrate. @@ -45,12 +46,14 @@ pub struct NodeConfig { // FIXME: rather than putting this on the config, let's have an actual intermediate setup state // https://github.com/paritytech/substrate/issues/1134 pub grandpa_import_setup: Option<(Arc>, grandpa::LinkHalfForService)>, + inherent_data_providers: InherentDataProviders, } impl Default for NodeConfig where F: substrate_service::ServiceFactory { fn default() -> NodeConfig { NodeConfig { grandpa_import_setup: None, + inherent_data_providers: InherentDataProviders::new(), } } } @@ -91,7 +94,8 @@ construct_service_factory! { proposer, service.network(), service.on_exit(), - )); + service.config.custom.inherent_data_providers.clone(), + )?); info!("Running Grandpa session as Authority {}", key.public()); } @@ -99,7 +103,8 @@ construct_service_factory! { executor.spawn(grandpa::run_grandpa( grandpa::Config { local_key, - gossip_duration: Duration::new(4, 0), // FIXME: make this available through chainspec? + // FIXME: make this available through chainspec? + gossip_duration: Duration::new(4, 0), justification_period: 4096, name: Some(service.config.name.clone()) }, @@ -117,35 +122,38 @@ construct_service_factory! { Self::Block, grandpa::BlockImportForService, NothingExtra, - ::consensus::InherentProducingFn, > { |config: &mut FactoryFullConfiguration , client: Arc>| { let slot_duration = SlotDuration::get_or_compute(&*client)?; - let (block_import, link_half) = grandpa::block_import::<_, _, _, RuntimeApi, FullClient>(client.clone(), client)?; + + let (block_import, link_half) = + grandpa::block_import::<_, _, _, RuntimeApi, FullClient>( + client.clone(), client + )?; let block_import = Arc::new(block_import); config.custom.grandpa_import_setup = Some((block_import.clone(), link_half)); - Ok(import_queue( + import_queue( slot_duration, block_import, NothingExtra, - ::consensus::make_basic_inherent as _, - )) + config.custom.inherent_data_providers.clone(), + ).map_err(Into::into) }}, LightImportQueue = AuraImportQueue< Self::Block, LightClient, NothingExtra, - ::consensus::InherentProducingFn, > - { |ref mut config, client: Arc>| - Ok(import_queue( - SlotDuration::get_or_compute(&*client)?, - client, - NothingExtra, - ::consensus::make_basic_inherent as _, - )) + { |config: &FactoryFullConfiguration, client: Arc>| { + import_queue( + SlotDuration::get_or_compute(&*client)?, + client, + NothingExtra, + config.custom.inherent_data_providers.clone(), + ).map_err(Into::into) + } }, } } diff --git a/substrate/node/primitives/src/lib.rs b/substrate/node/primitives/src/lib.rs index 504ac5db95..a114c653b7 100644 --- a/substrate/node/primitives/src/lib.rs +++ b/substrate/node/primitives/src/lib.rs @@ -33,8 +33,6 @@ extern crate substrate_primitives as primitives; use runtime_primitives::generic; use runtime_primitives::{OpaqueExtrinsic, traits::BlakeTwo256}; -pub use runtime_primitives::BasicInherentData as InherentData; - /// An index to a block. pub type BlockNumber = u64; diff --git a/substrate/node/runtime/src/lib.rs b/substrate/node/runtime/src/lib.rs index ed8bae6968..d7599c2c7f 100644 --- a/substrate/node/runtime/src/lib.rs +++ b/substrate/node/runtime/src/lib.rs @@ -64,14 +64,14 @@ use node_primitives::{ }; use grandpa::fg_primitives::{self, ScheduledChange}; use client::{ - block_builder::api as block_builder_api, runtime_api as client_api + block_builder::api::{self as block_builder_api, InherentData, CheckInherentsResult}, + runtime_api as client_api, }; -use runtime_primitives::{ApplyResult, CheckInherentError, BasicInherentData}; +use runtime_primitives::ApplyResult; use runtime_primitives::transaction_validity::TransactionValidity; use runtime_primitives::generic; use runtime_primitives::traits::{ - Convert, BlakeTwo256, Block as BlockT, DigestFor, NumberFor, ProvideInherent, - StaticLookup + Convert, BlakeTwo256, Block as BlockT, DigestFor, NumberFor, Extrinsic, StaticLookup, }; use version::RuntimeVersion; use council::{motions as council_motions, voting as council_voting}; @@ -90,9 +90,6 @@ pub use balances::Call as BalancesCall; pub use runtime_primitives::{Permill, Perbill}; pub use srml_support::{StorageValue, RuntimeMetadata}; -const TIMESTAMP_SET_POSITION: u32 = 0; -const NOTE_OFFLINE_POSITION: u32 = 1; - /// Runtime version. pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("node"), @@ -146,7 +143,6 @@ impl balances::Trait for Runtime { } impl consensus::Trait for Runtime { - const NOTE_OFFLINE_POSITION: u32 = NOTE_OFFLINE_POSITION; type Log = Log; type SessionKey = SessionKey; @@ -156,7 +152,6 @@ impl consensus::Trait for Runtime { } impl timestamp::Trait for Runtime { - const TIMESTAMP_SET_POSITION: u32 = TIMESTAMP_SET_POSITION; type Moment = u64; type OnTimestampSet = Aura; } @@ -228,10 +223,10 @@ construct_runtime!( pub enum Runtime with Log(InternalLog: DigestItem) where Block = Block, NodeBlock = node_primitives::Block, - InherentData = BasicInherentData + UncheckedExtrinsic = UncheckedExtrinsic { System: system::{default, Log(ChangesTrieRoot)}, - Aura: aura::{Module}, + Aura: aura::{Module, Inherent(Timestamp)}, Timestamp: timestamp::{Module, Call, Storage, Config, Inherent}, Consensus: consensus::{Module, Call, Storage, Config, Log(AuthoritiesChange), Inherent}, Indices: indices, @@ -292,7 +287,7 @@ impl_runtime_apis! { } } - impl block_builder_api::BlockBuilder for Runtime { + impl block_builder_api::BlockBuilder for Runtime { fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyResult { Executive::apply_extrinsic(extrinsic) } @@ -301,46 +296,12 @@ impl_runtime_apis! { Executive::finalise_block() } - fn inherent_extrinsics(data: BasicInherentData) -> Vec<::Extrinsic> { - let mut inherent = Vec::new(); - - inherent.extend( - Timestamp::create_inherent_extrinsics(data.timestamp) - .into_iter() - .map(|v| (v.0, UncheckedExtrinsic::new_unsigned(Call::Timestamp(v.1)))) - ); - - inherent.extend( - Consensus::create_inherent_extrinsics(data.consensus) - .into_iter() - .map(|v| (v.0, UncheckedExtrinsic::new_unsigned(Call::Consensus(v.1)))) - ); - - inherent.as_mut_slice().sort_unstable_by_key(|v| v.0); - inherent.into_iter().map(|v| v.1).collect() + fn inherent_extrinsics(data: InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() } - fn check_inherents(block: Block, data: BasicInherentData) -> Result<(), CheckInherentError> { - let expected_slot = data.aura_expected_slot; - - // draw timestamp out from extrinsics. - let set_timestamp = block.extrinsics() - .get(TIMESTAMP_SET_POSITION as usize) - .and_then(|xt: &UncheckedExtrinsic| match xt.function { - Call::Timestamp(TimestampCall::set(ref t)) => Some(t.clone()), - _ => None, - }) - .ok_or_else(|| CheckInherentError::Other("No valid timestamp in block.".into()))?; - - // take the "worse" result of normal verification and the timestamp vs. seal - // check. - CheckInherentError::combine_results( - Runtime::check_inherents(block, data), - || { - Aura::verify_inherent(set_timestamp.into(), expected_slot) - .map_err(|s| CheckInherentError::Other(s.into())) - }, - ) + fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult { + data.check_extrinsics(&block) } fn random_seed() -> ::Hash { diff --git a/substrate/node/runtime/wasm/Cargo.lock b/substrate/node/runtime/wasm/Cargo.lock index 15e1a533cd..29511a0dcc 100644 --- a/substrate/node/runtime/wasm/Cargo.lock +++ b/substrate/node/runtime/wasm/Cargo.lock @@ -468,7 +468,7 @@ name = "node-primitives" version = "0.1.0" dependencies = [ "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-primitives 0.1.0", @@ -484,7 +484,7 @@ dependencies = [ "integer-sqrt 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "node-primitives 0.1.0", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", @@ -600,12 +600,12 @@ dependencies = [ [[package]] name = "parity-codec-derive" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)", "quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.15.22 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -995,7 +995,7 @@ dependencies = [ "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -1027,7 +1027,7 @@ version = "0.1.0" dependencies = [ "impl-serde 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-primitives 0.1.0", @@ -1040,7 +1040,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", @@ -1050,6 +1050,7 @@ dependencies = [ "srml-support 0.1.0", "srml-system 0.1.0", "srml-timestamp 0.1.0", + "substrate-inherents 0.1.0", "substrate-primitives 0.1.0", ] @@ -1059,7 +1060,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -1077,13 +1078,14 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", "sr-std 0.1.0", "srml-support 0.1.0", "srml-system 0.1.0", + "substrate-inherents 0.1.0", "substrate-primitives 0.1.0", ] @@ -1092,7 +1094,7 @@ name = "srml-contract" version = "0.1.0" dependencies = [ "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parity-wasm 0.31.3 (registry+https://github.com/rust-lang/crates.io-index)", "pwasm-utils 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1112,7 +1114,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -1131,7 +1133,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -1149,7 +1151,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", @@ -1164,7 +1166,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -1183,7 +1185,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -1200,7 +1202,7 @@ name = "srml-metadata" version = "0.1.0" dependencies = [ "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-std 0.1.0", @@ -1213,7 +1215,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -1232,7 +1234,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -1254,7 +1256,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", @@ -1280,6 +1282,7 @@ dependencies = [ "sr-std 0.1.0", "srml-metadata 0.1.0", "srml-support-procedural 0.1.0", + "substrate-inherents 0.1.0", ] [[package]] @@ -1318,7 +1321,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", @@ -1334,6 +1337,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", @@ -1341,6 +1345,7 @@ dependencies = [ "srml-consensus 0.1.0", "srml-support 0.1.0", "srml-system 0.1.0", + "substrate-inherents 0.1.0", "substrate-primitives 0.1.0", ] @@ -1350,7 +1355,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", @@ -1367,7 +1372,7 @@ version = "0.1.0" dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.81 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 0.1.0", "sr-primitives 0.1.0", @@ -1410,6 +1415,7 @@ dependencies = [ "sr-version 0.1.0", "substrate-consensus-common 0.1.0", "substrate-executor 0.1.0", + "substrate-inherents 0.1.0", "substrate-keyring 0.1.0", "substrate-primitives 0.1.0", "substrate-state-machine 0.1.0", @@ -1438,10 +1444,11 @@ dependencies = [ "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "sr-primitives 0.1.0", "sr-version 0.1.0", + "substrate-inherents 0.1.0", "substrate-primitives 0.1.0", "tokio 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1473,13 +1480,24 @@ name = "substrate-finality-grandpa-primitives" version = "0.1.0" dependencies = [ "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "sr-primitives 0.1.0", "sr-std 0.1.0", "substrate-client 0.1.0", "substrate-primitives 0.1.0", ] +[[package]] +name = "substrate-inherents" +version = "0.1.0" +dependencies = [ + "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "sr-primitives 0.1.0", + "sr-std 0.1.0", +] + [[package]] name = "substrate-keyring" version = "0.1.0" @@ -1501,7 +1519,7 @@ dependencies = [ "hex-literal 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "impl-serde 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "primitive-types 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", "ring 0.13.5 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1562,16 +1580,6 @@ dependencies = [ "trie-root 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "syn" -version = "0.14.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "syn" version = "0.15.22" @@ -1987,7 +1995,7 @@ dependencies = [ "checksum owning_ref 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "49a4b8ea2179e6a2e27411d3bca09ca6dd630821cf6894c6c7c8467a8ee7ef13" "checksum parity-bytes 0.1.0 (git+https://github.com/paritytech/parity-common?rev=b0317f649ab2c665b7987b8475878fc4d2e1f81d)" = "" "checksum parity-codec 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e7b6a1290fe78aa6bbb5f3338ecede3062687a98b9e40cd1dbcaa47261d44097" -"checksum parity-codec-derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ffa42c2cb493b60b12c75b26e8c94cb734af4df4d7f2cc229dc04c1953dac189" +"checksum parity-codec-derive 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2632f530f37c8b939c7c194636a82ecbe41ab115e74e88f947ad41e483bbf19" "checksum parity-wasm 0.31.3 (registry+https://github.com/rust-lang/crates.io-index)" = "511379a8194230c2395d2f5fa627a5a7e108a9f976656ce723ae68fca4097bfc" "checksum parking_lot 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)" = "f0802bff09003b291ba756dc7e79313e51cc31667e94afbe847def490424cde5" "checksum parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ab41b4aed082705d1056416ae4468b6ea99d52599ecf3169b00088d43113e337" @@ -2034,7 +2042,6 @@ dependencies = [ "checksum smallvec 0.6.7 (registry+https://github.com/rust-lang/crates.io-index)" = "b73ea3738b47563803ef814925e69be00799a8c07420be8b996f8e98fb2336db" "checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8" "checksum static_assertions 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "c19be23126415861cb3a23e501d34a708f7f9b2183c5252d690941c2e69199d5" -"checksum syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)" = "261ae9ecaa397c42b960649561949d69311f08eeaea86a65696e6e46517cf741" "checksum syn 0.15.22 (registry+https://github.com/rust-lang/crates.io-index)" = "ae8b29eb5210bc5cf63ed6149cbf9adfc82ac0be023d8735c176ee74a2db4da7" "checksum take_mut 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f764005d11ee5f36500a149ace24e00e3da98b0158b3e2d53a7495660d3f4d60" "checksum thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b" diff --git a/substrate/node/runtime/wasm/target/wasm32-unknown-unknown/release/node_runtime.compact.wasm b/substrate/node/runtime/wasm/target/wasm32-unknown-unknown/release/node_runtime.compact.wasm index e39414434f..f7ce6caae3 100644 Binary files a/substrate/node/runtime/wasm/target/wasm32-unknown-unknown/release/node_runtime.compact.wasm and b/substrate/node/runtime/wasm/target/wasm32-unknown-unknown/release/node_runtime.compact.wasm differ diff --git a/substrate/srml/aura/Cargo.toml b/substrate/srml/aura/Cargo.toml index 480548e9d7..056128ea36 100644 --- a/substrate/srml/aura/Cargo.toml +++ b/substrate/srml/aura/Cargo.toml @@ -9,6 +9,7 @@ parity-codec = { version = "2.2", default-features = false } parity-codec-derive = { version = "2.1", default-features = false } serde = { version = "1.0", default-features = false } substrate-primitives = { path = "../../core/primitives", default-features = false } +substrate-inherents = { path = "../../core/inherents", default-features = false } sr-std = { path = "../../core/sr-std", default-features = false } sr-io = { path = "../../core/sr-io", default-features = false } sr-primitives = { path = "../../core/sr-primitives", default-features = false } @@ -37,4 +38,5 @@ std = [ "srml-consensus/std", "srml-timestamp/std", "srml-staking/std", + "substrate-inherents/std", ] diff --git a/substrate/srml/aura/src/lib.rs b/substrate/srml/aura/src/lib.rs index b0bc50d69b..273c3b27c5 100644 --- a/substrate/srml/aura/src/lib.rs +++ b/substrate/srml/aura/src/lib.rs @@ -18,8 +18,6 @@ #![cfg_attr(not(feature = "std"), no_std)] -#[allow(unused_imports)] -#[macro_use] extern crate sr_std as rstd; #[macro_use] @@ -31,9 +29,10 @@ extern crate srml_support as runtime_support; extern crate sr_primitives as primitives; extern crate srml_system as system; -extern crate srml_timestamp as timestamp; +pub extern crate srml_timestamp as timestamp; extern crate srml_staking as staking; extern crate substrate_primitives; +extern crate substrate_inherents as inherents; #[cfg(test)] extern crate srml_consensus as consensus; @@ -48,15 +47,93 @@ extern crate lazy_static; #[cfg(test)] extern crate parking_lot; -use rstd::prelude::*; +use rstd::{result, prelude::*}; use runtime_support::storage::StorageValue; -use runtime_support::dispatch::Result; use primitives::traits::{As, Zero}; use timestamp::OnTimestampSet; +#[cfg(feature = "std")] +use timestamp::TimestampInherentData; +#[cfg(feature = "std")] +use parity_codec::Decode; +use inherents::{RuntimeString, InherentIdentifier, InherentData, ProvideInherent, MakeFatalError}; +#[cfg(feature = "std")] +use inherents::{InherentDataProviders, ProvideInherentData}; mod mock; mod tests; +/// The aura inherent identifier. +pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"auraslot"; + +/// The type of the aura inherent. +pub type InherentType = u64; + +/// Auxiliary trait to extract aura inherent data. +pub trait AuraInherentData { + /// Get aura inherent data. + fn aura_inherent_data(&self) -> result::Result; + /// Replace aura inherent data. + fn aura_replace_inherent_data(&mut self, new: InherentType); +} + +impl AuraInherentData for InherentData { + fn aura_inherent_data(&self) -> result::Result { + self.get_data(&INHERENT_IDENTIFIER) + .and_then(|r| r.ok_or_else(|| "Aura inherent data not found".into())) + } + + fn aura_replace_inherent_data(&mut self, new: InherentType) { + self.replace_data(INHERENT_IDENTIFIER, &new); + } +} + +/// Provides the slot duration inherent data for `Aura`. +#[cfg(feature = "std")] +pub struct InherentDataProvider { + slot_duration: u64, +} + +#[cfg(feature = "std")] +impl InherentDataProvider { + pub fn new(slot_duration: u64) -> Self { + Self { + slot_duration + } + } +} + +#[cfg(feature = "std")] +impl ProvideInherentData for InherentDataProvider { + fn on_register( + &self, + providers: &InherentDataProviders, + ) -> result::Result<(), RuntimeString> { + if !providers.has_provider(×tamp::INHERENT_IDENTIFIER) { + // Add the timestamp inherent data provider, as we require it. + providers.register_provider(timestamp::InherentDataProvider) + } else { + Ok(()) + } + } + + fn inherent_identifier(&self) -> &'static inherents::InherentIdentifier { + &INHERENT_IDENTIFIER + } + + fn provide_inherent_data( + &self, + inherent_data: &mut InherentData, + ) -> result::Result<(), RuntimeString> { + let timestamp = inherent_data.timestamp_inherent_data()?; + let slot_num = timestamp / self.slot_duration; + inherent_data.put_data(INHERENT_IDENTIFIER, &slot_num) + } + + fn error_to_string(&self, error: &[u8]) -> Option { + RuntimeString::decode(&mut &error[..]).map(Into::into) + } +} + /// Something which can handle Aura consensus reports. pub trait HandleReport { fn handle_report(report: AuraReport); @@ -133,20 +210,6 @@ impl Module { >::block_period().as_().saturating_mul(2) } - /// Verify an inherent slot that is used in a block seal against a timestamp - /// extracted from the block. - // TODO: ensure `ProvideInherent` can deal with dependencies like this. - // https://github.com/paritytech/substrate/issues/1228 - pub fn verify_inherent(timestamp: T::Moment, seal_slot: u64) -> Result { - let timestamp_based_slot = timestamp.as_() / Self::slot_duration(); - - if timestamp_based_slot == seal_slot { - Ok(()) - } else { - Err("timestamp set in block doesn't match slot in seal".into()) - } - } - fn on_timestamp_set(now: T::Moment, slot_duration: T::Moment) { let last = Self::last(); ::LastTimestamp::put(now.clone()); @@ -197,3 +260,30 @@ impl HandleReport for StakingSlasher { ); } } + +impl ProvideInherent for Module { + type Call = timestamp::Call; + type Error = MakeFatalError; + const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER; + + fn create_inherent(_: &InherentData) -> Option { + None + } + + fn check_inherent(call: &Self::Call, data: &InherentData) -> result::Result<(), Self::Error> { + let timestamp = match call { + timestamp::Call::set(ref timestamp) => timestamp.clone(), + _ => return Ok(()), + }; + + let timestamp_based_slot = timestamp.as_() / Self::slot_duration(); + + let seal_slot = data.aura_inherent_data()?; + + if timestamp_based_slot == seal_slot { + Ok(()) + } else { + Err(RuntimeString::from("timestamp set in block doesn't match slot in seal").into()) + } + } +} diff --git a/substrate/srml/aura/src/mock.rs b/substrate/srml/aura/src/mock.rs index 6ff33e6c51..16d2b81280 100644 --- a/substrate/srml/aura/src/mock.rs +++ b/substrate/srml/aura/src/mock.rs @@ -32,7 +32,6 @@ impl_outer_origin!{ pub struct Test; impl consensus::Trait for Test { - const NOTE_OFFLINE_POSITION: u32 = 1; type Log = DigestItem; type SessionKey = UintAuthorityId; type InherentOfflineReport = (); @@ -53,8 +52,6 @@ impl system::Trait for Test { } impl timestamp::Trait for Test { - const TIMESTAMP_SET_POSITION: u32 = 0; - type Moment = u64; type OnTimestampSet = Aura; } diff --git a/substrate/srml/consensus/Cargo.toml b/substrate/srml/consensus/Cargo.toml index 9bc03d85ee..278482f816 100644 --- a/substrate/srml/consensus/Cargo.toml +++ b/substrate/srml/consensus/Cargo.toml @@ -9,6 +9,7 @@ serde = { version = "1.0", default-features = false } parity-codec = { version = "2.2", default-features = false } parity-codec-derive = { version = "2.1", default-features = false } substrate-primitives = { path = "../../core/primitives", default-features = false } +substrate-inherents = { path = "../../core/inherents", default-features = false } sr-std = { path = "../../core/sr-std", default-features = false } sr-io = { path = "../../core/sr-io", default-features = false } sr-primitives = { path = "../../core/sr-primitives", default-features = false } @@ -26,4 +27,5 @@ std = [ "srml-support/std", "sr-primitives/std", "srml-system/std", + "substrate-inherents/std", ] diff --git a/substrate/srml/consensus/src/lib.rs b/substrate/srml/consensus/src/lib.rs index e8ef08e4b9..54da8a5de0 100644 --- a/substrate/srml/consensus/src/lib.rs +++ b/substrate/srml/consensus/src/lib.rs @@ -18,8 +18,6 @@ #![cfg_attr(not(feature = "std"), no_std)] -#[allow(unused_imports)] -#[macro_use] extern crate sr_std as rstd; #[macro_use] @@ -37,18 +35,19 @@ extern crate substrate_primitives; #[cfg(test)] extern crate sr_io as runtime_io; +extern crate substrate_inherents as inherents; + use rstd::prelude::*; -use rstd::result; use parity_codec::Encode; use runtime_support::{storage, Parameter}; use runtime_support::storage::StorageValue; use runtime_support::storage::unhashed::StorageVec; -use primitives::CheckInherentError; -use primitives::traits::{ - MaybeSerializeDebug, Member, ProvideInherent, Block as BlockT -}; +use primitives::traits::{MaybeSerializeDebug, Member}; use substrate_primitives::storage::well_known_keys; use system::{ensure_signed, ensure_inherent}; +use inherents::{ + ProvideInherent, InherentData, InherentIdentifier, RuntimeString, MakeFatalError +}; #[cfg(any(feature = "std", test))] use substrate_primitives::Ed25519AuthorityId; @@ -56,6 +55,12 @@ use substrate_primitives::Ed25519AuthorityId; mod mock; mod tests; +/// The identifier for consensus inherents. +pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"offlrep0"; + +/// The error type used by this inherent. +pub type InherentError = RuntimeString; + struct AuthorityStorageVec(rstd::marker::PhantomData); impl StorageVec for AuthorityStorageVec { type Item = S; @@ -158,9 +163,6 @@ impl From> for primitives::testing::DigestItem where N: Into> + Into>; @@ -206,12 +208,6 @@ decl_module! { fn note_offline(origin, offline: ::Inherent) { ensure_inherent(origin)?; - assert!( - >::extrinsic_index() == Some(T::NOTE_OFFLINE_POSITION), - "note_offline extrinsic must be at position {} in the block", - T::NOTE_OFFLINE_POSITION - ); - T::InherentOfflineReport::handle_report(offline); } @@ -292,34 +288,38 @@ impl Module { } impl ProvideInherent for Module { - type Inherent = ::Inherent; type Call = Call; + type Error = MakeFatalError; + const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER; - fn create_inherent_extrinsics(data: Self::Inherent) -> Vec<(u32, Self::Call)> { - if ::is_empty(&data) { - vec![] + fn create_inherent(data: &InherentData) -> Option { + if let Ok(Some(data)) = + data.get_data::<::Inherent>( + &INHERENT_IDENTIFIER + ) + { + if ::is_empty(&data) { + None + } else { + Some(Call::note_offline(data)) + } } else { - vec![(T::NOTE_OFFLINE_POSITION, Call::note_offline(data))] + None } } - fn check_inherent Option<&Self::Call>>( - block: &Block, expected: Self::Inherent, extract_function: &F - ) -> result::Result<(), CheckInherentError> { - let noted_offline = block - .extrinsics() - .get(T::NOTE_OFFLINE_POSITION as usize) - .and_then(|xt| match extract_function(&xt) { - Some(Call::note_offline(ref x)) => Some(x), - _ => None, - }); + fn check_inherent(call: &Self::Call, data: &InherentData) -> Result<(), Self::Error> { + let offline = match call { + Call::note_offline(ref offline) => offline, + _ => return Ok(()), + }; - // REVIEW: perhaps we should be passing a `None` to check_inherent. - if let Some(noted_offline) = noted_offline { - ::check_inherent(¬ed_offline, &expected) - .map_err(|e| CheckInherentError::Other(e.into()))?; - } + let expected = data + .get_data::<::Inherent>(&INHERENT_IDENTIFIER)? + .ok_or(RuntimeString::from("No `offline_report` found in the inherent data!"))?; - Ok(()) + ::check_inherent( + &offline, &expected + ).map_err(|e| RuntimeString::from(e).into()) } } diff --git a/substrate/srml/consensus/src/mock.rs b/substrate/srml/consensus/src/mock.rs index 9bf81cd327..454aa61c41 100644 --- a/substrate/srml/consensus/src/mock.rs +++ b/substrate/srml/consensus/src/mock.rs @@ -31,7 +31,6 @@ impl_outer_origin!{ #[derive(Clone, PartialEq, Eq, Debug)] pub struct Test; impl Trait for Test { - const NOTE_OFFLINE_POSITION: u32 = 1; type Log = DigestItem; type SessionKey = UintAuthorityId; type InherentOfflineReport = ::InstantFinalityReportVec<()>; diff --git a/substrate/srml/consensus/src/tests.rs b/substrate/srml/consensus/src/tests.rs index 9dc65136fb..53d5732173 100644 --- a/substrate/srml/consensus/src/tests.rs +++ b/substrate/srml/consensus/src/tests.rs @@ -18,9 +18,10 @@ #![cfg(test)] -use primitives::{generic, testing::{self, UintAuthorityId}, traits::{OnFinalise, ProvideInherent}}; +use primitives::{generic, testing::{self, UintAuthorityId}, traits::OnFinalise}; use runtime_io::with_externalities; use mock::{Consensus, System, new_test_ext}; +use inherents::{InherentData, ProvideInherent}; #[test] fn authorities_change_logged() { @@ -31,7 +32,13 @@ fn authorities_change_logged() { let header = System::finalise(); assert_eq!(header.digest, testing::Digest { logs: vec![ - generic::DigestItem::AuthoritiesChange(vec![UintAuthorityId(4).into(), UintAuthorityId(5).into(), UintAuthorityId(6).into()]), + generic::DigestItem::AuthoritiesChange( + vec![ + UintAuthorityId(4).into(), + UintAuthorityId(5).into(), + UintAuthorityId(6).into() + ] + ), ], }); }); @@ -67,7 +74,12 @@ fn authorities_change_is_not_logged_when_changed_back_to_original() { fn offline_report_can_be_excluded() { with_externalities(&mut new_test_ext(vec![1, 2, 3]), || { System::initialise(&1, &Default::default(), &Default::default()); - assert!(Consensus::create_inherent_extrinsics(Vec::new()).is_empty()); - assert_eq!(Consensus::create_inherent_extrinsics(vec![0]).len(), 1); + assert!(Consensus::create_inherent(&InherentData::new()).is_none()); + + let offline_report: Vec = vec![0]; + let mut data = InherentData::new(); + data.put_data(super::INHERENT_IDENTIFIER, &offline_report).unwrap(); + + assert!(Consensus::create_inherent(&data).is_some()); }); } diff --git a/substrate/srml/session/src/lib.rs b/substrate/srml/session/src/lib.rs index bc316938c0..b758325cea 100644 --- a/substrate/srml/session/src/lib.rs +++ b/substrate/srml/session/src/lib.rs @@ -114,7 +114,6 @@ decl_event!( decl_storage! { trait Store for Module as Session { - /// The current set of validators. pub Validators get(validators) config(): Vec; /// Current length of the session. @@ -246,7 +245,6 @@ mod tests { #[derive(Clone, Eq, PartialEq)] pub struct Test; impl consensus::Trait for Test { - const NOTE_OFFLINE_POSITION: u32 = 1; type Log = DigestItem; type SessionKey = UintAuthorityId; type InherentOfflineReport = (); @@ -265,7 +263,6 @@ mod tests { type Log = DigestItem; } impl timestamp::Trait for Test { - const TIMESTAMP_SET_POSITION: u32 = 0; type Moment = u64; type OnTimestampSet = (); } diff --git a/substrate/srml/staking/src/mock.rs b/substrate/srml/staking/src/mock.rs index 752922da03..68145a7a70 100644 --- a/substrate/srml/staking/src/mock.rs +++ b/substrate/srml/staking/src/mock.rs @@ -32,7 +32,6 @@ impl_outer_origin!{ #[derive(Clone, PartialEq, Eq, Debug)] pub struct Test; impl consensus::Trait for Test { - const NOTE_OFFLINE_POSITION: u32 = 1; type Log = DigestItem; type SessionKey = UintAuthorityId; type InherentOfflineReport = (); @@ -63,7 +62,6 @@ impl session::Trait for Test { type Event = (); } impl timestamp::Trait for Test { - const TIMESTAMP_SET_POSITION: u32 = 0; type Moment = u64; type OnTimestampSet = (); } diff --git a/substrate/srml/support/Cargo.toml b/substrate/srml/support/Cargo.toml index 6a232215b3..9210d407d6 100644 --- a/substrate/srml/support/Cargo.toml +++ b/substrate/srml/support/Cargo.toml @@ -12,6 +12,7 @@ srml-metadata = { path = "../metadata", default-features = false } sr-std = { path = "../../core/sr-std", default-features = false } sr-io = { path = "../../core/sr-io", default-features = false } sr-primitives = { path = "../../core/sr-primitives", default-features = false } +substrate-inherents = { path = "../../core/inherents", default-features = false } srml-support-procedural = { path = "./procedural" } mashup = "0.1.7" once_cell = { version = "0.1.6", default-features = false, optional = true } @@ -32,6 +33,7 @@ std = [ "sr-std/std", "sr-primitives/std", "srml-metadata/std", + "substrate-inherents/std", ] nightly = [] strict = [] diff --git a/substrate/srml/support/src/inherent.rs b/substrate/srml/support/src/inherent.rs index 925ba91cec..9c99ba7281 100644 --- a/substrate/srml/support/src/inherent.rs +++ b/substrate/srml/support/src/inherent.rs @@ -15,11 +15,11 @@ // along with Substrate. If not, see . #[doc(hidden)] -pub use rstd::{cmp, result::Result, vec::Vec}; +pub use rstd::vec::Vec; #[doc(hidden)] -pub use runtime_primitives::{ - traits::{ProvideInherent, Block as BlockT}, CheckInherentError -}; +pub use runtime_primitives::traits::Block as BlockT; +#[doc(hidden)] +pub use inherents::{InherentData, ProvideInherent, CheckInherentsResult, IsFatalError}; /// Implement the outer inherent. @@ -30,54 +30,72 @@ pub use runtime_primitives::{ /// ```nocompile /// impl_outer_inherent! { /// pub struct InherentData where Block = Block, UncheckedExtrinsic = UncheckedExtrinsic { -/// timestamp: Timestamp export Error as TimestampInherentError, +/// timestamp: Timestamp, /// consensus: Consensus, +/// /// Aura module using the `Timestamp` call. +/// aura: Timestamp, /// } /// } /// ``` -/// -/// Additional parameters after `UncheckedExtrinsic` are `Error` and `Call`. #[macro_export] macro_rules! impl_outer_inherent { ( - for $runtime:ident, - Block = $block:ident, - InherentData = $inherent:ty + impl Inherents where Block = $block:ident, UncheckedExtrinsic = $uncheckedextrinsic:ident { - $( $module:ident: $module_ty:ident,)* + $( $module:ident: $call:ident, )* } ) => { - impl $runtime { - fn check_inherents( - block: $block, - data: $inherent - ) -> $crate::inherent::Result<(), $crate::inherent::CheckInherentError> { - use $crate::inherent::CheckInherentError; + trait InherentDataExt { + fn create_extrinsics(&self) -> + $crate::inherent::Vec<<$block as $crate::inherent::BlockT>::Extrinsic>; + fn check_extrinsics(&self, block: &$block) -> $crate::inherent::CheckInherentsResult; + } + + impl InherentDataExt for $crate::inherent::InherentData { + fn create_extrinsics(&self) -> + $crate::inherent::Vec<<$block as $crate::inherent::BlockT>::Extrinsic> { + use $crate::inherent::ProvideInherent; + + let mut inherents = Vec::new(); - let mut max_valid_after = None; $( - let res = <$module_ty as $crate::inherent::ProvideInherent>::check_inherent( - &block, - data.$module, - &|xt| match xt.function { - Call::$module_ty(ref data) => Some(data), - _ => None, - }, - ); - - match res { - Err(CheckInherentError::ValidAtTimestamp(t)) => - max_valid_after = $crate::inherent::cmp::max(max_valid_after, Some(t)), - res => res? + if let Some(inherent) = $module::create_inherent(self) { + inherents.push($uncheckedextrinsic::new_unsigned( + Call::$call(inherent)) + ); } )* - // once everything else has checked out, take the maximum of - // all things which are timestamp-restricted. - match max_valid_after { - Some(t) => Err(CheckInherentError::ValidAtTimestamp(t)), - None => Ok(()) + inherents + } + + fn check_extrinsics(&self, block: &$block) -> $crate::inherent::CheckInherentsResult { + use $crate::inherent::{ProvideInherent, IsFatalError}; + + let mut result = $crate::inherent::CheckInherentsResult::new(); + for xt in block.extrinsics() { + if xt.is_signed().unwrap_or(false) { + break; + } + + $( + match xt.function { + Call::$call(ref call) => { + if let Err(e) = $module::check_inherent(call, self) { + result.put_error( + $module::INHERENT_IDENTIFIER, &e + ).expect("There is only one fatal error; qed"); + if e.is_fatal_error() { + return result; + } + } + } + _ => {}, + } + )* } + + result } } }; diff --git a/substrate/srml/support/src/lib.rs b/substrate/srml/support/src/lib.rs index ec285590d2..5ad2985839 100644 --- a/substrate/srml/support/src/lib.rs +++ b/substrate/srml/support/src/lib.rs @@ -32,6 +32,7 @@ extern crate srml_metadata; extern crate mashup; #[cfg_attr(test, macro_use)] extern crate srml_support_procedural; +extern crate substrate_inherents as inherents; #[cfg(test)] #[macro_use] diff --git a/substrate/srml/support/src/runtime.rs b/substrate/srml/support/src/runtime.rs index d658de3426..f215e18a83 100644 --- a/substrate/srml/support/src/runtime.rs +++ b/substrate/srml/support/src/runtime.rs @@ -20,11 +20,11 @@ //! mostly for to combine data types and metadata of the included modules. /// Construct a runtime, with the given name and the given modules. -/// +/// /// The parameters here are specific types for Block, NodeBlock and InherentData /// (TODO: describe the difference between Block and NodeBlock) /// and the modules that are used by the runtime. -/// +/// /// # Example: /// /// ```nocompile @@ -32,7 +32,7 @@ /// pub enum Runtime with Log(interalIdent: DigestItem) where /// Block = Block, /// NodeBlock = runtime::Block, -/// InherentData = BasicInherentData +/// UncheckedExtrinsic = UncheckedExtrinsic /// { /// System: system, /// Test: test::{default, Log(Test)}, @@ -44,10 +44,10 @@ /// The module `System: system` will expand to `System: system::{Module, Call, Storage, Event, Config}`. /// The identifier `System` is the name of the module and the lower case identifier `system` is the /// name of the Rust module/crate for this Substrate module. -/// +/// /// The module `Test: test::{default, Log(Test)}` will expand to /// `Test: test::{Module, Call, Storage, Event, Config, Log(Test)}`. -/// +/// /// The module `Test2: test_with_long_module::{Module}` will expand to /// `Test2: test_with_long_module::{Module}`. /// @@ -59,9 +59,9 @@ /// - `Origin` or `Origin` (if the origin is generic) /// - `Config` or `Config` (if the config is generic) /// - `Log( $(IDENT),* )` -/// -/// The -/// +/// - `Inherent $( (CALL) )*` - If the module provides/can check inherents. The optional parameter +/// is for modules that use a `Call` from a different module as +/// inherent. #[macro_export] macro_rules! construct_runtime { @@ -73,7 +73,7 @@ macro_rules! construct_runtime { where Block = $block:ident, NodeBlock = $node_block:ty, - InherentData = $inherent:ty + UncheckedExtrinsic = $uncheckedextrinsic:ident { $( $rest:tt )* } @@ -82,7 +82,7 @@ macro_rules! construct_runtime { $runtime; $block; $node_block; - $inherent; + $uncheckedextrinsic; $log_internal < $( $log_genarg ),* >; ; $( $rest )* @@ -92,7 +92,7 @@ macro_rules! construct_runtime { $runtime:ident; $block:ident; $node_block:ty; - $inherent:ty; + $uncheckedextrinsic:ident; $log_internal:ident <$( $log_genarg:ty ),+>; $( $expanded_name:ident: $expanded_module:ident::{ @@ -120,7 +120,7 @@ macro_rules! construct_runtime { $runtime; $block; $node_block; - $inherent; + $uncheckedextrinsic; $log_internal < $( $log_genarg ),* >; $( $expanded_name: $expanded_module::{ @@ -148,7 +148,7 @@ macro_rules! construct_runtime { $runtime:ident; $block:ident; $node_block:ty; - $inherent:ty; + $uncheckedextrinsic:ident; $log_internal:ident <$( $log_genarg:ty ),+>; $( $expanded_name:ident: $expanded_module:ident::{ @@ -183,7 +183,7 @@ macro_rules! construct_runtime { $runtime; $block; $node_block; - $inherent; + $uncheckedextrinsic; $log_internal < $( $log_genarg ),* >; $( $expanded_name: $expanded_module::{ @@ -217,7 +217,7 @@ macro_rules! construct_runtime { $runtime:ident; $block:ident; $node_block:ty; - $inherent:ty; + $uncheckedextrinsic:ident; $log_internal:ident <$( $log_genarg:ty ),+>; $( $expanded_name:ident: $expanded_module:ident::{ @@ -251,7 +251,7 @@ macro_rules! construct_runtime { $runtime; $block; $node_block; - $inherent; + $uncheckedextrinsic; $log_internal < $( $log_genarg ),* >; $( $expanded_name: $expanded_module::{ @@ -287,7 +287,7 @@ macro_rules! construct_runtime { $runtime:ident; $block:ident; $node_block:ty; - $inherent:ty; + $uncheckedextrinsic:ident; $log_internal:ident <$( $log_genarg:ty ),+>; $( $name:ident: $module:ident::{ @@ -299,9 +299,9 @@ macro_rules! construct_runtime { } ),*; ) => { - // This generates a substrate_generate_ident_name macro that will substitute + // This generates a substrate_generate_ident_name macro that will substitute // "config-ident FooModule" => FooModuleConfig for every module included in the - // runtime. + // runtime. mashup! { $( substrate_generate_ident_name["config-ident" $name] = $name Config; @@ -370,19 +370,19 @@ macro_rules! construct_runtime { __decl_outer_inherent!( $runtime; $block; - $inherent; + $uncheckedextrinsic; ; $( - $name: $module::{ $( $modules $( <$modules_generic> )* ),* } + $name: $module::{ $( $modules $( ( $( $modules_args ),* ) )* ),* } ),*; ); } } /// A macro that generates a "__decl" private macro that transforms parts of the runtime definition -/// to feed them into a public "impl" macro which accepts the format +/// to feed them into a public "impl" macro which accepts the format /// "pub enum $name for $runtime where system = $system". -/// +/// /// Used to define Event and Origin associated types. #[macro_export] #[doc(hidden)] @@ -1109,23 +1109,23 @@ macro_rules! __decl_outer_inherent { ( $runtime:ident; $block:ident; - $inherent:ty; - $( $parsed_modules:ident :: $parsed_name:ident ),*; + $uncheckedextrinsic:ident; + $( $parsed_name:ident :: $parsed_call:ident ),*; $name:ident: $module:ident::{ - Inherent $(, $modules:ident $( <$modules_generic:ident> )* )* + Inherent $(, $modules:ident $( ( $( $modules_call:ident )* ) )* )* } $(, $rest_name:ident : $rest_module:ident::{ - $( $rest_modules:ident $( <$rest_modules_generic:ident> )* ),* + $( $rest_modules:ident $( ( $( $rest_call:ident )* ) )* ),* })*; ) => { __decl_outer_inherent!( $runtime; $block; - $inherent; - $( $parsed_modules :: $parsed_name, )* $module::$name; + $uncheckedextrinsic; + $( $parsed_name :: $parsed_call, )* $name::$name; $( $rest_name: $rest_module::{ - $( $rest_modules $( <$rest_modules_generic> )* ),* + $( $rest_modules $( ( $( $rest_call )* ) )* ),* } ),*; ); @@ -1133,24 +1133,49 @@ macro_rules! __decl_outer_inherent { ( $runtime:ident; $block:ident; - $inherent:ty; - $( $parsed_modules:ident :: $parsed_name:ident ),*; + $uncheckedextrinsic:ident; + $( $parsed_name:ident :: $parsed_call:ident ),*; $name:ident: $module:ident::{ - $ingore:ident $( <$ignor:ident> )* $(, $modules:ident $( <$modules_generic:ident> )* )* + Inherent ( $call:ident ) $(, $modules:ident $( ( $( $modules_call:ident )* ) )* )* } $(, $rest_name:ident : $rest_module:ident::{ - $( $rest_modules:ident $( <$rest_modules_generic:ident> )* ),* + $( $rest_modules:ident $( ( $( $rest_call:ident )* ) )* ),* })*; ) => { __decl_outer_inherent!( $runtime; $block; - $inherent; - $( $parsed_modules :: $parsed_name ),*; - $name: $module::{ $( $modules $( <$modules_generic> )* ),* } + $uncheckedextrinsic; + $( $parsed_name :: $parsed_call, )* $name::$call; + $( + $rest_name: $rest_module::{ + $( $rest_modules $( ( $( $rest_call )* ) )* ),* + } + ),*; + ); + }; + ( + $runtime:ident; + $block:ident; + $uncheckedextrinsic:ident; + $( $parsed_name:ident :: $parsed_call:ident ),*; + $name:ident: $module:ident::{ + $ingore:ident $( ( $( $ignor:ident )* ) )* + $(, $modules:ident $( ( $( $modules_call:ident )* ) )* )* + } + $(, $rest_name:ident : $rest_module:ident::{ + $( $rest_modules:ident $( ( $( $rest_call:ident )* ) )* ),* + })*; + ) => { + __decl_outer_inherent!( + $runtime; + $block; + $uncheckedextrinsic; + $( $parsed_name :: $parsed_call ),*; + $name: $module::{ $( $modules $( ( $( $modules_call )* ) )* ),* } $( , $rest_name: $rest_module::{ - $( $rest_modules $( <$rest_modules_generic> )* ),* + $( $rest_modules $( ( $( $rest_call )* ) )* ),* } )*; ); @@ -1158,21 +1183,21 @@ macro_rules! __decl_outer_inherent { ( $runtime:ident; $block:ident; - $inherent:ty; - $( $parsed_modules:ident :: $parsed_name:ident ),*; + $uncheckedextrinsic:ident; + $( $parsed_name:ident :: $parsed_call:ident ),*; $name:ident: $module:ident::{} $(, $rest_name:ident : $rest_module:ident::{ - $( $rest_modules:ident $( <$rest_modules_generic:ident> )* ),* + $( $rest_modules:ident $( ( $( $rest_call:ident )* ) )* ),* })*; ) => { __decl_outer_inherent!( $runtime; $block; - $inherent; - $( $parsed_modules :: $parsed_name ),*; + $uncheckedextrinsic; + $( $parsed_name :: $parsed_call ),*; $( $rest_name: $rest_module::{ - $( $rest_modules $( <$rest_modules_generic> )* ),* + $( $rest_modules $( ( $( $rest_call )* ) )* ),* } ),*; ); @@ -1180,15 +1205,13 @@ macro_rules! __decl_outer_inherent { ( $runtime:ident; $block:ident; - $inherent:ty; - $( $parsed_modules:ident :: $parsed_name:ident ),*; + $uncheckedextrinsic:ident; + $( $parsed_name:ident :: $parsed_call:ident ),*; ; ) => { impl_outer_inherent!( - for $runtime, - Block = $block, - InherentData = $inherent { - $($parsed_modules : $parsed_name,)* + impl Inherents where Block = $block, UncheckedExtrinsic = $uncheckedextrinsic { + $( $parsed_name : $parsed_call, )* } ); }; diff --git a/substrate/srml/timestamp/Cargo.toml b/substrate/srml/timestamp/Cargo.toml index 4e3ca526ad..3761719a52 100644 --- a/substrate/srml/timestamp/Cargo.toml +++ b/substrate/srml/timestamp/Cargo.toml @@ -7,10 +7,12 @@ authors = ["Parity Technologies "] hex-literal = "0.1.0" serde = { version = "1.0", default-features = false } parity-codec = { version = "2.2", default-features = false } +parity-codec-derive = { version = "2.2", default-features = false } substrate-primitives = { path = "../../core/primitives", default-features = false } sr-std = { path = "../../core/sr-std", default-features = false } sr-io = { path = "../../core/sr-io", default-features = false } sr-primitives = { path = "../../core/sr-primitives", default-features = false } +substrate-inherents = { path = "../../core/inherents", default-features = false } srml-support = { path = "../support", default-features = false } srml-system = { path = "../system", default-features = false } srml-consensus = { path = "../consensus", default-features = false } @@ -28,6 +30,8 @@ std = [ "srml-consensus/std", "serde/std", "parity-codec/std", + "parity-codec-derive/std", "substrate-primitives/std", "srml-system/std", + "substrate-inherents/std", ] diff --git a/substrate/srml/timestamp/src/lib.rs b/substrate/srml/timestamp/src/lib.rs index 8f78aabefe..6b401b8446 100644 --- a/substrate/srml/timestamp/src/lib.rs +++ b/substrate/srml/timestamp/src/lib.rs @@ -32,7 +32,6 @@ #![cfg_attr(not(feature = "std"), no_std)] -#[cfg_attr(not(feature = "std"), macro_use)] extern crate sr_std as rstd; #[macro_use] @@ -46,15 +45,95 @@ extern crate sr_primitives as runtime_primitives; extern crate srml_system as system; extern crate srml_consensus as consensus; extern crate parity_codec as codec; +#[macro_use] +extern crate parity_codec_derive; +extern crate substrate_inherents as inherents; use runtime_support::{StorageValue, Parameter}; -use runtime_primitives::CheckInherentError; -use runtime_primitives::traits::{ - As, SimpleArithmetic, Zero, ProvideInherent, Block as BlockT, Extrinsic -}; +use runtime_primitives::traits::{As, SimpleArithmetic, Zero}; use system::ensure_inherent; -use rstd::{result, ops::{Mul, Div}, vec::Vec}; +use rstd::{result, ops::{Mul, Div}, cmp}; use runtime_support::for_each_tuple; +use inherents::{RuntimeString, InherentIdentifier, ProvideInherent, IsFatalError, InherentData}; +#[cfg(feature = "std")] +use inherents::ProvideInherentData; + +/// The identifier for the `timestamp` inherent. +pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"timstap0"; +/// The type of the inherent. +pub type InherentType = u64; + +/// Errors that can occur while checking the timestamp inherent. +#[derive(Encode)] +#[cfg_attr(feature = "std", derive(Debug, Decode))] +pub enum InherentError { + /// The timestamp is valid in the future. + /// This is a non-fatal-error and will not stop checking the inherents. + ValidAtTimestamp(InherentType), + /// Some other error. + Other(RuntimeString), +} + +impl IsFatalError for InherentError { + fn is_fatal_error(&self) -> bool { + match self { + InherentError::ValidAtTimestamp(_) => false, + InherentError::Other(_) => true, + } + } +} + +impl InherentError { + /// Try to create an instance ouf of the given identifier and data. + #[cfg(feature = "std")] + pub fn try_from(id: &InherentIdentifier, data: &[u8]) -> Option { + if id == &INHERENT_IDENTIFIER { + ::decode(&mut &data[..]) + } else { + None + } + } +} + +/// Auxiliary trait to extract timestamp inherent data. +pub trait TimestampInherentData { + /// Get timestamp inherent data. + fn timestamp_inherent_data(&self) -> Result; +} + +impl TimestampInherentData for InherentData { + fn timestamp_inherent_data(&self) -> Result { + self.get_data(&INHERENT_IDENTIFIER) + .and_then(|r| r.ok_or_else(|| "Timestamp inherent data not found".into())) + } +} + +#[cfg(feature = "std")] +pub struct InherentDataProvider; + +#[cfg(feature = "std")] +impl ProvideInherentData for InherentDataProvider { + fn inherent_identifier(&self) -> &'static InherentIdentifier { + &INHERENT_IDENTIFIER + } + + fn provide_inherent_data(&self, inherent_data: &mut InherentData) -> Result<(), RuntimeString> { + use std::time::SystemTime; + + let now = SystemTime::now(); + now.duration_since(SystemTime::UNIX_EPOCH) + .map_err(|_| { + "Current time is before unix epoch".into() + }).and_then(|d| { + let duration: InherentType = d.as_secs(); + inherent_data.put_data(INHERENT_IDENTIFIER, &duration) + }) + } + + fn error_to_string(&self, error: &[u8]) -> Option { + InherentError::try_from(&INHERENT_IDENTIFIER, error).map(|e| format!("{:?}", e)) + } +} /// A trait which is called when the timestamp is set. pub trait OnTimestampSet { @@ -80,11 +159,10 @@ macro_rules! impl_timestamp_set { for_each_tuple!(impl_timestamp_set); pub trait Trait: consensus::Trait + system::Trait { - /// The position of the required timestamp-set extrinsic. - const TIMESTAMP_SET_POSITION: u32; - /// Type used for expressing timestamp. - type Moment: Parameter + Default + SimpleArithmetic + Mul + Div; + type Moment: Parameter + Default + SimpleArithmetic + + Mul + + Div; /// Something which can be notified when the timestamp is set. Set this to `()` if not needed. type OnTimestampSet: OnTimestampSet; } @@ -102,11 +180,6 @@ decl_module! { fn set(origin, #[compact] now: T::Moment) { ensure_inherent(origin)?; assert!(!::DidUpdate::exists(), "Timestamp must be updated only once in the block"); - assert!( - >::extrinsic_index() == Some(T::TIMESTAMP_SET_POSITION), - "Timestamp extrinsic must be at position {} in the block", - T::TIMESTAMP_SET_POSITION - ); assert!( Self::now().is_zero() || now >= Self::now() + Self::block_period(), "Timestamp must increment by at least between sequential blocks" @@ -152,33 +225,39 @@ impl Module { } } -impl ProvideInherent for Module { - type Inherent = T::Moment; - type Call = Call; +fn extract_inherent_data(data: &InherentData) -> Result { + data.get_data::(&INHERENT_IDENTIFIER) + .map_err(|_| RuntimeString::from("Invalid timestamp inherent data encoding."))? + .ok_or_else(|| "Timestamp inherent data is not provided.".into()) +} - fn create_inherent_extrinsics(data: Self::Inherent) -> Vec<(u32, Self::Call)> { - let next_time = ::rstd::cmp::max(data, Self::now() + Self::block_period()); - vec![(T::TIMESTAMP_SET_POSITION, Call::set(next_time.into()))] +impl ProvideInherent for Module { + type Call = Call; + type Error = InherentError; + const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER; + + fn create_inherent(data: &InherentData) -> Option { + let data = extract_inherent_data(data).expect("Gets and decodes timestamp inherent data"); + + let next_time = cmp::max(As::sa(data), Self::now() + Self::block_period()); + Some(Call::set(next_time.into())) } - fn check_inherent Option<&Self::Call>>( - block: &Block, data: Self::Inherent, extract_function: &F - ) -> result::Result<(), CheckInherentError> { + fn check_inherent(call: &Self::Call, data: &InherentData) -> result::Result<(), Self::Error> { const MAX_TIMESTAMP_DRIFT: u64 = 60; - let xt = block.extrinsics().get(T::TIMESTAMP_SET_POSITION as usize) - .ok_or_else(|| CheckInherentError::Other("No valid timestamp inherent in block".into()))?; - - let t = match (xt.is_signed(), extract_function(&xt)) { - (Some(false), Some(Call::set(ref t))) => t.clone(), - _ => return Err(CheckInherentError::Other("No valid timestamp inherent in block".into())), + let t = match call { + Call::set(ref t) => t.clone(), + _ => return Ok(()), }.as_(); + let data = extract_inherent_data(data).map_err(|e| InherentError::Other(e))?; + let minimum = (Self::now() + Self::block_period()).as_(); - if t > data.as_() + MAX_TIMESTAMP_DRIFT { - Err(CheckInherentError::Other("Timestamp too far in future to accept".into())) + if t > data + MAX_TIMESTAMP_DRIFT { + Err(InherentError::Other("Timestamp too far in future to accept".into())) } else if t < minimum { - Err(CheckInherentError::ValidAtTimestamp(minimum)) + Err(InherentError::ValidAtTimestamp(minimum)) } else { Ok(()) } @@ -215,13 +294,11 @@ mod tests { type Log = DigestItem; } impl consensus::Trait for Test { - const NOTE_OFFLINE_POSITION: u32 = 1; type Log = DigestItem; type SessionKey = UintAuthorityId; type InherentOfflineReport = (); } impl Trait for Test { - const TIMESTAMP_SET_POSITION: u32 = 0; type Moment = u64; type OnTimestampSet = (); }