Skip to content

Commit

Permalink
Merge pull request #329 from darwinia-network/denny_fix_eth_relay_bac…
Browse files Browse the repository at this point in the history
…king_tests

Fixing eth relay and backing tests
  • Loading branch information
AurevoirXavier authored Mar 10, 2020
2 parents 24d6317 + c84d73c commit 19f9355
Show file tree
Hide file tree
Showing 10 changed files with 278 additions and 19 deletions.
2 changes: 2 additions & 0 deletions .maintain/ci/travis.local.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ readonly TEST_CRATES=(
'ring'
'staking'
'treasury'
'eth-relay'
'eth-backing'
);

function main() {
Expand Down
8 changes: 8 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ jobs:
env: RUST_TOOLCHAIN=nightly-2020-02-07 TARGET=native TREASURY
script: .maintain/ci/darwinia_test_script.sh treasury

- stage: Darwinia Test
env: RUST_TOOLCHAIN=nightly-2020-02-07 TARGET=native TREASURY
script: .maintain/ci/darwinia_test_script.sh eth-relay

- stage: Darwinia Test
env: RUST_TOOLCHAIN=nightly-2020-02-07 TARGET=native TREASURY
script: .maintain/ci/darwinia_test_script.sh eth-backing

# TODO: remove this when overall test case ready
allow_failures:
- stage: Overall Test
Expand Down
3 changes: 2 additions & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion bin/node/executor/tests/submit_transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ fn submitted_transaction_should_be_valid() {
// add balance to the account
let author = extrinsic.signature.clone().unwrap().0;
let address = Indices::lookup(author).unwrap();
let data = pallet_balances::AccountData {
let data = pallet_balances::balance::AccountData {
free: 5_000_000_000_000,
..Default::default()
};
Expand Down
11 changes: 6 additions & 5 deletions frame/chainrelay/eth/backing/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,15 @@ rustc-hex = "2.0"
rlp = { package = "rlp", git = "https://github.com/darwinia-network/parity-common.git" }

pallet-session = { git = "https://github.com/darwinia-network/substrate.git", tag = "v2.0.0-alpha.3"}
pallet-timestamp = { git = "https://github.com/darwinia-network/substrate.git", tag = "v2.0.0-alpha.3" }

sp-io = { git = "https://github.com/darwinia-network/substrate.git", tag = "v2.0.0-alpha.3" }
sp-phragmen = { git = "https://github.com/darwinia-network/substrate.git", tag = "v2.0.0-alpha.3"}
sp-staking = { git = "https://github.com/darwinia-network/substrate.git", tag = "v2.0.0-alpha.3"}
sp-staking = { git = "https://github.com/darwinia-network/substrate.git", tag = "v2.0.0-alpha.3" }

kton = { package = "darwinia-kton", path = "../../../balances/kton" }
ring = { package = "darwinia-ring", path = '../../../balances/ring' }
staking = { package = "darwinia-staking", path = "../../../staking" }
pallet-ring = { package = "darwinia-ring", path = "../../../../frame/balances/ring" }
pallet-kton = { package = "darwinia-kton", path = "../../../../frame/balances/kton" }
pallet-staking = { package = "darwinia-staking", path = "../../../../frame/staking" }
darwinia-phragmen = { path = "../../../../primitives/phragmen" }

[features]
default = ["std"]
Expand Down
227 changes: 227 additions & 0 deletions frame/chainrelay/eth/backing/src/mock.rs
Original file line number Diff line number Diff line change
@@ -1 +1,228 @@
//! Mock file for eth-backing.
use hex_literal::hex;
use std::cell::RefCell;

use frame_support::{impl_outer_origin, parameter_types, weights::Weight};
use sp_core::{crypto::key_types, H256};
use sp_io;
use sp_runtime::{
testing::{Header, UintAuthorityId},
traits::{IdentifyAccount, IdentityLookup, OpaqueKeys, Verify},
{KeyTypeId, MultiSignature, Perbill},
};
use sp_staking::SessionIndex;

use pallet_staking::{EraIndex, Exposure, ExposureOf};

use darwinia_phragmen::Power;

use crate::*;

/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
pub type Signature = MultiSignature;
/// Some way of identifying an account on the chain. We intentionally make it equivalent
/// to the public key of our transaction signing scheme.
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
pub type BlockNumber = u64;
pub type Balance = u128;

pub type System = frame_system::Module<Test>;
//pub type Session = pallet_session::Module<Test>;
pub type Timestamp = pallet_timestamp::Module<Test>;

pub type EthBacking = Module<Test>;
pub type Ring = pallet_ring::Module<Test>;
pub type Kton = pallet_kton::Module<Test>;
pub type Staking = pallet_staking::Module<Test>;
pub type EthRelay = darwinia_eth_relay::Module<Test>;

pub const NANO: Balance = 1;
pub const MICRO: Balance = 1_000 * NANO;
pub const MILLI: Balance = 1_000 * MICRO;
pub const COIN: Balance = 1_000 * MILLI;

pub const CAP: Balance = 10_000_000_000 * COIN;
pub const GENESIS_TIME: Moment = 0;
pub const TOTAL_POWER: Power = 1_000_000_000;

thread_local! {
static EXISTENTIAL_DEPOSIT: RefCell<Balance> = RefCell::new(0);
static SLASH_DEFER_DURATION: RefCell<EraIndex> = RefCell::new(0);
}

pub struct TestSessionHandler;
impl pallet_session::SessionHandler<AccountId> for TestSessionHandler {
const KEY_TYPE_IDS: &'static [KeyTypeId] = &[key_types::DUMMY];

fn on_genesis_session<Ks: OpaqueKeys>(_validators: &[(AccountId, Ks)]) {}

fn on_new_session<Ks: OpaqueKeys>(
_changed: bool,
_validators: &[(AccountId, Ks)],
_queued_validators: &[(AccountId, Ks)],
) {
}

fn on_disabled(_validator_index: usize) {}
}

impl_outer_origin! {
pub enum Origin for Test where system = system {}
}

// Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Test;
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: Weight = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl frame_system::Trait for Test {
type Origin = Origin;
type Call = ();
type Index = u64;
type BlockNumber = BlockNumber;
type Hash = H256;
type Hashing = ::sp_runtime::traits::BlakeTwo256;
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
type ModuleToIndex = ();
type AccountData = darwinia_support::balance::AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
}
impl pallet_kton::Trait for Test {
type Balance = Balance;
type DustRemoval = ();
type Event = ();
type ExistentialDeposit = ();
type AccountStore = System;
type TryDropRing = ();
}
impl pallet_ring::Trait for Test {
type Balance = Balance;
type DustRemoval = ();
type Event = ();
type ExistentialDeposit = ();
type AccountStore = System;
type TryDropKton = ();
}

parameter_types! {
pub const MinimumPeriod: u64 = 5;
}
impl pallet_timestamp::Trait for Test {
type Moment = u64;
type OnTimestampSet = ();
type MinimumPeriod = MinimumPeriod;
}

parameter_types! {
pub const EthRopsten: u64 = 1;
}

impl darwinia_eth_relay::Trait for Test {
type Event = ();
type EthNetwork = EthRopsten;
}

parameter_types! {
pub const SessionsPerEra: SessionIndex = 3;
pub const BondingDurationInEra: EraIndex = 3;
// assume 60 blocks per session
pub const BondingDurationInBlockNumber: BlockNumber = 3 * 3 * 60;

pub const Cap: Balance = CAP;
pub const TotalPower: Power = TOTAL_POWER;
pub const GenesisTime: Moment = GENESIS_TIME;
}

impl pallet_staking::Trait for Test {
type Time = Timestamp;
type Event = ();
type SessionsPerEra = SessionsPerEra;
type BondingDurationInEra = ();
type BondingDurationInBlockNumber = ();
type SlashDeferDuration = ();
type SlashCancelOrigin = system::EnsureRoot<Self::AccountId>;
type SessionInterface = Self;
type RingCurrency = Ring;
type RingRewardRemainder = ();
type RingSlash = ();
type RingReward = ();
type KtonCurrency = Kton;
type KtonSlash = ();
type KtonReward = ();
type Cap = Cap;
type TotalPower = TotalPower;
type GenesisTime = GenesisTime;
}

parameter_types! {
pub const Period: BlockNumber = 1;
pub const Offset: BlockNumber = 0;
pub const UncleGenerations: u64 = 0;
pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(25);
}

impl pallet_session::Trait for Test {
type Event = ();
type ValidatorId = AccountId;
type ValidatorIdOf = ();
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
type SessionManager = pallet_session::historical::NoteHistoricalRoot<Test, Staking>;
type SessionHandler = TestSessionHandler;
type Keys = UintAuthorityId;
type DisabledValidatorsThreshold = ();
}
impl pallet_session::historical::Trait for Test {
type FullIdentification = Exposure<AccountId, Balance, Balance>;
type FullIdentificationOf = ExposureOf<Test>;
}

impl Trait for Test {
type Event = ();
type Time = Timestamp;
type EthRelay = EthRelay;
type Ring = Ring;
type Kton = Kton;
type OnDepositRedeem = Staking;
type DetermineAccountId = AccountIdDeterminator<Test>;
type RingReward = ();
type KtonReward = ();
}

pub struct ExtBuilder;
impl Default for ExtBuilder {
fn default() -> Self {
Self
}
}

impl ExtBuilder {
pub fn build(self) -> sp_io::TestExternalities {
let mut t = system::GenesisConfig::default().build_storage::<Test>().unwrap();

let _ = GenesisConfig::<Test> {
ring_redeem_address: hex!["dbc888d701167cbfb86486c516aafbefc3a4de6e"].into(),
kton_redeem_address: hex!["dbc888d701167cbfb86486c516aafbefc3a4de6e"].into(),
deposit_redeem_address: hex!["6ef538314829efa8386fc43386cb13b4e0a67d1e"].into(),
ring_locked: 20000000000000,
kton_locked: 5000000000000,
}
.assimilate_storage(&mut t)
.unwrap();

t.into()
}
}
25 changes: 15 additions & 10 deletions frame/chainrelay/eth/backing/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,24 @@
use std::str::FromStr;

use frame_support::{assert_err, assert_ok};
use frame_system::RawOrigin;
use hex_literal::hex;
use rustc_hex::FromHex;
use sr_primitives::{traits::Dispatchable, AccountId32};
use support::{assert_err, assert_ok};
use sp_runtime::{traits::Dispatchable, AccountId32};

use crate::{mock::*, *};
use darwinia_support::StakingLock;
use sp_eth_primitives::{header::EthHeader, Bloom, EthAddress, H64};
use staking::{RewardDestination, StakingBalances, StakingLedger, TimeDepositItem};
use darwinia_support::balance::lock::StakingLock;
use eth_primitives::{header::EthHeader, Bloom, EthAddress, H64};
use pallet_staking::{RewardDestination, StakingBalance, StakingLedger, TimeDepositItem};

#[test]
fn verify_parse_token_redeem_proof() {
ExtBuilder::default()
.build()
.execute_with(|| {
// System::inc_account_nonce(&2);
assert_ok!(EthRelay::set_number_of_blocks_safe(RawOrigin::Root.into(), 0));

// https://ropsten.etherscan.io/tx/0x59c6758bd2b93b2f060e471df8d6f4d901c453d2c2c012ba28088acfb94f8216
let proof_record = EthReceiptProof {
Expand Down Expand Up @@ -62,6 +64,7 @@ fn verify_redeem_ring() {
.build()
.execute_with(|| {
// System::inc_account_nonce(&2);
assert_ok!(EthRelay::set_number_of_blocks_safe(RawOrigin::Root.into(), 0));

// https://ropsten.etherscan.io/tx/0x59c6758bd2b93b2f060e471df8d6f4d901c453d2c2c012ba28088acfb94f8216
let proof_record = EthReceiptProof {
Expand Down Expand Up @@ -97,8 +100,8 @@ fn verify_redeem_ring() {
let expect_account_id = <Test as Trait>::DetermineAccountId::account_id_for(&hex!("2a92ae5b41feba5ee68a61449c557efa9e3b894a6461c058ec2de45429adb44546")).unwrap();

let id1 = AccountId32::from([0; 32]);
// If expect_account_id doesn't exist, redeem should fail
assert_err!(EthBacking::redeem_ring(Origin::signed(id1.clone()), proof_record.clone()), "beneficiary account must pre-exist");
// If expect_account_id doesn't exist, redeem should fail, "beneficiary account must pre-exist"
assert_err!(EthBacking::redeem_ring(Origin::signed(id1.clone()), proof_record.clone()), pallet_ring::Error::<Test, _>::DeadAccount);

let ring_locked_before = EthBacking::ring_locked();

Expand All @@ -122,6 +125,7 @@ fn verify_redeem_kton() {
.build()
.execute_with(|| {
// System::inc_account_nonce(&2);
assert_ok!(EthRelay::set_number_of_blocks_safe(RawOrigin::Root.into(), 0));

// https://ropsten.etherscan.io/tx/0xc878562085dd8b68ad81adf0820aa0380f1f81b0ea7c012be122937b74020f96
// darwinia: 5FP2eFNSVxJzSrE3N2NEVFPhUU34VzYFD6DDtRXbYzTdwPn8
Expand Down Expand Up @@ -166,7 +170,7 @@ fn verify_redeem_kton() {

let id1 = AccountId32::from([0; 32]);
// If expect_account_id doesn't exist, redeem should fail
assert_err!(EthBacking::redeem_kton(Origin::signed(id1.clone()), proof_record.clone()), "beneficiary account must pre-exist");
assert_err!(EthBacking::redeem_kton(Origin::signed(id1.clone()), proof_record.clone()), pallet_kton::Error::<Test, _>::DeadAccount);

let kton_locked_before = EthBacking::kton_locked();

Expand All @@ -189,6 +193,7 @@ fn verify_redeem_deposit() {
.build()
.execute_with(|| {
// System::inc_account_nonce(&2);
assert_ok!(EthRelay::set_number_of_blocks_safe(RawOrigin::Root.into(), 0));

// 1234ring -> 0.1234kton

Expand Down Expand Up @@ -242,9 +247,9 @@ fn verify_redeem_deposit() {
let controller = AccountId32::from([1; 32]);

let _ = Ring::deposit_creating(&expect_account_id, 1);
assert_ok!(staking::Call::<Test>::bond(
assert_ok!(pallet_staking::Call::<Test>::bond(
controller.clone(),
StakingBalances::RingBalance(1),
StakingBalance::RingBalance(1),
RewardDestination::Controller,
0,
).dispatch(Origin::signed(expect_account_id.clone())));
Expand Down
Loading

0 comments on commit 19f9355

Please sign in to comment.