Skip to content

Commit

Permalink
remove Litmus sudo (#876)
Browse files Browse the repository at this point in the history
* sudo

* change Root into Root +democracy

* debug: recover chainspec rootkey

* fix clippy

* try to fix #900

* add debug log #900

* make CI tests pass after remove litmus `Sudo`

* fmt

* debug

* debug

* rococo/litentry align with litmus

* remove useless test code

Co-authored-by: Kai <[email protected]>
Co-authored-by: BillyWooo <[email protected]>
Co-authored-by: zhiming-zhong <[email protected]>
  • Loading branch information
4 people authored Oct 26, 2022
1 parent b2be7f6 commit 3ddb119
Show file tree
Hide file tree
Showing 11 changed files with 161 additions and 54 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

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

4 changes: 4 additions & 0 deletions node/src/chain_specs/litentry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ pub fn get_chain_spec_dev() -> ChainSpec {
get_account_id_from_seed::<sr25519::Public>("Charlie"),
DEFAULT_ENDOWED_ACCOUNT_BALANCE,
),
(
get_account_id_from_seed::<sr25519::Public>("Eve"),
DEFAULT_ENDOWED_ACCOUNT_BALANCE,
),
],
vec![
get_account_id_from_seed::<sr25519::Public>("Alice"),
Expand Down
11 changes: 6 additions & 5 deletions node/src/chain_specs/litmus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use super::*;
use cumulus_primitives_core::ParaId;
use litmus_parachain_runtime::{
AccountId, AuraId, Balance, BalancesConfig, CollatorSelectionConfig, CouncilMembershipConfig,
GenesisConfig, ParachainInfoConfig, PolkadotXcmConfig, SessionConfig, SudoConfig, SystemConfig,
GenesisConfig, ParachainInfoConfig, PolkadotXcmConfig, SessionConfig, SystemConfig,
TechnicalCommitteeMembershipConfig, TeerexConfig, UNIT, WASM_BINARY,
};
use sc_service::ChainType;
Expand All @@ -45,6 +45,7 @@ const DEFAULT_ENDOWED_ACCOUNT_BALANCE: Balance = 1000 * UNIT;
/// GenesisInfo struct to store the parsed genesis_info JSON
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
struct GenesisInfo {
root_key: AccountId,
invulnerables: Vec<(AccountId, AuraId)>,
Expand All @@ -63,7 +64,6 @@ pub fn get_chain_spec_dev() -> ChainSpec {
ChainType::Development,
move || {
generate_genesis(
get_account_id_from_seed::<sr25519::Public>("Alice"),
vec![(
get_account_id_from_seed::<sr25519::Public>("Alice"),
get_collator_keys_from_seed("Alice"),
Expand All @@ -82,6 +82,10 @@ pub fn get_chain_spec_dev() -> ChainSpec {
get_account_id_from_seed::<sr25519::Public>("Charlie"),
DEFAULT_ENDOWED_ACCOUNT_BALANCE,
),
(
get_account_id_from_seed::<sr25519::Public>("Eve"),
DEFAULT_ENDOWED_ACCOUNT_BALANCE,
),
],
vec![
get_account_id_from_seed::<sr25519::Public>("Alice"),
Expand Down Expand Up @@ -152,7 +156,6 @@ fn get_chain_spec_from_genesis_info(
use std::str::FromStr;
let genesis_info_cloned = genesis_info.clone();
generate_genesis(
genesis_info_cloned.root_key,
genesis_info_cloned.invulnerables,
u128::from_str(&genesis_info_cloned.candidacy_bond)
.expect("Bad candicy bond; qed."),
Expand Down Expand Up @@ -187,7 +190,6 @@ fn get_chain_spec_from_genesis_info(
}

fn generate_genesis(
root_key: AccountId,
invulnerables: Vec<(AccountId, AuraId)>,
candicy_bond: Balance,
endowed_accounts: Vec<(AccountId, Balance)>,
Expand All @@ -200,7 +202,6 @@ fn generate_genesis(
code: WASM_BINARY.expect("WASM binary was not build, please build it!").to_vec(),
},
balances: BalancesConfig { balances: endowed_accounts },
sudo: SudoConfig { key: Some(root_key) },
parachain_info: ParachainInfoConfig { parachain_id: id },
collator_selection: CollatorSelectionConfig {
invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(),
Expand Down
4 changes: 4 additions & 0 deletions node/src/chain_specs/rococo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ pub fn get_chain_spec_dev() -> ChainSpec {
get_account_id_from_seed::<sr25519::Public>("Charlie"),
DEFAULT_ENDOWED_ACCOUNT_BALANCE,
),
(
get_account_id_from_seed::<sr25519::Public>("Eve"),
DEFAULT_ENDOWED_ACCOUNT_BALANCE,
),
],
vec![
get_account_id_from_seed::<sr25519::Public>("Alice"),
Expand Down
3 changes: 0 additions & 3 deletions runtime/litmus/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ pallet-preimage = { git = "https://github.com/paritytech/substrate", default-fea
pallet-proxy = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" }
pallet-scheduler = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" }
pallet-session = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" }
pallet-sudo = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" }
pallet-timestamp = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" }
pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" }
pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" }
Expand Down Expand Up @@ -155,7 +154,6 @@ std = [
"pallet-proxy/std",
"pallet-scheduler/std",
"pallet-session/std",
"pallet-sudo/std",
"pallet-timestamp/std",
"pallet-transaction-payment/std",
"pallet-transaction-payment-rpc-runtime-api/std",
Expand Down Expand Up @@ -263,7 +261,6 @@ try-runtime = [
"pallet-scheduler/try-runtime",
"pallet-session/try-runtime",
"pallet-sidechain/try-runtime",
"pallet-sudo/try-runtime",
"pallet-teeracle/try-runtime",
"pallet-teerex/try-runtime",
"pallet-timestamp/try-runtime",
Expand Down
30 changes: 12 additions & 18 deletions runtime/litmus/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use frame_support::{
weights::{constants::RocksDbWeight, ConstantMultiplier, IdentityFee, Weight},
PalletId, RuntimeDebug,
};
use frame_system::{EnsureRoot, EnsureSignedBy};
use frame_system::EnsureSignedBy;
use hex_literal::hex;

// for TEE
Expand Down Expand Up @@ -80,6 +80,7 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

pub mod asset_config;
pub mod constants;
pub mod migration;
pub mod weights;
pub mod xcm_config;

Expand Down Expand Up @@ -129,6 +130,7 @@ pub type Executive = frame_executive::Executive<
// it was reverse order before.
// See the comment before collation related pallets too.
AllPalletsWithSystem,
migration::RemoveSudoAndStorage<Runtime>,
>;

impl_opaque_keys! {
Expand Down Expand Up @@ -352,7 +354,7 @@ impl pallet_scheduler::Config for Runtime {
type PalletsOrigin = OriginCaller;
type Call = Call;
type MaximumWeight = MaximumSchedulerWeight;
type ScheduleOrigin = EnsureRoot<AccountId>;
type ScheduleOrigin = EnsureRootOrAllCouncil;
type MaxScheduledPerBlock = ConstU32<50>;
type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
type OriginPrivilegeCmp = frame_support::traits::EqualPrivilegeOnly;
Expand All @@ -369,7 +371,7 @@ impl pallet_preimage::Config for Runtime {
type WeightInfo = weights::pallet_preimage::WeightInfo<Runtime>;
type Event = Event;
type Currency = Balances;
type ManagerOrigin = EnsureRoot<AccountId>;
type ManagerOrigin = EnsureRootOrAllCouncil;
type MaxSize = PreimageMaxSize;
type BaseDeposit = PreimageBaseDeposit;
type ByteDeposit = PreimageByteDeposit;
Expand Down Expand Up @@ -454,7 +456,7 @@ impl pallet_democracy::Config for Runtime {
// To cancel a proposal before it has been passed, the technical committee must be unanimous or
// Root must agree.
type CancelProposalOrigin = EnsureRootOrAllTechnicalCommittee;
type BlacklistOrigin = EnsureRoot<AccountId>;
type BlacklistOrigin = EnsureRootOrAllCouncil;
// Any single technical committee member may veto a coming council proposal, however they can
// only do it once and it lasts only for the cool-off period.
type VetoOrigin = pallet_collective::EnsureMember<AccountId, TechnicalCommitteeInstance>;
Expand Down Expand Up @@ -581,11 +583,6 @@ impl pallet_bounties::Config for Runtime {
type ChildBountyManager = ();
}

impl pallet_sudo::Config for Runtime {
type Call = Call;
type Event = Event;
}

parameter_types! {
pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
Expand Down Expand Up @@ -613,16 +610,16 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime {
type ChannelInfo = ParachainSystem;
// We use pallet_xcm to confirm the version of xcm
type VersionWrapper = PolkadotXcm;
type ExecuteOverweightOrigin = EnsureRoot<AccountId>;
type ControllerOrigin = EnsureRoot<AccountId>;
type ExecuteOverweightOrigin = EnsureRootOrAllCouncil;
type ControllerOrigin = EnsureRootOrAllCouncil;
type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
}

impl cumulus_pallet_dmp_queue::Config for Runtime {
type Event = Event;
type XcmExecutor = XcmExecutor<XcmConfig>;
type ExecuteOverweightOrigin = EnsureRoot<AccountId>;
type ExecuteOverweightOrigin = EnsureRootOrAllCouncil;
}

parameter_types! {
Expand Down Expand Up @@ -802,7 +799,7 @@ ord_parameter_types! {

impl pallet_identity_management_mock::Config for Runtime {
type Event = Event;
type ManageWhitelistOrigin = EnsureRoot<Self::AccountId>;
type ManageWhitelistOrigin = EnsureRootOrAllCouncil;
type MaxVerificationDelay = ConstU32<10>;
// intentionally use ALICE for the IMP mock
type TEECallOrigin = EnsureSignedBy<ALICE, AccountId>;
Expand Down Expand Up @@ -892,9 +889,6 @@ construct_runtime! {

// Mock
IdentityManagementMock: pallet_identity_management_mock = 100,

// TMP
Sudo: pallet_sudo = 255,
}
}

Expand All @@ -904,8 +898,8 @@ impl Contains<Call> for BaseCallFilter {
fn contains(call: &Call) -> bool {
if matches!(
call,
Call::Sudo(_) |
Call::System(_) | Call::Timestamp(_) |
Call::System(_) |
Call::Timestamp(_) |
Call::ParachainSystem(_) |
Call::ExtrinsicFilter(_) |
Call::Multisig(_) |
Expand Down
70 changes: 70 additions & 0 deletions runtime/litmus/src/migration/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Copyright 2020-2021 Litentry Technologies GmbH.
// This file is part of Litentry.
//
// Litentry 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.
//
// Litentry 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 Litentry. If not, see <https://www.gnu.org/licenses/>.
use frame_support::{
traits::{Get, OnRuntimeUpgrade},
StorageHasher, Twox128,
};
use sp_std::marker::PhantomData;

pub struct RemoveSudoAndStorage<T>(PhantomData<T>);
impl<T> OnRuntimeUpgrade for RemoveSudoAndStorage<T>
where
T: frame_system::Config,
{
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<(), &'static str> {
log::info!("Pre check pallet Sudo exists");
assert!(
frame_support::storage::migration::have_storage_value(b"Sudo", b"Key", b"",),
"Storage query fails: Sudo Key"
);
Ok(())
}

fn on_runtime_upgrade() -> frame_support::weights::Weight {
use sp_io::KillStorageResult;
// Remove Sudo Storage
// TODO: Very Weak safety
let entries: u64 = 4 + 100;
let _res: KillStorageResult = frame_support::storage::unhashed::clear_prefix(
&Twox128::hash(b"Sudo"),
Some(entries.try_into().unwrap()),
None,
)
.into();
<T as frame_system::Config>::DbWeight::get().writes(entries)
}

#[cfg(feature = "try-runtime")]
fn post_upgrade() -> Result<(), &'static str> {
use sp_io::KillStorageResult;

log::info!("Post check Sudo");
let res: KillStorageResult =
frame_support::storage::unhashed::clear_prefix(&Twox128::hash(b"Sudo"), Some(0), None)
.into();

match res {
KillStorageResult::AllRemoved(0) | KillStorageResult::SomeRemaining(0) => {},
KillStorageResult::AllRemoved(n) | KillStorageResult::SomeRemaining(n) => {
log::error!("Remaining entries: {:?}", n);
return Err("Sudo not removed")
},
};

Ok(())
}
}
13 changes: 10 additions & 3 deletions ts-tests/tests/base-filter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,23 @@ describeLitentry('Test Base Filter', ``, (context) => {

expect(eveCurrentNonce.toNumber()).to.equal(eveInitNonce.toNumber() + 1);
// the balance transfer should work for litmus|rococo but not for litentry
if (context.parachain === 'litentry') {
const parachain = (await context.api.rpc.system.chain()).toString().toLowerCase();
if (parachain === 'litentry-dev') {
expect(bobCurrentBalance.free.toBigInt()).to.equal(bobInitBalance.free.toBigInt());
} else if (context.parachain === 'litmus' || context.parachain === 'rococo') {
} else if (parachain === 'litmus-dev' || parachain === 'litentry-rococo-dev') {
expect(bobCurrentBalance.free.toBigInt()).to.equal(bobInitBalance.free.toBigInt() + BigInt(1000));
} else {
assert.fail('unsupported parachain type');
assert.fail('unsupported parachain type', parachain);
}
});

step('Transfer 1000 unit from Eve to Bob with Sudo', async function () {
// only work for litentry|rococo
const parachain = (await context.api.rpc.system.chain()).toString().toLowerCase();
if (parachain === 'litmus-dev') {
console.log("skip test.")
return
}
// Get the initial balance of Alice and Bob
const { nonce: aliceInitNonce, data: aliceInitBalance } = await context.api.query.system.account(
context.alice.address
Expand Down
16 changes: 12 additions & 4 deletions ts-tests/tests/bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,25 @@ describeCrossChainTransfer('Test Cross-chain Transfer', ``, (context) => {
//FERDIE key command: polkadot key inspect //Ferdie
const destinationRecipientAddress = '0x1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c';

await erc20.approve(context.ethConfig.erc20Handler.address, depositAmount);
await sleep(2);
let data = createERCDepositData(depositAmount, 32, destinationRecipientAddress);
const beforeAccountData = await context.parachainConfig.api.query.system.account(
context.parachainConfig.ferdie.address
);
console.log("before deposit: ", beforeAccountData.toString())

// approve
await erc20.approve(context.ethConfig.erc20Handler.address, depositAmount);
await sleep(6);

// deposit
let data = createERCDepositData(depositAmount, 32, destinationRecipientAddress);
await bridge.deposit(destinationChainID, destResourceId, data);
await sleep(36);
await sleep(12 * 4);

const afterAccountData = await context.parachainConfig.api.query.system.account(
context.parachainConfig.ferdie.address
);
console.log("after deposit: ", afterAccountData.toString())

assert.equal(
bn100e12.add(beforeAccountData.data.free.toBn()).toString(),
afterAccountData.data.free.toBn().toString()
Expand Down
Loading

0 comments on commit 3ddb119

Please sign in to comment.