Skip to content

Commit

Permalink
chore: added test
Browse files Browse the repository at this point in the history
  • Loading branch information
GabrielMartinezRodriguez committed Jan 23, 2024
1 parent 6a2060b commit abbf4d7
Show file tree
Hide file tree
Showing 9 changed files with 281 additions and 15 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

14 changes: 14 additions & 0 deletions pallets/upgrade-runtime-proposal/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ pub mod pallet {
#[pallet::getter(fn application_block_number)]
pub type ApplicationBlockNumber<T: Config> = StorageValue<_, T::BlockNumber, OptionQuery>;

#[pallet::storage]
#[pallet::getter(fn current_code_hash)]
pub type CurrentCodeHash<T: Config> = StorageValue<_, T::Hash, OptionQuery>;

#[pallet::error]
pub enum Error<T> {
/// The address received is invalid
Expand Down Expand Up @@ -155,6 +159,8 @@ pub mod pallet {
if result.is_err() {
log::error!("Failed to upgrade runtime");
} else {
let hash = Pallet::<T>::hash_of_proposed_code().unwrap();
Pallet::<T>::set_current_code_hash(hash);
log::info!("Runtime upgraded");
}

Expand All @@ -174,12 +180,20 @@ pub mod pallet {
<ApplicationBlockNumber<T>>::get()
}

pub fn get_current_code_hash() -> Option<T::Hash> {
<CurrentCodeHash<T>>::get()
}

pub fn hash_of_proposed_code() -> Option<T::Hash> {
<ProposedCode<T>>::get().map(|code| {
T::Hashing::hash(&code)
})
}

pub fn set_current_code_hash(hash: T::Hash) -> () {
<CurrentCodeHash<T>>::put(hash)
}

pub fn set_application_block_number(block_number: T::BlockNumber) {
<ApplicationBlockNumber<T>>::put(block_number);
}
Expand Down
6 changes: 6 additions & 0 deletions pallets/upgrade-runtime-proposal/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,9 @@ fn test_scheduled_update_runtime() {
frame_system::RawOrigin::Root.into(),
stability_test_runtime_client::runtime::wasm_binary_unwrap().to_vec()
));

let proposed_code_hash = UpgradeRuntimeProposal::hash_of_proposed_code().unwrap();

assert_ok!(UpgradeRuntimeProposal::set_block_application(
frame_system::RawOrigin::Root.into(),
1
Expand All @@ -215,6 +218,9 @@ fn test_scheduled_update_runtime() {
UpgradeRuntimeProposal::on_initialize(1);

assert_runtime_updated_digest(1);

assert!(UpgradeRuntimeProposal::hash_of_proposed_code().is_none());
assert_eq!(UpgradeRuntimeProposal::get_current_code_hash().unwrap(), proposed_code_hash);
assert!(UpgradeRuntimeProposal::get_proposed_code().is_none());
assert!(UpgradeRuntimeProposal::get_application_block_number().is_none());
});
Expand Down
1 change: 1 addition & 0 deletions precompiles/upgrade-runtime-controller/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ scale-info = { version = "2.0", default-features = false, features = [ "derive"
sha3 = "0.10"
sp-io = { workspace = true }
stability-test-runtime-client = { workspace = true }
stbl-core-primitives = { workspace = true, features = ["std"] }

[features]
default = [ "std" ]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pragma solidity >=0.8.3;
interface UpgradeRuntimeController {
function setApplicationBlock(uint32 block) external; // onlyOwner
function rejectProposedCode() external; // onlyOwner
function getTechnicalCommitteeMembers() external view returns (address[] memory);
function addMemberToTechnicalCommittee(address member) external; // onlyOwner
function removeMemberFromTechnicalCommittee(address member) external; // onlyOwner
function getHashOfProposedCode() external view returns (bytes32);
Expand Down
15 changes: 13 additions & 2 deletions precompiles/upgrade-runtime-controller/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ where
<Runtime as frame_system::Config>::BlockNumber: From<u32>,
<Runtime as frame_system::Config>::Hash: Into<H256>,
<Runtime as frame_system::Config>::AccountId: From<H160>,
<Runtime as frame_system::Config>::AccountId: Into<H160>,
{
#[precompile::public("owner()")]
#[precompile::view]
Expand Down Expand Up @@ -246,7 +247,7 @@ where
let old_members = pallet_collective::Pallet::<Runtime, pallet_collective::Instance1>::members();

if old_members.contains(&member_id.into()) {
return Err(revert("Already a member"));
return Err(revert("already a member"));
}

let mut new_members = old_members
Expand Down Expand Up @@ -287,7 +288,7 @@ where
let old_members = pallet_collective::Pallet::<Runtime, pallet_collective::Instance1>::members();

if !old_members.contains(&member_account) {
return Err(revert("Not a member"));
return Err(revert("not a member"));
}

let mut new_members = old_members
Expand All @@ -306,6 +307,16 @@ where
Ok(())
}

#[precompile::public("getTechnicalCommitteeMembers()")]
#[precompile::view]
fn get_technical_committee_members(handle: &mut impl PrecompileHandle) -> EvmResult<Vec<Address>> {
handle.record_cost(RuntimeHelper::<Runtime>::db_read_gas_cost())?;

let members = pallet_collective::Pallet::<Runtime, pallet_collective::Instance1>::members();

Ok(members.iter().map(|m| Into::<H160>::into(m.clone())).map(|m| Into::<Address>::into(m)).collect())
}

#[precompile::public("getHashOfProposedCode()")]
#[precompile::view]
fn get_hash_of_proposed_code(handle: &mut impl PrecompileHandle) -> EvmResult<H256> {
Expand Down
54 changes: 42 additions & 12 deletions precompiles/upgrade-runtime-controller/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use sp_runtime::{
use sp_version::RuntimeVersion;
use precompile_utils::precompile_set::*;
use pallet_evm::{EnsureAddressRoot, EnsureAddressNever, AddressMapping};
use crate::mock::sp_api_hidden_includes_construct_runtime::hidden_include::traits::GenesisBuild;

type Block = frame_system::mocking::MockBlock<Test>;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
Expand Down Expand Up @@ -45,6 +46,7 @@ parameter_types! {
state_version: 1,
};
}
pub type AccountId = stbl_core_primitives::AccountId;

impl frame_system::Config for Test {
type BaseCallFilter = BlockEverything;
Expand All @@ -57,7 +59,7 @@ impl frame_system::Config for Test {
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type RuntimeEvent = RuntimeEvent;
Expand All @@ -78,7 +80,7 @@ parameter_types! {
}

impl pallet_upgrade_runtime_proposal::Config for Test {
type ControlOrigin = EnsureRoot<u64>;
type ControlOrigin = EnsureRoot<AccountId>;
type MaxSizeOfCode = MaxSizeOfCode;
}

Expand All @@ -94,16 +96,17 @@ impl pallet_timestamp::Config for Test {
}


pub struct NumberAddressMapping;

impl AddressMapping<u64> for NumberAddressMapping {
fn into_account_id(address: H160) -> u64 {
let address_bytes: [u8; 8] = (*address.as_fixed_bytes())[12..].try_into().unwrap();
u64::from_be_bytes(address_bytes)
pub struct IdentityAddressMapping;
impl pallet_evm::AddressMapping<AccountId> for IdentityAddressMapping {
fn into_account_id(address: H160) -> AccountId {
address.into()
}
}




parameter_types! {
pub BlockGasLimit: U256 = U256::max_value();
pub PrecompilesValue: Precompiles<Test> = Precompiles::new();
Expand All @@ -115,9 +118,9 @@ impl pallet_evm::Config for Test {
type FeeCalculator = ();
type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
type WeightPerGas = WeightPerGas;
type CallOrigin = EnsureAddressRoot<u64>;
type WithdrawOrigin = EnsureAddressNever<u64>;
type AddressMapping = NumberAddressMapping;
type CallOrigin = EnsureAddressRoot<AccountId>;
type WithdrawOrigin = EnsureAddressNever<AccountId>;
type AddressMapping = IdentityAddressMapping;
type Currency = Balances;
type RuntimeEvent = RuntimeEvent;
type Runner = pallet_evm::runner::stack::Runner<Self>;
Expand Down Expand Up @@ -158,6 +161,31 @@ impl pallet_balances::Config for Test {

type TechCommitteeInstance = pallet_collective::Instance1;

use frame_support::weights::{constants::WEIGHT_REF_TIME_PER_MILLIS};
use sp_runtime::{Perbill, Permill};
use stbl_core_primitives::BlockNumber;

// Block time
pub const MILLISECS_PER_BLOCK: u64 = 2000;

pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);

/// How much of time of block time is consumed (at most) in computing normal extrinsics
const COMPUTATION_BLOCK_TIME_RATIO: (u64, u64) = (2, 3); // 2 third parts of the block time

const COMPUTATION_POWER_MULTIPLIER: u64 = 6; // 6 times more computation power than normal

// how much weight for normal extrinsics could be processed in a block
pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_MILLIS * MILLISECS_PER_BLOCK * COMPUTATION_POWER_MULTIPLIER * COMPUTATION_BLOCK_TIME_RATIO.0 / COMPUTATION_BLOCK_TIME_RATIO.1, u64::MAX);


parameter_types! {
pub const CouncilMotionDuration: BlockNumber = 120;
pub const CouncilMaxProposals: u32 = 2;
pub const CouncilMaxMembers: u32 = 2;
pub const MaxProposalWeight: Weight = MAXIMUM_BLOCK_WEIGHT;
}

impl pallet_collective::Config<TechCommitteeInstance> for Test {
type RuntimeOrigin = RuntimeOrigin;
type Proposal = RuntimeCall;
Expand All @@ -167,7 +195,7 @@ impl pallet_collective::Config<TechCommitteeInstance> for Test {
type MaxMembers = CouncilMaxMembers;
type DefaultVote = pallet_collective::PrimeDefaultVote;
type WeightInfo = pallet_collective::weights::SubstrateWeight<Self>;
type SetMembersOrigin = EnsureRootOrHalfTechCommittee;
type SetMembersOrigin = EnsureRoot<AccountId>;
type MaxProposalWeight = MaxProposalWeight;
}

Expand All @@ -188,7 +216,7 @@ frame_support::construct_runtime!(

pub(crate) struct ExtBuilder {
// endowed accounts with balances
balances: Vec<(u64, Balance)>,
balances: Vec<(AccountId, Balance)>,
}

impl Default for ExtBuilder {
Expand All @@ -213,6 +241,8 @@ impl ExtBuilder {
members: vec![],
phantom: Default::default(),
}
.assimilate_storage(&mut t)
.expect("Pallet collective storage can be assimilated");

let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
Expand Down
Loading

0 comments on commit abbf4d7

Please sign in to comment.