Skip to content

Commit

Permalink
Refactor snowbridge-core crate
Browse files Browse the repository at this point in the history
  • Loading branch information
vgeddes committed Jul 28, 2023
1 parent 42ba62a commit 9de3945
Show file tree
Hide file tree
Showing 23 changed files with 327 additions and 421 deletions.
6 changes: 3 additions & 3 deletions core/packages/contracts/src/Verification.sol
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ library Verification {
/// @param encodedParaID The SCALE-encoded parachain ID of BridgeHub
/// @param commitment The message commitment root expected to be contained within the
/// digest of BridgeHub parachain header.
/// @param proof The chain of proofs described above
function verifyCommitment(address beefyClient, bytes4 encodedParaID, bytes32 commitment, Proof calldata proof)
external
view
Expand All @@ -109,12 +110,11 @@ library Verification {
// Compute the merkle leaf hash of our parachain
bytes32 parachainHeadHash = createParachainHeaderMerkleLeaf(encodedParaID, proof.header);

// Compute the merkle root hash of all parachain heads
//
// For reference, in the polkadot relay chain, this is where the merkle tree root is constructed:
if (proof.headProof.pos >= proof.headProof.width) {
return false;
}

// Compute the merkle root hash of all parachain heads
bytes32 parachainHeadsRoot = SubstrateMerkleProof.computeRoot(
parachainHeadHash, proof.headProof.pos, proof.headProof.width, proof.headProof.proof
);
Expand Down
5 changes: 3 additions & 2 deletions core/packages/contracts/src/interfaces/IGateway.sol
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,15 @@ interface IGateway {
*/

/// @dev Send a message to the AssetHub parachain to register a new fungible asset
/// in the `ForeignAssets` pallet.
/// in the `ForeignAssets` pallet.
function registerToken(address token) external payable;

/// @dev Send ERC20 tokens to Polkadot.
/// @dev Send ERC20 tokens to parachain `destinationChain` and deposit into account `destinationAddress`
function sendToken(address token, ParaID destinationChain, bytes32 destinationAddress, uint128 amount)
external
payable;

/// @dev Send ERC20 tokens to parachain `destinationChain` and deposit into account `destinationAddress`
function sendToken(address token, ParaID destinationChain, address destinationAddress, uint128 amount)
external
payable;
Expand Down
6 changes: 3 additions & 3 deletions core/packages/contracts/src/storage/CoreStorage.sol
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ library CoreStorage {
OperatingMode mode;
// Message channels
mapping(ParaID paraID => Channel) channels;
// All agents
// Agents
mapping(bytes32 agentID => address) agents;
// The fee charged to users for submitting outbound message to Polkadot
// The default fee charged to users for submitting outbound message to Polkadot
uint256 defaultFee;
// The reward given to relayers for submitting inbound messages from Polkadot
// The default reward given to relayers for submitting inbound messages from Polkadot
uint256 defaultReward;
}

Expand Down
1 change: 1 addition & 0 deletions core/packages/contracts/src/utils/ERC1967.sol
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
pragma solidity 0.8.20;

/// @title Minimal implementation of ERC1967 storage slot
library ERC1967 {
// bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
bytes32 public constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
Expand Down
12 changes: 0 additions & 12 deletions parachain/Cargo.lock

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

1 change: 0 additions & 1 deletion parachain/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
members = [
"primitives/core",
"primitives/ethereum",
"primitives/testutils",
"primitives/router",
"pallets/inbound-queue",
"pallets/outbound-queue",
Expand Down
20 changes: 14 additions & 6 deletions parachain/pallets/control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ mod benchmarking;
pub mod weights;
pub use weights::*;

use snowbridge_core::{Command, OutboundMessage, OutboundQueue as OutboundQueueTrait, ParaId};
use snowbridge_core::outbound::{Command, Message, OutboundQueue as OutboundQueueTrait, ParaId};
use sp_core::{H160, H256};
use sp_runtime::traits::Hash;
use sp_std::prelude::*;
Expand Down Expand Up @@ -73,6 +73,13 @@ pub mod pallet {

#[pallet::call]
impl<T: Config> Pallet<T> {
/// Sends a message to the Gateway contract to upgrade itself.
///
/// - `origin`: Must be `Root`.
/// - `impl_address`: The address of the new implementation contract.
/// - `impl_code_hash`: The codehash of `impl_address`.
/// - `params`: An optional list of ABI-encoded parameters for the implementation
/// contract's `initialize(bytes) function. If `None`, the initialization function is not called.
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::upgrade(params.clone().map_or(0, |d| d.len() as u32)))]
pub fn upgrade(
Expand All @@ -90,7 +97,7 @@ pub mod pallet {

let params_hash = params.as_ref().map(|p| T::MessageHasher::hash(p));

let message = OutboundMessage {
let message = Message {
origin: T::OwnParaId::get(),
command: Command::Upgrade { impl_address, impl_code_hash, params },
};
Expand All @@ -105,6 +112,9 @@ pub mod pallet {
Ok(())
}

/// Sends a message to the Gateway contract to create a new Agent representing `origin`
///
/// - `origin`: Must be `MultiLocation`
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::create_agent())]
pub fn create_agent(origin: OriginFor<T>) -> DispatchResult {
Expand All @@ -125,10 +135,8 @@ pub mod pallet {
return Ok(());
}

let message = OutboundMessage {
origin: T::OwnParaId::get(),
command: Command::CreateAgent { agent_id },
};
let message =
Message { origin: T::OwnParaId::get(), command: Command::CreateAgent { agent_id } };

let ticket =
T::OutboundQueue::validate(&message).map_err(|_| Error::<T>::SubmissionFailed)?;
Expand Down
10 changes: 5 additions & 5 deletions parachain/pallets/control/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use frame_support::{
#[cfg(feature = "runtime-benchmarks")]
use frame_benchmarking::v2::whitelisted_caller;

use snowbridge_core::{OutboundMessage, OutboundMessageHash, ParaId, SubmitError};
use snowbridge_core::outbound::{Message, MessageHash, ParaId, SubmitError};
use sp_core::H256;
use sp_runtime::{
testing::Header,
Expand Down Expand Up @@ -174,14 +174,14 @@ impl EnsureOrigin<RuntimeOrigin> for EnsureOriginFromTable {

pub struct MockOutboundQueue;
impl snowbridge_control::OutboundQueueTrait for MockOutboundQueue {
type Ticket = OutboundMessage;
type Ticket = Message;

fn validate(message: &OutboundMessage) -> Result<Self::Ticket, SubmitError> {
fn validate(message: &Message) -> Result<Self::Ticket, SubmitError> {
Ok(message.clone())
}

fn submit(_ticket: Self::Ticket) -> Result<OutboundMessageHash, SubmitError> {
Ok(OutboundMessageHash::zero())
fn submit(_ticket: Self::Ticket) -> Result<MessageHash, SubmitError> {
Ok(MessageHash::zero())
}
}

Expand Down
1 change: 0 additions & 1 deletion parachain/pallets/ethereum-beacon-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ bp-runtime = { git = "https://github.com/Snowfork/cumulus.git", branch = "snowbr
rand = "0.8.5"
sp-keyring = { git = "https://github.com/paritytech/substrate.git", branch = "master" }
sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "master" }
snowbridge-testutils = { path = "../../primitives/testutils" }
serde_json = "1.0.96"
hex-literal = { version = "0.4.1" }
pallet-timestamp = { git = "https://github.com/paritytech/substrate.git", branch = "master" }
Expand Down
41 changes: 21 additions & 20 deletions parachain/pallets/ethereum-beacon-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,14 @@ use primitives::{
CompactBeaconState, CompactExecutionHeader, ExecutionHeaderState, ForkData, ForkVersion,
ForkVersions, PublicKeyPrepared, SigningData,
};
use snowbridge_core::{Message, RingBufferMap, Verifier};
use snowbridge_core::{
inbound::{Message, Proof, Verifier},
RingBufferMap,
};
use sp_core::H256;
use sp_std::prelude::*;
pub use weights::WeightInfo;

use snowbridge_core::Proof;

use functions::{
compute_epoch, compute_period, decompress_sync_committee_bits, sync_committee_sum,
};
Expand Down Expand Up @@ -346,9 +347,9 @@ pub mod pallet {
// committee period.
let max_latency = config::EPOCHS_PER_SYNC_COMMITTEE_PERIOD * config::SLOTS_PER_EPOCH;
ensure!(
latest_execution_state.beacon_slot == 0 ||
latest_finalized_state.slot <
latest_execution_state.beacon_slot + max_latency as u64,
latest_execution_state.beacon_slot == 0
|| latest_finalized_state.slot
< latest_execution_state.beacon_slot + max_latency as u64,
Error::<T>::ExecutionHeaderTooFarBehind
);
Ok(())
Expand All @@ -366,8 +367,8 @@ pub mod pallet {

// Verify update does not skip a sync committee period.
ensure!(
update.signature_slot > update.attested_header.slot &&
update.attested_header.slot >= update.finalized_header.slot,
update.signature_slot > update.attested_header.slot
&& update.attested_header.slot >= update.finalized_header.slot,
Error::<T>::InvalidUpdateSlot
);
// Retrieve latest finalized state.
Expand All @@ -387,12 +388,12 @@ pub mod pallet {

// Verify update is relevant.
let update_attested_period = compute_period(update.attested_header.slot);
let update_has_next_sync_committee = !<NextSyncCommittee<T>>::exists() &&
(update.next_sync_committee_update.is_some() &&
update_attested_period == store_period);
let update_has_next_sync_committee = !<NextSyncCommittee<T>>::exists()
&& (update.next_sync_committee_update.is_some()
&& update_attested_period == store_period);
ensure!(
update.attested_header.slot > latest_finalized_state.slot ||
update_has_next_sync_committee,
update.attested_header.slot > latest_finalized_state.slot
|| update_has_next_sync_committee,
Error::<T>::IrrelevantUpdate
);

Expand Down Expand Up @@ -549,9 +550,9 @@ pub mod pallet {
// Checks that we don't skip execution headers, they need to be imported sequentially.
let latest_execution_state: ExecutionHeaderState = Self::latest_execution_state();
ensure!(
latest_execution_state.block_number == 0 ||
update.execution_header.block_number ==
latest_execution_state.block_number + 1,
latest_execution_state.block_number == 0
|| update.execution_header.block_number
== latest_execution_state.block_number + 1,
Error::<T>::ExecutionHeaderSkippedSlot
);

Expand Down Expand Up @@ -595,7 +596,7 @@ pub mod pallet {
let state = <FinalizedBeaconState<T>>::get(block_root)
.ok_or(Error::<T>::ExpectedFinalizedHeaderNotStored)?;
if update.header.slot != state.slot {
return Err(Error::<T>::ExpectedFinalizedHeaderNotStored.into())
return Err(Error::<T>::ExpectedFinalizedHeaderNotStored.into());
}
},
}
Expand Down Expand Up @@ -782,13 +783,13 @@ pub mod pallet {
let fork_versions = T::ForkVersions::get();

if epoch >= fork_versions.capella.epoch {
return fork_versions.capella.version
return fork_versions.capella.version;
}
if epoch >= fork_versions.bellatrix.epoch {
return fork_versions.bellatrix.version
return fork_versions.bellatrix.version;
}
if epoch >= fork_versions.altair.epoch {
return fork_versions.altair.version
return fork_versions.altair.version;
}

fork_versions.genesis.version
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::*;
use hex_literal::hex;
use snowbridge_beacon_primitives::CompactExecutionHeader;
use snowbridge_core::{Message, Proof};
use snowbridge_core::inbound::{Message, Proof};

pub struct InboundQueueTest {
pub execution_header: CompactExecutionHeader,
Expand Down
6 changes: 5 additions & 1 deletion parachain/pallets/inbound-queue/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use sp_runtime::traits::AccountIdConversion;
use sp_std::convert::TryFrom;

use envelope::Envelope;
use snowbridge_core::{Message, Verifier};
use snowbridge_core::inbound::{Message, Verifier};
use snowbridge_router_primitives::inbound;

use xcm::v3::{send_xcm, Junction::*, Junctions::*, MultiLocation, SendError};
Expand Down Expand Up @@ -119,10 +119,12 @@ pub mod pallet {
BridgeModule(bp_runtime::OwnedBridgeModuleError),
}

/// The address of the Gateway contract on Ethereum
#[pallet::storage]
#[pallet::getter(fn gateway)]
pub type Gateway<T: Config> = StorageValue<_, H160, ValueQuery>;

/// The current nonce for each parachain
#[pallet::storage]
pub type Nonce<T: Config> = StorageMap<_, Twox64Concat, ParaId, u64, ValueQuery>;

Expand All @@ -144,6 +146,7 @@ pub mod pallet {
#[pallet::genesis_config]
#[derive(DefaultNoBound)]
pub struct GenesisConfig {
/// The address of the Gateway contract on Ethereum
pub gateway: H160,
}

Expand All @@ -163,6 +166,7 @@ pub mod pallet {

#[pallet::call]
impl<T: Config> Pallet<T> {
/// Submit an inbound message originating from the Gateway contract on Ethereum
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::submit())]
pub fn submit(origin: OriginFor<T>, message: Message) -> DispatchResult {
Expand Down
2 changes: 1 addition & 1 deletion parachain/pallets/inbound-queue/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use sp_runtime::{
use sp_std::convert::From;

use snowbridge_beacon_primitives::{Fork, ForkVersions};
use snowbridge_core::{Message, Proof};
use snowbridge_core::inbound::{Message, Proof};
use snowbridge_ethereum::Log;

use hex_literal::hex;
Expand Down
2 changes: 1 addition & 1 deletion parachain/pallets/outbound-queue/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use super::*;

use codec::Encode;
use frame_benchmarking::v2::*;
use snowbridge_core::Command;
use snowbridge_core::outbound::Command;

#[allow(unused_imports)]
use crate::Pallet as OutboundQueue;
Expand Down
Loading

0 comments on commit 9de3945

Please sign in to comment.