Refactor sr-api to not depend on client anymore (#4086)

* Refactor sr-api to not depend on client anymore

* Fix benches

* Apply suggestions from code review

Co-Authored-By: Tomasz Drwięga <tomusdrw@users.noreply.github.com>

* Apply suggestions from code review
This commit is contained in:
Bastian Köcher
2019-11-11 16:26:49 +01:00
committed by Benjamin Kampmann
parent e26d1a0b3e
commit 2ecffa1cd0
140 changed files with 1514 additions and 984 deletions
+2 -1
View File
@@ -11,9 +11,10 @@ futures = { version = "0.3.0", features = ["thread-pool"] }
codec = { package = "parity-scale-codec", version = "1.0.0" }
parking_lot = "0.9.0"
sr-primitives = { path = "../sr-primitives" }
client = { package = "substrate-client", path = "../client" }
primitives = { package = "substrate-primitives", path = "../primitives" }
txpool = { package = "substrate-transaction-graph", path = "./graph" }
tx-runtime-api = { package = "substrate-transaction-pool-runtime-api", path = "runtime-api" }
sr-api = { path = "../sr-api" }
[dev-dependencies]
keyring = { package = "substrate-keyring", path = "../../core/keyring" }
@@ -0,0 +1,14 @@
[package]
name = "substrate-transaction-pool-runtime-api"
version = "2.0.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
[dependencies]
sr-primitives = { path = "../../sr-primitives", default-features = false }
primitives = { package = "substrate-primitives", path = "../../primitives", default-features = false }
sr-api = { path = "../../sr-api", default-features = false }
[features]
default = [ "std" ]
std = [ "sr-primitives/std", "primitives/std", "sr-api/std" ]
@@ -0,0 +1,29 @@
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate 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.
// Substrate 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 Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Substrate runtime api for the transaction queue.
#![cfg_attr(not(feature = "std"), no_std)]
use sr_primitives::{transaction_validity::TransactionValidity, traits::Block as BlockT};
sr_api::decl_runtime_apis! {
/// The `TaggedTransactionQueue` api trait for interfering with the transaction queue.
pub trait TaggedTransactionQueue {
/// Validate the given transaction.
fn validate_transaction(tx: <Block as BlockT>::Extrinsic) -> TransactionValidity;
}
}
+31 -35
View File
@@ -16,31 +16,19 @@
//! Chain api required for the transaction pool.
use std::{
marker::PhantomData,
pin::Pin,
sync::Arc,
};
use client::{runtime_api::TaggedTransactionQueue, blockchain::HeaderBackend};
use codec::Encode;
use futures::{
channel::oneshot,
executor::{ThreadPool, ThreadPoolBuilder},
future::Future,
};
use txpool;
use primitives::{
H256,
Blake2Hasher,
Hasher,
};
use sr_primitives::{
generic::BlockId,
traits,
transaction_validity::TransactionValidity,
};
use std::{marker::PhantomData, pin::Pin, sync::Arc};
use crate::error;
use codec::Encode;
use futures::{channel::oneshot, executor::{ThreadPool, ThreadPoolBuilder}, future::Future};
use primitives::{H256, Blake2Hasher, Hasher};
use sr_primitives::{generic::BlockId, traits, transaction_validity::TransactionValidity};
use tx_runtime_api::TaggedTransactionQueue;
use crate::error::{self, Error};
/// The transaction pool logic
pub struct FullChainApi<T, Block> {
@@ -51,7 +39,7 @@ pub struct FullChainApi<T, Block> {
impl<T, Block> FullChainApi<T, Block> where
Block: traits::Block,
T: traits::ProvideRuntimeApi + HeaderBackend<Block> {
T: traits::ProvideRuntimeApi + traits::BlockIdTo<Block> {
/// Create new transaction pool logic.
pub fn new(client: Arc<T>) -> Self {
FullChainApi {
@@ -67,14 +55,15 @@ impl<T, Block> FullChainApi<T, Block> where
}
impl<T, Block> txpool::ChainApi for FullChainApi<T, Block> where
Block: traits::Block<Hash=H256>,
T: traits::ProvideRuntimeApi + HeaderBackend<Block> + 'static,
T::Api: TaggedTransactionQueue<Block>
Block: traits::Block<Hash = H256>,
T: traits::ProvideRuntimeApi + traits::BlockIdTo<Block> + 'static + Send + Sync,
T::Api: TaggedTransactionQueue<Block>,
sr_api::ApiErrorFor<T, Block>: Send,
{
type Block = Block;
type Hash = H256;
type Error = error::Error;
type ValidationFuture = Pin<Box<dyn Future<Output=error::Result<TransactionValidity>> + Send>>;
type ValidationFuture = Pin<Box<dyn Future<Output = error::Result<TransactionValidity>> + Send>>;
fn validate_transaction(
&self,
@@ -86,7 +75,8 @@ impl<T, Block> txpool::ChainApi for FullChainApi<T, Block> where
let at = at.clone();
self.pool.spawn_ok(async move {
let res = client.runtime_api().validate_transaction(&at, uxt).map_err(Into::into);
let res = client.runtime_api().validate_transaction(&at, uxt)
.map_err(|e| Error::RuntimeApi(format!("{:?}", e)));
if let Err(e) = tx.send(res) {
log::warn!("Unable to send a validate transaction result: {:?}", e);
}
@@ -95,17 +85,23 @@ impl<T, Block> txpool::ChainApi for FullChainApi<T, Block> where
Box::pin(async move {
match rx.await {
Ok(r) => r,
Err(e) => Err(client::error::Error::Msg(format!("{}", e)))?,
Err(_) => Err(Error::RuntimeApi("Validation was canceled".into())),
}
})
}
fn block_id_to_number(&self, at: &BlockId<Self::Block>) -> error::Result<Option<txpool::NumberFor<Self>>> {
Ok(self.client.block_number_from_id(at)?)
fn block_id_to_number(
&self,
at: &BlockId<Self::Block>,
) -> error::Result<Option<txpool::NumberFor<Self>>> {
self.client.to_number(at).map_err(|e| Error::BlockIdConversion(format!("{:?}", e)))
}
fn block_id_to_hash(&self, at: &BlockId<Self::Block>) -> error::Result<Option<txpool::BlockHash<Self>>> {
Ok(self.client.block_hash_from_id(at)?)
fn block_id_to_hash(
&self,
at: &BlockId<Self::Block>,
) -> error::Result<Option<txpool::BlockHash<Self>>> {
self.client.to_hash(at).map_err(|e| Error::BlockIdConversion(format!("{:?}", e)))
}
fn hash_and_length(&self, ex: &txpool::ExtrinsicFor<Self>) -> (Self::Hash, usize) {
+6 -6
View File
@@ -16,26 +16,26 @@
//! Transaction pool error.
use client;
use txpool;
/// Transaction pool result.
pub type Result<T> = std::result::Result<T, Error>;
/// Transaction pool error type.
#[derive(Debug, derive_more::Display, derive_more::From)]
pub enum Error {
/// Client error.
Client(client::error::Error),
/// Pool error.
Pool(txpool::error::Error),
/// Error while converting a `BlockId`.
BlockIdConversion(String),
/// Error while calling the runtime api.
RuntimeApi(String),
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Client(ref err) => Some(err),
Error::Pool(ref err) => Some(err),
Error::BlockIdConversion(_) => None,
Error::RuntimeApi(_) => None,
}
}
}
+1 -2
View File
@@ -20,10 +20,9 @@
#![warn(unused_extern_crates)]
mod api;
pub mod error;
#[cfg(test)]
mod tests;
pub mod error;
pub use api::FullChainApi;
pub use txpool;