Skip to main content

sp_domains_fraud_proof/
execution_prover.rs

1//! This module provides the feature of generating and verifying the execution proof used in
2//! the Subspace fraud proof mechanism.
3//!
4//! The execution is more fine-grained than the entire block execution, block execution hooks
5//! (`initialize_block` and `finalize_block`) and any specific extrinsic execution are supported.
6
7use crate::fraud_proof::ExecutionPhase;
8use domain_block_builder::create_delta_backend;
9use sc_client_api::backend::Backend;
10use sp_api::StorageProof;
11use sp_core::traits::CodeExecutor;
12use sp_runtime::traits::{Block as BlockT, HashingFor};
13use sp_state_machine::BackendTransaction;
14use sp_state_machine::backend::AsTrieBackend;
15use std::marker::PhantomData;
16use std::sync::Arc;
17
18/// Creates storage proof for verifying an execution without owning the whole state.
19pub struct ExecutionProver<Block, B, Exec> {
20    backend: Arc<B>,
21    executor: Arc<Exec>,
22    _phantom: PhantomData<Block>,
23}
24
25impl<Block, B, Exec> ExecutionProver<Block, B, Exec>
26where
27    Block: BlockT,
28    B: Backend<Block>,
29    Exec: CodeExecutor + 'static,
30{
31    /// Constructs a new instance of [`ExecutionProver`].
32    pub fn new(backend: Arc<B>, executor: Arc<Exec>) -> Self {
33        Self {
34            backend,
35            executor,
36            _phantom: PhantomData::<Block>,
37        }
38    }
39
40    /// Returns a storage proof which can be used to reconstruct a partial state trie to re-run
41    /// the execution by someone who does not own the whole state.
42    pub fn prove_execution(
43        &self,
44        at: Block::Hash,
45        execution_phase: &ExecutionPhase,
46        call_data: &[u8],
47        delta_changes: Option<(BackendTransaction<HashingFor<Block>>, Block::Hash)>,
48    ) -> sp_blockchain::Result<StorageProof> {
49        // Trusted: bounded block-processing context (fraud proof generation)
50        let state = self
51            .backend
52            .state_at(at, sc_client_api::TrieCacheContext::Trusted)?;
53
54        let trie_backend = state.as_trie_backend();
55
56        let state_runtime_code = sp_state_machine::backend::BackendRuntimeCode::new(
57            trie_backend,
58            sp_state_machine::backend::TryPendingCode::Yes,
59        );
60        let runtime_code = state_runtime_code
61            .runtime_code()
62            .map_err(sp_blockchain::Error::RuntimeCode)?;
63
64        // TODO: avoid using the String API specified by `execution_method()`
65        // https://github.com/paritytech/substrate/discussions/11095
66        if let Some((delta, post_delta_root)) = delta_changes {
67            let delta_backend = create_delta_backend(trie_backend, &delta, post_delta_root);
68            sp_state_machine::prove_execution_on_trie_backend(
69                &delta_backend,
70                &mut Default::default(),
71                &*self.executor,
72                execution_phase.execution_method(),
73                call_data,
74                &runtime_code,
75                &mut Default::default(),
76            )
77            .map(|(_ret, proof)| proof)
78            .map_err(Into::into)
79        } else {
80            sp_state_machine::prove_execution_on_trie_backend(
81                trie_backend,
82                &mut Default::default(),
83                &*self.executor,
84                execution_phase.execution_method(),
85                call_data,
86                &runtime_code,
87                &mut Default::default(),
88            )
89            .map(|(_ret, proof)| proof)
90            .map_err(Into::into)
91        }
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98    use sc_client_api::backend::{BlockImportOperation, NewBlockState};
99    use sc_client_api::in_mem;
100    use sp_core::storage::{StateVersion, well_known_keys};
101    use sp_core::traits::{CallContext, CodeExecutor, ReadRuntimeVersion, RuntimeCode};
102    use sp_runtime::generic::{Block, Header};
103    use sp_runtime::traits::{BlakeTwo256, Header as HeaderT};
104    use sp_runtime::{OpaqueExtrinsic, Storage};
105    use std::sync::Mutex;
106
107    type TestBlock = Block<Header<u32, BlakeTwo256>, OpaqueExtrinsic>;
108
109    /// Records the runtime code the prover hands to the executor without running any wasm.
110    #[derive(Clone, Default)]
111    struct RecordingExecutor {
112        executed_code: Arc<Mutex<Vec<Vec<u8>>>>,
113    }
114
115    impl ReadRuntimeVersion for RecordingExecutor {
116        fn read_runtime_version(
117            &self,
118            _wasm_code: &[u8],
119            _ext: &mut dyn sp_core::traits::Externalities,
120        ) -> Result<Vec<u8>, String> {
121            Err("the prover does not read the runtime version".into())
122        }
123    }
124
125    impl CodeExecutor for RecordingExecutor {
126        type Error = String;
127
128        fn call(
129            &self,
130            _ext: &mut dyn sp_core::traits::Externalities,
131            runtime_code: &RuntimeCode,
132            _method: &str,
133            _data: &[u8],
134            _context: CallContext,
135        ) -> (Result<Vec<u8>, String>, bool) {
136            let code = runtime_code
137                .code_fetcher
138                .fetch_runtime_code()
139                .expect("the prover passes the runtime code to the executor")
140                .into_owned();
141            self.executed_code
142                .lock()
143                .expect("lock is not poisoned")
144                .push(code);
145            (Ok(Vec::new()), false)
146        }
147    }
148
149    #[test]
150    fn prover_executes_the_pending_code_of_the_upgrade_block() {
151        let old_code = vec![1u8; 32];
152        let pending_code = vec![2u8; 32];
153
154        let mut genesis_storage = Storage::default();
155        genesis_storage
156            .top
157            .insert(well_known_keys::CODE.to_vec(), old_code);
158        genesis_storage
159            .top
160            .insert(well_known_keys::PENDING_CODE.to_vec(), pending_code.clone());
161
162        let backend = Arc::new(in_mem::Backend::<TestBlock>::new());
163        let mut operation = backend
164            .begin_operation()
165            .expect("in-memory block import operation is created");
166        let state_root = operation
167            .set_genesis_state(genesis_storage, true, StateVersion::V1)
168            .expect("genesis state is set");
169        let header = Header::<u32, BlakeTwo256>::new(
170            0,
171            Default::default(),
172            state_root,
173            Default::default(),
174            Default::default(),
175        );
176        operation
177            .set_block_data(header.clone(), None, None, None, NewBlockState::Final, true)
178            .expect("genesis block data is set");
179        backend
180            .commit_operation(operation)
181            .expect("genesis block is committed");
182
183        let executor = Arc::new(RecordingExecutor::default());
184        let prover = ExecutionProver::<TestBlock, _, _>::new(backend, executor.clone());
185        prover
186            .prove_execution(header.hash(), &ExecutionPhase::InitializeBlock, &[], None)
187            .expect("execution proof is generated");
188
189        let executed_code = executor
190            .executed_code
191            .lock()
192            .expect("lock is not poisoned")
193            .clone();
194        assert_eq!(
195            executed_code,
196            vec![pending_code],
197            "the upgrade block must be executed against `:pending_code`, not `:code`"
198        );
199    }
200}