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