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
Select Git revision
  • 1000i100-test
  • 105_gitlab_container_registry
  • cgeek/issue-297-cpu
  • ci_cache
  • debug/podman
  • elois-compose-metrics
  • elois-duniter-storage
  • elois-smoldot
  • feature/dc-dump
  • feature/distance-rule
  • feature/show_milestone
  • fix-252
  • fix_picked_up_file_in_runtime_release
  • gdev-800-tests
  • hugo-release/runtime-701
  • hugo-tmp-dockerfile-cache
  • hugo/195-doc
  • hugo/195-graphql-schema
  • hugo/distance-precompute
  • hugo/endpoint-gossip
  • hugo/tmp-0.9.1
  • master
  • network/gdev-800
  • network/gdev-802
  • network/gdev-803
  • network/gdev-900
  • network/gtest-1000
  • pini-check-password
  • release/client-800.2
  • release/hugo-chainspec-gdev5
  • release/poka-chainspec-gdev5
  • release/poka-chainspec-gdev5-pini-docker
  • release/runtime-100
  • release/runtime-200
  • release/runtime-300
  • release/runtime-400
  • release/runtime-401
  • release/runtime-500
  • release/runtime-600
  • release/runtime-700
  • release/runtime-701
  • release/runtime-800
  • runtime/gtest-1000
  • tests/distance-with-oracle
  • tuxmain/anonymous-tx
  • tuxmain/benchmark-distance
  • tuxmain/fix-change-owner-key
  • update-docker-compose-rpc-squid-names
  • upgradable-multisig
  • gdev-800
  • gdev-800-0.8.0
  • gdev-802
  • gdev-803
  • gdev-900-0.10.0
  • gdev-900-0.10.1
  • gdev-900-0.9.0
  • gdev-900-0.9.1
  • gdev-900-0.9.2
  • gtest-1000
  • gtest-1000-0.11.0
  • gtest-1000-0.11.1
  • runtime-100
  • runtime-101
  • runtime-102
  • runtime-103
  • runtime-104
  • runtime-105
  • runtime-200
  • runtime-201
  • runtime-300
  • runtime-301
  • runtime-302
  • runtime-303
  • runtime-400
  • runtime-401
  • runtime-500
  • runtime-600
  • runtime-700
  • runtime-701
  • runtime-800
  • runtime-800-backup
  • runtime-800-bis
  • runtime-801
  • v0.1.0
  • v0.2.0
  • v0.3.0
  • v0.4.0
  • v0.4.1
88 results

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
Select Git revision
  • distance
  • elois-ci-binary-release
  • elois-compose-metrics
  • elois-duniter-storage
  • elois-fix-85
  • elois-opti-cert
  • elois-remove-renewable-period
  • elois-rework-certs
  • elois-smoldot
  • elois-substrate-v0.9.23
  • elois-technical-commitee
  • hugo-cucumber-identity
  • master
  • no-bootnodes
  • poc-oneshot-accounts
  • release/runtime-100
  • release/runtime-200
  • ts-types
  • ud-time-64
  • runtime-100
  • runtime-101
  • runtime-102
  • runtime-103
  • runtime-104
  • runtime-105
  • runtime-200
  • runtime-201
  • v0.1.0
28 results
Show changes
[package]
name = "weight-analyzer"
authors.workspace = true
edition.workspace = true
homepage.workspace = true
license.workspace = true
repository.workspace = true
version.workspace = true
[lib]
name = "weightanalyzer"
path = "src/lib.rs"
[dependencies]
convert_case = { workspace = true }
glob = { workspace = true }
serde = { workspace = true, features = ["derive"] }
subweight-core = { workspace = true }
[features]
std = []
use convert_case::{Case, Casing};
use glob::glob;
use serde::Serialize;
use std::{collections::HashMap, ops::Div, path::Path};
use subweight_core::{
parse::{
overhead::Weight,
pallet::{ChromaticExtrinsic, ComponentRange},
storage::Weights,
},
scope::Scope,
term::Term,
};
// Substrate default maximum weight of a block in nanoseconds.
// Since the maximum block weight is one-third of the execution time,
// it corresponds to a block time of 6 seconds.
const MAX_BLOCK_WEIGHT_NS: f64 = 2_000_000_000_000.;
pub struct MaxBlockWeight(f64);
impl Default for MaxBlockWeight {
fn default() -> Self {
MaxBlockWeight(MAX_BLOCK_WEIGHT_NS)
}
}
impl Div<&MaxBlockWeight> for f64 {
type Output = Self;
fn div(self, max_block_weight: &MaxBlockWeight) -> Self::Output {
self / max_block_weight.0
}
}
impl MaxBlockWeight {
pub fn new<T: Into<f64>>(value: T) -> Self {
MaxBlockWeight(value.into())
}
}
#[derive(Clone, Debug, Serialize)]
pub struct WeightInfo {
pub weight: u128,
pub relative_weight: f64,
}
/// Returns a HashMap <pallet_name, <extrinsic_name, weigh_info>>
/// of the analyzed weights.
///
/// # Arguments
///
/// * `folder_path` - A Path to a folder where the weight files are stored.
/// `paritydb_weights.rs` is mandatory and pallet weights should start by
/// `pallet_`.
/// * `max_block_weight` - The maximal weight of a block.
///
/// # Examples
///
/// ```
/// use weightanalyzer::analyze_weight;
/// use std::path::Path;
/// use weightanalyzer::MaxBlockWeight;
/// let weight_by_pallet = analyze_weight(Path::new("../../runtime/gdev/src/weights/"), &MaxBlockWeight::default());
/// println!("{:?}", weight_by_pallet);
/// ```
pub fn analyze_weight(
folder_path: &Path,
max_block_weight: &MaxBlockWeight,
) -> Result<HashMap<String, HashMap<String, WeightInfo>>, String> {
let pallet_weights = read_pallet_weight(folder_path)?;
let db_weight = read_db_weight(folder_path)?;
let overhead_weights = read_overhead_weight(folder_path)?;
// Initialize scope with db weights
let mut scope = Scope::from_substrate();
scope = scope.with_storage_weights(db_weight.weights.read, db_weight.weights.write);
process(pallet_weights, scope, max_block_weight, &overhead_weights)
}
fn read_pallet_weight(folder_path: &Path) -> Result<Vec<Vec<ChromaticExtrinsic>>, String> {
let mut parsed_files = Vec::new();
for path in glob(folder_path.join("*").to_str().expect("Invalid pallet path"))
.expect("Invalid pallet pattern")
.filter_map(Result::ok)
{
let file = subweight_core::parse::pallet::parse_file(&path);
if let Ok(file) = file {
parsed_files.push(file);
}
}
if parsed_files.is_empty() {
return Err("No pallet found".into());
}
Ok(parsed_files)
}
fn read_db_weight(folder_path: &Path) -> Result<Weights, String> {
subweight_core::parse::storage::parse_file(folder_path.join("paritydb_weights.rs").as_path())
}
fn read_overhead_weight(folder_path: &Path) -> Result<Weight, String> {
subweight_core::parse::overhead::parse_file(folder_path.join("extrinsic_weights.rs").as_path())
}
fn evaluate_weight(
extrinsic: ChromaticExtrinsic,
scope: &mut Scope<Term<u128>>,
max_block_weight: &MaxBlockWeight,
overhead: &Weight,
) -> Result<(String, String, WeightInfo), String> {
// Extend the scope with the maximum value of the complexity parameter.
if let Some(params) = extrinsic.comp_ranges {
params
.iter()
.for_each(|(key, val): (&String, &ComponentRange)| {
scope.put_var(key.as_str(), Term::Scalar(val.max.into()));
});
}
// Evaluate the weight
let mut weight = extrinsic
.term
.simplify(subweight_core::Dimension::Time)
.expect("Can't evaluate")
.eval(scope)?;
// Add base extrinsic overhead
if let Weight::ExtrinsicBase(i) = overhead {
weight += i
.simplify(subweight_core::Dimension::Time)
.expect("Can't evaluate")
.eval(scope)?;
}
let relative_weight = (weight as f64) / max_block_weight * 100.;
Ok((
extrinsic
.pallet
.to_case(Case::Title)
.replace("Pallet", "")
.replace(".rs", "")
.chars()
.filter(|c| !c.is_whitespace())
.collect(),
extrinsic.name,
WeightInfo {
weight,
relative_weight,
},
))
}
fn process(
pallet_weights: Vec<Vec<ChromaticExtrinsic>>,
mut scope: Scope<Term<u128>>,
max_block_weight: &MaxBlockWeight,
overhead: &Weight,
) -> Result<HashMap<String, HashMap<String, WeightInfo>>, String> {
let mut weight_by_pallet: HashMap<String, HashMap<String, WeightInfo>> = HashMap::new();
for i in pallet_weights {
for j in i {
let (pallet, extrinsic, weight) =
evaluate_weight(j, &mut scope, max_block_weight, overhead)?;
if let Some(i) = weight_by_pallet.get_mut(&pallet) {
i.insert(extrinsic, weight);
} else {
weight_by_pallet.insert(pallet, HashMap::from([(extrinsic, weight)]));
}
}
}
Ok(weight_by_pallet)
}
#[cfg(test)]
mod tests {
use crate::{analyze_weight, MaxBlockWeight};
use std::path::Path;
#[test]
fn should_works() {
let weight_by_pallet = analyze_weight(
Path::new("../../runtime/gdev/src/weights/"),
&MaxBlockWeight::default(),
);
assert!(
weight_by_pallet
.clone()
.unwrap()
.get("Balances")
.unwrap()
.len()
== 10
); // 8 extrinsics in pallet
println!("{:?}", weight_by_pallet); // cargo test -- --nocapture
}
#[test]
#[should_panic]
fn should_not_works() {
let _ = analyze_weight(Path::new(""), &MaxBlockWeight::default()).unwrap();
}
}
# Runtimes
Duniter client can run several runtimes.
- [ĞDev](https://doc-duniter-org.ipns.pagu.re/gdev_runtime/index.html) is for development purpose
- [ĞTest](https://doc-duniter-org.ipns.pagu.re/gtest_runtime/index.html) is to prepare Ğ1 migration and test features before deploying on Ǧ1
- [Ğ1](https://doc-duniter-org.ipns.pagu.re/g1_runtime/index.html) is the production currency
[package]
name = 'common-runtime'
description = 'Common code shared between all runtimes'
license = 'GPL-3.0-only'
version = '0.8.0-dev'
authors = ['Axiom-Team Developers <https://axiom-team.fr>']
edition = "2021"
name = "common-runtime"
description = "Common code shared between all runtimes"
license.workspace = true
authors.workspace = true
edition.workspace = true
version.workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[features]
default = ["std"]
no_std = []
constant-fees = []
runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
'frame-support/runtime-benchmarks',
'frame-system-benchmarking',
'frame-system/runtime-benchmarks',
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"pallet-authority-members/runtime-benchmarks",
"pallet-babe/runtime-benchmarks",
'pallet-balances/runtime-benchmarks',
'pallet-certification/runtime-benchmarks',
'pallet-duniter-wot/runtime-benchmarks',
'pallet-identity/runtime-benchmarks',
'pallet-membership/runtime-benchmarks',
'pallet-multisig/runtime-benchmarks',
'pallet-proxy/runtime-benchmarks',
'pallet-treasury/runtime-benchmarks',
'sp-runtime/runtime-benchmarks',
"pallet-balances/runtime-benchmarks",
"pallet-certification/runtime-benchmarks",
"pallet-distance/runtime-benchmarks",
"pallet-duniter-account/runtime-benchmarks",
"pallet-duniter-wot/runtime-benchmarks",
"pallet-identity/runtime-benchmarks",
"pallet-membership/runtime-benchmarks",
"pallet-offences/runtime-benchmarks",
"pallet-provide-randomness/runtime-benchmarks",
"pallet-quota/runtime-benchmarks",
"pallet-smith-members/runtime-benchmarks",
"pallet-timestamp/runtime-benchmarks",
"pallet-transaction-payment/runtime-benchmarks",
"pallet-treasury/runtime-benchmarks",
"pallet-universal-dividend/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"sp-staking/runtime-benchmarks",
]
std = [
'codec/std',
'duniter-primitives/std',
'frame-support/std',
'frame-system/std',
'log/std',
'pallet-authority-members/std',
'pallet-babe/std',
'pallet-balances/std',
'pallet-certification/std',
'pallet-duniter-account/std',
'pallet-duniter-wot/std',
'pallet-grandpa/std',
'pallet-identity/std',
'pallet-membership/std',
'pallet-multisig/std',
'pallet-provide-randomness/std',
'pallet-proxy/std',
'pallet-scheduler/std',
'pallet-timestamp/std',
'pallet-treasury/std',
'pallet-universal-dividend/std',
"codec/std",
"duniter-primitives/std",
"frame-benchmarking/std",
"frame-support/std",
"frame-system/std",
"pallet-authority-members/std",
"pallet-babe/std",
"pallet-balances/std",
"pallet-certification/std",
"pallet-distance/std",
"pallet-duniter-account/std",
"pallet-duniter-wot/std",
"pallet-identity/std",
"pallet-membership/std",
"pallet-offences/std",
"pallet-provide-randomness/std",
"pallet-quota/std",
"pallet-session/std",
"pallet-smith-members/std",
"pallet-timestamp/std",
"pallet-treasury/std",
"pallet-universal-dividend/std",
"scale-info/std",
"serde/std",
"serde_derive",
'sp-arithmetic/std',
'sp-core/std',
'sp-membership/std',
'sp-runtime/std',
'sp-std/std',
"sp-arithmetic/std",
"sp-consensus-babe/std",
"sp-core/std",
"sp-membership/std",
"sp-runtime/std",
"sp-staking/std",
"sp-weights/std",
]
try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
"pallet-authority-members/try-runtime",
"pallet-babe/try-runtime",
"pallet-grandpa/try-runtime",
"pallet-balances/try-runtime",
"pallet-certification/try-runtime",
"pallet-distance/try-runtime",
"pallet-duniter-account/try-runtime",
"pallet-duniter-wot/try-runtime",
"pallet-identity/try-runtime",
"pallet-membership/try-runtime",
"pallet-offences/try-runtime",
"pallet-provide-randomness/try-runtime",
"pallet-quota/try-runtime",
"pallet-session/try-runtime",
"pallet-smith-members/try-runtime",
"pallet-timestamp/try-runtime",
"pallet-transaction-payment/try-runtime",
"pallet-treasury/try-runtime",
"pallet-universal-dividend/try-runtime",
"sp-membership/try-runtime",
"sp-runtime/try-runtime",
]
[dependencies]
duniter-primitives = { path = '../../primitives/duniter', default-features = false }
pallet-authority-members = { path = '../../pallets/authority-members', default-features = false }
pallet-certification = { path = '../../pallets/certification', default-features = false }
pallet-duniter-account = { path = '../../pallets/duniter-account', default-features = false }
pallet-duniter-wot = { path = '../../pallets/duniter-wot', default-features = false }
pallet-identity = { path = '../../pallets/identity', default-features = false }
pallet-membership = { path = '../../pallets/membership', default-features = false }
pallet-provide-randomness = { path = '../../pallets/provide-randomness', default-features = false }
pallet-upgrade-origin = { path = '../../pallets/upgrade-origin', default-features = false }
pallet-universal-dividend = { path = '../../pallets/universal-dividend', default-features = false }
sp-membership = { path = '../../primitives/membership', default-features = false }
# Crates.io
codec = { package = "parity-scale-codec", version = "3.1.5", features = ["derive"], default-features = false }
log = { version = "0.4.14", default-features = false }
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
serde = { version = "1.0.101", default-features = false }
serde_derive = { version = "1.0.101", optional = true }
smallvec = "1.6.1"
# Substrate
frame-support = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
frame-system = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
pallet-babe = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
pallet-balances = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
pallet-grandpa = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
pallet-multisig = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
pallet-proxy = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
pallet-scheduler = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
pallet-session = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
pallet-timestamp = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
pallet-treasury = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
sp-arithmetic = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
sp-consensus-babe = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
sp-core = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
sp-runtime = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
sp-std = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
# substrate benchmarks
frame-benchmarking = { git = "https://github.com/duniter/substrate", branch = 'duniter-substrate-v0.9.23', default-features = false, optional = true }
frame-system-benchmarking = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false, optional = true }
# TODO: there is a bad coupling in substrate that force to add this dependency
sp-staking = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.23', default-features = false }
codec = { workspace = true, features = ["derive"] }
duniter-primitives = { workspace = true }
frame-benchmarking = { workspace = true }
frame-support = { workspace = true }
frame-system = { workspace = true }
pallet-authority-members = { workspace = true }
pallet-babe = { workspace = true }
pallet-balances = { workspace = true }
pallet-certification = { workspace = true }
pallet-distance = { workspace = true }
pallet-duniter-account = { workspace = true }
pallet-duniter-wot = { workspace = true }
pallet-identity = { workspace = true }
pallet-membership = { workspace = true }
pallet-offences = { workspace = true }
pallet-provide-randomness = { workspace = true }
pallet-quota = { workspace = true }
pallet-session = { workspace = true }
pallet-smith-members = { workspace = true }
pallet-timestamp = { workspace = true }
pallet-transaction-payment = { workspace = true }
pallet-treasury = { workspace = true }
pallet-universal-dividend = { workspace = true }
scale-info = { workspace = true, features = ["derive"] }
serde = { workspace = true }
smallvec = { workspace = true }
sp-arithmetic = { workspace = true }
sp-consensus-babe = { workspace = true }
sp-core = { workspace = true }
sp-membership = { workspace = true }
sp-runtime = { workspace = true }
sp-staking = { workspace = true }
sp-weights = { workspace = true }
// Copyright 2021 Axiom-Team
//
// This file is part of Substrate-Libre-Currency.
// This file is part of Duniter-v2S.
//
// Substrate-Libre-Currency is free software: you can redistribute it and/or modify
// Duniter-v2S is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Substrate-Libre-Currency is distributed in the hope that it will be useful,
// Duniter-v2S is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>.
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
// This file is not formatted automatically due to the nested macro definition.
// It can be formatted by commenting out the last line, the first five lines,
// and then running `rustfmt` on `runtime/common/src/apis.rs`.
#[macro_export]
macro_rules! runtime_apis {
{$($custom:tt)*} => {
($($custom:tt)*) => {
impl_runtime_apis! {
$($custom)*
......@@ -27,18 +30,18 @@ macro_rules! runtime_apis {
}
impl sp_consensus_babe::BabeApi<Block> for Runtime {
fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration {
fn configuration() -> sp_consensus_babe::BabeConfiguration {
// The choice of `c` parameter (where `1 - c` represents the
// probability of a slot being empty), is done in accordance to the
// slot duration and expected target block time, for safely
// resisting network delays of maximum two seconds.
// <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>
use frame_support::traits::Get as _;
sp_consensus_babe::BabeGenesisConfiguration {
sp_consensus_babe::BabeConfiguration {
slot_duration: Babe::slot_duration(),
epoch_length: EpochDuration::get(),
c: BABE_GENESIS_EPOCH_CONFIG.c,
genesis_authorities: Babe::authorities().to_vec(),
authorities: Babe::authorities().to_vec(),
randomness: Babe::randomness(),
allowed_slots: BABE_GENESIS_EPOCH_CONFIG.allowed_slots,
}
......@@ -73,10 +76,7 @@ macro_rules! runtime_apis {
) -> Option<()> {
let key_owner_proof = key_owner_proof.decode()?;
Babe::submit_unsigned_equivocation_report(
equivocation_proof,
key_owner_proof,
)
Babe::submit_unsigned_equivocation_report(equivocation_proof, key_owner_proof)
}
}
......@@ -89,7 +89,7 @@ macro_rules! runtime_apis {
Executive::execute_block(block)
}
fn initialize_block(header: &<Block as BlockT>::Header) {
fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
Executive::initialize_block(header)
}
}
......@@ -98,6 +98,14 @@ macro_rules! runtime_apis {
fn metadata() -> OpaqueMetadata {
OpaqueMetadata::new(Runtime::metadata().into())
}
fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
Runtime::metadata_at_version(version)
}
fn metadata_versions() -> Vec<u32> {
Runtime::metadata_versions()
}
}
impl sp_block_builder::BlockBuilder<Block> for Runtime {
......@@ -109,9 +117,7 @@ macro_rules! runtime_apis {
Executive::finalize_block()
}
fn inherent_extrinsics(
data: sp_inherents::InherentData,
) -> Vec<<Block as BlockT>::Extrinsic> {
fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
data.create_extrinsics()
}
......@@ -130,8 +136,7 @@ macro_rules! runtime_apis {
block_hash: <Block as BlockT>::Hash,
) -> TransactionValidity {
// Filtered calls should not enter the tx pool.
if !<Runtime as frame_system::Config>::BaseCallFilter::contains(&tx.function)
{
if !<Runtime as frame_system::Config>::BaseCallFilter::contains(&tx.function) {
return sp_runtime::transaction_validity::InvalidTransaction::Call.into();
}
Executive::validate_transaction(source, tx, block_hash)
......@@ -145,9 +150,7 @@ macro_rules! runtime_apis {
}
impl sp_session::SessionKeys<Block> for Runtime {
fn decode_session_keys(
encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
fn decode_session_keys(encoded: Vec<u8>) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
opaque::SessionKeys::decode_into_raw_public_keys(&encoded)
}
......@@ -192,8 +195,7 @@ macro_rules! runtime_apis {
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
for Runtime {
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
fn query_info(
uxt: <Block as BlockT>::Extrinsic,
len: u32,
......@@ -207,64 +209,101 @@ macro_rules! runtime_apis {
) -> pallet_transaction_payment::FeeDetails<Balance> {
TransactionPayment::query_fee_details(uxt, len)
}
fn query_weight_to_fee(weight: Weight) -> Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> Balance {
TransactionPayment::length_to_fee(length)
}
}
impl pallet_duniter_account::DuniterAccountApi<Block, Balance> for Runtime {
fn estimate_cost(
uxt: <Block as BlockT>::Extrinsic,
) -> pallet_duniter_account::EstimatedCost<Balance> {
pallet_duniter_account::Pallet::<Runtime>::estimate_cost(uxt)
}
}
impl pallet_universal_dividend::UniversalDividendApi<Block, AccountId, Balance> for Runtime {
fn account_balances(account: AccountId) -> pallet_universal_dividend::AccountBalances<Balance> {
UniversalDividend::account_balances(&account)
}
}
impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
frame_support::genesis_builder_helper::build_state::<RuntimeGenesisConfig>(config)
}
fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
frame_support::genesis_builder_helper::get_preset::<RuntimeGenesisConfig>(id, |_| None)
}
fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
vec![]
}
}
#[cfg(feature = "try-runtime")]
impl frame_try_runtime::TryRuntime<Block> for Runtime {
fn on_runtime_upgrade() -> (Weight, Weight) {
log::info!("try-runtime::on_runtime_upgrade.");
let weight = Executive::try_runtime_upgrade().unwrap();
fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
let weight = Executive::try_runtime_upgrade(checks).unwrap();
(weight, BlockWeights::get().max_block)
}
fn execute_block_no_check(block: Block) -> Weight {
Executive::execute_block_no_check(block)
fn execute_block(
block: Block,
state_root_check: bool,
signature_check: bool,
select: frame_try_runtime::TryStateSelect,
) -> Weight {
Executive::try_execute_block(block, state_root_check, signature_check, select)
.expect("execute-block failed")
}
}
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(extra: bool) -> (
fn benchmark_metadata(
extra: bool,
) -> (
Vec<frame_benchmarking::BenchmarkList>,
Vec<frame_support::traits::StorageInfo>,
) {
use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};
use frame_benchmarking::{list_benchmark, BenchmarkList, Benchmarking};
use frame_support::traits::StorageInfoTrait;
use frame_system_benchmarking::Pallet as SystemBench;
use frame_benchmarking::baseline::Pallet as Baseline;
use frame_system_benchmarking::{
extensions::Pallet as SystemExtensionsBench, Pallet as SystemBench,
};
use pallet_session_benchmarking::Pallet as SessionBench;
let mut list = Vec::<BenchmarkList>::new();
list_benchmark!(list, extra, frame_system, SystemBench::<Runtime>);
list_benchmark!(list, extra, pallet_balances, Balances);
list_benchmark!(list, extra, pallet_multisig, Multisig);
list_benchmark!(list, extra, pallet_proxy, Proxy);
list_benchmark!(list, extra, pallet_scheduler, Scheduler);
list_benchmark!(list, extra, pallet_timestamp, Timestamp);
list_benchmark!(list, extra, pallet_universal_dividend, UniversalDividend);
list_benchmark!(list, extra, pallet_upgrade_origin, UpgradeOrigin);
list_benchmark!(list, extra, pallet_utility, Utility);
list_benchmarks!(list, extra);
let storage_info = AllPalletsWithSystem::storage_info();
return (list, storage_info)
return (list, storage_info);
}
fn dispatch_benchmark(
config: frame_benchmarking::BenchmarkConfig
) -> Result<
Vec<frame_benchmarking::BenchmarkBatch>,
sp_runtime::RuntimeString,
> {
use frame_benchmarking::{Benchmarking, BenchmarkBatch, TrackedStorageKey};
// Trying to add benchmarks directly to some pallets caused cyclic dependency issues.
// To get around that, we separated the benchmarks into its own crate.
use frame_system_benchmarking::Pallet as SystemBench;
use frame_benchmarking::baseline::Pallet as Baseline;
config: frame_benchmarking::BenchmarkConfig,
) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, scale_info::prelude::string::String> {
use frame_benchmarking::{baseline::Pallet as Baseline, BenchmarkBatch, Benchmarking};
use frame_support::traits::{TrackedStorageKey, WhitelistedStorageKeys};
use frame_system_benchmarking::{
extensions::Pallet as SystemExtensionsBench, Pallet as SystemBench,
};
use pallet_session_benchmarking::Pallet as SessionBench;
impl pallet_session_benchmarking::Config for Runtime {}
impl frame_system_benchmarking::Config for Runtime {}
impl frame_benchmarking::baseline::Config for Runtime {}
let whitelist: Vec<TrackedStorageKey> = vec![
/*let whitelist: Vec<TrackedStorageKey> = vec![
// Block Number
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),
// Total Issuance
......@@ -277,24 +316,17 @@ macro_rules! runtime_apis {
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),
// Treasury Account
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95ecffd7b6c0f78751baa9d281e0bfa3a6d6f646c70792f74727372790000000000000000000000000000000000000000").to_vec().into(),
];
];*/
let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
let mut batches = Vec::<BenchmarkBatch>::new();
let params = (&config, &whitelist);
add_benchmark!(params, batches, frame_system, SystemBench::<Runtime>);
add_benchmark!(params, batches, pallet_balances, Balances);
add_benchmark!(params, batches, pallet_multisig, Multisig);
add_benchmark!(params, batches, pallet_proxy, Proxy);
add_benchmark!(params, batches, pallet_scheduler, Scheduler);
add_benchmark!(params, batches, pallet_timestamp, Timestamp);
add_benchmark!(params, batches, pallet_universal_dividend, UniversalDividend);
add_benchmark!(params, batches, pallet_upgrade_origin, UpgradeOrigin);
add_benchmark!(params, batches, pallet_utility, Utility);
if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
Ok(batches)
}
add_benchmarks!(params, batches);
if batches.is_empty() {
return Err("Benchmark not found for this pallet.".into());
}
Ok(batches)
}
};
}
}};}
// Copyright 2021 Axiom-Team
//
// This file is part of Duniter-v2S.
//
// Duniter-v2S is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Duniter-v2S is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
#![cfg(feature = "runtime-benchmarks")]
#[macro_export]
macro_rules! benchmarks_config {
() => {
#[macro_use]
extern crate frame_benchmarking;
pub use pallet_collective::RawOrigin;
type WorstOrigin = RawOrigin<AccountId, TechnicalCommitteeInstance>;
mod benches {
define_benchmarks!(
[pallet_certification, Certification]
[pallet_distance, Distance]
[pallet_oneshot_account, OneshotAccount]
[pallet_universal_dividend, UniversalDividend]
[pallet_provide_randomness, ProvideRandomness]
[pallet_upgrade_origin, UpgradeOrigin]
[pallet_duniter_account, Account]
[pallet_quota, Quota]
[pallet_identity, Identity]
[pallet_membership, Membership]
[pallet_smith_members, SmithMembers]
[pallet_authority_members, AuthorityMembers]
// Substrate
[frame_system_extensions, SystemExtensionsBench::<Runtime>]
[pallet_balances, Balances]
[frame_benchmarking::baseline, Baseline::<Runtime>]
[pallet_collective, TechnicalCommittee]
[pallet_session, SessionBench::<Runtime>]
[pallet_im_online, ImOnline]
[pallet_sudo, Sudo]
[pallet_multisig, Multisig]
[pallet_preimage, Preimage]
[pallet_proxy, Proxy]
[pallet_scheduler, Scheduler]
[frame_system, SystemBench::<Runtime>]
[pallet_timestamp, Timestamp]
[pallet_transaction_payment, TransactionPayment]
[pallet_treasury, Treasury]
[pallet_utility, Utility]
);
}
};
}
// Copyright 2021 Axiom-Team
//
// This file is part of Substrate-Libre-Currency.
// This file is part of Duniter-v2S.
//
// Substrate-Libre-Currency is free software: you can redistribute it and/or modify
// Duniter-v2S is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Substrate-Libre-Currency is distributed in the hope that it will be useful,
// Duniter-v2S is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>.
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
use crate::{Balance, BlockNumber};
use frame_support::weights::constants::WEIGHT_PER_MICROS;
use frame_support::weights::Weight;
use sp_runtime::Perbill;
/// This determines the average expected block time that we are targeting.
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
/// up by `pallet_babe` to implement `fn slot_duration()`.
///
/// Change this to adjust the block time.
// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
// up by `pallet_babe` to implement `fn slot_duration()`.
// Change this to adjust the block time.
pub const MILLISECS_PER_BLOCK: u64 = 6000;
pub const SECS_PER_BLOCK: u64 = MILLISECS_PER_BLOCK / 1_000;
......@@ -43,7 +40,7 @@ pub const YEARS: BlockNumber = (SECS_PER_YEAR / SECS_PER_BLOCK) as BlockNumber;
// 1 in 4 blocks (on average, not counting collisions) will be primary babe blocks.
pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4);
/// The BABE epoch configuration at genesis.
// The BABE epoch configuration at genesis.
pub const BABE_GENESIS_EPOCH_CONFIG: sp_consensus_babe::BabeEpochConfiguration =
sp_consensus_babe::BabeEpochConfiguration {
c: PRIMARY_PROBABILITY,
......@@ -60,47 +57,3 @@ pub const fn deposit(items: u32, bytes: u32) -> Balance {
// Maximal weight proportion of normal extrinsics per block
pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
// WEIGHTS CONSTANTS //
// Read DB weights
pub const READ_WEIGHTS: Weight = 250 * WEIGHT_PER_MICROS; // ~250 µs
// Write DB weights
pub const WRITE_WEIGHTS: Weight = 1_000 * WEIGHT_PER_MICROS; // ~1000 µs
// Execution cost of everything outside of the call itself:
// signature verification, pre_dispatch and post_dispatch
pub const EXTRINSIC_BASE_WEIGHTS: Weight = READ_WEIGHTS + WRITE_WEIGHTS;
// DB weights
frame_support::parameter_types! {
pub const DbWeight: frame_support::weights::RuntimeDbWeight = frame_support::weights::RuntimeDbWeight {
read: READ_WEIGHTS,
write: WRITE_WEIGHTS,
};
}
// Block weights limits
pub fn block_weights(
expected_block_weight: Weight,
normal_ratio: sp_arithmetic::Perbill,
) -> frame_system::limits::BlockWeights {
let normal_weight = normal_ratio * expected_block_weight;
frame_system::limits::BlockWeights::builder()
.for_class(frame_support::weights::DispatchClass::Normal, |weights| {
weights.base_extrinsic = EXTRINSIC_BASE_WEIGHTS;
weights.max_total = normal_weight.into();
})
.for_class(
frame_support::weights::DispatchClass::Operational,
|weights| {
weights.base_extrinsic = EXTRINSIC_BASE_WEIGHTS;
weights.max_total = expected_block_weight.into();
weights.reserved = (expected_block_weight - normal_weight).into();
},
)
.avg_block_initialization(sp_arithmetic::Perbill::from_percent(10))
.build()
.expect("Fatal error: invalid BlockWeights configuration")
}