mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-13 16:21:06 +00:00
Don't include :code by default in storage proofs (#5179)
* Don't include `:code` by default in storage proofs (#5060) * Adds test to verify that the runtime currently is always contained in the proof * Start passing the runtime wasm code from the outside * Fix compilation * More build fixes * Make the test work as expected now :) * Last fixes * Fixes benchmarks * Review feedback * Apply suggestions from code review Co-Authored-By: Sergei Pepyakin <sergei@parity.io> * Review feedback * Fix compilation Co-authored-by: Sergei Pepyakin <s.pepyakin@gmail.com> * Fix compilation and change the way `RuntimeCode` works * Fix tests * Switch to `Cow` Co-authored-by: Benjamin Kampmann <ben@gnunicorn.org> Co-authored-by: Sergei Pepyakin <s.pepyakin@gmail.com>
This commit is contained in:
@@ -471,4 +471,3 @@ mod tests {
|
||||
client.import(BlockOrigin::Own, block).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,3 +19,7 @@ sp-core = { version = "2.0.0-alpha.2", path = "../../primitives/core" }
|
||||
sp-block-builder = { version = "2.0.0-alpha.2", path = "../../primitives/block-builder" }
|
||||
sc-client-api = { version = "2.0.0-alpha.2", path = "../api" }
|
||||
codec = { package = "parity-scale-codec", version = "1.2.0", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
substrate-test-runtime-client = { path = "../../test-utils/runtime/client" }
|
||||
sp-trie = { version = "2.0.0-alpha.2", path = "../../primitives/trie" }
|
||||
|
||||
@@ -205,3 +205,41 @@ where
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sp_blockchain::HeaderBackend;
|
||||
use sp_core::Blake2Hasher;
|
||||
use sp_state_machine::Backend;
|
||||
use substrate_test_runtime_client::{DefaultTestClientBuilderExt, TestClientBuilderExt};
|
||||
|
||||
#[test]
|
||||
fn block_building_storage_proof_does_not_include_runtime_by_default() {
|
||||
let builder = substrate_test_runtime_client::TestClientBuilder::new();
|
||||
let backend = builder.backend();
|
||||
let client = builder.build();
|
||||
|
||||
let block = BlockBuilder::new(
|
||||
&client,
|
||||
client.info().best_hash,
|
||||
client.info().best_number,
|
||||
RecordProof::Yes,
|
||||
Default::default(),
|
||||
&*backend,
|
||||
).unwrap().build().unwrap();
|
||||
|
||||
let proof = block.proof.expect("Proof is build on request");
|
||||
|
||||
let backend = sp_state_machine::create_proof_check_backend::<Blake2Hasher>(
|
||||
block.storage_changes.transaction_storage_root,
|
||||
proof,
|
||||
).unwrap();
|
||||
|
||||
assert!(
|
||||
backend.storage(&sp_core::storage::well_known_keys::CODE)
|
||||
.unwrap_err()
|
||||
.contains("Database missing expected key"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,6 +49,7 @@ fn call_in_wasm<E: Externalities>(
|
||||
);
|
||||
executor.call_in_wasm(
|
||||
&WASM_BINARY[..],
|
||||
None,
|
||||
function,
|
||||
call_data,
|
||||
ext,
|
||||
@@ -513,6 +514,7 @@ fn should_trap_when_heap_exhausted(wasm_method: WasmExecutionMethod) {
|
||||
);
|
||||
executor.call_in_wasm(
|
||||
&WASM_BINARY[..],
|
||||
None,
|
||||
"test_exhaust_heap",
|
||||
&[0],
|
||||
&mut ext.ext(),
|
||||
|
||||
@@ -52,8 +52,12 @@ pub trait RuntimeInfo {
|
||||
/// Native runtime information.
|
||||
fn native_version(&self) -> &NativeVersion;
|
||||
|
||||
/// Extract RuntimeVersion of given :code block
|
||||
fn runtime_version(&self, ext: &mut dyn Externalities) -> error::Result<RuntimeVersion>;
|
||||
/// Extract [`RuntimeVersion`](sp_version::RuntimeVersion) of the given `runtime_code`.
|
||||
fn runtime_version(
|
||||
&self,
|
||||
ext: &mut dyn Externalities,
|
||||
runtime_code: &sp_core::traits::RuntimeCode,
|
||||
) -> error::Result<RuntimeVersion>;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -77,6 +81,7 @@ mod tests {
|
||||
);
|
||||
let res = executor.call_in_wasm(
|
||||
&WASM_BINARY[..],
|
||||
None,
|
||||
"test_empty_return",
|
||||
&[],
|
||||
&mut ext,
|
||||
|
||||
@@ -16,11 +16,11 @@
|
||||
|
||||
use crate::{
|
||||
RuntimeInfo, error::{Error, Result},
|
||||
wasm_runtime::{RuntimeCache, WasmExecutionMethod, CodeSource},
|
||||
wasm_runtime::{RuntimeCache, WasmExecutionMethod},
|
||||
};
|
||||
use sp_version::{NativeVersion, RuntimeVersion};
|
||||
use codec::{Decode, Encode};
|
||||
use sp_core::{NativeOrEncoded, traits::{CodeExecutor, Externalities}};
|
||||
use sp_core::{NativeOrEncoded, traits::{CodeExecutor, Externalities, RuntimeCode}};
|
||||
use log::trace;
|
||||
use std::{result, panic::{UnwindSafe, AssertUnwindSafe}, sync::Arc};
|
||||
use sp_wasm_interface::{HostFunctions, Function};
|
||||
@@ -111,7 +111,7 @@ impl WasmExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute the given closure `f` with the latest runtime (based on the `CODE` key in `ext`).
|
||||
/// Execute the given closure `f` with the latest runtime (based on `runtime_code`).
|
||||
///
|
||||
/// The closure `f` is expected to return `Err(_)` when there happened a `panic!` in native code
|
||||
/// while executing the runtime in Wasm. If a `panic!` occurred, the runtime is invalidated to
|
||||
@@ -124,9 +124,9 @@ impl WasmExecutor {
|
||||
/// runtime is invalidated on any `panic!` to prevent a poisoned state. `ext` is already
|
||||
/// implicitly handled as unwind safe, as we store it in a global variable while executing the
|
||||
/// native runtime.
|
||||
fn with_instance<'c, R, F>(
|
||||
fn with_instance<R, F>(
|
||||
&self,
|
||||
code: CodeSource<'c>,
|
||||
runtime_code: &RuntimeCode,
|
||||
ext: &mut dyn Externalities,
|
||||
f: F,
|
||||
) -> Result<R>
|
||||
@@ -137,7 +137,7 @@ impl WasmExecutor {
|
||||
) -> Result<Result<R>>,
|
||||
{
|
||||
match self.cache.with_instance(
|
||||
code,
|
||||
runtime_code,
|
||||
ext,
|
||||
self.method,
|
||||
self.default_heap_pages,
|
||||
@@ -158,17 +158,48 @@ impl WasmExecutor {
|
||||
impl sp_core::traits::CallInWasm for WasmExecutor {
|
||||
fn call_in_wasm(
|
||||
&self,
|
||||
wasm_blob: &[u8],
|
||||
wasm_code: &[u8],
|
||||
code_hash: Option<Vec<u8>>,
|
||||
method: &str,
|
||||
call_data: &[u8],
|
||||
ext: &mut dyn Externalities,
|
||||
) -> std::result::Result<Vec<u8>, String> {
|
||||
self.with_instance(CodeSource::Custom(wasm_blob), ext, |instance, _, mut ext| {
|
||||
if let Some(hash) = code_hash {
|
||||
let code = RuntimeCode {
|
||||
code_fetcher: &sp_core::traits::WrappedRuntimeCode(wasm_code.into()),
|
||||
hash,
|
||||
heap_pages: None,
|
||||
};
|
||||
|
||||
self.with_instance(&code, ext, |instance, _, mut ext| {
|
||||
with_externalities_safe(
|
||||
&mut **ext,
|
||||
move || instance.call(method, call_data),
|
||||
)
|
||||
}).map_err(|e| e.to_string())
|
||||
} else {
|
||||
let module = crate::wasm_runtime::create_wasm_runtime_with_code(
|
||||
self.method,
|
||||
self.default_heap_pages,
|
||||
&wasm_code,
|
||||
self.host_functions.to_vec(),
|
||||
self.allow_missing_func_imports,
|
||||
)
|
||||
.map_err(|e| format!("Failed to create module: {:?}", e))?;
|
||||
|
||||
let instance = module.new_instance()
|
||||
.map_err(|e| format!("Failed to create instance: {:?}", e))?;
|
||||
|
||||
let instance = AssertUnwindSafe(instance);
|
||||
let mut ext = AssertUnwindSafe(ext);
|
||||
|
||||
with_externalities_safe(
|
||||
&mut **ext,
|
||||
move || instance.call(method, call_data),
|
||||
)
|
||||
}).map_err(|e| e.to_string())
|
||||
.and_then(|r| r)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,8 +251,11 @@ impl<D: NativeExecutionDispatch> RuntimeInfo for NativeExecutor<D> {
|
||||
fn runtime_version(
|
||||
&self,
|
||||
ext: &mut dyn Externalities,
|
||||
runtime_code: &RuntimeCode,
|
||||
) -> Result<RuntimeVersion> {
|
||||
self.wasm.with_instance(CodeSource::Externalities, ext,
|
||||
self.wasm.with_instance(
|
||||
runtime_code,
|
||||
ext,
|
||||
|_instance, version, _ext|
|
||||
Ok(version.cloned().ok_or_else(|| Error::ApiError("Unknown version".into())))
|
||||
)
|
||||
@@ -237,6 +271,7 @@ impl<D: NativeExecutionDispatch + 'static> CodeExecutor for NativeExecutor<D> {
|
||||
>(
|
||||
&self,
|
||||
ext: &mut dyn Externalities,
|
||||
runtime_code: &RuntimeCode,
|
||||
method: &str,
|
||||
data: &[u8],
|
||||
use_native: bool,
|
||||
@@ -244,7 +279,7 @@ impl<D: NativeExecutionDispatch + 'static> CodeExecutor for NativeExecutor<D> {
|
||||
) -> (Result<NativeOrEncoded<R>>, bool) {
|
||||
let mut used_native = false;
|
||||
let result = self.wasm.with_instance(
|
||||
CodeSource::Externalities,
|
||||
runtime_code,
|
||||
ext,
|
||||
|instance, onchain_version, mut ext| {
|
||||
let onchain_version = onchain_version.ok_or_else(
|
||||
@@ -324,11 +359,12 @@ impl<D: NativeExecutionDispatch> sp_core::traits::CallInWasm for NativeExecutor<
|
||||
fn call_in_wasm(
|
||||
&self,
|
||||
wasm_blob: &[u8],
|
||||
code_hash: Option<Vec<u8>>,
|
||||
method: &str,
|
||||
call_data: &[u8],
|
||||
ext: &mut dyn Externalities,
|
||||
) -> std::result::Result<Vec<u8>, String> {
|
||||
sp_core::traits::CallInWasm::call_in_wasm(&self.wasm, wasm_blob, method, call_data, ext)
|
||||
self.wasm.call_in_wasm(wasm_blob, code_hash, method, call_data, ext)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,11 +20,10 @@
|
||||
//! components of the runtime that are expensive to initialize.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::borrow::Cow;
|
||||
use crate::error::{Error, WasmError};
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use codec::Decode;
|
||||
use sp_core::{storage::well_known_keys, traits::Externalities};
|
||||
use sp_core::traits::{Externalities, RuntimeCode, FetchRuntimeCode};
|
||||
use sp_version::RuntimeVersion;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use sc_executor_common::wasm_runtime::{WasmModule, WasmInstance};
|
||||
@@ -41,14 +40,6 @@ pub enum WasmExecutionMethod {
|
||||
Compiled,
|
||||
}
|
||||
|
||||
/// Executoed code origin.
|
||||
pub enum CodeSource<'a> {
|
||||
/// Take code from storage,
|
||||
Externalities,
|
||||
/// Use provided code,
|
||||
Custom(&'a [u8]),
|
||||
}
|
||||
|
||||
/// A Wasm runtime object along with its cached runtime version.
|
||||
struct VersionedRuntime {
|
||||
/// Runtime code hash.
|
||||
@@ -102,8 +93,7 @@ impl RuntimeCache {
|
||||
///
|
||||
/// `code` - Provides external code or tells the executor to fetch it from storage.
|
||||
///
|
||||
/// `ext` - Externalities to use for the runtime. This is used for setting
|
||||
/// up an initial runtime instance.
|
||||
/// `runtime_code` - The runtime wasm code used setup the runtime.
|
||||
///
|
||||
/// `default_heap_pages` - Number of 64KB pages to allocate for Wasm execution.
|
||||
///
|
||||
@@ -124,7 +114,7 @@ impl RuntimeCache {
|
||||
/// identifier `memory` can be found in the runtime.
|
||||
pub fn with_instance<'c, R, F>(
|
||||
&self,
|
||||
code: CodeSource<'c>,
|
||||
runtime_code: &'c RuntimeCode<'c>,
|
||||
ext: &mut dyn Externalities,
|
||||
wasm_method: WasmExecutionMethod,
|
||||
default_heap_pages: u64,
|
||||
@@ -138,28 +128,14 @@ impl RuntimeCache {
|
||||
&mut dyn Externalities)
|
||||
-> Result<R, Error>,
|
||||
{
|
||||
let (code_hash, heap_pages) = match &code {
|
||||
CodeSource::Externalities => {
|
||||
(
|
||||
ext
|
||||
.original_storage_hash(well_known_keys::CODE)
|
||||
.ok_or(Error::InvalidCode("`CODE` not found in storage.".into()))?,
|
||||
ext
|
||||
.storage(well_known_keys::HEAP_PAGES)
|
||||
.and_then(|pages| u64::decode(&mut &pages[..]).ok())
|
||||
.unwrap_or(default_heap_pages),
|
||||
)
|
||||
},
|
||||
CodeSource::Custom(code) => {
|
||||
(sp_core::blake2_256(code).to_vec(), default_heap_pages)
|
||||
}
|
||||
};
|
||||
let code_hash = &runtime_code.hash;
|
||||
let heap_pages = runtime_code.heap_pages.unwrap_or(default_heap_pages);
|
||||
|
||||
let mut runtimes = self.runtimes.lock(); // this must be released prior to calling f
|
||||
let pos = runtimes.iter().position(|r| r.as_ref().map_or(
|
||||
false,
|
||||
|r| r.wasm_method == wasm_method &&
|
||||
r.code_hash == code_hash &&
|
||||
r.code_hash == *code_hash &&
|
||||
r.heap_pages == heap_pages
|
||||
));
|
||||
|
||||
@@ -168,19 +144,11 @@ impl RuntimeCache {
|
||||
.clone()
|
||||
.expect("`position` only returns `Some` for entries that are `Some`"),
|
||||
None => {
|
||||
let code = match code {
|
||||
CodeSource::Externalities => {
|
||||
Cow::Owned(ext.original_storage(well_known_keys::CODE)
|
||||
.ok_or(WasmError::CodeNotFound)?)
|
||||
}
|
||||
CodeSource::Custom(code) => {
|
||||
Cow::Borrowed(code)
|
||||
}
|
||||
};
|
||||
let code = runtime_code.fetch_runtime_code().ok_or(WasmError::CodeNotFound)?;
|
||||
|
||||
let result = create_versioned_wasm_runtime(
|
||||
&code,
|
||||
code_hash,
|
||||
code_hash.clone(),
|
||||
ext,
|
||||
wasm_method,
|
||||
heap_pages,
|
||||
|
||||
@@ -66,7 +66,12 @@ pub trait Client<Block: BlockT>: Send + Sync {
|
||||
) -> Result<StorageProof, Error>;
|
||||
|
||||
/// Get method execution proof.
|
||||
fn execution_proof(&self, block: &Block::Hash, method: &str, data: &[u8]) -> Result<(Vec<u8>, StorageProof), Error>;
|
||||
fn execution_proof(
|
||||
&self,
|
||||
block: &Block::Hash,
|
||||
method: &str,
|
||||
data: &[u8],
|
||||
) -> Result<(Vec<u8>, StorageProof), Error>;
|
||||
|
||||
/// Get key changes proof.
|
||||
fn key_changes_proof(
|
||||
|
||||
@@ -254,13 +254,12 @@ where
|
||||
B: Block,
|
||||
{
|
||||
/// Construct a new light client handler.
|
||||
pub fn new
|
||||
( cfg: Config
|
||||
, chain: Arc<dyn Client<B>>
|
||||
, checker: Arc<dyn fetcher::FetchChecker<B>>
|
||||
, peerset: sc_peerset::PeersetHandle
|
||||
) -> Self
|
||||
{
|
||||
pub fn new(
|
||||
cfg: Config,
|
||||
chain: Arc<dyn Client<B>>,
|
||||
checker: Arc<dyn fetcher::FetchChecker<B>>,
|
||||
peerset: sc_peerset::PeersetHandle,
|
||||
) -> Self {
|
||||
LightClientHandler {
|
||||
config: cfg,
|
||||
chain,
|
||||
@@ -425,7 +424,8 @@ where
|
||||
log::trace!("remote call request from {} ({} at {:?})",
|
||||
peer,
|
||||
request.method,
|
||||
request.block);
|
||||
request.block,
|
||||
);
|
||||
|
||||
let block = Decode::decode(&mut request.block.as_ref())?;
|
||||
|
||||
@@ -436,7 +436,8 @@ where
|
||||
peer,
|
||||
request.method,
|
||||
request.block,
|
||||
e);
|
||||
e,
|
||||
);
|
||||
StorageProof::empty()
|
||||
}
|
||||
};
|
||||
|
||||
@@ -750,7 +750,11 @@ pub mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn check_execution_proof(&self, _: &RemoteCallRequest<B::Header>, _: StorageProof) -> ClientResult<Vec<u8>> {
|
||||
fn check_execution_proof(
|
||||
&self,
|
||||
_: &RemoteCallRequest<B::Header>,
|
||||
_: StorageProof,
|
||||
) -> ClientResult<Vec<u8>> {
|
||||
match self.ok {
|
||||
true => Ok(vec![42]),
|
||||
false => Err(ClientError::Backend("Test error".into())),
|
||||
|
||||
@@ -81,6 +81,7 @@ where
|
||||
id, self.backend.changes_trie_storage()
|
||||
)?;
|
||||
let state = self.backend.state_at(*id)?;
|
||||
let state_runtime_code = sp_state_machine::backend::BackendRuntimeCode::new(&state);
|
||||
let return_data = StateMachine::new(
|
||||
&state,
|
||||
changes_trie,
|
||||
@@ -89,6 +90,7 @@ where
|
||||
method,
|
||||
call_data,
|
||||
extensions.unwrap_or_default(),
|
||||
&state_runtime_code.runtime_code()?,
|
||||
).execute_using_consensus_failure_handler::<_, NeverNativeValue, fn() -> _>(
|
||||
strategy.get_manager(),
|
||||
None,
|
||||
@@ -135,42 +137,53 @@ where
|
||||
let mut storage_transaction_cache = storage_transaction_cache.map(|c| c.borrow_mut());
|
||||
|
||||
let mut state = self.backend.state_at(*at)?;
|
||||
match recorder {
|
||||
Some(recorder) => state.as_trie_backend()
|
||||
.ok_or_else(||
|
||||
Box::new(sp_state_machine::ExecutionError::UnableToGenerateProof)
|
||||
as Box<dyn sp_state_machine::Error>
|
||||
)
|
||||
.and_then(|trie_state| {
|
||||
let backend = sp_state_machine::ProvingBackend::new_with_recorder(
|
||||
trie_state,
|
||||
recorder.clone(),
|
||||
);
|
||||
|
||||
StateMachine::new(
|
||||
&backend,
|
||||
changes_trie_state,
|
||||
&mut *changes.borrow_mut(),
|
||||
&self.executor,
|
||||
method,
|
||||
call_data,
|
||||
extensions.unwrap_or_default(),
|
||||
)
|
||||
// TODO: https://github.com/paritytech/substrate/issues/4455
|
||||
// .with_storage_transaction_cache(storage_transaction_cache.as_mut().map(|c| &mut **c))
|
||||
.execute_using_consensus_failure_handler(execution_manager, native_call)
|
||||
}),
|
||||
None => StateMachine::new(
|
||||
&state,
|
||||
changes_trie_state,
|
||||
&mut *changes.borrow_mut(),
|
||||
&self.executor,
|
||||
method,
|
||||
call_data,
|
||||
extensions.unwrap_or_default(),
|
||||
)
|
||||
.with_storage_transaction_cache(storage_transaction_cache.as_mut().map(|c| &mut **c))
|
||||
.execute_using_consensus_failure_handler(execution_manager, native_call)
|
||||
match recorder {
|
||||
Some(recorder) => {
|
||||
let trie_state = state.as_trie_backend()
|
||||
.ok_or_else(||
|
||||
Box::new(sp_state_machine::ExecutionError::UnableToGenerateProof) as Box<dyn sp_state_machine::Error>
|
||||
)?;
|
||||
|
||||
let state_runtime_code = sp_state_machine::backend::BackendRuntimeCode::new(&trie_state);
|
||||
// It is important to extract the runtime code here before we create the proof
|
||||
// recorder.
|
||||
let runtime_code = state_runtime_code.runtime_code()?;
|
||||
|
||||
let backend = sp_state_machine::ProvingBackend::new_with_recorder(
|
||||
trie_state,
|
||||
recorder.clone(),
|
||||
);
|
||||
|
||||
StateMachine::new(
|
||||
&backend,
|
||||
changes_trie_state,
|
||||
&mut *changes.borrow_mut(),
|
||||
&self.executor,
|
||||
method,
|
||||
call_data,
|
||||
extensions.unwrap_or_default(),
|
||||
&runtime_code,
|
||||
)
|
||||
// TODO: https://github.com/paritytech/substrate/issues/4455
|
||||
// .with_storage_transaction_cache(storage_transaction_cache.as_mut().map(|c| &mut **c))
|
||||
.execute_using_consensus_failure_handler(execution_manager, native_call)
|
||||
},
|
||||
None => {
|
||||
let state_runtime_code = sp_state_machine::backend::BackendRuntimeCode::new(&state);
|
||||
StateMachine::new(
|
||||
&state,
|
||||
changes_trie_state,
|
||||
&mut *changes.borrow_mut(),
|
||||
&self.executor,
|
||||
method,
|
||||
call_data,
|
||||
extensions.unwrap_or_default(),
|
||||
&state_runtime_code.runtime_code()?,
|
||||
)
|
||||
.with_storage_transaction_cache(storage_transaction_cache.as_mut().map(|c| &mut **c))
|
||||
.execute_using_consensus_failure_handler(execution_manager, native_call)
|
||||
}
|
||||
}.map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -189,7 +202,8 @@ where
|
||||
changes_trie_state,
|
||||
None,
|
||||
);
|
||||
self.executor.runtime_version(&mut ext)
|
||||
let state_runtime_code = sp_state_machine::backend::BackendRuntimeCode::new(&state);
|
||||
self.executor.runtime_version(&mut ext, &state_runtime_code.runtime_code()?)
|
||||
.map_err(|e| sp_blockchain::Error::VersionInvalid(format!("{:?}", e)).into())
|
||||
}
|
||||
|
||||
@@ -206,6 +220,7 @@ where
|
||||
&self.executor,
|
||||
method,
|
||||
call_data,
|
||||
&sp_state_machine::backend::BackendRuntimeCode::new(trie_state).runtime_code()?,
|
||||
)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -41,8 +41,7 @@ use sp_runtime::{
|
||||
use sp_state_machine::{
|
||||
DBValue, Backend as StateBackend, ChangesTrieAnchorBlockId,
|
||||
prove_read, prove_child_read, ChangesTrieRootsStorage, ChangesTrieStorage,
|
||||
ChangesTrieConfigurationRange, key_changes, key_changes_proof, StorageProof,
|
||||
merge_storage_proofs,
|
||||
ChangesTrieConfigurationRange, key_changes, key_changes_proof,
|
||||
};
|
||||
use sc_executor::{RuntimeVersion, RuntimeInfo};
|
||||
use sp_consensus::{
|
||||
@@ -55,6 +54,7 @@ use sp_blockchain::{self as blockchain,
|
||||
well_known_cache_keys::Id as CacheKeyId,
|
||||
HeaderMetadata, CachedHeaderMetadata,
|
||||
};
|
||||
use sp_trie::StorageProof;
|
||||
|
||||
use sp_api::{
|
||||
CallApiAt, ConstructRuntimeApi, Core as CoreApi, ApiExt, ApiRef, ProvideRuntimeApi,
|
||||
@@ -472,7 +472,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
|
||||
Ok(())
|
||||
}, ())?;
|
||||
|
||||
Ok(merge_storage_proofs(proofs))
|
||||
Ok(StorageProof::merge(proofs))
|
||||
}
|
||||
|
||||
/// Generates CHT-based proof for roots of changes tries at given blocks (that are part of single CHT).
|
||||
@@ -1140,9 +1140,20 @@ impl<B, E, Block, RA> ProofProvider<Block> for Client<B, E, Block, RA> where
|
||||
method: &str,
|
||||
call_data: &[u8]
|
||||
) -> sp_blockchain::Result<(Vec<u8>, StorageProof)> {
|
||||
// Make sure we include the `:code` and `:heap_pages` in the execution proof to be
|
||||
// backwards compatible.
|
||||
//
|
||||
// TODO: Remove when solved: https://github.com/paritytech/substrate/issues/5047
|
||||
let code_proof = self.read_proof(
|
||||
id,
|
||||
&mut [well_known_keys::CODE, well_known_keys::HEAP_PAGES].iter().map(|v| *v),
|
||||
)?;
|
||||
|
||||
let state = self.state_at(id)?;
|
||||
let header = self.prepare_environment_block(id)?;
|
||||
prove_execution(state, header, &self.executor, method, call_data)
|
||||
prove_execution(state, header, &self.executor, method, call_data).map(|(r, p)| {
|
||||
(r, StorageProof::merge(vec![p, code_proof]))
|
||||
})
|
||||
}
|
||||
|
||||
fn header_proof(&self, id: &BlockId<Block>) -> sp_blockchain::Result<(Block::Header, StorageProof)> {
|
||||
|
||||
@@ -89,6 +89,8 @@ mod tests {
|
||||
};
|
||||
let hash = header.hash();
|
||||
let mut overlay = OverlayedChanges::default();
|
||||
let backend_runtime_code = sp_state_machine::backend::BackendRuntimeCode::new(&backend);
|
||||
let runtime_code = backend_runtime_code.runtime_code().expect("Code is part of the backend");
|
||||
|
||||
StateMachine::new(
|
||||
backend,
|
||||
@@ -98,6 +100,7 @@ mod tests {
|
||||
"Core_initialize_block",
|
||||
&header.encode(),
|
||||
Default::default(),
|
||||
&runtime_code,
|
||||
).execute(
|
||||
ExecutionStrategy::NativeElseWasm,
|
||||
).unwrap();
|
||||
@@ -111,6 +114,7 @@ mod tests {
|
||||
"BlockBuilder_apply_extrinsic",
|
||||
&tx.encode(),
|
||||
Default::default(),
|
||||
&runtime_code,
|
||||
).execute(
|
||||
ExecutionStrategy::NativeElseWasm,
|
||||
).unwrap();
|
||||
@@ -124,6 +128,7 @@ mod tests {
|
||||
"BlockBuilder_finalize_block",
|
||||
&[],
|
||||
Default::default(),
|
||||
&runtime_code,
|
||||
).execute(
|
||||
ExecutionStrategy::NativeElseWasm,
|
||||
).unwrap();
|
||||
@@ -161,6 +166,8 @@ mod tests {
|
||||
|
||||
let backend = InMemoryBackend::from(storage);
|
||||
let (b1data, _b1hash) = block1(genesis_hash, &backend);
|
||||
let backend_runtime_code = sp_state_machine::backend::BackendRuntimeCode::new(&backend);
|
||||
let runtime_code = backend_runtime_code.runtime_code().expect("Code is part of the backend");
|
||||
|
||||
let mut overlay = OverlayedChanges::default();
|
||||
let _ = StateMachine::new(
|
||||
@@ -171,6 +178,7 @@ mod tests {
|
||||
"Core_execute_block",
|
||||
&b1data,
|
||||
Default::default(),
|
||||
&runtime_code,
|
||||
).execute(
|
||||
ExecutionStrategy::NativeElseWasm,
|
||||
).unwrap();
|
||||
@@ -189,6 +197,8 @@ mod tests {
|
||||
|
||||
let backend = InMemoryBackend::from(storage);
|
||||
let (b1data, _b1hash) = block1(genesis_hash, &backend);
|
||||
let backend_runtime_code = sp_state_machine::backend::BackendRuntimeCode::new(&backend);
|
||||
let runtime_code = backend_runtime_code.runtime_code().expect("Code is part of the backend");
|
||||
|
||||
let mut overlay = OverlayedChanges::default();
|
||||
let _ = StateMachine::new(
|
||||
@@ -199,6 +209,7 @@ mod tests {
|
||||
"Core_execute_block",
|
||||
&b1data,
|
||||
Default::default(),
|
||||
&runtime_code,
|
||||
).execute(
|
||||
ExecutionStrategy::AlwaysWasm,
|
||||
).unwrap();
|
||||
@@ -217,6 +228,8 @@ mod tests {
|
||||
|
||||
let backend = InMemoryBackend::from(storage);
|
||||
let (b1data, _b1hash) = block1(genesis_hash, &backend);
|
||||
let backend_runtime_code = sp_state_machine::backend::BackendRuntimeCode::new(&backend);
|
||||
let runtime_code = backend_runtime_code.runtime_code().expect("Code is part of the backend");
|
||||
|
||||
let mut overlay = OverlayedChanges::default();
|
||||
let r = StateMachine::new(
|
||||
@@ -227,6 +240,7 @@ mod tests {
|
||||
"Core_execute_block",
|
||||
&b1data,
|
||||
Default::default(),
|
||||
&runtime_code,
|
||||
).execute(
|
||||
ExecutionStrategy::NativeElseWasm,
|
||||
);
|
||||
|
||||
@@ -172,9 +172,9 @@ impl<S, Block> ClientBackend<Block> for Backend<S, HashFor<Block>>
|
||||
match maybe_val {
|
||||
Some(val) => self.blockchain.storage().insert_aux(
|
||||
&[(&key[..], &val[..])],
|
||||
::std::iter::empty(),
|
||||
std::iter::empty(),
|
||||
)?,
|
||||
None => self.blockchain.storage().insert_aux(::std::iter::empty(), &[&key[..]])?,
|
||||
None => self.blockchain.storage().insert_aux(std::iter::empty(), &[&key[..]])?,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,6 @@ use sp_externalities::Extensions;
|
||||
use sp_state_machine::{
|
||||
self, Backend as StateBackend, OverlayedChanges, ExecutionStrategy, create_proof_check_backend,
|
||||
execution_proof_check_on_trie_backend, ExecutionManager, StorageProof,
|
||||
merge_storage_proofs,
|
||||
};
|
||||
use hash_db::Hasher;
|
||||
|
||||
@@ -206,7 +205,7 @@ pub fn prove_execution<Block, S, E>(
|
||||
method,
|
||||
call_data,
|
||||
)?;
|
||||
let total_proof = merge_storage_proofs(vec![init_proof, exec_proof]);
|
||||
let total_proof = StorageProof::merge(vec![init_proof, exec_proof]);
|
||||
|
||||
Ok((result, total_proof))
|
||||
}
|
||||
@@ -259,12 +258,18 @@ fn check_execution_proof_with_make_header<Header, E, H, MakeNextHeader: Fn(&Head
|
||||
let mut changes = OverlayedChanges::default();
|
||||
let trie_backend = create_proof_check_backend(root, remote_proof)?;
|
||||
let next_header = make_next_header(&request.header);
|
||||
|
||||
// TODO: Remove when solved: https://github.com/paritytech/substrate/issues/5047
|
||||
let backend_runtime_code = sp_state_machine::backend::BackendRuntimeCode::new(&trie_backend);
|
||||
let runtime_code = backend_runtime_code.runtime_code()?;
|
||||
|
||||
execution_proof_check_on_trie_backend::<H, Header::Number, _>(
|
||||
&trie_backend,
|
||||
&mut changes,
|
||||
executor,
|
||||
"Core_initialize_block",
|
||||
&next_header.encode(),
|
||||
&runtime_code,
|
||||
)?;
|
||||
|
||||
// execute method
|
||||
@@ -274,7 +279,9 @@ fn check_execution_proof_with_make_header<Header, E, H, MakeNextHeader: Fn(&Head
|
||||
executor,
|
||||
&request.method,
|
||||
&request.call_data,
|
||||
).map_err(Into::into)
|
||||
&runtime_code,
|
||||
)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -30,7 +30,7 @@ use sp_runtime::traits::{
|
||||
use sp_state_machine::{
|
||||
ChangesTrieRootsStorage, ChangesTrieAnchorBlockId, ChangesTrieConfigurationRange,
|
||||
InMemoryChangesTrieStorage, TrieBackend, read_proof_check, key_changes_proof_check_with_db,
|
||||
create_proof_check_backend_storage, read_child_proof_check,
|
||||
read_child_proof_check,
|
||||
};
|
||||
pub use sp_state_machine::StorageProof;
|
||||
use sp_blockchain::{Error as ClientError, Result as ClientResult};
|
||||
@@ -155,7 +155,7 @@ impl<E, H, B: BlockT, S: BlockchainStorage<B>> LightDataChecker<E, H, B, S> {
|
||||
H::Out: Ord + codec::Codec,
|
||||
{
|
||||
// all the checks are sharing the same storage
|
||||
let storage = create_proof_check_backend_storage(remote_roots_proof);
|
||||
let storage = remote_roots_proof.into_memory_db();
|
||||
|
||||
// remote_roots.keys() are sorted => we can use this to group changes tries roots
|
||||
// that are belongs to the same CHT
|
||||
@@ -187,7 +187,8 @@ impl<E, H, B: BlockT, S: BlockchainStorage<B>> LightDataChecker<E, H, B, S> {
|
||||
local_cht_root,
|
||||
block,
|
||||
remote_changes_trie_root,
|
||||
&proving_backend)?;
|
||||
&proving_backend,
|
||||
)?;
|
||||
|
||||
// and return the storage to use in following checks
|
||||
storage = proving_backend.into_storage();
|
||||
@@ -270,7 +271,7 @@ impl<E, Block, H, S> FetchChecker<Block> for LightDataChecker<E, H, Block, S>
|
||||
body: Vec<Block::Extrinsic>
|
||||
) -> ClientResult<Vec<Block::Extrinsic>> {
|
||||
// TODO: #2621
|
||||
let extrinsics_root = HashFor::<Block>::ordered_trie_root(
|
||||
let extrinsics_root = HashFor::<Block>::ordered_trie_root(
|
||||
body.iter().map(Encode::encode).collect(),
|
||||
);
|
||||
if *request.header.extrinsics_root() == extrinsics_root {
|
||||
@@ -294,7 +295,7 @@ struct RootsStorage<'a, Number: AtLeast32Bit, Hash: 'a> {
|
||||
impl<'a, H, Number, Hash> ChangesTrieRootsStorage<H, Number> for RootsStorage<'a, Number, Hash>
|
||||
where
|
||||
H: Hasher,
|
||||
Number: ::std::fmt::Display + ::std::hash::Hash + Clone + AtLeast32Bit + Encode + Decode + Send + Sync + 'static,
|
||||
Number: std::fmt::Display + std::hash::Hash + Clone + AtLeast32Bit + Encode + Decode + Send + Sync + 'static,
|
||||
Hash: 'a + Send + Sync + Clone + AsRef<[u8]>,
|
||||
{
|
||||
fn build_anchor(
|
||||
|
||||
Reference in New Issue
Block a user