Skip to content

Commit

Permalink
changes based on substrate-client-api
Browse files Browse the repository at this point in the history
  • Loading branch information
BillyWooo committed Feb 3, 2023
1 parent 97398da commit ab24686
Show file tree
Hide file tree
Showing 21 changed files with 3,564 additions and 806 deletions.
1,364 changes: 867 additions & 497 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion app-libs/stf/src/stf_sgx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ where
type Hash = Runtime::Hash;

fn get_events(state: &mut State) -> Vec<Box<Self::EventRecord>> {
state.execute_with(|| frame_system::Pallet::<Runtime>::read_events_no_consensus())
state.execute_with(|| frame_system::Pallet::<Runtime>::read_events_no_consensus().collect::<Vec<_>>())
}

fn get_event_count(state: &mut State) -> Self::EventIndex {
Expand Down
5 changes: 3 additions & 2 deletions cli/src/base_cli/commands/faucet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,14 @@ pub struct FaucetCommand {

impl FaucetCommand {
pub(crate) fn run(&self, cli: &Cli) {
let api = get_chain_api(cli).set_signer(AccountKeyring::Alice.pair());
let mut api = get_chain_api(cli);
api.set_signer(AccountKeyring::Alice.pair());
let mut nonce = api.get_nonce().unwrap();
for account in &self.accounts {
let to = get_accountid_from_str(account);
#[allow(clippy::redundant_clone)]
let xt: UncheckedExtrinsicV4<_, _> = compose_extrinsic_offline!(
api.clone().signer.unwrap(),
api.clone().signer().unwrap(),
RuntimeCall::Balances(BalancesCall::transfer {
dest: MultiAddress::Id(to.clone()),
value: PREFUNDING_AMOUNT
Expand Down
4 changes: 2 additions & 2 deletions cli/src/base_cli/commands/shield_funds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub struct ShieldFundsCommand {

impl ShieldFundsCommand {
pub(crate) fn run(&self, cli: &Cli) {
let chain_api = get_chain_api(cli);
let mut chain_api = get_chain_api(cli);

let shard_opt = match self.shard.from_base58() {
Ok(s) => ShardIdentifier::decode(&mut &s[..]),
Expand All @@ -60,7 +60,7 @@ impl ShieldFundsCommand {

// get the sender
let from = get_pair_from_str(&self.from);
let chain_api = chain_api.set_signer(sr25519_core::Pair::from(from));
chain_api.set_signer(sr25519_core::Pair::from(from));

// get the recipient
let to = get_accountid_from_str(&self.to);
Expand Down
3 changes: 2 additions & 1 deletion cli/src/base_cli/commands/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ impl TransferCommand {
let to_account = get_accountid_from_str(&self.to);
info!("from ss58 is {}", from_account.public().to_ss58check());
info!("to ss58 is {}", to_account.to_ss58check());
let api = get_chain_api(cli).set_signer(sr25519_core::Pair::from(from_account));
let mut api = get_chain_api(cli);
api.set_signer(sr25519_core::Pair::from(from_account));
let xt = api.balance_transfer(GenericAddress::Id(to_account.clone()), self.amount);
let tx_hash = api.send_extrinsic(xt.hex_encode(), XtStatus::InBlock).unwrap();
println!("[+] TrustedOperation got finalized. Hash: {:?}\n", tx_hash);
Expand Down
2 changes: 1 addition & 1 deletion cli/src/base_cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ fn list_accounts() {
}

fn print_metadata(cli: &Cli) {
let meta = get_chain_api(cli).get_metadata().unwrap();
let meta = get_chain_api(cli).metadata().metadata.clone();
println!("Metadata:\n {}", Metadata::pretty_format(&meta).unwrap());
}

Expand Down
14 changes: 7 additions & 7 deletions cli/src/trusted_operation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,38 +107,38 @@ fn send_request(
trusted_args: &TrustedCli,
trusted_operation: &TrustedOperation,
) -> Option<Vec<u8>> {
let chain_api = get_chain_api(cli);
let mut chain_api = get_chain_api(cli);
let encryption_key = get_shielding_key(cli).unwrap();
let call_encrypted = encryption_key.encrypt(&trusted_operation.encode()).unwrap();

let shard = read_shard(trusted_args).unwrap();

let arg_signer = &trusted_args.xt_signer;
let signer = get_pair_from_str(arg_signer);
let _chain_api = chain_api.set_signer(sr25519_core::Pair::from(signer));
chain_api.set_signer(sr25519_core::Pair::from(signer));

let request = Request { shard, cyphertext: call_encrypted };
let xt = compose_extrinsic!(_chain_api, TEEREX, "call_worker", request);
let xt = compose_extrinsic!(chain_api, TEEREX, "call_worker", request);

// send and watch extrinsic until block is executed
let block_hash =
_chain_api.send_extrinsic(xt.hex_encode(), XtStatus::InBlock).unwrap().unwrap();
chain_api.send_extrinsic(xt.hex_encode(), XtStatus::InBlock).unwrap().unwrap();

info!(
"Trusted call extrinsic sent and successfully included in parentchain block with hash {:?}.",
block_hash
);
info!("Waiting for execution confirmation from enclave...");
let (events_in, events_out) = channel();
_chain_api.subscribe_events(events_in).unwrap();
chain_api.subscribe_events(events_in).unwrap();

loop {
let ret: ProcessedParentchainBlockArgs =
_chain_api.wait_for_event::<ProcessedParentchainBlockArgs>(&events_out).unwrap();
chain_api.wait_for_event::<ProcessedParentchainBlockArgs>(&events_out).unwrap();
info!("Confirmation of ProcessedParentchainBlock received");
debug!("Expected block Hash: {:?}", block_hash);
debug!("Confirmed stf block Hash: {:?}", ret.block_hash);
match _chain_api.get_header::<Header>(Some(block_hash)) {
match chain_api.get_header::<Header>(Some(block_hash)) {
Ok(option) => {
match option {
None => {
Expand Down
10 changes: 6 additions & 4 deletions core-primitives/node-api/api-client-extensions/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive
thiserror = { version = "1.0" }

# substrate
sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.36" }
sp-finality-grandpa = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.36" }
sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.36" }
sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.37" }
sp-finality-grandpa = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.37" }
sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.37" }
sp-rpc = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.37" }

# scs
substrate-api-client = { git = "https://github.com/scs/substrate-api-client.git", branch = "polkadot-v0.9.36" }
substrate-api-client = { default-features = false, git = "https://github.com/scs/substrate-api-client.git", branch = "polkadot-v0.9.37" }
my-node-runtime = { package = "integritee-node-runtime", git = "https://github.com/integritee-network/integritee-node.git", branch = "polkadot-v0.9.37" }

# local deps
itp-types = { path = "../../types" }
Expand Down
24 changes: 17 additions & 7 deletions core-primitives/node-api/api-client-extensions/src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,33 @@ use crate::ApiResult;
use itp_types::AccountId;
use sp_core::crypto::Pair;
use sp_runtime::MultiSignature;
use substrate_api_client::{Api, ExtrinsicParams, RpcClient};
use sp_rpc::number::NumberOrHex;
use substrate_api_client::{Api, ExtrinsicParams, RpcClient, BalancesConfig, FromHexString};

use codec::Decode;
use core::str::FromStr;

/// ApiClient extension that contains some convenience methods around accounts.
pub trait AccountApi {
fn get_nonce_of(&self, who: &AccountId) -> ApiResult<u32>;
fn get_free_balance(&self, who: &AccountId) -> ApiResult<u128>;
// fn get_free_balance(&self, who: &AccountId) -> ApiResult<u128>;
}

impl<P: Pair, Client: RpcClient, Params: ExtrinsicParams> AccountApi for Api<P, Client, Params>
impl<P: Pair, Client: RpcClient, Params, Runtime> AccountApi for Api<P, Client, Params, Runtime>
where
MultiSignature: From<P::Signature>,
Params: ExtrinsicParams<Runtime::Index, Runtime::Hash>,
Runtime: BalancesConfig,
Runtime::Hash: FromHexString,
Runtime::Index: Into<u32> + Decode,
Runtime::Balance: TryFrom<NumberOrHex> + FromStr + Into<u128>,
{
fn get_nonce_of(&self, who: &AccountId) -> ApiResult<u32> {
Ok(self.get_account_info(who)?.map_or_else(|| 0, |info| info.nonce))
Ok(self.get_account_info(who)?.map_or_else(|| 0, |info| info.nonce.into()))
}

fn get_free_balance(&self, who: &AccountId) -> ApiResult<u128> {
Ok(self.get_account_data(who)?.map_or_else(|| 0, |data| data.free))
}
// fn get_free_balance(&self, who: &AccountId) -> ApiResult<u128> {
// Ok(self.get_account_info(who)?.map_or_else(|| 0, |info| info.data.free.into()))
// }

}
38 changes: 24 additions & 14 deletions core-primitives/node-api/api-client-extensions/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,54 +20,64 @@ use itp_types::{Header, SignedBlock};
use sp_core::{storage::StorageKey, Pair, H256};
use sp_finality_grandpa::{AuthorityList, VersionedAuthorityList, GRANDPA_AUTHORITIES_KEY};
use sp_runtime::MultiSignature;
use substrate_api_client::{Api, ExtrinsicParams, RpcClient};
use sp_rpc::number::NumberOrHex;
use substrate_api_client::{Api, ExtrinsicParams, RpcClient, BalancesConfig, FromHexString, FrameSystemConfig};

use codec::Decode;
use core::str::FromStr;


pub type StorageProof = Vec<Vec<u8>>;

/// ApiClient extension that simplifies chain data access.
pub trait ChainApi {
pub trait ChainApi <Runtime: FrameSystemConfig> {
fn last_finalized_block(&self) -> ApiResult<Option<SignedBlock>>;
fn signed_block(&self, hash: Option<H256>) -> ApiResult<Option<SignedBlock>>;
fn get_genesis_hash(&self) -> ApiResult<H256>;
fn get_header(&self, header_hash: Option<H256>) -> ApiResult<Option<Header>>;
fn signed_block(&self, hash: Option<Runtime::Hash>) -> ApiResult<Option<SignedBlock>>;
fn get_genesis_hash(&self) -> ApiResult<Runtime::Hash>;
fn get_header(&self, header_hash: Option<Runtime::Hash>) -> ApiResult<Option<Header>>;
/// Fetch blocks from parentchain with blocknumber from until to, including both boundaries.
/// Returns a vector with one element if from equals to.
/// Returns an empty vector if from is greater than to.
fn get_blocks(&self, from: u32, to: u32) -> ApiResult<Vec<SignedBlock>>;
fn is_grandpa_available(&self) -> ApiResult<bool>;
fn grandpa_authorities(&self, hash: Option<H256>) -> ApiResult<AuthorityList>;
fn grandpa_authorities_proof(&self, hash: Option<H256>) -> ApiResult<StorageProof>;
fn grandpa_authorities(&self, hash: Option<Runtime::Hash>) -> ApiResult<AuthorityList>;
fn grandpa_authorities_proof(&self, hash: Option<Runtime::Hash>) -> ApiResult<StorageProof>;
}

impl<P: Pair, Client: RpcClient, Params: ExtrinsicParams> ChainApi for Api<P, Client, Params>
impl<P: Pair, Client: RpcClient, Params, Runtime> ChainApi <Runtime> for Api<P, Client, Params, Runtime>
where
MultiSignature: From<P::Signature>,
Params: ExtrinsicParams<Runtime::Index, Runtime::Hash>,
Runtime: BalancesConfig,
Runtime::Hash: FromHexString + From<H256> + Into<H256>,
Runtime::Index: Into<u32> + Decode,
Runtime::Balance: TryFrom<NumberOrHex> + FromStr + Into<u128>,
{
fn last_finalized_block(&self) -> ApiResult<Option<SignedBlock>> {
self.get_finalized_head()?
.map_or_else(|| Ok(None), |hash| self.signed_block(Some(hash)))
}

fn signed_block(&self, hash: Option<H256>) -> ApiResult<Option<SignedBlock>> {
fn signed_block(&self, hash: Option<Runtime::Hash>) -> ApiResult<Option<SignedBlock>> {
// Even though this is only a wrapper here, we want to have this in the trait
// to be able to be generic over the trait and mock the `signed_block` method
// in tests.
self.get_signed_block(hash)
}

fn get_genesis_hash(&self) -> ApiResult<H256> {
fn get_genesis_hash(&self) -> ApiResult<Runtime::Hash> {
self.get_genesis_hash()
}

fn get_header(&self, header_hash: Option<H256>) -> ApiResult<Option<Header>> {
fn get_header(&self, header_hash: Option<Runtime::Hash>) -> ApiResult<Option<Header>> {
self.get_header(header_hash)
}

fn get_blocks(&self, from: u32, to: u32) -> ApiResult<Vec<SignedBlock>> {
let mut blocks = Vec::<SignedBlock>::new();

for n in from..=to {
if let Some(block) = self.get_signed_block_by_num(Some(n))? {
if let Some(block) = self.get_signed_block_by_num(Some(n.into()))? {
blocks.push(block);
}
}
Expand All @@ -83,14 +93,14 @@ where
.unwrap_or(false))
}

fn grandpa_authorities(&self, at_block: Option<H256>) -> ApiResult<AuthorityList> {
fn grandpa_authorities(&self, at_block: Option<Runtime::Hash>) -> ApiResult<AuthorityList> {
Ok(self
.get_storage_by_key_hash(StorageKey(GRANDPA_AUTHORITIES_KEY.to_vec()), at_block)?
.map(|g: VersionedAuthorityList| g.into())
.unwrap_or_default())
}

fn grandpa_authorities_proof(&self, at_block: Option<H256>) -> ApiResult<StorageProof> {
fn grandpa_authorities_proof(&self, at_block: Option<Runtime::Hash>) -> ApiResult<StorageProof> {
Ok(self
.get_storage_proof_by_keys(
vec![StorageKey(GRANDPA_AUTHORITIES_KEY.to_vec())],
Expand Down
37 changes: 23 additions & 14 deletions core-primitives/node-api/api-client-extensions/src/pallet_teerex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,43 +17,52 @@

use crate::ApiResult;
use itp_types::{Enclave, IpfsHash, ShardIdentifier};
use sp_core::{Pair, H256 as Hash};
use sp_core::Pair;
use sp_runtime::MultiSignature;
use substrate_api_client::{Api, ExtrinsicParams, RpcClient};
use sp_rpc::number::NumberOrHex;
use substrate_api_client::{Api, ExtrinsicParams, RpcClient, BalancesConfig, FromHexString};

use codec::Decode;
use core::str::FromStr;

pub const TEEREX: &str = "Teerex";
pub const SIDECHAIN: &str = "Sidechain";

/// ApiClient extension that enables communication with the `teerex` pallet.
pub trait PalletTeerexApi {
fn enclave(&self, index: u64, at_block: Option<Hash>) -> ApiResult<Option<Enclave>>;
fn enclave_count(&self, at_block: Option<Hash>) -> ApiResult<u64>;
fn all_enclaves(&self, at_block: Option<Hash>) -> ApiResult<Vec<Enclave>>;
pub trait PalletTeerexApi <Runtime: BalancesConfig> {
fn enclave(&self, index: u64, at_block: Option<Runtime::Hash>) -> ApiResult<Option<Enclave>>;
fn enclave_count(&self, at_block: Option<Runtime::Hash>) -> ApiResult<u64>;
fn all_enclaves(&self, at_block: Option<Runtime::Hash>) -> ApiResult<Vec<Enclave>>;
fn worker_for_shard(
&self,
shard: &ShardIdentifier,
at_block: Option<Hash>,
at_block: Option<Runtime::Hash>,
) -> ApiResult<Option<Enclave>>;
fn latest_ipfs_hash(
&self,
shard: &ShardIdentifier,
at_block: Option<Hash>,
at_block: Option<Runtime::Hash>,
) -> ApiResult<Option<IpfsHash>>;
}

impl<P: Pair, Client: RpcClient, Params: ExtrinsicParams> PalletTeerexApi for Api<P, Client, Params>
impl<P: Pair, Client: RpcClient, Params, Runtime> PalletTeerexApi <Runtime> for Api<P, Client, Params, Runtime>
where
MultiSignature: From<P::Signature>,
Params: ExtrinsicParams<Runtime::Index, Runtime::Hash>,
Runtime: BalancesConfig,
Runtime::Hash: FromHexString,
Runtime::Index: Into<u32> + Decode,
Runtime::Balance: TryFrom<NumberOrHex> + FromStr + Into<u128>,
{
fn enclave(&self, index: u64, at_block: Option<Hash>) -> ApiResult<Option<Enclave>> {
fn enclave(&self, index: u64, at_block: Option<Runtime::Hash>) -> ApiResult<Option<Enclave>> {
self.get_storage_map(TEEREX, "EnclaveRegistry", index, at_block)
}

fn enclave_count(&self, at_block: Option<Hash>) -> ApiResult<u64> {
fn enclave_count(&self, at_block: Option<Runtime::Hash>) -> ApiResult<u64> {
Ok(self.get_storage_value(TEEREX, "EnclaveCount", at_block)?.unwrap_or(0u64))
}

fn all_enclaves(&self, at_block: Option<Hash>) -> ApiResult<Vec<Enclave>> {
fn all_enclaves(&self, at_block: Option<Runtime::Hash>) -> ApiResult<Vec<Enclave>> {
let count = self.enclave_count(at_block)?;
let mut enclaves = Vec::with_capacity(count as usize);
for n in 1..=count {
Expand All @@ -65,7 +74,7 @@ where
fn worker_for_shard(
&self,
shard: &ShardIdentifier,
at_block: Option<Hash>,
at_block: Option<Runtime::Hash>,
) -> ApiResult<Option<Enclave>> {
self.get_storage_map(SIDECHAIN, "WorkerForShard", shard, at_block)?
.map_or_else(|| Ok(None), |w_index| self.enclave(w_index, at_block))
Expand All @@ -74,7 +83,7 @@ where
fn latest_ipfs_hash(
&self,
shard: &ShardIdentifier,
at_block: Option<Hash>,
at_block: Option<Runtime::Hash>,
) -> ApiResult<Option<IpfsHash>> {
self.get_storage_map(TEEREX, "LatestIPFSHash", shard, at_block)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

use crate::{pallet_teerex::PalletTeerexApi, ApiResult};
use itp_types::{Enclave, IpfsHash, ShardIdentifier, H256 as Hash};
use my_node_runtime::Runtime;

#[derive(Default)]
pub struct PalletTeerexApiMock {
Expand All @@ -30,7 +31,7 @@ impl PalletTeerexApiMock {
}
}

impl PalletTeerexApi for PalletTeerexApiMock {
impl PalletTeerexApi <Runtime> for PalletTeerexApiMock {
fn enclave(&self, index: u64, _at_block: Option<Hash>) -> ApiResult<Option<Enclave>> {
Ok(self.registered_enclaves.get(index as usize).cloned())
}
Expand Down
5 changes: 3 additions & 2 deletions core-primitives/node-api/api-client-types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ edition = "2021"
[dependencies]

# scs
substrate-api-client = { default-features = false, git = "https://github.com/scs/substrate-api-client.git", branch = "polkadot-v0.9.36" }
substrate-api-client = { default-features = false, git = "https://github.com/scs/substrate-api-client.git", branch = "polkadot-v0.9.37" }
my-node-runtime = { package = "integritee-node-runtime", git = "https://github.com/integritee-network/integritee-node.git", branch = "polkadot-v0.9.37" }

# substrate
sp-core = { optional = true, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.36" }
sp-core = { optional = true, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.37" }


[features]
Expand Down
Loading

0 comments on commit ab24686

Please sign in to comment.