Markdown linter (#1309)

* Add markdown linting

- add linter default rules
- adapt rules to current code
- fix the code for linting to pass
- add CI check

fix #1243

* Fix markdown for Substrate
* Fix tooling install
* Fix workflow
* Add documentation
* Remove trailing spaces
* Update .github/.markdownlint.yaml

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
* Fix mangled markdown/lists
* Fix captalization issues on known words
This commit is contained in:
Chevdor
2023-09-04 11:02:32 +02:00
committed by GitHub
parent 830fde2a60
commit a30092ab42
271 changed files with 6289 additions and 4450 deletions
+26 -20
View File
@@ -1,27 +1,35 @@
# Substrate &middot; [![GitHub license](https://img.shields.io/badge/license-GPL3%2FApache2-blue)](#LICENSE) [![GitLab Status](https://gitlab.parity.io/parity/mirrors/polkadot-sdk/badges/master/pipeline.svg)](https://gitlab.parity.io/parity/mirrors/polkadot-sdk/-/pipelines) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](docs/CONTRIBUTING.md) [![Stack Exchange](https://img.shields.io/badge/Substrate-Community%20&%20Support-24CC85?logo=stackexchange)](https://substrate.stackexchange.com/)
# Substrate
[![GitHub license](https://img.shields.io/badge/license-GPL3%2FApache2-blue)](#LICENSE)
[![GitLab
Status](https://gitlab.parity.io/parity/mirrors/polkadot-sdk/badges/master/pipeline.svg)](https://gitlab.parity.io/parity/mirrors/polkadot-sdk/-/pipelines)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](docs/CONTRIBUTING.md)
[![Stack
Exchange](https://img.shields.io/badge/Substrate-Community%20&%20Support-24CC85?logo=stackexchange)](https://substrate.stackexchange.com/)
<p align="center">
<img src="/docs/media/sub.gif">
<img src="../substrate/docs/media/sub.gif">
</p>
Substrate is a next-generation framework for blockchain innovation 🚀.
## Getting Started
Head to [docs.substrate.io](https://docs.substrate.io) and follow the
[installation](https://docs.substrate.io/install/) instructions. Then try out one of the
[tutorials](https://docs.substrate.io/tutorials/). Refer to the [Docker instructions](./docker/README.md) to quickly run Substrate, Substrate Node Template, Subkey, or to build a chain spec.
Head to [`docs.substrate.io`](https://docs.substrate.io) and follow the [installation](https://docs.substrate.io/install/)
instructions. Then try out one of the [tutorials](https://docs.substrate.io/tutorials/). Refer to the [Docker
instructions](./docker/README.md) to quickly run Substrate, Substrate Node Template, Subkey, or to build a chain spec.
## Community & Support
Join the highly active and supportive community on the
[Substrate Stack Exchange](https://substrate.stackexchange.com/) to ask questions about use and problems you run into using this software.
Please do report bugs and [issues here](https://github.com/paritytech/polkadot-sdk/issues) for anything you suspect requires action in the source.
Join the highly active and supportive community on the [Substrate Stack Exchange](https://substrate.stackexchange.com/)
to ask questions about use and problems you run into using this software. Please do report bugs and [issues
here](https://github.com/paritytech/polkadot-sdk/issues) for anything you suspect requires action in the source.
## Contributions & Code of Conduct
Please follow the contributions guidelines as outlined in
[`docs/CONTRIBUTING.md`](https://github.com/paritytech/polkadot-sdk/blob/master/docs/CONTRIBUTING.md).
In all communications and contributions, this project follows the [Contributor Covenant Code of Conduct](https://github.com/paritytech/polkadot-sdk/blob/master/docs/CODE_OF_CONDUCT.md).
[`docs/CONTRIBUTING.md`](https://github.com/paritytech/polkadot-sdk/blob/master/docs/CONTRIBUTING.md). In all
communications and contributions, this project follows the [Contributor Covenant Code of
Conduct](https://github.com/paritytech/polkadot-sdk/blob/master/docs/CODE_OF_CONDUCT.md).
## Security
@@ -30,15 +38,13 @@ The security policy and procedures can be found in
## License
- Substrate Primitives (`sp-*`), Frame (`frame-*`) and the pallets (`pallets-*`), binaries (`/bin`)
and all other utilities are licensed under [Apache 2.0](LICENSE-APACHE2). - Substrate Client
(`/client/*` / `sc-*`) is licensed under [GPL v3.0 with a classpath linking
exception](LICENSE-GPL3).
- Substrate Primitives (`sp-*`), Frame (`frame-*`) and the pallets (`pallets-*`), binaries (`/bin`) and all other
utilities are licensed under [Apache 2.0](LICENSE-APACHE2). - Substrate Client (`/client/*` / `sc-*`) is licensed under
[GPL v3.0 with a classpath linking exception](LICENSE-GPL3).
The reason for the split-licensing is to ensure that for the vast majority of teams using Substrate
to create feature-chains, then all changes can be made entirely in Apache2-licensed code, allowing
teams full freedom over what and how they release and giving licensing clarity to commercial teams.
The reason for the split-licensing is to ensure that for the vast majority of teams using Substrate to create
feature-chains, then all changes can be made entirely in Apache2-licensed code, allowing teams full freedom over what
and how they release and giving licensing clarity to commercial teams.
In the interests of the community, we require any deeper improvements made to Substrate's core logic
(e.g. Substrate's internal consensus, crypto or database code) to be contributed back so everyone
can benefit.
In the interests of the community, we require any deeper improvements made to Substrate's core logic (e.g. Substrate's
internal consensus, crypto or database code) to be contributed back so everyone can benefit.
+114 -53
View File
@@ -2,17 +2,26 @@
A fresh [Substrate](https://substrate.io/) node, ready for hacking :rocket:
A standalone version of this template is available for each release of Polkadot in the [Substrate Developer Hub Parachain Template](https://github.com/substrate-developer-hub/substrate-parachain-template/) repository.
The parachain template is generated directly at each Polkadot release branch from the [Node Template in Substrate](https://github.com/paritytech/substrate/tree/master/bin/node-template) upstream
A standalone version of this template is available for each release of Polkadot
in the [Substrate Developer Hub Parachain
Template](https://github.com/substrate-developer-hub/substrate-parachain-template/)
repository. The parachain template is generated directly at each Polkadot
release branch from the [Node Template in
Substrate](https://github.com/paritytech/substrate/tree/master/bin/node-template)
upstream
It is usually best to use the stand-alone version to start a new project.
All bugs, suggestions, and feature requests should be made upstream in the [Substrate](https://github.com/paritytech/substrate/tree/master/bin/node-template) repository.
It is usually best to use the stand-alone version to start a new project. All
bugs, suggestions, and feature requests should be made upstream in the
[Substrate](https://github.com/paritytech/substrate/tree/master/bin/node-template)
repository.
## Getting Started
Depending on your operating system and Rust version, there might be additional packages required to compile this template.
Check the [Install](https://docs.substrate.io/install/) instructions for your platform for the most common dependencies.
Alternatively, you can use one of the [alternative installation](#alternatives-installations) options.
Depending on your operating system and Rust version, there might be additional
packages required to compile this template. Check the
[Install](https://docs.substrate.io/install/) instructions for your platform for
the most common dependencies. Alternatively, you can use one of the [alternative
installation](#alternatives-installations) options.
### Build
@@ -24,13 +33,16 @@ cargo build --release
### Embedded Docs
After you build the project, you can use the following command to explore its parameters and subcommands:
After you build the project, you can use the following command to explore its
parameters and subcommands:
```sh
./target/release/node-template -h
```
You can generate and view the [Rust Docs](https://doc.rust-lang.org/cargo/commands/cargo-doc.html) for this template with this command:
You can generate and view the [Rust
Docs](https://doc.rust-lang.org/cargo/commands/cargo-doc.html) for this template
with this command:
```sh
cargo +nightly doc --open
@@ -38,7 +50,8 @@ cargo +nightly doc --open
### Single-Node Development Chain
The following command starts a single-node development chain that doesn't persist state:
The following command starts a single-node development chain that doesn't
persist state:
```sh
./target/release/node-template --dev
@@ -61,10 +74,12 @@ Development chains:
- Maintain state in a `tmp` folder while the node is running.
- Use the **Alice** and **Bob** accounts as default validator authorities.
- Use the **Alice** account as the default `sudo` account.
- Are preconfigured with a genesis state (`/node/src/chain_spec.rs`) that includes several prefunded development accounts.
- Are preconfigured with a genesis state (`/node/src/chain_spec.rs`) that
includes several prefunded development accounts.
To persist chain state between runs, specify a base path by running a command similar to the following:
To persist chain state between runs, specify a base path by running a command
similar to the following:
```sh
// Create a folder to use as the db base path
@@ -84,81 +99,127 @@ db keystore network
### Connect with Polkadot-JS Apps Front-End
After you start the node template locally, you can interact with it using the hosted version of the [Polkadot/Substrate Portal](https://polkadot.js.org/apps/#/explorer?rpc=ws://localhost:9944) front-end by connecting to the local node endpoint.
A hosted version is also available on [IPFS (redirect) here](https://dotapps.io/) or [IPNS (direct) here](ipns://dotapps.io/?rpc=ws%3A%2F%2F127.0.0.1%3A9944#/explorer).
You can also find the source code and instructions for hosting your own instance on the [polkadot-js/apps](https://github.com/polkadot-js/apps) repository.
After you start the node template locally, you can interact with it using the
hosted version of the [Polkadot/Substrate
Portal](https://polkadot.js.org/apps/#/explorer?rpc=ws://localhost:9944)
front-end by connecting to the local node endpoint. A hosted version is also
available on [IPFS (redirect) here](https://dotapps.io/) or [IPNS (direct)
here](ipns://dotapps.io/?rpc=ws%3A%2F%2F127.0.0.1%3A9944#/explorer). You can
also find the source code and instructions for hosting your own instance on the
[`polkadot-js/apps`](https://github.com/polkadot-js/apps) repository.
### Multi-Node Local Testnet
If you want to see the multi-node consensus algorithm in action, see [Simulate a network](https://docs.substrate.io/tutorials/build-a-blockchain/simulate-network/).
If you want to see the multi-node consensus algorithm in action, see [Simulate a
network](https://docs.substrate.io/tutorials/build-a-blockchain/simulate-network/).
## Template Structure
A Substrate project such as this consists of a number of components that are spread across a few directories.
A Substrate project such as this consists of a number of components that are
spread across a few directories.
### Node
A blockchain node is an application that allows users to participate in a blockchain network.
Substrate-based blockchain nodes expose a number of capabilities:
A blockchain node is an application that allows users to participate in a
blockchain network. Substrate-based blockchain nodes expose a number of
capabilities:
- Networking: Substrate nodes use the [`libp2p`](https://libp2p.io/) networking stack to allow the
nodes in the network to communicate with one another.
- Consensus: Blockchains must have a way to come to [consensus](https://docs.substrate.io/fundamentals/consensus/) on the state of the network.
Substrate makes it possible to supply custom consensus engines and also ships with several consensus mechanisms that have been built on top of [Web3 Foundation research](https://research.web3.foundation/en/latest/polkadot/NPoS/index.html).
- RPC Server: A remote procedure call (RPC) server is used to interact with Substrate nodes.
- Networking: Substrate nodes use the [`libp2p`](https://libp2p.io/) networking
stack to allow the nodes in the network to communicate with one another.
- Consensus: Blockchains must have a way to come to
[consensus](https://docs.substrate.io/fundamentals/consensus/) on the state of
the network. Substrate makes it possible to supply custom consensus engines
and also ships with several consensus mechanisms that have been built on top
of [Web3 Foundation
research](https://research.web3.foundation/en/latest/polkadot/NPoS/index.html).
- RPC Server: A remote procedure call (RPC) server is used to interact with
Substrate nodes.
There are several files in the `node` directory.
Take special note of the following:
- [`chain_spec.rs`](./node/src/chain_spec.rs): A [chain specification](https://docs.substrate.io/build/chain-spec/) is a source code file that defines a Substrate chain's initial (genesis) state.
Chain specifications are useful for development and testing, and critical when architecting the launch of a production chain.
Take note of the `development_config` and `testnet_genesis` functions,.
These functions are used to define the genesis state for the local development chain configuration.
These functions identify some [well-known accounts](https://docs.substrate.io/reference/command-line-tools/subkey/) and use them to configure the blockchain's initial state.
- [`service.rs`](./node/src/service.rs): This file defines the node implementation.
Take note of the libraries that this file imports and the names of the functions it invokes.
In particular, there are references to consensus-related topics, such as the [block finalization and forks](https://docs.substrate.io/fundamentals/consensus/#finalization-and-forks) and other [consensus mechanisms](https://docs.substrate.io/fundamentals/consensus/#default-consensus-models) such as Aura for block authoring and GRANDPA for finality.
There are several files in the `node` directory. Take special note of the
following:
- [`chain_spec.rs`](./node/src/chain_spec.rs): A [chain
specification](https://docs.substrate.io/build/chain-spec/) is a source code
file that defines a Substrate chain's initial (genesis) state. Chain
specifications are useful for development and testing, and critical when
architecting the launch of a production chain. Take note of the
`development_config` and `testnet_genesis` functions,. These functions are
used to define the genesis state for the local development chain
configuration. These functions identify some [well-known
accounts](https://docs.substrate.io/reference/command-line-tools/subkey/) and
use them to configure the blockchain's initial state.
- [`service.rs`](./node/src/service.rs): This file defines the node
implementation. Take note of the libraries that this file imports and the
names of the functions it invokes. In particular, there are references to
consensus-related topics, such as the [block finalization and
forks](https://docs.substrate.io/fundamentals/consensus/#finalization-and-forks)
and other [consensus
mechanisms](https://docs.substrate.io/fundamentals/consensus/#default-consensus-models)
such as Aura for block authoring and GRANDPA for finality.
### Runtime
In Substrate, the terms "runtime" and "state transition function" are analogous.
Both terms refer to the core logic of the blockchain that is responsible for validating blocks and executing the state changes they define.
The Substrate project in this repository uses [FRAME](https://docs.substrate.io/learn/runtime-development/#frame) to construct a blockchain runtime.
FRAME allows runtime developers to declare domain-specific logic in modules called "pallets".
At the heart of FRAME is a helpful [macro language](https://docs.substrate.io/reference/frame-macros/) that makes it easy to create pallets and flexibly compose them to create blockchains that can address [a variety of needs](https://substrate.io/ecosystem/projects/).
Both terms refer to the core logic of the blockchain that is responsible for
validating blocks and executing the state changes they define. The Substrate
project in this repository uses
[FRAME](https://docs.substrate.io/learn/runtime-development/#frame) to construct
a blockchain runtime. FRAME allows runtime developers to declare domain-specific
logic in modules called "pallets". At the heart of FRAME is a helpful [macro
language](https://docs.substrate.io/reference/frame-macros/) that makes it easy
to create pallets and flexibly compose them to create blockchains that can
address [a variety of needs](https://substrate.io/ecosystem/projects/).
Review the [FRAME runtime implementation](./runtime/src/lib.rs) included in this template and note the following:
Review the [FRAME runtime implementation](./runtime/src/lib.rs) included in this
template and note the following:
- This file configures several pallets to include in the runtime.
Each pallet configuration is defined by a code block that begins with `impl $PALLET_NAME::Config for Runtime`.
- The pallets are composed into a single runtime by way of the [`construct_runtime!`](https://paritytech.github.io/substrate/master/frame_support/macro.construct_runtime.html) macro, which is part of the [core FRAME pallet library](https://docs.substrate.io/reference/frame-pallets/#system-pallets).
- This file configures several pallets to include in the runtime. Each pallet
configuration is defined by a code block that begins with `impl
$PALLET_NAME::Config for Runtime`.
- The pallets are composed into a single runtime by way of the
[`construct_runtime!`](https://paritytech.github.io/substrate/master/frame_support/macro.construct_runtime.html)
macro, which is part of the [core FRAME pallet
library](https://docs.substrate.io/reference/frame-pallets/#system-pallets).
### Pallets
The runtime in this project is constructed using many FRAME pallets that ship with [the Substrate repository](https://github.com/paritytech/substrate/tree/master/frame) and a template pallet that is [defined in the `pallets`](./pallets/template/src/lib.rs) directory.
The runtime in this project is constructed using many FRAME pallets that ship
with [the Substrate
repository](https://github.com/paritytech/substrate/tree/master/frame) and a
template pallet that is [defined in the
`pallets`](./pallets/template/src/lib.rs) directory.
A FRAME pallet is comprised of a number of blockchain primitives, including:
- Storage: FRAME defines a rich set of powerful [storage abstractions](https://docs.substrate.io/build/runtime-storage/) that makes it easy to use Substrate's efficient key-value database to manage the evolving state of a blockchain.
- Dispatchables: FRAME pallets define special types of functions that can be invoked (dispatched) from outside of the runtime in order to update its state.
- Events: Substrate uses [events](https://docs.substrate.io/build/events-and-errors/) to notify users of significant state changes.
- Storage: FRAME defines a rich set of powerful [storage
abstractions](https://docs.substrate.io/build/runtime-storage/) that makes it
easy to use Substrate's efficient key-value database to manage the evolving
state of a blockchain.
- Dispatchables: FRAME pallets define special types of functions that can be
invoked (dispatched) from outside of the runtime in order to update its state.
- Events: Substrate uses
[events](https://docs.substrate.io/build/events-and-errors/) to notify users
of significant state changes.
- Errors: When a dispatchable fails, it returns an error.
Each pallet has its own `Config` trait which serves as a configuration interface to generically define the types and parameters it depends on.
Each pallet has its own `Config` trait which serves as a configuration interface
to generically define the types and parameters it depends on.
## Alternatives Installations
Instead of installing dependencies and building this source directly, consider the following alternatives.
Instead of installing dependencies and building this source directly, consider
the following alternatives.
### Nix
Install [nix](https://nixos.org/) and
[nix-direnv](https://github.com/nix-community/nix-direnv) for a fully plug-and-play
experience for setting up the development environment.
To get all the correct dependencies, activate direnv `direnv allow`.
[nix-direnv](https://github.com/nix-community/nix-direnv) for a fully
plug-and-play experience for setting up the development environment. To get all
the correct dependencies, activate direnv `direnv allow`.
### Docker
Please follow the [Substrate Docker instructions here](https://github.com/paritytech/substrate/blob/master/docker/README.md) to build the Docker container with the Substrate Node Template binary.
Please follow the [Substrate Docker instructions
here](https://github.com/paritytech/substrate/blob/master/docker/README.md) to
build the Docker container with the Substrate Node Template binary.
+48 -55
View File
@@ -1,22 +1,18 @@
---
title: Installation
---
# Installation
This guide is for reference only, please check the latest information on getting started with Substrate
[here](https://docs.substrate.io/main-docs/install/).
This guide is for reference only, please check the latest information on getting started with Substrate [here](https://docs.substrate.io/main-docs/install/).
This page will guide you through the **2 steps** needed to prepare a computer for **Substrate** development.
Since Substrate is built with [the Rust programming language](https://www.rust-lang.org/), the first
thing you will need to do is prepare the computer for Rust development - these steps will vary based
on the computer's operating system. Once Rust is configured, you will use its toolchains to interact
with Rust projects; the commands for Rust's toolchains will be the same for all supported,
Unix-based operating systems.
This page will guide you through the **2 steps** needed to prepare a computer for **Substrate** development. Since
Substrate is built with [the Rust programming language](https://www.rust-lang.org/), the first thing you will need to do
is prepare the computer for Rust development - these steps will vary based on the computer's operating system. Once Rust
is configured, you will use its toolchains to interact with Rust projects; the commands for Rust's toolchains will be
the same for all supported, Unix-based operating systems.
## Build dependencies
Substrate development is easiest on Unix-based operating systems like macOS or Linux. The examples
in the [Substrate Docs](https://docs.substrate.io) use Unix-style terminals to demonstrate how to
interact with Substrate from the command line.
Substrate development is easiest on Unix-based operating systems like macOS or Linux. The examples in the [Substrate
Docs](https://docs.substrate.io) use Unix-style terminals to demonstrate how to interact with Substrate from the command
line.
### Ubuntu/Debian
@@ -55,10 +51,9 @@ sudo zypper install clang curl git openssl-devel llvm-devel libudev-devel
### macOS
> **Apple M1 ARM**
> If you have an Apple M1 ARM system on a chip, make sure that you have Apple Rosetta 2
> installed through `softwareupdate --install-rosetta`. This is only needed to run the
> `protoc` tool during the build. The build itself and the target binaries would remain native.
> **Apple M1 ARM** If you have an Apple M1 ARM system on a chip, make sure that you have Apple Rosetta 2 installed
> through `softwareupdate --install-rosetta`. This is only needed to run the `protoc` tool during the build. The build
> itself and the target binaries would remain native.
Open the Terminal application and execute the following commands:
@@ -81,8 +76,8 @@ Please refer to the separate
## Rust developer environment
This guide uses <https://rustup.rs> installer and the `rustup` tool to manage the Rust toolchain.
First install and configure `rustup`:
This guide uses <https://rustup.rs> installer and the `rustup` tool to manage the Rust toolchain. First install and
configure `rustup`:
```bash
# Install
@@ -102,13 +97,13 @@ rustup target add wasm32-unknown-unknown --toolchain nightly
## Test your set-up
Now the best way to ensure that you have successfully prepared a computer for Substrate
development is to follow the steps in [our first Substrate tutorial](https://docs.substrate.io/tutorials/v3/create-your-first-substrate-chain/).
Now the best way to ensure that you have successfully prepared a computer for Substrate development is to follow the
steps in [our first Substrate tutorial](https://docs.substrate.io/tutorials/v3/create-your-first-substrate-chain/).
## Troubleshooting Substrate builds
Sometimes you can't get the Substrate node template
to compile out of the box. Here are some tips to help you work through that.
Sometimes you can't get the Substrate node template to compile out of the box. Here are some tips to help you work
through that.
### Rust configuration check
@@ -144,27 +139,27 @@ stable-x86_64-unknown-linux-gnu (default)
rustc 1.50.0 (cb75ad5db 2021-02-10)
```
As you can see above, the default toolchain is stable, and the
`nightly-x86_64-unknown-linux-gnu` toolchain as well as its `wasm32-unknown-unknown` target is installed.
You also see that `nightly-2020-10-06-x86_64-unknown-linux-gnu` is installed, but is not used unless explicitly defined as illustrated in the [specify your nightly version](#specifying-nightly-version)
section.
As you can see above, the default toolchain is stable, and the `nightly-x86_64-unknown-linux-gnu` toolchain as well as
its `wasm32-unknown-unknown` target is installed. You also see that `nightly-2020-10-06-x86_64-unknown-linux-gnu` is
installed, but is not used unless explicitly defined as illustrated in the [specify your nightly
version](#specifying-nightly-version) section.
### WebAssembly compilation
Substrate uses [WebAssembly](https://webassembly.org) (Wasm) to produce portable blockchain
runtimes. You will need to configure your Rust compiler to use
[`nightly` builds](https://doc.rust-lang.org/book/appendix-07-nightly-rust.html) to allow you to
compile Substrate runtime code to the Wasm target.
Substrate uses [WebAssembly](https://webassembly.org) (Wasm) to produce portable blockchain runtimes. You will need to
configure your Rust compiler to use [`nightly` builds](https://doc.rust-lang.org/book/appendix-07-nightly-rust.html) to
allow you to compile Substrate runtime code to the Wasm target.
> There are upstream issues in Rust that need to be resolved before all of Substrate can use the stable Rust toolchain.
> [This is our tracking issue](https://github.com/paritytech/substrate/issues/1252) if you're curious as to why and how this will be resolved.
> [This is our tracking issue](https://github.com/paritytech/substrate/issues/1252) if you're curious as to why and how
> this will be resolved.
#### Latest nightly for Substrate `master`
Developers who are building Substrate _itself_ should always use the latest bug-free versions of
Rust stable and nightly. This is because the Substrate codebase follows the tip of Rust nightly,
which means that changes in Substrate often depend on upstream changes in the Rust nightly compiler.
To ensure your Rust compiler is always up to date, you should run:
Developers who are building Substrate _itself_ should always use the latest bug-free versions of Rust stable and
nightly. This is because the Substrate codebase follows the tip of Rust nightly, which means that changes in Substrate
often depend on upstream changes in the Rust nightly compiler. To ensure your Rust compiler is always up to date, you
should run:
```bash
rustup update
@@ -172,21 +167,19 @@ rustup update nightly
rustup target add wasm32-unknown-unknown --toolchain nightly
```
> NOTE: It may be necessary to occasionally rerun `rustup update` if a change in the upstream Substrate
> codebase depends on a new feature of the Rust compiler. When you do this, both your nightly
> and stable toolchains will be pulled to the most recent release, and for nightly, it is
> generally _not_ expected to compile WASM without error (although it very often does).
> Be sure to [specify your nightly version](#specifying-nightly-version) if you get WASM build errors
> from `rustup` and [downgrade nightly as needed](#downgrading-rust-nightly).
> NOTE: It may be necessary to occasionally rerun `rustup update` if a change in the upstream Substrate codebase depends
> on a new feature of the Rust compiler. When you do this, both your nightly and stable toolchains will be pulled to the
> most recent release, and for nightly, it is generally _not_ expected to compile WASM without error (although it very
> often does). Be sure to [specify your nightly version](#specifying-nightly-version) if you get WASM build errors from
> `rustup` and [downgrade nightly as needed](#downgrading-rust-nightly).
#### Rust nightly toolchain
If you want to guarantee that your build works on your computer as you update Rust and other
dependencies, you should use a specific Rust nightly version that is known to be
compatible with the version of Substrate they are using; this version will vary from project to
project and different projects may use different mechanisms to communicate this version to
developers. For instance, the Polkadot client specifies this information in its
[release notes](https://github.com/paritytech/polkadot/releases).
If you want to guarantee that your build works on your computer as you update Rust and other dependencies, you should
use a specific Rust nightly version that is known to be compatible with the version of Substrate they are using; this
version will vary from project to project and different projects may use different mechanisms to communicate this
version to developers. For instance, the Polkadot client specifies this information in its [release
notes](https://github.com/paritytech/polkadot/releases).
```bash
# Specify the specific nightly toolchain in the date below:
@@ -203,20 +196,20 @@ rustup target add wasm32-unknown-unknown --toolchain nightly-<yyyy-MM-dd>
### Specifying nightly version
Use the `WASM_BUILD_TOOLCHAIN` environment variable to specify the Rust nightly version a Substrate
project should use for Wasm compilation:
Use the `WASM_BUILD_TOOLCHAIN` environment variable to specify the Rust nightly version a Substrate project should use
for Wasm compilation:
```bash
WASM_BUILD_TOOLCHAIN=nightly-<yyyy-MM-dd> cargo build --release
```
> Note that this only builds _the runtime_ with the specified nightly. The rest of project will be
> compiled with **your default toolchain**, i.e. the latest installed stable toolchain.
> Note that this only builds _the runtime_ with the specified nightly. The rest of project will be compiled with **your
> default toolchain**, i.e. the latest installed stable toolchain.
### Downgrading Rust nightly
If your computer is configured to use the latest Rust nightly and you would like to downgrade to a
specific nightly version, follow these steps:
If your computer is configured to use the latest Rust nightly and you would like to downgrade to a specific nightly
version, follow these steps:
```bash
rustup uninstall nightly
@@ -1 +1 @@
License: MIT-0
License: MIT-0
+46 -21
View File
@@ -1,26 +1,33 @@
# Subkey
Subkey is a commandline utility included with Substrate. It allows generating and restoring keys for Substrate based chains such as Polkadot, Kusama and a growing number of parachains and Substrate based projects.
Subkey is a commandline utility included with Substrate. It allows generating and restoring keys for Substrate based
chains such as Polkadot, Kusama and a growing number of parachains and Substrate based projects.
`subkey` provides a few sub-commands to generate keys, check keys, sign messages, verify messages, etc...
You can see the full list of commands with `subkey --help`. Most commands have additional help available with for instance `subkey generate --help` for the `generate` command.
You can see the full list of commands with `subkey --help`. Most commands have additional help available with for
instance `subkey generate --help` for the `generate` command.
## Safety first
`subkey` does not need an internet connection to work. Indeed, for the best security, you should be using `subkey` on a machine that is **not connected** to the internet.
`subkey` does not need an internet connection to work. Indeed, for the best security, you should be using `subkey` on a
machine that is **not connected** to the internet.
`subkey` deals with **seeds** and **private keys**. Make sure to use `subkey` in a safe environment (ie. no one looking over your shoulder) and on a safe computer (ie. no one able to check your command history).
`subkey` deals with **seeds** and **private keys**. Make sure to use `subkey` in a safe environment (ie. no one looking
over your shoulder) and on a safe computer (ie. no one able to check your command history).
If you save any output of `subkey` into a file, make sure to apply proper permissions and/or delete the file as soon as possible.
If you save any output of `subkey` into a file, make sure to apply proper permissions and/or delete the file as soon as
possible.
## Usage
The following guide explains *some* of the `subkey` commands. For the full list and the most up to date documentation, make sure to check the integrated help with `subkey --help`.
The following guide explains *some* of the `subkey` commands. For the full list and the most up to date documentation,
make sure to check the integrated help with `subkey --help`.
### Install with Cargo
You will need to have the Substrate build dependencies to install Subkey. Use the following two commands to install the dependencies and Subkey, respectively:
You will need to have the Substrate build dependencies to install Subkey. Use the following two commands to install the
dependencies and Subkey, respectively:
Command:
@@ -58,19 +65,26 @@ Secret phrase `hotel forest jar hover kite book view eight stuff angle legend de
---
☠️ DO NT RE-USE ANY OF THE SEEDS AND SECRETS FROM THIS PAGE ☠️.
You can read more about security and risks in [SECURITY.md](./SECURITY.md) and in the [Polkadot Wiki](https://wiki.polkadot.network/docs/learn-account-generation).
You can read more about security and risks in [SECURITY.md](./SECURITY.md) and in the [Polkadot
Wiki](https://wiki.polkadot.network/docs/learn-account-generation).
---
The output above shows a **secret phrase** (also called **mnemonic phrase**) and the **secret seed** (also called **Private Key**). Those 2 secrets are the pieces of information you MUST keep safe and secret. All the other information below can be derived from those secrets.
The output above shows a **secret phrase** (also called **mnemonic phrase**) and the **secret seed** (also called
**Private Key**). Those 2 secrets are the pieces of information you MUST keep safe and secret. All the other information
below can be derived from those secrets.
The output above also show the **public key** and the **Account ID**. Those are the independant from the network where you will use the key.
The output above also show the **public key** and the **Account ID**. Those are the independant from the network where
you will use the key.
The **SS58 address** (or **Public Address**) of a new account is a reprensentation of the public keys of an account for a given network (for instance Kusama or Polkadot).
The **SS58 address** (or **Public Address**) of a new account is a reprensentation of the public keys of an account for
a given network (for instance Kusama or Polkadot).
You can read more about the [SS58 format in the Substrate Docs](https://docs.substrate.io/reference/address-formats/) and see the list of reserved prefixes in the [SS58 Registry](https://github.com/paritytech/ss58-registry).
You can read more about the [SS58 format in the Substrate Docs](https://docs.substrate.io/reference/address-formats/)
and see the list of reserved prefixes in the [SS58 Registry](https://github.com/paritytech/ss58-registry).
For instance, considering the previous seed `0xa05c75731970cc7868a2fb7cb577353cd5b31f62dccced92c441acd8fee0c92d` the SS58 addresses are:
For instance, considering the previous seed `0xa05c75731970cc7868a2fb7cb577353cd5b31f62dccced92c441acd8fee0c92d` the
SS58 addresses are:
- Polkadot: `16m4J167Mptt8UXL8aGSAi7U2FnPpPxZHPrCgMG9KJzVoFqM`
- Kusama: `JLNozAv8QeLSbLFwe2UvWeKKE4yvmDbfGxTuiYkF2BUMx4M`
@@ -129,13 +143,17 @@ Secret phrase `soup lyrics media market way crouch elevator put moon useful ques
SS58 Address: 5He5pZpc7AJ8evPuab37vJF6KkFDqq9uDq2WXh877Qw6iaVC
```
Using the `inspect` command (see more details below), we see that knowning only the **secret seed** is no longer sufficient to recover the account:
Using the `inspect` command (see more details below), we see that knowning only the **secret seed** is no longer
sufficient to recover the account:
```bash
subkey inspect "soup lyrics media market way crouch elevator put moon useful question wide"
```
which recovers the account `5Fe4sqj2K4fRuzEGvToi4KATqZfiDU7TqynjXG6PZE2dxwyh` and not `5He5pZpc7AJ8evPuab37vJF6KkFDqq9uDq2WXh877Qw6iaVC` as we expected. The additional user-defined **password** (`extra_secret` in our example) is now required to fully recover the account. Let's inspect the the previous mnemonic, this time passing also the required `password` as shown below:
which recovers the account `5Fe4sqj2K4fRuzEGvToi4KATqZfiDU7TqynjXG6PZE2dxwyh` and not
`5He5pZpc7AJ8evPuab37vJF6KkFDqq9uDq2WXh877Qw6iaVC` as we expected. The additional user-defined **password**
(`extra_secret` in our example) is now required to fully recover the account. Let's inspect the the previous mnemonic,
this time passing also the required `password` as shown below:
```bash
subkey inspect --password extra_secret "soup lyrics media market way crouch elevator put moon useful question wide"
@@ -161,7 +179,8 @@ subkey inspect --public < pubkey | address >
**NOTE**: While you will be able to recover the secret seed from the mnemonic, the opposite is not possible.
**NOTE**: For obvious reasons, the **secrets** cannot be recovered from passing **public data** such as `pubkey` or `address` as input.
**NOTE**: For obvious reasons, the **secrets** cannot be recovered from passing **public data** such as `pubkey` or
`address` as input.
command:
@@ -181,7 +200,8 @@ Secret Key URI `0xa05c75731970cc7868a2fb7cb577353cd5b31f62dccced92c441acd8fee0c9
### Signing
`subkey` allows using a **secret key** to sign a random message. The signature can then be verified by anyone using your **public key**:
`subkey` allows using a **secret key** to sign a random message. The signature can then be verified by anyone using your
**public key**:
```bash
echo -n <msg> | subkey sign --suri <seed|mnemonic>
@@ -201,11 +221,13 @@ output:
9201af3788ad4f986b800853c79da47155f2e08fde2070d866be4c27ab060466fea0623dc2b51f4392f4c61f25381a62848dd66c5d8217fae3858e469ebd668c
```
**NOTE**: Each run of the `sign` command will yield a different output. While each signature is different, they are all valid.
**NOTE**: Each run of the `sign` command will yield a different output. While each signature is different, they are all
valid.
### Verifying a signature
Given a message, a signature and an address, `subkey` can verify whether the **message** has been digitally signed by the holder (or one of the holders) of the **private key** for the given **address**:
Given a message, a signature and an address, `subkey` can verify whether the **message** has been digitally signed by
the holder (or one of the holders) of the **private key** for the given **address**:
```bash
echo -n <msg> | subkey verify <sig> <address>
@@ -234,7 +256,8 @@ Error: SignatureInvalid
### Using the vanity generator
You can use the included vanity generator to find a seed that provides an address which includes the desired pattern. Be warned, depending on your hardware this may take a while.
You can use the included vanity generator to find a seed that provides an address which includes the desired pattern. Be
warned, depending on your hardware this may take a while.
command:
@@ -256,7 +279,9 @@ Secret Key URI `0x8c9a73097f235b84021a446bc2826a00c690ea0be3e0d81a84931cb4146d66
`Bob` now got a nice address starting with their name: 1**bob**YxBPjZWRPbVo35aSwci1u5Zmq8P6J2jpa4kkudBZMqE.
**Note**: While `Bob`, having a short name (3 chars), got a result rather quickly, it will take much longer for `Alice` who has a much longer name, thus the chances to generate a random address that contains the chain `alice` will be much smaller.
**Note**: While `Bob`, having a short name (3 chars), got a result rather quickly, it will take much longer for `Alice`
who has a much longer name, thus the chances to generate a random address that contains the chain `alice` will be much
smaller.
## License
+15 -8
View File
@@ -1,8 +1,9 @@
# Keys and Security
The following information is not exhaustive but meant to prevent the most common mistakes.
You can read more about security and risks in the [Polkadot Wiki](https://wiki.polkadot.network/docs/learn-account-generation).
The Polkadot network has a few **test networks**, e.g. **Westend**. Test networks are a great way to experiment and learn safely as you can lose tokens on those networks without any financial consequences.
The following information is not exhaustive but meant to prevent the most common mistakes. You can read more about
security and risks in the [Polkadot Wiki](https://wiki.polkadot.network/docs/learn-account-generation). The Polkadot
network has a few **test networks**, e.g. **Westend**. Test networks are a great way to experiment and learn safely as
you can lose tokens on those networks without any financial consequences.
`subkey` generates and provides 2 pieces of **secret** information:
- **secret phrase**: a bunch of words, exactly 12 by default (can be 12, 15, 18, 21 or 24)
@@ -10,16 +11,22 @@ The Polkadot network has a few **test networks**, e.g. **Westend**. Test network
There are 2 risks related to private keys:
- loss of keys: this can happen if you don't have a proper backup
- leak of the keys: this can unfortunately happen in many ways, including malware, phishing, key logger, backups on system that are online and not properly secured
- leak of the keys: this can unfortunately happen in many ways, including malware, phishing, key logger, backups on
system that are online and not properly secured
You want to ensure that:
- you **do not lose** those secrets
- **no one but you can access** those secrets
☠️ **DO NOT SHARE** your mnemonic phrase or secret seed with ANYONE under **ANY** circumstances. Doing so would give them access to your funds and to send transactions on your behalf.
☠️ **DO NOT SHARE** your mnemonic phrase or secret seed with ANYONE under **ANY** circumstances. Doing so would give
them access to your funds and to send transactions on your behalf.
☠️ If someone is asking for your **secret** phrase or **secret** seed, you can be **SURE** they are attempting to steal your funds.
☠️ If someone is asking for your **secret** phrase or **secret** seed, you can be **SURE** they are attempting to steal
your funds.
✅ It is however fine to share your **SS58 Address** as this is meant to be public information and is needed by anyone you want to be able to make transfer to or otherwise interact with your account. They will only ever need your **Public Address**.
✅ It is however fine to share your **SS58 Address** as this is meant to be public information and is needed by anyone
you want to be able to make transfer to or otherwise interact with your account. They will only ever need your **Public
Address**.
⚠️ While using the same key on multiple networks is possible, it is usually **not** recommended unless you have good motivations for doing so and understand the associated risks and drawbacks.
⚠️ While using the same key on multiple networks is possible, it is usually **not** recommended unless you have good
motivations for doing so and understand the associated risks and drawbacks.
+1 -1
View File
@@ -3,4 +3,4 @@ Collection of allocator implementations.
This crate provides the following allocator implementations:
- A freeing-bump allocator: [`FreeingBumpHeapAllocator`](https://docs.rs/sc-allocator/latest/sc_allocator/struct.FreeingBumpHeapAllocator.html)
License: Apache-2.0
License: Apache-2.0
+1 -1
View File
@@ -1,3 +1,3 @@
Substrate client interfaces.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -6,4 +6,4 @@ This crate provides the [`BlockBuilder`] utility and the corresponding runtime a
The block builder utility is used in the node as an abstraction over the runtime api to
initialize a block, to push extrinsics and to finalize a block.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -89,4 +89,4 @@ pub struct Extension {
pub type MyChainSpec<G> = GenericChainSpec<G, Extension>;
```
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -1,3 +1,3 @@
Substrate CLI library.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+2 -2
View File
@@ -1,4 +1,4 @@
Aura (Authority-round) consensus in substrate.
Aura (Authority-round) consensus in Substrate.
Aura works by having a list of authorities A who are expected to roughly
agree on the current time. Time is divided up into discrete slots of t
@@ -12,4 +12,4 @@ far in the future they are.
NOTE: Aura itself is designed to be generic over the crypto used.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -45,4 +45,4 @@ blocks) and will go with the longest one in case of a tie.
An in-depth description and analysis of the protocol can be found here:
<https://research.web3.foundation/en/latest/polkadot/block-production/Babe.html>
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
@@ -1,3 +1,3 @@
RPC api for babe.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -1,3 +1,3 @@
Collection of common consensus specific implementations
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -1,3 +1,3 @@
Generic utilities for epoch-based consensus engines.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+2 -2
View File
@@ -1,4 +1,4 @@
Integration of the GRANDPA finality gadget into substrate.
Integration of the GRANDPA finality gadget into Substrate.
This crate is unstable and the API and usage may change.
@@ -36,4 +36,4 @@ number (this is num(signal) + N). When finalizing a block, we either apply
or prune any signaled changes based on whether the signaling block is
included in the newly-finalized chain.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
@@ -1,3 +1,3 @@
RPC API for GRANDPA.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
@@ -1,4 +1,4 @@
A manual sealing engine: the engine listens for rpc calls to seal blocks and create forks.
This is suitable for a testing environment.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -4,4 +4,4 @@ Some consensus algorithms have a concept of *slots*, which are intervals in
time during which certain events can and/or must occur. This crate
provides generic functionality for slots.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -8,4 +8,4 @@ having discarded heavy state that will allow a chain reorganization.
Finality implies canonicality but not vice-versa.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -10,4 +10,4 @@ provided into the wasm runtime module.
by the current value of `:code` in the provided externalities), i.e. interfacing with
wasm engine used, instance cache.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -1,3 +1,3 @@
A set of common definitions that are needed for defining execution engines.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -1 +1 @@
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -1,3 +1,3 @@
Console informant. Prints sync progress and block events. Runs on the calling thread.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -1,3 +1,3 @@
Keystore (and session key management) for ed25519 based chains like Polkadot.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -38,4 +38,4 @@ opens the door for neighbor status packets to be baked into the gossip protocol.
These status packets will typically contain light pieces of information
used to inform peers of a current view of protocol state.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+5 -5
View File
@@ -80,8 +80,8 @@ is "dot". In the protocol names below, `<protocol-id>` must be replaced with the
protocol ID.
> **Note**: It is possible for the same connection to be used for multiple chains. For example,
> one can use both the `/dot/sync/2` and `/sub/sync/2` protocols on the same
> connection, provided that the remote supports them.
> one can use both the `/dot/sync/2` and `/sub/sync/2` protocols on the same
> connection, provided that the remote supports them.
Substrate uses the following standard libp2p protocols:
@@ -138,7 +138,7 @@ substream is closed, the entire connection is closed as well. This is a bug that
resolved by deprecating the protocol entirely.
Within the unique Substrate substream, messages encoded using
[*parity-scale-codec*](https://github.com/paritytech/parity-scale-codec) are exchanged.
[`parity-scale-codec``](https://github.com/paritytech/parity-scale-codec) are exchanged.
The detail of theses messages is not totally in place, but they can be found in the
`message.rs` file.
@@ -240,7 +240,7 @@ The state is then imported into the database and the keep-up sync starts in norm
This is similar to fast sync, but instead of downloading and verifying full header chain, the algorithm
only downloads finalized authority set changes.
### GRANDPA warp sync.
### GRANDPA warp sync
GRANDPA keeps justifications for each finalized authority set change. Each change is signed by the
authorities from the previous set. By downloading and verifying these signed hand-offs starting from genesis,
@@ -254,7 +254,7 @@ the fast sync. The state is verified to match the header storage root. After the
database it is queried for the information that allows GRANDPA and BABE to continue operating from that state.
This includes BABE epoch information and GRANDPA authority set id.
### Background block download.
### Background block download
After the latest state has been imported the node is fully operational, but is still missing historic block
data. I.e. it is unable to serve bock bodies and headers other than the most recent one. To make sure all
+1 -1
View File
@@ -15,4 +15,4 @@ for instance via:
2. Majority voting for results
3. etc
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -1,3 +1,3 @@
Prometheus basic proposer metrics.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+2 -2
View File
@@ -1,5 +1,5 @@
Substrate RPC interfaces.
A collection of RPC methods and subscriptions supported by all substrate clients.
A collection of RPC methods and subscriptions supported by all Substrate clients.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -1,3 +1,3 @@
Substrate RPC servers.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+2 -2
View File
@@ -1,5 +1,5 @@
Substrate RPC interfaces.
A collection of RPC methods and subscriptions supported by all substrate clients.
A collection of RPC methods and subscriptions supported by all Substrate clients.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -2,4 +2,4 @@ Substrate RPC implementation.
A core implementation of Substrate RPC interfaces.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+1 -1
View File
@@ -1,4 +1,4 @@
Substrate service. Starts a thread that spins up the network, client, and extrinsic pool.
Manages communication between them.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+3 -3
View File
@@ -2,15 +2,15 @@ State database maintenance. Handles canonicalization and pruning in the database
this module is a `ChangeSet` which is basically a list of key-value pairs (trie nodes) that
were added or deleted during block execution.
# Canonicalization.
# Canonicalization
Canonicalization window tracks a tree of blocks identified by header hash. The in-memory
overlay allows to get any node that was inserted in any of the blocks within the window.
The tree is journaled to the backing database and rebuilt on startup.
Canonicalization function selects one root from the top of the tree and discards all other roots and
their subtrees.
# Pruning.
# Pruning
See `RefWindow` for pruning algorithm details. `StateDb` prunes on each canonicalization until pruning
constraints are satisfied.
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+3 -3
View File
@@ -1,6 +1,6 @@
# sc-telemetry
Substrate's client telemetry is a part of substrate that allows ingesting telemetry data
Substrate's client telemetry is a part of Substrate that allows ingesting telemetry data
with for example [Polkadot telemetry](https://github.com/paritytech/substrate-telemetry).
It works using Tokio's [tracing](https://github.com/tokio-rs/tracing/) library. The telemetry
@@ -9,8 +9,8 @@ tracing `Layer`. This layer will then send the data through an asynchronous chan
background task called [`TelemetryWorker`] which will send the information to the configured
remote telemetry servers.
If multiple substrate nodes are running in the same process, it uses a `tracing::Span` to
identify which substrate node is reporting the telemetry. Every task spawned using sc-service's
If multiple Substrate nodes are running in the same process, it uses a `tracing::Span` to
identify which Substrate node is reporting the telemetry. Every task spawned using sc-service's
`TaskManager` automatically inherit this span.
Substrate's nodes initialize/register with the [`TelemetryWorker`] using a [`TelemetryHandle`].
+2 -2
View File
@@ -1,4 +1,4 @@
Instrumentation implementation for substrate.
Instrumentation implementation for Substrate.
This crate is unstable and the API and usage may change.
@@ -8,4 +8,4 @@ See `sp-tracing` for examples on how to use tracing.
Currently we provide `Log` (default), `Telemetry` variants for `Receiver`
License: GPL-3.0-or-later WITH Classpath-exception-2.0
License: GPL-3.0-or-later WITH Classpath-exception-2.0
+4 -4
View File
@@ -232,7 +232,7 @@ are interested in.
Since the pool is expected to store more transactions than what can fit
in a single block, validating the entire pool on every block might not be
feasible. This means that the actual implementation might need to take some
feasible. This means that the actual implementation might need to take some
shortcuts.
## Suggestions & caveats
@@ -255,7 +255,7 @@ shortcuts.
lot of re-orgs. Make sure that transactions are never lost.
1. The UTXO model is quite challenging. A transaction becomes valid right after
it's included in a block, however it is waiting for exactly the same inputs
it's included in a block, however it is waiting for exactly the same inputs
to be spent, so it will never really be included again.
1. Note that in a non-ideal implementation the state of the pool will most
@@ -278,7 +278,7 @@ shortcuts.
1. We periodically validate all transactions in the pool in batches.
1. To minimize runtime calls, we introduce the batch-verify call. Note it should
1. To minimize runtime calls, we introduce the batch-verify call. Note it should
reset the state (overlay) after every verification.
1. Consider leveraging finality. Maybe we could verify against latest finalised
@@ -355,7 +355,7 @@ figure out what tags were satisfied by a transaction in that block. For each blo
transaction we either call into the runtime to get it's `ValidTransaction` object,
or we check the pool if that transaction is already known to spare the runtime
call. From this we gather the full set of `provides` tags and perform pruning of
the `ready` pool based on that. Also, we promote all transactions from `future`
the `ready` pool based on that. Also, we promote all transactions from `future`
that have their tags satisfied.
In case we remove transactions that we are unsure if they were already included
+18 -12
View File
@@ -1,27 +1,32 @@
# Substrate Builder Docker Image
The Docker image in this folder is a `builder` image. It is self contained and allows users to build the binaries themselves.
There is no requirement on having Rust or any other toolchain installed but a working Docker environment.
The Docker image in this folder is a `builder` image. It is self contained and allows users to build the binaries
themselves. There is no requirement on having Rust or any other toolchain installed but a working Docker environment.
Unlike the `parity/polkadot` image which contains a single binary (`polkadot`!) used by default, the image in this folder builds and contains several binaries and you need to provide the name of the binary to be called.
Unlike the `parity/polkadot` image which contains a single binary (`polkadot`!) used by default, the image in this
folder builds and contains several binaries and you need to provide the name of the binary to be called.
You should refer to the [.Dockerfile](./substrate_builder.Dockerfile) for the actual list. At the time of editing, the list of included binaries is:
You should refer to the [.Dockerfile](./substrate_builder.Dockerfile) for the actual list. At the time of editing, the
list of included binaries is:
- substrate
- subkey
- node-template
- chain-spec-builder
- `substrate`
- `subkey`
- `node-template`
- `chain-spec-builder`
First, install [Docker](https://docs.docker.com/get-docker/).
Then to generate the latest parity/substrate image. Please run:
Then to generate the latest `parity/substrate` image. Please run:
```sh
./build.sh
```
> If you wish to create a debug build rather than a production build, then you may modify the [.Dockerfile](./substrate_builder.Dockerfile) replacing `cargo build --locked --release` with just `cargo build --locked` and replacing `target/release` with `target/debug`.
If you wish to create a debug build rather than a production build, then you may modify the
[.Dockerfile](./substrate_builder.Dockerfile) replacing `cargo build --locked --release` with just
`cargo build --locked` and replacing `target/release` with `target/debug`.
> If you get an error that a tcp port address is already in use then find an available port to use for the host port in the [.Dockerfile](./substrate_builder.Dockerfile).
If you get an error that a tcp port address is already in use then find an available port to use for the host port in
the [.Dockerfile](./substrate_builder.Dockerfile).
The image can be used by passing the selected binary followed by the appropriate tags for this binary.
@@ -32,7 +37,8 @@ Your best guess to get started is to pass the `--help flag`. Here are a few exam
- `./run.sh node-template --version`
- `./run.sh chain-spec-builder --help`
Then try running the following command to start a single node development chain using the Substrate Node Template binary `node-template`:
Then try running the following command to start a single node development chain using the Substrate Node Template binary
`node-template`:
```sh
./run.sh node-template --dev --ws-external
+61 -79
View File
@@ -8,24 +8,36 @@ The format is based on [Keep a Changelog].
## 2.0.1-> 3.0.0 - Apollo 14
Most notably, this is the first release of the new FRAME (2.0) with its new macro-syntax and some changes in types, and pallet versioning. This release also incorporates the faster and improve version 2.0 of the parity-scale-codec and upgraded dependencies all-around. While the `FinalityTracker` pallet has been dropped, this release marks the first public appearance of a few new pallets, too;Bounties, Lottery, Tips (extracted from the `Treasury`-pallet, see #7536) and Merkle-Mountain-Ranges (MMR).
Most notably, this is the first release of the new FRAME (2.0) with its new macro-syntax and some changes in types, and
pallet versioning. This release also incorporates the faster and improve version 2.0 of the `parity-scale-codec` and
upgraded dependencies all-around. While the `FinalityTracker` pallet has been dropped, this release marks the first
public appearance of a few new pallets, too;Bounties, Lottery, Tips (extracted from the `Treasury`-pallet, see #7536)
and Merkle-Mountain-Ranges (MMR).
On the client side, the most notable changes are around the keystore, making it async and switching to a different signing model allowing for remote-signing to be implemented; and various changes to improve networking and light-client support, like adding the Grandpa warp sync request-response protocol (#7711).
On the client side, the most notable changes are around the keystore, making it async and switching to a different
signing model allowing for remote-signing to be implemented; and various changes to improve networking and light-client
support, like adding the Grandpa warp sync request-response protocol (#7711).
_Contracts_: Please note that the contracts pallet _is not part_ of this release. The pallet is not yet ready and will be released separately in the coming weeks. The currently released contracts pallet _is not compatible_ with the new FRAME, thus if you need the contracts pallet, we recommend you wait with the upgrade until it has been released, too.
_Contracts_: Please note that the contracts pallet _is not part_ of this release. The pallet is not yet ready and will
be released separately in the coming weeks. The currently released contracts pallet _is not compatible_ with the new
FRAME, thus if you need the contracts pallet, we recommend you wait with the upgrade until it has been released, too.
### Upgrade instructions
Not too much has changed on the top and API level for developing Substrate between 2.0 and 3.0. The easiest and quickest path for upgrading is just to take the latest node-template and try applying your changes to it:
Not too much has changed on the top and API level for developing Substrate between 2.0 and 3.0. The easiest and quickest
path for upgrading is just to take the latest node-template and try applying your changes to it:
1. take a diff between 2.0 and your changes
2. store that diff
3. remove everything, copy over the 3.0 node-template
4. try re-applying your diff, manually, a hunk at a time.
If that doesn't work for you, we are working on an in-depth-guide for all major changes that took place and how you need to adapt your code for it. [You can find the upgrade guide under `docs/` in the repo](https://github.com/paritytech/substrate/blob/master/docs/Upgrading-2.0-to-3.0.md), if you have further questions or problem, please [feel free to ask in the github discussion board](https://github.com/paritytech/substrate/discussions).
If that doesn't work for you, we are working on an in-depth-guide for all major changes that took place and how you need
to adapt your code for it. [You can find the upgrade guide under `docs/` in the
repo](https://github.com/paritytech/substrate/blob/master/docs/Upgrading-2.0-to-3.0.md), if you have further questions
or problem, please [feel free to ask in the github discussion
board](https://github.com/paritytech/substrate/discussions).
Runtime
-------
#### Runtime
* contracts: Charge rent for code storage (#7935)
* contracts: Emit event on contract termination (#8014)
@@ -63,8 +75,7 @@ Runtime
* Move proxies migration (#7205)
* Introduce `cancel_proposal` to rid us of those pesky proposals (#7111)
Client
------
#### Client
* Remove backwards-compatibility networking hack (#8068)
* Extend SS58 network identifiers (#8039)
@@ -97,8 +108,7 @@ Client
* Refactor CurrencyToVote (#6896)
* client/network: Stop sending noise legacy handshake (#7211)
API
---
#### API
* pallet macro: easier syntax for `#[pallet::pallet]` with `struct Pallet<T>(_)` (#8091)
* WasmExecutor takes a cache directory (#8057)
@@ -106,7 +116,7 @@ API
* Migrate assets pallet to new macros (#7984)
* contracts: Make ChainExtension trait generic over the runtime (#8003)
* Decouple the session validators from im-online (#7127)
* Update parity-scale-codec to 2.0 (#7994)
* Update `parity-scale-codec` to 2.0 (#7994)
* Merkle Mountain Range pallet improvements (#7891)
* Cleaner GRANDPA RPC API for proving finality (#7339)
* Migrate frame-system to pallet attribute macro (#7898)
@@ -136,8 +146,7 @@ API
* SystemOrigin trait (#7226)
* permit setting treasury pallet initial funding through genesis (#7214)
Runtime Migrations
------------------
#### Runtime Migrations
* Migrate assets pallet to new macros (#7984)
* Fix elections-phragmen and proxy issue (#7040)
@@ -149,8 +158,7 @@ Runtime Migrations
## 2.0.0-> 2.0.1
Patch release with backports to fix broken nightly builds.
Namely contains backports of
Patch release with backports to fix broken nightly builds. Namely contains backports of
* [#7381: Make Substrate compile with latest nightly](https://github.com/paritytech/substrate/pull/7381)
* [#7238: Fix compilation with environmental on latest nightly](https://github.com/paritytech/substrate/pull/7238)
@@ -161,8 +169,7 @@ Namely contains backports of
## 2.0.0-rc6 -> 2.0.0 two dot 😮
Runtime
-------
### Runtime
* Rename `ModuleToIndex` to `PalletRuntimeSetup` (#7148)
* Bounties (#5715)
@@ -174,8 +181,7 @@ Runtime
* Time-delay proxies (#6770)
* Refcounts are now u32 (#7164)
Client
------
### Client
* Rename `inspect-key` to `inspect` (#7160)
* Send import notification always for re-orgs (#7118)
@@ -190,8 +196,7 @@ Client
* Fix benchmark read/write key tracker for keys in child storages. (#6905)
* *: Update to next libp2p version 0.24.0 (#6891)
API
---
### API
* grandpa-rpc: use FinalityProofProvider to check finality for rpc (#6215)
* pow: replace the thread-base mining loop with a future-based mining worker (#7060)
@@ -204,16 +209,14 @@ API
* Add a `LightSyncState` field to the chain spec (#6894)
* *: Update to next libp2p version 0.24.0 (#6891)
Runtime Migrations
------------------
### Runtime Migrations
* Time-delay proxies (#6770)
## 2.0.0-rc5 -> 2.0.0-rc6 Rock Hyrax
Runtime
-------
### Runtime
* Custom Codec Implementation for NPoS Election (#6720)
* Successful `note_imminent_preimage` is free (#6793)
@@ -224,8 +227,7 @@ Runtime
* pallet-evm: add support for tuple-based precompile declarations (#6681)
* grandpa: allow noting that the set has stalled (#6725)
Client
------
#### Client
* Merge Subkey into sc-cli (#4954)
* RpcHandlers Refactorings (#6846)
@@ -239,8 +241,7 @@ Client
* Name all the tasks! (#6726)
* Child nodes can be handled by adding a child `TaskManager` to the parent's `TaskManager` (#6771)
API
---
### API
* pow: add access to pre-digest for algorithm verifiers (#6900)
* babe, aura, pow: only call check_inherents if authoring version is compatible (#6862)
@@ -254,8 +255,7 @@ API
## 2.0.0-rc4 -> 2.0.0-rc5 River Dolphin
Runtime
-------
### Runtime
* Support using system storage directly for EVM balance and nonce (#6659)
* Properly filter out duplicate voters in elections. (#6693)
@@ -273,14 +273,13 @@ Runtime
* pallet-evm: customizable chain id (#6537)
* Refactor as_sub to make things clearer. (#6503)
Client
------
### Client
* Update wasmtime to (almost) latest master (#6662)
* Update to latest sysinfo prevents leaking fd-handlers (#6708)
* Tracing values (#6679)
* Graceful shutdown for the task manager (#6654)
* Update substrate-networking Grafana dashboard (#6649)
* Update `substrate-networking` Grafana dashboard (#6649)
* *: Update to libp2p v0.21.1 (#6559)
* Send Status message on all newly-opened legacy substreams (#6593)
* babe: report equivocations (#6362)
@@ -288,8 +287,7 @@ Client
* Remove the service, replacing it with a struct of individual chain components (#6352)
* Fix tx-pool returning the same transaction multiple times (#6535)
API
---
### API
* Better handling of stable-only build (#6569)
* Remove the service builder (#6557)
@@ -302,8 +300,7 @@ API
## 2.0.0-rc3 -> 2.0.0-rc4 (Rhinoceros)
Runtime
-------
### Runtime
* Staking Payout Creates Controller (#6496)
* `pallet-scheduler`: Check that `when` is not in the past (#6480)
@@ -321,8 +318,7 @@ Runtime
* Add events for balance reserve and unreserve functions (#6330)
* Introduce frozen indices. (#6307)
Client
------
### Client
* client/network/service: Add primary dimension to connection metrics (#6472)
* Fix Babe secondary plain slots claiming (#6451)
@@ -340,8 +336,7 @@ Client
* new crate sc-light (#6235)
* Allow adding a prefix to the informant (#6174)
API
---
### API
* seal: Remove ext_dispatch_call and ext_get_runtime_storage (#6464)
* seal: Refactor ext_gas_price (#6478)
@@ -356,16 +351,14 @@ API
## 2.0.0-rc2 -> 2.0.0-rc3
Runtime
-------
### Runtime
* Introduce stacked filtering (#6273)
* Allow "pure" proxied accounts (#6236)
* Allow over-weight collective proposals to be closed (#6163)
* Fix Election when ForceNone V1 (#6166)
Client
------
### Client
* Make transaction pool prune transactions only of canonical blocks (#6123)
* Rename all the election operations (#6245)
@@ -381,14 +374,12 @@ Client
## 2.0.0-alpha.8 -> 2.0.0-rc1
Runtime
-------
### Runtime
* Allow operational recovery path if on_initialize use fullblock. (#6089)
* Maximum extrinsic weight limit (#6067)
Client
------
### Client
* Add JSON format to import blocks and set it as default (#5816)
* Upgrade to libp2p v0.19 - Changes the default PeerId representation (#6064)
@@ -396,17 +387,17 @@ Client
## 2.0.0-alpha.7 -> 2.0.0-alpha.8
**License Changed**
From this release forward, the code is released under a new more relaxed license scheme: Client (`sc-*`) is released under "GPL 3.0 or newer with the Classpath Exception", while primitives, FRAME, the pallets, utils and test-utils are released under "Apache 2.0". More details in the [Relax licensing scheme PR](https://github.com/paritytech/substrate/pull/5947).
**License Changed** From this release forward, the code is released under a new more relaxed license scheme: Client
(`sc-*`) is released under "GPL 3.0 or newer with the Classpath Exception", while primitives, FRAME, the pallets, utils
and test-utils are released under "Apache 2.0". More details in the [Relax licensing scheme
PR](https://github.com/paritytech/substrate/pull/5947).
Runtime
-------
### Runtime
* Democracy weight (#5828)
* Make `Digest` support `StorageAppend` (#5922)
Client
------
### Client
* Meter block import results via prometheus (#6025)
* Added RuntimePublic for ecdsa public key. (#6029)
@@ -418,8 +409,7 @@ Client
## 2.0.0-alpha.6 -> 2.0.0-alpha.7
Runtime
-------
### Runtime
* Use `storage::append` in the implementation of the storage types (#5889)
* pallet-sudo: Store `DispatchResult` in `Sudid` event (#5804)
@@ -431,8 +421,7 @@ Runtime
* Transaction versioning in the RuntimeVersion (#5582)
* emit TipClosed event on success tip payout (#5656)
Client
------
### Client
* Adds `export-state` subcommand (#5842)
* Drop ClientProvider (#5823)
@@ -454,8 +443,7 @@ Client
* Use a Kademlia instance per `ProtocolId`. (#5045)
* Report tasks metrics to Prometheus (#5619)
API
---
### API
* Child trie api changes BREAKING (#4857)
* Pass max-total to RewardRemainder on end_era (#5697)
@@ -463,8 +451,7 @@ API
## 2.0.0-alpha.5 -> 2.0.0-alpha.6
Runtime
-------
### Runtime
* Unsigned Validation best practices (#5563)
* Generate Unit Tests for Benchmarks (#5527)
@@ -473,8 +460,7 @@ Runtime
* Pass transaction source to validate_transaction (#5366)
* on_initialize return weight consumed and default cost to default DispatchInfo instead of zero (#5382)
Client
------
### Client
* Add new RPC method to get the chain type (#5576)
* Reuse wasmtime instances, the PR (#5567)
@@ -488,10 +474,10 @@ Client
* Make transactions and block announces use notifications substre… (#5360)
* Adds state_queryStorageAt (#5362)
* Offchain Phragmén BREAKING. (#4517)
* `sc_rpc::system::SystemInfo.impl_version` now returns the full version (2.0.0-alpha.2-b950f731c-x86_64-linux-gnu) instead of the short version (1.0.0) (#5271)
* `sc_rpc::system::SystemInfo.impl_version` now returns the full version (2.0.0-alpha.2-b950f731c-x86_64-linux-gnu)
instead of the short version (1.0.0) (#5271)
API
---
### API
* Unsigned Validation best practices (#5563)
* Split the Roles in three types (#5520)
@@ -501,16 +487,14 @@ API
## 2.0.0-alpha.4 -> 2.0.0-alpha.5
Runtime
-------
### Runtime
* pallet-evm: configurable gasometer config (#5320)
* Adds new event phase `Initialization` (#5302)
## 2.0.0-alpha.3 -> 2.0.0-alpha.4
Runtime
-------
### Runtime
* Move runtime upgrade to `frame-executive` (#5197)
* Split fees and tips between author and treasury independently (#5207)
@@ -520,22 +504,20 @@ Runtime
* Adds `vested_transfer` to Vesting pallet (#5029)
* Change extrinsic_count to extrinsic_index in pallet-utility (#5044)
Client
------
### Client
* client/finality-grandpa: Add Prometheus metrics to GossipValidator (#5237)
* removes use of sc_client::Client from node-transaction-factory (#5158)
* removes use of sc_client::Client from sc_network (#5147)
* Use CLI to configure max instances cache (#5177)
* client/service/src/builder.rs: Add build_info metric (#5192)
* Remove substrate-ui.parity.io from CORS whitelist (#5142)
* Remove `substrate-ui.parity.io` from CORS whitelist (#5142)
* removes use of sc_client::Client from sc-rpc (#5063)
* Use 128mb for db cache default (#5134)
* Drop db-cache default from 1gig to 32mb (#5128)
* Add more metrics to prometheus (#5034)
API
---
### API
* Produce block always on updated transaction pool state (#5227)
* Add `ext_terminate` (#5234)
+26 -14
View File
@@ -1,11 +1,14 @@
<!-- markdown-link-check-disable -->
# Security Policy
Parity Technologies is committed to resolving security vulnerabilities in our software quickly and carefully. We take the necessary steps to minimize risk, provide timely information, and deliver vulnerability fixes and mitigations required to address security issues.
Parity Technologies is committed to resolving security vulnerabilities in our software quickly and carefully. We take
the necessary steps to minimize risk, provide timely information, and deliver vulnerability fixes and mitigations
required to address security issues.
## Reporting a Vulnerability
Security vulnerabilities in Parity software should be reported by email to security@parity.io. If you think your report might be eligible for the Parity Bug Bounty Program, your email should be send to bugbounty@parity.io.
Security vulnerabilities in Parity software should be reported by email to security@parity.io. If you think your report
might be eligible for the Parity Bug Bounty Program, your email should be send to bugbounty@parity.io.
Your report should include the following:
@@ -16,11 +19,16 @@ Your report should include the following:
- reproduction
- other details
Try to include as much information in your report as you can, including a description of the vulnerability, its potential impact, and steps for reproducing it. Be sure to use a descriptive subject line.
Try to include as much information in your report as you can, including a description of the vulnerability, its
potential impact, and steps for reproducing it. Be sure to use a descriptive subject line.
You'll receive a response to your email within two business days indicating the next steps in handling your report. We encourage finders to use encrypted communication channels to protect the confidentiality of vulnerability reports. You can encrypt your report using our public key. This key is [on MIT's key server](https://pgp.mit.edu/pks/lookup?op=get&search=0x5D0F03018D07DE73) server and reproduced below.
You'll receive a response to your email within two business days indicating the next steps in handling your report. We
encourage finders to use encrypted communication channels to protect the confidentiality of vulnerability reports. You
can encrypt your report using our public key. This key is [on MIT's key
server](https://pgp.mit.edu/pks/lookup?op=get&search=0x5D0F03018D07DE73) server and reproduced below.
After the initial reply to your report, our team will endeavor to keep you informed of the progress being made towards a fix. These updates will be sent at least every five business days.
After the initial reply to your report, our team will endeavor to keep you informed of the progress being made towards a
fix. These updates will be sent at least every five business days.
Thank you for taking the time to responsibly disclose any vulnerabilities you find.
@@ -29,19 +37,23 @@ Thank you for taking the time to responsibly disclose any vulnerabilities you fi
Responsible investigation and reporting includes, but isn't limited to, the following:
- Don't violate the privacy of other users, destroy data, etc.
- Dont defraud or harm Parity Technologies Ltd or its users during your research; you should make a good faith effort to not interrupt or degrade our services.
- Don't target our physical security measures, or attempt to use social engineering, spam, distributed denial of service (DDOS) attacks, etc.
- Dont defraud or harm Parity Technologies Ltd or its users during your research; you should make a good faith effort
to not interrupt or degrade our services.
- Don't target our physical security measures, or attempt to use social engineering, spam, distributed denial of service
(DDOS) attacks, etc.
- Initially report the bug only to us and not to anyone else.
- Give us a reasonable amount of time to fix the bug before disclosing it to anyone else, and give us adequate written warning before disclosing it to anyone else.
- In general, please investigate and report bugs in a way that makes a reasonable, good faith effort not to be disruptive or harmful to us or our users. Otherwise your actions might be interpreted as an attack rather than an effort to be helpful.
- Give us a reasonable amount of time to fix the bug before disclosing it to anyone else, and give us adequate written
warning before disclosing it to anyone else.
- In general, please investigate and report bugs in a way that makes a reasonable, good faith effort not to be
disruptive or harmful to us or our users. Otherwise your actions might be interpreted as an attack rather than an
effort to be helpful.
## Bug Bounty Program
Our Bug Bounty Program allows us to recognize and reward members of the Parity community for helping us find and address significant bugs, in accordance with the terms of the Parity Bug Bounty Program. A detailed description on eligibility, rewards, legal information and terms & conditions for contributors can be found on [our website](https://paritytech.io/bug-bounty.html).
Our Bug Bounty Program allows us to recognize and reward members of the Parity community for helping us find and address
significant bugs, in accordance with the terms of the Parity Bug Bounty Program. A detailed description on eligibility,
rewards, legal information and terms & conditions for contributors can be found on [our
website](https://paritytech.io/bug-bounty.html).
## Plaintext PGP Key
+35 -35
View File
@@ -2,19 +2,18 @@
title: Style Guide for Rust in Substrate
---
Where possible these styles are enforced by settings in `rustfmt.toml` so if you run `cargo fmt`
then you will adhere to most of these style guidelines automatically.
Where possible these styles are enforced by settings in `rustfmt.toml` so if you run `cargo fmt` then you will adhere to
most of these style guidelines automatically.
# Code Formatting
- Indent using tabs.
- Lines should be longer than 100 characters long only in exceptional circumstances and certainly
no longer than 120. For this purpose, tabs are considered 4 characters wide.
- Indent levels should be greater than 5 only in exceptional circumstances and certainly no
greater than 8. If they are greater than 5, then consider using `let` or auxiliary functions in
order to strip out complex inline expressions.
- Never have spaces on a line prior to a non-whitespace character
- Follow-on lines are only ever a single indent from the original line.
- Indent using tabs.
- Lines should be longer than 100 characters long only in exceptional circumstances and certainly no longer than 120.
For this purpose, tabs are considered 4 characters wide.
- Indent levels should be greater than 5 only in exceptional circumstances and certainly no greater than 8. If they are
greater than 5, then consider using `let` or auxiliary functions in order to strip out complex inline expressions.
- Never have spaces on a line prior to a non-whitespace character
- Follow-on lines are only ever a single indent from the original line.
```rust
fn calculation(some_long_variable_a: i8, some_long_variable_b: i8) -> bool {
@@ -25,8 +24,8 @@ fn calculation(some_long_variable_a: i8, some_long_variable_b: i8) -> bool {
}
```
- Indent level should follow open parens/brackets, but should be collapsed to the smallest number
of levels actually used:
- Indent level should follow open parens/brackets, but should be collapsed to the smallest number of levels actually
used:
```rust
fn calculate(
@@ -45,10 +44,10 @@ fn calculate(
}
```
- `where` is indented, and its items are indented one further.
- Argument lists or function invocations that are too long to fit on one line are indented
similarly to code blocks, and once one param is indented in such a way, all others should be,
too. Run-on parameter lists are also acceptable for single-line run-ons of basic function calls.
- `where` is indented, and its items are indented one further.
- Argument lists or function invocations that are too long to fit on one line are indented similarly to code blocks, and
once one param is indented in such a way, all others should be, too. Run-on parameter lists are also acceptable for
single-line run-ons of basic function calls.
```rust
// OK
@@ -92,7 +91,7 @@ fn foo(really_long_parameter_name_1: SomeLongTypeName, really_long_parameter_nam
}
```
- Always end last item of a multi-line comma-delimited set with `,` when legal:
- Always end last item of a multi-line comma-delimited set with `,` when legal:
```rust
struct Point<T> {
@@ -104,7 +103,7 @@ struct Point<T> {
enum Meal { Breakfast, Lunch, Dinner };
```
- Avoid trailing `;`s where unneeded.
- Avoid trailing `;`s where unneeded.
```rust
if condition {
@@ -112,8 +111,8 @@ if condition {
}
```
- `match` arms may be either blocks or have a trailing `,` but not both.
- Blocks should not be used unnecessarily.
- `match` arms may be either blocks or have a trailing `,` but not both.
- Blocks should not be used unnecessarily.
```rust
match meal {
@@ -126,9 +125,8 @@ match meal {
# Style
- Panickers require explicit proofs they don't trigger. Calling `unwrap` is discouraged. The
exception to this rule is test code. Avoiding panickers by restructuring code is preferred if
feasible.
- Panickers require explicit proofs they don't trigger. Calling `unwrap` is discouraged. The exception to this rule is
test code. Avoiding panickers by restructuring code is preferred if feasible.
```rust
let mut target_path =
@@ -139,21 +137,22 @@ let mut target_path =
);
```
- Unsafe code requires explicit proofs just as panickers do. When introducing unsafe code,
consider trade-offs between efficiency on one hand and reliability, maintenance costs, and
security on the other. Here is a list of questions that may help evaluating the trade-off while
preparing or reviewing a PR:
- how much more performant or compact the resulting code will be using unsafe code,
- how likely is it that invariants could be violated,
- are issues stemming from the use of unsafe code caught by existing tests/tooling,
- what are the consequences if the problems slip into production.
- Unsafe code requires explicit proofs just as panickers do. When introducing unsafe code, consider trade-offs between
efficiency on one hand and reliability, maintenance costs, and security on the other. Here is a list of questions
that may help evaluating the trade-off while preparing or reviewing a PR:
- how much more performant or compact the resulting code will be using unsafe code,
- how likely is it that invariants could be violated,
- are issues stemming from the use of unsafe code caught by existing tests/tooling,
- what are the consequences if the problems slip into production.
# Manifest Formatting
> **TLDR**
> You can use the CLI tool [Zepter](https://crates.io/crates/zepter) to format the files: `zepter format features`
> **TLDR** You can use the CLI tool [Zepter](https://crates.io/crates/zepter) to format the files: `zepter format
> features`
Rust `Cargo.toml` files need to respect certain formatting rules. All entries need to be alphabetically sorted. This makes it easier to read them and insert new entries. The exhaustive list of rules is enforced by the CI. The general format looks like this:
Rust `Cargo.toml` files need to respect certain formatting rules. All entries need to be alphabetically sorted. This
makes it easier to read them and insert new entries. The exhaustive list of rules is enforced by the CI. The general
format looks like this:
- The feature is written as a single line if it fits within 80 chars:
```toml
@@ -161,7 +160,8 @@ Rust `Cargo.toml` files need to respect certain formatting rules. All entries ne
default = [ "std" ]
```
- Otherwise the feature is broken down into multiple lines with one entry per line. Each line is padded with one tab and no trailing spaces but a trailing comma.
- Otherwise the feature is broken down into multiple lines with one entry per line. Each line is padded with one tab and
no trailing spaces but a trailing comma.
```toml
[features]
default = [
+5 -3
View File
@@ -1,5 +1,7 @@
# Upgrade path for you building on substrate
# Upgrade path for you building on Substrate
## master
- crate rename has been fixed `sp-application-crypto` (was `sc-application-crypto`); `.maintain/rename-crates-for-2.0.sh` has been updated accordingly, you can use it to upgrade to latest naming convention
- crates have been renamed, run `bash .maintain/rename-crates-for-2.0.sh`
- crate rename has been fixed `sp-application-crypto` (was `sc-application-crypto`);
`.maintain/rename-crates-for-2.0.sh` has been updated accordingly, you can use it to upgrade to latest naming
convention
- crates have been renamed, run `bash .maintain/rename-crates-for-2.0.sh`
+103 -37
View File
@@ -4,7 +4,8 @@ An incomplete guide.
## Refreshing the node-template
Not much has changed on the top and API level for developing Substrate between 2.0 and 3.0. If you've made only small changes to the node-template, we recommend to do the following - it is easiest and quickest path forward:
Not much has changed on the top and API level for developing Substrate between 2.0 and 3.0. If you've made only small
changes to the node-template, we recommend to do the following - it is easiest and quickest path forward:
1. take a diff between 2.0 and your changes
2. store that diff
3. remove everything, copy over the 3.0 node-template
@@ -12,19 +13,30 @@ Not much has changed on the top and API level for developing Substrate between 2
## In-Depth guide on the changes
If you've made significant changes or diverted from the node-template a lot, starting out with that is probably not helping. For that case, we'll take a look at all changes between 2.0 and 3.0 to the fully-implemented node and explain them one by one, so you can follow up, what needs to be changing for your node.
If you've made significant changes or diverted from the node-template a lot, starting out with that is probably not
helping. For that case, we'll take a look at all changes between 2.0 and 3.0 to the fully-implemented node and explain
them one by one, so you can follow up, what needs to be changing for your node.
_Note_: Of course, step 1 is to upgrade your `Cargo.toml`'s to use the latest version of Substrate and all dependencies.
We'll be taking the diff from 2.0.1 to 3.0.0 on `bin/node` as the baseline of what has changed between these two versions in terms of adapting ones code base. We will not be covering the changes made on the tests and bench-marking as they are mostly reactions to the other changes.
We'll be taking the diff from 2.0.1 to 3.0.0 on `bin/node` as the baseline of what has changed between these two
versions in terms of adapting ones code base. We will not be covering the changes made on the tests and bench-marking as
they are mostly reactions to the other changes.
### Versions upgrade
First and foremost you have to upgrade the version pf the dependencies of course, that's `0.8.x -> 0.9.0` and `2.0.x -> 3.0.0` for all `sc-`, `sp-`, `frame-`, and `pallet-` coming from Parity. Further more this release also upgraded its own dependencies, most notably, we are now using `parity-scale-codec 2.0`, `parking_lot 0.11` and `substrate-wasm-builder 3.0.0` (as build dependency). All other dependency upgrades should resolve automatically or are just internal. However you might see some error that another dependency/type you have as a dependency and one of our upgraded crates don't match up, if so please check the version of said dependency - we've probably upgraded it.
First and foremost you have to upgrade the version pf the dependencies of course, that's `0.8.x -> 0.9.0` and `2.0.x ->
3.0.0` for all `sc-`, `sp-`, `frame-`, and `pallet-` coming from Parity. Further more this release also upgraded its own
dependencies, most notably, we are now using `parity-scale-codec 2.0`, `parking_lot 0.11` and `substrate-wasm-builder
3.0.0` (as build dependency). All other dependency upgrades should resolve automatically or are just internal. However
you might see some error that another dependency/type you have as a dependency and one of our upgraded crates don't
match up, if so please check the version of said dependency - we've probably upgraded it.
### WASM-Builder
The new version of wasm-builder has gotten a bit smarter and a lot faster (you should definitely switch). Once you've upgraded the dependency, in most cases you just have to remove the now obsolete `with_wasm_builder_from_crates_or_path`-function and you are good to go:
The new version of wasm-builder has gotten a bit smarter and a lot faster (you should definitely switch). Once you've
upgraded the dependency, in most cases you just have to remove the now obsolete
`with_wasm_builder_from_crates_or_path`-function and you are good to go:
```diff: rust
--- a/bin/node/runtime/build.rs
@@ -49,11 +61,15 @@ The new version of wasm-builder has gotten a bit smarter and a lot faster (you s
#### FRAME 2.0
The new FRAME 2.0 macros are a lot nicer to use and easier to read. While we were on that change though, we also cleaned up some mainly internal names and traits. The old `macro`'s still work and also produce the new structure, however, when plugging all that together as a Runtime, there's some things we have to adapt now:
The new FRAME 2.0 macros are a lot nicer to use and easier to read. While we were on that change though, we also cleaned
up some mainly internal names and traits. The old `macro`'s still work and also produce the new structure, however, when
plugging all that together as a Runtime, there's some things we have to adapt now:
##### `::Trait for Runtime` becomes `::Config for Runtime`
The most visible and significant change is that the macros no longer generate the `$pallet::Trait` but now a much more aptly named `$pallet::Config`. Thus, we need to rename all `::Trait for Runtime` into`::Config for Runtime`, e.g. for the `sudo` pallet we must do:
The most visible and significant change is that the macros no longer generate the `$pallet::Trait` but now a much more
aptly named `$pallet::Config`. Thus, we need to rename all `::Trait for Runtime` into`::Config for Runtime`, e.g. for
the `sudo` pallet we must do:
```diff
-impl pallet_sudo::Trait for Runtime {
@@ -65,11 +81,15 @@ The same goes for all `<Self as frame_system::Trait>` and alike, which simply be
#### SS58 Prefix is now a runtime param
Since [#7810](https://github.com/paritytech/substrate/pull/7810) we don't define the ss58 prefix in the chainspec anymore but moved it into the runtime. Namely, `frame_system` now needs a new `SS58Prefix`, which in substrate node we have defined for ourselves as: `pub const SS58Prefix: u8 = 42;`. Use your own chain-specific value there.
Since [#7810](https://github.com/paritytech/substrate/pull/7810) we don't define the ss58 prefix in the chainspec
anymore but moved it into the runtime. Namely, `frame_system` now needs a new `SS58Prefix`, which in Substrate node we
have defined for ourselves as: `pub const SS58Prefix: u8 = 42;`. Use your own chain-specific value there.
#### Weight Definition
`type WeightInfo` has changed and instead on `weights::pallet_$name::WeightInfo` is now bound to the Runtime as `pallet_$name::weights::SubstrateWeight<Runtime>`. As a result we have to the change the type definitions everywhere in our Runtime accordingly:
`type WeightInfo` has changed and instead on `weights::pallet_$name::WeightInfo` is now bound to the Runtime as
`pallet_$name::weights::SubstrateWeight<Runtime>`. As a result we have to the change the type definitions everywhere in
our Runtime accordingly:
```diff
- type WeightInfo = weights::pallet_$name::WeightInfo;
@@ -170,24 +190,29 @@ And update the overall definition for weights on frame and a few related types a
+ type SystemWeightInfo = frame_system::weights::SubstrateWeight<Runtime>;
```
#### Pallets:
#### Pallets
##### Assets
The assets pallet has seen a variety of changes:
- [Features needed for reserve-backed stablecoins #7152 ](https://github.com/paritytech/substrate/pull/7152)
- [Freeze Assets and Asset Metadata #7346 ](https://github.com/paritytech/substrate/pull/7346)
- [Introduces account existence providers reference counting #7363 ]((https://github.com/paritytech/substrate/pull/7363))
- [Features needed for reserve-backed stablecoins #7152](https://github.com/paritytech/substrate/pull/7152)
- [Freeze Assets and Asset Metadata #7346](https://github.com/paritytech/substrate/pull/7346)
- [Introduces account existence providers reference counting #7363]((https://github.com/paritytech/substrate/pull/7363))
have all altered the feature set and changed the concepts. However, it has some of the best documentation and explains the current state very well. If you are using the assets pallet and need to upgrade from an earlier version, we recommend you use the current docs to guide your way!
have all altered the feature set and changed the concepts. However, it has some of the best documentation and explains
the current state very well. If you are using the assets pallet and need to upgrade from an earlier version, we
recommend you use the current docs to guide your way!
##### Contracts
As noted in the changelog, the `contracts`-pallet is still undergoing massive changes and is not yet part of this release. We are expecting for it to be released a few weeks after. If your chain is dependent on this pallet, we recommend to wait until it has been released as the currently released version is not compatible with FRAME 2.0.
As noted in the changelog, the `contracts`-pallet is still undergoing massive changes and is not yet part of this
release. We are expecting for it to be released a few weeks after. If your chain is dependent on this pallet, we
recommend to wait until it has been released as the currently released version is not compatible with FRAME 2.0.
#### (changes) Treasury
As mentioned above, Bounties, Tips and Lottery have been extracted out of treasury into their own pallets - removing these options here. Secondly we must now specify the `BurnDestination` and `SpendFunds`, which now go the `Bounties`.
As mentioned above, Bounties, Tips and Lottery have been extracted out of treasury into their own pallets - removing
these options here. Secondly we must now specify the `BurnDestination` and `SpendFunds`, which now go the `Bounties`.
```diff
- type Tippers = Elections;
@@ -206,9 +231,10 @@ As mentioned above, Bounties, Tips and Lottery have been extracted out of treasu
+ type SpendFunds = Bounties;
```
Factoring out Bounties and Tips means most of these definitions have now moved there, while the parameter types can be left as they were:
Factoring out Bounties and Tips means most of these definitions have now moved there, while the parameter types can be
left as they were:
###### 🆕 Bounties
##### 🆕 Bounties
```rust=
impl pallet_bounties::Config for Runtime {
@@ -241,11 +267,15 @@ impl pallet_tips::Config for Runtime {
#### `FinalityTracker` removed
Finality Tracker has been removed in favor of a different approach to handle the issue in GRANDPA, [see #7228 for details](https://github.com/paritytech/substrate/pull/7228). With latest GRANDPA this is not needed anymore and can be removed without worry.
Finality Tracker has been removed in favor of a different approach to handle the issue in GRANDPA, [see #7228 for
details](https://github.com/paritytech/substrate/pull/7228). With latest GRANDPA this is not needed anymore and can be
removed without worry.
#### (changes) Elections Phragmen
The pallet has been moved to a new system in which the exact amount of deposit for each voter, candidate, member, or runner-up is now deposited on-chain. Moreover, the concept of a `defunct_voter` is removed, since votes now have adequate deposit associated with them. A number of configuration parameters has changed to reflect this, as shown below:
The pallet has been moved to a new system in which the exact amount of deposit for each voter, candidate, member, or
runner-up is now deposited on-chain. Moreover, the concept of a `defunct_voter` is removed, since votes now have
adequate deposit associated with them. A number of configuration parameters has changed to reflect this, as shown below:
```diff=
parameter_types! {
@@ -277,11 +307,16 @@ The pallet has been moved to a new system in which the exact amount of deposit f
type TermDuration = TermDuration;
```
**This upgrade requires storage [migration](https://github.com/paritytech/substrate/blob/master/frame/elections-phragmen/src/migrations_3_0_0.rs)**. Further details can be found in the [pallet-specific changelog](https://github.com/paritytech/substrate/blob/master/frame/elections-phragmen/CHANGELOG.md#security).
**This upgrade requires storage
[migration](https://github.com/paritytech/substrate/blob/master/frame/elections-phragmen/src/migrations_3_0_0.rs)**.
Further details can be found in the [pallet-specific
changelog](https://github.com/paritytech/substrate/blob/master/frame/elections-phragmen/CHANGELOG.md#security).
#### (changes) Democracy
Democracy brings three new settings with this release, all to allow for better influx- and spam-control. Namely these allow to specify the maximum number of proposals at a time, who can blacklist and who can cancel proposals. This diff acts as a good starting point:
Democracy brings three new settings with this release, all to allow for better influx- and spam-control. Namely these
allow to specify the maximum number of proposals at a time, who can blacklist and who can cancel proposals. This diff
acts as a good starting point:
```diff=
@@ -508,6 +537,14 @@ impl pallet_democracy::Trait for Runtime {
@@ -311,7 +346,9 @@ Democracy brings three new settings with this release, all to allow for better i
### Primitives
The shared primitives define the API between Client and Runtime. Usually, you don't have to touch nor directly interact with them, unless you created your own client or frame-less runtime. Therefore we'd expect you to understand whether you are effected by changes and how to update your code yourself.
The shared primitives define the API between Client and Runtime. Usually, you don't have to touch nor directly interact
with them, unless you created your own client or frame-less runtime. Therefore we'd expect you to understand whether you
are effected by changes and how to update your code yourself.
----
@@ -321,10 +358,17 @@ The shared primitives define the API between Client and Runtime. Usually, you do
A few minor things have changed in the `cli` (compared to 2.0.1):
1. we've [replaced the newly added `BuildSyncSpec` subcommand with an RPC API](https://github.com/paritytech/substrate/commit/65cc9af9b8df8d36928f6144ee7474cefbd70454#diff-c57da6fbeff8c46ce15f55ea42fedaa5a4684d79578006ce4af01ae04fd6b8f8) in an on-going effort to make light-client-support smoother, see below
2. we've [removed double accounts from our chainspec-builder](https://github.com/paritytech/substrate/commit/31499cd29ed30df932fb71b7459796f7160d0272)
3. we [don't fallback to `--chain flaming-fir` anymore](https://github.com/paritytech/substrate/commit/13cdf1c8cd2ee62d411f82b64dc7eba860c9c6c6), if no chain is given our substrate-node will error.
4. [the `subkey`-integration has seen a fix to the `insert`-command](https://github.com/paritytech/substrate/commit/54bde60cfd2c544c54e9e8623b6b8725b99557f8) that requires you to now add the `&cli` as a param.
1. we've [replaced the newly added `BuildSyncSpec` subcommand with an RPC
API](https://github.com/paritytech/substrate/commit/65cc9af9b8df8d36928f6144ee7474cefbd70454#diff-c57da6fbeff8c46ce15f55ea42fedaa5a4684d79578006ce4af01ae04fd6b8f8)
in an on-going effort to make light-client-support smoother, see below
2. we've [removed double accounts from our
chainspec-builder](https://github.com/paritytech/substrate/commit/31499cd29ed30df932fb71b7459796f7160d0272)
3. we [don't fallback to `--chain flaming-fir`
anymore](https://github.com/paritytech/substrate/commit/13cdf1c8cd2ee62d411f82b64dc7eba860c9c6c6), if no chain is
given our `substrate-node` will error.
4. [the `subkey`-integration has seen a fix to the
`insert`-command](https://github.com/paritytech/substrate/commit/54bde60cfd2c544c54e9e8623b6b8725b99557f8) that
requires you to now add the `&cli` as a param.
```diff=
--- a/bin/node/cli/src/command.rs
+++ b/bin/node/cli/src/command.rs
@@ -344,7 +388,8 @@ A few minor things have changed in the `cli` (compared to 2.0.1):
##### Light client support
As said, we've added a new optional RPC service for improved light client support. For that to work, we need to pass the `chain_spec` and give access to the `AuxStore` to our `rpc`:
As said, we've added a new optional RPC service for improved light client support. For that to work, we need to pass the
`chain_spec` and give access to the `AuxStore` to our `rpc`:
```diff=
@@ -438,17 +483,30 @@ and add the new service:
##### Telemetry
The telemetry subsystem has seen a few fixes and refactorings to allow for a more flexible handling, in particular in regards to parachains. Most notably `sc_service::spawn_tasks` now returns the `telemetry_connection_notifier` as the second member of the tuple, (`let (_rpc_handlers, telemetry_connection_notifier) = sc_service::spawn_tasks(`), which should be passed to `telemetry_on_connect` of `new_full_base` now: `telemetry_on_connect: telemetry_connection_notifier.map(|x| x.on_connect_stream()),` (see the service-section below for a full diff).
The telemetry subsystem has seen a few fixes and refactorings to allow for a more flexible handling, in particular in
regards to parachains. Most notably `sc_service::spawn_tasks` now returns the `telemetry_connection_notifier` as the
second member of the tuple, (`let (_rpc_handlers, telemetry_connection_notifier) = sc_service::spawn_tasks(`), which
should be passed to `telemetry_on_connect` of `new_full_base` now: `telemetry_on_connect:
telemetry_connection_notifier.map(|x| x.on_connect_stream()),` (see the service-section below for a full diff).
##### Async & Remote Keystore support
In order to allow for remote-keystores, the keystore-subsystem has been reworked to support async operations and generally refactored to not provide the keys itself but only sign on request. This allows for remote-keystore to never hand out keys and thus to operate any substrate-based node in a manner without ever having the private keys in the local system memory.
In order to allow for remote-keystores, the keystore-subsystem has been reworked to support async operations and
generally refactored to not provide the keys itself but only sign on request. This allows for remote-keystore to never
hand out keys and thus to operate any Substrate-based node in a manner without ever having the private keys in the local
system memory.
There are some operations, however, that the keystore must be local for performance reasons and for which a remote keystore won't work (in particular around parachains). As such, the keystore has both a slot for remote but also always a local instance, where some operations hard bind to the local variant, while most subsystems just ask the generic keystore which prefers a remote signer if given. To reflect this change, `sc_service::new_full_parts` now returns a `KeystoreContainer` rather than the keystore, and the other subsystems (e.g. `sc_service::PartialComponents`) expect to be given that.
There are some operations, however, that the keystore must be local for performance reasons and for which a remote
keystore won't work (in particular around parachains). As such, the keystore has both a slot for remote but also always
a local instance, where some operations hard bind to the local variant, while most subsystems just ask the generic
keystore which prefers a remote signer if given. To reflect this change, `sc_service::new_full_parts` now returns a
`KeystoreContainer` rather than the keystore, and the other subsystems (e.g. `sc_service::PartialComponents`) expect to
be given that.
###### on RPC:
###### on RPC
This has most visible changes for the rpc, where we are switching from the previous `KeyStorePtr` to the new `SyncCryptoStorePtr`:
This has most visible changes for the rpc, where we are switching from the previous `KeyStorePtr` to the new
`SyncCryptoStorePtr`:
```diff
@@ -483,9 +541,15 @@ This has most visible changes for the rpc, where we are switching from the previ
##### GRANDPA
As already in the changelog, a few things significant things have changed in regards to GRANDPA: the finality tracker has been replaced, an RPC command has been added and WARP-sync-support for faster light client startup has been implemented. All this means we have to do a few changes to our GRANDPA setup procedures in the client.
As already in the changelog, a few things significant things have changed in regards to GRANDPA: the finality tracker
has been replaced, an RPC command has been added and WARP-sync-support for faster light client startup has been
implemented. All this means we have to do a few changes to our GRANDPA setup procedures in the client.
First and foremost, grandpa internalised a few aspects, and thus `new_partial` doesn't expect a tuple but only the `grandpa::SharedVoterState` as input now, and unpacking that again later is not needed anymore either. On the opposite side `grandpa::FinalityProofProvider::new_for_service` now requires the `Some(shared_authority_set)` to be passed as a new third parameter. This set also becomes relevant when adding warp-sync-support, which is added as an extra-protocol-layer to the networking as:
First and foremost, grandpa internalised a few aspects, and thus `new_partial` doesn't expect a tuple but only the
`grandpa::SharedVoterState` as input now, and unpacking that again later is not needed anymore either. On the opposite
side `grandpa::FinalityProofProvider::new_for_service` now requires the `Some(shared_authority_set)` to be passed as a
new third parameter. This set also becomes relevant when adding warp-sync-support, which is added as an
extra-protocol-layer to the networking as:
```diff=
+ config.network.extra_sets.push(grandpa::grandpa_peers_set_config());
@@ -496,11 +560,13 @@ First and foremost, grandpa internalised a few aspects, and thus `new_partial` d
+ ));
```
As these changes pull through the entirety of `cli/src/service.rs`, we recommend looking at the final diff below for guidance.
As these changes pull through the entirety of `cli/src/service.rs`, we recommend looking at the final diff below for
guidance.
##### In a nutshell
Altogether this accumulates to the following diff for `node/cli/src/service.rs`. If you want these features and have modified your chain you should probably try to apply these patches:
Altogether this accumulates to the following diff for `node/cli/src/service.rs`. If you want these features and have
modified your chain you should probably try to apply these patches:
```diff=
+45 -51
View File
@@ -1,71 +1,65 @@
# Substrate Node Template Release Process
1. This release process has to be run in a github checkout Substrate directory with your work
committed into `https://github.com/paritytech/substrate/`, because the build script will check
the existence of your current git commit ID in the remote repository.
## This release process has to be run in a github checkout Substrate directory with your work committed into
`https://github.com/paritytech/substrate/`, because the build script will check the existence of your current git commit
ID in the remote repository.
Assume you are in root directory of Substrate. Run:
Assume you are in root directory of Substrate. Run:
```bash
cd scripts/ci/
./node-template-release.sh <output tar.gz file>
```
```bash
cd scripts/ci/ ./node-template-release.sh <output tar.gz file>
```
2. Expand the output tar gzipped file and replace files in current Substrate Node Template
by running the following command.
## Expand the output tar gzipped file and replace files in current Substrate Node Template by running the following
command.
```bash
# This is where the tar.gz file uncompressed
cd substrate-node-template
# rsync with force copying. Note the slash at the destination directory is important
rsync -avh * <destination node-template directory>/
# For dry-running add `-n` argument
# rsync -avhn * <destination node-template directory>/
```
```bash
# This is where the tar.gz file uncompressed cd substrate-node-template # rsync with force copying. Note the
slash at the destination directory is important rsync -avh * <destination node-template directory>/ # For dry-running
add `-n` argument # rsync -avhn * <destination node-template directory>/
```
The above command only copies existing files from the source to the destination, but does not
delete files/directories that are removed from the source. So you need to manually check and
remove them in the destination.
The above command only copies existing files from the source to the destination, but does not delete files/directories
that are removed from the source. So you need to manually check and remove them in the destination.
3. There is a `Cargo.toml` file in the root directory. Inside, dependencies are listed form and
linked to a certain git commit in Substrate remote repository, such as:
## There is a `Cargo.toml` file in the root directory. Inside, dependencies are listed form and linked to a certain git
commit in Substrate remote repository, such as:
```toml
sp-core = { version = "7.0.0", git = "https://github.com/paritytech/substrate.git", rev = "de80d0107336a9c7a2efdc0199015e4d67fcbdb5", default-features = false }
```
```toml
toml sp-core = { version = "7.0.0", git = "https://github.com/paritytech/substrate.git", rev =
"de80d0107336a9c7a2efdc0199015e4d67fcbdb5", default-features = false }
```
We will update each of them to link to the Rust [crate registry](https://crates.io/).
After confirming the versioned package is published in the crate, the above will become:
e will update each of them to link to the Rust [crate registry](https://crates.io/). After confirming the versioned
package is published in the crate, the above will become:
```toml
[workspace.dependencies]
sp-core = { version = "7.0.0", default-features = false }
```
```toml
[workspace.dependencies] sp-core = { version = "7.0.0", default-features = false }
```
P.S: This step can be automated if we update `node-template-release` package in
`scripts/ci/node-template-release`.
P.S: This step can be automated if we update `node-template-release` package in `scripts/ci/node-template-release`.
4. Once the `Cargo.toml` is updated, compile and confirm that the Node Template builds. Then commit
the changes to a new branch in [Substrate Node Template](https://github.com/substrate-developer-hub/substrate-node-template), and make a PR.
## Once the `Cargo.toml` is updated, compile and confirm that the Node Template builds. Then commit the changes to a new
branch in [Substrate Node Template](https://github.com/substrate-developer-hub/substrate-node-template), and make a PR.
> Note that there is a chance the code in Substrate Node Template works with the linked Substrate git
commit but not with published packages due to the latest (as yet) unpublished features. In this case,
rollback that section of the Node Template to its previous version to ensure the Node Template builds.
> Note that there is a chance the code in Substrate Node Template works with the linked Substrate git commit but not
with published packages due to the latest (as yet) unpublished features. In this case, rollback that section of the
Node Template to its previous version to ensure the Node Template builds.
5. Once the PR is merged, tag the merged commit in master branch with the version number
`vX.Y.Z+A` (e.g. `v3.0.0+1`). The `X`(major), `Y`(minor), and `Z`(patch) version number should
follow Substrate release version. The last digit is any significant fixes made in the Substrate
Node Template apart from Substrate. When the Substrate version is updated, this digit is reset to 0.
## Once the PR is merged, tag the merged commit in master branch with the version number `vX.Y.Z+A` (e.g. `v3.0.0+1`)
The `X`(major), `Y`(minor), and `Z`(patch) version number should follow Substrate release version. The last digit is any
significant fixes made in the Substrate Node Template apart from Substrate. When the Substrate version is updated, this
digit is reset to 0.
## Troubleshooting
- Running the script `./node-template-release.sh <output tar.gz file>`, after all tests passed
successfully, seeing the following error message:
- Running the script `./node-template-release.sh <output tar.gz file>`, after all tests passed successfully, seeing the
following error message:
```
thread 'main' panicked at 'Creates output file: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:250:10
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```
```
thread 'main' panicked at 'Creates output file: Os { code: 2, kind: NotFound, message: "No such file or directory"
}', src/main.rs:250:10 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```
This is likely due to that your output path is not a valid `tar.gz` filename or you don't have write
permission to the destination. Try with a simple output path such as `~/node-tpl.tar.gz`.
This is likely due to that your output path is not a valid `tar.gz` filename or you don't have write permission to the
destination. Try with a simple output path such as `~/node-tpl.tar.gz`.
+4 -3
View File
@@ -1,11 +1,12 @@
# FRAME
The FRAME development environment provides modules (called "pallets") and support libraries that you can use, modify, and extend to build the runtime logic to suit the needs of your blockchain.
The FRAME development environment provides modules (called "pallets") and support libraries that you can use, modify,
and extend to build the runtime logic to suit the needs of your blockchain.
### Documentation
## Documentation
https://docs.substrate.io/reference/frame-pallets/
### Issues
## Issues
https://github.com/orgs/paritytech/projects/40
+17 -18
View File
@@ -4,21 +4,21 @@ A simple, secure module for dealing with fungible assets.
## Overview
The Assets module provides functionality for asset management of fungible asset classes
with a fixed supply, including:
The Assets module provides functionality for asset management of fungible asset classes with a fixed supply, including:
* Asset Issuance
* Asset Transfer
* Asset Destruction
To use it in your runtime, you need to implement the assets [`assets::Config`](https://docs.rs/pallet-assets/latest/pallet_assets/pallet/trait.Config.html).
To use it in your runtime, you need to implement the assets
[`assets::Config`](https://docs.rs/pallet-assets/latest/pallet_assets/pallet/trait.Config.html).
The supported dispatchable functions are documented in the [`assets::Call`](https://docs.rs/pallet-assets/latest/pallet_assets/pallet/enum.Call.html) enum.
The supported dispatchable functions are documented in the
[`assets::Call`](https://docs.rs/pallet-assets/latest/pallet_assets/pallet/enum.Call.html) enum.
### Terminology
* **Asset issuance:** The creation of a new asset, whose total supply will belong to the
account that issues the asset.
* **Asset issuance:** The creation of a new asset, whose total supply will belong to the account that issues the asset.
* **Asset transfer:** The action of transferring assets from one account to another.
* **Asset destruction:** The process of an account removing its entire holding of an asset.
* **Fungible asset:** An asset whose units are interchangeable.
@@ -30,20 +30,19 @@ The assets system in Substrate is designed to make the following possible:
* Issue a unique asset to its creator's account.
* Move assets between accounts.
* Remove an account's balance of an asset when requested by that account's owner and update
the asset's total supply.
* Remove an account's balance of an asset when requested by that account's owner and update the asset's total supply.
## Interface
### Dispatchable Functions
* `issue` - Issues the total supply of a new fungible asset to the account of the caller of the function.
* `transfer` - Transfers an `amount` of units of fungible asset `id` from the balance of
the function caller's account (`origin`) to a `target` account.
* `destroy` - Destroys the entire holding of a fungible asset `id` associated with the account
that called the function.
* `transfer` - Transfers an `amount` of units of fungible asset `id` from the balance of the function caller's account
(`origin`) to a `target` account.
* `destroy` - Destroys the entire holding of a fungible asset `id` associated with the account that called the function.
Please refer to the [`Call`](https://docs.rs/pallet-assets/latest/pallet_assets/enum.Call.html) enum and its associated variants for documentation on each function.
Please refer to the [`Call`](https://docs.rs/pallet-assets/latest/pallet_assets/enum.Call.html) enum and its associated
variants for documentation on each function.
### Public Functions
<!-- Original author of descriptions: @gavofyork -->
@@ -51,7 +50,8 @@ Please refer to the [`Call`](https://docs.rs/pallet-assets/latest/pallet_assets/
* `balance` - Get the asset `id` balance of `who`.
* `total_supply` - Get the total supply of an asset `id`.
Please refer to the [`Pallet`](https://docs.rs/pallet-assets/latest/pallet_assets/pallet/struct.Pallet.html) struct for details on publicly available functions.
Please refer to the [`Pallet`](https://docs.rs/pallet-assets/latest/pallet_assets/pallet/struct.Pallet.html) struct for
details on publicly available functions.
## Usage
@@ -111,11 +111,10 @@ pub mod pallet {
## Assumptions
Below are assumptions that must be held when using this module. If any of
them are violated, the behavior of this module is undefined.
Below are assumptions that must be held when using this module. If any of them are violated, the behavior of this
module is undefined.
* The total count of assets should be less than
`Config::AssetId::max_value()`.
* The total count of assets should be less than `Config::AssetId::max_value()`.
## Related Modules
+3 -3
View File
@@ -16,8 +16,8 @@ claimed within a specified duration of time, the sender may cancel it.
### Dispatchable Functions
* `create_swap` - called by a sender to register a new atomic swap
* `claim_swap` - called by the target to approve a swap
* `cancel_swap` - may be called by a sender after a specified duration
- `create_swap` - called by a sender to register a new atomic swap
- `claim_swap` - called by the target to approve a swap
- `cancel_swap` - may be called by a sender after a specified duration
License: Apache-2.0
+2 -1
View File
@@ -23,6 +23,7 @@ consensus rounds (via `slots`).
If you're interested in hacking on this module, it is useful to understand the interaction with
`substrate/primitives/inherents/src/lib.rs` and, specifically, the required implementation of
[`ProvideInherent`](https://docs.rs/sp-inherents/latest/sp_inherents/trait.ProvideInherent.html) and
[`ProvideInherentData`](https://docs.rs/sp-inherents/latest/sp_inherents/trait.ProvideInherentData.html) to create and check inherents.
[`ProvideInherentData`](https://docs.rs/sp-inherents/latest/sp_inherents/trait.ProvideInherentData.html) to create and
check inherents.
License: Apache-2.0
@@ -1,6 +1,6 @@
# Authority discovery module.
# Authority discovery module
This module is used by the `client/authority-discovery` to retrieve the
current set of authorities.
License: Apache-2.0
License: Apache-2.0
+1 -1
View File
@@ -2,4 +2,4 @@ Authorship tracking for FRAME runtimes.
This tracks the current author of the block and recent uncles.
License: Apache-2.0
License: Apache-2.0
+1 -1
View File
@@ -1,4 +1,4 @@
Consensus extension module for BABE consensus. Collects on-chain randomness
from VRF outputs and manages epoch transitions.
License: Apache-2.0
License: Apache-2.0
+31 -31
View File
@@ -21,49 +21,48 @@ The Balances module provides functions for:
### Terminology
- **Existential Deposit:** The minimum balance required to create or keep an account open. This prevents
"dust accounts" from filling storage. When the free plus the reserved balance (i.e. the total balance)
fall below this, then the account is said to be dead; and it loses its functionality as well as any
prior history and all information on it is removed from the chain's state.
No account should ever have a total balance that is strictly between 0 and the existential
deposit (exclusive). If this ever happens, it indicates either a bug in this module or an
erroneous raw mutation of storage.
- **Existential Deposit:** The minimum balance required to create or keep an account open. This prevents "dust accounts"
from filling storage. When the free plus the reserved balance (i.e. the total balance) fall below this, then the account
is said to be dead; and it loses its functionality as well as any prior history and all information on it is removed
from the chain's state. No account should ever have a total balance that is strictly between 0 and the existential
deposit (exclusive). If this ever happens, it indicates either a bug in this module or an erroneous raw mutation of
storage.
- **Total Issuance:** The total number of units in existence in a system.
- **Reaping an account:** The act of removing an account by resetting its nonce. Happens after its
total balance has become zero (or, strictly speaking, less than the Existential Deposit).
- **Reaping an account:** The act of removing an account by resetting its nonce. Happens after its total balance has
become zero (or, strictly speaking, less than the Existential Deposit).
- **Free Balance:** The portion of a balance that is not reserved. The free balance is the only
balance that matters for most operations.
- **Free Balance:** The portion of a balance that is not reserved. The free balance is the only balance that matters for
most operations.
- **Reserved Balance:** Reserved balance still belongs to the account holder, but is suspended.
Reserved balance can still be slashed, but only after all the free balance has been slashed.
- **Reserved Balance:** Reserved balance still belongs to the account holder, but is suspended. Reserved balance can
still be slashed, but only after all the free balance has been slashed.
- **Imbalance:** A condition when some funds were credited or debited without equal and opposite accounting
(i.e. a difference between total issuance and account balances). Functions that result in an imbalance will
return an object of the `Imbalance` trait that can be managed within your runtime logic. (If an imbalance is
simply dropped, it should automatically maintain any book-keeping such as total issuance.)
- **Imbalance:** A condition when some funds were credited or debited without equal and opposite accounting (i.e. a
difference between total issuance and account balances). Functions that result in an imbalance will return an object of
the `Imbalance` trait that can be managed within your runtime logic. (If an imbalance is simply dropped, it should
automatically maintain any book-keeping such as total issuance.)
- **Lock:** A freeze on a specified amount of an account's free balance until a specified block number. Multiple
locks always operate over the same funds, so they "overlay" rather than "stack".
- **Lock:** A freeze on a specified amount of an account's free balance until a specified block number. Multiple locks
always operate over the same funds, so they "overlay" rather than "stack".
### Implementations
The Balances module provides implementations for the following traits. If these traits provide the functionality
that you need, then you can avoid coupling with the Balances module.
The Balances module provides implementations for the following traits. If these traits provide the functionality that
you need, then you can avoid coupling with the Balances module.
- [`Currency`](https://docs.rs/frame-support/latest/frame_support/traits/trait.Currency.html): Functions for dealing with a
fungible assets system.
- [`Currency`](https://docs.rs/frame-support/latest/frame_support/traits/trait.Currency.html): Functions for dealing
with a fungible assets system.
- [`ReservableCurrency`](https://docs.rs/frame-support/latest/frame_support/traits/trait.ReservableCurrency.html):
Functions for dealing with assets that can be reserved from an account.
- [`LockableCurrency`](https://docs.rs/frame-support/latest/frame_support/traits/trait.LockableCurrency.html): Functions for
dealing with accounts that allow liquidity restrictions.
- [`LockableCurrency`](https://docs.rs/frame-support/latest/frame_support/traits/trait.LockableCurrency.html): Functions
for dealing with accounts that allow liquidity restrictions.
- [`Imbalance`](https://docs.rs/frame-support/latest/frame_support/traits/trait.Imbalance.html): Functions for handling
imbalances between total issuance in the system and account balances. Must be used when a function
creates new funds (e.g. a reward) or destroys some funds (e.g. a system fee).
- [`IsDeadAccount`](https://docs.rs/frame-support/latest/frame_support/traits/trait.IsDeadAccount.html): Determiner to say whether a
given account is unused.
imbalances between total issuance in the system and account balances. Must be used when a function creates new funds
(e.g. a reward) or destroys some funds (e.g. a system fee).
- [`IsDeadAccount`](https://docs.rs/frame-support/latest/frame_support/traits/trait.IsDeadAccount.html): Determiner to
say whether a given account is unused.
## Interface
@@ -113,10 +112,11 @@ fn update_ledger<T: Config>(
## Genesis config
The Balances module depends on the [`GenesisConfig`](https://docs.rs/pallet-balances/latest/pallet_balances/pallet/struct.GenesisConfig.html).
The Balances module depends on the
[`GenesisConfig`](https://docs.rs/pallet-balances/latest/pallet_balances/pallet/struct.GenesisConfig.html).
## Assumptions
* Total issued balanced of all accounts should be less than `Config::Balance::max_value()`.
- Total issued balanced of all accounts should be less than `Config::Balance::max_value()`.
License: Apache-2.0
+83 -98
View File
@@ -1,99 +1,86 @@
# Substrate Runtime Benchmarking Framework
This crate contains a set of utilities that can be used to benchmark and weigh FRAME pallets that
you develop for your Substrate Runtime.
This crate contains a set of utilities that can be used to benchmark and weigh FRAME pallets that you develop for your
Substrate Runtime.
## Overview
Substrate's FRAME framework allows you to develop custom logic for your blockchain that can be
included in your runtime. This flexibility is key to help you design complex and interactive
pallets, but without accurate weights assigned to dispatchables, your blockchain may become
vulnerable to denial of service (DoS) attacks by malicious actors.
Substrate's FRAME framework allows you to develop custom logic for your blockchain that can be included in your runtime.
This flexibility is key to help you design complex and interactive pallets, but without accurate weights assigned to
dispatchables, your blockchain may become vulnerable to denial of service (DoS) attacks by malicious actors.
The Substrate Runtime Benchmarking Framework is a tool you can use to mitigate DoS attacks against
your blockchain network by benchmarking the computational resources required to execute different
functions in the runtime, for example extrinsics, `on_initialize`, `verify_unsigned`, etc...
The Substrate Runtime Benchmarking Framework is a tool you can use to mitigate DoS attacks against your blockchain
network by benchmarking the computational resources required to execute different functions in the runtime, for example
extrinsics, `on_initialize`, `verify_unsigned`, etc...
The general philosophy behind the benchmarking system is: If your node can know ahead of time how
long it will take to execute an extrinsic, it can safely make decisions to include or exclude that
extrinsic based on its available resources. By doing this, it can keep the block production and
import process running smoothly.
The general philosophy behind the benchmarking system is: If your node can know ahead of time how long it will take to
execute an extrinsic, it can safely make decisions to include or exclude that extrinsic based on its available
resources. By doing this, it can keep the block production and import process running smoothly.
To achieve this, we need to model how long it takes to run each function in the runtime by:
* Creating custom benchmarking logic that executes a specific code path of a function.
* Executing the benchmark in the Wasm execution environment, on a specific set of hardware, with a
custom runtime configuration, etc...
* Executing the benchmark across controlled ranges of possible values that may affect the result of
the benchmark (called "components").
* Executing the benchmark in the Wasm execution environment, on a specific set of hardware, with a custom runtime
configuration, etc...
* Executing the benchmark across controlled ranges of possible values that may affect the result of the benchmark
(called "components").
* Executing the benchmark multiple times at each point in order to isolate and remove outliers.
* Using the results of the benchmark to create a linear model of the function across its components.
With this linear model, we are able to estimate ahead of time how long it takes to execute some
logic, and thus make informed decisions without actually spending any significant resources at
runtime.
With this linear model, we are able to estimate ahead of time how long it takes to execute some logic, and thus make
informed decisions without actually spending any significant resources at runtime.
Note that we assume that all extrinsics are assumed to be of linear complexity, which is why we are
able to always fit them to a linear model. Quadratic or higher complexity functions are, in general,
considered to be dangerous to the runtime as the weight of these functions may explode as the
runtime state or input becomes too complex.
Note that we assume that all extrinsics are assumed to be of linear complexity, which is why we are able to always fit
them to a linear model. Quadratic or higher complexity functions are, in general, considered to be dangerous to the
runtime as the weight of these functions may explode as the runtime state or input becomes too complex.
The benchmarking framework comes with the following tools:
* [A set of macros](./src/lib.rs) (`benchmarks!`, `add_benchmark!`, etc...) to make it easy to
write, test, and add runtime benchmarks.
* [A set of macros](./src/lib.rs) (`benchmarks!`, `add_benchmark!`, etc...) to make it easy to write, test, and add
runtime benchmarks.
* [A set of linear regression analysis functions](./src/analysis.rs) for processing benchmark data.
* [A CLI extension](../../utils/frame/benchmarking-cli/README.md) to make it easy to execute benchmarks on your
node.
* [A CLI extension](../../utils/frame/benchmarking-cli/README.md) to make it easy to execute benchmarks on your node.
The end-to-end benchmarking pipeline is disabled by default when compiling a node. If you want to
run benchmarks, you need to enable it by compiling with a Rust feature flag `runtime-benchmarks`.
More details about this below.
The end-to-end benchmarking pipeline is disabled by default when compiling a node. If you want to run benchmarks, you
need to enable it by compiling with a Rust feature flag `runtime-benchmarks`. More details about this below.
### Weight
Substrate represents computational resources using a generic unit of measurement called "Weight". It
defines 10^12 Weight as 1 second of computation on the physical machine used for benchmarking. This
means that the weight of a function may change based on the specific hardware used to benchmark the
runtime functions.
Substrate represents computational resources using a generic unit of measurement called "Weight". It defines 10^12
Weight as 1 second of computation on the physical machine used for benchmarking. This means that the weight of a
function may change based on the specific hardware used to benchmark the runtime functions.
By modeling the expected weight of each runtime function, the blockchain is able to calculate how
many transactions or system level functions it will be able to execute within a certain period of
time. Often, the limiting factor for a blockchain is the fixed block production time for the
network.
By modeling the expected weight of each runtime function, the blockchain is able to calculate how many transactions or
system level functions it will be able to execute within a certain period of time. Often, the limiting factor for a
blockchain is the fixed block production time for the network.
Within FRAME, each dispatchable function must have a `#[weight]` annotation with a function that can
return the expected weight for the worst case scenario execution of that function given its inputs.
This benchmarking framework will result in a file that automatically generates those formulas for
you, which you can then use in your pallet.
Within FRAME, each dispatchable function must have a `#[weight]` annotation with a function that can return the expected
weight for the worst case scenario execution of that function given its inputs. This benchmarking framework will result
in a file that automatically generates those formulas for you, which you can then use in your pallet.
## Writing Benchmarks
Writing a runtime benchmark is much like writing a unit test for your pallet. It needs to be
carefully crafted to execute a certain logical path in your code. In tests you want to check for
various success and failure conditions, but with benchmarks you specifically look for the **most
computationally heavy** path, a.k.a the "worst case scenario".
Writing a runtime benchmark is much like writing a unit test for your pallet. It needs to be carefully crafted to
execute a certain logical path in your code. In tests you want to check for various success and failure conditions, but
with benchmarks you specifically look for the **most computationally heavy** path, a.k.a the "worst case scenario".
This means that if there are certain storage items or runtime state that may affect the complexity
of the function, for example triggering more iterations in a `for` loop, to get an accurate result,
you must set up your benchmark to trigger this.
This means that if there are certain storage items or runtime state that may affect the complexity of the function, for
example triggering more iterations in a `for` loop, to get an accurate result, you must set up your benchmark to trigger
this.
It may be that there are multiple paths your function can go down, and it is not clear which one is
the heaviest. In this case, you should just create a benchmark for each scenario! You may find that
there are paths in your code where complexity may become unbounded depending on user input. This may
be a hint that you should enforce sane boundaries for how a user can use your pallet. For example:
limiting the number of elements in a vector, limiting the number of iterations in a `for` loop,
etc...
It may be that there are multiple paths your function can go down, and it is not clear which one is the heaviest. In
this case, you should just create a benchmark for each scenario! You may find that there are paths in your code where
complexity may become unbounded depending on user input. This may be a hint that you should enforce sane boundaries for
how a user can use your pallet. For example: limiting the number of elements in a vector, limiting the number of
iterations in a `for` loop, etc...
Examples of end-to-end benchmarks can be found in the [pallets provided by Substrate](../), and the
specific details on how to use the `benchmarks!` macro can be found in [its
documentation](./src/lib.rs).
Examples of end-to-end benchmarks can be found in the [pallets provided by Substrate](../), and the specific details on
how to use the `benchmarks!` macro can be found in [its documentation](./src/lib.rs).
## Testing Benchmarks
You can test your benchmarks using the same test runtime that you created for your pallet's unit
tests. By creating your benchmarks in the `benchmarks!` macro, it automatically generates test
functions for you:
You can test your benchmarks using the same test runtime that you created for your pallet's unit tests. By creating your
benchmarks in the `benchmarks!` macro, it automatically generates test functions for you:
```rust
fn test_benchmark_[benchmark_name]<T>::() -> Result<(), &'static str>
@@ -101,19 +88,18 @@ fn test_benchmark_[benchmark_name]<T>::() -> Result<(), &'static str>
Simply add these functions to a unit test and ensure that the result of the function is `Ok(())`.
> **Note:** If your test runtime and production runtime have different configurations, you may get
different results when testing your benchmark and actually running it.
> **Note:** If your test runtime and production runtime have different configurations, you may get different results
when testing your benchmark and actually running it.
In general, benchmarks returning `Ok(())` is all you need to check for since it signals the executed
extrinsic has completed successfully. However, you can optionally include a `verify` block with your
benchmark, which can additionally verify any final conditions, such as the final state of your
runtime.
In general, benchmarks returning `Ok(())` is all you need to check for since it signals the executed extrinsic has
completed successfully. However, you can optionally include a `verify` block with your benchmark, which can additionally
verify any final conditions, such as the final state of your runtime.
These additional `verify` blocks will not affect the results of your final benchmarking process.
To run the tests, you need to enable the `runtime-benchmarks` feature flag. This may also mean you
need to move into your node's binary folder. For example, with the Substrate repository, this is how
you would test the Balances pallet's benchmarks:
To run the tests, you need to enable the `runtime-benchmarks` feature flag. This may also mean you need to move into
your node's binary folder. For example, with the Substrate repository, this is how you would test the Balances pallet's
benchmarks:
```bash
cargo test -p pallet-balances --features runtime-benchmarks
@@ -123,19 +109,20 @@ cargo test -p pallet-balances --features runtime-benchmarks
> ```
> error: --features is not allowed in the root of a virtual workspace`
> ```
> To solve this, navigate to the folder of the node (`cd bin/node/cli`) or pallet (`cd frame/pallet`) and run the command there.
> To solve this, navigate to the folder of the node (`cd bin/node/cli`) or pallet (`cd frame/pallet`) and run the
> command there.
This will instance each linear component with different values. The number of values per component is set to six and can be changed with the `VALUES_PER_COMPONENT` environment variable.
This will instance each linear component with different values. The number of values per component is set to six and can
be changed with the `VALUES_PER_COMPONENT` environment variable.
## Adding Benchmarks
The benchmarks included with each pallet are not automatically added to your node. To actually
execute these benchmarks, you need to implement the `frame_benchmarking::Benchmark` trait. You can
see an example of how to do this in the [included Substrate
node](../../bin/node/runtime/src/lib.rs).
The benchmarks included with each pallet are not automatically added to your node. To actually execute these benchmarks,
you need to implement the `frame_benchmarking::Benchmark` trait. You can see an example of how to do this in the
[included Substrate node](../../bin/node/runtime/src/lib.rs).
Assuming there are already some benchmarks set up on your node, you just need to add another
instance of the `add_benchmark!` macro:
Assuming there are already some benchmarks set up on your node, you just need to add another instance of the
`add_benchmark!` macro:
```rust
/// configuration for running benchmarks
@@ -147,22 +134,20 @@ add_benchmark!(params, batches, pallet_balances, Balances);
/// the `struct` created for your pallet by `construct_runtime!`
```
Once you have done this, you will need to compile your node binary with the `runtime-benchmarks`
feature flag:
Once you have done this, you will need to compile your node binary with the `runtime-benchmarks` feature flag:
```bash
cd bin/node/cli
cargo build --profile=production --features runtime-benchmarks
```
The production profile applies various compiler optimizations.
These optimizations slow down the compilation process *a lot*.
The production profile applies various compiler optimizations.
These optimizations slow down the compilation process *a lot*.
If you are just testing things out and don't need final numbers, don't include `--profile=production`.
## Running Benchmarks
Finally, once you have a node binary with benchmarks enabled, you need to execute your various
benchmarks.
Finally, once you have a node binary with benchmarks enabled, you need to execute your various benchmarks.
You can get a list of the available benchmarks by running:
@@ -183,24 +168,24 @@ Then you can run a benchmark like so:
--output <path> \ # Output benchmark results into a folder or file
```
This will output a file `pallet_name.rs` which implements the `WeightInfo` trait you should include
in your pallet. Double colons `::` will be replaced with a `_` in the output name if you specify a directory. Each blockchain should generate their own benchmark file with their custom
implementation of the `WeightInfo` trait. This means that you will be able to use these modular
Substrate pallets while still keeping your network safe for your specific configuration and
This will output a file `pallet_name.rs` which implements the `WeightInfo` trait you should include in your pallet.
Double colons `::` will be replaced with a `_` in the output name if you specify a directory. Each blockchain should
generate their own benchmark file with their custom implementation of the `WeightInfo` trait. This means that you will
be able to use these modular Substrate pallets while still keeping your network safe for your specific configuration and
requirements.
The benchmarking CLI uses a Handlebars template to format the final output file. You can optionally
pass the flag `--template` pointing to a custom template that can be used instead. Within the
template, you have access to all the data provided by the `TemplateData` struct in the
[benchmarking CLI writer](../../utils/frame/benchmarking-cli/src/writer.rs). You can find the
default template used [here](../../utils/frame/benchmarking-cli/src/template.hbs).
The benchmarking CLI uses a Handlebars template to format the final output file. You can optionally pass the flag
`--template` pointing to a custom template that can be used instead. Within the template, you have access to all the
data provided by the `TemplateData` struct in the [benchmarking CLI
writer](../../utils/frame/benchmarking-cli/src/writer.rs). You can find the default template used
[here](../../utils/frame/benchmarking-cli/src/template.hbs).
There are some custom Handlebars helpers included with our output generation:
* `underscore`: Add an underscore to every 3rd character from the right of a string. Primarily to be
used for delimiting large numbers.
* `join`: Join an array of strings into a space-separated string for the template. Primarily to be
used for joining all the arguments passed to the CLI.
* `underscore`: Add an underscore to every 3rd character from the right of a string. Primarily to be used for delimiting
large numbers.
* `join`: Join an array of strings into a space-separated string for the template. Primarily to be used for joining all
the arguments passed to the CLI.
To get a full list of available options when running benchmarks, run:
+1 -1
View File
@@ -8,7 +8,7 @@ With child bounties, a large bounty proposal can be divided into smaller chunks,
for parallel execution, and for efficient governance and tracking of spent funds.
A child bounty is a smaller piece of work, extracted from a parent bounty.
A curator is assigned after the child bounty is created by the parent bounty curator,
to be delegated with the responsibility of assigning a payout address once
to be delegated with the responsibility of assigning a payout address once
the specified set of tasks is completed.
## Interface
+1 -1
View File
@@ -5,7 +5,7 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
The semantic versioning guarantees cover the interface to the substrate runtime which
The semantic versioning guarantees cover the interface to the Substrate runtime which
includes this pallet as a dependency. This module will also add storage migrations whenever
changes require it. Stability with regard to offchain tooling is explicitly excluded from
this guarantee: For example adding a new field to an in-storage data structure will require
+64 -64
View File
@@ -9,66 +9,68 @@ The Contracts module provides functionality for the runtime to deploy and execut
## Overview
This module extends accounts based on the [`frame_support::traits::fungible`] traits to have smart-contract functionality. It can
be used with other modules that implement accounts based on [`frame_support::traits::fungible`]. These "smart-contract accounts"
have the ability to instantiate smart-contracts and make calls to other contract and non-contract accounts.
This module extends accounts based on the [`frame_support::traits::fungible`] traits to have smart-contract
functionality. It can be used with other modules that implement accounts based on [`frame_support::traits::fungible`].
These "smart-contract accounts" have the ability to instantiate smart-contracts and make calls to other contract and
non-contract accounts.
The smart-contract code is stored once, and later retrievable via its `code_hash`.
This means that multiple smart-contracts can be instantiated from the same `code`, without replicating
the code each time.
The smart-contract code is stored once, and later retrievable via its `code_hash`. This means that multiple
smart-contracts can be instantiated from the same `code`, without replicating the code each time.
When a smart-contract is called, its associated code is retrieved via the code hash and gets executed.
This call can alter the storage entries of the smart-contract account, instantiate new smart-contracts,
or call other smart-contracts.
When a smart-contract is called, its associated code is retrieved via the code hash and gets executed. This call can
alter the storage entries of the smart-contract account, instantiate new smart-contracts, or call other smart-contracts.
Finally, when an account is reaped, its associated code and storage of the smart-contract account
will also be deleted.
Finally, when an account is reaped, its associated code and storage of the smart-contract account will also be deleted.
### Weight
Senders must specify a [`Weight`](https://paritytech.github.io/substrate/master/sp_weights/struct.Weight.html) limit with every call, as all instructions invoked by the smart-contract require weight.
Unused weight is refunded after the call, regardless of the execution outcome.
Senders must specify a [`Weight`](https://paritytech.github.io/substrate/master/sp_weights/struct.Weight.html) limit
with every call, as all instructions invoked by the smart-contract require weight. Unused weight is refunded after the
call, regardless of the execution outcome.
If the weight limit is reached, then all calls and state changes (including balance transfers) are only
reverted at the current call's contract level. For example, if contract A calls B and B runs out of weight mid-call,
then all of B's calls are reverted. Assuming correct error handling by contract A, A's other calls and state
changes still persist.
If the weight limit is reached, then all calls and state changes (including balance transfers) are only reverted at the
current call's contract level. For example, if contract A calls B and B runs out of weight mid-call, then all of B's
calls are reverted. Assuming correct error handling by contract A, A's other calls and state changes still persist.
One `ref_time` `Weight` is defined as one picosecond of execution time on the runtime's reference machine.
### Revert Behaviour
Contract call failures are not cascading. When failures occur in a sub-call, they do not "bubble up",
and the call will only revert at the specific contract level. For example, if contract A calls contract B, and B
fails, A can decide how to handle that failure, either proceeding or reverting A's changes.
Contract call failures are not cascading. When failures occur in a sub-call, they do not "bubble up", and the call will
only revert at the specific contract level. For example, if contract A calls contract B, and B fails, A can decide how
to handle that failure, either proceeding or reverting A's changes.
### Off-chain Execution
In general, a contract execution needs to be deterministic so that all nodes come to the same
conclusion when executing it. To that end we disallow any instructions that could cause
indeterminism. Most notable are any floating point arithmetic. That said, sometimes contracts
are executed off-chain and hence are not subject to consensus. If code is only executed by a
single node and implicitly trusted by other actors is such a case. Trusted execution environments
come to mind. To that end we allow the execution of indeterminstic code for off-chain usages
with the following constraints:
In general, a contract execution needs to be deterministic so that all nodes come to the same conclusion when executing
it. To that end we disallow any instructions that could cause indeterminism. Most notable are any floating point
arithmetic. That said, sometimes contracts are executed off-chain and hence are not subject to consensus. If code is
only executed by a single node and implicitly trusted by other actors is such a case. Trusted execution environments
come to mind. To that end we allow the execution of indeterminstic code for off-chain usages with the following
constraints:
1. No contract can ever be instantiated from an indeterministic code. The only way to execute
the code is to use a delegate call from a deterministic contract.
2. The code that wants to use this feature needs to depend on `pallet-contracts` and use [`bare_call()`](https://paritytech.github.io/substrate/master/pallet_contracts/pallet/struct.Pallet.html#method.bare_call)
1. No contract can ever be instantiated from an indeterministic code. The only way to execute the code is to use a
delegate call from a deterministic contract.
2. The code that wants to use this feature needs to depend on `pallet-contracts` and use
[`bare_call()`](https://paritytech.github.io/substrate/master/pallet_contracts/pallet/struct.Pallet.html#method.bare_call)
directly. This makes sure that by default `pallet-contracts` does not expose any indeterminism.
#### How to use
An indeterministic code can be deployed on-chain by passing `Determinism::Relaxed`
to [`upload_code()`](https://paritytech.github.io/substrate/master/pallet_contracts/pallet/struct.Pallet.html#method.upload_code). A deterministic contract can then delegate call into it if and only if it
is ran by using [`bare_call()`](https://paritytech.github.io/substrate/master/pallet_contracts/pallet/struct.Pallet.html#method.bare_call) and passing [`Determinism::Relaxed`](https://paritytech.github.io/substrate/master/pallet_contracts/enum.Determinism.html#variant.Relaxed) to it. **Never use
this argument when the contract is called from an on-chain transaction.**
An indeterministic code can be deployed on-chain by passing `Determinism::Relaxed` to
[`upload_code()`](https://paritytech.github.io/substrate/master/pallet_contracts/pallet/struct.Pallet.html#method.upload_code).
A deterministic contract can then delegate call into it if and only if it is ran by using
[`bare_call()`](https://paritytech.github.io/substrate/master/pallet_contracts/pallet/struct.Pallet.html#method.bare_call)
and passing
[`Determinism::Relaxed`](https://paritytech.github.io/substrate/master/pallet_contracts/enum.Determinism.html#variant.Relaxed)
to it. **Never use this argument when the contract is called from an on-chain transaction.**
## Interface
### Dispatchable functions
Those are documented in the [reference documentation](https://paritytech.github.io/substrate/master/pallet_contracts/index.html#dispatchable-functions).
Those are documented in the [reference
documentation](https://paritytech.github.io/substrate/master/pallet_contracts/index.html#dispatchable-functions).
### Interface exposed to contracts
@@ -99,43 +101,43 @@ The documentation of all importable functions can be found
## Usage
This module executes WebAssembly smart contracts. These can potentially be written in any language
that compiles to Wasm. However, using a language that specifically targets this module
will make things a lot easier. One such language is [`ink!`](https://use.ink). It enables
writing WebAssembly-based smart-contracts in the Rust programming language.
This module executes WebAssembly smart contracts. These can potentially be written in any language that compiles to
Wasm. However, using a language that specifically targets this module will make things a lot easier. One such language
is [`ink!`](https://use.ink). It enables writing WebAssembly-based smart-contracts in the Rust programming language.
## Debugging
Contracts can emit messages to the client when called as RPC through the [`debug_message`](https://paritytech.github.io/substrate/master/pallet_contracts/api_doc/trait.Current.html#tymethod.debug_message)
Contracts can emit messages to the client when called as RPC through the
[`debug_message`](https://paritytech.github.io/substrate/master/pallet_contracts/api_doc/trait.Current.html#tymethod.debug_message)
API. This is exposed in [ink!](https://use.ink) via
[`ink_env::debug_message()`](https://paritytech.github.io/ink/ink_env/fn.debug_message.html).
Those messages are gathered into an internal buffer and sent to the RPC client.
It is up the the individual client if and how those messages are presented to the user.
Those messages are gathered into an internal buffer and sent to the RPC client. It is up the the individual client if
and how those messages are presented to the user.
This buffer is also printed as a debug message. In order to see these messages on the node
console the log level for the `runtime::contracts` target needs to be raised to at least
the `debug` level. However, those messages are easy to overlook because of the noise generated
by block production. A good starting point for observing them on the console is using this
command line in the root directory of the substrate repository:
This buffer is also printed as a debug message. In order to see these messages on the node console the log level for the
`runtime::contracts` target needs to be raised to at least the `debug` level. However, those messages are easy to
overlook because of the noise generated by block production. A good starting point for observing them on the console is
using this command line in the root directory of the Substrate repository:
```bash
cargo run --release -- --dev -lerror,runtime::contracts=debug
```
This raises the log level of `runtime::contracts` to `debug` and all other targets
to `error` in order to prevent them from spamming the console.
This raises the log level of `runtime::contracts` to `debug` and all other targets to `error` in order to prevent them
from spamming the console.
`--dev`: Use a dev chain spec
`--tmp`: Use temporary storage for chain data (the chain state is deleted on exit)
`--dev`: Use a dev chain spec `--tmp`: Use temporary storage for chain data (the chain state is deleted on exit)
## Host function tracing
For contract authors, it can be a helpful debugging tool to see which host functions are called, with which arguments, and what the result was.
For contract authors, it can be a helpful debugging tool to see which host functions are called, with which arguments,
and what the result was.
In order to see these messages on the node console, the log level for the `runtime::contracts::strace` target needs to be raised to the `trace` level.
In order to see these messages on the node console, the log level for the `runtime::contracts::strace` target needs to
be raised to the `trace` level.
Example:
Example:
```bash
cargo run --release -- --dev -lerror,runtime::contracts::strace=trace,runtime::contracts=debug
@@ -143,18 +145,16 @@ cargo run --release -- --dev -lerror,runtime::contracts::strace=trace,runtime::c
## Unstable Interfaces
Driven by the desire to have an iterative approach in developing new contract interfaces
this pallet contains the concept of an unstable interface. Akin to the rust nightly compiler
it allows us to add new interfaces but mark them as unstable so that contract languages can
experiment with them and give feedback before we stabilize those.
Driven by the desire to have an iterative approach in developing new contract interfaces this pallet contains the
concept of an unstable interface. Akin to the rust nightly compiler it allows us to add new interfaces but mark them as
unstable so that contract languages can experiment with them and give feedback before we stabilize those.
In order to access interfaces marked as `#[unstable]` in [`runtime.rs`](src/wasm/runtime.rs) one need to set
`pallet_contracts::Config::UnsafeUnstableInterface` to `ConstU32<true>`. **It should be obvious
that any production runtime should never be compiled with this feature: In addition to be
subject to change or removal those interfaces might not have proper weights associated with
them and are therefore considered unsafe**.
`pallet_contracts::Config::UnsafeUnstableInterface` to `ConstU32<true>`. **It should be obvious that any production
runtime should never be compiled with this feature: In addition to be subject to change or removal those interfaces
might not have proper weights associated with them and are therefore considered unsafe**.
New interfaces are generally added as unstable and might go through several iterations
before they are promoted to a stable interface.
New interfaces are generally added as unstable and might go through several iterations before they are promoted to a
stable interface.
License: Apache-2.0
@@ -1,9 +1,8 @@
# Benchmarks
This directory contains real world ([ink!](https://use.ink), [solang](https://github.com/hyperledger/solang)) contracts which are used in macro benchmarks.
Those benchmarks are not used to determine weights but rather to compare different contract
languages and execution engines with larger wasm modules.
Files in this directory are used by `#[extra]` benchmarks in `src/benchmarking`. The json
files are for informational purposes only and are not consumed by the benchmarks.
This directory contains real world ([ink!](https://use.ink), [solang](https://github.com/hyperledger/solang)) contracts
which are used in macro benchmarks. Those benchmarks are not used to determine weights but rather to compare different
contract languages and execution engines with larger wasm modules.
Files in this directory are used by `#[extra]` benchmarks in `src/benchmarking`. The json files are for informational
purposes only and are not consumed by the benchmarks.
@@ -1,3 +1,3 @@
A crate that hosts a common definitions that are relevant for the pallet-contracts.
License: Apache-2.0
License: Apache-2.0
+1 -1
View File
@@ -1,3 +1,3 @@
# Core Fellowship
Logic specific to the core Polkadot Fellowship.
Logic specific to the core Polkadot Fellowship.
+41 -47
View File
@@ -1,64 +1,58 @@
# Phragmén Election Module.
# Phragmén Election Module
An election module based on sequential phragmen.
### Term and Round
## Term and Round
The election happens in _rounds_: every `N` blocks, all previous members are retired and a new
set is elected (which may or may not have an intersection with the previous set). Each round
lasts for some number of blocks defined by `TermDuration` storage item. The words _term_ and
_round_ can be used interchangeably in this context.
The election happens in _rounds_: every `N` blocks, all previous members are retired and a new set is elected (which may
or may not have an intersection with the previous set). Each round lasts for some number of blocks defined by
`TermDuration` storage item. The words _term_ and _round_ can be used interchangeably in this context.
`TermDuration` might change during a round. This can shorten or extend the length of the round.
The next election round's block number is never stored but rather always checked on the fly.
Based on the current block number and `TermDuration`, the condition `BlockNumber % TermDuration
== 0` being satisfied will always trigger a new election round.
`TermDuration` might change during a round. This can shorten or extend the length of the round. The next election
round's block number is never stored but rather always checked on the fly. Based on the current block number and
`TermDuration`, the condition `BlockNumber % TermDuration == 0` being satisfied will always trigger a new election
round.
### Voting
## Voting
Voters can vote for any set of the candidates by providing a list of account ids. Invalid votes
(voting for non-candidates) are ignored during election. Yet, a voter _might_ vote for a future
candidate. Voters reserve a bond as they vote. Each vote defines a `value`. This amount is
locked from the account of the voter and indicates the weight of the vote. Voters can update
their votes at any time by calling `vote()` again. This keeps the bond untouched but can
optionally change the locked `value`. After a round, votes are kept and might still be valid for
further rounds. A voter is responsible for calling `remove_voter` once they are done to have
their bond back and remove the lock.
Voters can vote for any set of the candidates by providing a list of account ids. Invalid votes (voting for
non-candidates) are ignored during election. Yet, a voter _might_ vote for a future candidate. Voters reserve a bond as
they vote. Each vote defines a `value`. This amount is locked from the account of the voter and indicates the weight of
the vote. Voters can update their votes at any time by calling `vote()` again. This keeps the bond untouched but can
optionally change the locked `value`. After a round, votes are kept and might still be valid for further rounds. A voter
is responsible for calling `remove_voter` once they are done to have their bond back and remove the lock.
Voters also report other voters as being defunct to earn their bond. A voter is defunct once all
of the candidates that they have voted for are neither a valid candidate anymore nor a member.
Upon reporting, if the target voter is actually defunct, the reporter will be rewarded by the
voting bond of the target. The target will lose their bond and get removed. If the target is not
defunct, the reporter is slashed and removed. To prevent being reported, voters should manually
submit a `remove_voter()` as soon as they are in the defunct state.
Voters also report other voters as being defunct to earn their bond. A voter is defunct once all of the candidates that
they have voted for are neither a valid candidate anymore nor a member. Upon reporting, if the target voter is actually
defunct, the reporter will be rewarded by the voting bond of the target. The target will lose their bond and get
removed. If the target is not defunct, the reporter is slashed and removed. To prevent being reported, voters should
manually submit a `remove_voter()` as soon as they are in the defunct state.
### Candidacy and Members
## Candidacy and Members
Candidates also reserve a bond as they submit candidacy. A candidate cannot take their candidacy
back. A candidate can end up in one of the below situations:
- **Winner**: A winner is kept as a _member_. They must still have a bond in reserve and they
are automatically counted as a candidate for the next election.
- **Runner-up**: Runners-up are the best candidates immediately after the winners. The number
of runners_up to keep is configurable. Runners-up are used, in order that they are elected,
as replacements when a candidate is kicked by `[remove_member]`, or when an active member
renounces their candidacy. Runners are automatically counted as a candidate for the next
election.
- **Loser**: Any of the candidate who are not a winner are left as losers. A loser might be an
_outgoing member or runner_, meaning that they are an active member who failed to keep their
spot. An outgoing will always lose their bond.
Candidates also reserve a bond as they submit candidacy. A candidate cannot take their candidacy back. A candidate can
end up in one of the below situations:
- **Winner**: A winner is kept as a _member_. They must still have a bond in reserve and they are automatically
counted as a candidate for the next election.
- **Runner-up**: Runners-up are the best candidates immediately after the winners. The number of runners_up to keep is
configurable. Runners-up are used, in order that they are elected, as replacements when a candidate is kicked by
`[remove_member]`, or when an active member renounces their candidacy. Runners are automatically counted as a
candidate for the next election.
- **Loser**: Any of the candidate who are not a winner are left as losers. A loser might be an _outgoing member or
runner_, meaning that they are an active member who failed to keep their spot. An outgoing will always lose their
bond.
##### Renouncing candidacy.
### Renouncing candidacy
All candidates, elected or not, can renounce their candidacy. A call to [`Module::renounce_candidacy`]
will always cause the candidacy bond to be refunded.
All candidates, elected or not, can renounce their candidacy. A call to [`Module::renounce_candidacy`] will always cause
the candidacy bond to be refunded.
Note that with the members being the default candidates for the next round and votes persisting
in storage, the election system is entirely stable given no further input. This means that if
the system has a particular set of candidates `C` and voters `V` that lead to a set of members
`M` being elected, as long as `V` and `C` don't remove their candidacy and votes, `M` will keep
being re-elected at the end of each round.
Note that with the members being the default candidates for the next round and votes persisting in storage, the election
system is entirely stable given no further input. This means that if the system has a particular set of candidates `C`
and voters `V` that lead to a set of members `M` being elected, as long as `V` and `C` don't remove their candidacy and
votes, `M` will keep being re-elected at the end of each round.
### Module Information
## Module Information
- [`election_sp_phragmen::Config`](https://docs.rs/pallet-elections-phragmen/latest/pallet_elections_phragmen/trait.Config.html)
- [`Call`](https://docs.rs/pallet-elections-phragmen/latest/pallet_elections_phragmen/enum.Call.html)
+1 -1
View File
@@ -9,7 +9,7 @@ Run `cargo doc --package pallet-example-basic --open` to view this pallet's docu
**This pallet serves as an example and is not meant to be used in production.**
### Documentation Guidelines:
## Documentation Guidelines
<!-- Original author of paragraph: Various. Based on collation of review comments to PRs addressing issues with -->
<!-- label 'S3-FRAME' in https://github.com/paritytech/substrate-developer-hub/issues -->
+1 -1
View File
@@ -3,7 +3,7 @@
A simple example of a FRAME pallet demonstrating the ability to split sections across multiple
files.
Note that this is purely experimental at this point.
Note that this is purely experimental at this point.
Run `cargo doc --package pallet-example-split --open` to view this pallet's documentation.
+9 -9
View File
@@ -1,13 +1,13 @@
# Executive Module
The Executive module acts as the orchestration layer for the runtime. It dispatches incoming
extrinsic calls to the respective modules in the runtime.
The Executive module acts as the orchestration layer for the runtime. It dispatches incoming extrinsic calls to the
respective modules in the runtime.
## Overview
The executive module is not a typical pallet providing functionality around a specific feature.
It is a cross-cutting framework component for the FRAME. It works in conjunction with the
[FRAME System module](https://docs.rs/frame-system/latest/frame_system/) to perform these cross-cutting functions.
The executive module is not a typical pallet providing functionality around a specific feature. It is a cross-cutting
framework component for the FRAME. It works in conjunction with the [FRAME System
module](https://docs.rs/frame-system/latest/frame_system/) to perform these cross-cutting functions.
The Executive module provides functions to:
@@ -26,7 +26,8 @@ The Executive module provides the following implementations:
## Usage
The default Substrate node template declares the [`Executive`](https://docs.rs/frame-executive/latest/frame_executive/struct.Executive.html) type in its library.
The default Substrate node template declares the
[`Executive`](https://docs.rs/frame-executive/latest/frame_executive/struct.Executive.html) type in its library.
### Example
@@ -46,9 +47,8 @@ pub type Executive = executive::Executive<
### Custom `OnRuntimeUpgrade` logic
You can add custom logic that should be called in your runtime on a runtime upgrade. This is
done by setting an optional generic parameter. The custom logic will be called before
the on runtime upgrade logic of all modules is called.
You can add custom logic that should be called in your runtime on a runtime upgrade. This is done by setting an optional
generic parameter. The custom logic will be called before the on runtime upgrade logic of all modules is called.
```rust
#
+5 -2
View File
@@ -4,6 +4,9 @@
# Glutton Pallet
The `Glutton` pallet gets the name from its property to consume vast amounts of resources. It can be used to push para-chains and their relay-chains to the limits. This is good for testing out theoretical limits in a practical way.
The `Glutton` pallet gets the name from its property to consume vast amounts of resources. It can be used to push
para-chains and their relay-chains to the limits. This is good for testing out theoretical limits in a practical way.
The `Glutton` can be set to consume a fraction of the available unused weight of a chain. It accomplishes this by utilizing the `on_idle` hook and consuming a specific ration of the remaining weight. The rations can be set via `set_compute` and `set_storage`. Initially the `Glutton` needs to be initialized once with `initialize_pallet`.
The `Glutton` can be set to consume a fraction of the available unused weight of a chain. It accomplishes this by
utilizing the `on_idle` hook and consuming a specific ration of the remaining weight. The rations can be set via
`set_compute` and `set_storage`. Initially the `Glutton` needs to be initialized once with `initialize_pallet`.
+1 -1
View File
@@ -9,4 +9,4 @@ finality notifications.
For full integration with GRANDPA, the `GrandpaApi` should be implemented.
The necessary items are re-exported via the `fg_primitives` crate.
License: Apache-2.0
License: Apache-2.0
+14 -14
View File
@@ -28,27 +28,27 @@ no state-bloat attack is viable.
### Dispatchable Functions
#### For general users
* `set_identity` - Set the associated identity of an account; a small deposit is reserved if not
- `set_identity` - Set the associated identity of an account; a small deposit is reserved if not
already taken.
* `clear_identity` - Remove an account's associated identity; the deposit is returned.
* `request_judgement` - Request a judgement from a registrar, paying a fee.
* `cancel_request` - Cancel the previous request for a judgement.
- `clear_identity` - Remove an account's associated identity; the deposit is returned.
- `request_judgement` - Request a judgement from a registrar, paying a fee.
- `cancel_request` - Cancel the previous request for a judgement.
#### For general users with sub-identities
* `set_subs` - Set the sub-accounts of an identity.
* `add_sub` - Add a sub-identity to an identity.
* `remove_sub` - Remove a sub-identity of an identity.
* `rename_sub` - Rename a sub-identity of an identity.
* `quit_sub` - Remove a sub-identity of an identity (called by the sub-identity).
- `set_subs` - Set the sub-accounts of an identity.
- `add_sub` - Add a sub-identity to an identity.
- `remove_sub` - Remove a sub-identity of an identity.
- `rename_sub` - Rename a sub-identity of an identity.
- `quit_sub` - Remove a sub-identity of an identity (called by the sub-identity).
#### For registrars
* `set_fee` - Set the fee required to be paid for a judgement to be given by the registrar.
* `set_fields` - Set the fields that a registrar cares about in their judgements.
* `provide_judgement` - Provide a judgement to an identity.
- `set_fee` - Set the fee required to be paid for a judgement to be given by the registrar.
- `set_fields` - Set the fields that a registrar cares about in their judgements.
- `provide_judgement` - Provide a judgement to an identity.
#### For super-users
* `add_registrar` - Add a new registrar to the system.
* `kill_identity` - Forcibly remove the associated identity; the deposit is lost.
- `add_registrar` - Add a new registrar to the system.
- `kill_identity` - Forcibly remove the associated identity; the deposit is lost.
[`Call`]: ./enum.Call.html
[`Config`]: ./trait.Config.html
+1 -1
View File
@@ -1,4 +1,4 @@
An index is a short form of an address. This module handles allocation
of indices for a newly created accounts.
License: Apache-2.0
License: Apache-2.0
@@ -1,25 +1,27 @@
# DO NOT USE IN PRODUCTION
The produced values do not fulfill the cryptographic requirements for random numbers. Should not be used for high-stake production use-cases.
The produced values do not fulfill the cryptographic requirements for random numbers. Should not be used for high-stake
production use-cases.
# Randomness Module
The Randomness Collective Flip module provides a [`random`](https://docs.rs/pallet-insecure-randomness-collective-flip/latest/pallet_insecure_randomness_collective_flip/struct.Module.html#method.random)
function that generates low-influence random values based on the block hashes from the previous
`81` blocks. Low-influence randomness can be useful when defending against relatively weak
adversaries. Using this pallet as a randomness source is advisable primarily in low-security
situations like testing.
The Randomness Collective Flip module provides a
[`random`](https://docs.rs/pallet-insecure-randomness-collective-flip/latest/pallet_insecure_randomness_collective_flip/struct.Module.html#method.random)
function that generates low-influence random values based on the block hashes from the previous `81` blocks.
Low-influence randomness can be useful when defending against relatively weak adversaries. Using this pallet as a
randomness source is advisable primarily in low-security situations like testing.
## Public Functions
See the [`Module`](https://docs.rs/pallet-insecure-randomness-collective-flip/latest/pallet_insecure_randomness_collective_flip/struct.Module.html) struct for details of publicly available functions.
See the
[`Module`](https://docs.rs/pallet-insecure-randomness-collective-flip/latest/pallet_insecure_randomness_collective_flip/struct.Module.html)
struct for details of publicly available functions.
## Usage
### Prerequisites
Import the Randomness Collective Flip module and derive your module's configuration trait from
the system trait.
Import the Randomness Collective Flip module and derive your module's configuration trait from the system trait.
### Example - Get random seed for the current block
+3 -3
View File
@@ -18,10 +18,10 @@ not available or desired.
### Dispatchable Functions
* `as_multi` - Approve and if possible dispatch a call from a composite origin formed from a
- `as_multi` - Approve and if possible dispatch a call from a composite origin formed from a
number of signed origins.
* `approve_as_multi` - Approve a call from a composite origin.
* `cancel_as_multi` - Cancel a call from a composite origin.
- `approve_as_multi` - Approve a call from a composite origin.
- `cancel_as_multi` - Cancel a call from a composite origin.
[`Call`]: ./enum.Call.html
[`Config`]: ./trait.Config.html
@@ -1,6 +1,8 @@
### Lock NFT
# Lock NFT
Lock an NFT from `pallet-nfts` and mint fungible assets from `pallet-assets`.
The NFT gets locked by putting a system-level attribute named `Locked`. This prevents the NFT from being transferred further.
The NFT becomes unlocked when the `Locked` attribute is removed. In order to unify the fungible asset and unlock the NFT, an account must hold the full issuance of the asset the NFT was fractionalised into. Holding less of the fungible asset will not allow the unlocking of the NFT.
The NFT gets locked by putting a system-level attribute named `Locked`. This prevents the NFT from being transferred
further. The NFT becomes unlocked when the `Locked` attribute is removed. In order to unify the fungible asset and
unlock the NFT, an account must hold the full issuance of the asset the NFT was fractionalised into. Holding less of the
fungible asset will not allow the unlocking of the NFT.
+13 -11
View File
@@ -13,9 +13,11 @@ The NFTs pallet provides functionality for non-fungible tokens' management, incl
* Attributes Management
* NFT Burning
To use it in your runtime, you need to implement [`nfts::Config`](https://paritytech.github.io/substrate/master/pallet_nfts/pallet/trait.Config.html).
To use it in your runtime, you need to implement
[`nfts::Config`](https://paritytech.github.io/substrate/master/pallet_nfts/pallet/trait.Config.html).
The supported dispatchable functions are documented in the [`nfts::Call`](https://paritytech.github.io/substrate/master/pallet_nfts/pallet/enum.Call.html) enum.
The supported dispatchable functions are documented in the
[`nfts::Call`](https://paritytech.github.io/substrate/master/pallet_nfts/pallet/enum.Call.html) enum.
### Terminology
@@ -24,8 +26,9 @@ The supported dispatchable functions are documented in the [`nfts::Call`](https:
* **NFT transfer:** The action of sending an item from one account to another.
* **Atomic swap:** The action of exchanging items between accounts without needing a 3rd party service.
* **NFT burning:** The destruction of an item.
* **Non-fungible token (NFT):** An item for which each unit has unique characteristics. There is exactly
one instance of such an item in existence and there is exactly one owning account (though that owning account could be a proxy account or multi-sig account).
* **Non-fungible token (NFT):** An item for which each unit has unique characteristics. There is exactly one instance of
such an item in existence and there is exactly one owning account (though that owning account could be a proxy account
or multi-sig account).
* **Soul Bound NFT:** An item that is non-transferable from the account which it is minted into.
### Goals
@@ -35,10 +38,8 @@ The NFTs pallet in Substrate is designed to make the following possible:
* Allow accounts to permissionlessly create nft collections.
* Allow a named (permissioned) account to mint and burn unique items within a collection.
* Move items between accounts permissionlessly.
* Allow a named (permissioned) account to freeze and unfreeze items within a
collection or the entire collection.
* Allow the owner of an item to delegate the ability to transfer the item to some
named third-party.
* Allow a named (permissioned) account to freeze and unfreeze items within a collection or the entire collection.
* Allow the owner of an item to delegate the ability to transfer the item to some named third-party.
* Allow third-parties to store information in an NFT _without_ owning it (Eg. save game state).
## Interface
@@ -71,7 +72,8 @@ The NFTs pallet in Substrate is designed to make the following possible:
* `clear_all_transfer_approvals`: Clears all transfer approvals set by calling the `approve_transfer`.
* `lock_collection`: Prevent all items within a collection from being transferred (making them all `soul bound`).
* `lock_item_properties`: Lock item's metadata or attributes.
* `transfer_ownership`: Alter the owner of a collection, moving all associated deposits. (Ownership of individual items will not be affected.)
* `transfer_ownership`: Alter the owner of a collection, moving all associated deposits. (Ownership of individual items
will not be affected.)
* `set_team`: Alter the permissioned accounts of a collection.
* `set_collection_max_supply`: Change the max supply of a collection.
* `update_mint_settings`: Update the minting settings for collection.
@@ -94,8 +96,8 @@ The NFTs pallet in Substrate is designed to make the following possible:
* `force_collection_config`: Change collection's config.
* `force_set_attribute`: Set an attribute.
Please refer to the [`Call`](https://paritytech.github.io/substrate/master/pallet_nfts/pallet/enum.Call.html) enum
and its associated variants for documentation on each function.
Please refer to the [`Call`](https://paritytech.github.io/substrate/master/pallet_nfts/pallet/enum.Call.html) enum and
its associated variants for documentation on each function.
## Related Modules
+3 -3
View File
@@ -14,10 +14,10 @@ have not been designed to be economically secure. Do not use this pallet as-is i
### Dispatchable Functions
* `set_name` - Set the associated name of an account; a small deposit is reserved if not already
- `set_name` - Set the associated name of an account; a small deposit is reserved if not already
taken.
* `clear_name` - Remove an account's associated name; the deposit is returned.
* `kill_name` - Forcibly remove the associated name; the deposit is lost.
- `clear_name` - Remove an account's associated name; the deposit is returned.
- `kill_name` - Forcibly remove the associated name; the deposit is lost.
[`Call`]: ./enum.Call.html
[`Config`]: ./trait.Config.html
+1 -1
View File
@@ -2,4 +2,4 @@
Provides a non-interactiove variant of staking.
License: Apache-2.0
License: Apache-2.0
@@ -1,3 +1,3 @@
Runtime API definition for nomination-pools pallet.
License: Apache-2.0
License: Apache-2.0
+1 -1
View File
@@ -2,4 +2,4 @@
Tracks reported offences
License: Apache-2.0
License: Apache-2.0
@@ -1,3 +1,3 @@
Offences pallet benchmarking.
License: Apache-2.0
License: Apache-2.0
+1 -1
View File
@@ -1,4 +1,4 @@
# Ranked collective system.
# Ranked collective system
This is a membership pallet providing a `Tally` implementation ready for use with polling
systems such as the Referenda pallet. Members each have a rank, with zero being the lowest.
+14 -14
View File
@@ -16,11 +16,11 @@ friends are needed to give another account access to the recoverable account.
The recovery process for each recoverable account can be configured by the account owner.
They are able to choose:
* `friends` - The list of friends that the account owner trusts to protect the
- `friends` - The list of friends that the account owner trusts to protect the
recovery process for their account.
* `threshold` - The number of friends that need to approve a recovery process for
- `threshold` - The number of friends that need to approve a recovery process for
the account to be successfully recovered.
* `delay_period` - The minimum number of blocks after the beginning of the recovery
- `delay_period` - The minimum number of blocks after the beginning of the recovery
process that need to pass before the account can be successfully recovered.
There is a configurable deposit that all users need to pay to create a recovery
@@ -84,20 +84,20 @@ It is important to note that this is a powerful pallet that can compromise the
security of an account if used incorrectly. Some recommended practices for users
of this pallet are:
* Configure a significant `delay_period` for your recovery process: As long as you
- Configure a significant `delay_period` for your recovery process: As long as you
have access to your recoverable account, you need only check the blockchain once
every `delay_period` blocks to ensure that no recovery attempt is successful
against your account. Using off-chain notification systems can help with this,
but ultimately, setting a large `delay_period` means that even the most skilled
attacker will need to wait this long before they can access your account.
* Use a high threshold of approvals: Setting a value of 1 for the threshold means
- Use a high threshold of approvals: Setting a value of 1 for the threshold means
that any of your friends would be able to recover your account. They would
simply need to start a recovery process and approve their own process. Similarly,
a threshold of 2 would mean that any 2 friends could work together to gain
access to your account. The only way to prevent against these kinds of attacks
is to choose a high threshold of approvals and select from a diverse friend
group that would not be able to reasonably coordinate with one another.
* Reset your configuration over time: Since the entire deposit of creating a
- Reset your configuration over time: Since the entire deposit of creating a
recovery configuration is returned to the user, the only cost of updating
your recovery configuration is the transaction fees for the calls. Thus,
it is strongly encouraged to regularly update your recovery configuration
@@ -110,25 +110,25 @@ of this pallet are:
#### For General Users
* `create_recovery` - Create a recovery configuration for your account and make it recoverable.
* `initiate_recovery` - Start the recovery process for a recoverable account.
- `create_recovery` - Create a recovery configuration for your account and make it recoverable.
- `initiate_recovery` - Start the recovery process for a recoverable account.
#### For Friends of a Recoverable Account
* `vouch_recovery` - As a `friend` of a recoverable account, vouch for a recovery attempt on the account.
- `vouch_recovery` - As a `friend` of a recoverable account, vouch for a recovery attempt on the account.
#### For a User Who Successfully Recovered an Account
* `claim_recovery` - Claim access to the account that you have successfully completed the recovery process for.
* `as_recovered` - Send a transaction as an account that you have recovered. See other functions below.
- `claim_recovery` - Claim access to the account that you have successfully completed the recovery process for.
- `as_recovered` - Send a transaction as an account that you have recovered. See other functions below.
#### For the Recoverable Account
* `close_recovery` - Close an active recovery process for your account and reclaim the recovery deposit.
* `remove_recovery` - Remove the recovery configuration from the account, making it un-recoverable.
- `close_recovery` - Close an active recovery process for your account and reclaim the recovery deposit.
- `remove_recovery` - Remove the recovery configuration from the account, making it un-recoverable.
#### For Super Users
* `set_recovered` - The ROOT origin is able to skip the recovery process and directly allow
- `set_recovered` - The ROOT origin is able to skip the recovery process and directly allow
one account to access another.
License: Apache-2.0
+1 -1
View File
@@ -1,6 +1,6 @@
# Remark Storage Pallet
Allows storing arbitrary data off chain.
Allows storing arbitrary data off chain.
License: Apache-2.0
+1 -1
View File
@@ -2,4 +2,4 @@
Pallet that allows the root to create an offence.
NOTE: This pallet should only be used for testing purposes.
NOTE: This pallet should only be used for testing purposes.
+1 -1
View File
@@ -2,4 +2,4 @@
Pallet that contains extrinsics that can be usefull in testing.
NOTE: This pallet should only be used for testing purposes and should not be used in production runtimes!
NOTE: This pallet should only be used for testing purposes and should not be used in production runtimes!
+1 -1
View File
@@ -1,3 +1,3 @@
# Salary
Make periodic payment to members of a ranked collective according to rank.
Make periodic payment to members of a ranked collective according to rank.
+4 -4
View File
@@ -23,12 +23,12 @@ then those filter will not be used when dispatching the schedule call.
### Dispatchable Functions
* `schedule` - schedule a dispatch, which may be periodic, to occur at a
- `schedule` - schedule a dispatch, which may be periodic, to occur at a
specified block and with a specified priority.
* `cancel` - cancel a scheduled dispatch, specified by block number and
- `cancel` - cancel a scheduled dispatch, specified by block number and
index.
* `schedule_named` - augments the `schedule` interface with an additional
- `schedule_named` - augments the `schedule` interface with an additional
`Vec<u8>` parameter that can be used for identification.
* `cancel_named` - the named complement to the cancel function.
- `cancel_named` - the named complement to the cancel function.
License: Apache 2.0
+31 -33
View File
@@ -1,7 +1,7 @@
# Session Pallet
The Session module allows validators to manage their session keys, provides a function for changing
the session length, and handles session rotation.
The Session module allows validators to manage their session keys, provides a function for changing the session length,
and handles session rotation.
- [`session::Trait`](https://docs.rs/pallet-session/latest/pallet_session/trait.Config.html)
- [`Call`](https://docs.rs/pallet-session/latest/pallet_session/enum.Call.html)
@@ -12,34 +12,31 @@ the session length, and handles session rotation.
### Terminology
<!-- Original author of paragraph: @gavofyork -->
- **Session:** A session is a period of time that has a constant set of validators. Validators can only join
or exit the validator set at a session change. It is measured in block numbers. The block where a session is
ended is determined by the `ShouldEndSession` trait. When the session is ending, a new validator set
can be chosen by `OnSessionEnding` implementations.
- **Session key:** A session key is actually several keys kept together that provide the various signing
functions required by network authorities/validators in pursuit of their duties.
- **Validator ID:** Every account has an associated validator ID. For some simple staking systems, this
may just be the same as the account ID. For staking systems using a stash/controller model,
the validator ID would be the stash account ID of the controller.
- **Session key configuration process:** Session keys are set using `set_keys` for use not in
the next session, but the session after next. They are stored in `NextKeys`, a mapping between
the caller's `ValidatorId` and the session keys provided. `set_keys` allows users to set their
session key prior to being selected as validator.
It is a public call since it uses `ensure_signed`, which checks that the origin is a signed account.
As such, the account ID of the origin stored in `NextKeys` may not necessarily be associated with
a block author or a validator. The session keys of accounts are removed once their account balance is zero.
- **Session length:** This pallet does not assume anything about the length of each session.
Rather, it relies on an implementation of `ShouldEndSession` to dictate a new session's start.
This pallet provides the `PeriodicSessions` struct for simple periodic sessions.
- **Session rotation configuration:** Configure as either a 'normal' (rewardable session where rewards are
applied) or 'exceptional' (slashable) session rotation.
- **Session rotation process:** At the beginning of each block, the `on_initialize` function
queries the provided implementation of `ShouldEndSession`. If the session is to end the newly
activated validator IDs and session keys are taken from storage and passed to the
`SessionHandler`. The validator set supplied by `SessionManager::new_session` and the corresponding session
keys, which may have been registered via `set_keys` during the previous session, are written
to storage where they will wait one session before being passed to the `SessionHandler`
themselves.
- **Session:** A session is a period of time that has a constant set of validators. Validators can only join or exit the
validator set at a session change. It is measured in block numbers. The block where a session is ended is determined by
the `ShouldEndSession` trait. When the session is ending, a new validator set can be chosen by `OnSessionEnding`
implementations.
- **Session key:** A session key is actually several keys kept together that provide the various signing functions
required by network authorities/validators in pursuit of their duties.
- **Validator ID:** Every account has an associated validator ID. For some simple staking systems, this may just be the
same as the account ID. For staking systems using a stash/controller model, the validator ID would be the stash account
ID of the controller.
- **Session key configuration process:** Session keys are set using `set_keys` for use not in the next session, but the
session after next. They are stored in `NextKeys`, a mapping between the caller's `ValidatorId` and the session keys
provided. `set_keys` allows users to set their session key prior to being selected as validator. It is a public call
since it uses `ensure_signed`, which checks that the origin is a signed account. As such, the account ID of the origin
stored in `NextKeys` may not necessarily be associated with a block author or a validator. The session keys of accounts
are removed once their account balance is zero.
- **Session length:** This pallet does not assume anything about the length of each session. Rather, it relies on an
implementation of `ShouldEndSession` to dictate a new session's start. This pallet provides the `PeriodicSessions`
struct for simple periodic sessions.
- **Session rotation configuration:** Configure as either a 'normal' (rewardable session where rewards are applied) or
'exceptional' (slashable) session rotation.
- **Session rotation process:** At the beginning of each block, the `on_initialize` function queries the provided
implementation of `ShouldEndSession`. If the session is to end the newly activated validator IDs and session keys are
taken from storage and passed to the `SessionHandler`. The validator set supplied by `SessionManager::new_session` and
the corresponding session keys, which may have been registered via `set_keys` during the previous session, are written
to storage where they will wait one session before being passed to the `SessionHandler` themselves.
### Goals
@@ -57,8 +54,8 @@ The Session pallet is designed to make the following possible:
### Public Functions
- `rotate_session` - Change to the next session. Register the new authority set. Queue changes
for next session rotation.
- `rotate_session` - Change to the next session. Register the new authority set. Queue changes for next session
rotation.
- `disable_index` - Disable a validator by index.
- `disable` - Disable a validator by Validator ID
@@ -66,7 +63,8 @@ for next session rotation.
### Example from the FRAME
The [Staking pallet](https://docs.rs/pallet-staking/latest/pallet_staking/) uses the Session pallet to get the validator set.
The [Staking pallet](https://docs.rs/pallet-staking/latest/pallet_staking/) uses the Session pallet to get the validator
set.
```rust
use pallet_session as session;
@@ -1,3 +1,3 @@
Benchmarks for the Session Pallet.
License: Apache-2.0
License: Apache-2.0
+19 -19
View File
@@ -11,16 +11,16 @@ and maintain a membership society.
### User Types
At any point, a user in the society can be one of a:
* Bidder - A user who has submitted intention of joining the society.
* Candidate - A user who will be voted on to join the society.
* Suspended Candidate - A user who failed to win a vote.
* Member - A user who is a member of the society.
* Suspended Member - A member of the society who has accumulated too many strikes
- Bidder - A user who has submitted intention of joining the society.
- Candidate - A user who will be voted on to join the society.
- Suspended Candidate - A user who failed to win a vote.
- Member - A user who is a member of the society.
- Suspended Member - A member of the society who has accumulated too many strikes
or failed their membership challenge.
Of the non-suspended members, there is always a:
* Head - A member who is exempt from suspension.
* Defender - A member whose membership is under question and voted on again.
- Head - A member who is exempt from suspension.
- Defender - A member whose membership is under question and voted on again.
Of the non-suspended members of the society, a random set of them are chosen as
"skeptics". The mechanics of skeptics is explained in the
@@ -201,28 +201,28 @@ future payouts slashed.
#### For General Users
* `bid` - A user can make a bid to join the membership society by reserving a deposit.
* `unbid` - A user can withdraw their bid for entry, the deposit is returned.
- `bid` - A user can make a bid to join the membership society by reserving a deposit.
- `unbid` - A user can withdraw their bid for entry, the deposit is returned.
#### For Members
* `vouch` - A member can place a bid on behalf of a user to join the membership society.
* `unvouch` - A member can revoke their vouch for a user.
* `vote` - A member can vote to approve or reject a candidate's request to join the society.
* `defender_vote` - A member can vote to approve or reject a defender's continued membership
- `vouch` - A member can place a bid on behalf of a user to join the membership society.
- `unvouch` - A member can revoke their vouch for a user.
- `vote` - A member can vote to approve or reject a candidate's request to join the society.
- `defender_vote` - A member can vote to approve or reject a defender's continued membership
to the society.
* `payout` - A member can claim their first matured payment.
* `unfound` - Allow the founder to unfound the society when they are the only member.
- `payout` - A member can claim their first matured payment.
- `unfound` - Allow the founder to unfound the society when they are the only member.
#### For Super Users
* `found` - The founder origin can initiate this society. Useful for bootstrapping the Society
- `found` - The founder origin can initiate this society. Useful for bootstrapping the Society
pallet on an already running chain.
* `judge_suspended_member` - The suspension judgement origin is able to make
- `judge_suspended_member` - The suspension judgement origin is able to make
judgement on a suspended member.
* `judge_suspended_candidate` - The suspension judgement origin is able to
- `judge_suspended_candidate` - The suspension judgement origin is able to
make judgement on a suspended candidate.
* `set_max_membership` - The ROOT origin can update the maximum member count for the society.
- `set_max_membership` - The ROOT origin can update the maximum member count for the society.
The max membership count must be greater than 1.
License: Apache-2.0
+97 -96
View File
@@ -8,25 +8,24 @@ The Staking module is used to manage funds at stake by network maintainers.
## Overview
The Staking module is the means by which a set of network maintainers (known as _authorities_ in
some contexts and _validators_ in others) are chosen based upon those who voluntarily place
funds under deposit. Under deposit, those funds are rewarded under normal operation but are held
at pain of _slash_ (expropriation) should the staked maintainer be found not to be discharging
its duties properly.
The Staking module is the means by which a set of network maintainers (known as _authorities_ in some contexts and
_validators_ in others) are chosen based upon those who voluntarily place funds under deposit. Under deposit, those
funds are rewarded under normal operation but are held at pain of _slash_ (expropriation) should the staked maintainer
be found not to be discharging its duties properly.
### Terminology
<!-- Original author of paragraph: @gavofyork -->
- Staking: The process of locking up funds for some time, placing them at risk of slashing
(loss) in order to become a rewarded maintainer of the network.
- Validating: The process of running a node to actively maintain the network, either by
producing blocks or guaranteeing finality of the chain.
- Nominating: The process of placing staked funds behind one or more validators in order to
share in any reward, and punishment, they take.
- Staking: The process of locking up funds for some time, placing them at risk of slashing (loss) in order to become a
rewarded maintainer of the network.
- Validating: The process of running a node to actively maintain the network, either by producing blocks or guaranteeing
finality of the chain.
- Nominating: The process of placing staked funds behind one or more validators in order to share in any reward, and
punishment, they take.
- Stash account: The account holding an owner's funds used for staking.
- Controller account: The account that controls an owner's funds for staking.
- Era: A (whole) number of sessions, which is the period that the validator set (and each
validator's active nominator set) is recalculated and where rewards are paid out.
- Era: A (whole) number of sessions, which is the period that the validator set (and each validator's active nominator
set) is recalculated and where rewards are paid out.
- Slash: The punishment of a staker by reducing its funds.
### Goals
@@ -42,91 +41,90 @@ The staking system in Substrate NPoS is designed to make the following possible:
#### Staking
Almost any interaction with the Staking module requires a process of _**bonding**_ (also known
as being a _staker_). To become *bonded*, a fund-holding account known as the _stash account_,
which holds some or all of the funds that become frozen in place as part of the staking process,
is paired with an active **controller** account, which issues instructions on how they shall be
used.
Almost any interaction with the Staking module requires a process of _**bonding**_ (also known as being a _staker_). To
become *bonded*, a fund-holding account known as the _stash account_, which holds some or all of the funds that become
frozen in place as part of the staking process, is paired with an active **controller** account, which issues
instructions on how they shall be used.
An account pair can become bonded using the [`bond`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.bond) call.
An account pair can become bonded using the
[`bond`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.bond) call.
Stash accounts can update their associated controller back to their stash account using the
[`set_controller`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.set_controller)
call.
[`set_controller`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.set_controller) call.
Note: Controller accounts are being deprecated in favor of proxy accounts, so it is no longer
possible to set a unique address for a stash's controller.
Note: Controller accounts are being deprecated in favor of proxy accounts, so it is no longer possible to set a unique
address for a stash's controller.
There are three possible roles that any staked account pair can be in: `Validator`, `Nominator`
and `Idle` (defined in [`StakerStatus`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.StakerStatus.html)). There are three
There are three possible roles that any staked account pair can be in: `Validator`, `Nominator` and `Idle` (defined in
[`StakerStatus`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.StakerStatus.html)). There are three
corresponding instructions to change between roles, namely:
[`validate`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.validate),
[`nominate`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.nominate), and [`chill`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.chill).
[`nominate`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.nominate), and
[`chill`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.chill).
#### Validating
A **validator** takes the role of either validating blocks or ensuring their finality,
maintaining the veracity of the network. A validator should avoid both any sort of malicious
misbehavior and going offline. Bonded accounts that state interest in being a validator do NOT
get immediately chosen as a validator. Instead, they are declared as a _candidate_ and they
_might_ get elected at the _next era_ as a validator. The result of the election is determined
by nominators and their votes.
A **validator** takes the role of either validating blocks or ensuring their finality, maintaining the veracity of the
network. A validator should avoid both any sort of malicious misbehavior and going offline. Bonded accounts that state
interest in being a validator do NOT get immediately chosen as a validator. Instead, they are declared as a _candidate_
and they _might_ get elected at the _next era_ as a validator. The result of the election is determined by nominators
and their votes.
An account can become a validator candidate via the
[`validate`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.validate) call.
#### Nomination
A **nominator** does not take any _direct_ role in maintaining the network, instead, it votes on
a set of validators to be elected. Once interest in nomination is stated by an account, it
takes effect at the next election round. The funds in the nominator's stash account indicate the
_weight_ of its vote. Both the rewards and any punishment that a validator earns are shared
between the validator and its nominators. This rule incentivizes the nominators to NOT vote for
the misbehaving/offline validators as much as possible, simply because the nominators will also
lose funds if they vote poorly.
A **nominator** does not take any _direct_ role in maintaining the network, instead, it votes on a set of validators to
be elected. Once interest in nomination is stated by an account, it takes effect at the next election round. The funds
in the nominator's stash account indicate the _weight_ of its vote. Both the rewards and any punishment that a validator
earns are shared between the validator and its nominators. This rule incentivizes the nominators to NOT vote for the
misbehaving/offline validators as much as possible, simply because the nominators will also lose funds if they vote
poorly.
An account can become a nominator via the [`nominate`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.nominate) call.
An account can become a nominator via the
[`nominate`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.nominate) call.
#### Rewards and Slash
The **reward and slashing** procedure is the core of the Staking module, attempting to _embrace
valid behavior_ while _punishing any misbehavior or lack of availability_.
The **reward and slashing** procedure is the core of the Staking module, attempting to _embrace valid behavior_ while
_punishing any misbehavior or lack of availability_.
Rewards must be claimed for each era before it gets too old by `$HISTORY_DEPTH` using the
`payout_stakers` call. Any account can call `payout_stakers`, which pays the reward to the
validator as well as its nominators. Only the [`Config::MaxNominatorRewardedPerValidator`]
biggest stakers can claim their reward. This is to limit the i/o cost to mutate storage for each
nominator's account.
Rewards must be claimed for each era before it gets too old by `$HISTORY_DEPTH` using the `payout_stakers` call. Any
account can call `payout_stakers`, which pays the reward to the validator as well as its nominators. Only the
[`Config::MaxNominatorRewardedPerValidator`] biggest stakers can claim their reward. This is to limit the i/o cost to
mutate storage for each nominator's account.
Slashing can occur at any point in time, once misbehavior is reported. Once slashing is
determined, a value is deducted from the balance of the validator and all the nominators who
voted for this validator (values are deducted from the _stash_ account of the slashed entity).
Slashing can occur at any point in time, once misbehavior is reported. Once slashing is determined, a value is deducted
from the balance of the validator and all the nominators who voted for this validator (values are deducted from the
_stash_ account of the slashed entity).
Slashing logic is further described in the documentation of the `slashing` module.
Similar to slashing, rewards are also shared among a validator and its associated nominators.
Yet, the reward funds are not always transferred to the stash account and can be configured. See
[Reward Calculation](https://docs.rs/pallet-staking/latest/pallet_staking/#reward-calculation) for more details.
Similar to slashing, rewards are also shared among a validator and its associated nominators. Yet, the reward funds are
not always transferred to the stash account and can be configured. See [Reward
Calculation](https://docs.rs/pallet-staking/latest/pallet_staking/#reward-calculation) for more details.
#### Chilling
Finally, any of the roles above can choose to step back temporarily and just chill for a while.
This means that if they are a nominator, they will not be considered as voters anymore and if
they are validators, they will no longer be a candidate for the next election.
Finally, any of the roles above can choose to step back temporarily and just chill for a while. This means that if they
are a nominator, they will not be considered as voters anymore and if they are validators, they will no longer be a
candidate for the next election.
An account can step back via the [`chill`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.chill) call.
An account can step back via the
[`chill`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.chill) call.
### Session managing
The module implement the trait `SessionManager`. Which is the only API to query new validator
set and allowing these validator set to be rewarded once their era is ended.
The module implement the trait `SessionManager`. Which is the only API to query new validator set and allowing these
validator set to be rewarded once their era is ended.
## Interface
### Dispatchable Functions
The dispatchable functions of the Staking module enable the steps needed for entities to accept
and change their role, alongside some helper functions to get/set the metadata of the module.
The dispatchable functions of the Staking module enable the steps needed for entities to accept and change their role,
alongside some helper functions to get/set the metadata of the module.
### Public Functions
@@ -134,7 +132,7 @@ The Staking module contains many public storage items and (im)mutable functions.
## Usage
### Example: Rewarding a validator by id.
### Example: Rewarding a validator by id
```rust
use pallet_staking::{self as staking};
@@ -169,7 +167,8 @@ pub mod pallet {
### Era payout
The era payout is computed using yearly inflation curve defined at
[`T::RewardCurve`](https://docs.rs/pallet-staking/latest/pallet_staking/trait.Config.html#associatedtype.RewardCurve) as such:
[`T::RewardCurve`](https://docs.rs/pallet-staking/latest/pallet_staking/trait.Config.html#associatedtype.RewardCurve) as
such:
```nocompile
staker_payout = yearly_inflation(npos_token_staked / total_tokens) * total_tokens / era_per_year
@@ -184,37 +183,38 @@ The remaining reward is send to the configurable end-point
### Reward Calculation
Validators and nominators are rewarded at the end of each era. The total reward of an era is
calculated using the era duration and the staking rate (the total amount of tokens staked by
nominators and validators, divided by the total token supply). It aims to incentivize toward a
defined staking rate. The full specification can be found
Validators and nominators are rewarded at the end of each era. The total reward of an era is calculated using the era
duration and the staking rate (the total amount of tokens staked by nominators and validators, divided by the total
token supply). It aims to incentivize toward a defined staking rate. The full specification can be found
[here](https://research.web3.foundation/en/latest/polkadot/economics/1-token-economics.html#inflation-model).
Total reward is split among validators and their nominators depending on the number of points
they received during the era. Points are added to a validator using
Total reward is split among validators and their nominators depending on the number of points they received during the
era. Points are added to a validator using
[`reward_by_ids`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.reward_by_ids) or
[`reward_by_indices`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.reward_by_indices).
[`Module`](https://docs.rs/pallet-staking/latest/pallet_staking/struct.Module.html) implements
[`pallet_authorship::EventHandler`](https://docs.rs/pallet-authorship/latest/pallet_authorship/trait.EventHandler.html) to add reward
points to block producer and block producer of referenced uncles.
[`pallet_authorship::EventHandler`](https://docs.rs/pallet-authorship/latest/pallet_authorship/trait.EventHandler.html)
to add reward points to block producer and block producer of referenced uncles.
The validator and its nominator split their reward as following:
The validator can declare an amount, named
[`commission`](https://docs.rs/pallet-staking/latest/pallet_staking/struct.ValidatorPrefs.html#structfield.commission), that does not get shared
with the nominators at each reward payout through its
[`ValidatorPrefs`](https://docs.rs/pallet-staking/latest/pallet_staking/struct.ValidatorPrefs.html). This value gets deducted from the total reward
that is paid to the validator and its nominators. The remaining portion is split among the
validator and all of the nominators that nominated the validator, proportional to the value
staked behind this validator (_i.e._ dividing the
[`commission`](https://docs.rs/pallet-staking/latest/pallet_staking/struct.ValidatorPrefs.html#structfield.commission),
that does not get shared with the nominators at each reward payout through its
[`ValidatorPrefs`](https://docs.rs/pallet-staking/latest/pallet_staking/struct.ValidatorPrefs.html). This value gets
deducted from the total reward that is paid to the validator and its nominators. The remaining portion is split among
the validator and all of the nominators that nominated the validator, proportional to the value staked behind this
validator (_i.e._ dividing the
[`own`](https://docs.rs/pallet-staking/latest/pallet_staking/struct.Exposure.html#structfield.own) or
[`others`](https://docs.rs/pallet-staking/latest/pallet_staking/struct.Exposure.html#structfield.others) by
[`total`](https://docs.rs/pallet-staking/latest/pallet_staking/struct.Exposure.html#structfield.total) in [`Exposure`](https://docs.rs/pallet-staking/latest/pallet_staking/struct.Exposure.html)).
[`total`](https://docs.rs/pallet-staking/latest/pallet_staking/struct.Exposure.html#structfield.total) in
[`Exposure`](https://docs.rs/pallet-staking/latest/pallet_staking/struct.Exposure.html)).
All entities who receive a reward have the option to choose their reward destination through the
[`Payee`](https://docs.rs/pallet-staking/latest/pallet_staking/struct.Payee.html) storage item (see
[`set_payee`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.set_payee)), to be one of the following:
[`set_payee`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.set_payee)), to be one of the
following:
- Controller account, (obviously) not increasing the staked value.
- Stash account, not increasing the staked value.
@@ -225,32 +225,33 @@ All entities who receive a reward have the option to choose their reward destina
Any funds already placed into stash can be the target of the following operations:
The controller account can free a portion (or all) of the funds using the
[`unbond`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.unbond) call. Note that the funds are not immediately
accessible. Instead, a duration denoted by [`BondingDuration`](https://docs.rs/pallet-staking/latest/pallet_staking/trait.Config.html#associatedtype.BondingDuration)
(in number of eras) must pass until the funds can actually be removed. Once the
`BondingDuration` is over, the [`withdraw_unbonded`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.withdraw_unbonded)
[`unbond`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.unbond) call. Note that the funds
are not immediately accessible. Instead, a duration denoted by
[`BondingDuration`](https://docs.rs/pallet-staking/latest/pallet_staking/trait.Config.html#associatedtype.BondingDuration)
(in number of eras) must pass until the funds can actually be removed. Once the `BondingDuration` is over, the
[`withdraw_unbonded`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.withdraw_unbonded)
call can be used to actually withdraw the funds.
Note that there is a limitation to the number of fund-chunks that can be scheduled to be
unlocked in the future via [`unbond`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.unbond). In case this maximum
(`MAX_UNLOCKING_CHUNKS`) is reached, the bonded account _must_ first wait until a successful
call to `withdraw_unbonded` to remove some of the chunks.
Note that there is a limitation to the number of fund-chunks that can be scheduled to be unlocked in the future via
[`unbond`](https://docs.rs/pallet-staking/latest/pallet_staking/enum.Call.html#variant.unbond). In case this maximum
(`MAX_UNLOCKING_CHUNKS`) is reached, the bonded account _must_ first wait until a successful call to `withdraw_unbonded`
to remove some of the chunks.
### Election Algorithm
The current election algorithm is implemented based on Phragmén. The reference implementation
can be found [here](https://github.com/w3f/consensus/tree/master/NPoS).
The current election algorithm is implemented based on Phragmén. The reference implementation can be found
[here](https://github.com/w3f/consensus/tree/master/NPoS).
The election algorithm, aside from electing the validators with the most stake value and votes,
tries to divide the nominator votes among candidates in an equal manner. To further assure this,
an optional post-processing can be applied that iteratively normalizes the nominator staked
values until the total difference among votes of a particular nominator are less than a
threshold.
The election algorithm, aside from electing the validators with the most stake value and votes, tries to divide the
nominator votes among candidates in an equal manner. To further assure this, an optional post-processing can be applied
that iteratively normalizes the nominator staked values until the total difference among votes of a particular nominator
are less than a threshold.
## GenesisConfig
The Staking module depends on the [`GenesisConfig`](https://docs.rs/pallet-staking/latest/pallet_staking/struct.GenesisConfig.html). The
`GenesisConfig` is optional and allow to set some initial stakers.
The Staking module depends on the
[`GenesisConfig`](https://docs.rs/pallet-staking/latest/pallet_staking/struct.GenesisConfig.html). The `GenesisConfig`
is optional and allow to set some initial stakers.
## Related Modules
+3 -3
View File
@@ -16,8 +16,8 @@ Only one account can be the sudo key at a time.
Only the sudo key can call the dispatchable functions from the Sudo module.
* `sudo` - Make a `Root` call to a dispatchable function.
* `set_key` - Assign a new account to be the sudo key.
- `sudo` - Make a `Root` call to a dispatchable function.
- `set_key` - Assign a new account to be the sudo key.
## Usage
@@ -68,7 +68,7 @@ You need to set an initial superuser account as the sudo `key`.
## Related Modules
* [Democracy](https://docs.rs/pallet-democracy/latest/pallet_democracy/)
- [Democracy](https://docs.rs/pallet-democracy/latest/pallet_democracy/)
[`Call`]: ./enum.Call.html
[`Config`]: ./trait.Config.html
+1 -1
View File
@@ -1,3 +1,3 @@
Support code for the runtime.
License: Apache-2.0
License: Apache-2.0
+3 -3
View File
@@ -1386,7 +1386,7 @@ fn metadata() {
}
}
let readme = "Support code for the runtime.\n\nLicense: Apache-2.0";
let readme = "Support code for the runtime.\n\nLicense: Apache-2.0\n";
let expected_pallet_doc = vec![" Pallet documentation", readme, readme];
let pallets = vec![
@@ -1889,7 +1889,7 @@ fn metadata_ir_pallet_runtime_docs() {
.find(|pallet| pallet.name == "Example")
.expect("Pallet should be present");
let readme = "Support code for the runtime.\n\nLicense: Apache-2.0";
let readme = "Support code for the runtime.\n\nLicense: Apache-2.0\n";
let expected = vec![" Pallet documentation", readme, readme];
assert_eq!(pallet.docs, expected);
}
@@ -1919,7 +1919,7 @@ fn extrinsic_metadata_ir_types() {
#[test]
fn test_pallet_runtime_docs() {
let docs = crate::pallet::Pallet::<Runtime>::pallet_documentation_metadata();
let readme = "Support code for the runtime.\n\nLicense: Apache-2.0";
let readme = "Support code for the runtime.\n\nLicense: Apache-2.0\n";
let expected = vec![" Pallet documentation", readme, readme];
assert_eq!(docs, expected);
}
+16 -20
View File
@@ -1,20 +1,20 @@
# System Module
The System module provides low-level access to core types and cross-cutting utilities.
It acts as the base layer for other pallets to interact with the Substrate framework components.
The System module provides low-level access to core types and cross-cutting utilities. It acts as the base layer for
other pallets to interact with the Substrate framework components.
- [`system::Config`](https://docs.rs/frame-system/latest/frame_system/pallet/trait.Config.html)
## Overview
The System module defines the core data types used in a Substrate runtime.
It also provides several utility functions (see [`Pallet`](https://docs.rs/frame-system/latest/frame_system/pallet/struct.Pallet.html)) for other FRAME pallets.
The System module defines the core data types used in a Substrate runtime. It also provides several utility functions
(see [`Pallet`](https://docs.rs/frame-system/latest/frame_system/pallet/struct.Pallet.html)) for other FRAME pallets.
In addition, it manages the storage items for extrinsics data, indexes, event records, and digest items,
among other things that support the execution of the current block.
In addition, it manages the storage items for extrinsics data, indexes, event records, and digest items, among other
things that support the execution of the current block.
It also handles low-level tasks like depositing logs, basic set up and take down of
temporary storage entries, and access to previous block hashes.
It also handles low-level tasks like depositing logs, basic set up and take down of temporary storage entries, and
access to previous block hashes.
## Interface
@@ -24,26 +24,22 @@ The System module does not implement any dispatchable functions.
### Public Functions
See the [`Pallet`](https://docs.rs/frame-system/latest/frame_system/pallet/struct.Pallet.html) struct for details of publicly available functions.
See the [`Pallet`](https://docs.rs/frame-system/latest/frame_system/pallet/struct.Pallet.html) struct for details of
publicly available functions.
### Signed Extensions
The System module defines the following extensions:
- [`CheckWeight`]: Checks the weight and length of the block and ensure that it does not
exceed the limits.
- [`CheckNonce`]: Checks the nonce of the transaction. Contains a single payload of type
`T::Nonce`.
- [`CheckWeight`]: Checks the weight and length of the block and ensure that it does not exceed the limits.
- [`CheckNonce`]: Checks the nonce of the transaction. Contains a single payload of type `T::Nonce`.
- [`CheckEra`]: Checks the era of the transaction. Contains a single payload of type `Era`.
- [`CheckGenesis`]: Checks the provided genesis hash of the transaction. Must be a part of the
signed payload of the transaction.
- [`CheckSpecVersion`]: Checks that the runtime version is the same as the one used to sign the
transaction.
- [`CheckTxVersion`]: Checks that the transaction version is the same as the one used to sign the
- [`CheckGenesis`]: Checks the provided genesis hash of the transaction. Must be a part of the signed payload of the
transaction.
- [`CheckSpecVersion`]: Checks that the runtime version is the same as the one used to sign the transaction.
- [`CheckTxVersion`]: Checks that the transaction version is the same as the one used to sign the transaction.
Lookup the runtime aggregator file (e.g. `node/runtime`) to see the full list of signed
extensions included in a chain.
Lookup the runtime aggregator file (e.g. `node/runtime`) to see the full list of signed extensions included in a chain.
## Usage
@@ -1 +1 @@
License: Apache-2.0
License: Apache-2.0
@@ -2,4 +2,5 @@ These runtimes are used for benchmarking the `set_code` intrinsic.
**Don't use them in production environments!**
To update the just copy the new runtime from `target/release/wbuild/kitchensink-runtime/kitchensink_runtime.compact.compressed.wasm` to here.
To update the just copy the new runtime from
`target/release/wbuild/kitchensink-runtime/kitchensink_runtime.compact.compressed.wasm` to here.
@@ -4,4 +4,4 @@ This API should be imported and implemented by the runtime,
of a node that wants to use the custom RPC extension
adding System access methods.
License: Apache-2.0
License: Apache-2.0
+4 -4
View File
@@ -22,16 +22,16 @@ because of cumulative calculation errors and hence should be avoided.
### Dispatchable Functions
* `set` - Sets the current time.
- `set` - Sets the current time.
### Public functions
* `get` - Gets the current time for the current block. If this function is called prior to
- `get` - Gets the current time for the current block. If this function is called prior to
setting the timestamp, it will return the timestamp of the previous block.
### Config Getters
* `MinimumPeriod` - Gets the minimum (and advised) period between blocks for the chain.
- `MinimumPeriod` - Gets the minimum (and advised) period between blocks for the chain.
## Usage
@@ -78,6 +78,6 @@ the Timestamp module for session management.
## Related Modules
* [Session](https://docs.rs/pallet-session/latest/pallet_session/)
- [Session](https://docs.rs/pallet-session/latest/pallet_session/)
License: Apache-2.0
+2 -2
View File
@@ -11,7 +11,7 @@ entered where any remaining members can declare their tip amounts also. After th
countdown period, the median of all declared tips is paid to the reported beneficiary, along with
any finders fee, in case of a public (and bonded) original report.
### Terminology
## Terminology
- **Tipping:** The process of gathering declarations of amounts to tip and taking the median amount
to be transferred from the treasury to a beneficiary account.
@@ -30,4 +30,4 @@ any finders fee, in case of a public (and bonded) original report.
- `tip_new` - Report an item worthy of a tip and declare a specific amount to tip.
- `tip` - Declare or redeclare an amount to tip for a particular reason.
- `close_tip` - Close and pay out a tip.
- `slash_tip` - Remove and slash an already-open tip.
- `slash_tip` - Remove and slash an already-open tip.
+14 -10
View File
@@ -2,8 +2,9 @@
Indexes transactions and manages storage proofs.
Allows storing arbitrary data on the chain. Data is automatically removed after `StoragePeriod` blocks, unless the storage is renewed.
Validators must submit proof of storing a random chunk of data for block `N - StoragePeriod` when producing block `N`.
Allows storing arbitrary data on the chain. Data is automatically removed after `StoragePeriod` blocks, unless the
storage is renewed. Validators must submit proof of storing a random chunk of data for block `N - StoragePeriod` when
producing block `N`.
# Running a chain
@@ -15,8 +16,9 @@ Start with generating a chain spec.
cargo run --release -- build-spec --chain=local > sc_init.json
```
Edit the json chain spec file to customise the chain. The storage chain genesis params are configured in the `transactionStorage` section.
Note that `storagePeriod` is specified in blocks and changing it also requires code changes at the moment.
Edit the json chain spec file to customise the chain. The storage chain genesis params are configured in the
`transactionStorage` section. Note that `storagePeriod` is specified in blocks and changing it also requires code
changes at the moment.
Build a raw spec from the init spec.
@@ -31,11 +33,11 @@ cargo run --release -- --chain=sc.json -d /tmp/alice --storage-chain --keep-bloc
cargo run --release -- --chain=sc.json -d /tmp/bob --storage-chain --keep-blocks=100800 --ipfs-server --validator --bob
```
`--storage-chain` enables transaction indexing.
`--keep-blocks=100800` enables block pruning. The value here should be greater or equal than the storage period.
`--ipfs-server` enables serving stored content over IPFS.
`--storage-chain` enables transaction indexing. `--keep-blocks=100800` enables block pruning. The value here should be
greater or equal than the storage period. `--ipfs-server` enables serving stored content over IPFS.
Once the network is started, any other joining nodes need to sync with `--sync=fast`. Regular sync will fail because block pruning removes old blocks. The chain does not keep full block history.
Once the network is started, any other joining nodes need to sync with `--sync=fast`. Regular sync will fail because
block pruning removes old blocks. The chain does not keep full block history.
```bash
cargo run --release -- --chain=sc.json -d /tmp/charlie --storage-chain --keep-blocks=100800 --ipfs-server --validator --charlie --sync=fast
@@ -43,7 +45,8 @@ cargo run --release -- --chain=sc.json -d /tmp/charlie --storage-chain --keep-bl
# Making transactions
To store data use the `transactionStorage.store` extrinsic. And IPFS CID can be generated from the Blake2-256 hash of the data.
To store data use the `transactionStorage.store` extrinsic. And IPFS CID can be generated from the Blake2-256 hash of
the data.
```js
const util_crypto = require('@polkadot/util-crypto');
@@ -76,7 +79,8 @@ ipfs block get /ipfs/<CID> > kitten.jpeg
```
To renew data and prevent it from being disposed after the storage period, use `transactionStorage.renew(block, index)`
where `block` is the block number of the previous store or renew transction, and index is the index of that transaction in the block.
where `block` is the block number of the previous store or renew transction, and index is the index of that transaction
in the block.
License: Apache-2.0
+8 -8
View File
@@ -13,9 +13,11 @@ The Uniques module provides functionality for non-fungible tokens' management, i
* Attributes Management
* Item Burning
To use it in your runtime, you need to implement [`uniques::Config`](https://paritytech.github.io/substrate/master/pallet_uniques/pallet/trait.Config.html).
To use it in your runtime, you need to implement
[`uniques::Config`](https://paritytech.github.io/substrate/master/pallet_uniques/pallet/trait.Config.html).
The supported dispatchable functions are documented in the [`uniques::Call`](https://paritytech.github.io/substrate/master/pallet_uniques/pallet/enum.Call.html) enum.
The supported dispatchable functions are documented in the
[`uniques::Call`](https://paritytech.github.io/substrate/master/pallet_uniques/pallet/enum.Call.html) enum.
### Terminology
@@ -23,8 +25,8 @@ The supported dispatchable functions are documented in the [`uniques::Call`](htt
* **Item minting:** The action of creating a new item within a collection.
* **Item transfer:** The action of sending an item from one account to another.
* **Item burning:** The destruction of an item.
* **Non-fungible token (NFT):** An item for which each unit has unique characteristics. There is exactly
one instance of such an item in existence and there is exactly one owning account.
* **Non-fungible token (NFT):** An item for which each unit has unique characteristics. There is exactly one instance of
such an item in existence and there is exactly one owning account.
### Goals
@@ -33,10 +35,8 @@ The Uniques pallet in Substrate is designed to make the following possible:
* Allow accounts to permissionlessly create NFT collections.
* Allow a named (permissioned) account to mint and burn unique items within a collection.
* Move items between accounts permissionlessly.
* Allow a named (permissioned) account to freeze and unfreeze unique items within a
collection or the entire collection.
* Allow the owner of an item to delegate the ability to transfer the item to some
named third-party.
* Allow a named (permissioned) account to freeze and unfreeze unique items within a collection or the entire collection.
* Allow the owner of an item to delegate the ability to transfer the item to some named third-party.
## Interface

Some files were not shown because too many files have changed in this diff Show More