Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce basic storage proof for the stateless fraud proof #2746

Merged
merged 7 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 13 additions & 12 deletions crates/pallet-domains/src/domain_registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use crate::pallet::{DomainStakingSummary, NextEVMChainId};
use crate::runtime_registry::DomainRuntimeInfo;
use crate::staking::StakingSummary;
use crate::{
BalanceOf, Config, DomainHashingFor, DomainRegistry, ExecutionReceiptOf, HoldIdentifier,
NextDomainId, RuntimeRegistry,
into_complete_raw_genesis, BalanceOf, Config, DomainHashingFor, DomainRegistry,
ExecutionReceiptOf, HoldIdentifier, NextDomainId, RuntimeRegistry,
};
#[cfg(not(feature = "std"))]
use alloc::string::String;
Expand All @@ -26,7 +26,7 @@ use scale_info::TypeInfo;
use sp_core::Get;
use sp_domains::{
derive_domain_block_hash, DomainBundleLimit, DomainId, DomainsDigestItem,
DomainsTransfersTracker, OperatorAllowList, RuntimeId, RuntimeType,
DomainsTransfersTracker, OnDomainInstantiated, OperatorAllowList, RuntimeId, RuntimeType,
};
use sp_runtime::traits::{CheckedAdd, Zero};
use sp_runtime::DigestItem;
Expand Down Expand Up @@ -236,14 +236,14 @@ pub(crate) fn do_instantiate_domain<T: Config>(

let genesis_receipt = {
let state_version = runtime_obj.version.state_version();
let raw_genesis = runtime_obj
.into_complete_raw_genesis::<T>(
domain_id,
domain_runtime_info,
total_issuance,
domain_config.initial_balances.clone(),
)
.map_err(Error::FailedToGenerateRawGenesis)?;
let raw_genesis = into_complete_raw_genesis::<T>(
runtime_obj,
domain_id,
domain_runtime_info,
total_issuance,
domain_config.initial_balances.clone(),
)
.map_err(Error::FailedToGenerateRawGenesis)?;
let state_root = raw_genesis.state_root::<DomainHashingFor<T>>(state_version);
let genesis_block_hash = derive_domain_block_hash::<T::DomainHeader>(
Zero::zero(),
Expand Down Expand Up @@ -293,6 +293,7 @@ pub(crate) fn do_instantiate_domain<T: Config>(
);

import_genesis_receipt::<T>(domain_id, genesis_receipt);
T::OnDomainInstantiated::on_domain_instantiated(domain_id);

frame_system::Pallet::<T>::deposit_log(DigestItem::domain_instantiation(domain_id));

Expand Down Expand Up @@ -347,13 +348,13 @@ pub(crate) fn calculate_max_bundle_weight_and_size(
#[cfg(test)]
mod tests {
use super::*;
use crate::runtime_registry::RuntimeObject;
use crate::tests::{new_test_ext, Test};
use domain_runtime_primitives::{AccountId20, AccountId20Converter};
use frame_support::traits::Currency;
use frame_support::{assert_err, assert_ok};
use hex_literal::hex;
use sp_domains::storage::RawGenesis;
use sp_domains::RuntimeObject;
use sp_runtime::traits::Convert;
use sp_std::vec;
use sp_version::RuntimeVersion;
Expand Down
32 changes: 18 additions & 14 deletions crates/pallet-domains/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ extern crate alloc;
use crate::block_tree::verify_execution_receipt;
use crate::bundle_storage_fund::storage_fund_account;
use crate::domain_registry::Error as DomainRegistryError;
use crate::runtime_registry::into_complete_raw_genesis;
use crate::staking::OperatorStatus;
use crate::staking_epoch::EpochTransitionResult;
use crate::weights::WeightInfo;
Expand Down Expand Up @@ -169,8 +170,7 @@ mod pallet {
};
use crate::runtime_registry::{
do_register_runtime, do_schedule_runtime_upgrade, do_upgrade_runtimes,
register_runtime_at_genesis, Error as RuntimeRegistryError, RuntimeObject,
ScheduledRuntimeUpgrade,
register_runtime_at_genesis, Error as RuntimeRegistryError, ScheduledRuntimeUpgrade,
};
#[cfg(not(feature = "runtime-benchmarks"))]
use crate::staking::do_reward_operators;
Expand Down Expand Up @@ -207,8 +207,8 @@ mod pallet {
use sp_domains::bundle_producer_election::ProofOfElectionError;
use sp_domains::{
BundleDigest, ConfirmedDomainBlock, DomainBundleSubmitted, DomainId,
DomainsTransfersTracker, EpochIndex, GenesisDomain, OperatorAllowList, OperatorId,
OperatorPublicKey, RuntimeId, RuntimeType,
DomainsTransfersTracker, EpochIndex, GenesisDomain, OnDomainInstantiated,
OperatorAllowList, OperatorId, OperatorPublicKey, RuntimeId, RuntimeObject, RuntimeType,
};
use sp_domains_fraud_proof::fraud_proof::FraudProof;
use sp_domains_fraud_proof::InvalidTransactionCode;
Expand Down Expand Up @@ -389,6 +389,9 @@ mod pallet {

/// Post hook to notify accepted domain bundles in previous block.
type DomainBundleSubmitted: DomainBundleSubmitted;

/// A hook to call after a domain is instantiated
type OnDomainInstantiated: OnDomainInstantiated;
}

#[pallet::pallet]
Expand All @@ -398,7 +401,7 @@ mod pallet {

/// Bundles submitted successfully in current block.
#[pallet::storage]
pub(super) type SuccessfulBundles<T> = StorageMap<_, Identity, DomainId, Vec<H256>, ValueQuery>;
pub type SuccessfulBundles<T> = StorageMap<_, Identity, DomainId, Vec<H256>, ValueQuery>;

/// Fraud proofs submitted successfully in current block.
#[pallet::storage]
Expand All @@ -425,7 +428,7 @@ mod pallet {
pub(super) type NextEVMChainId<T> = StorageValue<_, EVMChainId, ValueQuery, StartingEVMChainId>;

#[pallet::storage]
pub(super) type RuntimeRegistry<T: Config> =
pub type RuntimeRegistry<T: Config> =
StorageMap<_, Identity, RuntimeId, RuntimeObject<BlockNumberFor<T>, T::Hash>, OptionQuery>;

#[pallet::storage]
Expand Down Expand Up @@ -528,6 +531,7 @@ mod pallet {

/// Stores the next domain id.
#[pallet::storage]
#[pallet::getter(fn next_domain_id)]
pub(super) type NextDomainId<T> = StorageValue<_, DomainId, ValueQuery>;

/// The domain registry
Expand Down Expand Up @@ -1661,14 +1665,14 @@ impl<T: Config> Pallet<T> {
let runtime_object = RuntimeRegistry::<T>::get(domain_obj.domain_config.runtime_id)?;
let runtime_type = runtime_object.runtime_type.clone();
let total_issuance = domain_obj.domain_config.total_issuance()?;
let raw_genesis = runtime_object
.into_complete_raw_genesis::<T>(
domain_id,
domain_obj.domain_runtime_info,
total_issuance,
domain_obj.domain_config.initial_balances,
)
.ok()?;
let raw_genesis = into_complete_raw_genesis::<T>(
runtime_object,
domain_id,
domain_obj.domain_runtime_info,
total_issuance,
domain_obj.domain_config.initial_balances,
)
.ok()?;
Some((
DomainInstanceData {
runtime_type,
Expand Down
122 changes: 52 additions & 70 deletions crates/pallet-domains/src/runtime_registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use scale_info::TypeInfo;
use sp_core::crypto::AccountId32;
use sp_core::Hasher;
use sp_domains::storage::{RawGenesis, StorageData, StorageKey};
use sp_domains::{DomainId, DomainsDigestItem, RuntimeId, RuntimeType};
use sp_domains::{DomainId, DomainsDigestItem, RuntimeId, RuntimeObject, RuntimeType};
use sp_runtime::traits::{CheckedAdd, Get, Zero};
use sp_runtime::DigestItem;
use sp_std::vec;
Expand All @@ -39,20 +39,6 @@ pub enum Error {
InvalidAccountIdType,
}

#[derive(TypeInfo, Debug, Encode, Decode, Clone, PartialEq, Eq)]
pub struct RuntimeObject<Number, Hash> {
pub runtime_name: String,
pub runtime_type: RuntimeType,
pub runtime_upgrades: u32,
pub hash: Hash,
// The raw gensis storage that contains the runtime code.
// NOTE: don't use this field directly but `into_complete_raw_genesis` instead
pub raw_genesis: RawGenesis,
pub version: RuntimeVersion,
pub created_at: Number,
pub updated_at: Number,
}

/// Domain runtime specific information to create domain raw genesis.
#[derive(TypeInfo, Debug, Encode, Decode, Clone, PartialEq, Eq, Copy)]
pub enum DomainRuntimeInfo {
Expand Down Expand Up @@ -91,63 +77,59 @@ fn derive_initial_balances_storages<T: Config, AccountId: Encode>(
initial_storages
}

impl<Number, Hash> RuntimeObject<Number, Hash> {
// Return a complete raw genesis with runtime code and domain id set properly
pub fn into_complete_raw_genesis<T: Config>(
self,
domain_id: DomainId,
domain_runtime_info: DomainRuntimeInfo,
total_issuance: BalanceOf<T>,
initial_balances: Vec<(MultiAccountId, BalanceOf<T>)>,
) -> Result<RawGenesis, Error> {
let RuntimeObject {
mut raw_genesis, ..
} = self;
raw_genesis.set_domain_id(domain_id);
match domain_runtime_info {
DomainRuntimeInfo::EVM { chain_id } => {
raw_genesis.set_evm_chain_id(chain_id);
let initial_balances = initial_balances.into_iter().try_fold(
Vec::<(AccountId20, BalanceOf<T>)>::new(),
|mut balances, (account_id, balance)| {
let account_id =
domain_runtime_primitives::AccountId20Converter::try_convert_back(
account_id,
)
.ok_or(Error::InvalidAccountIdType)?;

balances.push((account_id, balance));
Ok(balances)
},
)?;
raw_genesis.set_top_storages(derive_initial_balances_storages::<T, _>(
total_issuance,
initial_balances,
));
}
DomainRuntimeInfo::AutoId => {
let initial_balances = initial_balances.into_iter().try_fold(
Vec::<(AccountId32, BalanceOf<T>)>::new(),
|mut balances, (account_id, balance)| {
let account_id =
domain_runtime_primitives::AccountIdConverter::try_convert_back(
account_id,
)
// Return a complete raw genesis with runtime code and domain id set properly
pub fn into_complete_raw_genesis<T: Config>(
runtime_obj: RuntimeObject<BlockNumberFor<T>, T::Hash>,
domain_id: DomainId,
domain_runtime_info: DomainRuntimeInfo,
total_issuance: BalanceOf<T>,
initial_balances: Vec<(MultiAccountId, BalanceOf<T>)>,
) -> Result<RawGenesis, Error> {
let RuntimeObject {
mut raw_genesis, ..
} = runtime_obj;
raw_genesis.set_domain_id(domain_id);
match domain_runtime_info {
DomainRuntimeInfo::EVM { chain_id } => {
raw_genesis.set_evm_chain_id(chain_id);
let initial_balances = initial_balances.into_iter().try_fold(
Vec::<(AccountId20, BalanceOf<T>)>::new(),
|mut balances, (account_id, balance)| {
let account_id =
domain_runtime_primitives::AccountId20Converter::try_convert_back(
account_id,
)
.ok_or(Error::InvalidAccountIdType)?;

balances.push((account_id, balance));
Ok(balances)
},
)?;
raw_genesis.set_top_storages(derive_initial_balances_storages::<T, _>(
total_issuance,
initial_balances,
));
}
DomainRuntimeInfo::AutoId => {
let initial_balances = initial_balances.into_iter().try_fold(
Vec::<(AccountId32, BalanceOf<T>)>::new(),
|mut balances, (account_id, balance)| {
let account_id =
domain_runtime_primitives::AccountIdConverter::try_convert_back(account_id)
.ok_or(Error::InvalidAccountIdType)?;

balances.push((account_id, balance));
Ok(balances)
},
)?;
raw_genesis.set_top_storages(derive_initial_balances_storages::<T, _>(
total_issuance,
initial_balances,
));
}
balances.push((account_id, balance));
Ok(balances)
},
)?;
raw_genesis.set_top_storages(derive_initial_balances_storages::<T, _>(
total_issuance,
initial_balances,
));
}

Ok(raw_genesis)
}

Ok(raw_genesis)
}

#[derive(TypeInfo, Debug, Encode, Decode, Clone, PartialEq, Eq)]
Expand Down Expand Up @@ -318,7 +300,7 @@ pub(crate) fn do_upgrade_runtimes<T: Config>(at: BlockNumberFor<T>) {
#[cfg(test)]
mod tests {
use crate::pallet::{NextRuntimeId, RuntimeRegistry, ScheduledRuntimeUpgrades};
use crate::runtime_registry::{Error as RuntimeRegistryError, RuntimeObject};
use crate::runtime_registry::Error as RuntimeRegistryError;
use crate::tests::{
new_test_ext, DomainRuntimeUpgradeDelay, Domains, ReadRuntimeVersion, System, Test,
};
Expand All @@ -328,7 +310,7 @@ mod tests {
use frame_support::dispatch::RawOrigin;
use frame_support::traits::OnInitialize;
use sp_domains::storage::RawGenesis;
use sp_domains::{DomainsDigestItem, RuntimeId, RuntimeType};
use sp_domains::{DomainsDigestItem, RuntimeId, RuntimeObject, RuntimeType};
use sp_runtime::traits::BlockNumberProvider;
use sp_runtime::{Digest, DispatchError};
use sp_version::RuntimeVersion;
Expand Down
3 changes: 2 additions & 1 deletion crates/pallet-domains/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ impl pallet_domains::Config for Test {
type BundleLongevity = BundleLongevity;
type ConsensusSlotProbability = SlotProbability;
type DomainBundleSubmitted = ();
type OnDomainInstantiated = ();
type Balance = Balance;
}

Expand Down Expand Up @@ -1280,7 +1281,7 @@ fn test_invalid_domain_block_hash_fraud_proof() {
fn generate_invalid_domain_block_hash_fraud_proof<T: Config>(
digest: Digest,
) -> (T::Hash, StorageProof) {
let digest_storage_key = sp_domains_fraud_proof::fraud_proof::system_digest_final_key();
let digest_storage_key = sp_domains::system_digest_final_key();
let mut root = T::Hash::default();
let mut mdb = PrefixedMemoryDB::<T::Hashing>::default();
{
Expand Down
Loading
Loading