Skip to content

Commit

Permalink
fix all tests
Browse files Browse the repository at this point in the history
  • Loading branch information
JesseAbram committed Oct 25, 2023
1 parent f2bb38a commit 136dfc2
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 352 deletions.
252 changes: 0 additions & 252 deletions node/cli/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -647,255 +647,3 @@ pub fn new_full(config: Configuration, cli: Cli) -> Result<TaskManager, ServiceE

Ok(task_manager)
}

#[cfg(test)]
mod tests {
use std::sync::Arc;

use codec::Encode;
use kitchensink_runtime::{
constants::{currency::CENTS, time::SLOT_DURATION},
Address, BalancesCall, RuntimeCall, UncheckedExtrinsic,
};
use node_primitives::{Block, DigestItem, Signature};
use sc_client_api::BlockBackend;
use sc_consensus::{BlockImport, BlockImportParams, ForkChoiceStrategy};
use sc_consensus_babe::{BabeIntermediate, CompatibleDigestItem, INTERMEDIATE_KEY};
use sc_consensus_epochs::descendent_query;
use sc_keystore::LocalKeystore;
use sc_service_test::TestNetNode;
use sc_transaction_pool_api::{ChainEvent, MaintainedTransactionPool};
use sp_consensus::{BlockOrigin, Environment, Proposer};
use sp_core::crypto::Pair;
use sp_inherents::InherentDataProvider;
use sp_keyring::AccountKeyring;
use sp_keystore::KeystorePtr;
use sp_runtime::{
generic::{Digest, Era, SignedPayload},
key_types::BABE,
traits::{Block as BlockT, Header as HeaderT, IdentifyAccount, Verify},
RuntimeAppPublic,
};

use crate::service::{new_full_base, NewFullBase};

type AccountPublic = <Signature as Verify>::Signer;

#[test]
// It is "ignored", but the node-cli ignored tests are running on the CI.
// This can be run locally with `cargo test --release -p node-cli test_sync -- --ignored`.
#[ignore]
fn test_sync() {
sp_tracing::try_init_simple();

let keystore_path = tempfile::tempdir().expect("Creates keystore path");
let keystore: KeystorePtr =
LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore").into();
let alice: sp_consensus_babe::AuthorityId = keystore
.sr25519_generate_new(BABE, Some("//Alice"))
.expect("Creates authority pair")
.into();

let chain_spec = crate::chain_spec::tests::integration_test_config_with_single_authority();

// For the block factory
let mut slot = 1u64;

// For the extrinsics factory
let bob = Arc::new(AccountKeyring::Bob.pair());
let charlie = Arc::new(AccountKeyring::Charlie.pair());
let mut index = 0;

sc_service_test::sync(
chain_spec,
|config| {
let mut setup_handles = None;
let NewFullBase { task_manager, client, network, sync, transaction_pool, .. } =
new_full_base(
config,
false,
|block_import: &sc_consensus_babe::BabeBlockImport<Block, _, _>,
babe_link: &sc_consensus_babe::BabeLink<Block>| {
setup_handles = Some((block_import.clone(), babe_link.clone()));
},
None,
)?;

let node = sc_service_test::TestNetComponents::new(
task_manager,
client,
network,
sync,
transaction_pool,
);
Ok((node, setup_handles.unwrap()))
},
|service, &mut (ref mut block_import, ref babe_link)| {
let parent_hash = service.client().chain_info().best_hash;
let parent_header = service.client().header(parent_hash).unwrap().unwrap();
let parent_number = *parent_header.number();

futures::executor::block_on(service.transaction_pool().maintain(
ChainEvent::NewBestBlock { hash: parent_header.hash(), tree_route: None },
));

let mut proposer_factory = sc_basic_authorship::ProposerFactory::new(
service.spawn_handle(),
service.client(),
service.transaction_pool(),
None,
None,
);

let mut digest = Digest::default();

// even though there's only one authority some slots might be empty,
// so we must keep trying the next slots until we can claim one.
let (babe_pre_digest, epoch_descriptor) = loop {
let epoch_descriptor = babe_link
.epoch_changes()
.shared_data()
.epoch_descriptor_for_child_of(
descendent_query(&*service.client()),
&parent_hash,
parent_number,
slot.into(),
)
.unwrap()
.unwrap();

let epoch = babe_link
.epoch_changes()
.shared_data()
.epoch_data(&epoch_descriptor, |slot| {
sc_consensus_babe::Epoch::genesis(babe_link.config(), slot)
})
.unwrap();

if let Some(babe_pre_digest) =
sc_consensus_babe::authorship::claim_slot(slot.into(), &epoch, &keystore)
.map(|(digest, _)| digest)
{
break (babe_pre_digest, epoch_descriptor);
}

slot += 1;
};

let inherent_data = futures::executor::block_on(
(
sp_timestamp::InherentDataProvider::new(
std::time::Duration::from_millis(SLOT_DURATION * slot).into(),
),
sp_consensus_babe::inherents::InherentDataProvider::new(slot.into()),
)
.create_inherent_data(),
)
.expect("Creates inherent data");

digest.push(<DigestItem as CompatibleDigestItem>::babe_pre_digest(babe_pre_digest));

let new_block = futures::executor::block_on(async move {
let proposer = proposer_factory.init(&parent_header).await;
proposer
.unwrap()
.propose(inherent_data, digest, std::time::Duration::from_secs(1), None)
.await
})
.expect("Error making test block")
.block;

let (new_header, new_body) = new_block.deconstruct();
let pre_hash = new_header.hash();
// sign the pre-sealed hash of the block and then
// add it to a digest item.
let to_sign = pre_hash.encode();
let signature = keystore
.sr25519_sign(sp_consensus_babe::AuthorityId::ID, alice.as_ref(), &to_sign)
.unwrap()
.unwrap();
let item = <DigestItem as CompatibleDigestItem>::babe_seal(signature.into());
slot += 1;

let mut params = BlockImportParams::new(BlockOrigin::File, new_header);
params.post_digests.push(item);
params.body = Some(new_body);
params.insert_intermediate(
INTERMEDIATE_KEY,
BabeIntermediate::<Block> { epoch_descriptor },
);
params.fork_choice = Some(ForkChoiceStrategy::LongestChain);

futures::executor::block_on(block_import.import_block(params))
.expect("error importing test block");
},
|service, _| {
let amount = 5 * CENTS;
let to: Address = AccountPublic::from(bob.public()).into_account().into();
let from: Address = AccountPublic::from(charlie.public()).into_account().into();
let genesis_hash = service.client().block_hash(0).unwrap().unwrap();
let best_hash = service.client().chain_info().best_hash;
let (spec_version, transaction_version) = {
let version = service.client().runtime_version_at(best_hash).unwrap();
(version.spec_version, version.transaction_version)
};
let signer = charlie.clone();

let function = RuntimeCall::Balances(BalancesCall::transfer_allow_death {
dest: to,
value: amount,
});

let check_non_zero_sender = frame_system::CheckNonZeroSender::new();
let check_spec_version = frame_system::CheckSpecVersion::new();
let check_tx_version = frame_system::CheckTxVersion::new();
let check_genesis = frame_system::CheckGenesis::new();
let check_era = frame_system::CheckEra::from(Era::Immortal);
let check_nonce = frame_system::CheckNonce::from(index);
let check_weight = frame_system::CheckWeight::new();
let tx_payment = pallet_asset_tx_payment::ChargeAssetTxPayment::from(0, None);
let extra = (
check_non_zero_sender,
check_spec_version,
check_tx_version,
check_genesis,
check_era,
check_nonce,
check_weight,
tx_payment,
);
let raw_payload = SignedPayload::from_raw(
function,
extra,
((), spec_version, transaction_version, genesis_hash, genesis_hash, (), (), ()),
);
let signature = raw_payload.using_encoded(|payload| signer.sign(payload));
let (function, extra, _) = raw_payload.deconstruct();
index += 1;
UncheckedExtrinsic::new_signed(function, from, signature.into(), extra).into()
},
);
}

#[test]
#[ignore]
fn test_consensus() {
sp_tracing::try_init_simple();

sc_service_test::consensus(
crate::chain_spec::tests::integration_test_config_with_two_authorities(),
|config| {
let NewFullBase { task_manager, client, network, sync, transaction_pool, .. } =
new_full_base(config, false, |_, _| (), None)?;
Ok(sc_service_test::TestNetComponents::new(
task_manager,
client,
network,
sync,
transaction_pool,
))
},
vec!["//Alice".into(), "//Bob".into()],
)
}
}
47 changes: 21 additions & 26 deletions pallets/relayer/src/mock.rs
Original file line number Diff line number Diff line change
@@ -1,47 +1,43 @@
use frame_election_provider_support::{onchain, SequentialPhragmen, VoteWeight};
use frame_support::{
parameter_types,
traits::{ConstU32, FindAuthor, GenesisBuild, OneSessionHandler},
traits::{ConstU32, FindAuthor, OneSessionHandler},
};
use frame_system as system;
use pallet_session::historical as pallet_session_historical;
use pallet_staking_extension::ServerInfo;
use sp_core::H256;
use sp_runtime::{
curve::PiecewiseLinear,
testing::{Header, TestXt, UintAuthorityId},
testing::{TestXt, UintAuthorityId},
traits::{BlakeTwo256, ConvertInto, IdentityLookup},
Perbill,
BuildStorage, Perbill,
};
use sp_staking::{EraIndex, SessionIndex};

use crate as pallet_relayer;

const NULL_ARR: [u8; 32] = [0; 32];
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
type BlockNumber = u64;
type AccountId = u64;
type Balance = u64;

// Configure a mock runtime to test the pallet.
frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
pub enum Test
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
Authorship: pallet_authorship::{Pallet, Storage},
Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
Relayer: pallet_relayer::{Pallet, Call, Storage, Event<T>},
Staking: pallet_staking_extension::{Pallet, Call, Storage, Event<T>, Config<T>},
FrameStaking: pallet_staking::{Pallet, Call, Storage, Event<T>},
Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>},
Historical: pallet_session_historical::{Pallet},
BagsList: pallet_bags_list::{Pallet, Call, Storage, Event<T>},
Constraints: pallet_constraints::{Pallet, Call, Storage, Event<T>},
System: frame_system,
Balances: pallet_balances,
Authorship: pallet_authorship,
Timestamp: pallet_timestamp,
Relayer: pallet_relayer,
Staking: pallet_staking_extension,
FrameStaking: pallet_staking,
Session: pallet_session,
Historical: pallet_session_historical,
BagsList: pallet_bags_list,
Constraints: pallet_constraints,
}
);

Expand All @@ -54,17 +50,16 @@ impl system::Config for Test {
type AccountData = pallet_balances::AccountData<Balance>;
type AccountId = u64;
type BaseCallFilter = frame_support::traits::Everything;
type Block = Block;
type BlockHashCount = BlockHashCount;
type BlockLength = ();
type BlockNumber = u64;
type BlockWeights = ();
type DbWeight = ();
type Hash = H256;
type Hashing = BlakeTwo256;
type Header = Header;
type Index = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type MaxConsumers = frame_support::traits::ConstU32<16>;
type Nonce = u64;
type OnKilledAccount = ();
type OnNewAccount = ();
type OnSetCode = ();
Expand Down Expand Up @@ -98,13 +93,13 @@ impl pallet_balances::Config for Test {
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type FreezeIdentifier = ();
type HoldIdentifier = ();
type MaxFreezes = ();
type MaxHolds = ();
type MaxLocks = MaxLocks;
type MaxReserves = ();
type ReserveIdentifier = [u8; 8];
type RuntimeEvent = RuntimeEvent;
type RuntimeHoldReason = RuntimeHoldReason;
type WeightInfo = ();
}

Expand Down Expand Up @@ -218,17 +213,17 @@ impl pallet_staking::Config for Test {
type BondingDuration = BondingDuration;
type Currency = Balances;
type CurrencyBalance = Balance;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type CurrencyToVote = ();
type ElectionProvider = onchain::OnChainExecution<OnChainSeqPhragmen>;
type EraPayout = pallet_staking::ConvertCurve<RewardCurve>;
type EventListeners = ();
type GenesisElectionProvider = Self::ElectionProvider;
type HistoryDepth = ConstU32<84>;
type MaxNominations = MaxNominations;
type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
type MaxUnlockingChunks = ConstU32<32>;
type NextNewSession = Session;
type OffendingValidatorsThreshold = OffendingValidatorsThreshold;
type OnStakerSlash = ();
type Reward = ();
type RewardRemainder = ();
type RuntimeEvent = RuntimeEvent;
Expand Down Expand Up @@ -314,7 +309,7 @@ impl pallet_constraints::Config for Test {

// Build genesis storage according to the mock runtime.
pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
let mut t = system::GenesisConfig::<Test>::default().build_storage().unwrap();
let pallet_staking_extension = pallet_staking_extension::GenesisConfig::<Test> {
threshold_servers: vec![
(5, ServerInfo { tss_account: 7, x25519_public_key: NULL_ARR, endpoint: vec![20] }),
Expand Down
Loading

0 comments on commit 136dfc2

Please sign in to comment.