Skip to content

Commit

Permalink
Remove digest_storage_proof from the invalid state transition proof a…
Browse files Browse the repository at this point in the history
…nd some cleanup

Signed-off-by: linning <linningde25@gmail.com>
  • Loading branch information
NingLin-P committed Oct 18, 2023
1 parent bc81164 commit 1063a3c
Show file tree
Hide file tree
Showing 8 changed files with 43 additions and 65 deletions.
5 changes: 1 addition & 4 deletions crates/pallet-domains/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -602,9 +602,6 @@ mod pallet {
/// The targetted bad receipt not found which may already pruned by other
/// fraud proof or the fraud proof is submitted to the wrong fork.
BadReceiptNotFound,
/// The targetted bad receipt's parent not found which may already pruned
/// by other fraud proof or the fraud proof is submitted to the wrong fork.
BadReceiptParentNotFound,
/// The genesis receipt is unchallengeable.
ChallengingGenesisReceipt,
/// The descendants of the fraudulent ER is not pruned
Expand Down Expand Up @@ -1615,7 +1612,7 @@ impl<T: Config> Pallet<T> {
FraudProof::InvalidStateTransition(proof) => {
let bad_receipt_parent =
BlockTreeNodes::<T>::get(bad_receipt.parent_domain_block_receipt_hash)
.ok_or(FraudProofError::BadReceiptParentNotFound)?
.ok_or(FraudProofError::ParentReceiptNotFound)?
.execution_receipt;

verify_invalid_state_transition_fraud_proof::<
Expand Down
33 changes: 14 additions & 19 deletions crates/sp-domains/src/fraud_proof.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
use crate::verification::StorageProofVerifier;
use crate::{valued_trie_root, DomainId, ExecutionReceipt, ReceiptHash, SealedBundleHeader};
use hash_db::Hasher;
use parity_scale_codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_consensus_slots::Slot;
use sp_core::storage::StorageKey;
use sp_core::H256;
use sp_domain_digests::AsPredigest;
use sp_runtime::traits::{
BlakeTwo256, Block as BlockT, Hash as HashT, Header as HeaderT, NumberFor,
};
use sp_runtime::Digest;
use sp_runtime::{Digest, DigestItem};
use sp_std::vec::Vec;
use sp_trie::{LayoutV1, StorageProof};
use subspace_runtime_primitives::{AccountId, Balance};
Expand All @@ -28,7 +27,7 @@ type ExecutionReceiptFor<DomainHeader, CBlock, Balance> = ExecutionReceipt<
#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone)]
pub enum ExecutionPhase {
/// Executes the `initialize_block` hook.
InitializeBlock { digest_storage_proof: StorageProof },
InitializeBlock,
/// Executes some extrinsic.
ApplyExtrinsic {
proof_of_inclusion: Vec<Vec<u8>>,
Expand All @@ -45,7 +44,7 @@ impl ExecutionPhase {
match self {
// TODO: Replace `DomainCoreApi_initialize_block_with_post_state_root` with `Core_initalize_block`
// Should be a same issue with https://github.com/paritytech/substrate/pull/10922#issuecomment-1068997467
Self::InitializeBlock { .. } => "DomainCoreApi_initialize_block_with_post_state_root",
Self::InitializeBlock => "DomainCoreApi_initialize_block_with_post_state_root",
Self::ApplyExtrinsic { .. } => "BlockBuilder_apply_extrinsic",
Self::FinalizeBlock => "BlockBuilder_finalize_block",
}
Expand All @@ -58,7 +57,7 @@ impl ExecutionPhase {
/// result of execution reported in [`FraudProof`] is expected or not.
pub fn verifying_method(&self) -> &'static str {
match self {
Self::InitializeBlock { .. } => "DomainCoreApi_initialize_block_with_post_state_root",
Self::InitializeBlock => "DomainCoreApi_initialize_block_with_post_state_root",
Self::ApplyExtrinsic { .. } => "DomainCoreApi_apply_extrinsic_with_post_state_root",
Self::FinalizeBlock => "BlockBuilder_finalize_block",
}
Expand All @@ -70,7 +69,7 @@ impl ExecutionPhase {
execution_result: Vec<u8>,
) -> Result<Header::Hash, VerificationError> {
match self {
Self::InitializeBlock { .. } | Self::ApplyExtrinsic { .. } => {
Self::InitializeBlock | Self::ApplyExtrinsic { .. } => {
let encoded_storage_root = Vec::<u8>::decode(&mut execution_result.as_slice())
.map_err(VerificationError::InitializeBlockOrApplyExtrinsicDecode)?;
Header::Hash::decode(&mut encoded_storage_root.as_slice())
Expand Down Expand Up @@ -98,7 +97,7 @@ impl ExecutionPhase {
return Err(VerificationError::InvalidExecutionTrace);
}
let (pre, post) = match self {
ExecutionPhase::InitializeBlock { .. } => (
ExecutionPhase::InitializeBlock => (
bad_receipt_parent.final_state_root,
bad_receipt.execution_trace[0],
),
Expand Down Expand Up @@ -135,23 +134,19 @@ impl ExecutionPhase {
DomainHeader::Hash: From<H256>,
{
Ok(match self {
ExecutionPhase::InitializeBlock {
digest_storage_proof,
} => {
let digest =
StorageProofVerifier::<DomainHeader::Hashing>::verify_and_get_value::<Digest>(
&bad_receipt.final_state_root,
digest_storage_proof.clone(),
StorageKey(system_digest_final_key()),
)
.map_err(|_| VerificationError::InvalidStorageProof)?;
ExecutionPhase::InitializeBlock => {
let inherent_digests = Digest {
logs: sp_std::vec![DigestItem::consensus_block_info(
bad_receipt.consensus_block_hash,
)],
};

let new_header = DomainHeader::new(
bad_receipt.domain_block_number,
Default::default(),
Default::default(),
bad_receipt_parent.domain_block_hash,
digest,
inherent_digests,
);
new_header.encode()
}
Expand Down
1 change: 1 addition & 0 deletions crates/sp-domains/src/valued_trie_root.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ pub fn generate_proof<Layout: TrieLayout>(input: &[Vec<u8>], index: u32) -> Opti
Some(proof)
}

// TODO: try using `StorageProofVerifier` to verify the proof-of-inclusion
/// Verify the proof-of-inclusion of the `data` at the `index` of the merkle root `root`
pub fn verify_proof<Layout>(
proof: &[Vec<u8>],
Expand Down
11 changes: 1 addition & 10 deletions crates/subspace-fraud-proof/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -431,16 +431,7 @@ async fn execution_proof_creation_and_verification_should_work() {
))],
},
);
let execution_phase = {
let digest_key = sp_domains::fraud_proof::system_digest_final_key();
let digest_storage_proof = alice
.client
.read_proof(header.hash(), &mut [digest_key.as_slice()].into_iter())
.unwrap();
ExecutionPhase::InitializeBlock {
digest_storage_proof,
}
};
let execution_phase = ExecutionPhase::InitializeBlock;
let initialize_block_call_data = new_header.encode();

let prover = ExecutionProver::new(alice.backend.clone(), alice.code_executor.clone());
Expand Down
4 changes: 2 additions & 2 deletions domains/client/domain-operator/src/bundle_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ where
return Ok(None);
};

let digest = Digest {
let inherent_digests = Digest {
logs: vec![DigestItem::consensus_block_info(consensus_block_hash)],
};

Expand All @@ -293,7 +293,7 @@ where
(consensus_block_hash, consensus_block_number),
(parent_hash, parent_number),
preprocess_result,
digest,
inherent_digests,
)
.await?;

Expand Down
14 changes: 10 additions & 4 deletions domains/client/domain-operator/src/domain_block_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ where
(consensus_block_hash, consensus_block_number): (CBlock::Hash, NumberFor<CBlock>),
(parent_hash, parent_number): (Block::Hash, NumberFor<Block>),
preprocess_result: PreprocessResult<Block>,
digests: Digest,
inherent_digests: Digest,
) -> Result<DomainBlockResult<Block, CBlock>, sp_blockchain::Error> {
let PreprocessResult {
extrinsics,
Expand All @@ -294,7 +294,13 @@ where
header_number,
header_hash,
} = self
.build_and_import_block(parent_hash, parent_number, extrinsics, fork_choice, digests)
.build_and_import_block(
parent_hash,
parent_number,
extrinsics,
fork_choice,
inherent_digests,
)
.await?;

tracing::debug!(
Expand Down Expand Up @@ -396,14 +402,14 @@ where
parent_number: NumberFor<Block>,
extrinsics: Vec<Block::Extrinsic>,
fork_choice: ForkChoiceStrategy,
digests: Digest,
inherent_digests: Digest,
) -> Result<DomainBlockBuildResult<Block>, sp_blockchain::Error> {
let block_builder = BlockBuilder::new(
&*self.client,
parent_hash,
parent_number,
RecordProof::No,
digests,
inherent_digests,
&*self.backend,
extrinsics,
)?;
Expand Down
25 changes: 11 additions & 14 deletions domains/client/domain-operator/src/fraud_proof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderBackend;
use sp_core::traits::CodeExecutor;
use sp_core::H256;
use sp_domain_digests::AsPredigest;
use sp_domains::fraud_proof::{
ExecutionPhase, ExtrinsicDigest, FraudProof, InvalidBundlesFraudProof,
InvalidDomainBlockHashProof, InvalidExtrinsicsRootProof, InvalidStateTransitionProof,
Expand All @@ -17,7 +18,7 @@ use sp_domains::fraud_proof::{
};
use sp_domains::{DomainId, DomainsApi};
use sp_runtime::traits::{BlakeTwo256, Block as BlockT, HashingFor, Header as HeaderT, NumberFor};
use sp_runtime::Digest;
use sp_runtime::{Digest, DigestItem};
use sp_trie::{LayoutV1, StorageProof};
use std::marker::PhantomData;
use std::sync::Arc;
Expand Down Expand Up @@ -265,7 +266,11 @@ where

let prover = ExecutionProver::new(self.backend.clone(), self.code_executor.clone());

let digest = self.client.runtime_api().block_digest(block_hash)?;
let inherent_digests = Digest {
logs: vec![DigestItem::consensus_block_info(
local_receipt.consensus_block_hash,
)],
};

let invalid_state_transition_proof = if local_trace_index == 0 {
// `initialize_block` execution proof.
Expand All @@ -274,17 +279,9 @@ where
Default::default(),
Default::default(),
parent_header.hash(),
digest,
inherent_digests,
);
let execution_phase = {
let digest_key = sp_domains::fraud_proof::system_digest_final_key();
let digest_storage_proof = self
.client
.read_proof(block_hash, &mut [digest_key.as_slice()].into_iter())?;
ExecutionPhase::InitializeBlock {
digest_storage_proof,
}
};
let execution_phase = ExecutionPhase::InitializeBlock;
let initialize_block_call_data = new_header.encode();

let proof = prover.prove_execution::<sp_trie::PrefixedMemoryDB<HashingFor<Block>>>(
Expand All @@ -311,7 +308,7 @@ where
parent_header.hash(),
*parent_header.number(),
RecordProof::No,
digest,
inherent_digests,
&*self.backend,
extrinsics,
)?;
Expand Down Expand Up @@ -340,7 +337,7 @@ where
&parent_header,
block_hash,
&prover,
digest,
inherent_digests,
)?;

// TODO: proof should be a CompactProof.
Expand Down
15 changes: 3 additions & 12 deletions domains/client/domain-operator/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use domain_test_service::EcdsaKeyring::{Alice, Bob};
use domain_test_service::Sr25519Keyring::{self, Ferdie};
use domain_test_service::GENESIS_DOMAIN_ID;
use futures::StreamExt;
use sc_client_api::{Backend, BlockBackend, HeaderBackend, ProofProvider};
use sc_client_api::{Backend, BlockBackend, HeaderBackend};
use sc_consensus::SharedBlockImport;
use sc_service::{BasePath, Role};
use sc_transaction_pool_api::error::Error as TxPoolError;
Expand Down Expand Up @@ -841,7 +841,7 @@ async fn test_invalid_state_transition_proof_creation_and_verification(
match mismatch_trace_index {
0 => assert!(matches!(
proof.execution_phase,
ExecutionPhase::InitializeBlock { .. }
ExecutionPhase::InitializeBlock
)),
1 => assert!(matches!(
proof.execution_phase,
Expand Down Expand Up @@ -1285,16 +1285,7 @@ async fn fraud_proof_verification_in_tx_pool_should_work() {
parent_header.hash(),
digest,
);
let execution_phase = {
let digest_key = sp_domains::fraud_proof::system_digest_final_key();
let digest_storage_proof = alice
.client
.read_proof(header.hash(), &mut [digest_key.as_slice()].into_iter())
.unwrap();
ExecutionPhase::InitializeBlock {
digest_storage_proof,
}
};
let execution_phase = ExecutionPhase::InitializeBlock;
let initialize_block_call_data = new_header.encode();

let storage_proof = prover
Expand Down

0 comments on commit 1063a3c

Please sign in to comment.