Commit Graph

8915 Commits

Author SHA1 Message Date
PG Herveou d38f6e6728 Update benchmarking macros (#3934)
Current benchmarking macro returns a closure with the captured
benchmarked code.
This can cause issues when the benchmarked code has complex lifetime
requirements.

This PR updates the existing macro by injecting the recording parameter
and invoking the start / stop method around the benchmarked block
instead of returning a closure

One other added benefit is that you can write this kind of code now as
well:

```rust
let v;
#[block]
{ v = func.call(); }
dbg!(v); // or assert something on v
```


[Weights compare
link](https://weights.tasty.limo/compare?unit=weight&ignore_errors=true&threshold=10&method=asymptotic&repo=polkadot-sdk&old=pg/fix-weights&new=pg/bench_update&path_pattern=substrate/frame/**/src/weights.rs,polkadot/runtime/*/src/weights/**/*.rs,polkadot/bridges/modules/*/src/weights.rs,cumulus/**/weights/*.rs,cumulus/**/weights/xcm/*.rs,cumulus/**/src/weights.rs)

---------

Co-authored-by: command-bot <>
Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: Alexander Theißen <alex.theissen@me.com>
2024-04-10 06:44:46 +00:00
PG Herveou 2d927b0772 Contracts: Fix legacy uapi (#3994)
Fix some broken legacy definitions of pallet_contracts_uapi storage host
functions
2024-04-10 05:05:21 +00:00
Sebastian Kunert df818d2974 Move cumulus zombienet tests to aura & async backing (#3568)
Cumulus test-parachain node and test runtime were still using relay
chain consensus and 12s blocktimes. With async backing around the corner
on the major chains we should switch our tests too.

Also needed to nicely test the changes coming to collators in #3168.

### Changes Overview
- Followed the [migration
guide](https://wiki.polkadot.network/docs/maintain-guides-async-backing)
for async backing for the cumulus-test-runtime
- Adjusted the cumulus-test-service to use the correct import-queue,
lookahead collator etc.
- The block validation function now uses the Aura Ext Executor so that
the seal of the block is validated
- Previous point requires that we seal block before calling into
`validate_block`, I introduced a helper function for that
- Test client adjusted to provide a slot to the relay chain proof and
the aura pre-digest
2024-04-09 16:53:30 +00:00
Alexandru Vasile 598e95577d rpc-v2/transaction: Generate Invalid events and add tests (#3784)
This PR ensures that the transaction API generates an `Invalid` events
for transaction bytes that fail to decode.

The spec mentioned the `Invalid` event at the jsonrpc error section,
however this spec PR makes things clearer:
- https://github.com/paritytech/json-rpc-interface-spec/pull/146

While at it have discovered an inconsistency with the generated events.
The drop event from the transaction pool was incorrectly mapped to the
`invalid` event.

Added tests for the API stabilize the API soon:
- https://github.com/paritytech/json-rpc-interface-spec/pull/144


Closes: https://github.com/paritytech/polkadot-sdk/issues/3083


cc @paritytech/subxt-team

---------

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>
2024-04-09 13:57:44 +00:00
Dmitry Markin a26d25d5c7 Detect closed notification substreams instead of evicting all peers (#3983)
This PR brings the fix
https://github.com/paritytech/substrate/pull/13396 to polkadot-sdk.

In the past, due to insufficient inbound slot count on polkadot &
kusama, this fix led to low peer count. The situation has improved since
then after changing the default ratio between `--in-peers` &
`--out-peers`.

Nevertheless, it's expected that the reported total peer count with this
fix is going to be lower than without it. This should be seen as the
correct number of working connections reported, as opposed to also
reporting already closed connections, and not as lower count of working
connections with peers.

This PR also removes the peer eviction mechanism, as closed substream
detection is a more granular way of detecting peers that stopped syncing
with us.

The burn-in has been already performed as part of testing these changes
in https://github.com/paritytech/polkadot-sdk/pull/3426.

---------

Co-authored-by: Aaro Altonen <a.altonen@hotmail.com>
2024-04-09 12:40:52 +00:00
Alexandru Vasile b1c9209a6c peer_store: Increase peer ban time until escapes banned threshold (#4031)
This is a tiny PR to increase the time a peer remains banned.

A peer is banned when the reputation drops below a threshold.
With every second, the peer reputation is exponentially decayed towards
zero.

For the previous setup:
- decaying to zero from (i32::MAX or i32::MIN) would take 948 seconds
(15mins 48seconds)
- from i32::MIN to escaping the banned threshold would take 10 seconds
This means we are decaying reputation a bit too aggressive and
misbehaving peers can misbehave again in 10 seconds.
Another side effect of this is that we have encountered multiple
warnings caused by a few misbehaving peers.

In the new setup:
- decaying to zero from (i32::MAX or i32::MIN) would take 3544 seconds
(59 minutes)
- from i32::MIN to escaping the banned threshold would take ~69 seconds

This is a followup of:
- https://github.com/paritytech/polkadot-sdk/pull/4000.

### Testing Done
- Created a misbehaving client with
[subp2p-explorer](https://github.com/lexnv/subp2p-explorer), the client
is banned for approx 69seconds until it is allowed to connect again.

cc @paritytech/networking

---------

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>
2024-04-09 11:24:49 +00:00
Facundo Farall 4e73c0fcd3 Upgrade trie-db from 0.28.0 to 0.29.0 (#3982)
# Description
- What does this PR do?
1. Upgrades `trie-db`'s version to the latest release. This release
includes, among others, an implementation of `DoubleEndedIterator` for
the `TrieDB` struct, allowing to iterate both backwards and forwards
within the leaves of a trie.
2. Upgrades `trie-bench` to `0.39.0` for compatibility.
3. Upgrades `criterion` to `0.5.1` for compatibility.
- Why are these changes needed?
Besides keeping up with the upgrade of `trie-db`, this specifically adds
the functionality of iterating back on the leafs of a trie, with
`sp-trie`. In a project we're currently working on, this comes very
handy to verify a Merkle proof that is the response to a challenge. The
challenge is a random hash that (most likely) will not be an existing
leaf in the trie. So the challenged user, has to provide a Merkle proof
of the previous and next existing leafs in the trie, that surround the
random challenged hash.

Without having DoubleEnded iterators, we're forced to iterate until we
find the first existing leaf, like so:
```rust
        // ************* VERIFIER (RUNTIME) *************
        // Verify proof. This generates a partial trie based on the proof and
        // checks that the root hash matches the `expected_root`.
        let (memdb, root) = proof.to_memory_db(Some(&root)).unwrap();
        let trie = TrieDBBuilder::<LayoutV1<RefHasher>>::new(&memdb, &root).build();

        // Print all leaf node keys and values.
        println!("\nPrinting leaf nodes of partial tree...");
        for key in trie.key_iter().unwrap() {
            if key.is_ok() {
                println!("Leaf node key: {:?}", key.clone().unwrap());

                let val = trie.get(&key.unwrap());

                if val.is_ok() {
                    println!("Leaf node value: {:?}", val.unwrap());
                } else {
                    println!("Leaf node value: None");
                }
            }
        }

        println!("RECONSTRUCTED TRIE {:#?}", trie);

        // Create an iterator over the leaf nodes.
        let mut iter = trie.iter().unwrap();

        // First element with a value should be the previous existing leaf to the challenged hash.
        let mut prev_key = None;
        for element in &mut iter {
            if element.is_ok() {
                let (key, _) = element.unwrap();
                prev_key = Some(key);
                break;
            }
        }
        assert!(prev_key.is_some());

        // Since hashes are `Vec<u8>` ordered in big-endian, we can compare them directly.
        assert!(prev_key.unwrap() <= challenge_hash.to_vec());

        // The next element should exist (meaning there is no other existing leaf between the
        // previous and next leaf) and it should be greater than the challenged hash.
        let next_key = iter.next().unwrap().unwrap().0;
        assert!(next_key >= challenge_hash.to_vec());
```

With DoubleEnded iterators, we can avoid that, like this:
```rust
        // ************* VERIFIER (RUNTIME) *************
        // Verify proof. This generates a partial trie based on the proof and
        // checks that the root hash matches the `expected_root`.
        let (memdb, root) = proof.to_memory_db(Some(&root)).unwrap();
        let trie = TrieDBBuilder::<LayoutV1<RefHasher>>::new(&memdb, &root).build();

        // Print all leaf node keys and values.
        println!("\nPrinting leaf nodes of partial tree...");
        for key in trie.key_iter().unwrap() {
            if key.is_ok() {
                println!("Leaf node key: {:?}", key.clone().unwrap());

                let val = trie.get(&key.unwrap());

                if val.is_ok() {
                    println!("Leaf node value: {:?}", val.unwrap());
                } else {
                    println!("Leaf node value: None");
                }
            }
        }

        // println!("RECONSTRUCTED TRIE {:#?}", trie);
        println!("\nChallenged key: {:?}", challenge_hash);

        // Create an iterator over the leaf nodes.
        let mut double_ended_iter = trie.into_double_ended_iter().unwrap();

        // First element with a value should be the previous existing leaf to the challenged hash.
        double_ended_iter.seek(&challenge_hash.to_vec()).unwrap();
        let next_key = double_ended_iter.next_back().unwrap().unwrap().0;
        let prev_key = double_ended_iter.next_back().unwrap().unwrap().0;

        // Since hashes are `Vec<u8>` ordered in big-endian, we can compare them directly.
        println!("Prev key: {:?}", prev_key);
        assert!(prev_key <= challenge_hash.to_vec());

        println!("Next key: {:?}", next_key);
        assert!(next_key >= challenge_hash.to_vec());
```
- How were these changes implemented and what do they affect?
All that is needed for this functionality to be exposed is changing the
version number of `trie-db` in all the `Cargo.toml`s applicable, and
re-exporting some additional structs from `trie-db` in `sp-trie`.

---------

Co-authored-by: Bastian Köcher <git@kchr.de>
2024-04-09 10:47:33 +00:00
PG Herveou b6231c79ca Contracts: Refactor API to use WeightMeter (#2943)
Update the Contracts API to use `WeightMeter`, as it simplifies the code
and makes it easier to reason about, rather than taking a mutable weight
or returning a tuple with the weight consumed

---------

Co-authored-by: Alexander Theißen <alex.theissen@me.com>
2024-04-09 10:22:54 +00:00
Ankan 10ed76437f Nomination pool configurations can be managed by custom origin (#3959)
closes https://github.com/paritytech/polkadot-sdk/issues/3894

Allows Nomination Pool configuration to be set by a custom origin
instead of root.

In runtimes, we would set this to be `StakingAdmin`, same as for
pallet-staking.

---------

Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
2024-04-09 10:14:19 +00:00
gupnik 0e27b881a4 Fixes validation for SkipCheckIfFeeless extension (#3993)
During validation, `SkipCheckIfFeeless` should check if the call is
`feeless` and delegate to the wrapped extension if not.
2024-04-09 08:35:46 +00:00
Léa Narzis d733c77ee2 Adapt RemoteExternalities and its related types to be used with generic hash parameters (#3953)
Closes  https://github.com/paritytech/polkadot-sdk/issues/3737

---------

Co-authored-by: command-bot <>
Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: Bastian Köcher <git@kchr.de>
2024-04-08 21:56:41 +00:00
Aaro Altonen 80616f6d03 Integrate litep2p into Polkadot SDK (#2944)
[litep2p](https://github.com/altonen/litep2p) is a libp2p-compatible P2P
networking library. It supports all of the features of `rust-libp2p`
that are currently being utilized by Polkadot SDK.

Compared to `rust-libp2p`, `litep2p` has a quite different architecture
which is why the new `litep2p` network backend is only able to use a
little of the existing code in `sc-network`. The design has been mainly
influenced by how we'd wish to structure our networking-related code in
Polkadot SDK: independent higher-levels protocols directly communicating
with the network over links that support bidirectional backpressure. A
good example would be `NotificationHandle`/`RequestResponseHandle`
abstractions which allow, e.g., `SyncingEngine` to directly communicate
with peers to announce/request blocks.

I've tried running `polkadot --network-backend litep2p` with a few
different peer configurations and there is a noticeable reduction in
networking CPU usage. For high load (`--out-peers 200`), networking CPU
usage goes down from ~110% to ~30% (80 pp) and for normal load
(`--out-peers 40`), the usage goes down from ~55% to ~18% (37 pp).

These should not be taken as final numbers because:

a) there are still some low-hanging optimization fruits, such as
enabling [receive window
auto-tuning](https://github.com/libp2p/rust-yamux/pull/176), integrating
`Peerset` more closely with `litep2p` or improving memory usage of the
WebSocket transport
b) fixing bugs/instabilities that incorrectly cause `litep2p` to do less
work will increase the networking CPU usage
c) verification in a more diverse set of tests/conditions is needed

Nevertheless, these numbers should give an early estimate for CPU usage
of the new networking backend.

This PR consists of three separate changes:
* introduce a generic `PeerId` (wrapper around `Multihash`) so that we
don't have use `NetworkService::PeerId` in every part of the code that
uses a `PeerId`
* introduce `NetworkBackend` trait, implement it for the libp2p network
stack and make Polkadot SDK generic over `NetworkBackend`
  * implement `NetworkBackend` for litep2p

The new library should be considered experimental which is why
`rust-libp2p` will remain as the default option for the time being. This
PR currently depends on the master branch of `litep2p` but I'll cut a
new release for the library once all review comments have been
addresses.

---------

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>
Co-authored-by: Dmitry Markin <dmitry@markin.tech>
Co-authored-by: Alexandru Vasile <60601340+lexnv@users.noreply.github.com>
Co-authored-by: Alexandru Vasile <alexandru.vasile@parity.io>
2024-04-08 16:44:13 +00:00
Oliver Tale-Yazdi 9543d31474 [FRAME] Runtime Omni Bencher (#3512)
This MR contains two major changes and some maintenance cleanup.  

## 1. Free Standing Pallet Benchmark Runner

Closes https://github.com/paritytech/polkadot-sdk/issues/3045, depends
on your runtime exposing the `GenesisBuilderApi` (like
https://github.com/paritytech/polkadot-sdk/pull/1492).

Introduces a new binary crate: `frame-omni-bencher`.  
It allows to directly benchmark a WASM blob - without needing a node or
chain spec.

This makes it much easier to generate pallet weights and should allow us
to remove bloaty code from the node.
It should work for all FRAME runtimes that dont use 3rd party host calls
or non `BlakeTwo256` block hashing (basically all polkadot parachains
should work).

It is 100% backwards compatible with the old CLI args, when the `v1`
compatibility command is used. This is done to allow for forwards
compatible addition of new commands.

### Example (full example in the Rust docs)

Installing the CLI:
```sh
cargo install --locked --path substrate/utils/frame/omni-bencher
frame-omni-bencher --help
```

Building the Westend runtime:
```sh
cargo build -p westend-runtime --release --features runtime-benchmarks
```

Benchmarking the runtime:
```sh
frame-omni-bencher v1 benchmark pallet --runtime target/release/wbuild/westend-runtime/westend_runtime.compact.compressed.wasm --all
```

## 2. Building the Benchmark Genesis State in the Runtime

Closes https://github.com/paritytech/polkadot-sdk/issues/2664

This adds `--runtime` and `--genesis-builder=none|runtime|spec`
arguments to the `benchmark pallet` command to make it possible to
generate the genesis storage by the runtime. This can be used with both
the node and the freestanding benchmark runners. It utilizes the new
`GenesisBuilder` RA and depends on having
https://github.com/paritytech/polkadot-sdk/pull/3412 deployed.

## 3. Simpler args for `PalletCmd::run`

You can do three things here to integrate the changes into your node:
- nothing: old code keeps working as before but emits a deprecated
warning
- delete: remove the pallet benchmarking code from your node and use the
omni-bencher instead
- patch: apply the patch below and keep using as currently. This emits a
deprecated warning at runtime, since it uses the old way to generate a
genesis state, but is the smallest change.

```patch
runner.sync_run(|config| cmd
-    .run::<HashingFor<Block>, ReclaimHostFunctions>(config)
+    .run_with_spec::<HashingFor<Block>, ReclaimHostFunctions>(Some(config.chain_spec))
)
```

## 4. Maintenance Change
- `pallet-nis` get a `BenchmarkSetup` config item to prepare its
counterparty asset.
- Add percent progress print when running benchmarks.
- Dont immediately exit on benchmark error but try to run as many as
possible and print errors last.

---------

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
2024-04-08 16:03:56 +00:00
Sebastian Kunert fdb1dba2e1 Add best block indicator to informant message + print parent block on import message (#4021)
Sometimes you need to debug some issues just by the logs and reconstruct
what happened.
In these scenarios it would be nice to know if a block was imported as
best block, and what it parent was.
So here I propose to change the output of the informant to this:

```
2024-04-05 20:38:22.004  INFO ⋮substrate: [Parachain]  Imported #18 (0xe7b3…4555 -> 0xbd6f…ced7)    
2024-04-05 20:38:24.005  INFO ⋮substrate: [Parachain]  Imported #19 (0xbd6f…ced7 -> 0x4dd0…d81f)    
2024-04-05 20:38:24.011  INFO ⋮substrate: [jobless-children-5352] 🌟 Imported #42 (0xed2e…27fc -> 0x718f…f30e)    
2024-04-05 20:38:26.005  INFO ⋮substrate: [Parachain]  Imported #20 (0x4dd0…d81f -> 0x6e85…e2b8)    
2024-04-05 20:38:28.004  INFO ⋮substrate: [Parachain] 🌟 Imported #21 (0x6e85…e2b8 -> 0xad53…2a97)    
2024-04-05 20:38:30.004  INFO ⋮substrate: [Parachain] 🌟 Imported #22 (0xad53…2a97 -> 0xa874…890f)    
```

---------

Co-authored-by: Bastian Köcher <git@kchr.de>
2024-04-08 13:30:32 +00:00
Bastian Köcher c1063a530e sc-beefy-consensus: Remove unneeded stream. (#4015)
The stream was just used to communicate from the validator the peer
reports back to the gossip engine. Internally the gossip engine just
forwards these reports to the networking engine. So, we can just do this
directly.

The reporting stream was also pumped [in the worker behind the
engine](https://github.com/paritytech/polkadot-sdk/blob/9d6261892814fa27c97881c0321c008d7340b54b/substrate/client/consensus/beefy/src/worker.rs#L939).
This means if there was a lot of data incoming over the engine, the
reporting stream was almost never processed and thus, it could have
started to grow and we have seen issues around this.

Partly Closes: https://github.com/paritytech/polkadot-sdk/issues/3945
2024-04-08 08:28:42 +00:00
HongKuang bd4471b4fc Fix some typos (#4018)
Signed-off-by: hongkuang <liurenhong@outlook.com>
2024-04-08 04:21:11 +00:00
Squirrel 9940038543 Major bump of tracing-subscriber version (#3891)
I don't think there are any more releases to the 0.2.x versions, so best
we're on the 0.3.x release.

No change on the benchmarks, fast local time is still just as fast as
before:

new version bench:
```
fast_local_time         time:   [30.551 ns 30.595 ns 30.668 ns]
```

old version bench:
```
fast_local_time         time:   [30.598 ns 30.646 ns 30.723 ns]
```

---------

Co-authored-by: Bastian Köcher <git@kchr.de>
2024-04-06 13:54:09 +00:00
Liam Aharon 74d6309c0c Improve frame umbrella crate doc experience (#4007)
1. Add `#[doc(no_inline)]` to frame umbrella crate re-exports that
eventually resolve to `frame_support_procedural` so docs don't look like
the screenshot below and instead link to the proper `frame-support`
docs.
<img width="1512" alt="Screenshot 2024-04-05 at 20 05 01"
src="https://github.com/paritytech/polkadot-sdk/assets/16665596/a41daa4c-ebca-44a4-9fea-f9f336314e13">


2. Remove `"Rust-Analyzer Users: "` prefix from
`frame_support_procedural` doc comments, since these doc comments are
visible in the web documentation and possible to stumble upon especially
when navigating from the frame umbrella crate.

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
2024-04-06 10:02:37 +00:00
Liam Aharon 9d62618928 pallet-uniques: decrement total_deposit when clearing collection metadata (#3976)
Decrements `total_deposit` when collection metadata is cleared in
`pallet-nfts` and `pallet-uniques`.
2024-04-06 05:10:46 +00:00
Sergej Sakac 1c85bfe901 Broker: sale price runtime api (#3485)
Defines a runtime api for `pallet-broker` for getting the current price
of a core if there is an ongoing sale.

Closes: #3413

---------

Co-authored-by: Bastian Köcher <git@kchr.de>
2024-04-05 23:29:35 +00:00
divdeploy a0eed0a6f8 chore: fix some comments (#4004)
Signed-off-by: divdeploy <chenguangxue@outlook.com>
2024-04-05 18:35:57 +00:00
Dónal Murray ba0f8de0c7 [pallet-broker] Fix claim revenue behaviour for zero timeslices (#3997)
This PR adds a check that `max_timeslices > 0` and errors if not. It
also adds a test for this behaviour and cleans up some misleading docs.
2024-04-05 13:18:48 +00:00
Michal Kucharczyk f910a15c1c GenesisConfig presets for runtime (#2714)
The runtime now can provide a number of predefined presets of
`RuntimeGenesisConfig` struct. This presets are intended to be used in
different deployments, e.g.: `local`, `staging`, etc, and should be
included into the corresponding chain-specs.

Having `GenesisConfig` presets in runtime allows to fully decouple node
from runtime types (the problem is described in #1984).

**Summary of changes:**
- The `GenesisBuilder` API was adjusted to enable this functionality
(and provide better naming - #150):
   ```rust
    fn preset_names() -> Vec<PresetId>;
fn get_preset(id: Option<PresetId>) -> Option<serde_json::Value>;
//`None` means default
    fn build_state(value: serde_json::Value);
    pub struct PresetId(Vec<u8>);
   ```

- **Breaking change**: Old `create_default_config` method was removed,
`build_config` was renamed to `build_state`. As a consequence a node
won't be able to interact with genesis config for older runtimes. The
cleanup was made for sake of API simplicity. Also IMO maintaining
compatibility with old API is not so crucial.
- Reference implementation was provided for `substrate-test-runtime` and
`rococo` runtimes. For rococo new
[`genesis_configs_presets`](https://github.com/paritytech/polkadot-sdk/blob/3b41d66b97c5ff0ec4a1989da5ffd8b9f3f588e3/polkadot/runtime/rococo/src/genesis_config_presets.rs#L530)
module was added and is used in `GenesisBuilder`
[_presets-related_](https://github.com/paritytech/polkadot-sdk/blob/3b41d66b97c5ff0ec4a1989da5ffd8b9f3f588e3/polkadot/runtime/rococo/src/lib.rs#L2462-L2485)
methods.

- The `chain-spec-builder` util was also improved and allows to
([_doc_](https://github.com/paritytech/polkadot-sdk/blob/3b41d66b97c5ff0ec4a1989da5ffd8b9f3f588e3/substrate/bin/utils/chain-spec-builder/src/lib.rs#L19)):
   - list presets provided by given runtime (`list-presets`),
- display preset or default config provided by the runtime
(`display-preset`),
   - build chain-spec using named preset (`create ... named-preset`),


- The `ChainSpecBuilder` is extended with
[`with_genesis_config_preset_name`](https://github.com/paritytech/polkadot-sdk/blob/3b41d66b97c5ff0ec4a1989da5ffd8b9f3f588e3/substrate/client/chain-spec/src/chain_spec.rs#L447)
method which allows to build chain-spec using named preset provided by
the runtime. Sample usage on the node side
[here](https://github.com/paritytech/polkadot-sdk/blob/2caffaae803e08a3d5b46c860e8016da023ff4ce/polkadot/node/service/src/chain_spec.rs#L404).

Implementation of #1984.
fixes: #150
part of: #25

---------

Co-authored-by: Sebastian Kunert <skunert49@gmail.com>
Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
2024-04-04 18:30:54 +00:00
Shawn Tabrizi 9d052b7e09 Make BlockNumberProvider::set_block_number available in tests / std (#3974)
This function is currently only exposed to runtime-benchmarks, where it
should be available in all tests.

Also made it available in `std` because this is how `set_block_number`
works in FRAME System, however, not sure if it is needed in the latest
std/no_std paradigm.

---------

Co-authored-by: Bastian Köcher <git@kchr.de>
Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
2024-04-04 16:20:09 +00:00
Liam Aharon bda4e75ac4 Migrate fee payment from Currency to fungible (#2292)
Part of https://github.com/paritytech/polkadot-sdk/issues/226 
Related https://github.com/paritytech/polkadot-sdk/issues/1833

- Deprecate `CurrencyAdapter` and introduce `FungibleAdapter`
- Deprecate `ToStakingPot` and replace usage with `ResolveTo`
- Required creating a new `StakingPotAccountId` struct that implements
`TypedGet` for the staking pot account ID
- Update parachain common utils `DealWithFees`, `ToAuthor` and
`AssetsToBlockAuthor` implementations to use `fungible`
- Update runtime XCM Weight Traders to use `ResolveTo` instead of
`ToStakingPot`
- Update runtime Transaction Payment pallets to use `FungibleAdapter`
instead of `CurrencyAdapter`
- [x] Blocked by https://github.com/paritytech/polkadot-sdk/pull/1296,
needs the `Unbalanced::decrease_balance` fix
2024-04-04 13:56:12 +00:00
Juan Girini bcb4d137c9 [doc] Example MBM pallet (#2119)
## Basic example showcasing a migration using the MBM framework

This PR has been built on top of
https://github.com/paritytech/polkadot-sdk/pull/1781 and adds two new
example crates to the `examples` pallet

### Changes Made:

Added the `pallet-example-mbm` crate: This crate provides a minimal
example of a pallet that uses MBM. It showcases a storage migration
where values are migrated from a `u32` to a `u64`.

---------

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
2024-04-04 11:47:24 +00:00
Liam Aharon 0ef37c7540 Fix Mermaid diagram rendering (#3875)
Closes https://github.com/paritytech/polkadot-sdk/issues/2977

The issue appears to stem from the `aquamarine` crate failing to render
diagrams in re-exported crates.

e.g. as raised
[here](https://github.com/paritytech/polkadot-sdk/issues/2977), diagrams
would render at `frame_support::traits::Hooks` but not the re-exported
doc `frame::traits::Hooks`, even if I added `aquamarine` as a `frame`
crate dependency.

To resolve this, I followed advice in
https://github.com/mersinvald/aquamarine/issues/20 to instead render
mermaid diagrams directly using JS by adding an `after-content.js`.

---

Also fixes compile warnings, enables `--all-features` and disallows
future warnings in CI.

---------

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
Co-authored-by: Bastian Köcher <git@kchr.de>
2024-04-04 11:32:01 +00:00
Lulu 0bbda78d86 Use 0.1.0 as minimum version for crates (#3941)
CI will be enforcing this with next parity-publish release
2024-04-04 09:26:53 +00:00
gupnik 3836376965 Renames frame crate to polkadot-sdk-frame (#3813)
Step in https://github.com/paritytech/polkadot-sdk/issues/3155

Needed for https://github.com/paritytech/eng-automation/issues/6

This PR renames `frame` crate to `polkadot-sdk-frame` as `frame` is not
available on crates.io

---------

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
2024-04-04 02:20:15 +00:00
Alexandru Vasile 287b116c3e chainHead: Ensure reasonable distance between leaf and finalized block (#3562)
This PR ensure that the distance between any leaf and the finalized
block is within a reasonable distance.

For a new subscription, the chainHead has to provide all blocks between
the leaves of the chain and the finalized block.
 When the distance between a leaf and the finalized block is large:
 - The tree route is costly to compute
 - We could deliver an unbounded number of blocks (potentially millions)
(For more details see
https://github.com/paritytech/polkadot-sdk/pull/3445#discussion_r1507210283)

The configuration of the ChainHead is extended with:
- suspend on lagging distance: When the distance between any leaf and
the finalized block is greater than this number, the subscriptions are
suspended for a given duration.
- All active subscriptions are terminated with the `Stop` event, all
blocks are unpinned and data discarded.
- For incoming subscriptions, until the suspended period expires the
subscriptions will immediately receive the `Stop` event.
    - Defaults to 128 blocks
- suspended duration: The amount of time for which subscriptions are
suspended
    - Defaults to 30 seconds
 
 
 cc @paritytech/subxt-team

---------

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>
Co-authored-by: Sebastian Kunert <skunert49@gmail.com>
2024-04-03 11:46:08 +00:00
Bastian Köcher 9b378a2ffe sp-wasm-interface: wasmtime should not be enabled by std (#3954)
Closes: https://github.com/paritytech/polkadot-sdk/issues/3909
2024-04-03 08:35:53 +00:00
Andrei Eres 665e3654ce Remove nextest filtration (#3885)
Fixes
https://github.com/paritytech/polkadot-sdk/issues/3884#issuecomment-2026058687

After moving regression tests to benchmarks
(https://github.com/paritytech/polkadot-sdk/pull/3741) we don't need to
filter tests anymore.

---------

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>
Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: Andrei Sandu <54316454+sandreim@users.noreply.github.com>
Co-authored-by: Alin Dima <alin@parity.io>
Co-authored-by: Andrei Sandu <andrei-mihail@parity.io>
Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: Javier Viola <363911+pepoviola@users.noreply.github.com>
Co-authored-by: Serban Iorga <serban@parity.io>
Co-authored-by: Adrian Catangiu <adrian@parity.io>
Co-authored-by: Bastian Köcher <git@kchr.de>
Co-authored-by: Alexandru Vasile <60601340+lexnv@users.noreply.github.com>
Co-authored-by: Niklas Adolfsson <niklasadolfsson1@gmail.com>
Co-authored-by: Dastan <88332432+dastansam@users.noreply.github.com>
Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
Co-authored-by: Clara van Staden <claravanstaden64@gmail.com>
Co-authored-by: Ron <yrong1997@gmail.com>
Co-authored-by: Vincent Geddes <vincent@snowfork.com>
Co-authored-by: Svyatoslav Nikolsky <svyatonik@gmail.com>
Co-authored-by: Bastian Köcher <info@kchr.de>
2024-04-02 19:27:11 +00:00
Dino Pačandi f88190a520 SortedMembers::add for pallet-membership benchmarks (#3729)
Adds implementation for `SortedMembers::add` for _pallet-membership_
benchmarks.

---------

Co-authored-by: Bastian Köcher <git@kchr.de>
Co-authored-by: command-bot <>
2024-04-02 19:08:02 +00:00
Michal Kucharczyk 0becc45bd8 sp_runtime: TryFrom<RuntimeString> for &str (#3942)
Added `TryFrom<&'a RuntimeString> for &'a str`
2024-04-02 16:06:01 +00:00
Dastan e54279699b migrations: prevent accidentally using unversioned migrations instead of VersionedMigration (#3835)
closes #1324 

#### Problem
Currently, it is possible to accidentally use inner unversioned
migration instead of `VersionedMigration` since both implement
`OnRuntimeUpgrade`.

#### Solution

With this change, we make it clear that value of `Inner` is not intended
to be used directly. It is achieved by bounding `Inner` to new trait
`UncheckedOnRuntimeUpgrade`, which has the same interface (except
`unchecked_` prefix) as `OnRuntimeUpgrade`.

#### `try-runtime` functions

Since developers can implement `try-runtime` for `Inner` value in
`VersionedMigration` and have custom logic for it, I added the same
`try-runtime` functions to `UncheckedOnRuntimeUpgrade`. I looked for a
ways to not duplicate functions, but couldn't find anything that doesn't
significantly change the codebase. So I would appreciate If you have any
suggestions to improve this

cc @liamaharon @xlc 

polkadot address: 16FqwPZ8GRC5U5D4Fu7W33nA55ZXzXGWHwmbnE1eT6pxuqcT

---------

Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
2024-04-02 13:43:09 +00:00
Serban Iorga 8e95a3e1aa Align dependencies with parity-bridges-common (#3937)
Working towards migrating the `parity-bridges-common` repo inside
`polkadot-sdk`. This PR upgrades some dependencies in order to align
them with the versions used in `parity-bridges-common`

Related to
https://github.com/paritytech/parity-bridges-common/issues/2538
2024-04-02 13:41:01 +00:00
Alexandru Vasile 7430f41350 chainHead: Allow methods to be called from within a single connection context and limit connections (#3481)
This PR ensures that the chainHead RPC class can be called only from
within the same connection context.

The chainHead methods are now registered as raw methods. 
- https://github.com/paritytech/jsonrpsee/pull/1297
The concept of raw methods is introduced in jsonrpsee, which is an async
method that exposes the connection ID:
The raw method doesn't have the concept of a blocking method. Previously
blocking methods are now spawning a blocking task to handle their
blocking (ie DB) access. We spawn the same number of tasks as before,
however we do that explicitly.

Another approach would be implementing a RPC middleware that captures
and decodes the method parameters:
- https://github.com/paritytech/polkadot-sdk/pull/3343
However, that approach is prone to errors since the methods are
hardcoded by name. Performace is affected by the double deserialization
that needs to happen to extract the subscription ID we'd like to limit.
Once from the middleware, and once from the methods itself.

This PR paves the way to implement the chainHead connection limiter:
- https://github.com/paritytech/polkadot-sdk/issues/1505
Registering tokens (subscription ID / operation ID) on the
`RpcConnections` could be extended to return an error when the maximum
number of operations is reached.

While at it, have added an integration-test to ensure that chainHead
methods can be called from within the same connection context.

Before this is merged, a new JsonRPC release should be made to expose
the `raw-methods`:
- [x] Use jsonrpsee from crates io (blocked by:
https://github.com/paritytech/jsonrpsee/pull/1297)

Closes: https://github.com/paritytech/polkadot-sdk/issues/3207


cc @paritytech/subxt-team

---------

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>
Co-authored-by: Niklas Adolfsson <niklasadolfsson1@gmail.com>
2024-04-02 13:12:34 +00:00
Adrian Catangiu 5eff3f94be beefy: error logs for validators with dummy keys (#3939)
This outputs:
```
2024-04-02 14:36:02.135 ERROR tokio-runtime-worker beefy: 🥩 for session starting at block 21990151
no BEEFY authority key found in store, you must generate valid session keys
(https://wiki.polkadot.network/docs/maintain-guides-how-to-validate-polkadot#generating-the-session-keys)
```
error log entry, once every session, for nodes running with
`Role::Authority` that have no public BEEFY key in their keystore

---------

Co-authored-by: Bastian Köcher <git@kchr.de>
2024-04-02 12:28:48 +00:00
Sam Johnson 9a62de27a9 Update derive syn parse 0.2.0 (+ docify) (#3920)
derive-syn-parse v0.2.0 came out recently which (finally) adds support
for syn 2x.

Upgrading to this will remove many of the places where syn 1x was still
compiling alongside syn 2x in the polkadot-sdk workspace.

This also upgrades `docify` to 0.2.8 which is the version that upgrades
derive-syn-pasre to 0.2.0.

Additionally, this consolidates the `docify` versions in the repo to all
use the latest, and in one case upgrades to the 0.2x syntax where 0.1.x
was still being used.

---------

Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
2024-04-02 05:53:51 +00:00
Andrei Sandu bf1ca86f87 pallet-scheduler: fix test (#3923)
fix https://github.com/paritytech/polkadot-sdk/issues/3921

---------

Signed-off-by: Andrei Sandu <andrei-mihail@parity.io>
2024-04-01 21:36:18 +00:00
Ross Bulat b772cb576d Pools: Make PermissionlessWithdraw the default claim permission (#3438)
Related Issue https://github.com/paritytech/polkadot-sdk/issues/3398

This PR makes permissionless withdrawing the default option, giving any
network participant access to claim pool rewards on member's behalf. Of
course, members can still opt out of this by setting a `Permissioned`
claim permission.

Permissionless claiming has been a part of the nomination pool pallet
for around 9 months now, with very limited uptake (~4% of total pool
members). 1.6% of pool members are using `PermissionlessAll`, strongly
suggesting it is not wanted - it is too ambiguous and doesn't provide
guidance to claimers.

Stakers expect rewards to be claimed on their behalf by default - I have
expanded upon this in detail within the [accompanying issue's
discussion](https://github.com/paritytech/polkadot-sdk/issues/3398).
Other protocols have this behaviour, whereby staking rewards are
received without the staker having to take any action. From this
perspective, permissionless claiming is not intuitive for pool members.
As evidence of this, over 150,000 DOT is currently unclaimed on
Polkadot, and is growing at a non-linear rate.
2024-04-01 09:35:36 +00:00
Matteo Muraca a2c9ab8c04 Removed pallet::getter usage from pallet-alliance (#3738)
Part of #3326 

cc @kianenigma @ggwpez @liamaharon 

polkadot address: 12poSUQPtcF1HUPQGY3zZu2P8emuW9YnsPduA4XG3oCEfJVp

---------

Signed-off-by: Matteo Muraca <mmuraca247@gmail.com>
Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
2024-04-01 05:17:20 +00:00
Liam Aharon 41257069b0 Tokens in FRAME Docs (#2802)
Closes https://github.com/paritytech/polkadot-sdk-docs/issues/70

WIP PR for an overview of how to develop tokens in FRAME. 

- [x] Tokens in Substrate Ref Doc
  - High-level overview of the token-related logic in FRAME
- Improve docs with better explanation of how holds, freezes, ed, free
balance, etc, all work
- [x] Update `pallet_balances` docs
  - Clearly mark what is deprecated (currency)
- [x] Write fungible trait docs
- [x] Evaluate and if required update `pallet_assets`, `pallet_uniques`,
`pallet_nfts` docs
- [x] Absorb https://github.com/paritytech/polkadot-sdk/pull/2683/
- [x] Audit individual trait method docs, and improve if possible

Feel free to suggest additional TODOs for this PR in the comments

---------

Co-authored-by: Bill Laboon <laboon@users.noreply.github.com>
Co-authored-by: Francisco Aguirre <franciscoaguirreperez@gmail.com>
Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
Co-authored-by: Sebastian Kunert <skunert49@gmail.com>
2024-03-31 09:59:33 +00:00
Dmitry Markin 0d93248473 Fix addresses_to_publish_respects_existing_p2p_protocol test in sc-authority-discovery (#3895)
Fixes https://github.com/paritytech/polkadot-sdk/issues/3887.
2024-03-29 13:13:21 +00:00
Alexandru Gheorghe 5638d1a830 Decorate mpsc-notification-to-protocol with the protocol name (#3873)
Currently, all protocols use the same metric name for
`mpsc-notification-to-protocol` this is bad because we can't actually
tell which protocol might cause problems.

This patch proposes we derive the name of the metric from the protocol
name, so that we have separate metrics for each protocol and properly
detect which one is having problem processing its messages.

---------

Signed-off-by: Alexandru Gheorghe <alexandru.gheorghe@parity.io>
2024-03-29 11:24:26 +00:00
dharjeezy 79b08d8847 Try State Hook for Beefy (#3246)
Part of: https://github.com/paritytech/polkadot-sdk/issues/239

Polkadot address: 12GyGD3QhT4i2JJpNzvMf96sxxBLWymz4RdGCxRH5Rj5agKW
2024-03-28 13:12:14 +00:00
Rodrigo Quelhas 987f1c24b6 Update benchmarking README.md (#3862)
Fix reference links

Co-authored-by: Bastian Köcher <git@kchr.de>
2024-03-28 12:50:06 +00:00
PG Herveou 78b1cab9e8 Contracts: add test builders (#3796)
Cleanup tests (-2.7k lines !) using some builder patterns to build
pallet_contracts api calls
2024-03-28 10:40:06 +00:00
Alessandro Siniscalchi 60846a081f [parachain-template] runtime API Implementations into mod apis (#3817)
This PR significantly refactors the runtime API implementations to
improve project structure, maintainability, and readability. Key changes
include:

1. **Enhancing Visibility**: Adjusts the visibility of
`RUNTIME_API_VERSIONS` in `impl_runtime_apis.rs` to `pub`, making it
accessible throughout the runtime module.
2. **Centralizing API Implementations**: Introduces a new file,
`apis.rs`, within the parachain template's runtime directory.
3. **Streamlining `lib.rs`**: Updates the main runtime library file to
reflect these structural changes. It removes redundant API
implementations and points `VERSION` to the newly exposed
`RUNTIME_API_VERSIONS` from `apis.rs`, simplifying the overall runtime
configuration.

### Motivations Behind the Refactoring:
- **Improved Project Structure**: Centralizing API implementations in
`apis.rs` offers a clearer, more navigable project structure.
- **Better Readability**: Streamlining `lib.rs` and reducing clutter
enhance readability, making it easier for new contributors to understand
the project layout and logic.

### Summary of Changes:
- Made `RUNTIME_API_VERSIONS` public in `impl_runtime_apis.rs`.
- Added `apis.rs` to centralize runtime API implementations.
- Streamlined `lib.rs` to adjust to the refactored project structure.
2024-03-28 09:12:37 +00:00
Tin Chung daf04f0182 Deprecate scheduler traits v1 and v2 (#3718)
This PR add `#[deprecated]` attribute to v1 and v2 of the schedule
trait. Proposed in this issue:
https://github.com/paritytech/polkadot-sdk/issues/3676

```rust
#[allow(deprecated)]
#[deprecated = "traits::schedule::v1 is deprecated. Please use v3 instead."]
pub mod v1 {
...
}

#[allow(deprecated)]
#[deprecated = "traits::schedule::v2 is deprecated. Please use v3 instead."]
pub mod v2 {
...
}
```

polkadot address: 19nSqFQorfF2HxD3oBzWM3oCh4SaCRKWt1yvmgaPYGCo71J

---------

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
2024-03-28 07:56:23 +00:00