Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
jasl committed Oct 7, 2023
1 parent a7c2ebb commit a42f5c5
Show file tree
Hide file tree
Showing 10 changed files with 54 additions and 55 deletions.
6 changes: 3 additions & 3 deletions crates/phala-node-rpc-ext/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use jsonrpsee::{
};
use pallet_mq_runtime_api::MqApi;
use sc_client_api::blockchain::{HeaderBackend, HeaderMetadata};
use sc_client_api::{backend, Backend, BlockBackend, StorageProvider};
use sc_client_api::{Backend, BlockBackend, StorageProvider};
use sc_transaction_pool_api::{InPoolTransaction, TransactionPool};
use sp_api::{ApiExt, Core, ProvideRuntimeApi, StateBackend};
use sp_runtime::traits::Header;
Expand Down Expand Up @@ -88,7 +88,7 @@ where
+ HeaderMetadata<Block, Error = sp_blockchain::Error>
+ ProvideRuntimeApi<Block>,
Client::Api:
sp_api::Metadata<Block> + ApiExt<Block, StateBackend = backend::StateBackendFor<BE, Block>>,
sp_api::Metadata<Block> + ApiExt<Block>,
Client::Api: MqApi<Block>,
Block: BlockT + 'static,
<<Block as BlockT>::Header as Header>::Number: Into<u64>,
Expand Down Expand Up @@ -153,7 +153,7 @@ pub fn extend_rpc<Client, BE, Block, P>(
+ 'static,
Block: BlockT + 'static,
Client::Api:
sp_api::Metadata<Block> + ApiExt<Block, StateBackend = backend::StateBackendFor<BE, Block>>,
sp_api::Metadata<Block> + ApiExt<Block>,
Client::Api: MqApi<Block>,
<<Block as BlockT>::Header as Header>::Number: Into<u64>,
P: TransactionPool + 'static,
Expand Down
2 changes: 1 addition & 1 deletion crates/phala-node-rpc-ext/src/mq_seq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ where
+ ProvideRuntimeApi<Block>,
Block: BlockT + 'static,
Client::Api:
sp_api::Metadata<Block> + ApiExt<Block, StateBackend = backend::StateBackendFor<BE, Block>>,
sp_api::Metadata<Block> + ApiExt<Block>,
Client::Api: MqApi<Block>,
<<Block as BlockT>::Header as Header>::Number: Into<u64>,
P: TransactionPool,
Expand Down
2 changes: 1 addition & 1 deletion crates/phala-node-rpc-ext/src/storage_changes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ where
+ ProvideRuntimeApi<Block>,
Block: BlockT + 'static,
Client::Api:
sp_api::Metadata<Block> + ApiExt<Block, StateBackend = backend::StateBackendFor<BE, Block>>,
sp_api::Metadata<Block> + ApiExt<Block>,
<<Block as BlockT>::Header as Header>::Number: Into<u64>,
{
fn header<Client: HeaderBackend<Block>, Block: BlockT>(
Expand Down
4 changes: 2 additions & 2 deletions crates/phala-trie-storage/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::iter::FromIterator;
use parity_scale_codec::Codec;
use sp_core::storage::ChildInfo;
use sp_core::Hasher;
use sp_state_machine::{Backend, IterArgs, TrieBackend, TrieBackendBuilder};
use sp_state_machine::{Backend, BackendTransaction, IterArgs, TrieBackend, TrieBackendBuilder};
use sp_trie::{trie_types::TrieDBMutBuilderV0 as TrieDBMutBuilder, TrieMut};

pub use memdb::GenericMemoryDB as MemoryDB;
Expand Down Expand Up @@ -128,7 +128,7 @@ where
&self,
delta: &'a StorageCollection,
child_deltas: &'a ChildStorageCollection,
) -> (H::Out, MemoryDB<H>) {
) -> (H::Out, BackendTransaction<H>) {
let child_deltas: Vec<(ChildInfo, &StorageCollection)> = child_deltas
.iter()
.map(|(k, v)| {
Expand Down
13 changes: 1 addition & 12 deletions crates/phala-trie-storage/src/memdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,29 +20,18 @@ use hash_db::{
pub(crate) use im::ordmap::{Entry, OrdMap as Map};
use std::{borrow::Borrow, cmp::Eq, hash, marker::PhantomData};

use sp_state_machine::{backend::Consolidate, DefaultError, TrieBackendStorage};
use sp_state_machine::{DefaultError, TrieBackendStorage};
use trie_db::DBValue;

pub trait MaybeDebug: std::fmt::Debug {}
impl<T: std::fmt::Debug> MaybeDebug for T {}

pub type GenericMemoryDB<H> = MemoryDB<H, HashKey<H>, trie_db::DBValue>;

impl<H: KeyHasher> Consolidate for GenericMemoryDB<H>
where
H::Out: Ord,
{
fn consolidate(&mut self, other: Self) {
MemoryDB::consolidate(self, other)
}
}

impl<H: KeyHasher> TrieBackendStorage<H> for GenericMemoryDB<H>
where
H::Out: Ord,
{
type Overlay = Self;

fn get(
&self,
key: &<H as KeyHasher>::Out,
Expand Down
15 changes: 10 additions & 5 deletions crates/pink/runtime/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ mod weights;
use crate::types::{AccountId, Balance, BlockNumber, Hash, Hashing, Nonce};
use frame_support::{
parameter_types,
traits::ConstBool,
traits::{ConstBool, ConstU32},
weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight},
};
use log::info;
use pallet_contracts::{
migration::{v10, v11, v12, v9},
migration::{v09, v10, v11, v12},
Config, Frame, Migration, Schedule,
};
use sp_runtime::{traits::IdentityLookup, Perbill};
Expand Down Expand Up @@ -119,7 +119,6 @@ parameter_types! {
pub const MaxCodeLen: u32 = MAX_CODE_LEN;
pub const MaxStorageKeyLen: u32 = 128;
pub const MaxDebugBufferLen: u32 = 128 * 1024;

pub DefaultSchedule: Schedule<PinkRuntime> = {
let mut schedule = Schedule::<PinkRuntime>::default();
const MB: u32 = 16; // 64KiB * 16
Expand All @@ -131,6 +130,7 @@ parameter_types! {
schedule.limits.payload_len = 1024 * 1024; // Max size for storage value
schedule
};
pub CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(30);
}

impl Config for PinkRuntime {
Expand All @@ -154,11 +154,16 @@ impl Config for PinkRuntime {
type UnsafeUnstableInterface = ConstBool<false>;
type MaxDebugBufferLen = MaxDebugBufferLen;
type Migrations = (
v9::Migration<Self>,
v09::Migration<Self>,
v10::Migration<Self>,
v11::Migration<Self>,
v12::Migration<Self>,
v12::Migration<Self, Balances>,
);
type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
type MaxDelegateDependencies = ConstU32<32>;
type RuntimeHoldReason = RuntimeHoldReason;
type Debug = ();
type Environment = ();
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion crates/pink/runtime/src/runtime/extension.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::borrow::Cow;

use frame_support::log::error;
use log::error;
use frame_support::traits::Currency;
use pallet_contracts::chain_extension::{
ChainExtension, Environment, Ext, InitState, Result as ExtResult, RetVal,
Expand Down
2 changes: 1 addition & 1 deletion standalone/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ where
P: TransactionPool + 'static,
SC: SelectChain<Block> + 'static,
B: sc_client_api::Backend<Block> + Send + Sync + 'static,
B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,
B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashingFor<Block>>,
{
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
use sc_consensus_babe_rpc::{Babe, BabeApiServer};
Expand Down
60 changes: 32 additions & 28 deletions standalone/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ mod msg_routing;

use codec::{Decode, Encode, MaxEncodedLen};
use frame_election_provider_support::{
bounds::{ElectionBounds, ElectionBoundsBuilder},
onchain, BalancingConfig, ElectionDataProvider, SequentialPhragmen, VoteWeight,
};
use frame_support::{
Expand All @@ -45,7 +46,7 @@ use frame_support::{
},
IdentityFee, Weight,
},
PalletId, RuntimeDebug,
PalletId,
};
use frame_system::{
limits::{BlockLength, BlockWeights},
Expand Down Expand Up @@ -74,7 +75,7 @@ use sp_runtime::{
},
transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
AccountId32, ApplyExtrinsicResult, FixedPointNumber, FixedU128, Perbill, Percent, Permill,
Perquintill,
Perquintill, RuntimeDebug,
};
use sp_std::prelude::*;
#[cfg(any(feature = "std", test))]
Expand Down Expand Up @@ -439,10 +440,11 @@ impl pallet_babe::Config for Runtime {
type DisabledValidators = Session;
type WeightInfo = ();
type MaxAuthorities = MaxAuthorities;
type MaxNominators = MaxNominatorRewardedPerValidator;
type KeyOwnerProof =
<Historical as KeyOwnerProofSystem<(KeyTypeId, pallet_babe::AuthorityId)>>::Proof;
type EquivocationReportSystem =
pallet_babe::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
pallet_babe::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
}

parameter_types! {
Expand Down Expand Up @@ -568,14 +570,16 @@ parameter_types! {
pub HistoryDepth: u32 = 84;
}

/// Upper limit on the number of NPOS nominations.
const MAX_QUOTA_NOMINATIONS: u32 = 16;

pub struct StakingBenchmarkingConfig;
impl pallet_staking::BenchmarkingConfig for StakingBenchmarkingConfig {
type MaxNominators = ConstU32<1000>;
type MaxValidators = ConstU32<1000>;
}

impl pallet_staking::Config for Runtime {
type MaxNominations = MaxNominations;
type Currency = Balances;
type CurrencyBalance = Balance;
type UnixTime = Timestamp;
Expand All @@ -600,6 +604,7 @@ impl pallet_staking::Config for Runtime {
type ElectionProvider = ElectionProviderMultiPhase;
type GenesisElectionProvider = onchain::OnChainExecution<OnChainSeqPhragmen>;
type VoterList = VoterList;
type NominationsQuota = pallet_staking::FixedNominationsQuota<MAX_QUOTA_NOMINATIONS>;
// This a placeholder, to be introduced in the next PR as an instance of bags-list
type TargetList = pallet_staking::UseValidatorsMap<Self>;
type MaxUnlockingChunks = ConstU32<32>;
Expand All @@ -611,7 +616,7 @@ impl pallet_staking::Config for Runtime {

impl pallet_fast_unstake::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type ControlOrigin = EnsureRoot<AccountId>;
type ControlOrigin = frame_system::EnsureRoot<AccountId>;
type BatchSize = ConstU32<64>;
type Deposit = ConstU128<{ DOLLARS }>;
type Currency = Balances;
Expand All @@ -634,7 +639,7 @@ parameter_types! {

pub BetterUnsignedThreshold: Perbill = Perbill::from_rational(1u32, 10_000);

// worker configs
// miner configs
pub const MultiPhaseUnsignedPriority: TransactionPriority = StakingUnsignedPriority::get() - 1u64;
pub MinerMaxWeight: Weight = RuntimeBlockWeights::get()
.get(DispatchClass::Normal)
Expand All @@ -653,17 +658,20 @@ frame_election_provider_support::generate_solution_type!(
VoterIndex = u32,
TargetIndex = u16,
Accuracy = sp_runtime::PerU16,
MaxVoters = MaxElectingVoters,
MaxVoters = MaxElectingVotersSolution,
>(16)
);

parameter_types! {
// Note: the EPM in this runtime runs the election on-chain. The election bounds must be
// carefully set so that an election round fits in one block.
pub ElectionBoundsMultiPhase: ElectionBounds = ElectionBoundsBuilder::default()
.voters_count(10_000.into()).targets_count(1_500.into()).build();
pub ElectionBoundsOnChain: ElectionBounds = ElectionBoundsBuilder::default()
.voters_count(5_000.into()).targets_count(1_250.into()).build();

pub MaxNominations: u32 = <NposSolution16 as frame_election_provider_support::NposSolution>::LIMIT as u32;
pub MaxElectingVoters: u32 = 40_000;
pub MaxElectableTargets: u16 = 10_000;
// OnChain values are lower.
pub MaxOnChainElectingVoters: u32 = 5000;
pub MaxOnChainElectableTargets: u16 = 1250;
pub MaxElectingVotersSolution: u32 = 40_000;
// The maximum winners that can be elected by the Election pallet which is equivalent to the
// maximum active validators the staking pallet can have.
pub MaxActiveValidators: u32 = 1000;
Expand All @@ -684,28 +692,25 @@ impl pallet_election_provider_multi_phase::BenchmarkingConfig for ElectionProvid
}

/// Maximum number of iterations for balancing that will be executed in the embedded OCW
/// worker of election provider multi phase.
pub const WORKER_MAX_ITERATIONS: u32 = 10;
/// miner of election provider multi phase.
pub const MINER_MAX_ITERATIONS: u32 = 10;

/// A source of random balance for NposSolver, which is meant to be run by the OCW election worker.
/// A source of random balance for NposSolver, which is meant to be run by the OCW election miner.
pub struct OffchainRandomBalancing;
impl Get<Option<BalancingConfig>> for OffchainRandomBalancing {
fn get() -> Option<BalancingConfig> {
let iterations = match WORKER_MAX_ITERATIONS {
let iterations = match MINER_MAX_ITERATIONS {
0 => 0,
max => {
let seed = sp_io::offchain::random_seed();
let random = <u32>::decode(&mut TrailingZeroInput::new(&seed))
.expect("input is padded with zeroes; qed")
% max.saturating_add(1);
.expect("input is padded with zeroes; qed") %
max.saturating_add(1);
random as usize
}
},
};

let config = BalancingConfig {
iterations,
tolerance: 0,
};
let config = BalancingConfig { iterations, tolerance: 0 };
Some(config)
}
}
Expand All @@ -720,8 +725,7 @@ impl onchain::Config for OnChainSeqPhragmen {
type DataProvider = <Runtime as pallet_election_provider_multi_phase::Config>::DataProvider;
type WeightInfo = frame_election_provider_support::weights::SubstrateWeight<Runtime>;
type MaxWinners = <Runtime as pallet_election_provider_multi_phase::Config>::MaxWinners;
type VotersBound = MaxOnChainElectingVoters;
type TargetsBound = MaxOnChainElectableTargets;
type Bounds = ElectionBoundsOnChain;
}

impl pallet_election_provider_multi_phase::MinerConfig for Runtime {
Expand Down Expand Up @@ -769,9 +773,8 @@ impl pallet_election_provider_multi_phase::Config for Runtime {
type GovernanceFallback = onchain::OnChainExecution<OnChainSeqPhragmen>;
type Solver = SequentialPhragmen<AccountId, SolutionAccuracyOf<Self>, OffchainRandomBalancing>;
type ForceOrigin = EnsureRootOrHalfCouncil;
type MaxElectableTargets = MaxElectableTargets;
type MaxWinners = MaxActiveValidators;
type MaxElectingVoters = MaxElectingVoters;
type ElectionBounds = ElectionBoundsMultiPhase;
type BenchmarkingConfig = ElectionProviderBenchmarkConfig;
type WeightInfo = pallet_election_provider_multi_phase::weights::SubstrateWeight<Self>;
}
Expand Down Expand Up @@ -1190,10 +1193,11 @@ impl pallet_grandpa::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type WeightInfo = ();
type MaxAuthorities = MaxAuthorities;
type MaxNominators = MaxNominatorRewardedPerValidator;
type MaxSetIdSessionEntries = MaxSetIdSessionEntries;
type KeyOwnerProof = <Historical as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
type EquivocationReportSystem =
pallet_grandpa::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
pallet_grandpa::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
}

parameter_types! {
Expand Down
3 changes: 2 additions & 1 deletion standalone/runtime/src/msg_routing.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use super::pallet_mq;
use codec::Decode;
use frame_support::dispatch::{DispatchError, DispatchResult};
use frame_support::dispatch::DispatchResult;
use sp_runtime::DispatchError;
use phala_types::messaging::{BindTopic, DecodedMessage, Message};

pub struct MessageRouteConfig;
Expand Down

0 comments on commit a42f5c5

Please sign in to comment.