Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
More refactoring and more documentation
  • Loading branch information
bkchr committed Nov 13, 2018
commit fb94becfcf31202ef61e05501e38f84d1c2194fc
28 changes: 25 additions & 3 deletions core/client/src/block_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,32 @@ use runtime_primitives::traits::{
};
use primitives::H256;
use runtime_primitives::generic::BlockId;
use runtime_api::{core::Core, BlockBuilder as BlockBuilderAPI};
use runtime_api::Core;
use error;
use runtime_primitives::ApplyOutcome;

/// The runtime api for building blocks.
pub mod api {
use runtime_primitives::{traits::Block as BlockT, ApplyResult};

decl_runtime_apis! {
/// The `BlockBuilder` api trait that provides required functions for building a block for a runtime.
pub trait BlockBuilder<Block: BlockT> {
/// Apply the given extrinsics.
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult;
/// Finish the current block.
fn finalise_block() -> <Block as BlockT>::Header;
/// Generate inherent extrinsics.
fn inherent_extrinsics<InherentExtrinsic, UncheckedExtrinsic>(inherent: InherentExtrinsic) -> Vec<UncheckedExtrinsic>;
/// Check that the inherents are valid.
fn check_inherents<InherentData, Error>(block: Block, data: InherentData) -> Result<(), Error>;
/// Generate a random seed.
fn random_seed() -> <Block as BlockT>::Hash;
}
}
}
use self::api::BlockBuilder as BlockBuilderApi;

/// Utility for building new (valid) blocks from a stream of extrinsics.
pub struct BlockBuilder<'a, Block, A: ProvideRuntimeApi> where Block: BlockT {
header: <Block as BlockT>::Header,
Expand All @@ -40,7 +62,7 @@ impl<'a, Block, A> BlockBuilder<'a, Block, A>
where
Block: BlockT<Hash=H256>,
A: ProvideRuntimeApi + HeaderBackend<Block> + 'a,
A::Api: BlockBuilderAPI<Block>,
A::Api: BlockBuilderApi<Block>,
{
/// Create a new instance of builder from the given client, building on the latest block.
pub fn new(api: &'a A) -> error::Result<Self> {
Expand Down Expand Up @@ -85,7 +107,7 @@ where
block_id: &BlockId<Block>,
xt: Block::Extrinsic,
extrinsics: &mut Vec<Block::Extrinsic>
) -> error::Result<()> where T: BlockBuilderAPI<Block> {
) -> error::Result<()> where T: api::BlockBuilder<Block> {
api.map_api_result(|api| {
match api.apply_extrinsic(block_id, &xt)? {
Ok(ApplyOutcome::Success) | Ok(ApplyOutcome::Fail) => {
Expand Down
7 changes: 2 additions & 5 deletions core/client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,7 @@ use runtime_primitives::traits::{
ApiRef, ProvideRuntimeApi
};
use runtime_primitives::BuildStorage;
use runtime_api::{
core::Core as CoreAPI, BlockBuilder as BlockBuilderAPI, core::CallApiAt,
TaggedTransactionQueue, core::ConstructRuntimeApi,
};
use runtime_api::{Core as CoreAPI, CallApiAt, TaggedTransactionQueue, ConstructRuntimeApi};
use primitives::{Blake2Hasher, H256, ChangesTrieConfiguration, convert_hash};
use primitives::storage::{StorageKey, StorageData};
use primitives::storage::well_known_keys;
Expand All @@ -52,7 +49,7 @@ use blockchain::{self, Info as ChainInfo, Backend as ChainBackend, HeaderBackend
use call_executor::{CallExecutor, LocalCallExecutor};
use executor::{RuntimeVersion, RuntimeInfo};
use notifications::{StorageNotifications, StorageEventStream};
use {cht, error, in_mem, block_builder, genesis, consensus};
use {cht, error, in_mem, block_builder::{self, api::BlockBuilder as BlockBuilderAPI}, genesis, consensus};

/// Type that implements `futures::Stream` of block import events.
pub type ImportNotifications<Block> = mpsc::UnboundedReceiver<BlockImportNotification<Block>>;
Expand Down
3 changes: 2 additions & 1 deletion core/client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ extern crate kvdb;
#[cfg(test)] #[macro_use] extern crate hex_literal;
#[cfg(test)] extern crate kvdb_memorydb;

#[macro_use]
pub mod runtime_api;
pub mod error;
pub mod blockchain;
pub mod backend;
Expand All @@ -56,7 +58,6 @@ mod leaves;
mod call_executor;
mod client;
mod notifications;
pub mod runtime_api;

pub use blockchain::Info as ChainInfo;
pub use call_executor::{CallResult, CallExecutor, LocalCallExecutor};
Expand Down
32 changes: 5 additions & 27 deletions core/client/src/runtime_api/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,38 +14,15 @@
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.

use super::{ConstructRuntimeApi, ApiExt};
use runtime_version::RuntimeVersion;
use runtime_primitives::{traits::{Block as BlockT, ApiRef}, generic::BlockId};
use runtime_primitives::{traits::Block as BlockT, generic::BlockId};
use primitives::AuthorityId;
use error::Result;
use state_machine::OverlayedChanges;
use std::result;

/// Something that can be constructed to a runtime api.
pub trait ConstructRuntimeApi<Block: BlockT>: Sized {
/// Construct the runtime api.
fn construct_runtime_api<'a, T: CallApiAt<Block>>(call: &'a T) -> ApiRef<'a, Self>;
}

pub trait ApiExt {
fn map_api_result<F: FnOnce(&Self) -> result::Result<R, E>, R, E>(&self, map_call: F) -> result::Result<R, E>;
}

/// Something that can call into the runtime.
pub trait CallApiAt<Block: BlockT> {
/// Call the given API function with the given arguments and returns the result at the given
/// block.
fn call_api_at(
&self,
at: &BlockId<Block>,
function: &'static str,
args: Vec<u8>,
changes: &mut OverlayedChanges,
initialised_block: &mut Option<BlockId<Block>>,
) -> Result<Vec<u8>>;
}

/// The `Core` api trait that is mandantory for each runtime.
/// This is the side that should be implemented for the `RuntimeApi` that is used by the `Client`.
/// Any modifications at one of these two traits, needs to be done on the other one as well.
pub trait Core<Block: BlockT>: 'static + Send + Sync + ConstructRuntimeApi<Block> + ApiExt {
/// Returns the version of the runtime.
fn version(&self, at: &BlockId<Block>) -> Result<RuntimeVersion>;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this file looks very boilerplatey given there are two instances of the same API with minor differences...

Expand All @@ -65,6 +42,7 @@ pub mod runtime {
use super::*;

/// The `Core` api trait that is mandantory for each runtime.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

spaces!

/// This is the side that should be implemented for the `Runtime`.
pub trait Core<Block: BlockT> {
/// Returns the version of the runtime.
fn version() -> RuntimeVersion;
Expand Down
55 changes: 27 additions & 28 deletions core/client/src/runtime_api/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
/// # Example:
///
/// ```nocompile
/// decl_apis!{
/// decl_runtime_apis!{
/// pub trait Test<Event> ExtraClientSide<ClientArg> {
/// fn test<AccountId>(event: Event) -> AccountId;
///
Expand Down Expand Up @@ -49,11 +49,11 @@
/// }
/// ```
///
/// The declarations generated in the `runtime` module will be used by `impl_apis!` for implementing
/// The declarations generated in the `runtime` module will be used by `impl_runtime_apis!` for implementing
/// the traits for a runtime. The other declarations should be used for implementing the interface
/// in the client.
#[macro_export]
macro_rules! decl_apis {
macro_rules! decl_runtime_apis {
(
$(
$( #[$attr:meta] )*
Expand All @@ -72,7 +72,7 @@ macro_rules! decl_apis {
)*
) => {
$(
decl_apis!(
decl_runtime_apis!(
@ADD_BLOCK_GENERIC
$( #[$attr] )*
pub trait $name $(< $( $generic_param $( : $generic_bound )* ),* >)* {
Expand All @@ -90,7 +90,7 @@ macro_rules! decl_apis {
$( $( $generic_param $( : $generic_bound )* ),* )*
);
)*
decl_apis! {
decl_runtime_apis! {
@GENERATE_RUNTIME_TRAITS
$(
$( #[$attr] )*
Expand Down Expand Up @@ -119,7 +119,7 @@ macro_rules! decl_apis {
Block: BlockT
$(, $generic_param_rest:ident $( : $generic_bound_rest:ident )* )*
) => {
decl_apis!(
decl_runtime_apis!(
@ADD_BLOCK_GENERIC
$( #[$attr] )*
pub trait $name $(< $( $generic_param_orig $( : $generic_bound_orig )* ),* >)* {
Expand Down Expand Up @@ -152,7 +152,7 @@ macro_rules! decl_apis {
$generic_param:ident $( : $generic_bound:ident )*
$(, $generic_param_rest:ident $( : $generic_bound_rest:ident )* )*
) => {
decl_apis!(
decl_runtime_apis!(
@ADD_BLOCK_GENERIC
$( #[$attr] )*
pub trait $name $(< $( $generic_param_orig $( : $generic_bound_orig )* ),* >)* {
Expand Down Expand Up @@ -183,7 +183,7 @@ macro_rules! decl_apis {
Found;
$( $generic_param_parsed:ident $( : $generic_bound_parsed:path )* ),*;
) => {
decl_apis!(
decl_runtime_apis!(
@GENERATE_RETURN_TYPES
$( #[$attr] )*
pub trait $name $(< $( $generic_param_orig $( : $generic_bound_orig )* ),* >)* {
Expand Down Expand Up @@ -214,7 +214,7 @@ macro_rules! decl_apis {
;
$( $generic_param_parsed:ident $( : $generic_bound_parsed:ident )* ),*;
) => {
decl_apis!(
decl_runtime_apis!(
@GENERATE_RETURN_TYPES
$( #[$attr] )*
pub trait $name $(< $( $generic_param_orig $( : $generic_bound_orig )* ),* >)* {
Expand Down Expand Up @@ -248,7 +248,7 @@ macro_rules! decl_apis {
$return_ty_current:ty;
$( $( $return_ty_rest:ty )*; )*
) => {
decl_apis!(
decl_runtime_apis!(
@GENERATE_RETURN_TYPES
$( #[$attr] )*
pub trait $name $(< $( $generic_param_orig $( : $generic_bound_orig )* ),* >)* {
Expand Down Expand Up @@ -281,7 +281,7 @@ macro_rules! decl_apis {
;
$( $( $return_ty_rest:ty )*; )*
) => {
decl_apis!(
decl_runtime_apis!(
@GENERATE_RETURN_TYPES
$( #[$attr] )*
pub trait $name $(< $( $generic_param_orig $( : $generic_bound_orig )* ),* >)* {
Expand Down Expand Up @@ -312,7 +312,7 @@ macro_rules! decl_apis {
$( $generic_param_parsed:ident $( : $generic_bound_parsed:path )* ),*;
{ $( $result_return_ty:ty; )* };
) => {
decl_apis!(
decl_runtime_apis!(
@GENERATE_CLIENT_TRAITS
$( #[$attr] )*
pub trait $name $(< $( $generic_param_orig $( : $generic_bound_orig )* ),* >)* {
Expand Down Expand Up @@ -343,7 +343,7 @@ macro_rules! decl_apis {
{ $( $result_return_ty:ty; )* };
) => {
$( #[$attr] )*
pub trait $name < $( $generic_param_parsed $( : $generic_bound_parsed )* ),* > : $crate::runtime_api::core::Core<Block> {
pub trait $name < $( $generic_param_parsed $( : $generic_bound_parsed )* ),* > : $crate::runtime_api::Core<Block> {
$( type $client_generic_param $( : $client_generic_bound )*; )*

$(
Expand All @@ -367,7 +367,7 @@ macro_rules! decl_apis {
};
)*
) => {
decl_apis! {
decl_runtime_apis! {
@GENERATE_RUNTIME_TRAITS_WITH_JOINED_GENERICS
$(
$( #[$attr] )*
Expand Down Expand Up @@ -409,7 +409,7 @@ macro_rules! decl_apis {
}

/// Implement the given API's for the given runtime.
/// All desired API's need to be implemented in one `impl_apis!` call.
/// All desired API's need to be implemented in one `impl_runtime_apis!` call.
/// Besides generating the implementation for the runtime, there will be also generated an
/// auxiliary module named `api` that contains function for inferring with the API in native/wasm.
/// It is important to use the traits from the `runtime` module with this macro.
Expand All @@ -418,18 +418,17 @@ macro_rules! decl_apis {
///
/// ```nocompile
/// #[macro_use]
/// extern crate sr_api as runtime_api;
/// extern crate substrate_client as client;
///
/// use runtime_api::runtime::{Core, TaggedTransactionQueue};
/// use client::runtime_api::runtime::{Core, TaggedTransactionQueue};
///
/// impl_apis! {
/// impl Core<Block, AccountId> for Runtime {
/// fn version() -> RuntimeVersion { 1 }
/// fn authorities() -> Vec<AuthorityId> { vec![1] }
/// impl_runtime_apis! {
/// impl Core<Block> for Runtime {
/// fn version() -> RuntimeVersion { unimplemented!() }
/// fn authorities() -> Vec<AuthorityId> { unimplemented!() }
/// fn execute_block(block: Block) {
/// //comment
/// let block = call_arbitrary_code(block);
/// execute(block);
/// unimplemented!()
/// }
/// }
///
Expand All @@ -443,7 +442,7 @@ macro_rules! decl_apis {
/// fn main() {}
/// ```
#[macro_export]
macro_rules! impl_apis {
macro_rules! impl_runtime_apis {
(
impl $trait_name:ident $( < $( $generic:ident ),* > )* for $runtime:ident {
$(
Expand All @@ -461,7 +460,7 @@ macro_rules! impl_apis {
}
)*
}
impl_apis! {
impl_runtime_apis! {
$runtime;
$( $fn_name ( $( $arg_name: $arg_ty ),* ); )*;
$( $rest )*
Expand All @@ -486,7 +485,7 @@ macro_rules! impl_apis {
}
)*
}
impl_apis! {
impl_runtime_apis! {
$runtime;
$( $fn_name_parsed ( $( $arg_name_parsed: $arg_ty_parsed ),* ); )*
$( $fn_name ( $( $arg_name: $arg_ty ),* ); )*;
Expand All @@ -505,7 +504,7 @@ macro_rules! impl_apis {
match method {
$(
stringify!($fn_name) => {
Some({impl_apis! {
Some({impl_runtime_apis! {
@GENERATE_IMPL_CALL
$runtime;
$fn_name;
Expand All @@ -530,7 +529,7 @@ macro_rules! impl_apis {
}
};

let output = { impl_apis! {
let output = { impl_runtime_apis! {
@GENERATE_IMPL_CALL
$runtime;
$fn_name;
Expand Down
Loading