From bb57020f0e6961b3d8f8a6e859bb5680a17fdb0f Mon Sep 17 00:00:00 2001 From: weichweich Date: Fri, 18 Mar 2022 07:45:26 +0100 Subject: [PATCH 01/31] wip: rpc --- Cargo.lock | 28 ++++++ Cargo.toml | 2 + nodes/parachain/Cargo.toml | 1 + nodes/parachain/src/rpc.rs | 10 +- pallets/pallet-web3-names/src/web3_name.rs | 2 - rpc/did/Cargo.toml | 20 ++++ rpc/did/runtime-api/Cargo.toml | 20 ++++ rpc/did/runtime-api/src/lib.rs | 32 ++++++ rpc/did/src/lib.rs | 111 +++++++++++++++++++++ runtimes/common/Cargo.toml | 1 + runtimes/common/src/lib.rs | 15 +++ runtimes/peregrine/Cargo.toml | 18 ++-- runtimes/peregrine/src/lib.rs | 38 ++++++- runtimes/spiritnet/Cargo.toml | 1 + runtimes/spiritnet/src/lib.rs | 37 ++++++- 15 files changed, 319 insertions(+), 17 deletions(-) create mode 100644 rpc/did/Cargo.toml create mode 100644 rpc/did/runtime-api/Cargo.toml create mode 100644 rpc/did/runtime-api/src/lib.rs create mode 100644 rpc/did/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 5e42bcae0b..58ddf5b027 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1909,6 +1909,31 @@ dependencies = [ "substrate-wasm-builder-runner", ] +[[package]] +name = "did-rpc" +version = "1.5.0" +dependencies = [ + "did-rpc-runtime-api", + "jsonrpc-core", + "jsonrpc-core-client", + "jsonrpc-derive", + "parity-scale-codec", + "sp-api", + "sp-blockchain", + "sp-core", + "sp-rpc", + "sp-runtime", +] + +[[package]] +name = "did-rpc-runtime-api" +version = "1.5.0" +dependencies = [ + "parity-scale-codec", + "sp-api", + "sp-runtime", +] + [[package]] name = "digest" version = "0.8.1" @@ -3535,6 +3560,7 @@ dependencies = [ "cumulus-relay-chain-interface", "cumulus-relay-chain-local", "derive_more", + "did-rpc", "frame-benchmarking", "frame-benchmarking-cli", "futures 0.3.21", @@ -6658,6 +6684,7 @@ dependencies = [ "cumulus-primitives-timestamp", "delegation", "did", + "did-rpc-runtime-api", "frame-benchmarking", "frame-executive", "frame-support", @@ -10834,6 +10861,7 @@ dependencies = [ "cumulus-primitives-timestamp", "delegation", "did", + "did-rpc-runtime-api", "frame-benchmarking", "frame-executive", "frame-support", diff --git a/Cargo.toml b/Cargo.toml index 89ae7cf8b4..040d093c24 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,8 @@ panic = "unwind" members = [ "nodes/*", "pallets/*", + "rpc/did", + "rpc/did/runtime-api", "runtimes/*", "support", ] diff --git a/nodes/parachain/Cargo.toml b/nodes/parachain/Cargo.toml index 83eda64dab..939bc76dc8 100644 --- a/nodes/parachain/Cargo.toml +++ b/nodes/parachain/Cargo.toml @@ -19,6 +19,7 @@ substrate-build-script-utils = {git = "https://github.com/paritytech/substrate", peregrine-runtime = {path = "../../runtimes/peregrine"} runtime-common = {path = "../../runtimes/common"} spiritnet-runtime = {path = "../../runtimes/spiritnet"} +did-rpc = {path = "../../rpc/did"} # External dependencies clap = { version = "3.1", features = ["derive"] } diff --git a/nodes/parachain/src/rpc.rs b/nodes/parachain/src/rpc.rs index 0130e35b10..8e6011f5a2 100644 --- a/nodes/parachain/src/rpc.rs +++ b/nodes/parachain/src/rpc.rs @@ -25,6 +25,10 @@ use std::sync::Arc; +use did_rpc::{DidApi, DidQuery}; +use frame_rpc_system::{FullSystem, SystemApi}; +use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; +use peregrine_runtime::{DidDoc, Web3Name}; use polkadot_service::AuxStore; use runtime_common::{AccountId, Balance, Block, Index}; use sc_service::Error; @@ -54,12 +58,10 @@ where C: Send + Sync + 'static, C::Api: frame_rpc_system::AccountNonceApi, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, + C::Api: did_rpc::DidRuntimeApi, C::Api: BlockBuilder, P: TransactionPool + Sync + Send + 'static, { - use frame_rpc_system::{FullSystem, SystemApi}; - use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; - let mut io = jsonrpc_core::IoHandler::default(); let FullDeps { client, @@ -75,6 +77,8 @@ where io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(client))); + io.extend_with(DidApi::to_delegate(DidQuery::new(client))); + // Extend this RPC with a custom API by using the following syntax. // `YourRpcStruct` should have a reference to a client, which is needed // to call into the runtime. diff --git a/pallets/pallet-web3-names/src/web3_name.rs b/pallets/pallet-web3-names/src/web3_name.rs index def58e9518..4b4b935e46 100644 --- a/pallets/pallet-web3-names/src/web3_name.rs +++ b/pallets/pallet-web3-names/src/web3_name.rs @@ -16,8 +16,6 @@ // If you feel like getting in touch with us, you can do so at info@botlabs.org -#![cfg_attr(not(feature = "std"), no_std)] - use sp_std::{fmt::Debug, marker::PhantomData, vec::Vec}; use codec::{Decode, Encode, MaxEncodedLen}; diff --git a/rpc/did/Cargo.toml b/rpc/did/Cargo.toml new file mode 100644 index 0000000000..db8e35a64f --- /dev/null +++ b/rpc/did/Cargo.toml @@ -0,0 +1,20 @@ +[package] +edition = "2021" +name = "did-rpc" +version = "1.5.0" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +codec = {package = "parity-scale-codec", version = "2.3.1"} +jsonrpc-core = "18.0.0" +jsonrpc-core-client = "18.0.0" +jsonrpc-derive = "18.0.0" + +did-rpc-runtime-api = {version = "1.5.0", path = "./runtime-api"} + +sp-api = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} +sp-blockchain = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} +sp-core = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} +sp-rpc = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} +sp-runtime = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} diff --git a/rpc/did/runtime-api/Cargo.toml b/rpc/did/runtime-api/Cargo.toml new file mode 100644 index 0000000000..c71fbc0e2a --- /dev/null +++ b/rpc/did/runtime-api/Cargo.toml @@ -0,0 +1,20 @@ +[package] +edition = "2021" +name = "did-rpc-runtime-api" +version = "1.5.0" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +codec = {package = "parity-scale-codec", version = "2.3.1", default-features = false, features = ["derive"]} + +sp-api = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} +sp-runtime = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} + +[features] +default = ["std"] +std = [ + "codec/std", + "sp-api/std", + "sp-runtime/std", +] diff --git a/rpc/did/runtime-api/src/lib.rs b/rpc/did/runtime-api/src/lib.rs new file mode 100644 index 0000000000..51950fdf72 --- /dev/null +++ b/rpc/did/runtime-api/src/lib.rs @@ -0,0 +1,32 @@ +// KILT Blockchain – https://botlabs.org +// Copyright (C) 2019-2022 BOTLabs GmbH + +// The KILT Blockchain 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. + +// The KILT Blockchain 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 this program. If not, see . + +// If you feel like getting in touch with us, you can do so at info@botlabs.org +#![cfg_attr(not(feature = "std"), no_std)] + +use codec::Codec; + +sp_api::decl_runtime_apis! { + /// The API to query account nonce (aka transaction index). + pub trait DidApi where + Web3Name: Codec, + DidDocument: Codec, + AccountId: Codec, + { + fn query_did_by_w3n(name: Web3Name) -> Option; + fn query_did_by_account_id(account: AccountId) -> Option; + } +} diff --git a/rpc/did/src/lib.rs b/rpc/did/src/lib.rs new file mode 100644 index 0000000000..804c28d8fd --- /dev/null +++ b/rpc/did/src/lib.rs @@ -0,0 +1,111 @@ +// KILT Blockchain – https://botlabs.org +// Copyright (C) 2019-2022 BOTLabs GmbH + +// The KILT Blockchain 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. + +// The KILT Blockchain 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 this program. If not, see . + +// If you feel like getting in touch with us, you can do so at info@botlabs.org + +use std::sync::Arc; + +use codec::Codec; +use jsonrpc_core::{Error as RpcError, ErrorCode, Result}; +use jsonrpc_derive::rpc; +use sp_api::ProvideRuntimeApi; +use sp_blockchain::HeaderBackend; +use sp_runtime::{generic::BlockId, traits::Block as BlockT}; + +pub use did_rpc_runtime_api::DidApi as DidRuntimeApi; + +#[rpc] +pub trait DidApi { + #[rpc(name = "did_queryByWeb3Name")] + fn query_did_by_w3n(&self, web3name: Web3Name, at: Option) -> Result>; + + #[rpc(name = "did_queryByAccount")] + fn query_did_by_account_id(&self, account: AccountId, at: Option) -> Result>; +} + +/// A struct that implements the [`TransactionPaymentApi`]. +pub struct DidQuery { + client: Arc, + _marker: std::marker::PhantomData

, +} + +impl DidQuery { + /// Create new `DidQuery` with the given reference to the client. + pub fn new(client: Arc) -> Self { + Self { + client, + _marker: Default::default(), + } + } +} + +/// Error type of this RPC api. +pub enum Error { + /// The transaction was not decodable. + DecodeError, + /// The call to runtime failed. + RuntimeError, +} + +impl From for i64 { + fn from(e: Error) -> i64 { + match e { + Error::RuntimeError => 1, + Error::DecodeError => 2, + } + } +} + +impl DidApi<::Hash, Web3Name, DidDoc, AccountId> + for DidQuery +where + Web3Name: Codec, + DidDoc: Codec, + AccountId: Codec, + Block: BlockT, + C: 'static + ProvideRuntimeApi + HeaderBackend, + C::Api: DidRuntimeApi, +{ + fn query_did_by_w3n(&self, web3name: Web3Name, at: Option<::Hash>) -> Result> { + let api = self.client.runtime_api(); + let at = BlockId::hash(at.unwrap_or_else(|| + // If the block hash is not supplied assume the best block. + self.client.info().best_hash)); + + api.query_did_by_w3n(&at, web3name).map_err(|e| RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Unable to query dispatch info.".into(), + data: Some(e.to_string().into()), + }) + } + + fn query_did_by_account_id( + &self, + account: AccountId, + at: Option<::Hash>, + ) -> Result> { + let api = self.client.runtime_api(); + let at = BlockId::hash(at.unwrap_or_else(|| + // If the block hash is not supplied assume the best block. + self.client.info().best_hash)); + + api.query_did_by_account_id(&at, account).map_err(|e| RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Unable to query fee details.".into(), + data: Some(e.to_string().into()), + }) + } +} diff --git a/runtimes/common/Cargo.toml b/runtimes/common/Cargo.toml index be65361d4d..6ae4694f0a 100644 --- a/runtimes/common/Cargo.toml +++ b/runtimes/common/Cargo.toml @@ -15,6 +15,7 @@ smallvec = "1.7.0" attestation = {default-features = false, path = "../../pallets/attestation"} parachain-staking = {default-features = false, path = "../../pallets/parachain-staking"} +# pallet-web3-names = {path = "../../pallet-web3-names", default-features = false} frame-support = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} frame-system = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} diff --git a/runtimes/common/src/lib.rs b/runtimes/common/src/lib.rs index 9ff9a63900..4dfdc932a0 100644 --- a/runtimes/common/src/lib.rs +++ b/runtimes/common/src/lib.rs @@ -20,6 +20,9 @@ #![cfg_attr(not(feature = "std"), no_std)] +#[cfg(feature = "std")] +use serde::{Deserialize, Serialize}; + use constants::{AVERAGE_ON_INITIALIZE_RATIO, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO}; use fees::SplitFeesByRatio; @@ -27,15 +30,18 @@ pub use sp_consensus_aura::sr25519::AuthorityId; pub use opaque::*; +use codec::{Decode, Encode}; pub use frame_support::weights::constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; use frame_support::{parameter_types, traits::Currency, weights::DispatchClass}; use frame_system::limits; use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment}; +use scale_info::TypeInfo; use sp_runtime::{ generic, traits::{IdentifyAccount, Verify}, FixedPointNumber, MultiSignature, Perquintill, }; +use sp_std::vec::Vec; pub mod authorization; pub mod constants; @@ -153,3 +159,12 @@ pub type FeeSplit = SplitFeesByRatio; /// https://w3f-research.readthedocs.io/en/latest/polkadot/Token%20Economics.html#-2.-slow-adjusting-mechanism pub type SlowAdjustingFeeUpdate = TargetedFeeAdjustment; + +#[derive(Encode, Decode, TypeInfo, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))] +#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] +pub struct DidDocument { + pub details: DidDetails, + pub web3name: Option, + pub accounts: Vec, +} diff --git a/runtimes/peregrine/Cargo.toml b/runtimes/peregrine/Cargo.toml index 6b15d7797c..74e6e8c8d1 100644 --- a/runtimes/peregrine/Cargo.toml +++ b/runtimes/peregrine/Cargo.toml @@ -20,18 +20,19 @@ serde = {version = "1.0.132", optional = true, features = ["derive"]} # RPC frame-system-rpc-runtime-api = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} pallet-transaction-payment-rpc-runtime-api = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} +did-rpc-runtime-api = {path = "../../rpc/did/runtime-api", default-features = false} # KILT pallets & primitives -attestation = {default-features = false, path = "../../pallets/attestation"} -ctype = {default-features = false, path = "../../pallets/ctype"} -delegation = {default-features = false, path = "../../pallets/delegation"} -did = {default-features = false, path = "../../pallets/did"} +attestation = {path = "../../pallets/attestation", default-features = false} +ctype = {path = "../../pallets/ctype", default-features = false} +delegation = {path = "../../pallets/delegation", default-features = false} +did = {path = "../../pallets/did", default-features = false} kilt-launch = {path = "../../pallets/kilt-launch", default-features = false} kilt-support = {path = "../../support", default-features = false, optional = true} -pallet-web3-names = {default-features = false, path = "../../pallets/pallet-web3-names"} -pallet-did-lookup = {default-features = false, path = "../../pallets/pallet-did-lookup"} +pallet-did-lookup = {path = "../../pallets/pallet-did-lookup", default-features = false} pallet-inflation = {path = "../../pallets/pallet-inflation", default-features = false} -parachain-staking = {default-features = false, path = "../../pallets/parachain-staking"} +pallet-web3-names = {path = "../../pallets/pallet-web3-names", default-features = false} +parachain-staking = {path = "../../pallets/parachain-staking", default-features = false} runtime-common = {path = "../../runtimes/common", default-features = false} # Substrate dependencies @@ -61,7 +62,7 @@ pallet-democracy = {git = "https://github.com/paritytech/substrate", default-fea pallet-indices = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} pallet-membership = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} pallet-preimage = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} -pallet-proxy = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17" } +pallet-proxy = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} pallet-randomness-collective-flip = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} pallet-scheduler = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} pallet-session = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} @@ -132,6 +133,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", ] std = [ + "did-rpc-runtime-api/std", "attestation/std", "codec/std", "ctype/std", diff --git a/runtimes/peregrine/src/lib.rs b/runtimes/peregrine/src/lib.rs index db22575945..849a131c4f 100644 --- a/runtimes/peregrine/src/lib.rs +++ b/runtimes/peregrine/src/lib.rs @@ -46,14 +46,16 @@ use sp_runtime::{ use sp_std::{cmp::Ordering, prelude::*}; use sp_version::RuntimeVersion; + use delegation::DelegationAc; +use did::did_details::DidDetails; pub use parachain_staking::InflationInfo; use runtime_common::{ authorization::{AuthorizationId, PalletAuthorize}, constants::{self, KILT, MICRO_KILT, MILLI_KILT}, fees::{ToAuthor, WeightToFee}, - pallet_id, AccountId, AuthorityId, Balance, BlockHashCount, BlockLength, BlockNumber, BlockWeights, DidIdentifier, - FeeSplit, Hash, Header, Index, Signature, SlowAdjustingFeeUpdate, + pallet_id, AccountId, AuthorityId, Balance, BlockHashCount, BlockLength, BlockNumber, BlockWeights, DidDocument, + DidIdentifier, FeeSplit, Hash, Header, Index, Signature, SlowAdjustingFeeUpdate, }; #[cfg(feature = "std")] @@ -968,6 +970,13 @@ pub type Executive = frame_executive::Executive< pallet_did_lookup::migrations::LookupReverseIndexMigration, >; + +pub type Web3Name = pallet_web3_names::web3_name::AsciiWeb3Name; +pub type DidDoc = DidDocument< + DidDetails, + pallet_web3_names::web3_name::AsciiWeb3Name, +>; + impl_runtime_apis! { impl sp_api::Core for Runtime { fn version() -> RuntimeVersion { @@ -1072,6 +1081,31 @@ impl_runtime_apis! { } } + impl did_rpc_runtime_api::DidApi< + Block, + Web3Name, + DidDoc, + AccountId + > for Runtime { + fn query_did_by_w3n(name: Web3Name) -> Option { + pallet_web3_names::Owner::::get(&name) + .and_then(|owner_info| { + did::Did::::get(owner_info.owner) + }) + .and_then(|did_details| { + Some(DidDoc { + accounts: vec![], + details: did_details, + web3name: Some(name), + }) + }) + } + fn query_did_by_account_id(account: AccountId) -> Option { + + None + } + } + #[cfg(feature = "runtime-benchmarks")] impl frame_benchmarking::Benchmark for Runtime { fn benchmark_metadata(extra: bool) -> ( diff --git a/runtimes/spiritnet/Cargo.toml b/runtimes/spiritnet/Cargo.toml index 9b323c75e5..f0c8eb243b 100644 --- a/runtimes/spiritnet/Cargo.toml +++ b/runtimes/spiritnet/Cargo.toml @@ -20,6 +20,7 @@ serde = {version = "1.0.132", optional = true, features = ["derive"]} # RPC frame-system-rpc-runtime-api = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} pallet-transaction-payment-rpc-runtime-api = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} +did-rpc-runtime-api = {path = "../../rpc/did/runtime-api", default-features = false} # KILT pallets & primitives attestation = {default-features = false, path = "../../pallets/attestation"} diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index 38886ab399..b3755038c4 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -46,14 +46,16 @@ use sp_runtime::{ use sp_std::{cmp::Ordering, prelude::*}; use sp_version::RuntimeVersion; + use delegation::DelegationAc; +use did::did_details::DidDetails; pub use parachain_staking::InflationInfo; use runtime_common::{ authorization::{AuthorizationId, PalletAuthorize}, constants::{self, KILT, MICRO_KILT, MILLI_KILT}, fees::{ToAuthor, WeightToFee}, - pallet_id, AccountId, AuthorityId, Balance, BlockHashCount, BlockLength, BlockNumber, BlockWeights, DidIdentifier, - FeeSplit, Hash, Header, Index, Signature, SlowAdjustingFeeUpdate, + pallet_id, AccountId, AuthorityId, Balance, BlockHashCount, BlockLength, BlockNumber, BlockWeights, DidDocument, + DidIdentifier, FeeSplit, Hash, Header, Index, Signature, SlowAdjustingFeeUpdate, }; #[cfg(feature = "std")] @@ -970,6 +972,12 @@ pub type Executive = frame_executive::Executive< pallet_did_lookup::migrations::LookupReverseIndexMigration, >; +pub type Web3Name = pallet_web3_names::web3_name::AsciiWeb3Name; +pub type DidDoc = DidDocument< + DidDetails, + pallet_web3_names::web3_name::AsciiWeb3Name, +>; + impl_runtime_apis! { impl sp_api::Core for Runtime { fn version() -> RuntimeVersion { @@ -1074,6 +1082,31 @@ impl_runtime_apis! { } } + impl did_rpc_runtime_api::DidApi< + Block, + Web3Name, + DidDoc, + AccountId + > for Runtime { + fn query_did_by_w3n(name: Web3Name) -> Option { + pallet_web3_names::Owner::::get(&name) + .and_then(|owner_info| { + did::Did::::get(owner_info.owner) + }) + .and_then(|did_details| { + Some(DidDoc { + accounts: vec![], + details: did_details, + web3name: Some(name), + }) + }) + } + fn query_did_by_account_id(account: AccountId) -> Option { + + None + } + } + #[cfg(feature = "runtime-benchmarks")] impl frame_benchmarking::Benchmark for Runtime { fn benchmark_metadata(extra: bool) -> ( From 2196e20db90afbb06728299eeb071d00a69550a9 Mon Sep 17 00:00:00 2001 From: weichweich Date: Wed, 30 Mar 2022 09:18:21 +0200 Subject: [PATCH 02/31] fix: use correct sporran keys --- nodes/standalone/src/chain_spec.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/nodes/standalone/src/chain_spec.rs b/nodes/standalone/src/chain_spec.rs index 8a593354b5..381281e4a2 100644 --- a/nodes/standalone/src/chain_spec.rs +++ b/nodes/standalone/src/chain_spec.rs @@ -79,9 +79,10 @@ fn get_authority_keys_from_secret(seed: &str) -> (AccountId, AuraId, GrandpaId) const TELEMETRY_URL: &str = "wss://telemetry-backend.kilt.io:8080/submit"; -const SPORRAN_AUTHORITY_ACC: [u8; 32] = hex!("0621f3a33afc66ab7973e3d2cdf86d30ab89aa3e717e8bb1db23a9cb1736061b"); +const SPORRAN_AUTHORITY_ACC: [u8; 32] = hex!("2c94fbcfe0a7db40579e12bc74d0f7215fe91ba51b3eade92799788ca549f373"); const SPORRAN_AUTHORITY_SESSION: [u8; 32] = hex!("3bbaa842650064362767a1d9dd8899f531c80dc42eafb9599f4df0965e4a5299"); -const SPORRAN_FAUCET: [u8; 32] = hex!("2c9e9c40e15a2767e2d04dc1f05d824dd76d1d37bada3d7bb1d40eca29f3a4ff"); +const SPORRAN_FAUCET: [u8; 32] = hex!("780d87860ac7a02ebffa10e41a5a486efdebf63d595a44907ec0ced1d8626c4a"); + const TRANSFER_ACCOUNT: [u8; 32] = hex!("6a3c793cec9dbe330b349dc4eea6801090f5e71f53b1b41ad11afb4a313a282c"); impl Alternative { From 12cee6845a9350a63c311d1fe84f1ef90d87ef52 Mon Sep 17 00:00:00 2001 From: weichweich Date: Wed, 30 Mar 2022 15:21:47 +0200 Subject: [PATCH 03/31] fix toml --- runtimes/spiritnet/Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/runtimes/spiritnet/Cargo.toml b/runtimes/spiritnet/Cargo.toml index f0c8eb243b..8a6c2d8d5a 100644 --- a/runtimes/spiritnet/Cargo.toml +++ b/runtimes/spiritnet/Cargo.toml @@ -143,6 +143,7 @@ std = [ "cumulus-primitives-timestamp/std", "delegation/std", "did/std", + "did-rpc-runtime-api/std", "frame-benchmarking/std", "frame-executive/std", "frame-support/std", From 1ea7c00b289bf1e75e13b57007c8ea219b2b7d55 Mon Sep 17 00:00:00 2001 From: weichweich Date: Thu, 31 Mar 2022 14:58:18 +0200 Subject: [PATCH 04/31] rpc calls --- Cargo.lock | 3 ++ nodes/parachain/src/rpc.rs | 7 ++-- nodes/parachain/src/service.rs | 5 +-- pallets/pallet-web3-names/Cargo.toml | 3 +- pallets/pallet-web3-names/src/web3_name.rs | 30 ++++++++++++----- runtimes/common/Cargo.toml | 5 +-- runtimes/common/src/lib.rs | 38 ++++++++++++---------- runtimes/peregrine/src/lib.rs | 38 +++++++++------------- runtimes/spiritnet/src/lib.rs | 30 +++++++++-------- 9 files changed, 88 insertions(+), 71 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 58ddf5b027..89ca369953 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6344,6 +6344,7 @@ dependencies = [ "pallet-balances", "parity-scale-codec", "scale-info", + "serde", "sp-core", "sp-io", "sp-keystore", @@ -8590,11 +8591,13 @@ name = "runtime-common" version = "1.6.1" dependencies = [ "attestation", + "did", "frame-support", "frame-system", "pallet-authorship", "pallet-balances", "pallet-transaction-payment", + "pallet-web3-names", "parachain-staking", "parity-scale-codec", "scale-info", diff --git a/nodes/parachain/src/rpc.rs b/nodes/parachain/src/rpc.rs index 8e6011f5a2..f3e282a6d7 100644 --- a/nodes/parachain/src/rpc.rs +++ b/nodes/parachain/src/rpc.rs @@ -28,9 +28,8 @@ use std::sync::Arc; use did_rpc::{DidApi, DidQuery}; use frame_rpc_system::{FullSystem, SystemApi}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; -use peregrine_runtime::{DidDoc, Web3Name}; use polkadot_service::AuxStore; -use runtime_common::{AccountId, Balance, Block, Index}; +use runtime_common::{AccountId, Balance, Block, DidDocument, Index}; use sc_service::Error; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; @@ -58,7 +57,7 @@ where C: Send + Sync + 'static, C::Api: frame_rpc_system::AccountNonceApi, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, - C::Api: did_rpc::DidRuntimeApi, + C::Api: did_rpc::DidRuntimeApi, DidDocument, AccountId>, C::Api: BlockBuilder, P: TransactionPool + Sync + Send + 'static, { @@ -75,7 +74,7 @@ where deny_unsafe, ))); - io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(client))); + io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone()))); io.extend_with(DidApi::to_delegate(DidQuery::new(client))); diff --git a/nodes/parachain/src/service.rs b/nodes/parachain/src/service.rs index 52ba2802f7..075eca3a72 100644 --- a/nodes/parachain/src/service.rs +++ b/nodes/parachain/src/service.rs @@ -38,7 +38,7 @@ use sp_runtime::traits::BlakeTwo256; use std::{sync::Arc, time::Duration}; use substrate_prometheus_endpoint::Registry; -use runtime_common::{AccountId, AuthorityId, Balance, BlockNumber, Index}; +use runtime_common::{AccountId, AuthorityId, Balance, BlockNumber, Index, DidDocument}; type Header = sp_runtime::generic::Header; pub type Block = sp_runtime::generic::Block; @@ -411,7 +411,8 @@ where + frame_rpc_system::AccountNonceApi + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi + sp_consensus_aura::AuraApi - + cumulus_primitives_core::CollectCollationInfo, + + cumulus_primitives_core::CollectCollationInfo + + did_rpc::DidRuntimeApi, DidDocument, AccountId>, sc_client_api::StateBackendFor, Block>: sp_api::StateBackend, { let rpc_extensions_builder = diff --git a/pallets/pallet-web3-names/Cargo.toml b/pallets/pallet-web3-names/Cargo.toml index d6a9ecdcc6..882e3c2ca3 100644 --- a/pallets/pallet-web3-names/Cargo.toml +++ b/pallets/pallet-web3-names/Cargo.toml @@ -20,6 +20,7 @@ sp-keystore = {branch = "polkadot-v0.9.17", default-features = false, git = "htt [dependencies] codec = {default-features = false, features = ["derive"], package = "parity-scale-codec", version = "2.3.1"} scale-info = {version = "1.0", default-features = false, features = ["derive"]} +serde = {version = "1.0.132", optional = true} # KILT kilt-support = {default-features = false, path = "../../support"} @@ -45,6 +46,7 @@ runtime-benchmarks = [ ] std = [ + "serde", "codec/std", "frame-benchmarking/std", "frame-support/std", @@ -54,5 +56,4 @@ std = [ "sp-std/std", ] - try-runtime = [] diff --git a/pallets/pallet-web3-names/src/web3_name.rs b/pallets/pallet-web3-names/src/web3_name.rs index 4b4b935e46..f88330a7af 100644 --- a/pallets/pallet-web3-names/src/web3_name.rs +++ b/pallets/pallet-web3-names/src/web3_name.rs @@ -16,7 +16,7 @@ // If you feel like getting in touch with us, you can do so at info@botlabs.org -use sp_std::{fmt::Debug, marker::PhantomData, vec::Vec}; +use sp_std::{fmt::Debug, marker::PhantomData, ops::Deref, vec::Vec}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ensure, sp_runtime::SaturatedConversion, traits::Get, BoundedVec}; @@ -36,6 +36,20 @@ pub struct AsciiWeb3Name, MaxLength: Get>( PhantomData<(T, MinLength)>, ); +impl Deref for AsciiWeb3Name { + type Target = BoundedVec; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl From> for Vec { + fn from(name: AsciiWeb3Name) -> Self { + name.0.into_inner() + } +} + impl TryFrom> for AsciiWeb3Name { type Error = Error; @@ -54,13 +68,6 @@ impl TryFrom> for AsciiWeb3Name bool { - input - .iter() - .all(|c| matches!(c, b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_')) -} - impl Debug for AsciiWeb3Name { fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { f.debug_tuple("AsciiWeb3Name").field(&self.0).finish() @@ -81,6 +88,13 @@ impl Clone for AsciiWeb3Name { } } +/// Verify that a given slice can be used as a web3 name. +fn is_valid_web3_name(input: &[u8]) -> bool { + input + .iter() + .all(|c| matches!(c, b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_')) +} + /// KILT web3 name ownership details. #[derive(Clone, Encode, Decode, Debug, PartialEq, TypeInfo, MaxEncodedLen)] pub struct Web3NameOwnership { diff --git a/runtimes/common/Cargo.toml b/runtimes/common/Cargo.toml index 6ae4694f0a..bf78e8d4c2 100644 --- a/runtimes/common/Cargo.toml +++ b/runtimes/common/Cargo.toml @@ -13,9 +13,10 @@ scale-info = {version = "1.0", default-features = false, features = ["derive"]} serde = {version = "1.0.132", optional = true, features = ["derive"]} smallvec = "1.7.0" -attestation = {default-features = false, path = "../../pallets/attestation"} +attestation = {path = "../../pallets/attestation", default-features = false} +did = {path = "../../pallets/did", default-features = false} +pallet-web3-names = {path = "../../pallets/pallet-web3-names", default-features = false} parachain-staking = {default-features = false, path = "../../pallets/parachain-staking"} -# pallet-web3-names = {path = "../../pallet-web3-names", default-features = false} frame-support = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} frame-system = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} diff --git a/runtimes/common/src/lib.rs b/runtimes/common/src/lib.rs index 4dfdc932a0..59e0af0e52 100644 --- a/runtimes/common/src/lib.rs +++ b/runtimes/common/src/lib.rs @@ -20,18 +20,7 @@ #![cfg_attr(not(feature = "std"), no_std)] -#[cfg(feature = "std")] -use serde::{Deserialize, Serialize}; - -use constants::{AVERAGE_ON_INITIALIZE_RATIO, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO}; -use fees::SplitFeesByRatio; - -pub use sp_consensus_aura::sr25519::AuthorityId; - -pub use opaque::*; - use codec::{Decode, Encode}; -pub use frame_support::weights::constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; use frame_support::{parameter_types, traits::Currency, weights::DispatchClass}; use frame_system::limits; use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment}; @@ -43,6 +32,15 @@ use sp_runtime::{ }; use sp_std::vec::Vec; +use constants::{AVERAGE_ON_INITIALIZE_RATIO, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO}; +use fees::SplitFeesByRatio; + +pub use sp_consensus_aura::sr25519::AuthorityId; + +pub use opaque::*; + +pub use frame_support::weights::constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; + pub mod authorization; pub mod constants; pub mod fees; @@ -160,11 +158,15 @@ pub type FeeSplit = SplitFeesByRatio; pub type SlowAdjustingFeeUpdate = TargetedFeeAdjustment; -#[derive(Encode, Decode, TypeInfo, PartialEq, Eq)] -#[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -pub struct DidDocument { - pub details: DidDetails, - pub web3name: Option, - pub accounts: Vec, +#[derive(Encode, Decode, TypeInfo, PartialEq)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub struct DidDocument { + pub identifier: DidIdentifier, + pub w3n: Option>, } + +pub type Web3Name = pallet_web3_names::web3_name::AsciiWeb3Name< + R, + constants::web3_names::MinNameLength, + constants::web3_names::MaxNameLength, +>; diff --git a/runtimes/peregrine/src/lib.rs b/runtimes/peregrine/src/lib.rs index 849a131c4f..85cf2454d1 100644 --- a/runtimes/peregrine/src/lib.rs +++ b/runtimes/peregrine/src/lib.rs @@ -46,16 +46,14 @@ use sp_runtime::{ use sp_std::{cmp::Ordering, prelude::*}; use sp_version::RuntimeVersion; - use delegation::DelegationAc; -use did::did_details::DidDetails; pub use parachain_staking::InflationInfo; use runtime_common::{ authorization::{AuthorizationId, PalletAuthorize}, constants::{self, KILT, MICRO_KILT, MILLI_KILT}, fees::{ToAuthor, WeightToFee}, pallet_id, AccountId, AuthorityId, Balance, BlockHashCount, BlockLength, BlockNumber, BlockWeights, DidDocument, - DidIdentifier, FeeSplit, Hash, Header, Index, Signature, SlowAdjustingFeeUpdate, + DidIdentifier, FeeSplit, Hash, Header, Index, Signature, SlowAdjustingFeeUpdate, Web3Name, }; #[cfg(feature = "std")] @@ -970,13 +968,6 @@ pub type Executive = frame_executive::Executive< pallet_did_lookup::migrations::LookupReverseIndexMigration, >; - -pub type Web3Name = pallet_web3_names::web3_name::AsciiWeb3Name; -pub type DidDoc = DidDocument< - DidDetails, - pallet_web3_names::web3_name::AsciiWeb3Name, ->; - impl_runtime_apis! { impl sp_api::Core for Runtime { fn version() -> RuntimeVersion { @@ -1083,26 +1074,29 @@ impl_runtime_apis! { impl did_rpc_runtime_api::DidApi< Block, - Web3Name, - DidDoc, + Vec, + DidDocument, AccountId > for Runtime { - fn query_did_by_w3n(name: Web3Name) -> Option { + fn query_did_by_w3n(name: Vec) -> Option { + let name: Web3Name = name.try_into().ok()?; pallet_web3_names::Owner::::get(&name) .and_then(|owner_info| { - did::Did::::get(owner_info.owner) - }) - .and_then(|did_details| { - Some(DidDoc { - accounts: vec![], - details: did_details, - web3name: Some(name), + Some(DidDocument { + identifier: owner_info.owner, + w3n: Some(name.into()), }) }) } - fn query_did_by_account_id(account: AccountId) -> Option { - None + fn query_did_by_account_id(account: AccountId) -> Option { + pallet_did_lookup::ConnectedDids::::get(account).and_then(|connection_record| { + let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); + Some(DidDocument { + identifier: connection_record.did, + w3n, + }) + }) } } diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index b3755038c4..d06d2a6ac4 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -48,14 +48,13 @@ use sp_version::RuntimeVersion; use delegation::DelegationAc; -use did::did_details::DidDetails; pub use parachain_staking::InflationInfo; use runtime_common::{ authorization::{AuthorizationId, PalletAuthorize}, constants::{self, KILT, MICRO_KILT, MILLI_KILT}, fees::{ToAuthor, WeightToFee}, pallet_id, AccountId, AuthorityId, Balance, BlockHashCount, BlockLength, BlockNumber, BlockWeights, DidDocument, - DidIdentifier, FeeSplit, Hash, Header, Index, Signature, SlowAdjustingFeeUpdate, + DidIdentifier, FeeSplit, Hash, Header, Index, Signature, SlowAdjustingFeeUpdate, Web3Name, }; #[cfg(feature = "std")] @@ -1084,26 +1083,29 @@ impl_runtime_apis! { impl did_rpc_runtime_api::DidApi< Block, - Web3Name, - DidDoc, + Vec, + DidDocument, AccountId > for Runtime { - fn query_did_by_w3n(name: Web3Name) -> Option { + fn query_did_by_w3n(name: Vec) -> Option { + let name: Web3Name = name.try_into().ok()?; pallet_web3_names::Owner::::get(&name) .and_then(|owner_info| { - did::Did::::get(owner_info.owner) - }) - .and_then(|did_details| { - Some(DidDoc { - accounts: vec![], - details: did_details, - web3name: Some(name), + Some(DidDocument { + identifier: owner_info.owner, + w3n: Some(name.into()), }) }) } - fn query_did_by_account_id(account: AccountId) -> Option { - None + fn query_did_by_account_id(account: AccountId) -> Option { + pallet_did_lookup::ConnectedDids::::get(account).and_then(|connection_record| { + let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); + Some(DidDocument { + identifier: connection_record.did, + w3n, + }) + }) } } From 35723609ec683545a146697e810b0f6c7d2da6b5 Mon Sep 17 00:00:00 2001 From: weichweich Date: Fri, 1 Apr 2022 15:56:28 +0200 Subject: [PATCH 05/31] rpc for standalone --- Cargo.lock | 3 ++ nodes/standalone/Cargo.toml | 1 + nodes/standalone/src/rpc.rs | 10 ++++- rpc/did/runtime-api/Cargo.toml | 2 + rpc/did/runtime-api/src/lib.rs | 6 +-- rpc/did/src/lib.rs | 18 ++++---- runtimes/standalone/Cargo.toml | 10 +++-- runtimes/standalone/src/lib.rs | 75 +++++++++++++++++++++------------- 8 files changed, 77 insertions(+), 48 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 89ca369953..bbe87ea7e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1932,6 +1932,7 @@ dependencies = [ "parity-scale-codec", "sp-api", "sp-runtime", + "sp-std", ] [[package]] @@ -4494,6 +4495,7 @@ name = "mashnet-node" version = "1.6.1" dependencies = [ "clap", + "did-rpc", "frame-benchmarking", "frame-benchmarking-cli", "futures 0.3.21", @@ -4549,6 +4551,7 @@ dependencies = [ "ctype", "delegation", "did", + "did-rpc-runtime-api", "frame-benchmarking", "frame-executive", "frame-support", diff --git a/nodes/standalone/Cargo.toml b/nodes/standalone/Cargo.toml index 32ac828f12..a1c56e8af6 100644 --- a/nodes/standalone/Cargo.toml +++ b/nodes/standalone/Cargo.toml @@ -18,6 +18,7 @@ vergen = "3.1.0" # Internal dependencies mashnet-node-runtime = {path = "../../runtimes/standalone"} runtime-common = {path = "../../runtimes/common"} +did-rpc = {path = "../../rpc/did"} # External dependencies clap = { version = "3.1", features = ["derive"] } diff --git a/nodes/standalone/src/rpc.rs b/nodes/standalone/src/rpc.rs index ebd0e00b6e..ce57686a46 100644 --- a/nodes/standalone/src/rpc.rs +++ b/nodes/standalone/src/rpc.rs @@ -25,8 +25,9 @@ use std::sync::Arc; +use did_rpc::{DidApi, DidQuery}; use mashnet_node_runtime::opaque::Block; -use runtime_common::{AccountId, Balance, Index}; +use runtime_common::{AccountId, Balance, Index, DidDocument}; pub use sc_rpc_api::DenyUnsafe; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; @@ -52,6 +53,7 @@ where C::Api: frame_rpc_system::AccountNonceApi, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, C::Api: BlockBuilder, + C::Api: did_rpc::DidRuntimeApi, P: TransactionPool + 'static, { use frame_rpc_system::{FullSystem, SystemApi}; @@ -70,7 +72,11 @@ where deny_unsafe, ))); - io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(client))); + io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new( + client.clone(), + ))); + + io.extend_with(DidApi::to_delegate(DidQuery::new(client))); // Extend this RPC with a custom API by using the following syntax. // `YourRpcStruct` should have a reference to a client, which is needed diff --git a/rpc/did/runtime-api/Cargo.toml b/rpc/did/runtime-api/Cargo.toml index c71fbc0e2a..e10533b00d 100644 --- a/rpc/did/runtime-api/Cargo.toml +++ b/rpc/did/runtime-api/Cargo.toml @@ -10,6 +10,7 @@ codec = {package = "parity-scale-codec", version = "2.3.1", default-features = f sp-api = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} sp-runtime = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} +sp-std = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} [features] default = ["std"] @@ -17,4 +18,5 @@ std = [ "codec/std", "sp-api/std", "sp-runtime/std", + "sp-std/std", ] diff --git a/rpc/did/runtime-api/src/lib.rs b/rpc/did/runtime-api/src/lib.rs index 51950fdf72..fb2b9f1c4a 100644 --- a/rpc/did/runtime-api/src/lib.rs +++ b/rpc/did/runtime-api/src/lib.rs @@ -18,15 +18,15 @@ #![cfg_attr(not(feature = "std"), no_std)] use codec::Codec; +use sp_std::vec::Vec; sp_api::decl_runtime_apis! { /// The API to query account nonce (aka transaction index). - pub trait DidApi where - Web3Name: Codec, + pub trait DidApi where DidDocument: Codec, AccountId: Codec, { - fn query_did_by_w3n(name: Web3Name) -> Option; + fn query_did_by_w3n(name: Vec) -> Option; fn query_did_by_account_id(account: AccountId) -> Option; } } diff --git a/rpc/did/src/lib.rs b/rpc/did/src/lib.rs index 804c28d8fd..6f4f43fa43 100644 --- a/rpc/did/src/lib.rs +++ b/rpc/did/src/lib.rs @@ -28,9 +28,9 @@ use sp_runtime::{generic::BlockId, traits::Block as BlockT}; pub use did_rpc_runtime_api::DidApi as DidRuntimeApi; #[rpc] -pub trait DidApi { +pub trait DidApi { #[rpc(name = "did_queryByWeb3Name")] - fn query_did_by_w3n(&self, web3name: Web3Name, at: Option) -> Result>; + fn query_did_by_w3n(&self, web3name: String, at: Option) -> Result>; #[rpc(name = "did_queryByAccount")] fn query_did_by_account_id(&self, account: AccountId, at: Option) -> Result>; @@ -69,23 +69,21 @@ impl From for i64 { } } -impl DidApi<::Hash, Web3Name, DidDoc, AccountId> - for DidQuery +impl DidApi<::Hash, DidDoc, AccountId> for DidQuery where - Web3Name: Codec, - DidDoc: Codec, - AccountId: Codec, + AccountId: Codec + std::marker::Send, + DidDoc: Codec + std::marker::Send, Block: BlockT, C: 'static + ProvideRuntimeApi + HeaderBackend, - C::Api: DidRuntimeApi, + C::Api: DidRuntimeApi, { - fn query_did_by_w3n(&self, web3name: Web3Name, at: Option<::Hash>) -> Result> { + fn query_did_by_w3n(&self, web3name: String, at: Option<::Hash>) -> Result> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. self.client.info().best_hash)); - api.query_did_by_w3n(&at, web3name).map_err(|e| RpcError { + api.query_did_by_w3n(&at, web3name.into()).map_err(|e| RpcError { code: ErrorCode::ServerError(Error::RuntimeError.into()), message: "Unable to query dispatch info.".into(), data: Some(e.to_string().into()), diff --git a/runtimes/standalone/Cargo.toml b/runtimes/standalone/Cargo.toml index 5d5bb1e1d5..1c27fa4bab 100644 --- a/runtimes/standalone/Cargo.toml +++ b/runtimes/standalone/Cargo.toml @@ -23,11 +23,14 @@ delegation = {default-features = false, path = "../../pallets/delegation"} did = {default-features = false, path = "../../pallets/did"} kilt-launch = {default-features = false, path = "../../pallets/kilt-launch"} kilt-support = {path = "../../support", default-features = false, optional = true} -pallet-web3-names = {default-features = false, path = "../../pallets/pallet-web3-names"} pallet-did-lookup = {default-features = false, path = "../../pallets/pallet-did-lookup"} +pallet-web3-names = {default-features = false, path = "../../pallets/pallet-web3-names"} runtime-common = {path = "../../runtimes/common", default-features = false} -# kilt specific +# RPC +did-rpc-runtime-api = {path = "../../rpc/did/runtime-api", default-features = false} +frame-system-rpc-runtime-api = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} +pallet-transaction-payment-rpc-runtime-api = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} # Benchmarking frame-system-benchmarking = {git = "https://github.com/paritytech/substrate", default-features = false, optional = true, branch = "polkadot-v0.9.17"} @@ -37,7 +40,6 @@ frame-benchmarking = {branch = "polkadot-v0.9.17", default-features = false, git frame-executive = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} frame-support = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} frame-system = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -frame-system-rpc-runtime-api = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} pallet-aura = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} pallet-authorship = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} pallet-balances = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} @@ -49,7 +51,6 @@ pallet-session = {branch = "polkadot-v0.9.17", default-features = false, git = " pallet-sudo = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} pallet-timestamp = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} pallet-transaction-payment = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -pallet-transaction-payment-rpc-runtime-api = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} pallet-utility = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} pallet-vesting = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} sp-api = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} @@ -104,6 +105,7 @@ std = [ "frame-support/std", "frame-system/std", "frame-system-rpc-runtime-api/std", + "did-rpc-runtime-api/std", "frame-try-runtime/std", "kilt-launch/std", "log/std", diff --git a/runtimes/standalone/src/lib.rs b/runtimes/standalone/src/lib.rs index a80ef32fef..2b7502a707 100644 --- a/runtimes/standalone/src/lib.rs +++ b/runtimes/standalone/src/lib.rs @@ -28,16 +28,13 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use codec::{Decode, Encode, MaxEncodedLen}; -use delegation::DelegationAc; -use frame_support::traits::InstanceFilter; -pub use frame_support::{ +use frame_support::{ construct_runtime, parameter_types, - traits::{Currency, FindAuthor, Imbalance, KeyOwnerProofSystem, OnUnbalanced, Randomness}, + traits::{Currency, InstanceFilter, KeyOwnerProofSystem}, weights::{ - constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND}, - IdentityFee, Weight, + constants::{RocksDbWeight, WEIGHT_PER_SECOND}, + IdentityFee, }, - ConsensusEngineId, StorageValue, }; use frame_system::EnsureRoot; use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList}; @@ -51,11 +48,20 @@ use sp_runtime::{ transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, RuntimeDebug, }; -pub use sp_runtime::{Perbill, Permill}; use sp_std::prelude::*; use sp_version::RuntimeVersion; +use delegation::DelegationAc; +use runtime_common::{ + authorization::{AuthorizationId, PalletAuthorize}, + constants::{self, KILT, MICRO_KILT, MILLI_KILT}, + fees::ToAuthor, + pallet_id, AccountId, Balance, BlockNumber, DidDocument, DidIdentifier, Hash, Index, Signature, + SlowAdjustingFeeUpdate, Web3Name, +}; + pub use pallet_timestamp::Call as TimestampCall; +pub use sp_runtime::{Perbill, Permill}; pub use attestation; pub use ctype; @@ -63,12 +69,6 @@ pub use delegation; pub use did; pub use pallet_balances::Call as BalancesCall; pub use pallet_web3_names; -use runtime_common::{ - authorization::{AuthorizationId, PalletAuthorize}, - constants::{self, KILT, MICRO_KILT, MILLI_KILT}, - fees::ToAuthor, - pallet_id, AccountId, Balance, BlockNumber, DidIdentifier, Hash, Index, Signature, SlowAdjustingFeeUpdate, -}; #[cfg(feature = "std")] use sp_version::NativeVersion; @@ -429,10 +429,6 @@ impl did::Config for Runtime { type WeightInfo = (); } -parameter_types! { - pub const DidLookupDeposit: Balance = constants::did_lookup::DID_CONNECTION_DEPOSIT; -} - impl pallet_did_lookup::Config for Runtime { type Event = Event; type Signature = Signature; @@ -440,7 +436,7 @@ impl pallet_did_lookup::Config for Runtime { type DidIdentifier = DidIdentifier; type Currency = Balances; - type Deposit = DidLookupDeposit; + type Deposit = constants::did_lookup::DidLookupDeposit; type EnsureOrigin = did::EnsureDidOrigin; type OriginSuccess = did::DidRawOrigin; @@ -448,22 +444,16 @@ impl pallet_did_lookup::Config for Runtime { type WeightInfo = (); } -parameter_types! { - pub const Web3NameDeposit: Balance = constants::web3_names::DEPOSIT; - pub const MinNameLength: u32 = constants::web3_names::MIN_LENGTH; - pub const MaxNameLength: u32 = constants::web3_names::MAX_LENGTH; -} - impl pallet_web3_names::Config for Runtime { type BanOrigin = EnsureRoot; type OwnerOrigin = did::EnsureDidOrigin; type OriginSuccess = did::DidRawOrigin; type Currency = Balances; - type Deposit = Web3NameDeposit; + type Deposit = constants::web3_names::Web3NameDeposit; type Event = Event; - type MaxNameLength = MaxNameLength; - type MinNameLength = MinNameLength; - type Web3Name = pallet_web3_names::web3_name::AsciiWeb3Name; + type MaxNameLength = constants::web3_names::MaxNameLength; + type MinNameLength = constants::web3_names::MinNameLength; + type Web3Name = Web3Name; type Web3NameOwner = DidIdentifier; type WeightInfo = (); } @@ -913,6 +903,33 @@ impl_runtime_apis! { } } + impl did_rpc_runtime_api::DidApi< + Block, + DidDocument, + AccountId + > for Runtime { + fn query_did_by_w3n(name: Vec) -> Option { + let name: Web3Name = name.try_into().ok()?; + pallet_web3_names::Owner::::get(&name) + .and_then(|owner_info| { + Some(DidDocument { + identifier: owner_info.owner, + w3n: Some(name.into()), + }) + }) + } + + fn query_did_by_account_id(account: AccountId) -> Option { + pallet_did_lookup::ConnectedDids::::get(account).and_then(|connection_record| { + let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); + Some(DidDocument { + identifier: connection_record.did, + w3n, + }) + }) + } + } + #[cfg(feature = "runtime-benchmarks")] impl frame_benchmarking::Benchmark for Runtime { fn benchmark_metadata(extra: bool) -> ( From d77128682fbba0866dceb6e1d18d29b332a2003d Mon Sep 17 00:00:00 2001 From: weichweich Date: Tue, 5 Apr 2022 08:53:27 +0200 Subject: [PATCH 06/31] rpcs --- Cargo.lock | 3 ++ nodes/parachain/src/rpc.rs | 8 ++-- nodes/parachain/src/service.rs | 4 +- nodes/standalone/src/rpc.rs | 4 +- pallets/pallet-did-lookup/Cargo.toml | 1 - rpc/did/runtime-api/Cargo.toml | 7 +++ rpc/did/runtime-api/src/lib.rs | 24 +++++++--- rpc/did/src/lib.rs | 66 ++++++++++++++++++++-------- runtimes/common/src/lib.rs | 10 ----- runtimes/peregrine/src/lib.rs | 17 +++---- runtimes/spiritnet/src/lib.rs | 25 ++++++----- runtimes/standalone/src/lib.rs | 16 ++++--- 12 files changed, 117 insertions(+), 68 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bbe87ea7e3..1c3384d051 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1929,7 +1929,10 @@ dependencies = [ name = "did-rpc-runtime-api" version = "1.5.0" dependencies = [ + "did", "parity-scale-codec", + "scale-info", + "serde", "sp-api", "sp-runtime", "sp-std", diff --git a/nodes/parachain/src/rpc.rs b/nodes/parachain/src/rpc.rs index f3e282a6d7..aba11fd4fa 100644 --- a/nodes/parachain/src/rpc.rs +++ b/nodes/parachain/src/rpc.rs @@ -29,7 +29,7 @@ use did_rpc::{DidApi, DidQuery}; use frame_rpc_system::{FullSystem, SystemApi}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; use polkadot_service::AuxStore; -use runtime_common::{AccountId, Balance, Block, DidDocument, Index}; +use runtime_common::{AccountId, Balance, Block, DidIdentifier, Index}; use sc_service::Error; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; @@ -57,7 +57,7 @@ where C: Send + Sync + 'static, C::Api: frame_rpc_system::AccountNonceApi, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, - C::Api: did_rpc::DidRuntimeApi, DidDocument, AccountId>, + C::Api: did_rpc::DidRuntimeApi, C::Api: BlockBuilder, P: TransactionPool + Sync + Send + 'static, { @@ -74,7 +74,9 @@ where deny_unsafe, ))); - io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone()))); + io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new( + client.clone(), + ))); io.extend_with(DidApi::to_delegate(DidQuery::new(client))); diff --git a/nodes/parachain/src/service.rs b/nodes/parachain/src/service.rs index 075eca3a72..d03765b4eb 100644 --- a/nodes/parachain/src/service.rs +++ b/nodes/parachain/src/service.rs @@ -38,7 +38,7 @@ use sp_runtime::traits::BlakeTwo256; use std::{sync::Arc, time::Duration}; use substrate_prometheus_endpoint::Registry; -use runtime_common::{AccountId, AuthorityId, Balance, BlockNumber, Index, DidDocument}; +use runtime_common::{AccountId, AuthorityId, Balance, BlockNumber, DidIdentifier, Index}; type Header = sp_runtime::generic::Header; pub type Block = sp_runtime::generic::Block; @@ -412,7 +412,7 @@ where + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi + sp_consensus_aura::AuraApi + cumulus_primitives_core::CollectCollationInfo - + did_rpc::DidRuntimeApi, DidDocument, AccountId>, + + did_rpc::DidRuntimeApi, sc_client_api::StateBackendFor, Block>: sp_api::StateBackend, { let rpc_extensions_builder = diff --git a/nodes/standalone/src/rpc.rs b/nodes/standalone/src/rpc.rs index ce57686a46..aa9f992d83 100644 --- a/nodes/standalone/src/rpc.rs +++ b/nodes/standalone/src/rpc.rs @@ -27,7 +27,7 @@ use std::sync::Arc; use did_rpc::{DidApi, DidQuery}; use mashnet_node_runtime::opaque::Block; -use runtime_common::{AccountId, Balance, Index, DidDocument}; +use runtime_common::{AccountId, Balance, Index, DidIdentifier}; pub use sc_rpc_api::DenyUnsafe; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; @@ -53,7 +53,7 @@ where C::Api: frame_rpc_system::AccountNonceApi, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, C::Api: BlockBuilder, - C::Api: did_rpc::DidRuntimeApi, + C::Api: did_rpc::DidRuntimeApi, P: TransactionPool + 'static, { use frame_rpc_system::{FullSystem, SystemApi}; diff --git a/pallets/pallet-did-lookup/Cargo.toml b/pallets/pallet-did-lookup/Cargo.toml index e4df0be5d1..a0dc163330 100644 --- a/pallets/pallet-did-lookup/Cargo.toml +++ b/pallets/pallet-did-lookup/Cargo.toml @@ -46,7 +46,6 @@ runtime-benchmarks = [ ] std = [ - "pallet-balances/std", "codec/std", "frame-benchmarking/std", "frame-support/std", diff --git a/rpc/did/runtime-api/Cargo.toml b/rpc/did/runtime-api/Cargo.toml index e10533b00d..54cdd33b91 100644 --- a/rpc/did/runtime-api/Cargo.toml +++ b/rpc/did/runtime-api/Cargo.toml @@ -7,16 +7,23 @@ version = "1.5.0" [dependencies] codec = {package = "parity-scale-codec", version = "2.3.1", default-features = false, features = ["derive"]} +scale-info = {version = "1.0", default-features = false, features = ["derive"]} +serde = {version = "1.0.132", optional = true, features = ["derive"]} sp-api = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} sp-runtime = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} sp-std = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} +did = {path = "../../../pallets/did", default-features = false} + [features] default = ["std"] std = [ + "serde", "codec/std", "sp-api/std", "sp-runtime/std", "sp-std/std", + "scale-info/std", + "did/std", ] diff --git a/rpc/did/runtime-api/src/lib.rs b/rpc/did/runtime-api/src/lib.rs index fb2b9f1c4a..e8abcbf6fa 100644 --- a/rpc/did/runtime-api/src/lib.rs +++ b/rpc/did/runtime-api/src/lib.rs @@ -17,16 +17,30 @@ // If you feel like getting in touch with us, you can do so at info@botlabs.org #![cfg_attr(not(feature = "std"), no_std)] -use codec::Codec; +use codec::{Codec, Decode, Encode}; +use scale_info::TypeInfo; use sp_std::vec::Vec; +#[derive(Encode, Decode, TypeInfo, PartialEq)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub struct DidDocument { + pub identifier: DidIdentifier, + pub accounts: Option>, + pub w3n: Option, +} + +/// The DidDocument with a Web3Name represented as a byte array. +/// +/// This will be returned by the runtime and processed by the client side RPC implementation. +pub type RawDidDocument = DidDocument>; + sp_api::decl_runtime_apis! { /// The API to query account nonce (aka transaction index). - pub trait DidApi where - DidDocument: Codec, + pub trait DidApi where + DidIdentifier: Codec, AccountId: Codec, { - fn query_did_by_w3n(name: Vec) -> Option; - fn query_did_by_account_id(account: AccountId) -> Option; + fn query_did_by_w3n(name: Vec) -> Option>; + fn query_did_by_account_id(account: AccountId) -> Option>; } } diff --git a/rpc/did/src/lib.rs b/rpc/did/src/lib.rs index 6f4f43fa43..3c9db32051 100644 --- a/rpc/did/src/lib.rs +++ b/rpc/did/src/lib.rs @@ -19,6 +19,7 @@ use std::sync::Arc; use codec::Codec; +use did_rpc_runtime_api::DidDocument; use jsonrpc_core::{Error as RpcError, ErrorCode, Result}; use jsonrpc_derive::rpc; use sp_api::ProvideRuntimeApi; @@ -28,12 +29,20 @@ use sp_runtime::{generic::BlockId, traits::Block as BlockT}; pub use did_rpc_runtime_api::DidApi as DidRuntimeApi; #[rpc] -pub trait DidApi { +pub trait DidApi { #[rpc(name = "did_queryByWeb3Name")] - fn query_did_by_w3n(&self, web3name: String, at: Option) -> Result>; + fn query_did_by_w3n( + &self, + web3name: String, + at: Option, + ) -> Result>>; #[rpc(name = "did_queryByAccount")] - fn query_did_by_account_id(&self, account: AccountId, at: Option) -> Result>; + fn query_did_by_account_id( + &self, + account: AccountId, + at: Option, + ) -> Result>>; } /// A struct that implements the [`TransactionPaymentApi`]. @@ -69,41 +78,62 @@ impl From for i64 { } } -impl DidApi<::Hash, DidDoc, AccountId> for DidQuery +impl DidApi<::Hash, DidIdentifier, AccountId> + for DidQuery where AccountId: Codec + std::marker::Send, - DidDoc: Codec + std::marker::Send, + DidIdentifier: Codec + std::marker::Send, Block: BlockT, C: 'static + ProvideRuntimeApi + HeaderBackend, - C::Api: DidRuntimeApi, + C::Api: DidRuntimeApi, { - fn query_did_by_w3n(&self, web3name: String, at: Option<::Hash>) -> Result> { + fn query_did_by_w3n( + &self, + web3name: String, + at: Option<::Hash>, + ) -> Result>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. self.client.info().best_hash)); - api.query_did_by_w3n(&at, web3name.into()).map_err(|e| RpcError { - code: ErrorCode::ServerError(Error::RuntimeError.into()), - message: "Unable to query dispatch info.".into(), - data: Some(e.to_string().into()), - }) + match api.query_did_by_w3n(&at, web3name.into()) { + Err(e) => Err(RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Unable to query dispatch info.".into(), + data: Some(e.to_string().into()), + }), + Ok(doc) => Ok(doc.map(|doc| DidDocument { + // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we ignore the w3n and pretend it doesn't exist. + w3n: doc.w3n.and_then(|w3n| String::from_utf8(w3n).ok()), + accounts: doc.accounts, + identifier: doc.identifier, + })), + } } fn query_did_by_account_id( &self, account: AccountId, at: Option<::Hash>, - ) -> Result> { + ) -> Result>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. self.client.info().best_hash)); - api.query_did_by_account_id(&at, account).map_err(|e| RpcError { - code: ErrorCode::ServerError(Error::RuntimeError.into()), - message: "Unable to query fee details.".into(), - data: Some(e.to_string().into()), - }) + match api.query_did_by_account_id(&at, account) { + Err(e) => Err(RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Unable to query fee details.".into(), + data: Some(e.to_string().into()), + }), + Ok(doc) => Ok(doc.map(|doc| DidDocument { + // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we ignore the w3n and pretend it doesn't exist. + w3n: doc.w3n.and_then(|w3n| String::from_utf8(w3n).ok()), + accounts: doc.accounts, + identifier: doc.identifier, + })), + } } } diff --git a/runtimes/common/src/lib.rs b/runtimes/common/src/lib.rs index 59e0af0e52..1c041898e3 100644 --- a/runtimes/common/src/lib.rs +++ b/runtimes/common/src/lib.rs @@ -20,17 +20,14 @@ #![cfg_attr(not(feature = "std"), no_std)] -use codec::{Decode, Encode}; use frame_support::{parameter_types, traits::Currency, weights::DispatchClass}; use frame_system::limits; use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment}; -use scale_info::TypeInfo; use sp_runtime::{ generic, traits::{IdentifyAccount, Verify}, FixedPointNumber, MultiSignature, Perquintill, }; -use sp_std::vec::Vec; use constants::{AVERAGE_ON_INITIALIZE_RATIO, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO}; use fees::SplitFeesByRatio; @@ -158,13 +155,6 @@ pub type FeeSplit = SplitFeesByRatio; pub type SlowAdjustingFeeUpdate = TargetedFeeAdjustment; -#[derive(Encode, Decode, TypeInfo, PartialEq)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -pub struct DidDocument { - pub identifier: DidIdentifier, - pub w3n: Option>, -} - pub type Web3Name = pallet_web3_names::web3_name::AsciiWeb3Name< R, constants::web3_names::MinNameLength, diff --git a/runtimes/peregrine/src/lib.rs b/runtimes/peregrine/src/lib.rs index 85cf2454d1..e5885f6429 100644 --- a/runtimes/peregrine/src/lib.rs +++ b/runtimes/peregrine/src/lib.rs @@ -52,8 +52,8 @@ use runtime_common::{ authorization::{AuthorizationId, PalletAuthorize}, constants::{self, KILT, MICRO_KILT, MILLI_KILT}, fees::{ToAuthor, WeightToFee}, - pallet_id, AccountId, AuthorityId, Balance, BlockHashCount, BlockLength, BlockNumber, BlockWeights, DidDocument, - DidIdentifier, FeeSplit, Hash, Header, Index, Signature, SlowAdjustingFeeUpdate, Web3Name, + pallet_id, AccountId, AuthorityId, Balance, BlockHashCount, BlockLength, BlockNumber, BlockWeights, DidIdentifier, + FeeSplit, Hash, Header, Index, Signature, SlowAdjustingFeeUpdate, Web3Name, }; #[cfg(feature = "std")] @@ -1074,27 +1074,28 @@ impl_runtime_apis! { impl did_rpc_runtime_api::DidApi< Block, - Vec, - DidDocument, + DidIdentifier, AccountId > for Runtime { - fn query_did_by_w3n(name: Vec) -> Option { + fn query_did_by_w3n(name: Vec) -> Option> { let name: Web3Name = name.try_into().ok()?; pallet_web3_names::Owner::::get(&name) .and_then(|owner_info| { - Some(DidDocument { + Some(did_rpc_runtime_api::RawDidDocument { identifier: owner_info.owner, w3n: Some(name.into()), + accounts: None, }) }) } - fn query_did_by_account_id(account: AccountId) -> Option { + fn query_did_by_account_id(account: AccountId) -> Option> { pallet_did_lookup::ConnectedDids::::get(account).and_then(|connection_record| { let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); - Some(DidDocument { + Some(did_rpc_runtime_api::RawDidDocument { identifier: connection_record.did, w3n, + accounts: None, }) }) } diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index d06d2a6ac4..5aa17214cd 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -53,8 +53,8 @@ use runtime_common::{ authorization::{AuthorizationId, PalletAuthorize}, constants::{self, KILT, MICRO_KILT, MILLI_KILT}, fees::{ToAuthor, WeightToFee}, - pallet_id, AccountId, AuthorityId, Balance, BlockHashCount, BlockLength, BlockNumber, BlockWeights, DidDocument, - DidIdentifier, FeeSplit, Hash, Header, Index, Signature, SlowAdjustingFeeUpdate, Web3Name, + pallet_id, AccountId, AuthorityId, Balance, BlockHashCount, BlockLength, BlockNumber, BlockWeights, DidIdentifier, + FeeSplit, Hash, Header, Index, Signature, SlowAdjustingFeeUpdate, Web3Name, }; #[cfg(feature = "std")] @@ -1083,28 +1083,29 @@ impl_runtime_apis! { impl did_rpc_runtime_api::DidApi< Block, - Vec, - DidDocument, + DidIdentifier, AccountId > for Runtime { - fn query_did_by_w3n(name: Vec) -> Option { + fn query_did_by_w3n(name: Vec) -> Option> { let name: Web3Name = name.try_into().ok()?; pallet_web3_names::Owner::::get(&name) - .and_then(|owner_info| { - Some(DidDocument { + .map(|owner_info| { + did_rpc_runtime_api::RawDidDocument { identifier: owner_info.owner, w3n: Some(name.into()), - }) + accounts: None, + } }) } - fn query_did_by_account_id(account: AccountId) -> Option { - pallet_did_lookup::ConnectedDids::::get(account).and_then(|connection_record| { + fn query_did_by_account_id(account: AccountId) -> Option> { + pallet_did_lookup::ConnectedDids::::get(account).map(|connection_record| { let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); - Some(DidDocument { + did_rpc_runtime_api::RawDidDocument { identifier: connection_record.did, w3n, - }) + accounts: None, + } }) } } diff --git a/runtimes/standalone/src/lib.rs b/runtimes/standalone/src/lib.rs index 2b7502a707..56bf4445b6 100644 --- a/runtimes/standalone/src/lib.rs +++ b/runtimes/standalone/src/lib.rs @@ -56,8 +56,8 @@ use runtime_common::{ authorization::{AuthorizationId, PalletAuthorize}, constants::{self, KILT, MICRO_KILT, MILLI_KILT}, fees::ToAuthor, - pallet_id, AccountId, Balance, BlockNumber, DidDocument, DidIdentifier, Hash, Index, Signature, - SlowAdjustingFeeUpdate, Web3Name, + pallet_id, AccountId, Balance, BlockNumber, DidIdentifier, Hash, Index, Signature, SlowAdjustingFeeUpdate, + Web3Name, }; pub use pallet_timestamp::Call as TimestampCall; @@ -905,26 +905,28 @@ impl_runtime_apis! { impl did_rpc_runtime_api::DidApi< Block, - DidDocument, + DidIdentifier, AccountId > for Runtime { - fn query_did_by_w3n(name: Vec) -> Option { + fn query_did_by_w3n(name: Vec) -> Option> { let name: Web3Name = name.try_into().ok()?; pallet_web3_names::Owner::::get(&name) .and_then(|owner_info| { - Some(DidDocument { + Some(did_rpc_runtime_api::RawDidDocument { identifier: owner_info.owner, w3n: Some(name.into()), + accounts: None, }) }) } - fn query_did_by_account_id(account: AccountId) -> Option { + fn query_did_by_account_id(account: AccountId) -> Option> { pallet_did_lookup::ConnectedDids::::get(account).and_then(|connection_record| { let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); - Some(DidDocument { + Some(did_rpc_runtime_api::RawDidDocument { identifier: connection_record.did, w3n, + accounts: None, }) }) } From 39c6934814667aba67dc492d9e883b24bdbac85c Mon Sep 17 00:00:00 2001 From: weichweich Date: Tue, 5 Apr 2022 10:25:13 +0200 Subject: [PATCH 07/31] fix clippy --- runtimes/peregrine/src/lib.rs | 12 ++++++------ runtimes/standalone/src/lib.rs | 16 ++++++++-------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/runtimes/peregrine/src/lib.rs b/runtimes/peregrine/src/lib.rs index e5885f6429..84a9a5e971 100644 --- a/runtimes/peregrine/src/lib.rs +++ b/runtimes/peregrine/src/lib.rs @@ -1080,23 +1080,23 @@ impl_runtime_apis! { fn query_did_by_w3n(name: Vec) -> Option> { let name: Web3Name = name.try_into().ok()?; pallet_web3_names::Owner::::get(&name) - .and_then(|owner_info| { - Some(did_rpc_runtime_api::RawDidDocument { + .map(|owner_info| { + did_rpc_runtime_api::RawDidDocument { identifier: owner_info.owner, w3n: Some(name.into()), accounts: None, - }) + } }) } fn query_did_by_account_id(account: AccountId) -> Option> { - pallet_did_lookup::ConnectedDids::::get(account).and_then(|connection_record| { + pallet_did_lookup::ConnectedDids::::get(account).map(|connection_record| { let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); - Some(did_rpc_runtime_api::RawDidDocument { + did_rpc_runtime_api::RawDidDocument { identifier: connection_record.did, w3n, accounts: None, - }) + } }) } } diff --git a/runtimes/standalone/src/lib.rs b/runtimes/standalone/src/lib.rs index 56bf4445b6..97a2dcb025 100644 --- a/runtimes/standalone/src/lib.rs +++ b/runtimes/standalone/src/lib.rs @@ -911,23 +911,23 @@ impl_runtime_apis! { fn query_did_by_w3n(name: Vec) -> Option> { let name: Web3Name = name.try_into().ok()?; pallet_web3_names::Owner::::get(&name) - .and_then(|owner_info| { - Some(did_rpc_runtime_api::RawDidDocument { + .map(|owner_info| { + did_rpc_runtime_api::RawDidDocument { identifier: owner_info.owner, w3n: Some(name.into()), accounts: None, - }) + } }) } fn query_did_by_account_id(account: AccountId) -> Option> { - pallet_did_lookup::ConnectedDids::::get(account).and_then(|connection_record| { + pallet_did_lookup::ConnectedDids::::get(account).map(|connection_record| { let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); - Some(did_rpc_runtime_api::RawDidDocument { + did_rpc_runtime_api::RawDidDocument { identifier: connection_record.did, w3n, accounts: None, - }) + } }) } } @@ -1019,7 +1019,7 @@ impl_runtime_apis! { #[cfg(feature = "try-runtime")] impl frame_try_runtime::TryRuntime for Runtime { - fn on_runtime_upgrade() -> (Weight, Weight) { + fn on_runtime_upgrade() -> (frame_support::pallet_prelude::Weight, frame_support::pallet_prelude::Weight) { log::info!("try-runtime::on_runtime_upgrade standalone runtime."); let weight = Executive::try_runtime_upgrade().map_err(|err|{ log::info!("try-runtime::on_runtime_upgrade failed with: {:?}", err); @@ -1027,7 +1027,7 @@ impl_runtime_apis! { }).unwrap(); (weight, BlockWeights::get().max_block) } - fn execute_block_no_check(block: Block) -> Weight { + fn execute_block_no_check(block: Block) -> frame_support::pallet_prelude::Weight { Executive::execute_block_no_check(block) } } From 726542b7196c086b3e17d3ef27b3a17258063f9e Mon Sep 17 00:00:00 2001 From: weichweich Date: Wed, 6 Apr 2022 13:52:54 +0200 Subject: [PATCH 08/31] fix --- runtimes/spiritnet/src/lib.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index 5aa17214cd..b24c71a069 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -971,12 +971,6 @@ pub type Executive = frame_executive::Executive< pallet_did_lookup::migrations::LookupReverseIndexMigration, >; -pub type Web3Name = pallet_web3_names::web3_name::AsciiWeb3Name; -pub type DidDoc = DidDocument< - DidDetails, - pallet_web3_names::web3_name::AsciiWeb3Name, ->; - impl_runtime_apis! { impl sp_api::Core for Runtime { fn version() -> RuntimeVersion { From 931151ade81b81cb234ecbe66320da19a5cbf756 Mon Sep 17 00:00:00 2001 From: weichweich Date: Wed, 6 Apr 2022 14:34:54 +0200 Subject: [PATCH 09/31] fixes --- nodes/standalone/src/rpc.rs | 2 +- rpc/did/runtime-api/src/lib.rs | 3 ++- rpc/did/src/lib.rs | 6 ++++-- runtimes/spiritnet/src/lib.rs | 1 - 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/nodes/standalone/src/rpc.rs b/nodes/standalone/src/rpc.rs index aa9f992d83..171c6ddb2e 100644 --- a/nodes/standalone/src/rpc.rs +++ b/nodes/standalone/src/rpc.rs @@ -27,7 +27,7 @@ use std::sync::Arc; use did_rpc::{DidApi, DidQuery}; use mashnet_node_runtime::opaque::Block; -use runtime_common::{AccountId, Balance, Index, DidIdentifier}; +use runtime_common::{AccountId, Balance, DidIdentifier, Index}; pub use sc_rpc_api::DenyUnsafe; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; diff --git a/rpc/did/runtime-api/src/lib.rs b/rpc/did/runtime-api/src/lib.rs index e8abcbf6fa..512879786d 100644 --- a/rpc/did/runtime-api/src/lib.rs +++ b/rpc/did/runtime-api/src/lib.rs @@ -31,7 +31,8 @@ pub struct DidDocument { /// The DidDocument with a Web3Name represented as a byte array. /// -/// This will be returned by the runtime and processed by the client side RPC implementation. +/// This will be returned by the runtime and processed by the client side RPC +/// implementation. pub type RawDidDocument = DidDocument>; sp_api::decl_runtime_apis! { diff --git a/rpc/did/src/lib.rs b/rpc/did/src/lib.rs index 3c9db32051..42c2ee0156 100644 --- a/rpc/did/src/lib.rs +++ b/rpc/did/src/lib.rs @@ -104,7 +104,8 @@ where data: Some(e.to_string().into()), }), Ok(doc) => Ok(doc.map(|doc| DidDocument { - // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we ignore the w3n and pretend it doesn't exist. + // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we + // ignore the w3n and pretend it doesn't exist. w3n: doc.w3n.and_then(|w3n| String::from_utf8(w3n).ok()), accounts: doc.accounts, identifier: doc.identifier, @@ -129,7 +130,8 @@ where data: Some(e.to_string().into()), }), Ok(doc) => Ok(doc.map(|doc| DidDocument { - // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we ignore the w3n and pretend it doesn't exist. + // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we + // ignore the w3n and pretend it doesn't exist. w3n: doc.w3n.and_then(|w3n| String::from_utf8(w3n).ok()), accounts: doc.accounts, identifier: doc.identifier, diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index b24c71a069..cf24325dc5 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -46,7 +46,6 @@ use sp_runtime::{ use sp_std::{cmp::Ordering, prelude::*}; use sp_version::RuntimeVersion; - use delegation::DelegationAc; pub use parachain_staking::InflationInfo; use runtime_common::{ From b7a1d2b9416e893a8269be36bb487d6cced1c7c8 Mon Sep 17 00:00:00 2001 From: weichweich Date: Wed, 6 Apr 2022 14:35:02 +0200 Subject: [PATCH 10/31] fix debug implementation --- pallets/parachain-staking/src/set.rs | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/pallets/parachain-staking/src/set.rs b/pallets/parachain-staking/src/set.rs index a0e2cf4205..060ade6380 100644 --- a/pallets/parachain-staking/src/set.rs +++ b/pallets/parachain-staking/src/set.rs @@ -16,7 +16,7 @@ // If you feel like getting in touch with us, you can do so at info@botlabs.org -use frame_support::{traits::Get, BoundedVec, DefaultNoBound}; +use frame_support::{traits::Get, BoundedVec, DefaultNoBound, RuntimeDebug}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_runtime::{traits::Zero, SaturatedConversion}; @@ -27,10 +27,10 @@ use sp_std::{ }; #[cfg(feature = "std")] -use sp_std::{fmt, prelude::*}; +use sp_std::prelude::*; /// An ordered set backed by `BoundedVec`. -#[derive(PartialEq, Eq, Encode, Decode, DefaultNoBound, Clone, TypeInfo, MaxEncodedLen)] +#[derive(PartialEq, Eq, Encode, Decode, RuntimeDebug, DefaultNoBound, Clone, TypeInfo, MaxEncodedLen)] #[scale_info(skip_type_params(S))] #[codec(mel_bound(T: MaxEncodedLen))] pub struct OrderedSet>(BoundedVec); @@ -230,17 +230,6 @@ impl> OrderedSet { } } -#[cfg(feature = "std")] -impl fmt::Debug for OrderedSet -where - T: fmt::Debug, - S: Get, -{ - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_tuple("OrderedSet").field(&self.0).finish() - } -} - impl> From> for OrderedSet { fn from(bv: BoundedVec) -> Self { Self::from(bv) From 0f8cba471c89d388865a3b709d6d32908d7b8a90 Mon Sep 17 00:00:00 2001 From: weichweich Date: Wed, 6 Apr 2022 14:37:11 +0200 Subject: [PATCH 11/31] fix features --- runtimes/common/Cargo.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/runtimes/common/Cargo.toml b/runtimes/common/Cargo.toml index bf78e8d4c2..e00b882ddf 100644 --- a/runtimes/common/Cargo.toml +++ b/runtimes/common/Cargo.toml @@ -35,6 +35,10 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", ] std = [ + "parachain-staking/std", + "pallet-web3-names/std", + "did/std", + "attestation/std", "codec/std", "frame-support/std", "frame-system/std", From 219b69195c56f25787846026f7620b7e96c987b7 Mon Sep 17 00:00:00 2001 From: weichweich Date: Wed, 20 Apr 2022 08:38:59 +0200 Subject: [PATCH 12/31] feat: list of linked accounts --- rpc/did/runtime-api/src/lib.rs | 2 +- runtimes/peregrine/src/lib.rs | 7 +++++-- runtimes/spiritnet/src/lib.rs | 7 +++++-- runtimes/standalone/src/lib.rs | 7 +++++-- 4 files changed, 16 insertions(+), 7 deletions(-) diff --git a/rpc/did/runtime-api/src/lib.rs b/rpc/did/runtime-api/src/lib.rs index 512879786d..ecb125b5c4 100644 --- a/rpc/did/runtime-api/src/lib.rs +++ b/rpc/did/runtime-api/src/lib.rs @@ -25,7 +25,7 @@ use sp_std::vec::Vec; #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] pub struct DidDocument { pub identifier: DidIdentifier, - pub accounts: Option>, + pub accounts: Vec, pub w3n: Option, } diff --git a/runtimes/peregrine/src/lib.rs b/runtimes/peregrine/src/lib.rs index b404dd49a0..5681d65af2 100644 --- a/runtimes/peregrine/src/lib.rs +++ b/runtimes/peregrine/src/lib.rs @@ -1113,10 +1113,11 @@ impl_runtime_apis! { let name: Web3Name = name.try_into().ok()?; pallet_web3_names::Owner::::get(&name) .map(|owner_info| { + let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&owner_info.owner).collect(); did_rpc_runtime_api::RawDidDocument { identifier: owner_info.owner, w3n: Some(name.into()), - accounts: None, + accounts, } }) } @@ -1124,10 +1125,12 @@ impl_runtime_apis! { fn query_did_by_account_id(account: AccountId) -> Option> { pallet_did_lookup::ConnectedDids::::get(account).map(|connection_record| { let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); + let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); + did_rpc_runtime_api::RawDidDocument { identifier: connection_record.did, w3n, - accounts: None, + accounts, } }) } diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index 420f5f22df..951f9783d9 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -1116,10 +1116,11 @@ impl_runtime_apis! { let name: Web3Name = name.try_into().ok()?; pallet_web3_names::Owner::::get(&name) .map(|owner_info| { + let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&owner_info.owner).collect(); did_rpc_runtime_api::RawDidDocument { identifier: owner_info.owner, w3n: Some(name.into()), - accounts: None, + accounts, } }) } @@ -1127,10 +1128,12 @@ impl_runtime_apis! { fn query_did_by_account_id(account: AccountId) -> Option> { pallet_did_lookup::ConnectedDids::::get(account).map(|connection_record| { let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); + let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); + did_rpc_runtime_api::RawDidDocument { identifier: connection_record.did, w3n, - accounts: None, + accounts, } }) } diff --git a/runtimes/standalone/src/lib.rs b/runtimes/standalone/src/lib.rs index 8cc486289a..7ad88df22f 100644 --- a/runtimes/standalone/src/lib.rs +++ b/runtimes/standalone/src/lib.rs @@ -912,10 +912,11 @@ impl_runtime_apis! { let name: Web3Name = name.try_into().ok()?; pallet_web3_names::Owner::::get(&name) .map(|owner_info| { + let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&owner_info.owner).collect(); did_rpc_runtime_api::RawDidDocument { identifier: owner_info.owner, w3n: Some(name.into()), - accounts: None, + accounts, } }) } @@ -923,10 +924,12 @@ impl_runtime_apis! { fn query_did_by_account_id(account: AccountId) -> Option> { pallet_did_lookup::ConnectedDids::::get(account).map(|connection_record| { let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); + let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); + did_rpc_runtime_api::RawDidDocument { identifier: connection_record.did, w3n, - accounts: None, + accounts, } }) } From a7495c63500cd324d9b488d1fe473100193ed410 Mon Sep 17 00:00:00 2001 From: weichweich Date: Wed, 20 Apr 2022 09:52:36 +0200 Subject: [PATCH 13/31] fix: features --- pallets/attestation/Cargo.toml | 11 ++++++----- pallets/ctype/Cargo.toml | 10 ++++++---- pallets/delegation/Cargo.toml | 6 +++--- pallets/did/Cargo.toml | 6 +++--- pallets/kilt-launch/Cargo.toml | 4 ++-- pallets/pallet-did-lookup/Cargo.toml | 8 ++++---- pallets/pallet-inflation/Cargo.toml | 6 +++--- pallets/pallet-web3-names/Cargo.toml | 8 ++++---- pallets/parachain-staking/Cargo.toml | 10 +++++----- runtimes/common/Cargo.toml | 2 ++ scripts/all.fish | 12 ++++++++++++ 11 files changed, 50 insertions(+), 33 deletions(-) diff --git a/pallets/attestation/Cargo.toml b/pallets/attestation/Cargo.toml index d595d7ec2b..9e55bbe429 100644 --- a/pallets/attestation/Cargo.toml +++ b/pallets/attestation/Cargo.toml @@ -13,14 +13,15 @@ targets = ["x86_64-unknown-linux-gnu"] substrate-wasm-builder-runner = {version = "3.0.0"} [dev-dependencies] +serde = {version = "1.0.132"} + ctype = {features = ["mock"], path = "../ctype"} kilt-support = {features = ["mock"], path = "../../support"} -pallet-balances = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -serde = {version = "1.0.132"} -sp-core = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -sp-io = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -sp-keystore = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} +pallet-balances = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-core = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-io = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-keystore = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} [dependencies] codec = {default-features = false, features = ["derive"], package = "parity-scale-codec", version = "2.3.1"} diff --git a/pallets/ctype/Cargo.toml b/pallets/ctype/Cargo.toml index 83a27f8bb7..6c1293040f 100644 --- a/pallets/ctype/Cargo.toml +++ b/pallets/ctype/Cargo.toml @@ -13,11 +13,13 @@ targets = ["x86_64-unknown-linux-gnu"] substrate-wasm-builder-runner = {version = "3.0.0"} [dev-dependencies] -kilt-support = {features = ["mock"], path = "../../support"} -pallet-balances = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} serde = {version = "1.0.132"} -sp-core = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -sp-keystore = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} + +kilt-support = {features = ["mock"], path = "../../support"} + +pallet-balances = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-core = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-keystore = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} [dependencies] codec = {default-features = false, features = ["derive"], package = "parity-scale-codec", version = "2.3.1"} diff --git a/pallets/delegation/Cargo.toml b/pallets/delegation/Cargo.toml index f00b345461..fc73b0b498 100644 --- a/pallets/delegation/Cargo.toml +++ b/pallets/delegation/Cargo.toml @@ -22,9 +22,9 @@ env_logger = {version = "0.8.4"} serde = {version = "1.0.132"} # Substrate dependencies -pallet-balances = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -sp-core = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -sp-keystore = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} +pallet-balances = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-core = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-keystore = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} [dependencies] # Internal dependencies diff --git a/pallets/did/Cargo.toml b/pallets/did/Cargo.toml index 2e98e16f41..4517e10559 100644 --- a/pallets/did/Cargo.toml +++ b/pallets/did/Cargo.toml @@ -18,9 +18,9 @@ serde = {version = "1.0.132"} ctype = {features = ["mock"], path = "../ctype"} -frame-benchmarking = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -pallet-balances = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -sp-keystore = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} +frame-benchmarking = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +pallet-balances = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-keystore = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} [dependencies] # Internal dependencies diff --git a/pallets/kilt-launch/Cargo.toml b/pallets/kilt-launch/Cargo.toml index f755c40621..ac33d9570e 100644 --- a/pallets/kilt-launch/Cargo.toml +++ b/pallets/kilt-launch/Cargo.toml @@ -10,8 +10,8 @@ version = "1.6.2" targets = ["x86_64-unknown-linux-gnu"] [dev-dependencies] -sp-core = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} -sp-io = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} +sp-core = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17"} +sp-io = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17"} [dependencies] codec = {package = "parity-scale-codec", version = "2.3.1", default-features = false, features = ["derive"]} diff --git a/pallets/pallet-did-lookup/Cargo.toml b/pallets/pallet-did-lookup/Cargo.toml index 6b73ae2e1b..9cca1e906b 100644 --- a/pallets/pallet-did-lookup/Cargo.toml +++ b/pallets/pallet-did-lookup/Cargo.toml @@ -12,10 +12,10 @@ targets = ["x86_64-unknown-linux-gnu"] [dev-dependencies] kilt-support = {features = ["mock"], path = "../../support"} -pallet-balances = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -sp-core = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -sp-io = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -sp-keystore = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} +pallet-balances = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-core = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-io = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-keystore = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} [dependencies] codec = {default-features = false, features = ["derive"], package = "parity-scale-codec", version = "2.3.1"} diff --git a/pallets/pallet-inflation/Cargo.toml b/pallets/pallet-inflation/Cargo.toml index 830ee4e441..6ff859548d 100644 --- a/pallets/pallet-inflation/Cargo.toml +++ b/pallets/pallet-inflation/Cargo.toml @@ -12,9 +12,9 @@ targets = ["x86_64-unknown-linux-gnu"] [dev-dependencies] serde = {version = "1.0.132"} -pallet-balances = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -sp-core = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -sp-io = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} +pallet-balances = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-core = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-io = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} [dependencies] codec = {default-features = false, features = ["derive"], package = "parity-scale-codec", version = "2.3.1"} diff --git a/pallets/pallet-web3-names/Cargo.toml b/pallets/pallet-web3-names/Cargo.toml index 1ad0234ff3..116fd988a2 100644 --- a/pallets/pallet-web3-names/Cargo.toml +++ b/pallets/pallet-web3-names/Cargo.toml @@ -12,10 +12,10 @@ targets = ["x86_64-unknown-linux-gnu"] [dev-dependencies] kilt-support = {features = ["mock"], path = "../../support"} -pallet-balances = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -sp-core = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -sp-io = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -sp-keystore = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} +pallet-balances = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-core = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-io = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} +sp-keystore = {branch = "polkadot-v0.9.17", git = "https://github.com/paritytech/substrate"} [dependencies] codec = {default-features = false, features = ["derive"], package = "parity-scale-codec", version = "2.3.1"} diff --git a/pallets/parachain-staking/Cargo.toml b/pallets/parachain-staking/Cargo.toml index 98bcf2860c..e47c2fb4f2 100644 --- a/pallets/parachain-staking/Cargo.toml +++ b/pallets/parachain-staking/Cargo.toml @@ -6,11 +6,11 @@ name = "parachain-staking" version = "1.6.2" [dev-dependencies] -pallet-aura = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17", default-features = false} -pallet-timestamp = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17", default-features = false} -sp-consensus-aura = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17", default-features = false} -sp-core = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17", default-features = false} -sp-io = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17", default-features = false} +pallet-aura = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17"} +pallet-timestamp = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17"} +sp-consensus-aura = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17"} +sp-core = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17"} +sp-io = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17"} [dependencies] hex-literal = "0.3.4" diff --git a/runtimes/common/Cargo.toml b/runtimes/common/Cargo.toml index 28ce7b8b1a..7b0adb4000 100644 --- a/runtimes/common/Cargo.toml +++ b/runtimes/common/Cargo.toml @@ -34,6 +34,8 @@ default = ["std"] fast-gov = [] runtime-benchmarks = [ "attestation/runtime-benchmarks", + "did/runtime-benchmarks", + "pallet-web3-names/runtime-benchmarks", "frame-support/runtime-benchmarks", "parachain-staking/runtime-benchmarks", "sp-runtime/runtime-benchmarks", diff --git a/scripts/all.fish b/scripts/all.fish index 57693e947d..316bf21361 100644 --- a/scripts/all.fish +++ b/scripts/all.fish @@ -13,3 +13,15 @@ for features in "--features default" "--all-features" "--features runtime-benchm echo cargo build -p $package (echo $features | string split " ") end end + +for features in "--features default" "--all-features" "--features runtime-benchmarks" "--features try-runtime" + for package in (cargo workspaces list) + cargo test -p $package (echo $features | string split " ") > /dev/null ^ /dev/null + if [ "$status" = "0" ] + echo -n "[ok] " + else + echo -n "[fail] " + end + echo cargo test -p $package (echo $features | string split " ") + end +end From 003c3f1d66cd3850f44bb1b8c332f16b57a74d23 Mon Sep 17 00:00:00 2001 From: weichweich Date: Thu, 21 Apr 2022 09:52:58 +0200 Subject: [PATCH 14/31] reafactor: derive debug --- pallets/did/src/service_endpoints.rs | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/pallets/did/src/service_endpoints.rs b/pallets/did/src/service_endpoints.rs index 104aee443c..3053d8c5c2 100644 --- a/pallets/did/src/service_endpoints.rs +++ b/pallets/did/src/service_endpoints.rs @@ -18,7 +18,7 @@ use crate::{errors::InputError, Config}; use codec::{Decode, Encode, MaxEncodedLen}; -use frame_support::{ensure, traits::Get, BoundedVec}; +use frame_support::{ensure, traits::Get, BoundedVec, RuntimeDebug}; use scale_info::TypeInfo; use sp_runtime::traits::SaturatedConversion; use sp_std::str; @@ -43,7 +43,7 @@ pub(crate) type ServiceEndpointUrlEntries = BoundedVec, ::MaxNumberOfUrlsPerService>; /// A single service endpoint description. -#[derive(Clone, Decode, Encode, PartialEq, Eq, TypeInfo, MaxEncodedLen)] +#[derive(Clone, Decode, Encode, RuntimeDebug, PartialEq, Eq, TypeInfo, MaxEncodedLen)] #[scale_info(skip_type_params(T))] #[codec(mel_bound())] pub struct DidEndpoint { @@ -56,16 +56,6 @@ pub struct DidEndpoint { pub urls: ServiceEndpointUrlEntries, } -impl sp_std::fmt::Debug for DidEndpoint { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { - f.debug_struct("DidEndpoint") - .field("id", &self.id.clone().into_inner()) - .field("service_types", &self.service_types.encode()) - .field("urls", &self.urls.encode()) - .finish() - } -} - impl DidEndpoint { /// Validates a given [DidEndpoint] instance against the constraint /// set in the pallet's [Config]. From 5d552126ddcf887607e56caeb73d88e45b2fe9b7 Mon Sep 17 00:00:00 2001 From: weichweich Date: Fri, 22 Apr 2022 09:50:07 +0200 Subject: [PATCH 15/31] feat: include service endpoints --- rpc/did/runtime-api/src/lib.rs | 34 +++++++++++++++++++++++-- rpc/did/src/lib.rs | 45 ++++++++++++++++++++++++++++------ runtimes/peregrine/src/lib.rs | 5 ++++ runtimes/spiritnet/src/lib.rs | 5 ++++ runtimes/standalone/src/lib.rs | 5 ++++ 5 files changed, 85 insertions(+), 9 deletions(-) diff --git a/rpc/did/runtime-api/src/lib.rs b/rpc/did/runtime-api/src/lib.rs index ecb125b5c4..e08f41d4ef 100644 --- a/rpc/did/runtime-api/src/lib.rs +++ b/rpc/did/runtime-api/src/lib.rs @@ -23,17 +23,47 @@ use sp_std::vec::Vec; #[derive(Encode, Decode, TypeInfo, PartialEq)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -pub struct DidDocument { +pub struct ServiceEndpoint { + pub id: Id, + pub service_types: Vec, + pub urls: Vec, +} + +impl From> for ServiceEndpoint, Vec, Vec> { + fn from(runtime_endpoint: did::service_endpoints::DidEndpoint) -> Self { + ServiceEndpoint { + id: runtime_endpoint.id.into_inner(), + service_types: runtime_endpoint + .service_types + .into_inner() + .into_iter() + .map(|v| v.into_inner()) + .collect(), + urls: runtime_endpoint + .urls + .into_inner() + .into_iter() + .map(|v| v.into_inner()) + .collect(), + } + } +} + +#[derive(Encode, Decode, TypeInfo, PartialEq)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub struct DidDocument { pub identifier: DidIdentifier, pub accounts: Vec, pub w3n: Option, + pub service_endpoints: Vec>, } /// The DidDocument with a Web3Name represented as a byte array. /// /// This will be returned by the runtime and processed by the client side RPC /// implementation. -pub type RawDidDocument = DidDocument>; +pub type RawDidDocument = + DidDocument, Vec, Vec, Vec>; sp_api::decl_runtime_apis! { /// The API to query account nonce (aka transaction index). diff --git a/rpc/did/src/lib.rs b/rpc/did/src/lib.rs index 42c2ee0156..be6985c92a 100644 --- a/rpc/did/src/lib.rs +++ b/rpc/did/src/lib.rs @@ -19,7 +19,7 @@ use std::sync::Arc; use codec::Codec; -use did_rpc_runtime_api::DidDocument; +use did_rpc_runtime_api::{DidDocument, ServiceEndpoint}; use jsonrpc_core::{Error as RpcError, ErrorCode, Result}; use jsonrpc_derive::rpc; use sp_api::ProvideRuntimeApi; @@ -28,6 +28,27 @@ use sp_runtime::{generic::BlockId, traits::Block as BlockT}; pub use did_rpc_runtime_api::DidApi as DidRuntimeApi; +pub type RpcDidDocument = + DidDocument; + +fn raw_did_endpoint_to_rpc( + raw: ServiceEndpoint, Vec, Vec>, +) -> Option> { + Some(ServiceEndpoint { + id: String::from_utf8(raw.id).ok()?, + service_types: raw + .service_types + .into_iter() + .filter_map(|st| String::from_utf8(st).ok()) + .collect(), + urls: raw + .urls + .into_iter() + .filter_map(|url| String::from_utf8(url).ok()) + .collect(), + }) +} + #[rpc] pub trait DidApi { #[rpc(name = "did_queryByWeb3Name")] @@ -35,14 +56,14 @@ pub trait DidApi { &self, web3name: String, at: Option, - ) -> Result>>; + ) -> Result>>; #[rpc(name = "did_queryByAccount")] fn query_did_by_account_id( &self, account: AccountId, at: Option, - ) -> Result>>; + ) -> Result>>; } /// A struct that implements the [`TransactionPaymentApi`]. @@ -91,7 +112,7 @@ where &self, web3name: String, at: Option<::Hash>, - ) -> Result>> { + ) -> Result>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. @@ -103,12 +124,17 @@ where message: "Unable to query dispatch info.".into(), data: Some(e.to_string().into()), }), - Ok(doc) => Ok(doc.map(|doc| DidDocument { + Ok(doc) => Ok(doc.map(|doc| RpcDidDocument { // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we // ignore the w3n and pretend it doesn't exist. w3n: doc.w3n.and_then(|w3n| String::from_utf8(w3n).ok()), accounts: doc.accounts, identifier: doc.identifier, + service_endpoints: doc + .service_endpoints + .into_iter() + .filter_map(raw_did_endpoint_to_rpc) + .collect(), })), } } @@ -117,7 +143,7 @@ where &self, account: AccountId, at: Option<::Hash>, - ) -> Result>> { + ) -> Result>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. @@ -129,12 +155,17 @@ where message: "Unable to query fee details.".into(), data: Some(e.to_string().into()), }), - Ok(doc) => Ok(doc.map(|doc| DidDocument { + Ok(doc) => Ok(doc.map(|doc| RpcDidDocument { // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we // ignore the w3n and pretend it doesn't exist. w3n: doc.w3n.and_then(|w3n| String::from_utf8(w3n).ok()), accounts: doc.accounts, identifier: doc.identifier, + service_endpoints: doc + .service_endpoints + .into_iter() + .filter_map(raw_did_endpoint_to_rpc) + .collect(), })), } } diff --git a/runtimes/peregrine/src/lib.rs b/runtimes/peregrine/src/lib.rs index 5681d65af2..da3ef905e0 100644 --- a/runtimes/peregrine/src/lib.rs +++ b/runtimes/peregrine/src/lib.rs @@ -1114,10 +1114,13 @@ impl_runtime_apis! { pallet_web3_names::Owner::::get(&name) .map(|owner_info| { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&owner_info.owner).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e|From::from(e.1)).collect(); + did_rpc_runtime_api::RawDidDocument { identifier: owner_info.owner, w3n: Some(name.into()), accounts, + service_endpoints, } }) } @@ -1126,11 +1129,13 @@ impl_runtime_apis! { pallet_did_lookup::ConnectedDids::::get(account).map(|connection_record| { let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); did_rpc_runtime_api::RawDidDocument { identifier: connection_record.did, w3n, accounts, + service_endpoints, } }) } diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index 951f9783d9..064cfbb79b 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -1117,10 +1117,13 @@ impl_runtime_apis! { pallet_web3_names::Owner::::get(&name) .map(|owner_info| { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&owner_info.owner).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e|From::from(e.1)).collect(); + did_rpc_runtime_api::RawDidDocument { identifier: owner_info.owner, w3n: Some(name.into()), accounts, + service_endpoints, } }) } @@ -1129,11 +1132,13 @@ impl_runtime_apis! { pallet_did_lookup::ConnectedDids::::get(account).map(|connection_record| { let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); did_rpc_runtime_api::RawDidDocument { identifier: connection_record.did, w3n, accounts, + service_endpoints, } }) } diff --git a/runtimes/standalone/src/lib.rs b/runtimes/standalone/src/lib.rs index 7ad88df22f..ee23c4fcf1 100644 --- a/runtimes/standalone/src/lib.rs +++ b/runtimes/standalone/src/lib.rs @@ -913,10 +913,13 @@ impl_runtime_apis! { pallet_web3_names::Owner::::get(&name) .map(|owner_info| { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&owner_info.owner).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e|From::from(e.1)).collect(); + did_rpc_runtime_api::RawDidDocument { identifier: owner_info.owner, w3n: Some(name.into()), accounts, + service_endpoints, } }) } @@ -925,11 +928,13 @@ impl_runtime_apis! { pallet_did_lookup::ConnectedDids::::get(account).map(|connection_record| { let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); did_rpc_runtime_api::RawDidDocument { identifier: connection_record.did, w3n, accounts, + service_endpoints, } }) } From aa6329c21a0dc13c15e8e06c75b2e05aef3d222d Mon Sep 17 00:00:00 2001 From: weichweich Date: Tue, 26 Apr 2022 14:28:07 +0200 Subject: [PATCH 16/31] feat: query by did --- rpc/did/runtime-api/src/lib.rs | 1 + rpc/did/src/lib.rs | 38 ++++++++++++++++++++++++++++++++++ runtimes/peregrine/src/lib.rs | 13 ++++++++++++ runtimes/spiritnet/src/lib.rs | 13 ++++++++++++ runtimes/standalone/src/lib.rs | 13 ++++++++++++ 5 files changed, 78 insertions(+) diff --git a/rpc/did/runtime-api/src/lib.rs b/rpc/did/runtime-api/src/lib.rs index e08f41d4ef..5d0109d70a 100644 --- a/rpc/did/runtime-api/src/lib.rs +++ b/rpc/did/runtime-api/src/lib.rs @@ -73,5 +73,6 @@ sp_api::decl_runtime_apis! { { fn query_did_by_w3n(name: Vec) -> Option>; fn query_did_by_account_id(account: AccountId) -> Option>; + fn query_did(did: DidIdentifier) -> Option>; } } diff --git a/rpc/did/src/lib.rs b/rpc/did/src/lib.rs index be6985c92a..8516dda35f 100644 --- a/rpc/did/src/lib.rs +++ b/rpc/did/src/lib.rs @@ -64,6 +64,13 @@ pub trait DidApi { account: AccountId, at: Option, ) -> Result>>; + + #[rpc(name = "did_query")] + fn query_did( + &self, + account: DidIdentifier, + at: Option, + ) -> Result>>; } /// A struct that implements the [`TransactionPaymentApi`]. @@ -169,4 +176,35 @@ where })), } } + + fn query_did( + &self, + did: DidIdentifier, + at: Option<::Hash>, + ) -> Result>> { + let api = self.client.runtime_api(); + let at = BlockId::hash(at.unwrap_or_else(|| + // If the block hash is not supplied assume the best block. + self.client.info().best_hash)); + + match api.query_did(&at, did) { + Err(e) => Err(RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Unable to query fee details.".into(), + data: Some(e.to_string().into()), + }), + Ok(doc) => Ok(doc.map(|doc| RpcDidDocument { + // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we + // ignore the w3n and pretend it doesn't exist. + w3n: doc.w3n.and_then(|w3n| String::from_utf8(w3n).ok()), + accounts: doc.accounts, + identifier: doc.identifier, + service_endpoints: doc + .service_endpoints + .into_iter() + .filter_map(raw_did_endpoint_to_rpc) + .collect(), + })), + } + } } diff --git a/runtimes/peregrine/src/lib.rs b/runtimes/peregrine/src/lib.rs index da3ef905e0..5c12915359 100644 --- a/runtimes/peregrine/src/lib.rs +++ b/runtimes/peregrine/src/lib.rs @@ -1139,6 +1139,19 @@ impl_runtime_apis! { } }) } + + fn query_did(did: DidIdentifier) -> Option> { + let w3n = pallet_web3_names::Names::::get(&did).map(Into::into); + let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&did).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e|From::from(e.1)).collect(); + + Some(did_rpc_runtime_api::RawDidDocument { + identifier: did, + w3n, + accounts, + service_endpoints, + }) + } } #[cfg(feature = "runtime-benchmarks")] diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index 064cfbb79b..8688aee2a2 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -1142,6 +1142,19 @@ impl_runtime_apis! { } }) } + + fn query_did(did: DidIdentifier) -> Option> { + let w3n = pallet_web3_names::Names::::get(&did).map(Into::into); + let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&did).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e|From::from(e.1)).collect(); + + Some(did_rpc_runtime_api::RawDidDocument { + identifier: did, + w3n, + accounts, + service_endpoints, + }) + } } #[cfg(feature = "runtime-benchmarks")] diff --git a/runtimes/standalone/src/lib.rs b/runtimes/standalone/src/lib.rs index ee23c4fcf1..9e502b4ecc 100644 --- a/runtimes/standalone/src/lib.rs +++ b/runtimes/standalone/src/lib.rs @@ -938,6 +938,19 @@ impl_runtime_apis! { } }) } + + fn query_did(did: DidIdentifier) -> Option> { + let w3n = pallet_web3_names::Names::::get(&did).map(Into::into); + let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&did).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e|From::from(e.1)).collect(); + + Some(did_rpc_runtime_api::RawDidDocument { + identifier: did, + w3n, + accounts, + service_endpoints, + }) + } } #[cfg(feature = "runtime-benchmarks")] From b2f26b0d7660ae1050b5778648510509cd9a1ceb Mon Sep 17 00:00:00 2001 From: weichweich Date: Tue, 26 Apr 2022 14:36:08 +0200 Subject: [PATCH 17/31] refactor: derive debug --- pallets/did/src/did_details.rs | 25 +++++-------------------- 1 file changed, 5 insertions(+), 20 deletions(-) diff --git a/pallets/did/src/did_details.rs b/pallets/did/src/did_details.rs index 528d641134..d90a3f6712 100644 --- a/pallets/did/src/did_details.rs +++ b/pallets/did/src/did_details.rs @@ -21,6 +21,7 @@ use frame_support::{ ensure, storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet}, traits::Get, + RuntimeDebug, }; use kilt_support::deposit::Deposit; use scale_info::TypeInfo; @@ -551,7 +552,7 @@ pub(crate) type DidPublicKeyMap = BoundedBTreeMap, DidPublicKeyDetails, ::MaxPublicKeysPerDid>; /// The details of a new DID to create. -#[derive(Clone, Decode, Encode, PartialEq, TypeInfo)] +#[derive(Clone, Decode, Encode, PartialEq, TypeInfo, RuntimeDebug)] #[scale_info(skip_type_params(T))] pub struct DidCreationDetails { @@ -569,25 +570,9 @@ pub struct DidCreationDetails { pub new_service_details: Vec>, } -impl sp_std::fmt::Debug for DidCreationDetails { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { - f.debug_struct("DidCreationDetails") - .field("did", &self.did) - .field("submitter", &self.submitter) - .field( - "new_key_agreement_keys", - &self.new_key_agreement_keys.clone().into_inner(), - ) - .field("new_attestation_key", &self.new_attestation_key) - .field("new_delegation_key", &self.new_delegation_key) - .field("new_service_details", &self.new_service_details) - .finish() - } -} - /// Errors that might occur while deriving the authorization verification key /// relationship. -#[derive(Clone, Debug, Decode, Encode, PartialEq)] +#[derive(Clone, RuntimeDebug, Decode, Encode, PartialEq)] pub enum RelationshipDeriveError { /// The call is not callable by a did origin. NotCallableByDid, @@ -618,7 +603,7 @@ pub trait DeriveDidCallAuthorizationVerificationKeyRelationship { /// A DID operation that wraps other extrinsic calls, allowing those /// extrinsic to have a DID origin and perform DID-based authorization upon /// their invocation. -#[derive(Clone, Debug, Decode, Encode, PartialEq, TypeInfo)] +#[derive(Clone, RuntimeDebug, Decode, Encode, PartialEq, TypeInfo)] #[scale_info(skip_type_params(T))] pub struct DidAuthorizedCallOperation { @@ -638,7 +623,7 @@ pub struct DidAuthorizedCallOperation { /// /// It contains additional information about the type of DID key to used for /// authorization. -#[derive(Clone, Debug, PartialEq, TypeInfo)] +#[derive(Clone, RuntimeDebug, PartialEq, TypeInfo)] #[scale_info(skip_type_params(T))] pub struct DidAuthorizedCallOperationWithVerificationRelationship { From 77a5547328151b0f207b2ef5e9834ccbf36831b8 Mon Sep 17 00:00:00 2001 From: weichweich Date: Tue, 26 Apr 2022 16:05:36 +0200 Subject: [PATCH 18/31] refactor: clear DidPublicKeyDetails from pallet specifics --- pallets/did/src/did_details.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/pallets/did/src/did_details.rs b/pallets/did/src/did_details.rs index d90a3f6712..5b3f88126f 100644 --- a/pallets/did/src/did_details.rs +++ b/pallets/did/src/did_details.rs @@ -231,13 +231,12 @@ impl> DidVerifiableIdentifier for I { /// It is currently used to keep track of all the past and current /// attestation keys a DID might control. #[derive(Clone, Debug, Decode, Encode, PartialEq, Ord, PartialOrd, Eq, TypeInfo, MaxEncodedLen)] -#[scale_info(skip_type_params(T))] #[codec(mel_bound())] -pub struct DidPublicKeyDetails { +pub struct DidPublicKeyDetails { /// A public key the DID controls. pub key: DidPublicKey, /// The block number in which the verification key was added to the DID. - pub block_number: BlockNumberOf, + pub block_number: BlockNumber, } /// The details associated to a DID identity. @@ -549,7 +548,7 @@ impl DidDetails { pub(crate) type DidNewKeyAgreementKeySet = BoundedBTreeSet::MaxNewKeyAgreementKeys>; pub(crate) type DidKeyAgreementKeySet = BoundedBTreeSet, ::MaxTotalKeyAgreementKeys>; pub(crate) type DidPublicKeyMap = - BoundedBTreeMap, DidPublicKeyDetails, ::MaxPublicKeysPerDid>; + BoundedBTreeMap, DidPublicKeyDetails>, ::MaxPublicKeysPerDid>; /// The details of a new DID to create. #[derive(Clone, Decode, Encode, PartialEq, TypeInfo, RuntimeDebug)] From 560b321fb7af8a93ada4e8fb8b9cac0f28a0df15 Mon Sep 17 00:00:00 2001 From: weichweich Date: Wed, 27 Apr 2022 13:13:02 +0200 Subject: [PATCH 19/31] feat: did details --- Cargo.lock | 2 + nodes/parachain/src/rpc.rs | 4 +- nodes/parachain/src/service.rs | 2 +- nodes/standalone/src/rpc.rs | 9 +-- pallets/did/Cargo.toml | 2 + pallets/did/src/did_details.rs | 30 ++++----- pallets/did/src/lib.rs | 4 +- rpc/did/runtime-api/Cargo.toml | 2 + rpc/did/runtime-api/src/did_details.rs | 52 +++++++++++++++ rpc/did/runtime-api/src/lib.rs | 51 +++++---------- rpc/did/runtime-api/src/service_endpoint.rs | 48 ++++++++++++++ rpc/did/src/lib.rs | 36 +++++++---- runtimes/peregrine/src/lib.rs | 71 ++++++++++++++++----- runtimes/spiritnet/src/lib.rs | 71 ++++++++++++++++----- runtimes/standalone/src/lib.rs | 71 ++++++++++++++++----- support/Cargo.toml | 3 + support/src/deposit.rs | 1 + 17 files changed, 334 insertions(+), 125 deletions(-) create mode 100644 rpc/did/runtime-api/src/did_details.rs create mode 100644 rpc/did/runtime-api/src/service_endpoint.rs diff --git a/Cargo.lock b/Cargo.lock index 7f108f77ce..4434f312d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1930,6 +1930,7 @@ name = "did-rpc-runtime-api" version = "1.5.0" dependencies = [ "did", + "kilt-support", "parity-scale-codec", "scale-info", "serde", @@ -3631,6 +3632,7 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", + "serde", "sp-core", "sp-runtime", "sp-std", diff --git a/nodes/parachain/src/rpc.rs b/nodes/parachain/src/rpc.rs index aba11fd4fa..4940cc6845 100644 --- a/nodes/parachain/src/rpc.rs +++ b/nodes/parachain/src/rpc.rs @@ -29,7 +29,7 @@ use did_rpc::{DidApi, DidQuery}; use frame_rpc_system::{FullSystem, SystemApi}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; use polkadot_service::AuxStore; -use runtime_common::{AccountId, Balance, Block, DidIdentifier, Index}; +use runtime_common::{AccountId, Balance, Block, DidIdentifier, Index, BlockNumber, Hash}; use sc_service::Error; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; @@ -57,7 +57,7 @@ where C: Send + Sync + 'static, C::Api: frame_rpc_system::AccountNonceApi, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, - C::Api: did_rpc::DidRuntimeApi, + C::Api: did_rpc::DidRuntimeApi, C::Api: BlockBuilder, P: TransactionPool + Sync + Send + 'static, { diff --git a/nodes/parachain/src/service.rs b/nodes/parachain/src/service.rs index d03765b4eb..c97f8029b1 100644 --- a/nodes/parachain/src/service.rs +++ b/nodes/parachain/src/service.rs @@ -412,7 +412,7 @@ where + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi + sp_consensus_aura::AuraApi + cumulus_primitives_core::CollectCollationInfo - + did_rpc::DidRuntimeApi, + + did_rpc::DidRuntimeApi, sc_client_api::StateBackendFor, Block>: sp_api::StateBackend, { let rpc_extensions_builder = diff --git a/nodes/standalone/src/rpc.rs b/nodes/standalone/src/rpc.rs index 171c6ddb2e..250bc7c484 100644 --- a/nodes/standalone/src/rpc.rs +++ b/nodes/standalone/src/rpc.rs @@ -25,15 +25,16 @@ use std::sync::Arc; -use did_rpc::{DidApi, DidQuery}; -use mashnet_node_runtime::opaque::Block; -use runtime_common::{AccountId, Balance, DidIdentifier, Index}; pub use sc_rpc_api::DenyUnsafe; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; use sp_block_builder::BlockBuilder; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; +use did_rpc::{DidApi, DidQuery}; +use mashnet_node_runtime::opaque::Block; +use runtime_common::{AccountId, Balance, BlockNumber, DidIdentifier, Hash, Index}; + /// Full client dependencies. pub struct FullDeps { /// The client instance to use. @@ -53,7 +54,7 @@ where C::Api: frame_rpc_system::AccountNonceApi, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, C::Api: BlockBuilder, - C::Api: did_rpc::DidRuntimeApi, + C::Api: did_rpc::DidRuntimeApi, P: TransactionPool + 'static, { use frame_rpc_system::{FullSystem, SystemApi}; diff --git a/pallets/did/Cargo.toml b/pallets/did/Cargo.toml index 4517e10559..8d159999c2 100644 --- a/pallets/did/Cargo.toml +++ b/pallets/did/Cargo.toml @@ -31,6 +31,7 @@ kilt-support = {default-features = false, path = "../../support"} env_logger = {default-features = false, version = "0.8.3", optional = true} hex = {default-features = false, features = ["alloc"], version = "0.4.2"} log = "0.4" +serde = {version = "1.0.132", optional = true, features = ["derive"]} codec = {default-features = false, features = ["derive"], package = "parity-scale-codec", version = "2.3.1"} frame-support = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} @@ -63,6 +64,7 @@ runtime-benchmarks = [ "kilt-support/runtime-benchmarks", ] std = [ + "serde", "codec/std", "ctype/std", "frame-support/std", diff --git a/pallets/did/src/did_details.rs b/pallets/did/src/did_details.rs index 5b3f88126f..ed196bd7d9 100644 --- a/pallets/did/src/did_details.rs +++ b/pallets/did/src/did_details.rs @@ -37,6 +37,7 @@ use crate::{ /// Types of verification keys a DID can control. #[derive(Clone, Decode, Debug, Encode, Eq, Ord, PartialEq, PartialOrd, TypeInfo, MaxEncodedLen)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] pub enum DidVerificationKey { /// An Ed25519 public key. Ed25519(ed25519::Public), @@ -88,6 +89,7 @@ impl From for DidVerificationKey { /// Types of encryption keys a DID can control. #[derive(Clone, Copy, Decode, Debug, Encode, Eq, Ord, PartialEq, PartialOrd, TypeInfo, MaxEncodedLen)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] pub enum DidEncryptionKey { /// An X25519 public key. X25519([u8; 32]), @@ -95,6 +97,7 @@ pub enum DidEncryptionKey { /// A general public key under the control of the DID. #[derive(Clone, Decode, Debug, Encode, Eq, Ord, PartialEq, PartialOrd, TypeInfo, MaxEncodedLen)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] pub enum DidPublicKey { /// A verification key, used to generate and verify signatures. PublicVerificationKey(DidVerificationKey), @@ -232,6 +235,7 @@ impl> DidVerifiableIdentifier for I { /// attestation keys a DID might control. #[derive(Clone, Debug, Decode, Encode, PartialEq, Ord, PartialOrd, Eq, TypeInfo, MaxEncodedLen)] #[codec(mel_bound())] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] pub struct DidPublicKeyDetails { /// A public key the DID controls. pub key: DidPublicKey, @@ -247,16 +251,16 @@ pub struct DidPublicKeyDetails { pub struct DidDetails { /// The ID of the authentication key, used to authenticate DID-related /// operations. - pub(crate) authentication_key: KeyIdOf, + pub authentication_key: KeyIdOf, /// The set of the key agreement key IDs, which can be used to encrypt /// data addressed to the DID subject. - pub(crate) key_agreement_keys: DidKeyAgreementKeySet, + pub key_agreement_keys: DidKeyAgreementKeySet, /// \[OPTIONAL\] The ID of the delegation key, used to verify the /// signatures of the delegations created by the DID subject. - pub(crate) delegation_key: Option>, + pub delegation_key: Option>, /// \[OPTIONAL\] The ID of the attestation key, used to verify the /// signatures of the attestations created by the DID subject. - pub(crate) attestation_key: Option>, + pub attestation_key: Option>, /// The map of public keys, with the key label as /// the key map and the tuple (key, addition_block_number) as the map /// value. @@ -266,14 +270,14 @@ pub struct DidDetails { /// the old attestation keys that have been rotated, i.e., they cannot /// be used to create new attestations but can still be used to verify /// previously issued attestations. - pub(crate) public_keys: DidPublicKeyMap, + pub public_keys: DidPublicKeyMap, /// The counter used to avoid replay attacks, which is checked and /// updated upon each DID operation involving with the subject as the /// creator. - pub(crate) last_tx_counter: u64, + pub last_tx_counter: u64, /// The deposit that was taken to incentivise fair use of the on chain /// storage. - pub(crate) deposit: Deposit, BalanceOf>, + pub deposit: Deposit, BalanceOf>, } impl DidDetails { @@ -528,21 +532,11 @@ impl DidDetails { } /// Increase the tx counter of the DID. - pub fn increase_tx_counter(&mut self) { + pub fn increase_tx_counter(&mut self) -> u64 { // Since we have transaction mortality now, we can safely wrap nonces around. self.last_tx_counter = self.last_tx_counter.wrapping_add(1); - } - - /// Returns the last used tx counter for the DID. - pub fn get_tx_counter_value(&self) -> u64 { self.last_tx_counter } - - /// Set the DID tx counter to an arbitrary value. - #[cfg(any(feature = "mock", test))] - pub fn set_tx_counter(&mut self, value: u64) { - self.last_tx_counter = value; - } } pub(crate) type DidNewKeyAgreementKeySet = BoundedBTreeSet::MaxNewKeyAgreementKeys>; diff --git a/pallets/did/src/lib.rs b/pallets/did/src/lib.rs index 883f5858c6..636f1cecf9 100644 --- a/pallets/did/src/lib.rs +++ b/pallets/did/src/lib.rs @@ -178,8 +178,8 @@ pub mod pallet { #[pallet::origin] pub type Origin = DidRawOrigin, AccountIdOf>; + pub type BalanceOf = as Currency>>::Balance; pub(crate) type CurrencyOf = ::Currency; - pub(crate) type BalanceOf = as Currency>>::Balance; pub(crate) type NegativeImbalanceOf = <::Currency as Currency>>::NegativeImbalance; #[pallet::config] @@ -1132,7 +1132,7 @@ pub mod pallet { fn validate_counter_value(counter: u64, did_details: &DidDetails) -> Result<(), DidError> { // Verify that the operation counter is equal to the stored one + 1, // possibly wrapping around when u64::MAX is reached. - let expected_nonce_value = did_details.get_tx_counter_value().wrapping_add(1); + let expected_nonce_value = did_details.last_tx_counter.wrapping_add(1); ensure!( counter == expected_nonce_value, DidError::SignatureError(SignatureError::InvalidNonce) diff --git a/rpc/did/runtime-api/Cargo.toml b/rpc/did/runtime-api/Cargo.toml index 54cdd33b91..cf1ebfa85d 100644 --- a/rpc/did/runtime-api/Cargo.toml +++ b/rpc/did/runtime-api/Cargo.toml @@ -15,6 +15,7 @@ sp-runtime = {git = "https://github.com/paritytech/substrate", default-features sp-std = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} did = {path = "../../../pallets/did", default-features = false} +kilt-support = {path = "../../../support", default-features = false} [features] default = ["std"] @@ -26,4 +27,5 @@ std = [ "sp-std/std", "scale-info/std", "did/std", + "kilt-support/std", ] diff --git a/rpc/did/runtime-api/src/did_details.rs b/rpc/did/runtime-api/src/did_details.rs new file mode 100644 index 0000000000..ec1cb1d810 --- /dev/null +++ b/rpc/did/runtime-api/src/did_details.rs @@ -0,0 +1,52 @@ +// KILT Blockchain – https://botlabs.org +// Copyright (C) 2019-2022 BOTLabs GmbH + +// The KILT Blockchain 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. + +// The KILT Blockchain 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 this program. If not, see . + +// If you feel like getting in touch with us, you can do so at info@botlabs.org + +use codec::{Decode, Encode, MaxEncodedLen}; +use scale_info::TypeInfo; +use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet}; + +use did::{did_details::DidPublicKeyDetails, AccountIdOf, BalanceOf, BlockNumberOf, KeyIdOf}; +use kilt_support::deposit::Deposit; + +#[derive(Encode, Decode, TypeInfo, Clone, Debug, PartialEq)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub struct DidDetails { + pub authentication_key: Key, + pub key_agreement_keys: BTreeSet, + pub delegation_key: Option, + pub attestation_key: Option, + pub public_keys: BTreeMap>, + pub last_tx_counter: u64, + pub deposit: Deposit, +} + +impl From> + for DidDetails, BlockNumberOf, AccountIdOf, BalanceOf> +{ + fn from(did_details: did::did_details::DidDetails) -> Self { + Self { + authentication_key: did_details.authentication_key, + key_agreement_keys: did_details.key_agreement_keys.into(), + delegation_key: did_details.delegation_key.into(), + attestation_key: did_details.attestation_key.into(), + public_keys: did_details.public_keys.into(), + last_tx_counter: did_details.last_tx_counter, + deposit: did_details.deposit, + } + } +} diff --git a/rpc/did/runtime-api/src/lib.rs b/rpc/did/runtime-api/src/lib.rs index 5d0109d70a..9978c33a3d 100644 --- a/rpc/did/runtime-api/src/lib.rs +++ b/rpc/did/runtime-api/src/lib.rs @@ -17,62 +17,45 @@ // If you feel like getting in touch with us, you can do so at info@botlabs.org #![cfg_attr(not(feature = "std"), no_std)] -use codec::{Codec, Decode, Encode}; +use codec::{Codec, Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_std::vec::Vec; -#[derive(Encode, Decode, TypeInfo, PartialEq)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -pub struct ServiceEndpoint { - pub id: Id, - pub service_types: Vec, - pub urls: Vec, -} +mod did_details; +mod service_endpoint; -impl From> for ServiceEndpoint, Vec, Vec> { - fn from(runtime_endpoint: did::service_endpoints::DidEndpoint) -> Self { - ServiceEndpoint { - id: runtime_endpoint.id.into_inner(), - service_types: runtime_endpoint - .service_types - .into_inner() - .into_iter() - .map(|v| v.into_inner()) - .collect(), - urls: runtime_endpoint - .urls - .into_inner() - .into_iter() - .map(|v| v.into_inner()) - .collect(), - } - } -} +pub use did_details::*; +pub use service_endpoint::*; #[derive(Encode, Decode, TypeInfo, PartialEq)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -pub struct DidDocument { +pub struct DidDocument +{ pub identifier: DidIdentifier, pub accounts: Vec, pub w3n: Option, pub service_endpoints: Vec>, + pub details: DidDetails, } /// The DidDocument with a Web3Name represented as a byte array. /// /// This will be returned by the runtime and processed by the client side RPC /// implementation. -pub type RawDidDocument = - DidDocument, Vec, Vec, Vec>; +pub type RawDidDocument = + DidDocument, Vec, Vec, Vec, Balance, Key, BlockNumber>; sp_api::decl_runtime_apis! { /// The API to query account nonce (aka transaction index). - pub trait DidApi where + pub trait DidApi where DidIdentifier: Codec, AccountId: Codec, + BlockNumber: Codec + MaxEncodedLen, + Key: Codec, + Balance: Codec, { - fn query_did_by_w3n(name: Vec) -> Option>; - fn query_did_by_account_id(account: AccountId) -> Option>; - fn query_did(did: DidIdentifier) -> Option>; + fn query_did_by_w3n(name: Vec) -> Option>; + fn query_did_by_account_id(account: AccountId) -> Option>; + fn query_did(did: DidIdentifier) -> Option>; } } diff --git a/rpc/did/runtime-api/src/service_endpoint.rs b/rpc/did/runtime-api/src/service_endpoint.rs new file mode 100644 index 0000000000..6e47cbab2a --- /dev/null +++ b/rpc/did/runtime-api/src/service_endpoint.rs @@ -0,0 +1,48 @@ +// KILT Blockchain – https://botlabs.org +// Copyright (C) 2019-2022 BOTLabs GmbH + +// The KILT Blockchain 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. + +// The KILT Blockchain 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 this program. If not, see . + +// If you feel like getting in touch with us, you can do so at info@botlabs.org +use codec::{Decode, Encode}; +use scale_info::TypeInfo; +use sp_std::vec::Vec; + +#[derive(Encode, Decode, TypeInfo, PartialEq)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub struct ServiceEndpoint { + pub id: Id, + pub service_types: Vec, + pub urls: Vec, +} + +impl From> for ServiceEndpoint, Vec, Vec> { + fn from(runtime_endpoint: did::service_endpoints::DidEndpoint) -> Self { + ServiceEndpoint { + id: runtime_endpoint.id.into_inner(), + service_types: runtime_endpoint + .service_types + .into_inner() + .into_iter() + .map(|v| v.into_inner()) + .collect(), + urls: runtime_endpoint + .urls + .into_inner() + .into_iter() + .map(|v| v.into_inner()) + .collect(), + } + } +} diff --git a/rpc/did/src/lib.rs b/rpc/did/src/lib.rs index 8516dda35f..6f3c93783c 100644 --- a/rpc/did/src/lib.rs +++ b/rpc/did/src/lib.rs @@ -18,7 +18,7 @@ use std::sync::Arc; -use codec::Codec; +use codec::{Codec, MaxEncodedLen}; use did_rpc_runtime_api::{DidDocument, ServiceEndpoint}; use jsonrpc_core::{Error as RpcError, ErrorCode, Result}; use jsonrpc_derive::rpc; @@ -28,8 +28,8 @@ use sp_runtime::{generic::BlockId, traits::Block as BlockT}; pub use did_rpc_runtime_api::DidApi as DidRuntimeApi; -pub type RpcDidDocument = - DidDocument; +pub type RpcDidDocument = + DidDocument; fn raw_did_endpoint_to_rpc( raw: ServiceEndpoint, Vec, Vec>, @@ -50,27 +50,31 @@ fn raw_did_endpoint_to_rpc( } #[rpc] -pub trait DidApi { +pub trait DidApi +where + BlockNumber: MaxEncodedLen, + Key: Ord, +{ #[rpc(name = "did_queryByWeb3Name")] fn query_did_by_w3n( &self, web3name: String, at: Option, - ) -> Result>>; + ) -> Result>>; #[rpc(name = "did_queryByAccount")] fn query_did_by_account_id( &self, account: AccountId, at: Option, - ) -> Result>>; + ) -> Result>>; #[rpc(name = "did_query")] fn query_did( &self, account: DidIdentifier, at: Option, - ) -> Result>>; + ) -> Result>>; } /// A struct that implements the [`TransactionPaymentApi`]. @@ -106,20 +110,23 @@ impl From for i64 { } } -impl DidApi<::Hash, DidIdentifier, AccountId> - for DidQuery +impl + DidApi<::Hash, DidIdentifier, AccountId, Balance, Key, BlockNumber> for DidQuery where AccountId: Codec + std::marker::Send, DidIdentifier: Codec + std::marker::Send, + Key: Codec + Ord, + Balance: Codec, + BlockNumber: Codec + MaxEncodedLen, Block: BlockT, C: 'static + ProvideRuntimeApi + HeaderBackend, - C::Api: DidRuntimeApi, + C::Api: DidRuntimeApi, { fn query_did_by_w3n( &self, web3name: String, at: Option<::Hash>, - ) -> Result>> { + ) -> Result>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. @@ -142,6 +149,7 @@ where .into_iter() .filter_map(raw_did_endpoint_to_rpc) .collect(), + details: doc.details, })), } } @@ -150,7 +158,7 @@ where &self, account: AccountId, at: Option<::Hash>, - ) -> Result>> { + ) -> Result>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. @@ -173,6 +181,7 @@ where .into_iter() .filter_map(raw_did_endpoint_to_rpc) .collect(), + details: doc.details, })), } } @@ -181,7 +190,7 @@ where &self, did: DidIdentifier, at: Option<::Hash>, - ) -> Result>> { + ) -> Result>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. @@ -204,6 +213,7 @@ where .into_iter() .filter_map(raw_did_endpoint_to_rpc) .collect(), + details: doc.details, })), } } diff --git a/runtimes/peregrine/src/lib.rs b/runtimes/peregrine/src/lib.rs index 5c12915359..7c2cb9175f 100644 --- a/runtimes/peregrine/src/lib.rs +++ b/runtimes/peregrine/src/lib.rs @@ -1107,12 +1107,25 @@ impl_runtime_apis! { impl did_rpc_runtime_api::DidApi< Block, DidIdentifier, - AccountId + AccountId, + Balance, + Hash, + BlockNumber > for Runtime { - fn query_did_by_w3n(name: Vec) -> Option> { + fn query_did_by_w3n(name: Vec) -> Option + > { let name: Web3Name = name.try_into().ok()?; pallet_web3_names::Owner::::get(&name) - .map(|owner_info| { + .and_then(|owner_info| { + did::Did::::get(&owner_info.owner).map(|details| (owner_info, details)) + }) + .map(|(owner_info, details)| { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&owner_info.owner).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e|From::from(e.1)).collect(); @@ -1121,26 +1134,49 @@ impl_runtime_apis! { w3n: Some(name.into()), accounts, service_endpoints, + details: details.into(), } }) } - fn query_did_by_account_id(account: AccountId) -> Option> { - pallet_did_lookup::ConnectedDids::::get(account).map(|connection_record| { - let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); - let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); - let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); - - did_rpc_runtime_api::RawDidDocument { - identifier: connection_record.did, - w3n, - accounts, - service_endpoints, - } - }) + fn query_did_by_account_id(account: AccountId) -> Option< + did_rpc_runtime_api::RawDidDocument< + DidIdentifier, + AccountId, + Balance, + Hash, + BlockNumber + > + > { + pallet_did_lookup::ConnectedDids::::get(account) + .and_then(|owner_info| { + did::Did::::get(&owner_info.did).map(|details| (owner_info, details)) + }) + .map(|(connection_record, details)| { + let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); + let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); + + did_rpc_runtime_api::RawDidDocument { + identifier: connection_record.did, + w3n, + accounts, + service_endpoints, + details: details.into(), + } + }) } - fn query_did(did: DidIdentifier) -> Option> { + fn query_did(did: DidIdentifier) -> Option< + did_rpc_runtime_api::RawDidDocument< + DidIdentifier, + AccountId, + Balance, + Hash, + BlockNumber + > + > { + let details = did::Did::::get(&did)?; let w3n = pallet_web3_names::Names::::get(&did).map(Into::into); let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&did).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e|From::from(e.1)).collect(); @@ -1150,6 +1186,7 @@ impl_runtime_apis! { w3n, accounts, service_endpoints, + details: details.into(), }) } } diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index 8688aee2a2..6e5b6337c9 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -1110,12 +1110,25 @@ impl_runtime_apis! { impl did_rpc_runtime_api::DidApi< Block, DidIdentifier, - AccountId + AccountId, + Balance, + Hash, + BlockNumber > for Runtime { - fn query_did_by_w3n(name: Vec) -> Option> { + fn query_did_by_w3n(name: Vec) -> Option + > { let name: Web3Name = name.try_into().ok()?; pallet_web3_names::Owner::::get(&name) - .map(|owner_info| { + .and_then(|owner_info| { + did::Did::::get(&owner_info.owner).map(|details| (owner_info, details)) + }) + .map(|(owner_info, details)| { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&owner_info.owner).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e|From::from(e.1)).collect(); @@ -1124,26 +1137,49 @@ impl_runtime_apis! { w3n: Some(name.into()), accounts, service_endpoints, + details: details.into(), } }) } - fn query_did_by_account_id(account: AccountId) -> Option> { - pallet_did_lookup::ConnectedDids::::get(account).map(|connection_record| { - let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); - let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); - let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); - - did_rpc_runtime_api::RawDidDocument { - identifier: connection_record.did, - w3n, - accounts, - service_endpoints, - } - }) + fn query_did_by_account_id(account: AccountId) -> Option< + did_rpc_runtime_api::RawDidDocument< + DidIdentifier, + AccountId, + Balance, + Hash, + BlockNumber + > + > { + pallet_did_lookup::ConnectedDids::::get(account) + .and_then(|owner_info| { + did::Did::::get(&owner_info.did).map(|details| (owner_info, details)) + }) + .map(|(connection_record, details)| { + let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); + let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); + + did_rpc_runtime_api::RawDidDocument { + identifier: connection_record.did, + w3n, + accounts, + service_endpoints, + details: details.into(), + } + }) } - fn query_did(did: DidIdentifier) -> Option> { + fn query_did(did: DidIdentifier) -> Option< + did_rpc_runtime_api::RawDidDocument< + DidIdentifier, + AccountId, + Balance, + Hash, + BlockNumber + > + > { + let details = did::Did::::get(&did)?; let w3n = pallet_web3_names::Names::::get(&did).map(Into::into); let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&did).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e|From::from(e.1)).collect(); @@ -1153,6 +1189,7 @@ impl_runtime_apis! { w3n, accounts, service_endpoints, + details: details.into(), }) } } diff --git a/runtimes/standalone/src/lib.rs b/runtimes/standalone/src/lib.rs index 9e502b4ecc..b868630bd1 100644 --- a/runtimes/standalone/src/lib.rs +++ b/runtimes/standalone/src/lib.rs @@ -906,12 +906,25 @@ impl_runtime_apis! { impl did_rpc_runtime_api::DidApi< Block, DidIdentifier, - AccountId + AccountId, + Balance, + Hash, + BlockNumber > for Runtime { - fn query_did_by_w3n(name: Vec) -> Option> { + fn query_did_by_w3n(name: Vec) -> Option + > { let name: Web3Name = name.try_into().ok()?; pallet_web3_names::Owner::::get(&name) - .map(|owner_info| { + .and_then(|owner_info| { + did::Did::::get(&owner_info.owner).map(|details| (owner_info, details)) + }) + .map(|(owner_info, details)| { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&owner_info.owner).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e|From::from(e.1)).collect(); @@ -920,26 +933,49 @@ impl_runtime_apis! { w3n: Some(name.into()), accounts, service_endpoints, + details: details.into(), } }) } - fn query_did_by_account_id(account: AccountId) -> Option> { - pallet_did_lookup::ConnectedDids::::get(account).map(|connection_record| { - let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); - let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); - let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); - - did_rpc_runtime_api::RawDidDocument { - identifier: connection_record.did, - w3n, - accounts, - service_endpoints, - } - }) + fn query_did_by_account_id(account: AccountId) -> Option< + did_rpc_runtime_api::RawDidDocument< + DidIdentifier, + AccountId, + Balance, + Hash, + BlockNumber + > + > { + pallet_did_lookup::ConnectedDids::::get(account) + .and_then(|owner_info| { + did::Did::::get(&owner_info.did).map(|details| (owner_info, details)) + }) + .map(|(connection_record, details)| { + let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); + let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); + + did_rpc_runtime_api::RawDidDocument { + identifier: connection_record.did, + w3n, + accounts, + service_endpoints, + details: details.into(), + } + }) } - fn query_did(did: DidIdentifier) -> Option> { + fn query_did(did: DidIdentifier) -> Option< + did_rpc_runtime_api::RawDidDocument< + DidIdentifier, + AccountId, + Balance, + Hash, + BlockNumber + > + > { + let details = did::Did::::get(&did)?; let w3n = pallet_web3_names::Names::::get(&did).map(Into::into); let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&did).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e|From::from(e.1)).collect(); @@ -949,6 +985,7 @@ impl_runtime_apis! { w3n, accounts, service_endpoints, + details: details.into(), }) } } diff --git a/support/Cargo.toml b/support/Cargo.toml index e639e89d49..25a12da7e5 100644 --- a/support/Cargo.toml +++ b/support/Cargo.toml @@ -9,6 +9,8 @@ version = "1.6.2" [dependencies] codec = {default-features = false, features = ["derive"], package = "parity-scale-codec", version = "2.3.1"} scale-info = {version = "1.0", default-features = false, features = ["derive"]} +serde = {version = "1.0.132", optional = true, features = ["derive"]} + frame-support = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} frame-system = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} @@ -28,6 +30,7 @@ runtime-benchmarks = [ "frame-system/runtime-benchmarks", ] std = [ + "serde", "codec/std", "frame-support/std", "frame-system/std", diff --git a/support/src/deposit.rs b/support/src/deposit.rs index a36a96e203..f113f8ee84 100644 --- a/support/src/deposit.rs +++ b/support/src/deposit.rs @@ -20,6 +20,7 @@ use scale_info::TypeInfo; /// An amount of balance reserved by the specified address. #[derive(Clone, Debug, Encode, Decode, PartialEq, TypeInfo, MaxEncodedLen)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] pub struct Deposit { pub owner: Account, pub amount: Balance, From 1dea6a245724cc7ceefdc08d951e46f4ee62e641 Mon Sep 17 00:00:00 2001 From: weichweich Date: Wed, 27 Apr 2022 14:20:00 +0200 Subject: [PATCH 20/31] fix: u128 not supported by serde --- rpc/did/runtime-api/src/did_details.rs | 18 +++++++++++++++++- rpc/did/runtime-api/src/lib.rs | 26 ++++++++++++++++++++++++++ rpc/did/src/lib.rs | 5 +++-- support/src/deposit.rs | 25 +++++++++++++++++++++++-- 4 files changed, 69 insertions(+), 5 deletions(-) diff --git a/rpc/did/runtime-api/src/did_details.rs b/rpc/did/runtime-api/src/did_details.rs index ec1cb1d810..227c10983c 100644 --- a/rpc/did/runtime-api/src/did_details.rs +++ b/rpc/did/runtime-api/src/did_details.rs @@ -16,15 +16,31 @@ // If you feel like getting in touch with us, you can do so at info@botlabs.org +#[cfg(feature = "std")] +use serde::{Deserialize, Serialize}; + use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet}; + use did::{did_details::DidPublicKeyDetails, AccountIdOf, BalanceOf, BlockNumberOf, KeyIdOf}; use kilt_support::deposit::Deposit; #[derive(Encode, Decode, TypeInfo, Clone, Debug, PartialEq)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "std", serde(bound( + serialize = " + Balance: std::fmt::Display, + AccountId: Serialize, + Key: Serialize, + BlockNumber: Serialize", + deserialize = " + Balance: std::str::FromStr, + AccountId: Deserialize<'de>, + Key: Deserialize<'de>, + BlockNumber: Deserialize<'de>" +)))] pub struct DidDetails { pub authentication_key: Key, pub key_agreement_keys: BTreeSet, diff --git a/rpc/did/runtime-api/src/lib.rs b/rpc/did/runtime-api/src/lib.rs index 9978c33a3d..d3f8d836e9 100644 --- a/rpc/did/runtime-api/src/lib.rs +++ b/rpc/did/runtime-api/src/lib.rs @@ -17,6 +17,10 @@ // If you feel like getting in touch with us, you can do so at info@botlabs.org #![cfg_attr(not(feature = "std"), no_std)] + +#[cfg(feature = "std")] +use serde::{Deserialize, Serialize}; + use codec::{Codec, Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_std::vec::Vec; @@ -29,6 +33,28 @@ pub use service_endpoint::*; #[derive(Encode, Decode, TypeInfo, PartialEq)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "std", serde(bound( + serialize = " + Balance: std::fmt::Display, + AccountId: Serialize, + Key: Serialize, + BlockNumber: Serialize, + DidIdentifier: Serialize, + Type: Serialize, + Url: Serialize, + Id: Serialize, + Web3Name: Serialize,", + deserialize = " + Balance: std::str::FromStr, + AccountId: Deserialize<'de>, + Key: Deserialize<'de>, + BlockNumber: Deserialize<'de>, + DidIdentifier: Deserialize<'de>, + Type: Deserialize<'de>, + Url: Deserialize<'de>, + Id: Deserialize<'de>, + Web3Name: Deserialize<'de>," +)))] pub struct DidDocument { pub identifier: DidIdentifier, diff --git a/rpc/did/src/lib.rs b/rpc/did/src/lib.rs index 6f3c93783c..d5af8ef2d4 100644 --- a/rpc/did/src/lib.rs +++ b/rpc/did/src/lib.rs @@ -16,7 +16,7 @@ // If you feel like getting in touch with us, you can do so at info@botlabs.org -use std::sync::Arc; +use std::{fmt::Display, str::FromStr, sync::Arc}; use codec::{Codec, MaxEncodedLen}; use did_rpc_runtime_api::{DidDocument, ServiceEndpoint}; @@ -54,6 +54,7 @@ pub trait DidApi where BlockNumber: MaxEncodedLen, Key: Ord, + Balance: FromStr + Display, { #[rpc(name = "did_queryByWeb3Name")] fn query_did_by_w3n( @@ -116,7 +117,7 @@ where AccountId: Codec + std::marker::Send, DidIdentifier: Codec + std::marker::Send, Key: Codec + Ord, - Balance: Codec, + Balance: Codec + FromStr + Display, BlockNumber: Codec + MaxEncodedLen, Block: BlockT, C: 'static + ProvideRuntimeApi + HeaderBackend, diff --git a/support/src/deposit.rs b/support/src/deposit.rs index f113f8ee84..4da488a9bb 100644 --- a/support/src/deposit.rs +++ b/support/src/deposit.rs @@ -13,15 +13,36 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . - // If you feel like getting in touch with us, you can do so at info@botlabs.org + use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; +#[cfg(feature = "std")] +use serde::{Deserialize, Serialize}; + /// An amount of balance reserved by the specified address. #[derive(Clone, Debug, Encode, Decode, PartialEq, TypeInfo, MaxEncodedLen)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "std", serde(bound(serialize = "Balance: std::fmt::Display, Account: Serialize")))] +#[cfg_attr(feature = "std", serde(bound(deserialize = "Balance: std::str::FromStr, Account: Deserialize<'de>")))] pub struct Deposit { pub owner: Account, + #[cfg_attr(feature = "std", serde(with = "serde_balance"))] pub amount: Balance, } + +#[cfg(feature = "std")] +mod serde_balance { + use serde::{Deserialize, Deserializer, Serializer}; + + pub fn serialize(t: &T, serializer: S) -> Result { + serializer.serialize_str(&t.to_string()) + } + + pub fn deserialize<'de, D: Deserializer<'de>, T: std::str::FromStr>(deserializer: D) -> Result { + let s = String::deserialize(deserializer)?; + s.parse::() + .map_err(|_| serde::de::Error::custom("Parse from string failed")) + } +} From 5b8123a74fdb48918b954034c793b606f7bceec8 Mon Sep 17 00:00:00 2001 From: weichweich Date: Wed, 27 Apr 2022 14:36:15 +0200 Subject: [PATCH 21/31] fix: clippy & tests --- nodes/parachain/src/rpc.rs | 2 +- pallets/did/src/tests.rs | 16 ++++++++-------- rpc/did/runtime-api/src/did_details.rs | 16 +++++++++------- rpc/did/runtime-api/src/lib.rs | 12 +++++++----- rpc/did/src/lib.rs | 9 ++++++--- support/src/deposit.rs | 17 ++++++++++++++--- 6 files changed, 45 insertions(+), 27 deletions(-) diff --git a/nodes/parachain/src/rpc.rs b/nodes/parachain/src/rpc.rs index 4940cc6845..c0f5c18638 100644 --- a/nodes/parachain/src/rpc.rs +++ b/nodes/parachain/src/rpc.rs @@ -29,7 +29,7 @@ use did_rpc::{DidApi, DidQuery}; use frame_rpc_system::{FullSystem, SystemApi}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; use polkadot_service::AuxStore; -use runtime_common::{AccountId, Balance, Block, DidIdentifier, Index, BlockNumber, Hash}; +use runtime_common::{AccountId, Balance, Block, BlockNumber, DidIdentifier, Hash, Index}; use sc_service::Error; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; diff --git a/pallets/did/src/tests.rs b/pallets/did/src/tests.rs index 0311e82947..d90dedfab4 100644 --- a/pallets/did/src/tests.rs +++ b/pallets/did/src/tests.rs @@ -2872,8 +2872,8 @@ fn check_authentication_successful_operation_verification() { // Verify that the DID tx counter has increased let did_details = Did::get_did(&call_operation.operation.did).expect("DID should be present on chain."); assert_eq!( - did_details.get_tx_counter_value(), - mock_did.get_tx_counter_value() + 1u64 + did_details.last_tx_counter, + mock_did.last_tx_counter + 1u64 ); }); } @@ -2902,8 +2902,8 @@ fn check_attestation_successful_operation_verification() { // Verify that the DID tx counter has increased let did_details = Did::get_did(&call_operation.operation.did).expect("DID should be present on chain."); assert_eq!( - did_details.get_tx_counter_value(), - mock_did.get_tx_counter_value() + 1u64 + did_details.last_tx_counter, + mock_did.last_tx_counter + 1u64 ); }); } @@ -2935,8 +2935,8 @@ fn check_delegation_successful_operation_verification() { // Verify that the DID tx counter has increased let did_details = Did::get_did(&call_operation.operation.did).expect("DID should be present on chain."); assert_eq!( - did_details.get_tx_counter_value(), - mock_did.get_tx_counter_value() + 1u64 + did_details.last_tx_counter, + mock_did.last_tx_counter + 1u64 ); }); } @@ -2966,7 +2966,7 @@ fn check_tx_counter_wrap_operation_verification() { let did = get_did_identifier_from_sr25519_key(auth_key.public()); let mut mock_did = generate_base_did_details::(DidVerificationKey::from(auth_key.public())); - mock_did.set_tx_counter(u64::MAX); + mock_did.last_tx_counter = u64::MAX; let mut call_operation = generate_test_did_call(DidVerificationKeyRelationship::Authentication, did.clone(), ACCOUNT_00); @@ -2984,7 +2984,7 @@ fn check_tx_counter_wrap_operation_verification() { )); // Verify that the DID tx counter has wrapped around let did_details = Did::get_did(&call_operation.operation.did).expect("DID should be present on chain."); - assert_eq!(did_details.get_tx_counter_value(), 0u64); + assert_eq!(did_details.last_tx_counter, 0u64); }); } diff --git a/rpc/did/runtime-api/src/did_details.rs b/rpc/did/runtime-api/src/did_details.rs index 227c10983c..e4e0972650 100644 --- a/rpc/did/runtime-api/src/did_details.rs +++ b/rpc/did/runtime-api/src/did_details.rs @@ -23,24 +23,26 @@ use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet}; - use did::{did_details::DidPublicKeyDetails, AccountIdOf, BalanceOf, BlockNumberOf, KeyIdOf}; use kilt_support::deposit::Deposit; #[derive(Encode, Decode, TypeInfo, Clone, Debug, PartialEq)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -#[cfg_attr(feature = "std", serde(bound( - serialize = " +#[cfg_attr( + feature = "std", + serde(bound( + serialize = " Balance: std::fmt::Display, AccountId: Serialize, Key: Serialize, BlockNumber: Serialize", - deserialize = " + deserialize = " Balance: std::str::FromStr, AccountId: Deserialize<'de>, Key: Deserialize<'de>, BlockNumber: Deserialize<'de>" -)))] + )) +)] pub struct DidDetails { pub authentication_key: Key, pub key_agreement_keys: BTreeSet, @@ -58,8 +60,8 @@ impl From> Self { authentication_key: did_details.authentication_key, key_agreement_keys: did_details.key_agreement_keys.into(), - delegation_key: did_details.delegation_key.into(), - attestation_key: did_details.attestation_key.into(), + delegation_key: did_details.delegation_key, + attestation_key: did_details.attestation_key, public_keys: did_details.public_keys.into(), last_tx_counter: did_details.last_tx_counter, deposit: did_details.deposit, diff --git a/rpc/did/runtime-api/src/lib.rs b/rpc/did/runtime-api/src/lib.rs index d3f8d836e9..602ba804a4 100644 --- a/rpc/did/runtime-api/src/lib.rs +++ b/rpc/did/runtime-api/src/lib.rs @@ -17,7 +17,6 @@ // If you feel like getting in touch with us, you can do so at info@botlabs.org #![cfg_attr(not(feature = "std"), no_std)] - #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; @@ -33,8 +32,10 @@ pub use service_endpoint::*; #[derive(Encode, Decode, TypeInfo, PartialEq)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "std", serde(bound( - serialize = " +#[cfg_attr( + feature = "std", + serde(bound( + serialize = " Balance: std::fmt::Display, AccountId: Serialize, Key: Serialize, @@ -44,7 +45,7 @@ pub use service_endpoint::*; Url: Serialize, Id: Serialize, Web3Name: Serialize,", - deserialize = " + deserialize = " Balance: std::str::FromStr, AccountId: Deserialize<'de>, Key: Deserialize<'de>, @@ -54,7 +55,8 @@ pub use service_endpoint::*; Url: Deserialize<'de>, Id: Deserialize<'de>, Web3Name: Deserialize<'de>," -)))] + )) +)] pub struct DidDocument { pub identifier: DidIdentifier, diff --git a/rpc/did/src/lib.rs b/rpc/did/src/lib.rs index d5af8ef2d4..5c40eaf8e2 100644 --- a/rpc/did/src/lib.rs +++ b/rpc/did/src/lib.rs @@ -49,6 +49,9 @@ fn raw_did_endpoint_to_rpc( }) } +pub type DidRpcResponse = + Option>; + #[rpc] pub trait DidApi where @@ -61,21 +64,21 @@ where &self, web3name: String, at: Option, - ) -> Result>>; + ) -> Result>; #[rpc(name = "did_queryByAccount")] fn query_did_by_account_id( &self, account: AccountId, at: Option, - ) -> Result>>; + ) -> Result>; #[rpc(name = "did_query")] fn query_did( &self, account: DidIdentifier, at: Option, - ) -> Result>>; + ) -> Result>; } /// A struct that implements the [`TransactionPaymentApi`]. diff --git a/support/src/deposit.rs b/support/src/deposit.rs index 4da488a9bb..cb6ecb46ad 100644 --- a/support/src/deposit.rs +++ b/support/src/deposit.rs @@ -13,6 +13,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . + // If you feel like getting in touch with us, you can do so at info@botlabs.org use codec::{Decode, Encode, MaxEncodedLen}; @@ -20,18 +21,28 @@ use scale_info::TypeInfo; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; - /// An amount of balance reserved by the specified address. #[derive(Clone, Debug, Encode, Decode, PartialEq, TypeInfo, MaxEncodedLen)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -#[cfg_attr(feature = "std", serde(bound(serialize = "Balance: std::fmt::Display, Account: Serialize")))] -#[cfg_attr(feature = "std", serde(bound(deserialize = "Balance: std::str::FromStr, Account: Deserialize<'de>")))] +#[cfg_attr( + feature = "std", + serde(bound( + serialize = " + Balance: std::fmt::Display, + Account: Serialize", + deserialize = " + Balance: std::str::FromStr, + Account: Deserialize<'de>" + )) +)] pub struct Deposit { pub owner: Account, #[cfg_attr(feature = "std", serde(with = "serde_balance"))] pub amount: Balance, } +// This code was copied from https://github.com/paritytech/substrate/blob/ded44948e2d5a398abcb4e342b0513cb690961bb/frame/transaction-payment/src/types.rs#L113 +// It is needed because u128 cannot be serialized by serde out of the box. #[cfg(feature = "std")] mod serde_balance { use serde::{Deserialize, Deserializer, Serializer}; From 8ae429c2a03589b17fc30448ee82c220ce7e0a1a Mon Sep 17 00:00:00 2001 From: weichweich Date: Wed, 27 Apr 2022 14:50:52 +0200 Subject: [PATCH 22/31] test: test u128 serde fix --- Cargo.lock | 1 + support/Cargo.toml | 3 +++ support/src/deposit.rs | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 4434f312d2..8ffe47e8f3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3633,6 +3633,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", + "serde_json", "sp-core", "sp-runtime", "sp-std", diff --git a/support/Cargo.toml b/support/Cargo.toml index 25a12da7e5..dae3091525 100644 --- a/support/Cargo.toml +++ b/support/Cargo.toml @@ -18,6 +18,9 @@ sp-core = {branch = "polkadot-v0.9.17", default-features = false, git = "https:/ sp-runtime = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} sp-std = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} +[dev-dependencies] +serde_json = "1.0.74" + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/support/src/deposit.rs b/support/src/deposit.rs index cb6ecb46ad..836898ab76 100644 --- a/support/src/deposit.rs +++ b/support/src/deposit.rs @@ -57,3 +57,40 @@ mod serde_balance { .map_err(|_| serde::de::Error::custom("Parse from string failed")) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn should_serialize_and_deserialize_properly_with_string() { + let deposit = Deposit { + owner: 0_u8, + amount: 1_000_000_u128, + }; + + let json_str = r#"{"owner":0,"amount":"1000000"}"#; + + assert_eq!(serde_json::to_string(&deposit).unwrap(), json_str); + assert_eq!(serde_json::from_str::>(json_str).unwrap(), deposit); + + // should not panic + serde_json::to_value(&deposit).unwrap(); + } + + #[test] + fn should_serialize_and_deserialize_properly_large_value() { + let deposit = Deposit { + owner: 0_u8, + amount: 1_000_000_u128, + }; + + let json_str = r#"{"owner":0,"amount":"1000000"}"#; + + assert_eq!(serde_json::to_string(&deposit).unwrap(), json_str); + assert_eq!(serde_json::from_str::>(json_str).unwrap(), deposit); + + // should not panic + serde_json::to_value(&deposit).unwrap(); + } +} From 11c90c03d47617b8e6229fd9bd7c19cdb89e95fd Mon Sep 17 00:00:00 2001 From: weichweich Date: Wed, 27 Apr 2022 15:32:10 +0200 Subject: [PATCH 23/31] fmt --- pallets/did/src/tests.rs | 15 +++------------ rpc/did/runtime-api/src/lib.rs | 18 ++++++++++++++++++ rpc/did/src/lib.rs | 18 ++++++++++++++++++ 3 files changed, 39 insertions(+), 12 deletions(-) diff --git a/pallets/did/src/tests.rs b/pallets/did/src/tests.rs index d90dedfab4..fb4b4fcb65 100644 --- a/pallets/did/src/tests.rs +++ b/pallets/did/src/tests.rs @@ -2871,10 +2871,7 @@ fn check_authentication_successful_operation_verification() { )); // Verify that the DID tx counter has increased let did_details = Did::get_did(&call_operation.operation.did).expect("DID should be present on chain."); - assert_eq!( - did_details.last_tx_counter, - mock_did.last_tx_counter + 1u64 - ); + assert_eq!(did_details.last_tx_counter, mock_did.last_tx_counter + 1u64); }); } @@ -2901,10 +2898,7 @@ fn check_attestation_successful_operation_verification() { )); // Verify that the DID tx counter has increased let did_details = Did::get_did(&call_operation.operation.did).expect("DID should be present on chain."); - assert_eq!( - did_details.last_tx_counter, - mock_did.last_tx_counter + 1u64 - ); + assert_eq!(did_details.last_tx_counter, mock_did.last_tx_counter + 1u64); }); } @@ -2934,10 +2928,7 @@ fn check_delegation_successful_operation_verification() { )); // Verify that the DID tx counter has increased let did_details = Did::get_did(&call_operation.operation.did).expect("DID should be present on chain."); - assert_eq!( - did_details.last_tx_counter, - mock_did.last_tx_counter + 1u64 - ); + assert_eq!(did_details.last_tx_counter, mock_did.last_tx_counter + 1u64); }); } diff --git a/rpc/did/runtime-api/src/lib.rs b/rpc/did/runtime-api/src/lib.rs index 602ba804a4..8a903643e1 100644 --- a/rpc/did/runtime-api/src/lib.rs +++ b/rpc/did/runtime-api/src/lib.rs @@ -82,8 +82,26 @@ sp_api::decl_runtime_apis! { Key: Codec, Balance: Codec, { + /// Given a web3name this returns: + /// * the DID + /// * public keys stored for the did + /// * the web3name (optional) + /// * associated accounts + /// * service endpoints fn query_did_by_w3n(name: Vec) -> Option>; + /// Given an account address this returns: + /// * the DID + /// * public keys stored for the did + /// * the web3name (optional) + /// * associated accounts + /// * service endpoints fn query_did_by_account_id(account: AccountId) -> Option>; + /// Given a did this returns: + /// * the DID + /// * public keys stored for the did + /// * the web3name (optional) + /// * associated accounts + /// * service endpoints fn query_did(did: DidIdentifier) -> Option>; } } diff --git a/rpc/did/src/lib.rs b/rpc/did/src/lib.rs index 5c40eaf8e2..8d49c85fc2 100644 --- a/rpc/did/src/lib.rs +++ b/rpc/did/src/lib.rs @@ -59,6 +59,12 @@ where Key: Ord, Balance: FromStr + Display, { + /// Given a web3name this returns: + /// * the DID + /// * public keys stored for the did + /// * the web3name (optional) + /// * associated accounts + /// * service endpoints #[rpc(name = "did_queryByWeb3Name")] fn query_did_by_w3n( &self, @@ -66,6 +72,12 @@ where at: Option, ) -> Result>; + /// Given an account this returns: + /// * the DID + /// * public keys stored for the did + /// * the web3name (optional) + /// * associated accounts + /// * service endpoints #[rpc(name = "did_queryByAccount")] fn query_did_by_account_id( &self, @@ -73,6 +85,12 @@ where at: Option, ) -> Result>; + /// Given a did this returns: + /// * the DID + /// * public keys stored for the did + /// * the web3name (optional) + /// * associated accounts + /// * service endpoints #[rpc(name = "did_query")] fn query_did( &self, From 7fbc0a5012561da8824434825fbffe2683b65ce5 Mon Sep 17 00:00:00 2001 From: weichweich Date: Thu, 28 Apr 2022 17:33:36 +0200 Subject: [PATCH 24/31] chore: cleaning --- Cargo.lock | 2 -- pallets/attestation/Cargo.toml | 3 +-- pallets/ctype/Cargo.toml | 4 +--- pallets/pallet-web3-names/Cargo.toml | 2 +- runtimes/common/Cargo.toml | 12 ++---------- runtimes/common/src/lib.rs | 19 +++++++++---------- 6 files changed, 14 insertions(+), 28 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 33a1ce8ca4..25895ac90e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8906,14 +8906,12 @@ name = "runtime-common" version = "1.6.2" dependencies = [ "attestation", - "did", "frame-support", "frame-system", "pallet-authorship", "pallet-balances", "pallet-membership", "pallet-transaction-payment", - "pallet-web3-names", "parachain-staking", "parity-scale-codec", "scale-info", diff --git a/pallets/attestation/Cargo.toml b/pallets/attestation/Cargo.toml index f4db947dd3..f7feecaa56 100644 --- a/pallets/attestation/Cargo.toml +++ b/pallets/attestation/Cargo.toml @@ -13,12 +13,11 @@ targets = ["x86_64-unknown-linux-gnu"] substrate-wasm-builder-runner = "3.0.0" [dev-dependencies] -serde = "1.0.136" - ctype = {features = ["mock"], path = "../ctype"} kilt-support = {features = ["mock"], path = "../../support"} pallet-balances = {branch = "polkadot-v0.9.19", git = "https://github.com/paritytech/substrate"} +serde = "1.0.136" sp-core = {branch = "polkadot-v0.9.19", git = "https://github.com/paritytech/substrate"} sp-io = {branch = "polkadot-v0.9.19", git = "https://github.com/paritytech/substrate"} sp-keystore = {branch = "polkadot-v0.9.19", git = "https://github.com/paritytech/substrate"} diff --git a/pallets/ctype/Cargo.toml b/pallets/ctype/Cargo.toml index 4b6a897b4a..414c666302 100644 --- a/pallets/ctype/Cargo.toml +++ b/pallets/ctype/Cargo.toml @@ -13,11 +13,9 @@ targets = ["x86_64-unknown-linux-gnu"] substrate-wasm-builder-runner = "3.0.0" [dev-dependencies] -serde = "1.0.136" - kilt-support = {features = ["mock"], path = "../../support"} - pallet-balances = {branch = "polkadot-v0.9.19", git = "https://github.com/paritytech/substrate"} +serde = "1.0.136" sp-core = {branch = "polkadot-v0.9.19", git = "https://github.com/paritytech/substrate"} sp-keystore = {branch = "polkadot-v0.9.19", git = "https://github.com/paritytech/substrate"} diff --git a/pallets/pallet-web3-names/Cargo.toml b/pallets/pallet-web3-names/Cargo.toml index 99543b0cc7..f21c4bc622 100644 --- a/pallets/pallet-web3-names/Cargo.toml +++ b/pallets/pallet-web3-names/Cargo.toml @@ -18,7 +18,7 @@ sp-io = {branch = "polkadot-v0.9.19", git = "https://github.com/paritytech/subst sp-keystore = {branch = "polkadot-v0.9.19", git = "https://github.com/paritytech/substrate"} [dependencies] -codec = {default-features = false, features = ["derive"], package = "parity-scale-codec", version = "3.1.2"} +codec = {package = "parity-scale-codec", version = "3.1.2", default-features = false, features = ["derive"]} scale-info = {version = "2.1.1", default-features = false, features = ["derive"]} serde = {version = "1.0.136", optional = true} diff --git a/runtimes/common/Cargo.toml b/runtimes/common/Cargo.toml index 768e4eecfc..8bed6f103d 100644 --- a/runtimes/common/Cargo.toml +++ b/runtimes/common/Cargo.toml @@ -13,9 +13,7 @@ scale-info = {version = "2.1.1", default-features = false, features = ["derive"] serde = {version = "1.0.136", optional = true, features = ["derive"]} smallvec = "1.8.0" -attestation = {path = "../../pallets/attestation", default-features = false} -did = {path = "../../pallets/did", default-features = false} -pallet-web3-names = {path = "../../pallets/pallet-web3-names", default-features = false} +attestation = {default-features = false, path = "../../pallets/attestation"} parachain-staking = {default-features = false, path = "../../pallets/parachain-staking"} frame-support = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.19"} @@ -34,26 +32,20 @@ default = ["std"] fast-gov = [] runtime-benchmarks = [ "attestation/runtime-benchmarks", - "did/runtime-benchmarks", - "pallet-web3-names/runtime-benchmarks", "frame-support/runtime-benchmarks", "parachain-staking/runtime-benchmarks", "sp-runtime/runtime-benchmarks", ] std = [ "attestation/std", + "parachain-staking/std", "codec/std", - "did/std", "frame-support/std", "frame-system/std", "pallet-transaction-payment/std", "pallet-balances/std", "pallet-membership/std", "pallet-authorship/std", - "pallet-balances/std", - "pallet-transaction-payment/std", - "pallet-web3-names/std", - "parachain-staking/std", "scale-info/std", "serde", "sp-consensus-aura/std", diff --git a/runtimes/common/src/lib.rs b/runtimes/common/src/lib.rs index 5d3155cdd0..c05f191df8 100644 --- a/runtimes/common/src/lib.rs +++ b/runtimes/common/src/lib.rs @@ -20,6 +20,14 @@ #![cfg_attr(not(feature = "std"), no_std)] +use constants::{AVERAGE_ON_INITIALIZE_RATIO, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO}; +use fees::SplitFeesByRatio; + +pub use sp_consensus_aura::sr25519::AuthorityId; + +pub use opaque::*; + +pub use frame_support::weights::constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; use frame_support::{ parameter_types, traits::{Contains, ContainsLengthBound, Currency, Get, SortedMembers}, @@ -34,16 +42,6 @@ use sp_runtime::{ }; use sp_std::marker::PhantomData; -use crate::{ - constants::{AVERAGE_ON_INITIALIZE_RATIO, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO}, - fees::SplitFeesByRatio, -}; - -pub use frame_support::weights::constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; -pub use sp_consensus_aura::sr25519::AuthorityId; - -pub use crate::opaque::*; - pub mod authorization; pub mod constants; pub mod fees; @@ -160,6 +158,7 @@ pub type FeeSplit = SplitFeesByRatio; /// https://w3f-research.readthedocs.io/en/latest/polkadot/Token%20Economics.html#-2.-slow-adjusting-mechanism pub type SlowAdjustingFeeUpdate = TargetedFeeAdjustment; + pub struct Tippers(PhantomData, PhantomData); impl ContainsLengthBound for Tippers where From 6691f34af52af2abc981d05fb747549047b0cfe6 Mon Sep 17 00:00:00 2001 From: weichweich Date: Fri, 29 Apr 2022 07:32:31 +0200 Subject: [PATCH 25/31] sorted features --- pallets/did/Cargo.toml | 2 +- runtimes/peregrine/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pallets/did/Cargo.toml b/pallets/did/Cargo.toml index 7d80cacbb3..5453da705e 100644 --- a/pallets/did/Cargo.toml +++ b/pallets/did/Cargo.toml @@ -62,7 +62,6 @@ runtime-benchmarks = [ "kilt-support/runtime-benchmarks", ] std = [ - "serde", "codec/std", "ctype/std", "frame-support/std", @@ -72,6 +71,7 @@ std = [ "log/std", "pallet-balances/std", "scale-info/std", + "serde", "sp-core/std", "sp-io/std", "sp-keystore/std", diff --git a/runtimes/peregrine/Cargo.toml b/runtimes/peregrine/Cargo.toml index d87fb2ba06..79279eb6eb 100644 --- a/runtimes/peregrine/Cargo.toml +++ b/runtimes/peregrine/Cargo.toml @@ -135,7 +135,6 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", ] std = [ - "did-rpc-runtime-api/std", "attestation/std", "codec/std", "ctype/std", @@ -145,6 +144,7 @@ std = [ "cumulus-primitives-core/std", "cumulus-primitives-timestamp/std", "delegation/std", + "did-rpc-runtime-api/std", "did/std", "frame-benchmarking/std", "frame-executive/std", From 3c2d6b5a43708efbc652ab31850fab7cd5cefbcc Mon Sep 17 00:00:00 2001 From: Albrecht Date: Mon, 2 May 2022 08:07:04 +0200 Subject: [PATCH 26/31] Update rpc/did/src/lib.rs Co-authored-by: William Freudenberger --- rpc/did/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rpc/did/src/lib.rs b/rpc/did/src/lib.rs index 8d49c85fc2..bc51a39cc4 100644 --- a/rpc/did/src/lib.rs +++ b/rpc/did/src/lib.rs @@ -151,7 +151,7 @@ where ) -> Result>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| - // If the block hash is not supplied assume the best block. + // If the block hash is not provided, assume the best block. self.client.info().best_hash)); match api.query_did_by_w3n(&at, web3name.into()) { From ccc688f9c366ffe277ca6c47849885b94aff14d6 Mon Sep 17 00:00:00 2001 From: weichweich Date: Mon, 16 May 2022 10:48:08 +0200 Subject: [PATCH 27/31] refactor: Rename to linked info DidDocument is overloaded --- rpc/did/runtime-api/src/lib.rs | 14 +++++++------- rpc/did/src/lib.rs | 20 ++++++++++---------- runtimes/peregrine/src/lib.rs | 12 ++++++------ runtimes/spiritnet/src/lib.rs | 12 ++++++------ runtimes/standalone/src/lib.rs | 12 ++++++------ 5 files changed, 35 insertions(+), 35 deletions(-) diff --git a/rpc/did/runtime-api/src/lib.rs b/rpc/did/runtime-api/src/lib.rs index 8a903643e1..07b5532e51 100644 --- a/rpc/did/runtime-api/src/lib.rs +++ b/rpc/did/runtime-api/src/lib.rs @@ -57,7 +57,7 @@ pub use service_endpoint::*; Web3Name: Deserialize<'de>," )) )] -pub struct DidDocument +pub struct DidLinkedInfo { pub identifier: DidIdentifier, pub accounts: Vec, @@ -66,12 +66,12 @@ pub struct DidDocument, } -/// The DidDocument with a Web3Name represented as a byte array. +/// The DidLinkedInfo with a Web3Name represented as a byte array. /// /// This will be returned by the runtime and processed by the client side RPC /// implementation. -pub type RawDidDocument = - DidDocument, Vec, Vec, Vec, Balance, Key, BlockNumber>; +pub type RawDidLinkedInfo = + DidLinkedInfo, Vec, Vec, Vec, Balance, Key, BlockNumber>; sp_api::decl_runtime_apis! { /// The API to query account nonce (aka transaction index). @@ -88,20 +88,20 @@ sp_api::decl_runtime_apis! { /// * the web3name (optional) /// * associated accounts /// * service endpoints - fn query_did_by_w3n(name: Vec) -> Option>; + fn query_did_by_w3n(name: Vec) -> Option>; /// Given an account address this returns: /// * the DID /// * public keys stored for the did /// * the web3name (optional) /// * associated accounts /// * service endpoints - fn query_did_by_account_id(account: AccountId) -> Option>; + fn query_did_by_account_id(account: AccountId) -> Option>; /// Given a did this returns: /// * the DID /// * public keys stored for the did /// * the web3name (optional) /// * associated accounts /// * service endpoints - fn query_did(did: DidIdentifier) -> Option>; + fn query_did(did: DidIdentifier) -> Option>; } } diff --git a/rpc/did/src/lib.rs b/rpc/did/src/lib.rs index bc51a39cc4..223e0ac31b 100644 --- a/rpc/did/src/lib.rs +++ b/rpc/did/src/lib.rs @@ -19,7 +19,7 @@ use std::{fmt::Display, str::FromStr, sync::Arc}; use codec::{Codec, MaxEncodedLen}; -use did_rpc_runtime_api::{DidDocument, ServiceEndpoint}; +use did_rpc_runtime_api::{DidLinkedInfo, ServiceEndpoint}; use jsonrpc_core::{Error as RpcError, ErrorCode, Result}; use jsonrpc_derive::rpc; use sp_api::ProvideRuntimeApi; @@ -28,8 +28,8 @@ use sp_runtime::{generic::BlockId, traits::Block as BlockT}; pub use did_rpc_runtime_api::DidApi as DidRuntimeApi; -pub type RpcDidDocument = - DidDocument; +pub type RpcDidLinkedInfo = + DidLinkedInfo; fn raw_did_endpoint_to_rpc( raw: ServiceEndpoint, Vec, Vec>, @@ -50,7 +50,7 @@ fn raw_did_endpoint_to_rpc( } pub type DidRpcResponse = - Option>; + Option>; #[rpc] pub trait DidApi @@ -148,7 +148,7 @@ where &self, web3name: String, at: Option<::Hash>, - ) -> Result>> { + ) -> Result>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not provided, assume the best block. @@ -160,7 +160,7 @@ where message: "Unable to query dispatch info.".into(), data: Some(e.to_string().into()), }), - Ok(doc) => Ok(doc.map(|doc| RpcDidDocument { + Ok(doc) => Ok(doc.map(|doc| RpcDidLinkedInfo { // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we // ignore the w3n and pretend it doesn't exist. w3n: doc.w3n.and_then(|w3n| String::from_utf8(w3n).ok()), @@ -180,7 +180,7 @@ where &self, account: AccountId, at: Option<::Hash>, - ) -> Result>> { + ) -> Result>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. @@ -192,7 +192,7 @@ where message: "Unable to query fee details.".into(), data: Some(e.to_string().into()), }), - Ok(doc) => Ok(doc.map(|doc| RpcDidDocument { + Ok(doc) => Ok(doc.map(|doc| RpcDidLinkedInfo { // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we // ignore the w3n and pretend it doesn't exist. w3n: doc.w3n.and_then(|w3n| String::from_utf8(w3n).ok()), @@ -212,7 +212,7 @@ where &self, did: DidIdentifier, at: Option<::Hash>, - ) -> Result>> { + ) -> Result>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. @@ -224,7 +224,7 @@ where message: "Unable to query fee details.".into(), data: Some(e.to_string().into()), }), - Ok(doc) => Ok(doc.map(|doc| RpcDidDocument { + Ok(doc) => Ok(doc.map(|doc| RpcDidLinkedInfo { // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we // ignore the w3n and pretend it doesn't exist. w3n: doc.w3n.and_then(|w3n| String::from_utf8(w3n).ok()), diff --git a/runtimes/peregrine/src/lib.rs b/runtimes/peregrine/src/lib.rs index 92cf968388..4f58c17b9f 100644 --- a/runtimes/peregrine/src/lib.rs +++ b/runtimes/peregrine/src/lib.rs @@ -1092,7 +1092,7 @@ impl_runtime_apis! { Hash, BlockNumber > for Runtime { - fn query_did_by_w3n(name: Vec) -> Option) -> Option::iter_key_prefix(&owner_info.owner).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e|From::from(e.1)).collect(); - did_rpc_runtime_api::RawDidDocument { + did_rpc_runtime_api::RawDidLinkedInfo { identifier: owner_info.owner, w3n: Some(name.into()), accounts, @@ -1120,7 +1120,7 @@ impl_runtime_apis! { } fn query_did_by_account_id(account: AccountId) -> Option< - did_rpc_runtime_api::RawDidDocument< + did_rpc_runtime_api::RawDidLinkedInfo< DidIdentifier, AccountId, Balance, @@ -1137,7 +1137,7 @@ impl_runtime_apis! { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); - did_rpc_runtime_api::RawDidDocument { + did_rpc_runtime_api::RawDidLinkedInfo { identifier: connection_record.did, w3n, accounts, @@ -1148,7 +1148,7 @@ impl_runtime_apis! { } fn query_did(did: DidIdentifier) -> Option< - did_rpc_runtime_api::RawDidDocument< + did_rpc_runtime_api::RawDidLinkedInfo< DidIdentifier, AccountId, Balance, @@ -1161,7 +1161,7 @@ impl_runtime_apis! { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&did).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e|From::from(e.1)).collect(); - Some(did_rpc_runtime_api::RawDidDocument { + Some(did_rpc_runtime_api::RawDidLinkedInfo { identifier: did, w3n, accounts, diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index 03ff0e6198..37f4a1ba0b 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -1095,7 +1095,7 @@ impl_runtime_apis! { Hash, BlockNumber > for Runtime { - fn query_did_by_w3n(name: Vec) -> Option) -> Option::iter_key_prefix(&owner_info.owner).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e|From::from(e.1)).collect(); - did_rpc_runtime_api::RawDidDocument { + did_rpc_runtime_api::RawDidLinkedInfo { identifier: owner_info.owner, w3n: Some(name.into()), accounts, @@ -1123,7 +1123,7 @@ impl_runtime_apis! { } fn query_did_by_account_id(account: AccountId) -> Option< - did_rpc_runtime_api::RawDidDocument< + did_rpc_runtime_api::RawDidLinkedInfo< DidIdentifier, AccountId, Balance, @@ -1140,7 +1140,7 @@ impl_runtime_apis! { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); - did_rpc_runtime_api::RawDidDocument { + did_rpc_runtime_api::RawDidLinkedInfo { identifier: connection_record.did, w3n, accounts, @@ -1151,7 +1151,7 @@ impl_runtime_apis! { } fn query_did(did: DidIdentifier) -> Option< - did_rpc_runtime_api::RawDidDocument< + did_rpc_runtime_api::RawDidLinkedInfo< DidIdentifier, AccountId, Balance, @@ -1164,7 +1164,7 @@ impl_runtime_apis! { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&did).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e|From::from(e.1)).collect(); - Some(did_rpc_runtime_api::RawDidDocument { + Some(did_rpc_runtime_api::RawDidLinkedInfo { identifier: did, w3n, accounts, diff --git a/runtimes/standalone/src/lib.rs b/runtimes/standalone/src/lib.rs index 66737d0ef0..694ef12fa0 100644 --- a/runtimes/standalone/src/lib.rs +++ b/runtimes/standalone/src/lib.rs @@ -903,7 +903,7 @@ impl_runtime_apis! { Hash, BlockNumber > for Runtime { - fn query_did_by_w3n(name: Vec) -> Option) -> Option::iter_key_prefix(&owner_info.owner).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e|From::from(e.1)).collect(); - did_rpc_runtime_api::RawDidDocument { + did_rpc_runtime_api::RawDidLinkedInfo { identifier: owner_info.owner, w3n: Some(name.into()), accounts, @@ -931,7 +931,7 @@ impl_runtime_apis! { } fn query_did_by_account_id(account: AccountId) -> Option< - did_rpc_runtime_api::RawDidDocument< + did_rpc_runtime_api::RawDidLinkedInfo< DidIdentifier, AccountId, Balance, @@ -948,7 +948,7 @@ impl_runtime_apis! { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); - did_rpc_runtime_api::RawDidDocument { + did_rpc_runtime_api::RawDidLinkedInfo { identifier: connection_record.did, w3n, accounts, @@ -959,7 +959,7 @@ impl_runtime_apis! { } fn query_did(did: DidIdentifier) -> Option< - did_rpc_runtime_api::RawDidDocument< + did_rpc_runtime_api::RawDidLinkedInfo< DidIdentifier, AccountId, Balance, @@ -972,7 +972,7 @@ impl_runtime_apis! { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&did).collect(); let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e|From::from(e.1)).collect(); - Some(did_rpc_runtime_api::RawDidDocument { + Some(did_rpc_runtime_api::RawDidLinkedInfo { identifier: did, w3n, accounts, From f9cc49c1858c64d8f1f84b2ccabf28e8f9ce441a Mon Sep 17 00:00:00 2001 From: Antonio Antonino Date: Wed, 22 Jun 2022 15:13:45 +0200 Subject: [PATCH 28/31] fix: integrate develop and update to new jsonrpsee framework --- nodes/parachain/src/rpc.rs | 2 +- nodes/parachain/src/service.rs | 3 ++- nodes/standalone/src/rpc.rs | 4 ++-- rpc/did/runtime-api/src/lib.rs | 13 +++++++++++-- rpc/did/src/lib.rs | 9 ++++++--- 5 files changed, 22 insertions(+), 9 deletions(-) diff --git a/nodes/parachain/src/rpc.rs b/nodes/parachain/src/rpc.rs index db55f251f7..263d2ec5f2 100644 --- a/nodes/parachain/src/rpc.rs +++ b/nodes/parachain/src/rpc.rs @@ -57,9 +57,9 @@ where C::Api: did_rpc::DidRuntimeApi, P: TransactionPool + 'static, { + use did_rpc::{DidApiServer, DidQuery}; use frame_rpc_system::{System, SystemApiServer}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; - use did_rpc::{DidQuery, DidApiServer}; let mut module = RpcModule::new(()); let FullDeps { diff --git a/nodes/parachain/src/service.rs b/nodes/parachain/src/service.rs index 0b045f2516..115a49df1c 100644 --- a/nodes/parachain/src/service.rs +++ b/nodes/parachain/src/service.rs @@ -237,7 +237,8 @@ where + sp_block_builder::BlockBuilder + cumulus_primitives_core::CollectCollationInfo + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi - + frame_rpc_system::AccountNonceApi, + + frame_rpc_system::AccountNonceApi + + did_rpc::DidRuntimeApi, sc_client_api::StateBackendFor, Block>: sp_api::StateBackend, Executor: sc_executor::NativeExecutionDispatch + 'static, RB: FnOnce( diff --git a/nodes/standalone/src/rpc.rs b/nodes/standalone/src/rpc.rs index ac8b5c4572..3f7ce955fb 100644 --- a/nodes/standalone/src/rpc.rs +++ b/nodes/standalone/src/rpc.rs @@ -27,12 +27,12 @@ use std::sync::Arc; use jsonrpsee::RpcModule; +use runtime_common::{AccountId, Balance, Block, BlockNumber, DidIdentifier, Hash, Index}; pub use sc_rpc_api::DenyUnsafe; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; use sp_block_builder::BlockBuilder; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; -use runtime_common::{AccountId, Balance, Block, BlockNumber, DidIdentifier, Hash, Index}; /// Full client dependencies. pub struct FullDeps { @@ -56,9 +56,9 @@ where C::Api: did_rpc::DidRuntimeApi, P: TransactionPool + 'static, { + use did_rpc::{DidApiServer, DidQuery}; use frame_rpc_system::{System, SystemApiServer}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; - use did_rpc::{DidQuery, DidApiServer}; let mut module = RpcModule::new(()); let FullDeps { diff --git a/rpc/did/runtime-api/src/lib.rs b/rpc/did/runtime-api/src/lib.rs index 07b5532e51..afa320bbb4 100644 --- a/rpc/did/runtime-api/src/lib.rs +++ b/rpc/did/runtime-api/src/lib.rs @@ -57,8 +57,17 @@ pub use service_endpoint::*; Web3Name: Deserialize<'de>," )) )] -pub struct DidLinkedInfo -{ +pub struct DidLinkedInfo< + DidIdentifier, + AccountId, + Web3Name, + Id, + Type, + Url, + Balance, + Key: Ord, + BlockNumber: MaxEncodedLen, +> { pub identifier: DidIdentifier, pub accounts: Vec, pub w3n: Option, diff --git a/rpc/did/src/lib.rs b/rpc/did/src/lib.rs index 0569d75271..9e9a97b12f 100644 --- a/rpc/did/src/lib.rs +++ b/rpc/did/src/lib.rs @@ -163,7 +163,8 @@ where Error::RuntimeError.into(), "Unable to query DID by web3name.", Some(format!("{:?}", e)), - )).into()), + )) + .into()), Ok(doc) => Ok(doc.map(|doc| RpcDidLinkedInfo { // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we // ignore the w3n and pretend it doesn't exist. @@ -195,7 +196,8 @@ where Error::RuntimeError.into(), "Unable to query account by DID.", Some(format!("{:?}", e)), - )).into()), + )) + .into()), Ok(doc) => Ok(doc.map(|doc| RpcDidLinkedInfo { // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we // ignore the w3n and pretend it doesn't exist. @@ -227,7 +229,8 @@ where Error::RuntimeError.into(), "Unable to query DID details.", Some(format!("{:?}", e)), - )).into()), + )) + .into()), Ok(doc) => Ok(doc.map(|doc| RpcDidLinkedInfo { // convert the w3n from a byte array to a string. if it's invalid utf-8 which should never happen, we // ignore the w3n and pretend it doesn't exist. From e9e5253a84b1ef9f81e204c139e423c5e3c0afef Mon Sep 17 00:00:00 2001 From: Antonio Antonino Date: Wed, 22 Jun 2022 15:22:19 +0200 Subject: [PATCH 29/31] chore: minor chores --- Cargo.lock | 4 ++-- nodes/parachain/src/rpc.rs | 7 ++++++- nodes/standalone/src/rpc.rs | 10 ++++++++-- rpc/did/Cargo.toml | 14 ++++++++++++-- rpc/did/runtime-api/Cargo.toml | 2 +- scripts/all.fish | 8 ++++++-- 6 files changed, 35 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aec9a784ef..e7ad3590b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2025,7 +2025,7 @@ dependencies = [ [[package]] name = "did-rpc" -version = "1.5.0" +version = "1.6.2" dependencies = [ "did-rpc-runtime-api", "jsonrpsee", @@ -2039,7 +2039,7 @@ dependencies = [ [[package]] name = "did-rpc-runtime-api" -version = "1.5.0" +version = "1.6.2" dependencies = [ "did", "kilt-support", diff --git a/nodes/parachain/src/rpc.rs b/nodes/parachain/src/rpc.rs index 263d2ec5f2..f271ed4c8d 100644 --- a/nodes/parachain/src/rpc.rs +++ b/nodes/parachain/src/rpc.rs @@ -57,9 +57,9 @@ where C::Api: did_rpc::DidRuntimeApi, P: TransactionPool + 'static, { - use did_rpc::{DidApiServer, DidQuery}; use frame_rpc_system::{System, SystemApiServer}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; + use did_rpc::{DidApiServer, DidQuery}; let mut module = RpcModule::new(()); let FullDeps { @@ -70,6 +70,11 @@ where module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?; module.merge(TransactionPayment::new(client.clone()).into_rpc())?; + // Extend this RPC with a custom API by using the following syntax. + // `YourRpcStruct` should have a reference to a client, which is needed + // to call into the runtime. + // + // `module.merge(YourRpcStruct::new(ReferenceToClient).into_rpc())?;` module.merge(DidQuery::new(client).into_rpc())?; Ok(module) diff --git a/nodes/standalone/src/rpc.rs b/nodes/standalone/src/rpc.rs index 3f7ce955fb..aa858939ba 100644 --- a/nodes/standalone/src/rpc.rs +++ b/nodes/standalone/src/rpc.rs @@ -54,11 +54,11 @@ where C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, C::Api: BlockBuilder, C::Api: did_rpc::DidRuntimeApi, - P: TransactionPool + 'static, + P: TransactionPool + Sync + Send + 'static, { - use did_rpc::{DidApiServer, DidQuery}; use frame_rpc_system::{System, SystemApiServer}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; + use did_rpc::{DidApiServer, DidQuery}; let mut module = RpcModule::new(()); let FullDeps { @@ -69,6 +69,12 @@ where module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?; module.merge(TransactionPayment::new(client.clone()).into_rpc())?; + + // Extend this RPC with a custom API by using the following syntax. + // `YourRpcStruct` should have a reference to a client, which is needed + // to call into the runtime. + // + // `module.merge(YourRpcStruct::new(ReferenceToClient).into_rpc())?;` module.merge(DidQuery::new(client).into_rpc())?; Ok(module) diff --git a/rpc/did/Cargo.toml b/rpc/did/Cargo.toml index 0411a03a36..bf5026b805 100644 --- a/rpc/did/Cargo.toml +++ b/rpc/did/Cargo.toml @@ -1,7 +1,7 @@ [package] edition = "2021" name = "did-rpc" -version = "1.5.0" +version = "1.6.2" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -9,10 +9,20 @@ version = "1.5.0" codec = { package = "parity-scale-codec", version = "3.1.2" } jsonrpsee = { version = "0.13.1", features = ["server", "macros"] } -did-rpc-runtime-api = {version = "1.5.0", path = "./runtime-api"} +did-rpc-runtime-api = {version = "1.6.2", path = "./runtime-api"} sp-api = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.23"} sp-blockchain = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.23"} sp-core = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.23"} sp-rpc = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.23"} sp-runtime = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.23"} + +[features] +default = ["std"] +std = [ + "codec/std", + "did-rpc-runtime-api/std", + "sp-api/std", + "sp-core/std", + "sp-runtime/std", +] diff --git a/rpc/did/runtime-api/Cargo.toml b/rpc/did/runtime-api/Cargo.toml index 17c418c34f..1f2e228486 100644 --- a/rpc/did/runtime-api/Cargo.toml +++ b/rpc/did/runtime-api/Cargo.toml @@ -1,7 +1,7 @@ [package] edition = "2021" name = "did-rpc-runtime-api" -version = "1.5.0" +version = "1.6.2" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/scripts/all.fish b/scripts/all.fish index 316bf21361..7acfbed744 100644 --- a/scripts/all.fish +++ b/scripts/all.fish @@ -2,15 +2,17 @@ # Check a few feature combinations for all crates. # Requires `cargo-workspaces` to be installed. +echo "Features check started..." + for features in "--features default" "--all-features" "--features runtime-benchmarks" "--features try-runtime" for package in (cargo workspaces list) - cargo build -p $package (echo $features | string split " ") > /dev/null ^ /dev/null + cargo check -p $package (echo $features | string split " ") > /dev/null ^ /dev/null if [ "$status" = "0" ] echo -n "[ok] " else echo -n "[fail] " end - echo cargo build -p $package (echo $features | string split " ") + echo cargo check -p $package (echo $features | string split " ") end end @@ -25,3 +27,5 @@ for features in "--features default" "--all-features" "--features runtime-benchm echo cargo test -p $package (echo $features | string split " ") end end + +echo "Features check completed!" From 9733f93ee876ce09be332c9fb5e2e8d72a71f89a Mon Sep 17 00:00:00 2001 From: Antonio Antonino Date: Thu, 23 Jun 2022 13:38:38 +0200 Subject: [PATCH 30/31] chore: fmt --- nodes/parachain/src/rpc.rs | 2 +- nodes/standalone/src/rpc.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nodes/parachain/src/rpc.rs b/nodes/parachain/src/rpc.rs index f271ed4c8d..bd0aa872b5 100644 --- a/nodes/parachain/src/rpc.rs +++ b/nodes/parachain/src/rpc.rs @@ -57,9 +57,9 @@ where C::Api: did_rpc::DidRuntimeApi, P: TransactionPool + 'static, { + use did_rpc::{DidApiServer, DidQuery}; use frame_rpc_system::{System, SystemApiServer}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; - use did_rpc::{DidApiServer, DidQuery}; let mut module = RpcModule::new(()); let FullDeps { diff --git a/nodes/standalone/src/rpc.rs b/nodes/standalone/src/rpc.rs index aa858939ba..12dd25ef97 100644 --- a/nodes/standalone/src/rpc.rs +++ b/nodes/standalone/src/rpc.rs @@ -56,9 +56,9 @@ where C::Api: did_rpc::DidRuntimeApi, P: TransactionPool + Sync + Send + 'static, { + use did_rpc::{DidApiServer, DidQuery}; use frame_rpc_system::{System, SystemApiServer}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; - use did_rpc::{DidApiServer, DidQuery}; let mut module = RpcModule::new(()); let FullDeps { From 55f8d18b5e4c3cc78d4ae18de57ec774a7499007 Mon Sep 17 00:00:00 2001 From: weichweich Date: Tue, 28 Jun 2022 14:03:06 +0200 Subject: [PATCH 31/31] =?UTF-8?q?style:=20=F0=9F=A7=B9=F0=9F=90=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- nodes/standalone/src/rpc.rs | 2 +- runtimes/peregrine/src/lib.rs | 6 +++--- runtimes/spiritnet/src/lib.rs | 6 +++--- runtimes/standalone/src/lib.rs | 6 +++--- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/nodes/standalone/src/rpc.rs b/nodes/standalone/src/rpc.rs index 12dd25ef97..d0144fb6b2 100644 --- a/nodes/standalone/src/rpc.rs +++ b/nodes/standalone/src/rpc.rs @@ -54,7 +54,7 @@ where C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, C::Api: BlockBuilder, C::Api: did_rpc::DidRuntimeApi, - P: TransactionPool + Sync + Send + 'static, + P: TransactionPool + 'static, { use did_rpc::{DidApiServer, DidQuery}; use frame_rpc_system::{System, SystemApiServer}; diff --git a/runtimes/peregrine/src/lib.rs b/runtimes/peregrine/src/lib.rs index a35d8e1635..856eace4bd 100644 --- a/runtimes/peregrine/src/lib.rs +++ b/runtimes/peregrine/src/lib.rs @@ -1097,7 +1097,7 @@ impl_runtime_apis! { }) .map(|(owner_info, details)| { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&owner_info.owner).collect(); - let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e|From::from(e.1)).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e| From::from(e.1)).collect(); did_rpc_runtime_api::RawDidLinkedInfo { identifier: owner_info.owner, @@ -1125,7 +1125,7 @@ impl_runtime_apis! { .map(|(connection_record, details)| { let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); - let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e| From::from(e.1)).collect(); did_rpc_runtime_api::RawDidLinkedInfo { identifier: connection_record.did, @@ -1149,7 +1149,7 @@ impl_runtime_apis! { let details = did::Did::::get(&did)?; let w3n = pallet_web3_names::Names::::get(&did).map(Into::into); let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&did).collect(); - let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e|From::from(e.1)).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e| From::from(e.1)).collect(); Some(did_rpc_runtime_api::RawDidLinkedInfo { identifier: did, diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index 0071baa4cc..067ecd9b46 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -1090,7 +1090,7 @@ impl_runtime_apis! { }) .map(|(owner_info, details)| { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&owner_info.owner).collect(); - let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e|From::from(e.1)).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e| From::from(e.1)).collect(); did_rpc_runtime_api::RawDidLinkedInfo { identifier: owner_info.owner, @@ -1118,7 +1118,7 @@ impl_runtime_apis! { .map(|(connection_record, details)| { let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); - let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e| From::from(e.1)).collect(); did_rpc_runtime_api::RawDidLinkedInfo { identifier: connection_record.did, @@ -1142,7 +1142,7 @@ impl_runtime_apis! { let details = did::Did::::get(&did)?; let w3n = pallet_web3_names::Names::::get(&did).map(Into::into); let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&did).collect(); - let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e|From::from(e.1)).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e| From::from(e.1)).collect(); Some(did_rpc_runtime_api::RawDidLinkedInfo { identifier: did, diff --git a/runtimes/standalone/src/lib.rs b/runtimes/standalone/src/lib.rs index 53ffe85bbb..5f001739d1 100644 --- a/runtimes/standalone/src/lib.rs +++ b/runtimes/standalone/src/lib.rs @@ -904,7 +904,7 @@ impl_runtime_apis! { }) .map(|(owner_info, details)| { let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&owner_info.owner).collect(); - let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e|From::from(e.1)).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&owner_info.owner).map(|e| From::from(e.1)).collect(); did_rpc_runtime_api::RawDidLinkedInfo { identifier: owner_info.owner, @@ -932,7 +932,7 @@ impl_runtime_apis! { .map(|(connection_record, details)| { let w3n = pallet_web3_names::Names::::get(&connection_record.did).map(Into::into); let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&connection_record.did).collect(); - let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e|From::from(e.1)).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&connection_record.did).map(|e| From::from(e.1)).collect(); did_rpc_runtime_api::RawDidLinkedInfo { identifier: connection_record.did, @@ -956,7 +956,7 @@ impl_runtime_apis! { let details = did::Did::::get(&did)?; let w3n = pallet_web3_names::Names::::get(&did).map(Into::into); let accounts = pallet_did_lookup::ConnectedAccounts::::iter_key_prefix(&did).collect(); - let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e|From::from(e.1)).collect(); + let service_endpoints = did::ServiceEndpoints::::iter_prefix(&did).map(|e| From::from(e.1)).collect(); Some(did_rpc_runtime_api::RawDidLinkedInfo { identifier: did,