Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • nodes/rust/duniter-v2s
  • llaq/lc-core-substrate
  • pini-gh/duniter-v2s
  • vincentux/duniter-v2s
  • mildred/duniter-v2s
  • d0p1/duniter-v2s
  • bgallois/duniter-v2s
  • Nicolas80/duniter-v2s
8 results
Show changes
Showing
with 95835 additions and 387 deletions
...@@ -33,13 +33,13 @@ use std::path::PathBuf; ...@@ -33,13 +33,13 @@ use std::path::PathBuf;
use std::process::Command; use std::process::Command;
use std::str::FromStr; use std::str::FromStr;
use subxt::ext::{sp_core, sp_runtime}; use subxt::ext::{sp_core, sp_runtime};
use subxt::rpc::{rpc_params, ClientT, SubscriptionClientT}; use subxt::rpc::rpc_params;
use subxt::tx::BaseExtrinsicParamsBuilder; use subxt::tx::BaseExtrinsicParamsBuilder;
pub type Client = subxt::OnlineClient<GdevConfig>; pub type Client = subxt::OnlineClient<GdevConfig>;
pub type Event = gdev::Event; pub type Event = gdev::Event;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
pub type SignedSubmittableExtrinsic = subxt::tx::SignedSubmittableExtrinsic<GdevConfig, Client>; pub type SubmittableExtrinsic = subxt::tx::SubmittableExtrinsic<GdevConfig, Client>;
pub type TxProgress = subxt::tx::TxProgress<GdevConfig, Client>; pub type TxProgress = subxt::tx::TxProgress<GdevConfig, Client>;
pub enum GdevConfig {} pub enum GdevConfig {}
...@@ -52,7 +52,6 @@ impl subxt::config::Config for GdevConfig { ...@@ -52,7 +52,6 @@ impl subxt::config::Config for GdevConfig {
type Address = sp_runtime::MultiAddress<Self::AccountId, u32>; type Address = sp_runtime::MultiAddress<Self::AccountId, u32>;
type Header = sp_runtime::generic::Header<Self::BlockNumber, sp_runtime::traits::BlakeTwo256>; type Header = sp_runtime::generic::Header<Self::BlockNumber, sp_runtime::traits::BlakeTwo256>;
type Signature = sp_runtime::MultiSignature; type Signature = sp_runtime::MultiSignature;
type Extrinsic = sp_runtime::OpaqueExtrinsic;
type ExtrinsicParams = subxt::tx::BaseExtrinsicParams<Self, Tip>; type ExtrinsicParams = subxt::tx::BaseExtrinsicParams<Self, Tip>;
} }
...@@ -122,7 +121,6 @@ pub async fn create_empty_block(client: &Client) -> Result<()> { ...@@ -122,7 +121,6 @@ pub async fn create_empty_block(client: &Client) -> Result<()> {
// Create an empty block // Create an empty block
let _: Value = client let _: Value = client
.rpc() .rpc()
.client
.request("engine_createBlock", rpc_params![true, false, Value::Null]) .request("engine_createBlock", rpc_params![true, false, Value::Null])
.await?; .await?;
...@@ -131,8 +129,8 @@ pub async fn create_empty_block(client: &Client) -> Result<()> { ...@@ -131,8 +129,8 @@ pub async fn create_empty_block(client: &Client) -> Result<()> {
pub async fn create_block_with_extrinsic( pub async fn create_block_with_extrinsic(
client: &Client, client: &Client,
extrinsic: SignedSubmittableExtrinsic, extrinsic: SubmittableExtrinsic,
) -> Result<subxt::tx::TxEvents<GdevConfig>> { ) -> Result<subxt::blocks::ExtrinsicEvents<GdevConfig>> {
//println!("extrinsic encoded: {}", hex::encode(extrinsic.encoded())); //println!("extrinsic encoded: {}", hex::encode(extrinsic.encoded()));
let watcher = extrinsic.submit_and_watch().await?; let watcher = extrinsic.submit_and_watch().await?;
...@@ -140,7 +138,6 @@ pub async fn create_block_with_extrinsic( ...@@ -140,7 +138,6 @@ pub async fn create_block_with_extrinsic(
// Create a non-empty block // Create a non-empty block
let _: Value = client let _: Value = client
.rpc() .rpc()
.client
.request("engine_createBlock", rpc_params![false, false, Value::Null]) .request("engine_createBlock", rpc_params![false, false, Value::Null])
.await?; .await?;
...@@ -223,14 +220,14 @@ fn wait_until_log_line(expected_log_line: &str, log_file_path: &str, timeout: st ...@@ -223,14 +220,14 @@ fn wait_until_log_line(expected_log_line: &str, log_file_path: &str, timeout: st
let mut watcher = notify::watcher(tx, std::time::Duration::from_millis(100)).unwrap(); let mut watcher = notify::watcher(tx, std::time::Duration::from_millis(100)).unwrap();
use notify::Watcher as _; use notify::Watcher as _;
watcher watcher
.watch(&log_file_path, notify::RecursiveMode::NonRecursive) .watch(log_file_path, notify::RecursiveMode::NonRecursive)
.unwrap(); .unwrap();
let mut pos = 0; let mut pos = 0;
loop { loop {
match rx.recv_timeout(timeout) { match rx.recv_timeout(timeout) {
Ok(notify::DebouncedEvent::Write(_)) => { Ok(notify::DebouncedEvent::Write(_)) => {
let mut file = std::fs::File::open(&log_file_path).unwrap(); let mut file = std::fs::File::open(log_file_path).unwrap();
file.seek(std::io::SeekFrom::Start(pos)).unwrap(); file.seek(std::io::SeekFrom::Start(pos)).unwrap();
pos = file.metadata().unwrap().len(); pos = file.metadata().unwrap().len();
let reader = std::io::BufReader::new(file); let reader = std::io::BufReader::new(file);
......
...@@ -412,7 +412,7 @@ async fn should_be_certified_by( ...@@ -412,7 +412,7 @@ async fn should_be_certified_by(
.unwrap(); .unwrap();
let issuers = world let issuers = world
.read_or_default(&gdev::storage().cert().certs_by_receiver(&receiver_index)) .read_or_default(&gdev::storage().cert().certs_by_receiver(receiver_index))
.await?; .await?;
// look for certification by issuer/receiver pair // look for certification by issuer/receiver pair
......
...@@ -12,6 +12,6 @@ version = '3.0.0' ...@@ -12,6 +12,6 @@ version = '3.0.0'
anyhow = "1.0" anyhow = "1.0"
hex-literal = "0.3" hex-literal = "0.3"
parity-scale-codec = "3.1.5" parity-scale-codec = "3.1.5"
sp-core = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.26' } sp-core = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32' }
subxt = { git = 'https://github.com/duniter/subxt', branch = 'duniter-substrate-v0.9.26' } subxt = { git = 'https://github.com/duniter/subxt', branch = 'duniter-substrate-v0.9.32' }
tokio = { version = "1.15.0", features = ["macros"] } tokio = { version = "1.15.0", features = ["macros"] }
This diff is collapsed.
...@@ -21,7 +21,7 @@ use std::collections::BTreeMap; ...@@ -21,7 +21,7 @@ use std::collections::BTreeMap;
type MembershipData = sp_membership::MembershipData<u32>; type MembershipData = sp_membership::MembershipData<u32>;
const EXISTENTIAL_DEPOSIT: u64 = 100; const EXISTENTIAL_DEPOSIT: u64 = 200;
#[derive(Clone)] #[derive(Clone)]
pub struct GenesisData<Parameters: DeserializeOwned, SessionKeys: Decode> { pub struct GenesisData<Parameters: DeserializeOwned, SessionKeys: Decode> {
......
...@@ -16,17 +16,18 @@ ...@@ -16,17 +16,18 @@
use super::*; use super::*;
use common_runtime::constants::*; use common_runtime::constants::*;
use common_runtime::entities::IdtyName; use common_runtime::entities::IdtyData;
use common_runtime::*;
use gtest_runtime::{ use gtest_runtime::{
opaque::SessionKeys, AccountId, AuthorityMembersConfig, BabeConfig, BalancesConfig, CertConfig, opaque::SessionKeys, AccountConfig, AccountId, AuthorityMembersConfig, BabeConfig,
GenesisConfig, IdentityConfig, IdtyValue, ImOnlineId, MembershipConfig, SessionConfig, BalancesConfig, CertConfig, GenesisConfig, IdentityConfig, IdtyValue, ImOnlineId,
SmithsCertConfig, SmithsMembershipConfig, SudoConfig, SystemConfig, UdAccountsStorageConfig, MembershipConfig, SessionConfig, SmithsCertConfig, SmithsMembershipConfig, SudoConfig,
UniversalDividendConfig, WASM_BINARY, SystemConfig, TechnicalCommitteeConfig, UniversalDividendConfig, WASM_BINARY,
}; };
use sc_service::ChainType; use sc_service::ChainType;
use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId;
use sp_consensus_babe::AuthorityId as BabeId; use sp_consensus_babe::AuthorityId as BabeId;
use sp_core::sr25519; use sp_core::{blake2_256, sr25519, Encode, H256};
use sp_finality_grandpa::AuthorityId as GrandpaId; use sp_finality_grandpa::AuthorityId as GrandpaId;
use sp_membership::MembershipData; use sp_membership::MembershipData;
use std::collections::BTreeMap; use std::collections::BTreeMap;
...@@ -69,10 +70,12 @@ pub fn development_chain_spec() -> Result<ChainSpec, String> { ...@@ -69,10 +70,12 @@ pub fn development_chain_spec() -> Result<ChainSpec, String> {
move || { move || {
gen_genesis_for_local_chain( gen_genesis_for_local_chain(
wasm_binary, wasm_binary,
// Initial authorities // Initial authorities len
1, 1,
// Inital identities // Initial smiths members len
3, 3,
// Inital identities len
4,
// Sudo account // Sudo account
get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Alice"),
true, true,
...@@ -103,6 +106,7 @@ pub fn development_chain_spec() -> Result<ChainSpec, String> { ...@@ -103,6 +106,7 @@ pub fn development_chain_spec() -> Result<ChainSpec, String> {
pub fn local_testnet_config( pub fn local_testnet_config(
initial_authorities_len: usize, initial_authorities_len: usize,
initial_smiths_len: usize,
initial_identities_len: usize, initial_identities_len: usize,
) -> Result<ChainSpec, String> { ) -> Result<ChainSpec, String> {
let wasm_binary = WASM_BINARY.ok_or_else(|| "wasm not available".to_string())?; let wasm_binary = WASM_BINARY.ok_or_else(|| "wasm not available".to_string())?;
...@@ -118,6 +122,8 @@ pub fn local_testnet_config( ...@@ -118,6 +122,8 @@ pub fn local_testnet_config(
wasm_binary, wasm_binary,
// Initial authorities len // Initial authorities len
initial_authorities_len, initial_authorities_len,
// Initial smiths len,
initial_smiths_len,
// Initial identities len // Initial identities len
initial_identities_len, initial_identities_len,
// Sudo account // Sudo account
...@@ -151,11 +157,18 @@ pub fn local_testnet_config( ...@@ -151,11 +157,18 @@ pub fn local_testnet_config(
fn gen_genesis_for_local_chain( fn gen_genesis_for_local_chain(
wasm_binary: &[u8], wasm_binary: &[u8],
initial_authorities_len: usize, initial_authorities_len: usize,
initial_smiths_len: usize,
initial_identities_len: usize, initial_identities_len: usize,
root_key: AccountId, root_key: AccountId,
_enable_println: bool, _enable_println: bool,
) -> GenesisConfig { ) -> GenesisConfig {
let initial_authorities = (0..initial_authorities_len) assert!(initial_identities_len <= 6);
assert!(initial_smiths_len <= initial_identities_len);
assert!(initial_authorities_len <= initial_smiths_len);
let first_ud = 1_000;
let initial_smiths = (0..initial_smiths_len)
.map(|i| get_authority_keys_from_seed(NAMES[i])) .map(|i| get_authority_keys_from_seed(NAMES[i]))
.collect::<Vec<AuthorityKeys>>(); .collect::<Vec<AuthorityKeys>>();
let initial_identities = (0..initial_identities_len) let initial_identities = (0..initial_identities_len)
...@@ -172,9 +185,25 @@ fn gen_genesis_for_local_chain( ...@@ -172,9 +185,25 @@ fn gen_genesis_for_local_chain(
// Add Wasm runtime to storage. // Add Wasm runtime to storage.
code: wasm_binary.to_vec(), code: wasm_binary.to_vec(),
}, },
account: AccountConfig {
accounts: initial_identities
.iter()
.enumerate()
.map(|(i, (_, owner_key))| {
(
owner_key.clone(),
GenesisAccountData {
random_id: H256(blake2_256(&(i as u32, owner_key).encode())),
balance: first_ud,
is_identity: true,
},
)
})
.collect(),
},
authority_discovery: Default::default(), authority_discovery: Default::default(),
authority_members: AuthorityMembersConfig { authority_members: AuthorityMembersConfig {
initial_authorities: initial_authorities initial_authorities: initial_smiths
.iter() .iter()
.enumerate() .enumerate()
.map(|(i, keys)| (i as u32 + 1, (keys.0.clone(), true))) .map(|(i, keys)| (i as u32 + 1, (keys.0.clone(), true)))
...@@ -190,7 +219,7 @@ fn gen_genesis_for_local_chain( ...@@ -190,7 +219,7 @@ fn gen_genesis_for_local_chain(
grandpa: Default::default(), grandpa: Default::default(),
im_online: Default::default(), im_online: Default::default(),
session: SessionConfig { session: SessionConfig {
keys: initial_authorities keys: initial_smiths
.iter() .iter()
.map(|x| { .map(|x| {
( (
...@@ -205,14 +234,28 @@ fn gen_genesis_for_local_chain( ...@@ -205,14 +234,28 @@ fn gen_genesis_for_local_chain(
// Assign network admin rights. // Assign network admin rights.
key: Some(root_key), key: Some(root_key),
}, },
technical_committee: TechnicalCommitteeConfig {
members: initial_smiths
.iter()
.map(|x| x.0.clone())
.collect::<Vec<_>>(),
..Default::default()
},
identity: IdentityConfig { identity: IdentityConfig {
identities: initial_identities identities: initial_identities
.iter() .iter()
.map(|(name, account)| IdtyValue { .enumerate()
.map(|(i, (name, owner_key))| common_runtime::GenesisIdty {
index: i as u32 + 1,
name: name.clone(), name: name.clone(),
next_creatable_identity_on: Default::default(), value: IdtyValue {
removable_on: 0, data: IdtyData::new(),
status: gtest_runtime::IdtyStatus::Validated, next_creatable_identity_on: Default::default(),
old_owner_key: None,
owner_key: owner_key.clone(),
removable_on: 0,
status: IdtyStatus::Validated,
},
}) })
.collect(), .collect(),
}, },
...@@ -230,13 +273,10 @@ fn gen_genesis_for_local_chain( ...@@ -230,13 +273,10 @@ fn gen_genesis_for_local_chain(
}, },
cert: CertConfig { cert: CertConfig {
apply_cert_period_at_genesis: false, apply_cert_period_at_genesis: false,
certs_by_issuer: clique_wot( certs_by_receiver: clique_wot(initial_identities.len()),
initial_identities.len(),
gtest_runtime::parameters::ValidityPeriod::get(),
),
}, },
smiths_membership: SmithsMembershipConfig { smiths_membership: SmithsMembershipConfig {
memberships: (1..=initial_authorities_len) memberships: (1..=initial_smiths_len)
.map(|i| { .map(|i| {
( (
i as u32, i as u32,
...@@ -249,18 +289,14 @@ fn gen_genesis_for_local_chain( ...@@ -249,18 +289,14 @@ fn gen_genesis_for_local_chain(
}, },
smiths_cert: SmithsCertConfig { smiths_cert: SmithsCertConfig {
apply_cert_period_at_genesis: false, apply_cert_period_at_genesis: false,
certs_by_issuer: clique_wot( certs_by_receiver: clique_wot(initial_smiths_len),
initial_authorities_len,
gtest_runtime::parameters::SmithValidityPeriod::get(),
),
},
ud_accounts_storage: UdAccountsStorageConfig {
ud_accounts: initial_identities.values().cloned().collect(),
}, },
universal_dividend: UniversalDividendConfig { universal_dividend: UniversalDividendConfig {
first_reeval: 100,
first_ud: 1_000, first_ud: 1_000,
initial_monetary_mass: 0, initial_monetary_mass: 0,
}, },
treasury: Default::default(),
} }
} }
......
...@@ -87,7 +87,7 @@ pub enum Subcommand { ...@@ -87,7 +87,7 @@ pub enum Subcommand {
} }
/// Block authoring scheme to be used by the node /// Block authoring scheme to be used by the node
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ArgEnum)] #[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum Sealing { pub enum Sealing {
/// Author a block using normal runtime behavior (mandatory for production networks) /// Author a block using normal runtime behavior (mandatory for production networks)
Production, Production,
...@@ -129,6 +129,6 @@ impl std::str::FromStr for Sealing { ...@@ -129,6 +129,6 @@ impl std::str::FromStr for Sealing {
#[derive(Debug, clap::Args)] #[derive(Debug, clap::Args)]
pub struct Completion { pub struct Completion {
#[clap(short, long, arg_enum)] #[clap(short, long, value_enum)]
pub generator: clap_complete::Shell, pub generator: clap_complete::Shell,
} }
...@@ -28,6 +28,7 @@ use crate::service::GTestExecutor; ...@@ -28,6 +28,7 @@ use crate::service::GTestExecutor;
use crate::service::{IdentifyRuntimeType, RuntimeType}; use crate::service::{IdentifyRuntimeType, RuntimeType};
use crate::{chain_spec, service}; use crate::{chain_spec, service};
use clap::CommandFactory; use clap::CommandFactory;
#[cfg(feature = "runtime-benchmarks")]
use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE}; use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};
use sc_cli::{ChainSpec, RuntimeVersion, SubstrateCli}; use sc_cli::{ChainSpec, RuntimeVersion, SubstrateCli};
...@@ -42,6 +43,7 @@ lazy_static! { ...@@ -42,6 +43,7 @@ lazy_static! {
}*/ }*/
/// Unwraps a [`crate::client::Client`] into the concrete runtime client. /// Unwraps a [`crate::client::Client`] into the concrete runtime client.
#[cfg(feature = "runtime-benchmarks")]
macro_rules! unwrap_client { macro_rules! unwrap_client {
( (
$client:ident, $client:ident,
...@@ -78,7 +80,7 @@ impl SubstrateCli for Cli { ...@@ -78,7 +80,7 @@ impl SubstrateCli for Cli {
} }
fn support_url() -> String { fn support_url() -> String {
"support.anonymous.an".into() "https://forum.duniter.org/".into()
} }
fn copyright_start_year() -> i32 { fn copyright_start_year() -> i32 {
...@@ -106,11 +108,11 @@ impl SubstrateCli for Cli { ...@@ -106,11 +108,11 @@ impl SubstrateCli for Cli {
#[cfg(feature = "gtest")] #[cfg(feature = "gtest")]
"gtest_dev" => Box::new(chain_spec::gtest::development_chain_spec()?), "gtest_dev" => Box::new(chain_spec::gtest::development_chain_spec()?),
#[cfg(feature = "gtest")] #[cfg(feature = "gtest")]
"gtest_local" => Box::new(chain_spec::gtest::local_testnet_config(2, 3)?), "gtest_local" => Box::new(chain_spec::gtest::local_testnet_config(2, 3, 4)?),
#[cfg(feature = "gtest")] #[cfg(feature = "gtest")]
"gtest_local3" => Box::new(chain_spec::gtest::local_testnet_config(3, 4)?), "gtest_local3" => Box::new(chain_spec::gtest::local_testnet_config(3, 3, 4)?),
#[cfg(feature = "gtest")] #[cfg(feature = "gtest")]
"gtest_local4" => Box::new(chain_spec::gtest::local_testnet_config(4, 5)?), "gtest_local4" => Box::new(chain_spec::gtest::local_testnet_config(4, 4, 5)?),
#[cfg(feature = "gtest")] #[cfg(feature = "gtest")]
"gtest" => { "gtest" => {
unimplemented!() unimplemented!()
...@@ -129,7 +131,7 @@ impl SubstrateCli for Cli { ...@@ -129,7 +131,7 @@ impl SubstrateCli for Cli {
let starts_with = |prefix: &str| { let starts_with = |prefix: &str| {
path.file_name() path.file_name()
.and_then(|f| f.to_str().map(|s| s.starts_with(&prefix))) .and_then(|f| f.to_str().map(|s| s.starts_with(prefix)))
.unwrap_or(false) .unwrap_or(false)
}; };
...@@ -278,6 +280,7 @@ pub fn run() -> sc_cli::Result<()> { ...@@ -278,6 +280,7 @@ pub fn run() -> sc_cli::Result<()> {
); );
Ok(()) Ok(())
} }
#[cfg(feature = "runtime-benchmarks")]
Some(Subcommand::Benchmark(cmd)) => { Some(Subcommand::Benchmark(cmd)) => {
let runner = cli.create_runner(cmd)?; let runner = cli.create_runner(cmd)?;
let chain_spec = &runner.config().chain_spec; let chain_spec = &runner.config().chain_spec;
...@@ -304,7 +307,13 @@ pub fn run() -> sc_cli::Result<()> { ...@@ -304,7 +307,13 @@ pub fn run() -> sc_cli::Result<()> {
unwrap_client!( unwrap_client!(
client, client,
cmd.run(config, client.clone(), inherent_data, wrapped) cmd.run(
config,
client.clone(),
inherent_data,
Vec::new(),
wrapped.as_ref()
)
) )
}), }),
BenchmarkCmd::Pallet(cmd) => { BenchmarkCmd::Pallet(cmd) => {
...@@ -339,6 +348,12 @@ pub fn run() -> sc_cli::Result<()> { ...@@ -339,6 +348,12 @@ pub fn run() -> sc_cli::Result<()> {
_ => panic!("unknown runtime"), _ => panic!("unknown runtime"),
} }
} }
#[cfg(not(feature = "runtime-benchmarks"))]
Some(Subcommand::Benchmark(_cmd)) => {
Err("Benchmark wasn't enabled when building the node. \
You can enable it with `--features runtime-benchmarks`."
.into())
}
#[cfg(feature = "try-runtime")] #[cfg(feature = "try-runtime")]
Some(Subcommand::TryRuntime(cmd)) => { Some(Subcommand::TryRuntime(cmd)) => {
let runner = cli.create_runner(cmd)?; let runner = cli.create_runner(cmd)?;
......
...@@ -73,7 +73,7 @@ impl GenSessionKeysCmd { ...@@ -73,7 +73,7 @@ impl GenSessionKeysCmd {
let suri = utils::read_uri(self.suri.as_ref())?; let suri = utils::read_uri(self.suri.as_ref())?;
let base_path = self let base_path = self
.shared_params .shared_params
.base_path() .base_path()?
.unwrap_or_else(|| BasePath::from_project("", "", &C::executable_name())); .unwrap_or_else(|| BasePath::from_project("", "", &C::executable_name()));
let chain_id = self.shared_params.chain_id(self.shared_params.is_dev()); let chain_id = self.shared_params.chain_id(self.shared_params.is_dev());
let chain_spec = cli.load_spec(&chain_id)?; let chain_spec = cli.load_spec(&chain_id)?;
......
...@@ -50,7 +50,7 @@ impl StorageKeyPrefixCmd { ...@@ -50,7 +50,7 @@ impl StorageKeyPrefixCmd {
if let Some(ref pallet_name) = self.pallet_name { if let Some(ref pallet_name) = self.pallet_name {
print_key_prefix = true; print_key_prefix = true;
let pallet_prefix = twox_128(pallet_name.as_bytes()); let pallet_prefix = twox_128(pallet_name.as_bytes());
println!("Pallet prefix: 0x{}", hex::encode(&pallet_prefix)); println!("Pallet prefix: 0x{}", hex::encode(pallet_prefix));
key_prefix.extend_from_slice(&pallet_prefix[..]); key_prefix.extend_from_slice(&pallet_prefix[..]);
} }
if let Some(ref item_name) = self.item_name { if let Some(ref item_name) = self.item_name {
......
...@@ -23,7 +23,7 @@ use async_io::Timer; ...@@ -23,7 +23,7 @@ use async_io::Timer;
use common_runtime::Block; use common_runtime::Block;
use futures::{Stream, StreamExt}; use futures::{Stream, StreamExt};
use manual_seal::{run_manual_seal, EngineCommand, ManualSealParams}; use manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};
use sc_client_api::{BlockBackend, ExecutorProvider}; use sc_client_api::BlockBackend;
pub use sc_executor::NativeElseWasmExecutor; pub use sc_executor::NativeElseWasmExecutor;
use sc_finality_grandpa::SharedVoterState; use sc_finality_grandpa::SharedVoterState;
use sc_keystore::LocalKeystore; use sc_keystore::LocalKeystore;
...@@ -292,7 +292,7 @@ where ...@@ -292,7 +292,7 @@ where
let justification_import = grandpa_block_import.clone(); let justification_import = grandpa_block_import.clone();
let babe_config = babe::Config::get(&*client)?; let babe_config = babe::configuration(&*client)?;
let (babe_block_import, babe_link) = let (babe_block_import, babe_link) =
babe::block_import(babe_config, grandpa_block_import, client.clone())?; babe::block_import(babe_config, grandpa_block_import, client.clone())?;
...@@ -319,11 +319,10 @@ where ...@@ -319,11 +319,10 @@ where
slot_duration, slot_duration,
); );
Ok((timestamp, slot)) Ok((slot, timestamp))
}, },
&task_manager.spawn_essential_handle(), &task_manager.spawn_essential_handle(),
config.prometheus_registry(), config.prometheus_registry(),
sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),
telemetry.as_ref().map(|x| x.handle()), telemetry.as_ref().map(|x| x.handle()),
)? )?
}; };
...@@ -404,7 +403,7 @@ where ...@@ -404,7 +403,7 @@ where
Vec::default(), Vec::default(),
)); ));
let (network, system_rpc_tx, network_starter) = let (network, system_rpc_tx, tx_handler_controller, network_starter) =
sc_service::build_network(sc_service::BuildNetworkParams { sc_service::build_network(sc_service::BuildNetworkParams {
config: &config, config: &config,
client: client.clone(), client: client.clone(),
...@@ -520,9 +519,6 @@ where ...@@ -520,9 +519,6 @@ where
}), }),
); );
} else { } else {
let can_author_with =
sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());
let client_clone = client.clone(); let client_clone = client.clone();
let slot_duration = babe_link.config().slot_duration(); let slot_duration = babe_link.config().slot_duration();
let babe_config = babe::BabeParams { let babe_config = babe::BabeParams {
...@@ -550,13 +546,12 @@ where ...@@ -550,13 +546,12 @@ where
slot_duration, slot_duration,
); );
Ok((timestamp, slot, uncles)) Ok((slot, timestamp, uncles))
} }
}, },
force_authoring, force_authoring,
backoff_authoring_blocks, backoff_authoring_blocks,
babe_link, babe_link,
can_author_with,
block_proposal_slot_portion: babe::SlotProportion::new(2f32 / 3f32), block_proposal_slot_portion: babe::SlotProportion::new(2f32 / 3f32),
max_block_proposal_slot_portion: None, max_block_proposal_slot_portion: None,
telemetry: telemetry.as_ref().map(|x| x.handle()), telemetry: telemetry.as_ref().map(|x| x.handle()),
...@@ -600,15 +595,16 @@ where ...@@ -600,15 +595,16 @@ where
}; };
let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams { let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
config,
backend,
network: network.clone(), network: network.clone(),
client, client,
keystore: keystore_container.sync_keystore(), keystore: keystore_container.sync_keystore(),
task_manager: &mut task_manager, task_manager: &mut task_manager,
transaction_pool, transaction_pool,
rpc_builder: rpc_extensions_builder, rpc_builder: rpc_extensions_builder,
backend,
system_rpc_tx, system_rpc_tx,
config, tx_handler_controller,
telemetry: telemetry.as_mut(), telemetry: telemetry.as_mut(),
})?; })?;
......
...@@ -19,6 +19,7 @@ use sc_client_api::{AuxStore, Backend as BackendT, BlockchainEvents, KeyIterator ...@@ -19,6 +19,7 @@ use sc_client_api::{AuxStore, Backend as BackendT, BlockchainEvents, KeyIterator
use sp_api::{CallApiAt, NumberFor, ProvideRuntimeApi}; use sp_api::{CallApiAt, NumberFor, ProvideRuntimeApi};
use sp_blockchain::{HeaderBackend, HeaderMetadata}; use sp_blockchain::{HeaderBackend, HeaderMetadata};
use sp_consensus::BlockStatus; use sp_consensus::BlockStatus;
use sp_core::{Encode, Pair};
use sp_runtime::{ use sp_runtime::{
generic::{BlockId, SignedBlock}, generic::{BlockId, SignedBlock},
traits::{BlakeTwo256, Block as BlockT}, traits::{BlakeTwo256, Block as BlockT},
...@@ -155,22 +156,34 @@ pub enum Client { ...@@ -155,22 +156,34 @@ pub enum Client {
} }
macro_rules! with_client { macro_rules! with_client {
{ {
$self:ident, $self:ident,
$client:ident, $client:ident,
{ {
$( $code:tt )* $( $code:tt )*
} }
} => { } => {
match $self { match $self {
#[cfg(feature = "g1")] #[cfg(feature = "g1")]
Self::G1($client) => { $( $code )* }, Self::G1($client) => {
#[cfg(feature = "gtest")] #[allow(unused_imports)]
Self::GTest($client) => { $( $code )* }, use g1_runtime as runtime;
#[cfg(feature = "gdev")] $( $code )*
Self::GDev($client) => { $( $code )* }, }
} #[cfg(feature = "gtest")]
} Self::GTest($client) => {
#[allow(unused_imports)]
use gtest_runtime as runtime;
$( $code )*
}
#[cfg(feature = "gdev")]
Self::GDev($client) => {
#[allow(unused_imports)]
use gdev_runtime as runtime;
$( $code )*
}
}
}
} }
impl ClientHandle for Client { impl ClientHandle for Client {
...@@ -274,44 +287,99 @@ impl sc_client_api::BlockBackend<Block> for Client { ...@@ -274,44 +287,99 @@ impl sc_client_api::BlockBackend<Block> for Client {
} }
} }
impl frame_benchmarking_cli::ExtrinsicBuilder for Client { /// Helper trait to implement [`frame_benchmarking_cli::ExtrinsicBuilder`].
fn remark( ///
/// Should only be used for benchmarking since it makes strong assumptions
/// about the chain state that these calls will be valid for.
trait BenchmarkCallSigner<RuntimeCall: Encode + Clone, Signer: Pair> {
/// Signs a call together with the signed extensions of the specific runtime.
///
/// Only works if the current block is the genesis block since the
/// `CheckMortality` check is mocked by using the genesis block.
fn sign_call(
&self, &self,
_nonce: u32, call: RuntimeCall,
) -> std::result::Result<sp_runtime::OpaqueExtrinsic, &'static str> { nonce: u32,
todo!() current_block: u64,
/*with_signed_payload! { period: u64,
self, genesis: sp_core::H256,
{extra, client, raw_payload}, acc: Signer,
{ ) -> sp_runtime::OpaqueExtrinsic;
// First the setup code to init all the variables that are needed }
// to build the signed extras.
use runtime::{Call, SystemCall};
let call = Call::System(SystemCall::remark { remark: vec![] }); #[cfg(feature = "gdev")]
let bob = Sr25519Keyring::Bob.pair(); impl BenchmarkCallSigner<gdev_runtime::RuntimeCall, sp_core::sr25519::Pair>
for super::FullClient<gdev_runtime::RuntimeApi, super::GDevExecutor>
{
fn sign_call(
&self,
call: gdev_runtime::RuntimeCall,
nonce: u32,
current_block: u64,
period: u64,
genesis: sp_core::H256,
acc: sp_core::sr25519::Pair,
) -> sp_runtime::OpaqueExtrinsic {
use gdev_runtime as runtime;
let extra: runtime::SignedExtra = (
frame_system::CheckNonZeroSender::<runtime::Runtime>::new(),
frame_system::CheckSpecVersion::<runtime::Runtime>::new(),
frame_system::CheckTxVersion::<runtime::Runtime>::new(),
frame_system::CheckGenesis::<runtime::Runtime>::new(),
frame_system::CheckMortality::<runtime::Runtime>::from(
sp_runtime::generic::Era::mortal(period, current_block),
),
frame_system::CheckNonce::<runtime::Runtime>::from(nonce).into(),
frame_system::CheckWeight::<runtime::Runtime>::new(),
pallet_transaction_payment::ChargeTransactionPayment::<runtime::Runtime>::from(0),
);
let payload = sp_runtime::generic::SignedPayload::from_raw(
call.clone(),
extra.clone(),
(
(),
runtime::VERSION.spec_version,
runtime::VERSION.transaction_version,
genesis,
genesis,
(),
(),
(),
),
);
let signature = payload.using_encoded(|p| acc.sign(p));
runtime::UncheckedExtrinsic::new_signed(
call,
sp_runtime::AccountId32::from(acc.public()).into(),
common_runtime::Signature::Sr25519(signature),
extra,
)
.into()
}
}
let period = polkadot_runtime_common::BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2) as u64; impl frame_benchmarking_cli::ExtrinsicBuilder for Client {
fn pallet(&self) -> &str {
"system"
}
fn extrinsic(&self) -> &str {
"remark"
}
fn build(&self, nonce: u32) -> std::result::Result<sp_runtime::OpaqueExtrinsic, &'static str> {
with_client! {
self, client, {
let call = runtime::RuntimeCall::System(runtime::SystemCall::remark { remark: vec![] });
let signer = sp_keyring::Sr25519Keyring::Bob.pair();
let current_block = 0; let period = runtime::BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2) as u64;
let tip = 0;
let genesis = client.usage_info().chain.best_hash; let genesis = client.usage_info().chain.best_hash;
},
(period, current_block, nonce, tip, call, genesis), Ok(client.sign_call(call, nonce, 0, period, genesis, signer))
/* The SignedPayload is generated here */
{
// Use the payload to generate a signature.
let signature = raw_payload.using_encoded(|payload| bob.sign(payload));
let ext = runtime::UncheckedExtrinsic::new_signed(
call,
sp_runtime::AccountId32::from(bob.public()).into(),
polkadot_core_primitives::Signature::Sr25519(signature.clone()),
extra,
);
Ok(ext.into())
} }
}*/ }
} }
} }
...@@ -340,7 +408,7 @@ impl sp_blockchain::HeaderBackend<Block> for Client { ...@@ -340,7 +408,7 @@ impl sp_blockchain::HeaderBackend<Block> for Client {
impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client { impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client {
fn storage( fn storage(
&self, &self,
id: &BlockId<Block>, id: &<Block as BlockT>::Hash,
key: &StorageKey, key: &StorageKey,
) -> sp_blockchain::Result<Option<StorageData>> { ) -> sp_blockchain::Result<Option<StorageData>> {
match_client!(self, storage(id, key)) match_client!(self, storage(id, key))
...@@ -348,7 +416,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client { ...@@ -348,7 +416,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client {
fn storage_keys( fn storage_keys(
&self, &self,
id: &BlockId<Block>, id: &<Block as BlockT>::Hash,
key_prefix: &StorageKey, key_prefix: &StorageKey,
) -> sp_blockchain::Result<Vec<StorageKey>> { ) -> sp_blockchain::Result<Vec<StorageKey>> {
match_client!(self, storage_keys(id, key_prefix)) match_client!(self, storage_keys(id, key_prefix))
...@@ -356,7 +424,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client { ...@@ -356,7 +424,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client {
fn storage_hash( fn storage_hash(
&self, &self,
id: &BlockId<Block>, id: &<Block as BlockT>::Hash,
key: &StorageKey, key: &StorageKey,
) -> sp_blockchain::Result<Option<<Block as BlockT>::Hash>> { ) -> sp_blockchain::Result<Option<<Block as BlockT>::Hash>> {
match_client!(self, storage_hash(id, key)) match_client!(self, storage_hash(id, key))
...@@ -364,7 +432,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client { ...@@ -364,7 +432,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client {
fn storage_pairs( fn storage_pairs(
&self, &self,
id: &BlockId<Block>, id: &<Block as BlockT>::Hash,
key_prefix: &StorageKey, key_prefix: &StorageKey,
) -> sp_blockchain::Result<Vec<(StorageKey, StorageData)>> { ) -> sp_blockchain::Result<Vec<(StorageKey, StorageData)>> {
match_client!(self, storage_pairs(id, key_prefix)) match_client!(self, storage_pairs(id, key_prefix))
...@@ -372,7 +440,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client { ...@@ -372,7 +440,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client {
fn storage_keys_iter<'a>( fn storage_keys_iter<'a>(
&self, &self,
id: &BlockId<Block>, id: &<Block as BlockT>::Hash,
prefix: Option<&'a StorageKey>, prefix: Option<&'a StorageKey>,
start_key: Option<&StorageKey>, start_key: Option<&StorageKey>,
) -> sp_blockchain::Result< ) -> sp_blockchain::Result<
...@@ -383,7 +451,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client { ...@@ -383,7 +451,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client {
fn child_storage( fn child_storage(
&self, &self,
id: &BlockId<Block>, id: &<Block as BlockT>::Hash,
child_info: &ChildInfo, child_info: &ChildInfo,
key: &StorageKey, key: &StorageKey,
) -> sp_blockchain::Result<Option<StorageData>> { ) -> sp_blockchain::Result<Option<StorageData>> {
...@@ -392,7 +460,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client { ...@@ -392,7 +460,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client {
fn child_storage_keys( fn child_storage_keys(
&self, &self,
id: &BlockId<Block>, id: &<Block as BlockT>::Hash,
child_info: &ChildInfo, child_info: &ChildInfo,
key_prefix: &StorageKey, key_prefix: &StorageKey,
) -> sp_blockchain::Result<Vec<StorageKey>> { ) -> sp_blockchain::Result<Vec<StorageKey>> {
...@@ -401,7 +469,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client { ...@@ -401,7 +469,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client {
fn child_storage_keys_iter<'a>( fn child_storage_keys_iter<'a>(
&self, &self,
id: &BlockId<Block>, id: &<Block as BlockT>::Hash,
child_info: ChildInfo, child_info: ChildInfo,
prefix: Option<&'a StorageKey>, prefix: Option<&'a StorageKey>,
start_key: Option<&StorageKey>, start_key: Option<&StorageKey>,
...@@ -416,7 +484,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client { ...@@ -416,7 +484,7 @@ impl sc_client_api::StorageProvider<Block, super::FullBackend> for Client {
fn child_storage_hash( fn child_storage_hash(
&self, &self,
id: &BlockId<Block>, id: &<Block as BlockT>::Hash,
child_info: &ChildInfo, child_info: &ChildInfo,
key: &StorageKey, key: &StorageKey,
) -> sp_blockchain::Result<Option<<Block as BlockT>::Hash>> { ) -> sp_blockchain::Result<Option<<Block as BlockT>::Hash>> {
...@@ -433,6 +501,7 @@ impl sc_client_api::UsageProvider<Block> for Client { ...@@ -433,6 +501,7 @@ impl sc_client_api::UsageProvider<Block> for Client {
/// Generates inherent data for benchmarking G1, GTest and GDev. /// Generates inherent data for benchmarking G1, GTest and GDev.
/// ///
/// Not to be used outside of benchmarking since it returns mocked values. /// Not to be used outside of benchmarking since it returns mocked values.
#[cfg(feature = "runtime-benchmarks")]
pub fn benchmark_inherent_data( pub fn benchmark_inherent_data(
) -> std::result::Result<sp_inherents::InherentData, sp_inherents::Error> { ) -> std::result::Result<sp_inherents::InherentData, sp_inherents::Error> {
use sp_inherents::InherentDataProvider; use sp_inherents::InherentDataProvider;
......
...@@ -46,23 +46,23 @@ version = "3.1.5" ...@@ -46,23 +46,23 @@ version = "3.1.5"
default-features = false default-features = false
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
optional = true optional = true
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
[dependencies.frame-support] [dependencies.frame-support]
default-features = false default-features = false
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
[dependencies.frame-system] [dependencies.frame-system]
default-features = false default-features = false
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
[dependencies.pallet-session] [dependencies.pallet-session]
default-features = false default-features = false
features = ["historical"] features = ["historical"]
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
[dependencies.serde] [dependencies.serde]
version = "1.0.101" version = "1.0.101"
...@@ -72,22 +72,22 @@ features = ["derive"] ...@@ -72,22 +72,22 @@ features = ["derive"]
[dependencies.sp-core] [dependencies.sp-core]
default-features = false default-features = false
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
[dependencies.sp-runtime] [dependencies.sp-runtime]
default-features = false default-features = false
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
[dependencies.sp-staking] [dependencies.sp-staking]
default-features = false default-features = false
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
[dependencies.sp-std] [dependencies.sp-std]
default-features = false default-features = false
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
### DOC ### ### DOC ###
...@@ -104,4 +104,4 @@ version = '1.0.119' ...@@ -104,4 +104,4 @@ version = '1.0.119'
[dev-dependencies.sp-io] [dev-dependencies.sp-io]
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
...@@ -63,7 +63,6 @@ pub mod pallet { ...@@ -63,7 +63,6 @@ pub mod pallet {
pub trait Config: pub trait Config:
frame_system::Config + pallet_session::Config + pallet_session::historical::Config frame_system::Config + pallet_session::Config + pallet_session::historical::Config
{ {
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
type KeysWrapper: Parameter + Into<Self::Keys>; type KeysWrapper: Parameter + Into<Self::Keys>;
type IsMember: IsMember<Self::MemberId>; type IsMember: IsMember<Self::MemberId>;
type OnNewSession: OnNewSession; type OnNewSession: OnNewSession;
...@@ -77,7 +76,8 @@ pub mod pallet { ...@@ -77,7 +76,8 @@ pub mod pallet {
type MaxOfflineSessions: Get<SessionIndex>; type MaxOfflineSessions: Get<SessionIndex>;
type MemberId: Copy + Ord + MaybeSerializeDeserialize + Parameter; type MemberId: Copy + Ord + MaybeSerializeDeserialize + Parameter;
type MemberIdOf: Convert<Self::AccountId, Option<Self::MemberId>>; type MemberIdOf: Convert<Self::AccountId, Option<Self::MemberId>>;
type RemoveMemberOrigin: EnsureOrigin<Self::Origin>; type RemoveMemberOrigin: EnsureOrigin<Self::RuntimeOrigin>;
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
} }
// GENESIS STUFF // // GENESIS STUFF //
...@@ -396,7 +396,7 @@ pub mod pallet { ...@@ -396,7 +396,7 @@ pub mod pallet {
Self::deposit_event(Event::MemberRemoved(member_id)); Self::deposit_event(Event::MemberRemoved(member_id));
let _ = T::OnRemovedMember::on_removed_member(member_id); let _ = T::OnRemovedMember::on_removed_member(member_id);
0 Weight::zero()
} }
pub(super) fn expire_memberships(current_session_index: SessionIndex) { pub(super) fn expire_memberships(current_session_index: SessionIndex) {
for member_id in MembersExpireOn::<T>::take(current_session_index) { for member_id in MembersExpireOn::<T>::take(current_session_index) {
......
...@@ -71,8 +71,8 @@ impl system::Config for Test { ...@@ -71,8 +71,8 @@ impl system::Config for Test {
type BlockWeights = (); type BlockWeights = ();
type BlockLength = (); type BlockLength = ();
type DbWeight = (); type DbWeight = ();
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
type Call = Call; type RuntimeCall = RuntimeCall;
type Index = u64; type Index = u64;
type BlockNumber = u64; type BlockNumber = u64;
type Hash = H256; type Hash = H256;
...@@ -80,7 +80,7 @@ impl system::Config for Test { ...@@ -80,7 +80,7 @@ impl system::Config for Test {
type AccountId = AccountId; type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header; type Header = Header;
type Event = Event; type RuntimeEvent = RuntimeEvent;
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
type Version = (); type Version = ();
type PalletInfo = PalletInfo; type PalletInfo = PalletInfo;
...@@ -118,7 +118,7 @@ impl ShouldEndSession<u64> for TestShouldEndSession { ...@@ -118,7 +118,7 @@ impl ShouldEndSession<u64> for TestShouldEndSession {
} }
impl pallet_session::Config for Test { impl pallet_session::Config for Test {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type ValidatorId = u64; type ValidatorId = u64;
type ValidatorIdOf = ConvertInto; type ValidatorIdOf = ConvertInto;
type ShouldEndSession = TestShouldEndSession; type ShouldEndSession = TestShouldEndSession;
...@@ -148,7 +148,6 @@ impl IsMember<u64> for TestIsSmithMember { ...@@ -148,7 +148,6 @@ impl IsMember<u64> for TestIsSmithMember {
} }
impl pallet_authority_members::Config for Test { impl pallet_authority_members::Config for Test {
type Event = Event;
type KeysWrapper = MockSessionKeys; type KeysWrapper = MockSessionKeys;
type IsMember = TestIsSmithMember; type IsMember = TestIsSmithMember;
type MaxAuthorities = ConstU32<4>; type MaxAuthorities = ConstU32<4>;
...@@ -159,6 +158,7 @@ impl pallet_authority_members::Config for Test { ...@@ -159,6 +158,7 @@ impl pallet_authority_members::Config for Test {
type OnNewSession = (); type OnNewSession = ();
type OnRemovedMember = (); type OnRemovedMember = ();
type RemoveMemberOrigin = system::EnsureRoot<u64>; type RemoveMemberOrigin = system::EnsureRoot<u64>;
type RuntimeEvent = RuntimeEvent;
} }
// Build genesis storage according to the mock runtime. // Build genesis storage according to the mock runtime.
......
...@@ -81,11 +81,11 @@ fn test_max_keys_life_rule() { ...@@ -81,11 +81,11 @@ fn test_max_keys_life_rule() {
// Member 3 and 6 rotate their sessions keys // Member 3 and 6 rotate their sessions keys
assert_ok!(AuthorityMembers::set_session_keys( assert_ok!(AuthorityMembers::set_session_keys(
Origin::signed(3), RuntimeOrigin::signed(3),
UintAuthorityId(3).into() UintAuthorityId(3).into()
),); ),);
assert_ok!(AuthorityMembers::set_session_keys( assert_ok!(AuthorityMembers::set_session_keys(
Origin::signed(6), RuntimeOrigin::signed(6),
UintAuthorityId(6).into() UintAuthorityId(6).into()
),); ),);
...@@ -132,7 +132,7 @@ fn test_go_offline() { ...@@ -132,7 +132,7 @@ fn test_go_offline() {
run_to_block(1); run_to_block(1);
// Member 9 should be able to go offline // Member 9 should be able to go offline
assert_ok!(AuthorityMembers::go_offline(Origin::signed(9)),); assert_ok!(AuthorityMembers::go_offline(RuntimeOrigin::signed(9)),);
// Verify state // Verify state
assert_eq!(AuthorityMembers::incoming(), EMPTY); assert_eq!(AuthorityMembers::incoming(), EMPTY);
...@@ -185,7 +185,7 @@ fn test_go_online() { ...@@ -185,7 +185,7 @@ fn test_go_online() {
// Member 12 should be able to set their session keys // Member 12 should be able to set their session keys
assert_ok!(AuthorityMembers::set_session_keys( assert_ok!(AuthorityMembers::set_session_keys(
Origin::signed(12), RuntimeOrigin::signed(12),
UintAuthorityId(12).into(), UintAuthorityId(12).into(),
)); ));
assert_eq!( assert_eq!(
...@@ -198,7 +198,7 @@ fn test_go_online() { ...@@ -198,7 +198,7 @@ fn test_go_online() {
); );
// Member 12 should be able to go online // Member 12 should be able to go online
assert_ok!(AuthorityMembers::go_online(Origin::signed(12)),); assert_ok!(AuthorityMembers::go_online(RuntimeOrigin::signed(12)),);
// Verify state // Verify state
assert_eq!(AuthorityMembers::incoming(), vec![12]); assert_eq!(AuthorityMembers::incoming(), vec![12]);
...@@ -237,27 +237,27 @@ fn test_too_many_authorities() { ...@@ -237,27 +237,27 @@ fn test_too_many_authorities() {
// Member 12 sets their session keys then go online // Member 12 sets their session keys then go online
assert_ok!(AuthorityMembers::set_session_keys( assert_ok!(AuthorityMembers::set_session_keys(
Origin::signed(12), RuntimeOrigin::signed(12),
UintAuthorityId(12).into(), UintAuthorityId(12).into(),
)); ));
assert_eq!(AuthorityMembers::authorities_counter(), 3); assert_eq!(AuthorityMembers::authorities_counter(), 3);
assert_ok!(AuthorityMembers::go_online(Origin::signed(12)),); assert_ok!(AuthorityMembers::go_online(RuntimeOrigin::signed(12)),);
// Member 15 can't go online because there is already 4 authorities "planned" // Member 15 can't go online because there is already 4 authorities "planned"
assert_ok!(AuthorityMembers::set_session_keys( assert_ok!(AuthorityMembers::set_session_keys(
Origin::signed(15), RuntimeOrigin::signed(15),
UintAuthorityId(15).into(), UintAuthorityId(15).into(),
)); ));
assert_eq!(AuthorityMembers::authorities_counter(), 4); assert_eq!(AuthorityMembers::authorities_counter(), 4);
assert_noop!( assert_noop!(
AuthorityMembers::go_online(Origin::signed(15)), AuthorityMembers::go_online(RuntimeOrigin::signed(15)),
Error::<Test>::TooManyAuthorities, Error::<Test>::TooManyAuthorities,
); );
// If member 3 go_offline, member 15 can go_online // If member 3 go_offline, member 15 can go_online
assert_ok!(AuthorityMembers::go_offline(Origin::signed(3)),); assert_ok!(AuthorityMembers::go_offline(RuntimeOrigin::signed(3)),);
assert_eq!(AuthorityMembers::authorities_counter(), 3); assert_eq!(AuthorityMembers::authorities_counter(), 3);
assert_ok!(AuthorityMembers::go_online(Origin::signed(15)),); assert_ok!(AuthorityMembers::go_online(RuntimeOrigin::signed(15)),);
assert_eq!(AuthorityMembers::authorities_counter(), 4); assert_eq!(AuthorityMembers::authorities_counter(), 4);
}); });
} }
...@@ -269,16 +269,16 @@ fn test_go_online_then_go_offline_in_same_session() { ...@@ -269,16 +269,16 @@ fn test_go_online_then_go_offline_in_same_session() {
// Member 12 sets their session keys & go online // Member 12 sets their session keys & go online
assert_ok!(AuthorityMembers::set_session_keys( assert_ok!(AuthorityMembers::set_session_keys(
Origin::signed(12), RuntimeOrigin::signed(12),
UintAuthorityId(12).into(), UintAuthorityId(12).into(),
)); ));
assert_ok!(AuthorityMembers::go_online(Origin::signed(12)),); assert_ok!(AuthorityMembers::go_online(RuntimeOrigin::signed(12)),);
run_to_block(2); run_to_block(2);
// Member 12 should be able to go offline at the same session to "cancel" their previous // Member 12 should be able to go offline at the same session to "cancel" their previous
// action // action
assert_ok!(AuthorityMembers::go_offline(Origin::signed(12)),); assert_ok!(AuthorityMembers::go_offline(RuntimeOrigin::signed(12)),);
// Verify state // Verify state
assert_eq!(AuthorityMembers::incoming(), EMPTY); assert_eq!(AuthorityMembers::incoming(), EMPTY);
...@@ -301,12 +301,12 @@ fn test_go_offline_then_go_online_in_same_session() { ...@@ -301,12 +301,12 @@ fn test_go_offline_then_go_online_in_same_session() {
run_to_block(6); run_to_block(6);
// Member 9 go offline // Member 9 go offline
assert_ok!(AuthorityMembers::go_offline(Origin::signed(9)),); assert_ok!(AuthorityMembers::go_offline(RuntimeOrigin::signed(9)),);
run_to_block(7); run_to_block(7);
// Member 9 should be able to go online at the same session to "cancel" their previous action // Member 9 should be able to go online at the same session to "cancel" their previous action
assert_ok!(AuthorityMembers::go_online(Origin::signed(9)),); assert_ok!(AuthorityMembers::go_online(RuntimeOrigin::signed(9)),);
// Verify state // Verify state
assert_eq!(AuthorityMembers::incoming(), EMPTY); assert_eq!(AuthorityMembers::incoming(), EMPTY);
......
...@@ -23,7 +23,7 @@ pub trait OnNewSession { ...@@ -23,7 +23,7 @@ pub trait OnNewSession {
impl OnNewSession for () { impl OnNewSession for () {
fn on_new_session(_: SessionIndex) -> Weight { fn on_new_session(_: SessionIndex) -> Weight {
0 Weight::zero()
} }
} }
...@@ -33,6 +33,6 @@ pub trait OnRemovedMember<MemberId> { ...@@ -33,6 +33,6 @@ pub trait OnRemovedMember<MemberId> {
impl<MemberId> OnRemovedMember<MemberId> for () { impl<MemberId> OnRemovedMember<MemberId> for () {
fn on_removed_member(_: MemberId) -> Weight { fn on_removed_member(_: MemberId) -> Weight {
0 Weight::zero()
} }
} }
...@@ -39,17 +39,17 @@ version = "3.1.5" ...@@ -39,17 +39,17 @@ version = "3.1.5"
default-features = false default-features = false
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
optional = true optional = true
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
[dependencies.frame-support] [dependencies.frame-support]
default-features = false default-features = false
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
[dependencies.frame-system] [dependencies.frame-system]
default-features = false default-features = false
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
[dependencies.serde] [dependencies.serde]
version = "1.0.101" version = "1.0.101"
...@@ -59,17 +59,17 @@ features = ["derive"] ...@@ -59,17 +59,17 @@ features = ["derive"]
[dependencies.sp-core] [dependencies.sp-core]
default-features = false default-features = false
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
[dependencies.sp-runtime] [dependencies.sp-runtime]
default-features = false default-features = false
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
[dependencies.sp-std] [dependencies.sp-std]
default-features = false default-features = false
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
### DOC ### ### DOC ###
...@@ -86,4 +86,4 @@ version = '1.0.2' ...@@ -86,4 +86,4 @@ version = '1.0.2'
[dev-dependencies.sp-io] [dev-dependencies.sp-io]
default-features = false default-features = false
git = 'https://github.com/duniter/substrate' git = 'https://github.com/duniter/substrate'
branch = 'duniter-substrate-v0.9.26' branch = 'duniter-substrate-v0.9.32'
...@@ -30,6 +30,7 @@ pub use types::*; ...@@ -30,6 +30,7 @@ pub use types::*;
use crate::traits::*; use crate::traits::*;
use codec::Codec; use codec::Codec;
use frame_support::pallet_prelude::*;
use frame_support::traits::StorageVersion; use frame_support::traits::StorageVersion;
use sp_runtime::traits::AtLeast32BitUnsigned; use sp_runtime::traits::AtLeast32BitUnsigned;
use sp_std::{fmt::Debug, vec::Vec}; use sp_std::{fmt::Debug, vec::Vec};
...@@ -37,7 +38,6 @@ use sp_std::{fmt::Debug, vec::Vec}; ...@@ -37,7 +38,6 @@ use sp_std::{fmt::Debug, vec::Vec};
#[frame_support::pallet] #[frame_support::pallet]
pub mod pallet { pub mod pallet {
use super::*; use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*; use frame_system::pallet_prelude::*;
use sp_runtime::traits::{Convert, Saturating}; use sp_runtime::traits::{Convert, Saturating};
use sp_std::collections::btree_map::BTreeMap; use sp_std::collections::btree_map::BTreeMap;
...@@ -56,8 +56,6 @@ pub mod pallet { ...@@ -56,8 +56,6 @@ pub mod pallet {
#[pallet::constant] #[pallet::constant]
/// Minimum duration between two certifications issued by the same issuer /// Minimum duration between two certifications issued by the same issuer
type CertPeriod: Get<Self::BlockNumber>; type CertPeriod: Get<Self::BlockNumber>;
/// Because this pallet emits events, it depends on the runtime's definition of an event.
type Event: From<Event<Self, I>> + IsType<<Self as frame_system::Config>::Event>;
/// A short identity index. /// A short identity index.
type IdtyIndex: Parameter type IdtyIndex: Parameter
+ Member + Member
...@@ -71,7 +69,7 @@ pub mod pallet { ...@@ -71,7 +69,7 @@ pub mod pallet {
/// Something that give the owner key of an identity /// Something that give the owner key of an identity
type OwnerKeyOf: Convert<Self::IdtyIndex, Option<Self::AccountId>>; type OwnerKeyOf: Convert<Self::IdtyIndex, Option<Self::AccountId>>;
/// ///
type IsCertAllowed: IsCertAllowed<Self::IdtyIndex>; type CheckCertAllowed: CheckCertAllowed<Self::IdtyIndex>;
#[pallet::constant] #[pallet::constant]
/// Maximum number of active certifications by issuer /// Maximum number of active certifications by issuer
type MaxByIssuer: Get<u32>; type MaxByIssuer: Get<u32>;
...@@ -82,6 +80,9 @@ pub mod pallet { ...@@ -82,6 +80,9 @@ pub mod pallet {
type OnNewcert: OnNewcert<Self::IdtyIndex>; type OnNewcert: OnNewcert<Self::IdtyIndex>;
/// Handler for Removed event /// Handler for Removed event
type OnRemovedCert: OnRemovedCert<Self::IdtyIndex>; type OnRemovedCert: OnRemovedCert<Self::IdtyIndex>;
/// Because this pallet emits events, it depends on the runtime's definition of an event.
type RuntimeEvent: From<Event<Self, I>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
#[pallet::constant] #[pallet::constant]
/// Duration of validity of a certification /// Duration of validity of a certification
type ValidityPeriod: Get<Self::BlockNumber>; type ValidityPeriod: Get<Self::BlockNumber>;
...@@ -127,8 +128,9 @@ pub mod pallet { ...@@ -127,8 +128,9 @@ pub mod pallet {
.or_insert(IdtyCertMeta { .or_insert(IdtyCertMeta {
issued_count: 0, issued_count: 0,
next_issuable_on: sp_runtime::traits::Zero::zero(), next_issuable_on: sp_runtime::traits::Zero::zero(),
received_count: issuers.len() as u32, received_count: 0,
}); })
.received_count = issuers.len() as u32;
let mut issuers_: Vec<_> = Vec::with_capacity(issuers.len()); let mut issuers_: Vec<_> = Vec::with_capacity(issuers.len());
for (issuer, maybe_removable_on) in issuers { for (issuer, maybe_removable_on) in issuers {
...@@ -138,7 +140,7 @@ pub mod pallet { ...@@ -138,7 +140,7 @@ pub mod pallet {
.or_insert(IdtyCertMeta { .or_insert(IdtyCertMeta {
issued_count: 0, issued_count: 0,
next_issuable_on: sp_runtime::traits::Zero::zero(), next_issuable_on: sp_runtime::traits::Zero::zero(),
received_count: issuers.len() as u32, received_count: 0,
}) })
.issued_count += 1; .issued_count += 1;
...@@ -210,6 +212,8 @@ pub mod pallet { ...@@ -210,6 +212,8 @@ pub mod pallet {
pub type StorageCertsRemovableOn<T: Config<I>, I: 'static = ()> = pub type StorageCertsRemovableOn<T: Config<I>, I: 'static = ()> =
StorageMap<_, Twox64Concat, T::BlockNumber, Vec<(T::IdtyIndex, T::IdtyIndex)>, OptionQuery>; StorageMap<_, Twox64Concat, T::BlockNumber, Vec<(T::IdtyIndex, T::IdtyIndex)>, OptionQuery>;
// EVENTS //
#[pallet::event] #[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)] #[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config<I>, I: 'static = ()> { pub enum Event<T: Config<I>, I: 'static = ()> {
...@@ -238,12 +242,12 @@ pub mod pallet { ...@@ -238,12 +242,12 @@ pub mod pallet {
}, },
} }
// ERRORS //
#[pallet::error] #[pallet::error]
pub enum Error<T, I = ()> { pub enum Error<T, I = ()> {
/// An identity cannot certify itself /// An identity cannot certify itself
CannotCertifySelf, CannotCertifySelf,
/// Certification non autorisée
CertNotAllowed,
/// This identity has already issued the maximum number of certifications /// This identity has already issued the maximum number of certifications
IssuedTooManyCert, IssuedTooManyCert,
/// Issuer not found /// Issuer not found
...@@ -325,10 +329,7 @@ pub mod pallet { ...@@ -325,10 +329,7 @@ pub mod pallet {
ensure!(issuer_owner_key == who, DispatchError::BadOrigin); ensure!(issuer_owner_key == who, DispatchError::BadOrigin);
// Verify compatibility with other pallets state // Verify compatibility with other pallets state
ensure!( T::CheckCertAllowed::check_cert_allowed(issuer, receiver)?;
T::IsCertAllowed::is_cert_allowed(issuer, receiver),
Error::<T, I>::CertNotAllowed
);
// Verify rule MinReceivedCertToBeAbleToIssueCert // Verify rule MinReceivedCertToBeAbleToIssueCert
let issuer_idty_cert_meta = <StorageIdtyCertMeta<T, I>>::get(issuer); let issuer_idty_cert_meta = <StorageIdtyCertMeta<T, I>>::get(issuer);
...@@ -438,7 +439,7 @@ pub mod pallet { ...@@ -438,7 +439,7 @@ pub mod pallet {
Ok(().into()) Ok(().into())
} }
fn prune_certifications(block_number: T::BlockNumber) -> Weight { fn prune_certifications(block_number: T::BlockNumber) -> Weight {
let mut total_weight: Weight = 0; let mut total_weight = Weight::zero();
if let Some(certs) = StorageCertsRemovableOn::<T, I>::take(block_number) { if let Some(certs) = StorageCertsRemovableOn::<T, I>::take(block_number) {
for (issuer, receiver) in certs { for (issuer, receiver) in certs {
...@@ -453,7 +454,7 @@ pub mod pallet { ...@@ -453,7 +454,7 @@ pub mod pallet {
receiver: T::IdtyIndex, receiver: T::IdtyIndex,
block_number_opt: Option<T::BlockNumber>, block_number_opt: Option<T::BlockNumber>,
) -> Weight { ) -> Weight {
let mut total_weight: Weight = 0; let mut total_weight = Weight::zero();
let mut removed = false; let mut removed = false;
CertsByReceiver::<T, I>::mutate_exists(receiver, |issuers_opt| { CertsByReceiver::<T, I>::mutate_exists(receiver, |issuers_opt| {
let issuers = issuers_opt.get_or_insert(Vec::with_capacity(0)); let issuers = issuers_opt.get_or_insert(Vec::with_capacity(0));
...@@ -505,14 +506,11 @@ pub mod pallet { ...@@ -505,14 +506,11 @@ pub mod pallet {
} }
impl<T: Config<I>, I: 'static> SetNextIssuableOn<T::BlockNumber, T::IdtyIndex> for Pallet<T, I> { impl<T: Config<I>, I: 'static> SetNextIssuableOn<T::BlockNumber, T::IdtyIndex> for Pallet<T, I> {
fn set_next_issuable_on( fn set_next_issuable_on(idty_index: T::IdtyIndex, next_issuable_on: T::BlockNumber) -> Weight {
idty_index: T::IdtyIndex,
next_issuable_on: T::BlockNumber,
) -> frame_support::pallet_prelude::Weight {
<StorageIdtyCertMeta<T, I>>::mutate_exists(idty_index, |cert_meta_opt| { <StorageIdtyCertMeta<T, I>>::mutate_exists(idty_index, |cert_meta_opt| {
let cert_meta = cert_meta_opt.get_or_insert(IdtyCertMeta::default()); let cert_meta = cert_meta_opt.get_or_insert(IdtyCertMeta::default());
cert_meta.next_issuable_on = next_issuable_on; cert_meta.next_issuable_on = next_issuable_on;
}); });
0 Weight::zero()
} }
} }
...@@ -55,8 +55,8 @@ impl system::Config for Test { ...@@ -55,8 +55,8 @@ impl system::Config for Test {
type BlockWeights = (); type BlockWeights = ();
type BlockLength = (); type BlockLength = ();
type DbWeight = (); type DbWeight = ();
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
type Call = Call; type RuntimeCall = RuntimeCall;
type Index = u64; type Index = u64;
type BlockNumber = BlockNumber; type BlockNumber = BlockNumber;
type Hash = H256; type Hash = H256;
...@@ -64,7 +64,7 @@ impl system::Config for Test { ...@@ -64,7 +64,7 @@ impl system::Config for Test {
type AccountId = AccountId; type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header; type Header = Header;
type Event = Event; type RuntimeEvent = RuntimeEvent;
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
type Version = (); type Version = ();
type PalletInfo = PalletInfo; type PalletInfo = PalletInfo;
...@@ -78,12 +78,12 @@ impl system::Config for Test { ...@@ -78,12 +78,12 @@ impl system::Config for Test {
} }
pub struct EnsureRoot; pub struct EnsureRoot;
impl frame_support::traits::EnsureOrigin<(Origin, IdtyIndex, IdtyIndex)> for EnsureRoot { impl frame_support::traits::EnsureOrigin<(RuntimeOrigin, IdtyIndex, IdtyIndex)> for EnsureRoot {
type Success = (); type Success = ();
fn try_origin( fn try_origin(
o: (Origin, IdtyIndex, IdtyIndex), o: (RuntimeOrigin, IdtyIndex, IdtyIndex),
) -> Result<Self::Success, (Origin, IdtyIndex, IdtyIndex)> { ) -> Result<Self::Success, (RuntimeOrigin, IdtyIndex, IdtyIndex)> {
match o.0.clone().into() { match o.0.clone().into() {
Ok(system::RawOrigin::Root) => Ok(()), Ok(system::RawOrigin::Root) => Ok(()),
_ => Err(o), _ => Err(o),
...@@ -100,14 +100,14 @@ parameter_types! { ...@@ -100,14 +100,14 @@ parameter_types! {
impl pallet_certification::Config for Test { impl pallet_certification::Config for Test {
type CertPeriod = CertPeriod; type CertPeriod = CertPeriod;
type Event = Event;
type IdtyIndex = IdtyIndex; type IdtyIndex = IdtyIndex;
type OwnerKeyOf = sp_runtime::traits::ConvertInto; type OwnerKeyOf = sp_runtime::traits::ConvertInto;
type IsCertAllowed = (); type CheckCertAllowed = ();
type MaxByIssuer = MaxByIssuer; type MaxByIssuer = MaxByIssuer;
type MinReceivedCertToBeAbleToIssueCert = MinReceivedCertToBeAbleToIssueCert; type MinReceivedCertToBeAbleToIssueCert = MinReceivedCertToBeAbleToIssueCert;
type OnNewcert = (); type OnNewcert = ();
type OnRemovedCert = (); type OnRemovedCert = ();
type RuntimeEvent = RuntimeEvent;
type ValidityPeriod = ValidityPeriod; type ValidityPeriod = ValidityPeriod;
} }
......