Skip to content

Commit

Permalink
Use different chain primitives in Millau (paritytech#517)
Browse files Browse the repository at this point in the history
  • Loading branch information
svyatonik authored and serban300 committed Apr 9, 2024
1 parent 4228a58 commit 6b8bdee
Show file tree
Hide file tree
Showing 15 changed files with 182 additions and 40 deletions.
2 changes: 1 addition & 1 deletion bridges/bin/millau/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ impl pallet_timestamp::Trait for Runtime {
}

parameter_types! {
pub const ExistentialDeposit: u128 = 500;
pub const ExistentialDeposit: bp_millau::Balance = 500;
// For weight estimation, we assume that the most locks on an individual account will be 50.
// This number may need to be adjusted in the future if this assumption no longer holds true.
pub const MaxLocks: u32 = 50;
Expand Down
4 changes: 2 additions & 2 deletions bridges/bin/millau/runtime/src/rialto_messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,12 @@ impl MessageBridge for WithRialtoMessageBridge {

fn bridged_weight_to_bridged_balance(weight: Weight) -> bp_rialto::Balance {
// we're using the same weights in both chains now
<crate::Runtime as pallet_transaction_payment::Trait>::WeightToFee::calc(&weight)
<crate::Runtime as pallet_transaction_payment::Trait>::WeightToFee::calc(&weight) as _
}

fn this_balance_to_bridged_balance(this_balance: bp_millau::Balance) -> bp_rialto::Balance {
// 1:1 conversion that will probably change in the future
this_balance
this_balance as _
}
}

Expand Down
2 changes: 1 addition & 1 deletion bridges/bin/rialto/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ impl pallet_timestamp::Trait for Runtime {
}

parameter_types! {
pub const ExistentialDeposit: u128 = 500;
pub const ExistentialDeposit: bp_rialto::Balance = 500;
// For weight estimation, we assume that the most locks on an individual account will be 50.
// This number may need to be adjusted in the future if this assumption no longer holds true.
pub const MaxLocks: u32 = 50;
Expand Down
4 changes: 2 additions & 2 deletions bridges/bin/rialto/runtime/src/millau_messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,12 @@ impl MessageBridge for WithMillauMessageBridge {

fn bridged_weight_to_bridged_balance(weight: Weight) -> bp_millau::Balance {
// we're using the same weights in both chains now
<crate::Runtime as pallet_transaction_payment::Trait>::WeightToFee::calc(&weight)
<crate::Runtime as pallet_transaction_payment::Trait>::WeightToFee::calc(&weight) as _
}

fn this_balance_to_bridged_balance(this_balance: bp_rialto::Balance) -> bp_millau::Balance {
// 1:1 conversion that will probably change in the future
this_balance
this_balance as _
}
}

Expand Down
16 changes: 16 additions & 0 deletions bridges/primitives/millau/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,39 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0"

bp-message-lane = { path = "../message-lane", default-features = false }
bp-runtime = { path = "../runtime", default-features = false }
fixed-hash = { version = "0.6.1", default-features = false }
hash256-std-hasher = { version = "0.15.2", default-features = false }
impl-codec = { version = "0.4.2", default-features = false }
impl-serde = { version = "0.3.1", optional = true }
parity-util-mem = { version = "0.7.0", default-features = false, features = ["primitive-types"] }
serde = { version = "1.0.101", optional = true, features = ["derive"] }

# Substrate Based Dependencies

frame-support = { version = "2.0", default-features = false }
sp-api = { version = "2.0", default-features = false }
sp-core = { version = "2.0", default-features = false }
sp-io = { version = "2.0", default-features = false }
sp-runtime = { version = "2.0", default-features = false }
sp-std = { version = "2.0", default-features = false }
sp-trie = { version = "2.0", default-features = false }

[features]
default = ["std"]
std = [
"bp-message-lane/std",
"bp-runtime/std",
"fixed-hash/std",
"frame-support/std",
"hash256-std-hasher/std",
"impl-codec/std",
"impl-serde",
"parity-util-mem/std",
"serde",
"sp-api/std",
"sp-core/std",
"sp-io/std",
"sp-runtime/std",
"sp-std/std",
"sp-trie/std",
]
52 changes: 45 additions & 7 deletions bridges/primitives/millau/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,35 +20,73 @@
// Runtime-generated DecodeLimit::decode_all_With_depth_limit
#![allow(clippy::unnecessary_mut_passed)]

mod millau_hash;

use bp_message_lane::MessageNonce;
use bp_runtime::Chain;
use frame_support::{weights::Weight, RuntimeDebug};
use sp_core::Hasher as HasherT;
use sp_runtime::{
traits::{BlakeTwo256, IdentifyAccount, Verify},
traits::{IdentifyAccount, Verify},
MultiSignature, MultiSigner,
};
use sp_std::prelude::*;
use sp_trie::{trie_types::Layout, TrieConfiguration};

#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};

pub use millau_hash::MillauHash;

/// Millau Hasher (Blake2-256 ++ Keccak-256) implementation.
#[derive(PartialEq, Eq, Clone, Copy, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct BlakeTwoAndKeccak256;

impl sp_core::Hasher for BlakeTwoAndKeccak256 {
type Out = MillauHash;
type StdHasher = hash256_std_hasher::Hash256StdHasher;
const LENGTH: usize = 64;

fn hash(s: &[u8]) -> Self::Out {
let mut combined_hash = MillauHash::default();
combined_hash.as_mut()[..32].copy_from_slice(&sp_io::hashing::blake2_256(s));
combined_hash.as_mut()[32..].copy_from_slice(&sp_io::hashing::keccak_256(s));
combined_hash
}
}

impl sp_runtime::traits::Hash for BlakeTwoAndKeccak256 {
type Output = MillauHash;

fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>) -> Self::Output {
Layout::<BlakeTwoAndKeccak256>::trie_root(input)
}

fn ordered_trie_root(input: Vec<Vec<u8>>) -> Self::Output {
Layout::<BlakeTwoAndKeccak256>::ordered_trie_root(input)
}
}

/// Maximal weight of single Millau block.
pub const MAXIMUM_BLOCK_WEIGHT: Weight = 2_000_000_000_000;
pub const MAXIMUM_BLOCK_WEIGHT: Weight = 10_000_000_000;
/// Portion of block reserved for regular transactions.
pub const AVAILABLE_BLOCK_RATIO: u32 = 75;
/// Maximal weight of single Millau extrinsic (65% of maximum block weight = 75% for regular
/// transactions minus 10% for initialization).
pub const MAXIMUM_EXTRINSIC_WEIGHT: Weight = MAXIMUM_BLOCK_WEIGHT / 100 * (AVAILABLE_BLOCK_RATIO as Weight - 10);

/// Maximal number of unconfirmed messages at inbound lane.
pub const MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE: MessageNonce = 128;
pub const MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE: MessageNonce = 1024;

/// Block number type used in Millau.
pub type BlockNumber = u32;
pub type BlockNumber = u64;

/// Hash type used in Millau.
pub type Hash = <BlakeTwo256 as HasherT>::Out;
pub type Hash = <BlakeTwoAndKeccak256 as HasherT>::Out;

/// The type of an object that can produce hashes on Millau.
pub type Hasher = BlakeTwo256;
pub type Hasher = BlakeTwoAndKeccak256;

/// The header type used by Millau.
pub type Header = sp_runtime::generic::Header<BlockNumber, Hasher>;
Expand Down Expand Up @@ -84,7 +122,7 @@ pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::Account
pub type AccountSigner = MultiSigner;

/// Balance of an account.
pub type Balance = u128;
pub type Balance = u64;

sp_api::decl_runtime_apis! {
/// API for querying information about Millau headers from the Bridge Pallet instance.
Expand Down
57 changes: 57 additions & 0 deletions bridges/primitives/millau/src/millau_hash.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.

// Parity Bridges Common is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Parity Bridges Common is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.

use parity_util_mem::MallocSizeOf;
use sp_runtime::traits::CheckEqual;

// `sp_core::H512` can't be used, because it doesn't implement `CheckEqual`, which is required
// by `frame_system::Trait::Hash`.

fixed_hash::construct_fixed_hash! {
/// Hash type used in Millau chain.
#[derive(MallocSizeOf)]
pub struct MillauHash(64);
}

#[cfg(feature = "std")]
impl_serde::impl_fixed_hash_serde!(MillauHash, 64);

impl_codec::impl_fixed_hash_codec!(MillauHash, 64);

impl CheckEqual for MillauHash {
#[cfg(feature = "std")]
fn check_equal(&self, other: &Self) {
use sp_core::hexdisplay::HexDisplay;
if self != other {
println!(
"Hash: given={}, expected={}",
HexDisplay::from(self.as_fixed_bytes()),
HexDisplay::from(other.as_fixed_bytes()),
);
}
}

#[cfg(not(feature = "std"))]
fn check_equal(&self, other: &Self) {
use frame_support::Printable;

if self != other {
"Hash not equal".print();
self.as_bytes().print();
other.as_bytes().print();
}
}
}
16 changes: 1 addition & 15 deletions bridges/relays/headers-relay/src/sync_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,21 +52,7 @@ pub trait HeadersSyncPipeline: Clone + Send + Sync {
/// Headers we're syncing are identified by this hash.
type Hash: Eq + Clone + Copy + Send + Sync + std::fmt::Debug + std::fmt::Display + std::hash::Hash;
/// Headers we're syncing are identified by this number.
type Number: From<u32>
+ Ord
+ Clone
+ Copy
+ Send
+ Sync
+ std::fmt::Debug
+ std::fmt::Display
+ std::hash::Hash
+ std::ops::Add<Output = Self::Number>
+ std::ops::Sub<Output = Self::Number>
+ num_traits::Saturating
+ num_traits::Zero
+ num_traits::One
+ Into<u64>;
type Number: relay_utils::BlockNumberBase;
/// Type of header that we're syncing.
type Header: SourceHeader<Self::Hash, Self::Number>;
/// Type of extra data for the header that we're receiving from the source node:
Expand Down
7 changes: 3 additions & 4 deletions bridges/relays/messages-relay/src/message_lane.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@
//! 1) relay new messages from source to target node;
//! 2) relay proof-of-delivery from target to source node.

use relay_utils::HeaderId;

use relay_utils::{BlockNumberBase, HeaderId};
use std::fmt::Debug;

/// One-way message lane.
Expand All @@ -36,12 +35,12 @@ pub trait MessageLane: Clone + Send + Sync {
type MessagesReceivingProof: Clone + Send + Sync;

/// Number of the source header.
type SourceHeaderNumber: Clone + Debug + Ord + PartialEq + Into<u64> + Send + Sync;
type SourceHeaderNumber: BlockNumberBase;
/// Hash of the source header.
type SourceHeaderHash: Clone + Debug + Default + PartialEq + Send + Sync;

/// Number of the target header.
type TargetHeaderNumber: Clone + Debug + Ord + PartialEq + Into<u64> + Send + Sync;
type TargetHeaderNumber: BlockNumberBase;
/// Hash of the target header.
type TargetHeaderHash: Clone + Debug + Default + PartialEq + Send + Sync;
}
Expand Down
3 changes: 1 addition & 2 deletions bridges/relays/substrate-client/src/headers_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ use headers_relay::{
sync_loop::SourceClient,
sync_types::{HeaderIdOf, HeadersSyncPipeline, QueuedHeader, SourceHeader},
};
use num_traits::Saturating;
use sp_runtime::{traits::Header as HeaderT, Justification};
use std::marker::PhantomData;

Expand All @@ -49,7 +48,7 @@ impl<C: Chain, P> HeadersSource<C, P> {
impl<C, P> SourceClient<P> for HeadersSource<C, P>
where
C: Chain,
C::BlockNumber: Into<u64> + Saturating,
C::BlockNumber: relay_utils::BlockNumberBase,
C::Header: Into<P::Header>,
P: HeadersSyncPipeline<Extra = (), Completion = Justification, Hash = C::Hash, Number = C::BlockNumber>,
P::Header: SourceHeader<C::Hash, C::BlockNumber>,
Expand Down
6 changes: 3 additions & 3 deletions bridges/relays/substrate/src/headers_pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ use headers_relay::{
sync::{HeadersSyncParams, TargetTransactionMode},
sync_types::{HeadersSyncPipeline, QueuedHeader, SourceHeader},
};
use num_traits::Saturating;
use relay_substrate_client::{headers_source::HeadersSource, BlockNumberOf, Chain, Client, HashOf};
use relay_utils::BlockNumberBase;
use sp_runtime::Justification;
use std::marker::PhantomData;

Expand Down Expand Up @@ -59,7 +59,7 @@ impl<SourceChain, SourceSyncHeader, TargetChain, TargetSign> HeadersSyncPipeline
for SubstrateHeadersToSubstrate<SourceChain, SourceSyncHeader, TargetChain, TargetSign>
where
SourceChain: Clone + Chain,
BlockNumberOf<SourceChain>: Saturating + Into<u64>,
BlockNumberOf<SourceChain>: BlockNumberBase,
SourceSyncHeader:
SourceHeader<HashOf<SourceChain>, BlockNumberOf<SourceChain>> + std::ops::Deref<Target = SourceChain::Header>,
TargetChain: Clone + Chain,
Expand Down Expand Up @@ -107,7 +107,7 @@ pub async fn run<SourceChain, TargetChain, P>(
P::Header: SourceHeader<HashOf<SourceChain>, BlockNumberOf<SourceChain>>,
SourceChain: Clone + Chain,
SourceChain::Header: Into<P::Header>,
BlockNumberOf<SourceChain>: Into<u64> + Saturating,
BlockNumberOf<SourceChain>: BlockNumberBase,
TargetChain: Clone + Chain,
{
let source_justifications = match source_client.clone().subscribe_justifications().await {
Expand Down
4 changes: 2 additions & 2 deletions bridges/relays/substrate/src/messages_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use messages_relay::{
message_lane_loop::{ClientState, MessageProofParameters, MessageWeightsMap, SourceClient, SourceClientState},
};
use relay_substrate_client::{Chain, Client, Error as SubstrateError, HashOf, HeaderIdOf};
use relay_utils::HeaderId;
use relay_utils::{BlockNumberBase, HeaderId};
use sp_core::Bytes;
use sp_runtime::{traits::Header as HeaderT, DeserializeOwned};
use sp_trie::StorageProof;
Expand Down Expand Up @@ -93,7 +93,7 @@ where
C: Chain,
C::Header: DeserializeOwned,
C::Index: DeserializeOwned,
<C::Header as HeaderT>::Number: Into<u64>,
C::BlockNumber: BlockNumberBase,
P: MessageLane<
MessagesProof = SubstrateMessagesProof<C>,
SourceHeaderNumber = <C::Header as HeaderT>::Number,
Expand Down
3 changes: 2 additions & 1 deletion bridges/relays/substrate/src/messages_target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use messages_relay::{
message_lane_loop::{TargetClient, TargetClientState},
};
use relay_substrate_client::{Chain, Client, Error as SubstrateError, HashOf};
use relay_utils::BlockNumberBase;
use sp_core::Bytes;
use sp_runtime::{traits::Header as HeaderT, DeserializeOwned};
use sp_trie::StorageProof;
Expand Down Expand Up @@ -89,7 +90,7 @@ where
C: Chain,
C::Header: DeserializeOwned,
C::Index: DeserializeOwned,
<C::Header as HeaderT>::Number: Into<u64>,
<C::Header as HeaderT>::Number: BlockNumberBase,
P: MessageLane<
MessagesReceivingProof = (HashOf<C>, StorageProof, LaneId),
TargetHeaderNumber = <C::Header as HeaderT>::Number,
Expand Down
1 change: 1 addition & 0 deletions bridges/relays/utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ backoff = "0.2"
env_logger = "0.7.0"
futures = "0.3.5"
log = "0.4.11"
num-traits = "0.2"
sysinfo = "0.15"
time = "0.2"

Expand Down
Loading

0 comments on commit 6b8bdee

Please sign in to comment.