Skip to content

Commit

Permalink
pink-runtime: Add on_idle and bump to 1.2
Browse files Browse the repository at this point in the history
  • Loading branch information
kvinwang committed Sep 5, 2023
1 parent 033b9e3 commit be58767
Show file tree
Hide file tree
Showing 10 changed files with 142 additions and 15 deletions.
49 changes: 48 additions & 1 deletion Cargo.lock

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

11 changes: 8 additions & 3 deletions crates/phactory/src/system/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use core::fmt;
use phala_scheduler::RequestScheduler;
use pink::{
capi::v1::ecall::{ClusterSetupConfig, ECalls},
types::{AccountId, ExecSideEffects, ExecutionMode, TransactionArguments},
types::{AccountId, ECallsAvailable, ExecSideEffects, ExecutionMode, TransactionArguments},
};
use runtime::BlockNumber;

Expand Down Expand Up @@ -664,6 +664,7 @@ impl<Platform: pal::Platform> System<Platform> {
}

fn process_contract_messages(&mut self, block: &mut BlockInfo) {
let log_handler = self.get_system_message_handler();
// Iterate over all contracts to handle their incoming commands.
//
// Since the wasm contracts can instantiate new contracts, it means that it will mutate the `self.contracts`.
Expand All @@ -674,7 +675,6 @@ impl<Platform: pal::Platform> System<Platform> {
// Inner loop to handle commands. One command per iteration and apply the command side-effects to make it
// availabe for next command.
loop {
let log_handler = self.get_system_message_handler();
let Some(cluster) = &mut self.contract_cluster else {
return;
};
Expand All @@ -698,11 +698,16 @@ impl<Platform: pal::Platform> System<Platform> {
block,
&self.egress,
&self.sidevm_spawner,
log_handler,
log_handler.clone(),
block.storage,
);
}
}
if let Some(cluster) = &mut self.contract_cluster {
if ECallsAvailable::on_idle(cluster.config.runtime_version) {
cluster.runtime_mut(log_handler).on_idle(block.block_number);
}
};
}

pub fn did_process_block(&mut self, block: &mut BlockInfo) {
Expand Down
6 changes: 4 additions & 2 deletions crates/pink/capi/src/v1/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub trait OCall: CrossCall {}

pub mod ecall {
use super::{CrossCallMut, ECall, Executing};
use crate::types::{AccountId, Balance, ExecutionMode, Hash, Weight};
use crate::types::{AccountId, Balance, ExecutionMode, Hash, Weight, BlockNumber};
use pink_macro::cross_call;
use scale::{Decode, Encode};
pub trait EventCallbacks {
Expand Down Expand Up @@ -116,8 +116,10 @@ pub mod ecall {
fn git_revision(&self) -> String;
#[xcall(id = 22)]
fn on_genesis(&mut self);
#[xcall(id = 23)]
#[xcall(id = 23, since = "1.1")]
fn on_runtime_upgrade(&mut self);
#[xcall(id = 24, since = "1.2")]
fn on_idle(&mut self, block_number: BlockNumber);
}
}

Expand Down
1 change: 1 addition & 0 deletions crates/pink/macro/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ proc-macro-crate = "1.0.0"
proc-macro2 = "1.0"
syn = { version = "1.0", features = ["full", "visit-mut", "extra-traits", "parsing"] }
heck = "0.4.0"
template-quote = "0.3"

[dev-dependencies]
insta = "1.14.0"
Expand Down
56 changes: 55 additions & 1 deletion crates/pink/macro/src/macro_xcall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ use syn::{parse_quote, Result};

struct Method {
id: u32,
since_version: (u32, u32),
args: Vec<TokenStream>,
method: syn::TraitItemMethod,
}

impl Method {
fn parse(method: &syn::TraitItemMethod) -> Result<Self> {
let mut id = None;
let mut since = None;

for attr in method.attrs.iter() {
if !attr.is_xcall() {
Expand Down Expand Up @@ -50,6 +52,34 @@ impl Method {
));
}
},
"since" => {
macro_rules! value_err {
() => {
Err(syn::Error::new_spanned(
&name_value.lit,
"Expected a version string with format \"major.minor\"",
))
};
}
match &name_value.lit {
syn::Lit::Str(value) => {
// parse version string, e.g. "1.2"
let value = value.value();
let parts: Vec<_> = value.split('.').collect();
if parts.len() != 2 {
return value_err!();
}
let major =
parts[0].parse::<u32>().or(value_err!())?;
let minor =
parts[1].parse::<u32>().or(value_err!())?;
since = Some((major, minor));
}
_ => {
return value_err!();
}
}
}
attr => {
return Err(syn::Error::new_spanned(
name_value,
Expand All @@ -71,6 +101,8 @@ impl Method {
}
}

let since_version = since.unwrap_or((1, 0));

match id {
None => Err(syn::Error::new_spanned(
&method.sig,
Expand All @@ -80,7 +112,12 @@ impl Method {
let mut method = method.clone();
let args = parse_args(&method)?;
method.attrs.retain(|attr| !attr.is_xcall());
Ok(Method { id, args, method })
Ok(Method {
id,
since_version,
args,
method,
})
}
}
}
Expand Down Expand Up @@ -115,6 +152,7 @@ fn patch_or_err(config: TokenStream, input: TokenStream) -> Result<TokenStream>

let call_impl = gen_call_impl(&call_methods, &trait_item.ident, &impl_for)?;
let trait_ro = gen_call_impl_ro(&call_methods, &trait_item.ident, &impl_for)?;
let checker = gen_availability_checker(&call_methods, &trait_item.ident)?;

let exec_dispatcher = gen_exec_dispatcher(&call_methods, &trait_item.ident)?;

Expand All @@ -130,6 +168,8 @@ fn patch_or_err(config: TokenStream, input: TokenStream) -> Result<TokenStream>
#exec_dispatcher

#id2name

#checker
})
}

Expand Down Expand Up @@ -222,6 +262,20 @@ fn gen_call_impl(
})
}

fn gen_availability_checker(call_methods: &[Method], trait_name: &Ident) -> Result<TokenStream> {
let checker_name = Ident::new(&format!("{}Available", trait_name), Span::call_site());
Ok(template_quote::quote! {
pub struct #checker_name;
impl #checker_name {
#(for method in call_methods) {
pub fn #{&method.method.sig.ident}(version: (u32, u32)) -> bool {
version >= (#{ method.since_version.0 }, #{ method.since_version.1 })
}
}
}
})
}

fn gen_call_impl_ro(
call_methods: &[Method],
trait_name: &Ident,
Expand Down
2 changes: 1 addition & 1 deletion crates/pink/runner/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ pub use sp_weights::constants;

pub mod types {
pub use crate::capi::types::*;
pub use crate::capi::v1::ecall::TransactionArguments;
pub use crate::capi::v1::ecall::{ECallsAvailable, TransactionArguments};
}

pub mod runtimes;
Expand Down
2 changes: 1 addition & 1 deletion crates/pink/runtime/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "pink"
version = "1.1.0"
version = "1.2.0"
edition = "2021"

[lib]
Expand Down
9 changes: 7 additions & 2 deletions crates/pink/runtime/src/capi/ecall_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ use scale::Encode;
use crate::{
contract::check_instantiate_result,
runtime::{
on_genesis, on_runtime_upgrade, Balances as PalletBalances, Contracts as PalletContracts,
Pink as PalletPink,
on_genesis, on_idle, on_runtime_upgrade, Balances as PalletBalances,
Contracts as PalletContracts, Pink as PalletPink,
},
types::BlockNumber,
};

use super::OCallImpl;
Expand Down Expand Up @@ -285,6 +286,10 @@ impl ecall::ECalls for ECallImpl {
fn on_runtime_upgrade(&mut self) {
on_runtime_upgrade();
}

fn on_idle(&mut self, block_number: BlockNumber) {
on_idle(block_number);
}
}

/// Clip gas limit to 0.5 second for tx, 10 seconds for query
Expand Down
21 changes: 17 additions & 4 deletions crates/pink/runtime/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@ mod extension;
mod pallet_pink;
mod weights;

use crate::types::{AccountId, Balance, BlockNumber, Nonce, Hash, Hashing};
use crate::types::{AccountId, Balance, BlockNumber, Hash, Hashing, Nonce};
use frame_support::{
parameter_types,
traits::ConstBool,
weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight},
};
use log::info;
use pallet_contracts::{Config, Frame, Migration, Schedule};
use pallet_contracts::{
migration::{v10, v11, v12, v9},
Config, Frame, Migration, Schedule,
};
use sp_runtime::{traits::IdentityLookup, Perbill};

pub use extension::get_side_effects;
Expand All @@ -18,7 +21,7 @@ pub use pink_extension::{EcdhPublicKey, HookPoint, Message, OspMessage, PinkEven

type Block = sp_runtime::generic::Block<
sp_runtime::generic::Header<BlockNumber, Hashing>,
frame_system::mocking:: MockUncheckedExtrinsic<PinkRuntime>,
frame_system::mocking::MockUncheckedExtrinsic<PinkRuntime>,
>;

pub type SystemEvents = Vec<frame_system::EventRecord<RuntimeEvent, Hash>>;
Expand Down Expand Up @@ -150,7 +153,12 @@ impl Config for PinkRuntime {
type MaxStorageKeyLen = MaxStorageKeyLen;
type UnsafeUnstableInterface = ConstBool<false>;
type MaxDebugBufferLen = MaxDebugBufferLen;
type Migrations = ();
type Migrations = (
v9::Migration<Self>,
v10::Migration<Self>,
v11::Migration<Self>,
v12::Migration<Self>,
);
}

#[test]
Expand All @@ -177,3 +185,8 @@ pub fn on_runtime_upgrade() {
Migrations::on_runtime_upgrade();
info!("Runtime database migration done");
}

/// Call on_idle for each pallet.
pub fn on_idle(n: BlockNumber) {
<AllPalletsWithSystem as frame_support::traits::OnIdle<BlockNumber>>::on_idle(n, Weight::MAX);
}
Binary file not shown.

0 comments on commit be58767

Please sign in to comment.