#![cfg_attr(not(feature = "std"), no_std)] #![recursion_limit = "512"] use crate::storage_utils::MessageStatusEnum; use alloy_sol_types::{sol, SolValue}; use ark_std::format; use avail_base::{MemoryTemporaryStorage, ProvidePostInherent}; use avail_core::data_proof::{tx_uid, AddressedMessage, Message, MessageType}; use sp1_verifier::{Groth16Verifier, GROTH16_VK_BYTES}; use codec::Compact; use frame_support::{ pallet_prelude::*, traits::{Currency, ExistenceRequirement, UnixTime}, PalletId, }; use sp_core::H256; use sp_runtime::SaturatedConversion; use sp_std::{vec, vec::Vec}; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; pub mod constants; #[cfg(test)] mod mock; mod state; mod storage_utils; #[cfg(test)] mod tests; mod weights; pub use pallet::*; sol! { #[derive(Debug)] struct ProofOutputs { bytes32 executionStateRoot; bytes32 newHeader; bytes32 nextSyncCommitteeHash; uint256 newHead; bytes32 prevHeader; uint256 prevHead; bytes32 syncCommitteeHash; // Hash of the current sync committee that signed the previous update. bytes32 startSyncCommitteeHash; } } pub type ProofInput = BoundedVec>; pub type PublicValuesInput = BoundedVec>; pub type ValidProof = BoundedVec>, ConstU32<32>>; // Avail asset is supported for now pub const SUPPORTED_ASSET_ID: H256 = H256::zero(); pub const FAILED_SEND_MSG_ID: &[u8] = b"vector:failed_send_msg_txs"; pub const LOG_TARGET: &str = "runtime::vector"; pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; #[frame_support::pallet] pub mod pallet { use ethabi::Token::Uint; use frame_support::dispatch::GetDispatchInfo; use frame_support::traits::{LockableCurrency, UnfilteredDispatchable}; use frame_support::{pallet_prelude::ValueQuery, DefaultNoBound}; use frame_system::pallet_prelude::*; use primitive_types::H160; use primitive_types::{H256, U256}; use sp_io::hashing::keccak_256; use sp_runtime::traits::AccountIdConversion; pub use weights::WeightInfo; use crate::state::Configuration; use crate::storage_utils::{get_storage_root, get_storage_value}; use super::*; #[pallet::error] pub enum Error { ConfigurationNotSet, SlotBehindHead, VerificationFailed, HeaderRootAlreadySet, StateRootAlreadySet, MessageAlreadyExecuted, WrongDestinationChain, UnsupportedOriginChain, BroadcasterSourceChainNotSet, SourceChainFrozen, CannotGetStorageRoot, CannotGetStorageValue, InvalidMessageHash, CannotDecodeData, CannotDecodeDestinationAccountId, /// Given AssetId is not supported AssetNotSupported, /// Given inputs for the selected MessageType are invalid InvalidBridgeInputs, /// Domain is not supported DomainNotSupported, /// Inherent call outside of block execution context. BadContext, /// Invalid FailedIndices InvalidFailedIndices, /// Invalid updater UpdaterMisMatch, /// Cannot get current message id CurrentMessageIdNotFound, /// Public values decoding error. CannotDecodePublicValue, /// Sync committee hash is already set for given period. SyncCommitteeHashAlreadySet, /// Emit when start sync committee does not match. SyncCommitteeStartMismatch, /// Mock is unusable: either it is not enabled, or the source chain is Ethereum /// mainnet, where mock must never be reachable. MockError, /// The proof's previous header does not match the header stored for that slot, /// so the update does not extend the chain this pallet has already accepted. PreviousHeaderMismatch, /// A slot in the proof output does not fit in a u64. The values are `uint256` on the /// wire and are only bounded by the circuit, so they must be range-checked here /// rather than narrowed with a panicking conversion. SlotOutOfRange, } #[pallet::event] #[pallet::generate_deposit(pub (super) fn deposit_event)] pub enum Event { /// Emit event once the head is updated. HeadUpdated { slot: u64, finalization_root: H256, execution_state_root: H256, }, /// Emit when new updater is set. BroadcasterUpdated { old: H256, new: H256, domain: u32 }, /// Emit when message gets executed. MessageExecuted { from: H256, to: H256, message_id: u64, message_root: H256, }, /// Emit if source chain gets frozen. SourceChainFrozen { source_chain_id: u32, frozen: bool }, /// Emit when message is submitted. MessageSubmitted { from: T::AccountId, to: H256, message_type: MessageType, destination_domain: u32, message_id: u64, }, /// Emit whitelisted domains that are updated. WhitelistedDomainsUpdated, /// Emit when configuration is updated. ConfigurationUpdated { slots_per_period: u64, finality_threshold: u16, }, /// Emit new updater. NewUpdater { old: H256, new: H256 }, /// Emit new SP1 verification key. NewSP1VerificationKey { old: H256, new: H256 }, /// Emit when new sync committee is updated. SyncCommitteeHashUpdated { period: u64, hash: H256 }, /// Emit when mocks are enabled or disabled MockEnabled { value: bool }, } /// Storage for a head updates. #[pallet::storage] #[pallet::getter(fn head)] pub type Head = StorageValue<_, u64, ValueQuery>; /// Maps from a slot to a block header root. #[pallet::storage] #[pallet::getter(fn headers)] pub type Headers = StorageMap<_, Identity, u64, H256, ValueQuery>; /// Maps slot to the timestamp of when the headers mapping was updated with slot as a key #[pallet::storage] pub type Timestamps = StorageMap<_, Identity, u64, u64, ValueQuery>; /// Maps from a slot to the current finalized ethereum execution state root. #[pallet::storage] pub type ExecutionStateRoots = StorageMap<_, Identity, u64, H256, ValueQuery>; /// Storage for a config of finality threshold and slots per period. #[pallet::storage] pub type ConfigurationStorage = StorageValue<_, Configuration, ValueQuery>; /// Maps status of the message to the message root. #[pallet::storage] pub type MessageStatus = StorageMap<_, Identity, H256, MessageStatusEnum, ValueQuery>; /// Mapping between source chainId and the address of the broadcaster on that chain. #[pallet::storage] pub type Broadcasters = StorageMap<_, Identity, u32, H256, ValueQuery>; /// Flags source chain to be frozen. #[pallet::storage] pub type SourceChainFrozen = StorageMap<_, Identity, u32, bool, ValueQuery>; /// List of permitted domains. #[pallet::storage] pub type WhitelistedDomains = StorageValue<_, BoundedVec>, ValueQuery>; /// Genesis validator root, used to check initialization. #[pallet::storage] #[pallet::getter(fn genesis_validator_root)] pub type GenesisValidatorRoot = StorageValue<_, H256, ValueQuery>; /// Genesis timestamp, used to check initialization. #[pallet::storage] #[pallet::getter(fn genesis_timestamp)] pub type GenesisTimestamp = StorageValue<_, u64, ValueQuery>; /// Seconds per slot, used to check initialization. #[pallet::storage] #[pallet::getter(fn seconds_per_slot)] pub type SecondsPerSlot = StorageValue<_, u64, ValueQuery>; /// Source chain id, used to check initialization. #[pallet::storage] #[pallet::getter(fn source_chain_id)] pub type SourceChainId = StorageValue<_, u64, ValueQuery>; /// Updater that can submit updates #[pallet::storage] #[pallet::getter(fn updater)] pub type Updater = StorageValue<_, H256, ValueQuery>; /// Maps from a period to the the sync committee hash. #[pallet::storage] #[pallet::getter(fn sync_committee_hashes)] pub type SyncCommitteeHashes = StorageMap<_, Identity, u64, H256, ValueQuery>; /// SP1 program verification key. #[pallet::storage] #[pallet::getter(fn sp1_verification_key)] pub type SP1VerificationKey = StorageValue<_, H256, ValueQuery>; /// Enable mock functions #[pallet::storage] #[pallet::getter(fn verification_disabled)] pub type MockEnabled = StorageValue<_, bool, ValueQuery>; /// Default implementations of [`DefaultConfig`], which can be used to implement [`Config`]. pub mod config_preludes { use super::*; use frame_support::derive_impl; use frame_support::parameter_types; use frame_support::traits::ConstU64; parameter_types! { pub const BridgePalletId: PalletId = PalletId(*b"avl/brdg"); } /// Provides a viable default config that can be used with /// [`derive_impl`](`frame_support::derive_impl`) to derive a testing pallet config /// based on this one. pub struct TestDefaultConfig; #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig, no_aggregated_types )] impl frame_system::DefaultConfig for TestDefaultConfig {} #[frame_support::register_default_impl(TestDefaultConfig)] impl DefaultConfig for TestDefaultConfig { type WeightInfo = (); type MessageMappingStorageIndex = ConstU64<1>; type AvailDomain = ConstU32<1>; #[inject_runtime_type] type RuntimeEvent = (); #[inject_runtime_type] type RuntimeCall = (); type PalletId = BridgePalletId; } } #[pallet::config(with_default)] pub trait Config: frame_system::Config { /// Because this pallet emits events, it depends on the runtime's definition of an event. #[pallet::no_default_bounds] type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// Because this pallet has dispatchables, it depends on the runtime's definition of a call. #[pallet::no_default_bounds] type RuntimeCall: Parameter + UnfilteredDispatchable + GetDispatchInfo; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; /// Currency type for this pallet. #[pallet::no_default] type Currency: LockableCurrency>; /// Dependency that can provide current time. #[pallet::no_default] type TimeProvider: UnixTime; /// The index of the `messages` mapping in contract. /// This is mandatory when calling execute messages via storage proofs. #[pallet::constant] type MessageMappingStorageIndex: Get; /// Bridge's pallet id, used for deriving its sovereign account ID. #[pallet::constant] type PalletId: Get; /// Unique value associated with Avail Network. Used to distinguish messages between Avail and non-Avail networks. #[pallet::constant] type AvailDomain: Get; } #[pallet::genesis_config] #[derive(DefaultNoBound)] pub struct GenesisConfig { pub slots_per_period: u64, pub finality_threshold: u16, pub period: u64, pub broadcaster: H256, pub broadcaster_domain: u32, pub whitelisted_domains: Vec, pub genesis_validator_root: H256, pub genesis_time: u64, pub seconds_per_slot: u64, pub source_chain_id: u64, /// Slot the SP1 light client starts tracking from. Must be paired with `header` /// and `sync_committee_hash`. pub head: u64, /// Beacon header root for `head`. `fulfill` binds every update to the header already /// stored for its anchor slot, so a chain starting mid-history without this could /// never accept a first update. pub header: H256, /// Sync committee hash for `head`'s period. `fulfill` checks the proof's /// `startSyncCommitteeHash` against this, so it is the second half of what a fresh /// chain needs; without it genesis leaves the chain unable to sync. pub sync_committee_hash: H256, pub _phantom: PhantomData, } #[pallet::genesis_build] impl BuildGenesisConfig for GenesisConfig { fn build(&self) { // Preconfigure init data >::put(Configuration { slots_per_period: self.slots_per_period, finality_threshold: self.finality_threshold, }); let mut domains = self.whitelisted_domains.clone(); // Whitelisted domains sanitization. domains.sort(); domains.dedup(); let domains = BoundedVec::try_from(domains).expect("Cannot have more than 10_000 domains."); WhitelistedDomains::::put(domains); Broadcasters::::set(self.broadcaster_domain, self.broadcaster); GenesisValidatorRoot::::set(self.genesis_validator_root); GenesisTimestamp::::set(self.genesis_time); SecondsPerSlot::::set(self.seconds_per_slot); SourceChainId::::set(self.source_chain_id); if self.head != 0 { assert!( self.header != H256::zero(), "Vector genesis sets a non-zero head but no header; `fulfill` would be permanently blocked." ); assert!( self.sync_committee_hash != H256::zero(), "Vector genesis sets a non-zero head but no sync committee hash; `fulfill` would reject every update." ); assert!( self.slots_per_period != 0, "Vector genesis needs a non-zero slots_per_period to derive the head's period." ); let head_period = self.head / self.slots_per_period; Head::::set(self.head); Headers::::insert(self.head, self.header); SyncCommitteeHashes::::insert(head_period, self.sync_committee_hash); } else { assert!( self.header == H256::zero() && self.sync_committee_hash == H256::zero(), "Vector genesis supplies anchor state but no head; `fulfill` would reject every update." ); } } } #[pallet::pallet] pub struct Pallet(_); #[pallet::hooks] impl Hooks> for Pallet { fn on_initialize(_n: BlockNumberFor) -> Weight { if let Some(failed_txs) = MemoryTemporaryStorage::take::>>(FAILED_SEND_MSG_ID) { log::trace!(target: LOG_TARGET, "Failed Txs cleaned: {failed_txs:?}"); } Weight::zero() } } #[pallet::call] impl Pallet where [u8; 32]: From, { /// Executes message if a valid proofs are provided for the supported message type, assets and domains. #[pallet::call_index(1)] #[pallet::weight({ match addr_message.message { Message::ArbitraryMessage(ref data) => T::WeightInfo::execute_arbitrary_message(data.len() as u32), Message::FungibleToken {..} => T::WeightInfo::execute_fungible_token(), } })] pub fn execute( origin: OriginFor, #[pallet::compact] slot: u64, addr_message: AddressedMessage, account_proof: ValidProof, storage_proof: ValidProof, ) -> DispatchResultWithPostInfo { ensure_signed(origin)?; let encoded_data = addr_message.clone().abi_encode(); let message_root = H256(keccak_256(encoded_data.as_slice())); Self::check_preconditions(&addr_message, message_root)?; ensure!( !SourceChainFrozen::::get(addr_message.origin_domain), Error::::SourceChainFrozen ); let root = ExecutionStateRoots::::get(slot); let broadcaster = Broadcasters::::get(addr_message.origin_domain); // extract contract address let contract_broadcaster_address = H160::from_slice(broadcaster[..20].as_ref()); let account_proof_vec = account_proof .iter() .map(|inner_bounded_vec| inner_bounded_vec.iter().copied().collect()) .collect(); let storage_root = get_storage_root(account_proof_vec, contract_broadcaster_address, root) .map_err(|_| Error::::CannotGetStorageRoot)?; let message_id = Uint(U256::from(addr_message.id)); let mm_idx = Uint(U256::from(T::MessageMappingStorageIndex::get())); let slot_key = H256(keccak_256(ethabi::encode(&[message_id, mm_idx]).as_slice())); let storage_proof_vec = storage_proof .iter() .map(|inner_bounded_vec| inner_bounded_vec.iter().copied().collect()) .collect(); let slot_value = get_storage_value(slot_key, storage_root, storage_proof_vec) .map_err(|_| Error::::CannotGetStorageValue)?; ensure!(slot_value == message_root, Error::::InvalidMessageHash); if let Message::FungibleToken { asset_id, amount } = &addr_message.message { ensure!( SUPPORTED_ASSET_ID == *asset_id, Error::::AssetNotSupported ); let destination_account_id = T::AccountId::decode(&mut &addr_message.to.encode()[..]) .map_err(|_| Error::::CannotDecodeDestinationAccountId)?; T::Currency::transfer( &Self::account_id(), &destination_account_id, (*amount).saturated_into(), ExistenceRequirement::AllowDeath, )?; } MessageStatus::::set(message_root, MessageStatusEnum::ExecutionSucceeded); Self::deposit_event(Event::::MessageExecuted { from: addr_message.from, to: addr_message.to, message_id: addr_message.id, message_root, }); Ok(().into()) } /// source_chain_froze froze source chain and prevent messages to be executed. // // Test names: source_chain_froze_works_with_root(), source_chain_froze_does_not_work_with_non_root() #[pallet::call_index(2)] #[pallet::weight(T::WeightInfo::source_chain_froze())] pub fn source_chain_froze( origin: OriginFor, #[pallet::compact] source_chain_id: u32, frozen: bool, ) -> DispatchResult { ensure_root(origin)?; SourceChainFrozen::::set(source_chain_id, frozen); Self::deposit_event(Event::::SourceChainFrozen { source_chain_id, frozen, }); Ok(()) } /// send_message sends a message from an origin chain to the destination chain. // // Test names: // send_message_fungible_token_works(), send_message_fungible_token_doesnt_accept_data(), // send_message_fungible_token_doesnt_accept_empty_asset_id(), send_message_fungible_token_doesnt_accept_empty_value(), // send_message_arbitrary_message_works(), send_message_arbitrary_message_doesnt_accept_value(), // send_message_arbitrary_message_doesnt_accept_asset_id(), send_message_arbitrary_message_doesnt_accept_empty_data() #[pallet::call_index(3)] #[pallet::weight({ match message { Message::ArbitraryMessage(ref data) => T::WeightInfo::send_message_arbitrary_message(data.len() as u32), Message::FungibleToken{..} => T::WeightInfo::send_message_fungible_token(), } })] pub fn send_message( origin: OriginFor, message: Message, to: H256, #[pallet::compact] domain: u32, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; let dispatch = Self::do_send_message(who, message, to, domain); if dispatch.is_err() { let _ = MemoryTemporaryStorage::update::>, _>( FAILED_SEND_MSG_ID.to_vec(), |failed| { let tx_idx_result = >::extrinsic_index(); // this should never happen and we can just log warn if tx_idx_result.is_none() { log::warn!(target: LOG_TARGET, "Transaction index is none!"); } let tx_idx = tx_idx_result.unwrap_or_default(); failed.push(tx_idx.into()); log::trace!(target: LOG_TARGET, "Send Message failed txs: {failed:?}"); }, ); } dispatch } /// set_broadcaster sets the broadcaster address of the message from the origin chain. // // Test names: set_broadcaster_works_with_root(), set_broadcaster_does_not_work_with_non_root() #[pallet::call_index(5)] #[pallet::weight(T::WeightInfo::set_broadcaster())] pub fn set_broadcaster( origin: OriginFor, #[pallet::compact] broadcaster_domain: u32, broadcaster: H256, ) -> DispatchResult { ensure_root(origin)?; let old_bc = Broadcasters::::get(broadcaster_domain); Broadcasters::::set(broadcaster_domain, broadcaster); Self::deposit_event(Event::BroadcasterUpdated { old: old_bc, new: broadcaster, domain: broadcaster_domain, }); Ok(()) } /// The set_whitelisted_domains function allows the root (administrator) to set the whitelisted domains. It is a /// privileged function intended for administrative purposes, used to manage a list of permitted domains. // // Test names: set_whitelisted_domains_works_with_root(), set_whitelisted_domains_does_not_work_with_non_root() #[pallet::call_index(6)] #[pallet::weight(T::WeightInfo::set_whitelisted_domains())] pub fn set_whitelisted_domains( origin: OriginFor, value: BoundedVec>, ) -> DispatchResult { ensure_root(origin)?; WhitelistedDomains::::put(value); Self::deposit_event(Event::WhitelistedDomainsUpdated); Ok(()) } /// The set_configuration function allows the root (administrator) to set the configuration. It is a /// privileged function intended for administrative purposes, used to manage slots_per_period and finality_threshold values. // // Test names: set_configuration_works_with_root(), set_configuration_does_not_work_with_non_root() #[pallet::call_index(7)] #[pallet::weight(T::WeightInfo::set_configuration())] pub fn set_configuration(origin: OriginFor, value: Configuration) -> DispatchResult { ensure_root(origin)?; ConfigurationStorage::::put(value); Self::deposit_event(Event::ConfigurationUpdated { slots_per_period: value.slots_per_period, finality_threshold: value.finality_threshold, }); Ok(()) } #[pallet::call_index(11)] #[pallet::weight(( T::WeightInfo::failed_tx_index(0u32), DispatchClass::Mandatory ))] pub fn failed_send_message_txs( origin: OriginFor, failed_txs: Vec>, ) -> DispatchResult { ensure_none(origin)?; let local_failed_txs = MemoryTemporaryStorage::get::>>(FAILED_SEND_MSG_ID) .unwrap_or_default(); ensure!( local_failed_txs == failed_txs, Error::::InvalidFailedIndices ); Ok(()) } #[pallet::call_index(12)] #[pallet::weight(T::WeightInfo::set_updater())] pub fn set_updater(origin: OriginFor, updater: H256) -> DispatchResult { ensure_root(origin)?; let old = Updater::::get(); Updater::::set(updater); Self::deposit_event(Event::::NewUpdater { old, new: updater }); Ok(()) } /// The entrypoint for fulfill a call. /// proof Input proof value. /// public_values Input public values. #[pallet::call_index(13)] #[pallet::weight(T::WeightInfo::fulfill())] pub fn fulfill( origin: OriginFor, proof: ProofInput, public_values: PublicValuesInput, ) -> DispatchResultWithPostInfo { let sender: [u8; 32] = ensure_signed(origin)?.into(); let updater = Updater::::get(); // ensure sender is preconfigured ensure!(H256(sender) == updater, Error::::UpdaterMisMatch); let proof_outputs: ProofOutputs = SolValue::abi_decode(&public_values, true) .map_err(|_| Error::::CannotDecodePublicValue)?; let head = Head::::get(); let new_head: u64 = proof_outputs .newHead .try_into() .map_err(|_| Error::::SlotOutOfRange)?; ensure!(new_head > head, Error::::SlotBehindHead); let config = ConfigurationStorage::::get(); let current_period = head .checked_div(config.slots_per_period) .ok_or(Error::::ConfigurationNotSet)?; let current_sync_committee_hash = SyncCommitteeHashes::::get(current_period); // The "start" sync committee hash is the hash of the sync committee that should sign the next update. ensure!( current_sync_committee_hash == H256::from(proof_outputs.startSyncCommitteeHash.0), Error::::SyncCommitteeStartMismatch ); let sp1_vk = SP1VerificationKey::::get(); let is_valid = Groth16Verifier::verify( &proof, &public_values, &format!("{:?}", sp1_vk), &GROTH16_VK_BYTES, ); ensure!(is_valid.is_ok(), Error::::VerificationFailed); // The circuit derives `prevHeader`/`prevHead` from the prover-supplied anchor store, // so the proof alone does not tie the update to this pallet's state. Binding the // anchor to a header we already stored is what makes `Headers` a chain rather than a // set of unrelated roots, and `execute` authorizes messages against those roots. let prev_head: u64 = proof_outputs .prevHead .try_into() .map_err(|_| Error::::SlotOutOfRange)?; let prev_header = Headers::::try_get(prev_head).map_err(|_| Error::::PreviousHeaderMismatch)?; ensure!( prev_header == H256::from(proof_outputs.prevHeader.0), Error::::PreviousHeaderMismatch ); Head::::set(new_head); let header = Headers::::get(new_head); ensure!(header == H256::zero(), Error::::HeaderRootAlreadySet); let new_header = H256::from(proof_outputs.newHeader.0); let execution_state_root = ExecutionStateRoots::::get(new_head); ensure!( execution_state_root == H256::zero(), Error::::StateRootAlreadySet ); let new_execution_state_root = H256::from(proof_outputs.executionStateRoot.0); Headers::::insert(new_head, new_header); ExecutionStateRoots::::insert(new_head, new_execution_state_root); Self::deposit_event(Event::HeadUpdated { slot: new_head, finalization_root: new_header, execution_state_root: new_execution_state_root, }); let period = new_head .checked_div(config.slots_per_period) .ok_or(Error::::ConfigurationNotSet)?; // If the sync committee for the period is not set, set it. // This can happen if the light client was very behind and had a lot of updates // and only the last sync committee is stored, not the intermediate ones for every period and may have gaps in periods. if SyncCommitteeHashes::::get(period) == H256::zero() { let sync_committee_hash = H256::from(proof_outputs.syncCommitteeHash.0); SyncCommitteeHashes::::set(period, sync_committee_hash); Self::deposit_event(Event::SyncCommitteeHashUpdated { period, hash: sync_committee_hash, }); } // Update next sync committee hash only if it is not set let next_sync_committee_hash = H256::from(proof_outputs.nextSyncCommitteeHash.0); if next_sync_committee_hash != H256::zero() { let next_period = period + 1; let sync_committee_hash = SyncCommitteeHashes::::get(next_period); if sync_committee_hash != next_sync_committee_hash { ensure!( sync_committee_hash == H256::zero(), Error::::SyncCommitteeHashAlreadySet ); SyncCommitteeHashes::::set(next_period, next_sync_committee_hash); Self::deposit_event(Event::SyncCommitteeHashUpdated { period: next_period, hash: next_sync_committee_hash, }); } } Timestamps::::insert(new_head, T::TimeProvider::now().as_secs()); Ok(().into()) } #[pallet::call_index(14)] #[pallet::weight(T::WeightInfo::set_sp1_verification_key())] pub fn set_sp1_verification_key(origin: OriginFor, sp1_vk: H256) -> DispatchResult { ensure_root(origin)?; let old_vk = SP1VerificationKey::::get(); SP1VerificationKey::::put(sp1_vk); Self::deposit_event(Event::NewSP1VerificationKey { old: old_vk, new: sp1_vk, }); Ok(()) } #[pallet::call_index(15)] #[pallet::weight(T::WeightInfo::set_sync_committee_hash())] pub fn set_sync_committee_hash( origin: OriginFor, period: u64, hash: H256, ) -> DispatchResult { ensure_root(origin)?; SyncCommitteeHashes::::insert(period, hash); Self::deposit_event(Event::SyncCommitteeHashUpdated { period, hash }); Ok(()) } #[pallet::call_index(16)] #[pallet::weight(T::WeightInfo::enable_mock())] pub fn enable_mock(origin: OriginFor, value: bool) -> DispatchResult { ensure_root(origin)?; // Mock accepts state roots with no proof at all, so it must never be reachable // on a chain bridging Ethereum mainnet. ensure!(SourceChainId::::get() != 1, Error::::MockError); MockEnabled::::set(value); Self::deposit_event(Event::MockEnabled { value }); Ok(()) } /// The entrypoint for mock_fulfill call. /// public_values Input public values. #[pallet::call_index(17)] #[pallet::weight(T::WeightInfo::fulfill())] pub fn mock_fulfill( origin: OriginFor, public_values: PublicValuesInput, ) -> DispatchResultWithPostInfo { ensure!(MockEnabled::::get() == true, Error::::MockError); // Defence in depth: `enable_mock` already refuses to arm this on chain id 1, but // the flag could predate that check or survive a source chain id change. ensure!(SourceChainId::::get() != 1, Error::::MockError); let sender: [u8; 32] = ensure_signed(origin)?.into(); let updater = Updater::::get(); // ensure sender is preconfigured ensure!(H256(sender) == updater, Error::::UpdaterMisMatch); let proof_outputs: ProofOutputs = SolValue::abi_decode(&public_values, true) .map_err(|_| Error::::CannotDecodePublicValue)?; let head = Head::::get(); let new_head: u64 = proof_outputs .newHead .try_into() .map_err(|_| Error::::SlotOutOfRange)?; ensure!(new_head > head, Error::::SlotBehindHead); let config = ConfigurationStorage::::get(); let current_period = head .checked_div(config.slots_per_period) .ok_or(Error::::ConfigurationNotSet)?; let current_sync_committee_hash = SyncCommitteeHashes::::get(current_period); // The "start" sync committee hash is the hash of the sync committee that should sign the next update. ensure!( current_sync_committee_hash == H256::from(proof_outputs.startSyncCommitteeHash.0), Error::::SyncCommitteeStartMismatch ); // Deliberately no anchor binding here. This extrinsic already accepts an // arbitrary header and execution state root with no proof, so requiring a known // anchor buys no security -- it would only stop mock from bootstrapping a test // chain, which is the whole point of it. The `SourceChainId != 1` guard above is // what keeps that acceptable. Head::::set(new_head); let header = Headers::::get(new_head); ensure!(header == H256::zero(), Error::::HeaderRootAlreadySet); let new_header = H256::from(proof_outputs.newHeader.0); let execution_state_root = ExecutionStateRoots::::get(new_head); ensure!( execution_state_root == H256::zero(), Error::::StateRootAlreadySet ); let new_execution_state_root = H256::from(proof_outputs.executionStateRoot.0); Headers::::insert(new_head, new_header); ExecutionStateRoots::::insert(new_head, new_execution_state_root); Self::deposit_event(Event::HeadUpdated { slot: new_head, finalization_root: new_header, execution_state_root: new_execution_state_root, }); let period = new_head .checked_div(config.slots_per_period) .ok_or(Error::::ConfigurationNotSet)?; // If the sync committee for the period is not set, set it. // This can happen if the light client was very behind and had a lot of updates // and only the last sync committee is stored, not the intermediate ones for every period and may have gaps in periods. if SyncCommitteeHashes::::get(period) == H256::zero() { let sync_committee_hash = H256::from(proof_outputs.syncCommitteeHash.0); SyncCommitteeHashes::::set(period, sync_committee_hash); Self::deposit_event(Event::SyncCommitteeHashUpdated { period, hash: sync_committee_hash, }); } // Update next sync committee hash only if it is not set let next_sync_committee_hash = H256::from(proof_outputs.nextSyncCommitteeHash.0); if next_sync_committee_hash != H256::zero() { let next_period = period + 1; let sync_committee_hash = SyncCommitteeHashes::::get(next_period); if sync_committee_hash != next_sync_committee_hash { ensure!( sync_committee_hash == H256::zero(), Error::::SyncCommitteeHashAlreadySet ); SyncCommitteeHashes::::set(next_period, next_sync_committee_hash); Self::deposit_event(Event::SyncCommitteeHashUpdated { period: next_period, hash: next_sync_committee_hash, }); } } Timestamps::::insert(new_head, T::TimeProvider::now().as_secs()); Ok(().into()) } } impl Pallet { fn do_send_message( who: T::AccountId, message: Message, to: H256, domain: u32, ) -> DispatchResultWithPostInfo { // Ensure the domain is currently supported ensure!( Self::is_domain_valid(domain), Error::::DomainNotSupported ); // Check MessageType and enforce the rules let message_type = message.r#type(); match message { Message::FungibleToken { asset_id, amount } => { ensure!( SUPPORTED_ASSET_ID == asset_id, Error::::AssetNotSupported ); ensure!( amount.saturated_into::() > 0, Error::::InvalidBridgeInputs ); T::Currency::transfer( &who, &Self::account_id(), amount.saturated_into(), ExistenceRequirement::KeepAlive, )?; }, Message::ArbitraryMessage(data) => { ensure!(!data.is_empty(), Error::::InvalidBridgeInputs) }, }; let message_id = Self::fetch_curr_message_id()?; Self::deposit_event(Event::MessageSubmitted { from: who, to, message_type, destination_domain: domain, message_id, }); Ok(().into()) } fn fetch_curr_message_id() -> Result { let number = >::block_number().saturated_into::(); let tx_index_option = >::extrinsic_index(); match tx_index_option { Some(tx_index) => Ok(tx_uid(number, tx_index)), None => Err(Error::::CurrentMessageIdNotFound.into()), } } fn check_preconditions( message: &AddressedMessage, message_root: H256, ) -> Result<(), DispatchError> { let message_status = MessageStatus::::get(message_root); // Message must not be executed ensure!( message_status == MessageStatusEnum::NotExecuted, Error::::MessageAlreadyExecuted ); ensure!( message.destination_domain == T::AvailDomain::get(), Error::::WrongDestinationChain ); ensure!( WhitelistedDomains::::get().contains(&message.origin_domain), Error::::UnsupportedOriginChain ); let source_chain = Broadcasters::::get(message.origin_domain); ensure!( source_chain != H256::zero(), Error::::BroadcasterSourceChainNotSet ); Ok(()) } /// The account ID of the bridge's pot. pub fn account_id() -> T::AccountId { T::PalletId::get().into_account_truncating() } /// Check if the given domain is supported or not fn is_domain_valid(domain: u32) -> bool { WhitelistedDomains::::get().contains(&domain) } } } impl ProvidePostInherent for Pallet where [u8; 32]: From, { type Call = Call; type Error = (); fn create_inherent(_: &avail_base::StorageMap) -> Option { let failed_txs = MemoryTemporaryStorage::get::>>(FAILED_SEND_MSG_ID) .unwrap_or_default(); log::trace!(target: LOG_TARGET, "Create post inherent failed vector txs: {failed_txs:?}"); Some(Call::failed_send_message_txs { failed_txs }) } fn is_inherent(call: &Self::Call) -> bool { matches!(call, Call::failed_send_message_txs { .. }) } fn check_inherent(call: &Self::Call) -> Result<(), Self::Error> { if let Call::failed_send_message_txs { failed_txs } = call { let local_failed_txs = MemoryTemporaryStorage::get::>>(FAILED_SEND_MSG_ID) .unwrap_or_default(); ensure!(&local_failed_txs == failed_txs, ()); } Ok(()) } }