build: 🏗️ DataHaven operator setup (#6)

Adds the `Substrate` node and runtime, as well as configuration and test
files, from https://github.com/Moonsong-Labs/flamingo to the `operator`
folder in DataHaven
This commit is contained in:
Gonza Montiel 2025-03-17 17:57:14 +01:00 committed by GitHub
parent b4797cceef
commit 7a4d441fd9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
56 changed files with 7270 additions and 0 deletions

90
.github/workflows/build.yml vendored Normal file
View file

@ -0,0 +1,90 @@
name: Build
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
CARGO_TERM_COLOR: always
WORKING_DIR: operator
jobs:
cargo-check:
name: Cargo Check
runs-on: ubuntu-latest
defaults:
run:
working-directory: ${{ env.WORKING_DIR }}
steps:
- uses: actions/checkout@v4
- name: Install protoc
run: |
sudo apt-get update
sudo apt-get install -y protobuf-compiler
protoc --version
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- name: Cache dependencies
uses: Swatinem/rust-cache@v2
- name: Run cargo check
run: cargo check
cargo-fmt:
name: Cargo Format
runs-on: ubuntu-latest
defaults:
run:
working-directory: ${{ env.WORKING_DIR }}
steps:
- uses: actions/checkout@v4
- name: Install protoc
run: |
sudo apt-get update
sudo apt-get install -y protobuf-compiler
protoc --version
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- name: Cache dependencies
uses: Swatinem/rust-cache@v2
- name: Run cargo fmt
run: cargo fmt --all -- --check
cargo-test:
name: Cargo Test
runs-on: ubuntu-latest
defaults:
run:
working-directory: ${{ env.WORKING_DIR }}
steps:
- uses: actions/checkout@v4
- name: Install protoc
run: |
sudo apt-get update
sudo apt-get install -y protobuf-compiler
protoc --version
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- name: Cache dependencies
uses: Swatinem/rust-cache@v2
- name: Run tests
run: cargo test --verbose

31
operator/.gitignore vendored Normal file
View file

@ -0,0 +1,31 @@
# MacOS thing
**/.DS_Store
# Rust directories
target
# Typescript directories
**/node_modules
**/.yarn
# Spec/Wasm build directory
/build/
# Moonbeam-Launch
*.log
tools/specFiles
tools/*-local.json
tools/*-local-raw.json
tools/build
# RustRover
.idea/
# VSCode
.vscode/
# Environment variables
.env
# Temporary files
**/tmp

123
operator/Cargo.toml Normal file
View file

@ -0,0 +1,123 @@
[workspace.package]
license = "GPL-3"
authors = ["MoonsongLabs <dev@moonsonglabs.com>"]
homepage = "https://moonbeam.network/"
repository = "https://github.com/Moonsong-Labs/datahaven.git"
edition = "2021"
[workspace]
members = [
"node",
"runtime",
"pallets/validator-set",
"runtime/common",
]
resolver = "2"
[workspace.dependencies]
# Local
datahaven-runtime = { path = "./runtime", default-features = false }
datahaven-runtime-common = { path = "./runtime/common", default-features = false }
pallet-validator-set = { path = "./pallets/validator-set", default-features = false }
# Crates.io (wasm)
async-trait = { version = "0.1.42" }
parity-scale-codec = { version = "3.0.0", default-features = false, features = ["derive"] }
scale-info = { version = "2.11.6", default-features = false}
serde = { version = "1.0.197", default-features = false, features = [ "derive" ]}
serde_json = { version = "1.0.127", default-features = false }
log = { version = "0.4.25" }
clap = { version = "4.5.10" }
futures = { version = "0.3.30" }
jsonrpsee = { version = "0.24.3" }
hex-literal = { version = "0.3.4" }
codec = { version = "3.6.12", default-features = false, package = "parity-scale-codec" }
blake2-rfc = { version = "0.2.18", default-features = false }
impl-serde = { version = "0.5.0", default-features = false }
libsecp256k1 = { version = "0.7", default-features = false }
sha3 = { version = "0.10", default-features = false }
hex = { version = "0.4.3", default-features = false }
# Polkadot
pallet-transaction-payment = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-basic-authorship = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-client-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-consensus = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-consensus-babe = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-consensus-grandpa = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-executor = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-network = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-offchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-service = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-telemetry = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-transaction-pool-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-application-crypto = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-block-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-blockchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-consensus-babe = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-consensus-grandpa = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-inherents = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-keyring = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-runtime-interface = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-staking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
substrate-frame-rpc-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
substrate-build-script-utils = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
frame-benchmarking-cli = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
frame-metadata-hash-extension = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
frame-executive = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
frame-support-test = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
frame-system-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
frame-system-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
frame-try-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
pallet-babe = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
pallet-grandpa = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
pallet-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
pallet-sudo = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
pallet-timestamp = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
polkadot-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
polkadot-runtime-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-genesis-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-offchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-session = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-storage = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-transaction-pool = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sp-version = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
substrate-wasm-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
# BEEFY
sp-consensus-beefy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-consensus-beefy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
sc-consensus-beefy-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
mmr-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
pallet-beefy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
pallet-beefy-mmr = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
pallet-mmr = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
# Snowbridge
snowbridge-beacon-primitives = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
snowbridge-pallet-ethereum-client = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409", default-features = false }
# Moonkit
pallet-author-inherent = { git = "https://github.com/Moonsong-Labs/moonkit", rev = "002c1a5ae3ce82e1136d5321bff124ab93ed050f", default-features = false }
# Frontier (wasm)
fp-account = { git = "https://github.com/polkadot-evm/frontier", branch = "stable2409", default-features = false }
pallet-ethereum = { git = "https://github.com/polkadot-evm/frontier/", branch = "stable2409", default-features = false }
pallet-evm = { git = "https://github.com/polkadot-evm/frontier/", branch = "stable2409", default-features = false }
pallet-evm-chain-id = { git = "https://github.com/polkadot-evm/frontier/", branch = "stable2409", default-features = false }

View file

28
operator/Dockerfile Normal file
View file

@ -0,0 +1,28 @@
FROM docker.io/paritytech/ci-unified:latest as builder
WORKDIR /polkadot
COPY . /polkadot
RUN cargo fetch
RUN cargo build --locked --release
FROM docker.io/parity/base-bin:latest
COPY --from=builder /polkadot/target/release/datahaven-node /usr/local/bin
USER root
RUN useradd -m -u 1001 -U -s /bin/sh -d /polkadot polkadot && \
mkdir -p /data /polkadot/.local/share && \
chown -R polkadot:polkadot /data && \
ln -s /data /polkadot/.local/share/polkadot && \
# unclutter and minimize the attack surface
rm -rf /usr/bin /usr/sbin && \
# check if executable works in this container
/usr/local/bin/datahaven-node --version
USER polkadot
EXPOSE 30333 9933 9944 9615
VOLUME ["/data"]
ENTRYPOINT ["/usr/local/bin/datahaven-node"]

674
operator/LICENSE Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

13
operator/README.md Normal file
View file

@ -0,0 +1,13 @@
# Datahaven 🫎
Based on https://github.com/paritytech/polkadot-sdk-solochain-template
# Zombienet testing
First, install [zombienet](https://github.com/paritytech/zombienet).
To spawn a local solo chain with four validators and BABE finality, run:
```bash
zombienet -p native spawn test/config/zombie-datahaven-local.toml
```

123
operator/node/Cargo.toml Normal file
View file

@ -0,0 +1,123 @@
[package]
name = "datahaven-node"
description = "A solochain node template built with Substrate, part of Polkadot Sdk."
version = "0.1.0"
license = "Unlicense"
authors.workspace = true
homepage.workspace = true
repository.workspace = true
edition.workspace = true
publish = false
build = "build.rs"
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
clap = { features = ["derive"], workspace = true }
futures = { features = ["thread-pool"], workspace = true }
serde_json = { workspace = true, default-features = true }
jsonrpsee = { features = ["server"], workspace = true }
hex-literal.workspace = true
fp-account = { workspace = true }
sc-cli.workspace = true
sc-cli.default-features = true
sp-core.workspace = true
sp-core.default-features = true
sc-executor.workspace = true
sc-executor.default-features = true
sc-network.workspace = true
sc-network.default-features = true
sc-service.workspace = true
sc-service.default-features = true
sc-telemetry.workspace = true
sc-telemetry.default-features = true
sc-transaction-pool.workspace = true
sc-transaction-pool.default-features = true
sc-transaction-pool-api.workspace = true
sc-transaction-pool-api.default-features = true
sc-offchain.workspace = true
sc-offchain.default-features = true
sc-consensus-babe.workspace = true
sc-consensus-babe.default-features = true
sp-consensus-babe.workspace = true
sp-consensus-babe.default-features = true
sp-consensus-beefy.workspace = true
sp-consensus-beefy.default-features = true
sc-consensus.workspace = true
sc-consensus.default-features = true
sc-consensus-grandpa.workspace = true
sc-consensus-grandpa.default-features = true
sp-consensus-grandpa.workspace = true
sp-consensus-grandpa.default-features = true
sc-client-api.workspace = true
sc-client-api.default-features = true
sc-basic-authorship.workspace = true
sc-basic-authorship.default-features = true
sp-runtime.workspace = true
sp-runtime.default-features = true
sp-io.workspace = true
sp-io.default-features = true
sp-timestamp.workspace = true
sp-timestamp.default-features = true
sp-inherents.workspace = true
sp-inherents.default-features = true
sp-keyring.workspace = true
sp-keyring.default-features = true
sp-api.workspace = true
sp-api.default-features = true
sp-blockchain.workspace = true
sp-blockchain.default-features = true
sp-block-builder.workspace = true
sp-block-builder.default-features = true
frame-system.workspace = true
frame-system.default-features = true
frame-metadata-hash-extension.workspace = true
frame-metadata-hash-extension.default-features = true
pallet-transaction-payment.workspace = true
pallet-transaction-payment.default-features = true
pallet-transaction-payment-rpc.workspace = true
pallet-transaction-payment-rpc.default-features = true
substrate-frame-rpc-system.workspace = true
substrate-frame-rpc-system.default-features = true
frame-benchmarking-cli.workspace = true
frame-benchmarking-cli.default-features = true
datahaven-runtime.workspace = true
# RPC
sc-rpc = { workspace = true, default-features = true }
# Beefy
sc-consensus-beefy.workspace = true
sc-consensus-beefy.default-features = true
sc-consensus-beefy-rpc = { workspace = true, default-features = true }
# MMR
mmr-rpc = { workspace = true, default-features = true }
[build-dependencies]
substrate-build-script-utils.workspace = true
substrate-build-script-utils.default-features = true
[features]
default = ["std"]
std = [
"datahaven-runtime/std",
]
# Dependencies that are only required if runtime benchmarking should be build.
runtime-benchmarks = [
"frame-benchmarking-cli/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"sc-service/runtime-benchmarks",
"datahaven-runtime/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
]
# Enable features that allow the runtime to be tried and debugged. Name might be subject to change
# in the near future.
try-runtime = [
"frame-system/try-runtime",
"pallet-transaction-payment/try-runtime",
"datahaven-runtime/try-runtime",
"sp-runtime/try-runtime",
]

5
operator/node/README.md Normal file
View file

@ -0,0 +1,5 @@
## Release
Polkadot SDK stable2409

7
operator/node/build.rs Normal file
View file

@ -0,0 +1,7 @@
use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};
fn main() {
generate_cargo_keys();
rerun_if_git_head_changed();
}

View file

@ -0,0 +1,174 @@
//! Setup code for [`super::command`] which would otherwise bloat that module.
//!
//! Should only be used for benchmarking as it may break in other contexts.
use crate::service::FullClient;
use datahaven_runtime as runtime;
use fp_account::EthereumSignature;
use runtime::{AccountId, Balance, BalancesCall, SystemCall};
use sc_cli::Result;
use sc_client_api::BlockBackend;
use sp_core::{ecdsa, Encode, Pair};
use sp_inherents::{InherentData, InherentDataProvider};
use sp_runtime::{MultiSignature, OpaqueExtrinsic, SaturatedConversion};
use std::{sync::Arc, time::Duration};
/// Generates extrinsics for the `benchmark overhead` command.
///
/// Note: Should only be used for benchmarking.
pub struct RemarkBuilder {
client: Arc<FullClient>,
}
impl RemarkBuilder {
/// Creates a new [`Self`] from the given client.
pub fn new(client: Arc<FullClient>) -> Self {
Self { client }
}
}
impl frame_benchmarking_cli::ExtrinsicBuilder for RemarkBuilder {
fn pallet(&self) -> &str {
"system"
}
fn extrinsic(&self) -> &str {
"remark"
}
fn build(&self, nonce: u32) -> std::result::Result<OpaqueExtrinsic, &'static str> {
let extrinsic: OpaqueExtrinsic = create_benchmark_extrinsic(
self.client.as_ref(),
ecdsa::Pair::from_string("//Bob", None).expect("static values are valid; qed"),
SystemCall::remark { remark: vec![] }.into(),
nonce,
)
.into();
Ok(extrinsic)
}
}
/// Generates `Balances::TransferKeepAlive` extrinsics for the benchmarks.
///
/// Note: Should only be used for benchmarking.
pub struct TransferKeepAliveBuilder {
client: Arc<FullClient>,
dest: AccountId,
value: Balance,
}
impl TransferKeepAliveBuilder {
/// Creates a new [`Self`] from the given client.
pub fn new(client: Arc<FullClient>, dest: AccountId, value: Balance) -> Self {
Self {
client,
dest,
value,
}
}
}
impl frame_benchmarking_cli::ExtrinsicBuilder for TransferKeepAliveBuilder {
fn pallet(&self) -> &str {
"balances"
}
fn extrinsic(&self) -> &str {
"transfer_keep_alive"
}
fn build(&self, nonce: u32) -> std::result::Result<OpaqueExtrinsic, &'static str> {
let extrinsic: OpaqueExtrinsic = create_benchmark_extrinsic(
self.client.as_ref(),
ecdsa::Pair::from_string("//Bob", None).expect("static values are valid; qed"),
BalancesCall::transfer_keep_alive {
dest: self.dest.clone().into(),
value: self.value,
}
.into(),
nonce,
)
.into();
Ok(extrinsic)
}
}
/// Create a transaction using the given `call`.
///
/// Note: Should only be used for benchmarking.
pub fn create_benchmark_extrinsic(
client: &FullClient,
sender: ecdsa::Pair,
call: runtime::RuntimeCall,
nonce: u32,
) -> runtime::UncheckedExtrinsic {
let genesis_hash = client
.block_hash(0)
.ok()
.flatten()
.expect("Genesis block exists; qed");
let best_hash = client.chain_info().best_hash;
let best_block = client.chain_info().best_number;
let period = runtime::configs::BlockHashCount::get()
.checked_next_power_of_two()
.map(|c| c / 2)
.unwrap_or(2) as u64;
let extra: runtime::SignedExtra = (
frame_system::CheckNonZeroSender::<runtime::Runtime>::new(),
frame_system::CheckSpecVersion::<runtime::Runtime>::new(),
frame_system::CheckTxVersion::<runtime::Runtime>::new(),
frame_system::CheckGenesis::<runtime::Runtime>::new(),
frame_system::CheckEra::<runtime::Runtime>::from(sp_runtime::generic::Era::mortal(
period,
best_block.saturated_into(),
)),
frame_system::CheckNonce::<runtime::Runtime>::from(nonce),
frame_system::CheckWeight::<runtime::Runtime>::new(),
pallet_transaction_payment::ChargeTransactionPayment::<runtime::Runtime>::from(0),
frame_metadata_hash_extension::CheckMetadataHash::<runtime::Runtime>::new(false),
);
let raw_payload = runtime::SignedPayload::from_raw(
call.clone(),
extra.clone(),
(
(),
runtime::VERSION.spec_version,
runtime::VERSION.transaction_version,
genesis_hash,
best_hash,
(),
(),
(),
None,
),
);
let signature = raw_payload.using_encoded(|e| sender.sign(e));
let signature = MultiSignature::Ecdsa(signature);
let signature = EthereumSignature::from(signature);
runtime::UncheckedExtrinsic::new_signed(
call,
runtime::AccountId::from(sender.public()).into(),
runtime::Signature::from(signature),
extra,
)
}
/// Generates inherent data for the `benchmark overhead` command.
///
/// Note: Should only be used for benchmarking.
pub fn inherent_benchmark_data() -> Result<InherentData> {
let mut inherent_data = InherentData::new();
let d = Duration::from_millis(0);
let timestamp = sp_timestamp::InherentDataProvider::new(d.into());
futures::executor::block_on(timestamp.provide_inherent_data(&mut inherent_data))
.map_err(|e| format!("creating inherent data: {:?}", e))?;
Ok(inherent_data)
}

View file

@ -0,0 +1,180 @@
use datahaven_runtime::{
configs::BABE_GENESIS_EPOCH_CONFIG, AccountId, SessionKeys, Signature, WASM_BINARY,
};
use hex_literal::hex;
use sc_service::ChainType;
use sp_consensus_babe::AuthorityId as BabeId;
use sp_consensus_beefy::ecdsa_crypto::AuthorityId as BeefyId;
use sp_consensus_grandpa::AuthorityId as GrandpaId;
use sp_core::{ecdsa, Pair, Public};
use sp_runtime::traits::{IdentifyAccount, Verify};
/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.
pub type ChainSpec = sc_service::GenericChainSpec;
/// Generate a crypto pair from seed.
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
TPublic::Pair::from_string(&format!("//{}", seed), None)
.expect("static values are valid; qed")
.public()
}
fn session_keys(babe: BabeId, grandpa: GrandpaId, beefy: BeefyId) -> SessionKeys {
SessionKeys {
babe,
grandpa,
beefy,
}
}
type AccountPublic = <Signature as Verify>::Signer;
/// Generate an account ID from seed.
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
where
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}
/// Generate a Babe authority key.
pub fn authority_keys_from_seed(s: &str) -> (AccountId, BabeId, GrandpaId, BeefyId) {
(
get_account_id_from_seed::<ecdsa::Public>(s),
get_from_seed::<BabeId>(s),
get_from_seed::<GrandpaId>(s),
get_from_seed::<BeefyId>(s),
)
}
pub fn development_config() -> Result<ChainSpec, String> {
let mut default_funded_accounts = pre_funded_accounts();
default_funded_accounts.sort();
default_funded_accounts.dedup();
Ok(ChainSpec::builder(
WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?,
None,
)
.with_name("Development")
.with_id("dev")
.with_chain_type(ChainType::Development)
.with_genesis_config_patch(testnet_genesis(
// Initial PoA authorities
vec![authority_keys_from_seed("Alice")],
// Sudo account
alith(),
// Pre-funded accounts
default_funded_accounts.clone(),
true,
))
.build())
}
pub fn local_testnet_config() -> Result<ChainSpec, String> {
Ok(ChainSpec::builder(
WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?,
None,
)
.with_name("Local Testnet")
.with_id("local_testnet")
.with_chain_type(ChainType::Local)
.with_genesis_config_patch(testnet_genesis(
// Initial PoA authorities
vec![
authority_keys_from_seed("Alice"),
authority_keys_from_seed("Bob"),
authority_keys_from_seed("Charlie"),
authority_keys_from_seed("Dave"),
authority_keys_from_seed("Eve"),
authority_keys_from_seed("Ferdie"),
],
// Sudo account
alith(),
// Pre-funded accounts
vec![
alith(),
baltathar(),
charleth(),
dorothy(),
ethan(),
frank(),
],
true,
))
.build())
}
/// Configure initial storage state for FRAME modules.
fn testnet_genesis(
initial_authorities: Vec<(AccountId, BabeId, GrandpaId, BeefyId)>,
root_key: AccountId,
endowed_accounts: Vec<AccountId>,
_enable_println: bool,
) -> serde_json::Value {
serde_json::json!({
"balances": {
// Configure endowed accounts with initial balance of 1 << 60.
"balances": endowed_accounts.iter().cloned().map(|k| (k, 1u64 << 60)).collect::<Vec<_>>(),
},
"babe": {
"epochConfig": Some(BABE_GENESIS_EPOCH_CONFIG),
},
"grandpa": {},
"sudo": {
// Assign network admin rights.
"key": Some(root_key),
},
"validatorSet": {
"initialValidators": initial_authorities.iter().map(|x| x.0.clone()).collect::<Vec<_>>(),
},
"session": {
"keys": initial_authorities.iter().map(|x| {
(x.0.clone(), x.0.clone(), session_keys(x.1.clone(), x.2.clone(), x.3.clone()))
}).collect::<Vec<_>>(),
},
})
}
pub fn alith() -> AccountId {
AccountId::from(hex!("f24FF3a9CF04c71Dbc94D0b566f7A27B94566cac"))
}
pub fn baltathar() -> AccountId {
AccountId::from(hex!("3Cd0A705a2DC65e5b1E1205896BaA2be8A07c6e0"))
}
pub fn charleth() -> AccountId {
AccountId::from(hex!("798d4Ba9baf0064Ec19eB4F0a1a45785ae9D6DFc"))
}
pub fn dorothy() -> AccountId {
AccountId::from(hex!("773539d4Ac0e786233D90A233654ccEE26a613D9"))
}
pub fn ethan() -> AccountId {
AccountId::from(hex!("Ff64d3F6efE2317EE2807d2235B1ac2AA69d9E87"))
}
pub fn frank() -> AccountId {
AccountId::from(hex!("C0F0f4ab324C46e55D02D0033343B4Be8A55532d"))
}
pub fn beacon_relayer() -> AccountId {
AccountId::from(hex!("c46e141b5083721ad5f5056ba1cded69dce4a65f"))
}
/// Get pre-funded accounts
pub fn pre_funded_accounts() -> Vec<AccountId> {
// These addresses are derived from Substrate's canonical mnemonic:
// bottom drive obey lake curtain smoke basket hold race lonely fit walk
vec![
alith(),
baltathar(),
charleth(),
dorothy(),
ethan(),
frank(),
beacon_relayer(),
]
}

46
operator/node/src/cli.rs Normal file
View file

@ -0,0 +1,46 @@
use sc_cli::RunCmd;
#[derive(Debug, clap::Parser)]
pub struct Cli {
#[command(subcommand)]
pub subcommand: Option<Subcommand>,
#[clap(flatten)]
pub run: RunCmd,
}
#[derive(Debug, clap::Subcommand)]
#[allow(clippy::large_enum_variant)]
pub enum Subcommand {
/// Key management cli utilities
#[command(subcommand)]
Key(sc_cli::KeySubcommand),
/// Build a chain specification.
BuildSpec(sc_cli::BuildSpecCmd),
/// Validate blocks.
CheckBlock(sc_cli::CheckBlockCmd),
/// Export blocks.
ExportBlocks(sc_cli::ExportBlocksCmd),
/// Export the state of a given block into a chain spec.
ExportState(sc_cli::ExportStateCmd),
/// Import blocks.
ImportBlocks(sc_cli::ImportBlocksCmd),
/// Remove the whole chain.
PurgeChain(sc_cli::PurgeChainCmd),
/// Revert the chain to a previous state.
Revert(sc_cli::RevertCmd),
/// Sub-commands concerned with benchmarking.
#[command(subcommand)]
Benchmark(frame_benchmarking_cli::BenchmarkCmd),
/// Db meta columns information.
ChainInfo(sc_cli::ChainInfoCmd),
}

View file

@ -0,0 +1,221 @@
use std::sync::Arc;
use crate::{
benchmarking::{inherent_benchmark_data, RemarkBuilder, TransferKeepAliveBuilder},
chain_spec::{self, alith},
cli::{Cli, Subcommand},
service,
};
use datahaven_runtime::{Block, EXISTENTIAL_DEPOSIT};
use frame_benchmarking_cli::{BenchmarkCmd, ExtrinsicFactory, SUBSTRATE_REFERENCE_HARDWARE};
use sc_cli::SubstrateCli;
use sc_service::PartialComponents;
impl SubstrateCli for Cli {
fn impl_name() -> String {
"Substrate Node".into()
}
fn impl_version() -> String {
env!("SUBSTRATE_CLI_IMPL_VERSION").into()
}
fn description() -> String {
env!("CARGO_PKG_DESCRIPTION").into()
}
fn author() -> String {
env!("CARGO_PKG_AUTHORS").into()
}
fn support_url() -> String {
"support.anonymous.an".into()
}
fn copyright_start_year() -> i32 {
2017
}
fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
Ok(match id {
"dev" => Box::new(chain_spec::development_config()?),
"" | "datahaven-local" => Box::new(chain_spec::local_testnet_config()?),
path => Box::new(chain_spec::ChainSpec::from_json_file(
std::path::PathBuf::from(path),
)?),
})
}
}
/// Parse and run command line arguments
pub fn run() -> sc_cli::Result<()> {
let cli = Cli::from_args();
match &cli.subcommand {
Some(Subcommand::Key(cmd)) => cmd.run(&cli),
Some(Subcommand::BuildSpec(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run(config.chain_spec, config.network))
}
Some(Subcommand::CheckBlock(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents {
client,
task_manager,
import_queue,
..
} = service::new_partial(&config)?;
Ok((cmd.run(client, import_queue), task_manager))
})
}
Some(Subcommand::ExportBlocks(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents {
client,
task_manager,
..
} = service::new_partial(&config)?;
Ok((cmd.run(client, config.database), task_manager))
})
}
Some(Subcommand::ExportState(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents {
client,
task_manager,
..
} = service::new_partial(&config)?;
Ok((cmd.run(client, config.chain_spec), task_manager))
})
}
Some(Subcommand::ImportBlocks(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents {
client,
task_manager,
import_queue,
..
} = service::new_partial(&config)?;
Ok((cmd.run(client, import_queue), task_manager))
})
}
Some(Subcommand::PurgeChain(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run(config.database))
}
Some(Subcommand::Revert(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents {
client,
task_manager,
backend,
..
} = service::new_partial(&config)?;
let aux_revert = Box::new(|client: Arc<service::FullClient>, backend, blocks| {
sc_consensus_babe::revert(client.clone(), backend, blocks)?;
sc_consensus_grandpa::revert(client, blocks)?;
Ok(())
});
Ok((cmd.run(client, backend, Some(aux_revert)), task_manager))
})
}
Some(Subcommand::Benchmark(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| {
// This switch needs to be in the client, since the client decides
// which sub-commands it wants to support.
match cmd {
BenchmarkCmd::Pallet(cmd) => {
if !cfg!(feature = "runtime-benchmarks") {
return Err(
"Runtime benchmarking wasn't enabled when building the node. \
You can enable it with `--features runtime-benchmarks`."
.into(),
);
}
cmd.run_with_spec::<sp_runtime::traits::HashingFor<Block>, ()>(Some(
config.chain_spec,
))
}
BenchmarkCmd::Block(cmd) => {
let PartialComponents { client, .. } = service::new_partial(&config)?;
cmd.run(client)
}
#[cfg(not(feature = "runtime-benchmarks"))]
BenchmarkCmd::Storage(_) => Err(
"Storage benchmarking can be enabled with `--features runtime-benchmarks`."
.into(),
),
#[cfg(feature = "runtime-benchmarks")]
BenchmarkCmd::Storage(cmd) => {
let PartialComponents {
client, backend, ..
} = service::new_partial(&config)?;
let db = backend.expose_db();
let storage = backend.expose_storage();
cmd.run(config, client, db, storage)
}
BenchmarkCmd::Overhead(cmd) => {
let PartialComponents { client, .. } = service::new_partial(&config)?;
let ext_builder = RemarkBuilder::new(client.clone());
cmd.run(
config,
client,
inherent_benchmark_data()?,
Vec::new(),
&ext_builder,
)
}
BenchmarkCmd::Extrinsic(cmd) => {
let PartialComponents { client, .. } = service::new_partial(&config)?;
// Register the *Remark* and *TKA* builders.
let ext_factory = ExtrinsicFactory(vec![
Box::new(RemarkBuilder::new(client.clone())),
Box::new(TransferKeepAliveBuilder::new(
client.clone(),
alith(),
EXISTENTIAL_DEPOSIT,
)),
]);
cmd.run(client, inherent_benchmark_data()?, Vec::new(), &ext_factory)
}
BenchmarkCmd::Machine(cmd) => {
cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone())
}
}
})
}
Some(Subcommand::ChainInfo(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run::<Block>(&config))
}
None => {
let runner = cli.create_runner(&cli.run)?;
runner.run_node_until_exit(|config| async move {
match config.network.network_backend {
sc_network::config::NetworkBackendType::Libp2p => service::new_full::<
sc_network::NetworkWorker<
datahaven_runtime::opaque::Block,
<datahaven_runtime::opaque::Block as sp_runtime::traits::Block>::Hash,
>,
>(config)
.map_err(sc_cli::Error::Service),
sc_network::config::NetworkBackendType::Litep2p => {
service::new_full::<sc_network::Litep2pNetworkBackend>(config)
.map_err(sc_cli::Error::Service)
}
}
})
}
}
}

13
operator/node/src/main.rs Normal file
View file

@ -0,0 +1,13 @@
//! Substrate Node Template CLI library.
#![warn(missing_docs)]
mod benchmarking;
mod chain_spec;
mod cli;
mod command;
mod rpc;
mod service;
fn main() -> sc_cli::Result<()> {
command::run()
}

106
operator/node/src/rpc.rs Normal file
View file

@ -0,0 +1,106 @@
//! A collection of node-specific RPC methods.
//! Substrate provides the `sc-rpc` crate, which defines the core RPC layer
//! used by Substrate nodes. This file extends those RPC definitions with
//! capabilities that are specific to this project's runtime configuration.
#![warn(missing_docs)]
use std::sync::Arc;
use datahaven_runtime::{opaque::Block, AccountId, Balance, BlockNumber, Nonce};
use jsonrpsee::RpcModule;
use sc_consensus_beefy::communication::notification::{
BeefyBestBlockStream, BeefyVersionedFinalityProofStream,
};
use sc_transaction_pool_api::TransactionPool;
use sp_api::ProvideRuntimeApi;
use sp_block_builder::BlockBuilder;
use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
use sp_consensus_beefy::AuthorityIdBound;
/// Dependencies for BEEFY
pub struct BeefyDeps<AuthorityId: AuthorityIdBound> {
/// Receives notifications about finality proof events from BEEFY.
pub beefy_finality_proof_stream: BeefyVersionedFinalityProofStream<Block, AuthorityId>,
/// Receives notifications about best block events from BEEFY.
pub beefy_best_block_stream: BeefyBestBlockStream<Block>,
/// Executor to drive the subscription manager in the BEEFY RPC handler.
pub subscription_executor: sc_rpc::SubscriptionTaskExecutor,
}
/// Full client dependencies.
pub struct FullDeps<C, P, B, AuthorityId: AuthorityIdBound> {
/// The client instance to use.
pub client: Arc<C>,
/// Transaction pool instance.
pub pool: Arc<P>,
/// BEEFY dependencies.
pub beefy: BeefyDeps<AuthorityId>,
/// Backend used by the node.
pub backend: Arc<B>,
}
/// Instantiate all full RPC extensions.
pub fn create_full<C, P, B, AuthorityId>(
deps: FullDeps<C, P, B, AuthorityId>,
) -> Result<RpcModule<()>, Box<dyn std::error::Error + Send + Sync>>
where
C: ProvideRuntimeApi<Block>,
C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,
C: Send + Sync + 'static,
C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Nonce>,
C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
C::Api: BlockBuilder<Block>,
C::Api: mmr_rpc::MmrRuntimeApi<Block, <Block as sp_runtime::traits::Block>::Hash, BlockNumber>,
P: TransactionPool + 'static,
B: sc_client_api::Backend<Block> + Send + Sync + 'static,
B::State: sc_client_api::StateBackend<sp_runtime::traits::HashingFor<Block>>,
AuthorityId: AuthorityIdBound,
{
use mmr_rpc::{Mmr, MmrApiServer};
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
use sc_consensus_beefy_rpc::{Beefy, BeefyApiServer};
use substrate_frame_rpc_system::{System, SystemApiServer};
let mut module = RpcModule::new(());
let FullDeps {
client,
pool,
beefy,
backend,
} = deps;
module.merge(System::new(client.clone(), pool).into_rpc())?;
module.merge(TransactionPayment::new(client.clone()).into_rpc())?;
module.merge(
Beefy::<Block, AuthorityId>::new(
beefy.beefy_finality_proof_stream,
beefy.beefy_best_block_stream,
beefy.subscription_executor,
)?
.into_rpc(),
)?;
module.merge(
Mmr::new(
client,
backend
.offchain_storage()
.ok_or("Backend doesn't provide the required offchain storage")?,
)
.into_rpc(),
)?;
// Extend this RPC with a custom API by using the following syntax.
// `YourRpcStruct` should have a reference to a client, which is needed
// to call into the runtime.
// `module.merge(YourRpcTrait::into_rpc(YourRpcStruct::new(ReferenceToClient, ...)))?;`
// You probably want to enable the `rpc v2 chainSpec` API as well
//
// let chain_name = chain_spec.name().to_string();
// let genesis_hash = client.block_hash(0).ok().flatten().expect("Genesis block exists; qed");
// let properties = chain_spec.properties();
// module.merge(ChainSpec::new(chain_name, genesis_hash, properties).into_rpc())?;
Ok(module)
}

View file

@ -0,0 +1,459 @@
//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.
use crate::rpc::BeefyDeps;
use datahaven_runtime::{self, apis::RuntimeApi, opaque::Block};
use futures::FutureExt;
use sc_client_api::{Backend, BlockBackend};
use sc_consensus_babe::ImportQueueParams;
use sc_consensus_grandpa::SharedVoterState;
use sc_service::{error::Error as ServiceError, Configuration, TaskManager, WarpSyncConfig};
use sc_telemetry::{Telemetry, TelemetryWorker};
use sc_transaction_pool_api::OffchainTransactionPoolFactory;
use sp_consensus_beefy::ecdsa_crypto;
use std::{sync::Arc, time::Duration};
pub(crate) type FullClient = sc_service::TFullClient<
Block,
RuntimeApi,
sc_executor::WasmExecutor<sp_io::SubstrateHostFunctions>,
>;
type FullBackend = sc_service::TFullBackend<Block>;
type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;
type FullGrandpaBlockImport =
sc_consensus_grandpa::GrandpaBlockImport<FullBackend, Block, FullClient, FullSelectChain>;
type FullBeefyBlockImport<InnerBlockImport, AuthorityId> =
sc_consensus_beefy::import::BeefyBlockImport<
Block,
FullBackend,
FullClient,
InnerBlockImport,
AuthorityId,
>;
/// The minimum period of blocks on which justifications will be
/// imported and generated.
const GRANDPA_JUSTIFICATION_PERIOD: u32 = 512;
pub type Service = sc_service::PartialComponents<
FullClient,
FullBackend,
FullSelectChain,
sc_consensus::DefaultImportQueue<Block>,
sc_transaction_pool::FullPool<Block, FullClient>,
(
sc_consensus_babe::BabeBlockImport<
Block,
FullClient,
FullBeefyBlockImport<FullGrandpaBlockImport, ecdsa_crypto::AuthorityId>,
>,
sc_consensus_grandpa::LinkHalf<Block, FullClient, FullSelectChain>,
sc_consensus_babe::BabeLink<Block>,
sc_consensus_beefy::BeefyVoterLinks<Block, ecdsa_crypto::AuthorityId>,
sc_consensus_beefy::BeefyRPCLinks<Block, ecdsa_crypto::AuthorityId>,
Option<Telemetry>,
),
>;
pub fn new_partial(config: &Configuration) -> Result<Service, ServiceError> {
let telemetry = config
.telemetry_endpoints
.clone()
.filter(|x| !x.is_empty())
.map(|endpoints| -> Result<_, sc_telemetry::Error> {
let worker = TelemetryWorker::new(16)?;
let telemetry = worker.handle().new_telemetry(endpoints);
Ok((worker, telemetry))
})
.transpose()?;
let executor = sc_service::new_wasm_executor::<sp_io::SubstrateHostFunctions>(&config.executor);
let (client, backend, keystore_container, task_manager) =
sc_service::new_full_parts::<Block, RuntimeApi, _>(
config,
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
executor,
)?;
let client = Arc::new(client);
let telemetry = telemetry.map(|(worker, telemetry)| {
task_manager
.spawn_handle()
.spawn("telemetry", None, worker.run());
telemetry
});
let select_chain = sc_consensus::LongestChain::new(backend.clone());
let transaction_pool = sc_transaction_pool::BasicPool::new_full(
config.transaction_pool.clone(),
config.role.is_authority().into(),
config.prometheus_registry(),
task_manager.spawn_essential_handle(),
client.clone(),
);
let (grandpa_block_import, grandpa_link) = sc_consensus_grandpa::block_import(
client.clone(),
GRANDPA_JUSTIFICATION_PERIOD,
&client,
select_chain.clone(),
telemetry.as_ref().map(|x| x.handle()),
)?;
let (beefy_block_import, beefy_voter_links, beefy_rpc_links) =
sc_consensus_beefy::beefy_block_import_and_links(
grandpa_block_import.clone(),
backend.clone(),
client.clone(),
config.prometheus_registry().cloned(),
);
let (block_import, babe_link) = sc_consensus_babe::block_import(
sc_consensus_babe::configuration(&*client)?,
beefy_block_import,
client.clone(),
)?;
let slot_duration = babe_link.config().slot_duration();
let (import_queue, babe_worker_handle) = sc_consensus_babe::import_queue(ImportQueueParams {
link: babe_link.clone(),
block_import: block_import.clone(),
justification_import: Some(Box::new(grandpa_block_import.clone())),
client: client.clone(),
select_chain: select_chain.clone(),
create_inherent_data_providers: move |_, ()| async move {
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
let slot =
sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
*timestamp,
slot_duration,
);
Ok((slot, timestamp))
},
spawner: &task_manager.spawn_essential_handle(),
registry: config.prometheus_registry(),
telemetry: telemetry.as_ref().map(|x| x.handle()),
offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(transaction_pool.clone()),
})?;
// TODO Wire up to RPC
std::mem::forget(babe_worker_handle);
Ok(sc_service::PartialComponents {
client,
backend,
task_manager,
import_queue,
keystore_container,
select_chain,
transaction_pool,
other: (
block_import,
grandpa_link,
babe_link,
beefy_voter_links,
beefy_rpc_links,
telemetry,
),
})
}
/// Builds a new service for a full client.
pub fn new_full<
N: sc_network::NetworkBackend<Block, <Block as sp_runtime::traits::Block>::Hash>,
>(
config: Configuration,
) -> Result<TaskManager, ServiceError> {
let sc_service::PartialComponents {
client,
backend,
mut task_manager,
import_queue,
keystore_container,
select_chain,
transaction_pool,
other:
(block_import, grandpa_link, babe_link, beefy_voter_links, beefy_rpc_links, mut telemetry),
} = new_partial(&config)?;
let mut net_config = sc_network::config::FullNetworkConfiguration::<
Block,
<Block as sp_runtime::traits::Block>::Hash,
N,
>::new(&config.network, config.prometheus_registry().cloned());
let metrics = N::register_notification_metrics(config.prometheus_registry());
let peer_store_handle = net_config.peer_store_handle();
let genesis_hash = client
.block_hash(0)
.ok()
.flatten()
.expect("Genesis block exists; qed");
let grandpa_protocol_name =
sc_consensus_grandpa::protocol_standard_name(&genesis_hash, &config.chain_spec);
let (grandpa_protocol_config, grandpa_notification_service) =
sc_consensus_grandpa::grandpa_peers_set_config::<_, N>(
grandpa_protocol_name.clone(),
metrics.clone(),
Arc::clone(&peer_store_handle),
);
net_config.add_notification_protocol(grandpa_protocol_config);
let beefy_gossip_proto_name =
sc_consensus_beefy::gossip_protocol_name(&genesis_hash, config.chain_spec.fork_id());
let (beefy_on_demand_justifications_handler, beefy_req_resp_cfg) =
sc_consensus_beefy::communication::request_response::BeefyJustifsRequestHandler::new::<_, N>(
&genesis_hash,
config.chain_spec.fork_id(),
client.clone(),
config.prometheus_registry().cloned(),
);
let enable_beefy = true;
let beefy_notification_service = match enable_beefy {
false => None,
true => {
let (beefy_notification_config, beefy_notification_service) =
sc_consensus_beefy::communication::beefy_peers_set_config::<_, N>(
beefy_gossip_proto_name.clone(),
metrics.clone(),
Arc::clone(&peer_store_handle),
);
net_config.add_notification_protocol(beefy_notification_config);
net_config.add_request_response_protocol(beefy_req_resp_cfg);
Some(beefy_notification_service)
}
};
let warp_sync = Arc::new(sc_consensus_grandpa::warp_proof::NetworkProvider::new(
backend.clone(),
grandpa_link.shared_authority_set().clone(),
Vec::default(),
));
let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =
sc_service::build_network(sc_service::BuildNetworkParams {
config: &config,
net_config,
client: client.clone(),
transaction_pool: transaction_pool.clone(),
spawn_handle: task_manager.spawn_handle(),
import_queue,
block_announce_validator_builder: None,
warp_sync_config: Some(WarpSyncConfig::WithProvider(warp_sync)),
block_relay: None,
metrics,
})?;
if config.offchain_worker.enabled {
task_manager.spawn_handle().spawn(
"offchain-workers-runner",
"offchain-worker",
sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions {
runtime_api_provider: client.clone(),
is_validator: config.role.is_authority(),
keystore: Some(keystore_container.keystore()),
offchain_db: backend.offchain_storage(),
transaction_pool: Some(OffchainTransactionPoolFactory::new(
transaction_pool.clone(),
)),
network_provider: Arc::new(network.clone()),
enable_http_requests: true,
custom_extensions: |_| vec![],
})
.run(client.clone(), task_manager.spawn_handle())
.boxed(),
);
}
let role = config.role;
let force_authoring = config.force_authoring;
let backoff_authoring_blocks: Option<()> = None;
let name = config.network.node_name.clone();
let enable_grandpa = !config.disable_grandpa;
let prometheus_registry = config.prometheus_registry().cloned();
let rpc_extensions_builder = {
let client = client.clone();
let pool = transaction_pool.clone();
let backend = backend.clone();
Box::new(move |subscription_executor| {
let deps = crate::rpc::FullDeps {
client: client.clone(),
pool: pool.clone(),
beefy: BeefyDeps::<ecdsa_crypto::AuthorityId> {
beefy_finality_proof_stream: beefy_rpc_links.from_voter_justif_stream.clone(),
beefy_best_block_stream: beefy_rpc_links.from_voter_best_beefy_stream.clone(),
subscription_executor,
},
backend: backend.clone(),
};
crate::rpc::create_full(deps).map_err(Into::into)
})
};
let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
network: Arc::new(network.clone()),
client: client.clone(),
keystore: keystore_container.keystore(),
task_manager: &mut task_manager,
transaction_pool: transaction_pool.clone(),
rpc_builder: rpc_extensions_builder,
backend: backend.clone(),
system_rpc_tx,
tx_handler_controller,
sync_service: sync_service.clone(),
config,
telemetry: telemetry.as_mut(),
})?;
if role.is_authority() {
let proposer_factory = sc_basic_authorship::ProposerFactory::new(
task_manager.spawn_handle(),
client.clone(),
transaction_pool.clone(),
prometheus_registry.as_ref(),
telemetry.as_ref().map(|x| x.handle()),
);
let slot_duration = babe_link.config().slot_duration();
let babe_config = sc_consensus_babe::BabeParams {
keystore: keystore_container.keystore(),
client: client.clone(),
select_chain,
env: proposer_factory,
block_import,
sync_oracle: sync_service.clone(),
justification_sync_link: sync_service.clone(),
create_inherent_data_providers: move |_, ()| async move {
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
let slot =
sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
*timestamp,
slot_duration,
);
Ok((slot, timestamp))
},
force_authoring,
backoff_authoring_blocks,
babe_link,
block_proposal_slot_portion: sc_consensus_babe::SlotProportion::new(0.5),
max_block_proposal_slot_portion: None,
telemetry: telemetry.as_ref().map(|x| x.handle()),
};
let babe = sc_consensus_babe::start_babe(babe_config)?;
task_manager.spawn_essential_handle().spawn_blocking(
"babe-proposer",
Some("block-authoring"),
babe,
);
}
if enable_grandpa {
// if the node isn't actively participating in consensus then it doesn't
// need a keystore, regardless of which protocol we use below.
let keystore = if role.is_authority() {
Some(keystore_container.keystore())
} else {
None
};
let grandpa_config = sc_consensus_grandpa::Config {
// FIXME #1578 make this available through chainspec
gossip_duration: Duration::from_millis(333),
justification_generation_period: GRANDPA_JUSTIFICATION_PERIOD,
name: Some(name),
observer_enabled: false,
keystore,
local_role: role,
telemetry: telemetry.as_ref().map(|x| x.handle()),
protocol_name: grandpa_protocol_name,
};
// start the full GRANDPA voter
// NOTE: non-authorities could run the GRANDPA observer protocol, but at
// this point the full voter should provide better guarantees of block
// and vote data availability than the observer. The observer has not
// been tested extensively yet and having most nodes in a network run it
// could lead to finality stalls.
let grandpa_config = sc_consensus_grandpa::GrandpaParams {
config: grandpa_config,
link: grandpa_link,
network: network.clone(),
sync: Arc::new(sync_service.clone()),
notification_service: grandpa_notification_service,
voting_rule: sc_consensus_grandpa::VotingRulesBuilder::default().build(),
prometheus_registry: prometheus_registry.clone(),
shared_voter_state: SharedVoterState::empty(),
telemetry: telemetry.as_ref().map(|x| x.handle()),
offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(transaction_pool),
};
// the GRANDPA voter task is considered infallible, i.e.
// if it fails we take down the service with it.
task_manager.spawn_essential_handle().spawn_blocking(
"grandpa-voter",
None,
sc_consensus_grandpa::run_grandpa_voter(grandpa_config)?,
);
}
// if the node isn't actively participating in consensus then it doesn't
// need a keystore, regardless of which protocol we use below.
let keystore_opt = if role.is_authority() {
Some(keystore_container.keystore())
} else {
None
};
// beefy is enabled if its notification service exists
if let Some(notification_service) = beefy_notification_service {
let justifications_protocol_name = beefy_on_demand_justifications_handler.protocol_name();
let network_params = sc_consensus_beefy::BeefyNetworkParams {
network: Arc::new(network.clone()),
sync: sync_service.clone(),
gossip_protocol_name: beefy_gossip_proto_name,
justifications_protocol_name,
notification_service,
_phantom: core::marker::PhantomData::<Block>,
};
let payload_provider = sp_consensus_beefy::mmr::MmrRootProvider::new(client.clone());
let beefy_params = sc_consensus_beefy::BeefyParams {
client: client.clone(),
backend: backend.clone(),
payload_provider,
runtime: client.clone(),
key_store: keystore_opt.clone(),
network_params,
min_block_delta: 8,
prometheus_registry: prometheus_registry.clone(),
links: beefy_voter_links,
on_demand_justifications_handler: beefy_on_demand_justifications_handler,
is_authority: role.is_authority(),
};
let gadget = sc_consensus_beefy::start_beefy_gadget::<
_,
_,
_,
_,
_,
_,
_,
ecdsa_crypto::AuthorityId,
>(beefy_params);
// BEEFY is part of consensus, if it fails we'll bring the node down with it to make sure it
// is noticed.
task_manager
.spawn_essential_handle()
.spawn_blocking("beefy-gadget", None, gadget);
}
network_starter.start_network();
Ok(task_manager)
}

View file

@ -0,0 +1,44 @@
[package]
name = 'pallet-validator-set'
version = '1.0.0'
authors = ['Gautam Dhameja <quasijatt@outlook.com>', 'Parity Technologies <admin@parity.io>']
edition = '2021'
license = 'Apache-2.0'
[dependencies]
codec = { features = [
"derive",
], workspace = true }
scale-info = { features = [
"derive",
"serde",
], workspace = true }
sp-core.workspace = true
sp-io.workspace = true
sp-runtime.workspace = true
sp-staking.workspace = true
log.workspace = true
frame-support.workspace = true
frame-benchmarking.workspace = true
frame-benchmarking.optional = true
frame-system.workspace = true
pallet-session = { workspace = true, features = ['historical'] }
[features]
default = ['std']
runtime-benchmarks = ['frame-benchmarking/runtime-benchmarks']
std = [
'codec/std',
'frame-benchmarking/std',
'frame-support/std',
'frame-system/std',
'scale-info/std',
'sp-core/std',
'sp-io/std',
'sp-runtime/std',
'pallet-session/std',
]
try-runtime = ['frame-support/try-runtime']

View file

@ -0,0 +1,196 @@
# Substrate Validator Set Pallet
A [Substrate](https://github.com/paritytech/substrate/) pallet to add/remove authorities/validators in PoA networks.
**Note: Current master is compatible with Substrate [polkadot-v1.0.0](https://github.com/paritytech/substrate/tree/polkadot-v1.0.0) branch. For older versions, please see releases/tags.**
## Setup with Substrate Node Template
### Dependencies - runtime/cargo.toml
* Add the module's dependency in the `Cargo.toml` of your runtime directory. Make sure to enter the correct path or git url of the pallet as per your setup.
* Make sure that you also have the Substrate [session pallet](https://github.com/paritytech/substrate/tree/master/frame/session) as part of your runtime. This is because the validator-set pallet is dependent on the session pallet.
```toml
[dependencies.validator-set]
default-features = false
package = 'substrate-validator-set'
git = 'https://github.com/gautamdhameja/substrate-validator-set.git'
version = '0.9.42'
[dependencies.pallet-session]
default-features = false
git = 'https://github.com/paritytech/substrate.git'
branch = 'polkadot-v1.0.0'
```
```toml
std = [
...
'validator-set/std',
'pallet-session/std',
]
```
### Pallet Initialization - runtime/src/lib.rs
* Import `OpaqueKeys` in your `runtime/src/lib.rs`.
```rust
use sp_runtime::traits::{
AccountIdLookup, BlakeTwo256, Block as BlockT, Verify, IdentifyAccount, NumberFor, OpaqueKeys,
};
```
* Also in `runtime/src/lib.rs` import the `EnsureRoot` trait. This would change if you want to configure a custom origin (see below).
```rust
use frame_system::EnsureRoot;
```
* Declare the pallet in your `runtime/src/lib.rs`. The pallet supports configurable origin and you can either set it to use one of the governance pallets (Collective, Democracy, etc.), or just use root as shown below. But **do not use a normal origin here** because the addition and removal of validators should be done using elevated privileges.
```rust
parameter_types! {
pub const MinAuthorities: u32 = 2;
}
impl validator_set::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type AddRemoveOrigin = EnsureRoot<AccountId>;
type MinAuthorities = MinAuthorities;
type WeightInfo = validator_set::weights::SubstrateWeight<Runtime>;
}
```
* Also, declare the session pallet in your `runtime/src/lib.rs`. Some of the type configuration of session pallet would depend on the ValidatorSet pallet as shown below.
```rust
parameter_types! {
pub const Period: u32 = 2 * MINUTES;
pub const Offset: u32 = 0;
}
impl pallet_session::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type ValidatorId = <Self as frame_system::Config>::AccountId;
type ValidatorIdOf = validator_set::ValidatorOf<Self>;
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
type SessionManager = ValidatorSet;
type SessionHandler = <opaque::SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type Keys = opaque::SessionKeys;
type WeightInfo = ();
}
```
* Add `validator_set`, and `session` pallets in `construct_runtime` macro. **Make sure to add them before `Aura` and `Grandpa` pallets and after `Balances`. Also make sure that the `validator_set` pallet is added _before_ the `session` pallet, because it provides the initial validators at genesis, and must initialize first.**
```rust
construct_runtime!(
pub enum Runtime where
Block = Block,
NodeBlock = opaque::Block,
UncheckedExtrinsic = UncheckedExtrinsic
{
...
Balances: pallet_balances,
ValidatorSet: validator_set,
Session: pallet_session,
Aura: pallet_aura,
Grandpa: pallet_grandpa,
...
...
}
);
```
### Genesis config - chain_spec.rs
* Import `opaque::SessionKeys, ValidatorSetConfig, SessionConfig` from the runtime in `node/src/chain_spec.rs`.
```rust
use node_template_runtime::{
AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig,
SudoConfig, SystemConfig, WASM_BINARY, Signature,
opaque::SessionKeys, ValidatorSetConfig, SessionConfig
};
```
* And then in `node/src/chain_spec.rs` update the key generation functions.
```rust
fn session_keys(aura: AuraId, grandpa: GrandpaId) -> SessionKeys {
SessionKeys { aura, grandpa }
}
pub fn authority_keys_from_seed(s: &str) -> (AccountId, AuraId, GrandpaId) {
(
get_account_id_from_seed::<sr25519::Public>(s),
get_from_seed::<AuraId>(s),
get_from_seed::<GrandpaId>(s)
)
}
```
* Add genesis config in the `chain_spec.rs` file for `session` and `validatorset` pallets, and update it for `Aura` and `Grandpa` pallets. Because the validators are provided by the `session` pallet, we do not initialize them explicitly for `Aura` and `Grandpa` pallets. Order is important, notice that `pallet_session` is declared after `pallet_balances` since it depends on it (session accounts should have some balance).
```rust
fn testnet_genesis(
wasm_binary: &[u8],
initial_authorities: Vec<(AccountId, AuraId, GrandpaId)>,
root_key: AccountId,
endowed_accounts: Vec<AccountId>,
_enable_println: bool,
) -> GenesisConfig {
GenesisConfig {
system: SystemConfig {
// Add Wasm runtime to storage.
code: wasm_binary.to_vec(),
},
balances: BalancesConfig {
// Configure endowed accounts with initial balance of 1 << 60.
balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(),
},
validator_set: ValidatorSetConfig {
initial_validators: initial_authorities.iter().map(|x| x.0.clone()).collect::<Vec<_>>(),
},
session: SessionConfig {
keys: initial_authorities.iter().map(|x| {
(x.0.clone(), x.0.clone(), session_keys(x.1.clone(), x.2.clone()))
}).collect::<Vec<_>>(),
},
aura: AuraConfig {
authorities: vec![],
},
grandpa: GrandpaConfig {
authorities: vec![],
},
sudo: SudoConfig {
// Assign network admin rights.
key: Some(root_key),
},
transaction_payment: Default::default(),
}
}
```
## Run
Once you have set up the pallet in your node/node-template and everything compiles, follow the steps in [docs/local-network-setup.md](./docs/local-network-setup.md) to run a local network and add validators.
Also, watch this video to see this in action - https://www.youtube.com/watch?v=lIYxE-tOAdw.
## Extensions
### Council-based Governance
Instead of using `sudo`, for a council-based governance, use the pallet with the `Collective` pallet. Follow the steps in [docs/council-integration.md](./docs/council-integration.md).
### Auto-removal Of Offline Validators
When a validator goes offline, it skips its block production slot and that causes increased block times. Sometimes, we want to remove these offline validators so that the block time can recover to normal. The `ImOnline` pallet, when added to a runtime, can report offline validators. The `ValidatorSet` pallet implements the required types to integrate with `ImOnline` pallet for automatic removal of offline validators. To use the `ValidatorSet` pallet with the `ImOnline` pallet, follow the steps in [docs/im-online-integration.md](./docs/im-online-integration.md).
## Disclaimer
This code is **not audited** for production use cases. You can expect security vulnerabilities. Do not use it without proper testing and audit in a production applications.

View file

@ -0,0 +1,67 @@
// Copyright (C) Gautam Dhameja.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![cfg(feature = "runtime-benchmarks")]
use super::{Pallet as ValidatorSet, *};
use frame_benchmarking::v2::{account, benchmarks, impl_benchmark_test_suite, vec, BenchmarkError};
use frame_support::traits::EnsureOrigin;
use frame_system::{EventRecord, Pallet as System};
const SEED: u32 = 0;
fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {
let events = System::<T>::events();
let system_event: <T as frame_system::Config>::RuntimeEvent = generic_event.into();
let EventRecord { event, .. } = &events[events.len() - 1];
assert_eq!(event, &system_event);
}
#[benchmarks]
mod benchmarks {
use super::*;
#[benchmark]
fn add_validator() -> Result<(), BenchmarkError> {
let origin = T::AddRemoveOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Stop("unable to compute origin"))?;
let who: T::AccountId = account("validator", 0, SEED);
#[extrinsic_call]
_(origin as T::RuntimeOrigin, who.clone());
assert_last_event::<T>(Event::ValidatorAdded(who).into());
Ok(())
}
#[benchmark]
fn remove_validator() -> Result<(), BenchmarkError> {
let origin = T::AddRemoveOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Stop("unable to compute origin"))?;
let who: T::AccountId = account("validator", 0, SEED);
ValidatorSet::<T>::add_validator(origin.clone(), who.clone())
.map_err(|_| BenchmarkError::Stop("unable to add validator"))?;
#[extrinsic_call]
_(origin as T::RuntimeOrigin, who.clone());
assert_last_event::<T>(Event::ValidatorRemoved(who).into());
Ok(())
}
impl_benchmark_test_suite!(ValidatorSet, crate::mock::new_test_ext(), crate::mock::Test);
}

View file

@ -0,0 +1,405 @@
// Copyright (C) Gautam Dhameja.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Validator set pallet. Maintains a set of validators which can be added to or removed from by a
//! privileged origin.
//!
//! Provides a [`SessionManager`] implementation which returns the current validator set from
//! `new_session`. Also provides an [`OnOffenceHandler`] implementation which removes the offending
//! validators from the set (if they would be slashed) and temporarily disables them according to
//! the [`DisableStrategy`].
//!
//! Adding a validator to the set increments the validator account's provider reference count. This
//! allows the validator to set their session keys with
//! [`set_keys`](pallet_session::Pallet::set_keys). When a validator is removed, either explicitly
//! via [`remove_validator`](Pallet::remove_validator) or implicitly due to an offence, the
//! validator's session keys are automatically purged and the validator account's provider
//! reference count is decremented again. Note that failure to decrement the provider reference
//! count does not cause removal to fail; the provider reference is just leaked.
//!
//! This pallet directly depends on [`pallet_session`] and [`pallet_session::historical`].
//! [`pallet_session::Config::ValidatorId`] must be [`AccountId`](frame_system::Config::AccountId)
//! and [`pallet_session::Config::ValidatorIdOf`] must be [`ConvertInto`].
#![cfg_attr(not(feature = "std"), no_std)]
mod benchmarking;
mod mock;
mod tests;
pub mod weights;
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{
dispatch::RawOrigin,
ensure,
pallet_prelude::{DispatchResult, Weight},
traits::Get,
DefaultNoBound,
};
use frame_system::pallet_prelude::BlockNumberFor;
pub use pallet::*;
use pallet_session::SessionManager;
use sp_runtime::{
traits::{ConvertInto, Zero},
transaction_validity::{InvalidTransaction, TransactionValidityError},
Perbill, Saturating, Vec,
};
use sp_staking::{
offence::{OffenceDetails, OnOffenceHandler},
SessionIndex,
};
pub use weights::WeightInfo;
const LOG_TARGET: &str = "runtime::validator-set";
/// Per-validator data stored by this pallet.
#[derive(Encode, Decode, scale_info::TypeInfo, MaxEncodedLen)]
struct Validator<BlockNumber> {
/// The validator may not set its session keys before this block.
min_set_keys_block: BlockNumber,
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::config]
pub trait Config:
frame_system::Config
+ pallet_session::Config<
ValidatorId = <Self as frame_system::Config>::AccountId,
ValidatorIdOf = ConvertInto,
>
{
/// The overarching event type.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
/// Origin for adding or removing a validator.
type AddRemoveOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// Maximum number of validators.
#[pallet::constant]
type MaxAuthorities: Get<u32>;
/// Minimum number of blocks between [`set_keys`](pallet_session::Pallet::set_keys) calls
/// by a validator.
#[pallet::constant]
type SetKeysCooldownBlocks: Get<BlockNumberFor<Self>>;
}
#[pallet::pallet]
pub struct Pallet<T>(_);
/// Validator set. Changes to this will take effect in the session after next.
#[pallet::storage]
pub(super) type Validators<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, Validator<BlockNumberFor<T>>, OptionQuery>;
/// Number of validators in `Validators`.
#[pallet::storage]
pub(super) type NumValidators<T: Config> = StorageValue<_, u32, ValueQuery>;
/// Validators that should be disabled in the next session.
///
/// Validator removal takes effect in the session after next. Validator disabling takes effect
/// until the end of the session. We extend disables to cover the next session as well (by
/// adding validators here when we disable them) so that when a validator is both disabled and
/// removed in response to an offence, there isn't a gap where it is actually present and
/// enabled.
#[pallet::storage]
pub(super) type NextDisabledValidators<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, (), OptionQuery>;
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// New validator added. Effective in session after next.
ValidatorAdded(T::AccountId),
/// Validator removed. Effective in session after next.
ValidatorRemoved(T::AccountId),
}
#[pallet::error]
pub enum Error<T> {
/// Validator is already in the validator set.
Duplicate,
/// Validator is not in the validator set.
NotAValidator,
/// Adding the validator would take the validator count above the maximum.
TooManyValidators,
}
#[pallet::genesis_config]
#[derive(DefaultNoBound)]
pub struct GenesisConfig<T: Config> {
pub initial_validators: BoundedVec<T::AccountId, T::MaxAuthorities>,
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
assert!(
Validators::<T>::iter().next().is_none(),
"Validators are already initialized"
);
assert_eq!(NumValidators::<T>::get(), 0);
for who in &self.initial_validators {
assert!(Pallet::<T>::do_add_validator(who).is_ok());
}
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Add a new validator.
///
/// This will increment the validator's provider reference count, allowing the validator to
/// call [`set_keys`](pallet_session::Pallet::set_keys).
///
/// Provided the validator calls `set_keys` in time, the addition will take effect the
/// session after next.
///
/// The origin for this call must be the pallet's `AddRemoveOrigin`. Emits
/// [`ValidatorAdded`](Event::ValidatorAdded) when successful.
#[pallet::call_index(0)]
#[pallet::weight(<T as Config>::WeightInfo::add_validator())]
pub fn add_validator(origin: OriginFor<T>, who: T::AccountId) -> DispatchResult {
T::AddRemoveOrigin::ensure_origin(origin)?;
Self::do_add_validator(&who)?;
Self::deposit_event(Event::ValidatorAdded(who));
Ok(())
}
/// Set the validator set to exactly match the provided list of validators.
///
/// This will:
/// 1. Keep existing validators that are in the input list
/// 2. Remove validators that are not in the input list
/// 3. Add new validators from the input list
///
/// The origin for this call must be the pallet's `AddRemoveOrigin`. Emits
/// [`ValidatorAdded`](Event::ValidatorAdded) for each new validator and
/// [`ValidatorRemoved`](Event::ValidatorRemoved) for each removed validator.
///
/// If the number of validators would exceed the maximum, the operation fails.
#[pallet::call_index(1)]
#[pallet::weight(<T as Config>::WeightInfo::add_validator().saturating_mul(validators.len() as u64))]
pub fn set_validators(
origin: OriginFor<T>,
validators: Vec<T::AccountId>,
) -> DispatchResult {
T::AddRemoveOrigin::ensure_origin(origin)?;
// Check if the new validator count would exceed the maximum
ensure!(
validators.len() <= T::MaxAuthorities::get() as usize,
Error::<T>::TooManyValidators
);
// Check for duplicates in the input list
for (i, _) in validators.iter().enumerate() {
for j in 0..i {
ensure!(validators[i] != validators[j], Error::<T>::Duplicate);
}
}
// Get current validators
let current_validators: Vec<T::AccountId> = Validators::<T>::iter_keys().collect();
// Remove validators that are not in the new list
for who in current_validators.iter() {
if !validators.contains(who) {
if Self::do_remove_validator(who) {
Self::deposit_event(Event::ValidatorRemoved(who.clone()));
}
}
}
// Add new validators
for who in validators {
if Validators::<T>::get(&who).is_none() {
Self::do_add_validator(&who)?;
Self::deposit_event(Event::ValidatorAdded(who));
}
}
Ok(())
}
/// Remove a validator.
///
/// This will purge the validator's session keys and decrement the validator's provider
/// reference count.
///
/// The removal will take effect the session after next.
///
/// The origin for this call must be the pallet's `AddRemoveOrigin`. Emits
/// [`ValidatorRemoved`](Event::ValidatorRemoved) when successful.
#[pallet::call_index(2)]
#[pallet::weight(<T as Config>::WeightInfo::remove_validator())]
pub fn remove_validator(origin: OriginFor<T>, who: T::AccountId) -> DispatchResult {
T::AddRemoveOrigin::ensure_origin(origin)?;
ensure!(Self::do_remove_validator(&who), Error::<T>::NotAValidator);
Self::deposit_event(Event::ValidatorRemoved(who));
Ok(())
}
}
}
impl<T: Config> Pallet<T> {
pub fn validators() -> Vec<T::AccountId> {
Validators::<T>::iter_keys().collect()
}
fn do_add_validator(who: &T::AccountId) -> DispatchResult {
NumValidators::<T>::mutate(|num| {
if *num >= T::MaxAuthorities::get() {
return Err(Error::<T>::TooManyValidators);
}
Validators::<T>::mutate(who, |validator| {
if !validator.is_none() {
return Err(Error::<T>::Duplicate);
}
*validator = Some(Validator {
min_set_keys_block: Zero::zero(),
});
Ok(())
})?;
*num += 1;
Ok(())
})?;
frame_system::Pallet::<T>::inc_providers(who);
Ok(())
}
/// Returns `false` if `who` is not a validator.
fn do_remove_validator(who: &T::AccountId) -> bool {
if Validators::<T>::take(who).is_none() {
return false;
}
NumValidators::<T>::mutate(|num| *num -= 1);
// Decrement who's provider reference count. Purge who's session keys first as
// dec_providers will fail if there are any consumers.
if let Err(err) =
pallet_session::Pallet::<T>::purge_keys(RawOrigin::Signed(who.clone()).into())
{
log::trace!(
target: LOG_TARGET,
"Failed to purge session keys for validator {who:?}: {err:?}"
);
}
if let Err(err) = frame_system::Pallet::<T>::dec_providers(who) {
log::warn!(
target: LOG_TARGET,
"Failed to decrement provider reference count for validator {who:?}, \
leaking reference: {err:?}"
);
}
true
}
fn check_min_set_keys_block(
validator: &Validator<BlockNumberFor<T>>,
) -> Result<(), TransactionValidityError> {
if frame_system::Pallet::<T>::block_number() < validator.min_set_keys_block {
Err(InvalidTransaction::Future.into())
} else {
Ok(())
}
}
/// Check the validity of a [`set_keys`](pallet_session::Pallet::set_keys) call by `who`.
pub fn validate_set_keys(who: &T::AccountId) -> Result<(), TransactionValidityError> {
match Validators::<T>::get(who) {
Some(validator) => Self::check_min_set_keys_block(&validator),
None => Err(InvalidTransaction::BadSigner.into()),
}
}
/// Check the validity of a [`set_keys`](pallet_session::Pallet::set_keys) call by `who`, and,
/// if valid, note the call.
pub fn pre_dispatch_set_keys(who: &T::AccountId) -> Result<(), TransactionValidityError> {
Validators::<T>::mutate(who, |validator| match validator {
Some(validator) => {
Self::check_min_set_keys_block(validator)?;
validator.min_set_keys_block = frame_system::Pallet::<T>::block_number()
.saturating_add(T::SetKeysCooldownBlocks::get());
Ok(())
}
None => Err(InvalidTransaction::BadSigner.into()),
})
}
}
impl<T: Config> SessionManager<T::AccountId> for Pallet<T> {
fn new_session(_new_index: SessionIndex) -> Option<Vec<T::AccountId>> {
Some(Self::validators())
}
fn end_session(_end_index: SessionIndex) {}
fn start_session(_start_index: SessionIndex) {
for (who, _) in NextDisabledValidators::<T>::drain() {
pallet_session::Pallet::<T>::disable(&who);
}
}
}
impl<T: Config>
OnOffenceHandler<T::AccountId, pallet_session::historical::IdentificationTuple<T>, Weight>
for Pallet<T>
where
T: pallet_session::historical::Config,
{
fn on_offence(
offenders: &[OffenceDetails<
T::AccountId,
pallet_session::historical::IdentificationTuple<T>,
>],
slash_fractions: &[Perbill],
_slash_session: SessionIndex,
) -> Weight {
let mut weight = Weight::zero();
let db_weight = T::DbWeight::get();
for (offender, slash_fraction) in offenders.iter().zip(slash_fractions) {
// Determine actions to take with this validator
let remove = !slash_fraction.is_zero();
if remove {
// Note that the validator might already have been removed (explicitly, for another
// offence, or even by an earlier report of this offence)
weight.saturating_accrue(db_weight.reads(1));
if Self::do_remove_validator(&offender.offender.0) {
weight.saturating_accrue(db_weight.reads_writes(1, 2));
}
}
}
weight
}
}

View file

@ -0,0 +1,191 @@
// Copyright (C) Gautam Dhameja.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Mock helpers for Validator Set pallet.
#![cfg(test)]
use crate as pallet_validator_set;
use frame_support::{
parameter_types,
traits::{ConstU32, ConstU64, OnFinalize, OnInitialize, OneSessionHandler},
};
use frame_system::{pallet_prelude::BlockNumberFor, EnsureRoot};
use pallet_session::ShouldEndSession;
use sp_core::H256;
use sp_runtime::{
impl_opaque_keys,
testing::UintAuthorityId,
traits::{BlakeTwo256, ConvertInto, IdentityLookup},
BuildStorage,
};
use std::cell::Cell;
pub type AccountId = u64;
type Block = frame_system::mocking::MockBlock<Test>;
frame_support::construct_runtime!(
pub struct Test {
System: frame_system,
ValidatorSet: pallet_validator_set,
Session: pallet_session,
}
);
pub struct MockSessionHandler;
impl OneSessionHandler<AccountId> for MockSessionHandler {
type Key = UintAuthorityId;
fn on_genesis_session<'a, I: 'a>(_validators: I)
where
I: Iterator<Item = (&'a AccountId, Self::Key)>,
{
}
fn on_new_session<'a, I: 'a>(_changed: bool, _validators: I, _queued_validators: I)
where
I: Iterator<Item = (&'a AccountId, Self::Key)>,
{
}
fn on_disabled(_i: u32) {}
}
impl sp_runtime::BoundToRuntimeAppPublic for MockSessionHandler {
type Public = UintAuthorityId;
}
impl_opaque_keys! {
pub struct MockSessionKeys {
pub mock: MockSessionHandler,
}
}
impl From<AccountId> for MockSessionKeys {
fn from(who: AccountId) -> Self {
Self {
mock: UintAuthorityId(who),
}
}
}
thread_local! {
static END_SESSION: Cell<bool> = Cell::new(false);
}
pub struct MockShouldEndSession;
impl<T> ShouldEndSession<T> for MockShouldEndSession {
fn should_end_session(_now: T) -> bool {
END_SESSION.replace(false)
}
}
pub fn next_block() {
System::on_finalize(System::block_number());
System::set_block_number(System::block_number() + 1);
System::on_initialize(System::block_number());
Session::on_initialize(System::block_number());
}
pub fn next_session() {
END_SESSION.set(true);
next_block();
assert!(!END_SESSION.get());
}
pub fn new_test_ext() -> sp_io::TestExternalities {
let validators = vec![1, 2, 3];
let keys = validators
.iter()
.map(|who| (*who, *who, (*who).into()))
.collect();
let t = RuntimeGenesisConfig {
system: Default::default(),
session: SessionConfig {
keys,
non_authority_keys: Default::default(),
},
validator_set: ValidatorSetConfig {
initial_validators: validators.try_into().unwrap(),
},
}
.build_storage()
.unwrap();
t.into()
}
impl frame_system::Config for Test {
type BaseCallFilter = frame_support::traits::Everything;
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type RuntimeOrigin = RuntimeOrigin;
type Nonce = u64;
type RuntimeCall = RuntimeCall;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = AccountId;
type Lookup = IdentityLookup<AccountId>;
type Block = Block;
type RuntimeEvent = RuntimeEvent;
type BlockHashCount = ConstU64<250>;
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = ();
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = ConstU32<16>;
type RuntimeTask = ();
type SingleBlockMigrations = ();
type MultiBlockMigrator = ();
type PreInherents = ();
type PostInherents = ();
type PostTransactions = ();
}
parameter_types! {
pub const SetKeysCooldownBlocks: BlockNumberFor<Test> = 2;
}
impl pallet_validator_set::Config for Test {
type RuntimeEvent = RuntimeEvent;
type WeightInfo = ();
type AddRemoveOrigin = EnsureRoot<AccountId>;
type MaxAuthorities = ConstU32<6>;
type SetKeysCooldownBlocks = SetKeysCooldownBlocks;
}
impl pallet_session::Config for Test {
type ValidatorId = AccountId;
type ValidatorIdOf = ConvertInto;
type ShouldEndSession = MockShouldEndSession;
type NextSessionRotation = ();
type SessionManager = ValidatorSet;
type SessionHandler = (MockSessionHandler,);
type Keys = MockSessionKeys;
type WeightInfo = ();
type RuntimeEvent = RuntimeEvent;
}
impl pallet_session::historical::Config for Test {
type FullIdentification = Self::ValidatorId;
type FullIdentificationOf = Self::ValidatorIdOf;
}

View file

@ -0,0 +1,177 @@
// Copyright (C) Gautam Dhameja.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Tests for the Validator Set pallet.
#![cfg(test)]
use super::mock::{
new_test_ext, next_block, next_session, AccountId, RuntimeOrigin, Session, System, Test,
ValidatorSet,
};
use frame_support::{assert_noop, assert_ok, traits::ValidatorRegistration};
use sp_runtime::{traits::Zero, transaction_validity::InvalidTransaction, DispatchError};
use std::collections::HashSet;
type Error = super::Error<Test>;
fn validators() -> HashSet<AccountId> {
ValidatorSet::validators().into_iter().collect()
}
fn active_validators() -> HashSet<AccountId> {
Session::validators().into_iter().collect()
}
#[test]
fn initial_validators() {
new_test_ext().execute_with(|| {
assert_eq!(validators(), HashSet::from([1, 2, 3]));
assert_eq!(active_validators(), HashSet::from([1, 2, 3]));
});
}
#[test]
fn add_validator_updates_validators_list() {
new_test_ext().execute_with(|| {
assert_eq!(validators(), HashSet::from([1, 2, 3]));
assert_ok!(ValidatorSet::add_validator(RuntimeOrigin::root(), 4));
assert_eq!(validators(), HashSet::from([1, 2, 3, 4]));
// add_validator should take effect in the session after next, provided the keys have been
// set
assert_ok!(Session::set_keys(
RuntimeOrigin::signed(4),
4.into(),
vec![]
));
assert_eq!(active_validators(), HashSet::from([1, 2, 3]));
next_session();
assert_eq!(active_validators(), HashSet::from([1, 2, 3]));
next_session();
assert_eq!(active_validators(), HashSet::from([1, 2, 3, 4]));
});
}
#[test]
fn remove_validator_updates_validators_list() {
new_test_ext().execute_with(|| {
assert_ok!(ValidatorSet::remove_validator(RuntimeOrigin::root(), 2));
assert_eq!(validators(), HashSet::from([1, 3]));
// Add validator again
assert_ok!(ValidatorSet::add_validator(RuntimeOrigin::root(), 2));
assert_eq!(validators(), HashSet::from([1, 2, 3]));
});
}
#[test]
fn add_validator_fails_with_invalid_origin() {
new_test_ext().execute_with(|| {
assert_noop!(
ValidatorSet::add_validator(RuntimeOrigin::signed(1), 4),
DispatchError::BadOrigin
);
});
}
#[test]
fn remove_validator_fails_with_invalid_origin() {
new_test_ext().execute_with(|| {
assert_noop!(
ValidatorSet::remove_validator(RuntimeOrigin::signed(1), 4),
DispatchError::BadOrigin
);
});
}
#[test]
fn duplicate_check() {
new_test_ext().execute_with(|| {
assert_ok!(ValidatorSet::add_validator(RuntimeOrigin::root(), 4));
assert_eq!(validators(), HashSet::from([1, 2, 3, 4]));
assert_noop!(
ValidatorSet::add_validator(RuntimeOrigin::root(), 4),
Error::Duplicate
);
});
}
#[test]
fn too_many_validators_check() {
new_test_ext().execute_with(|| {
assert_ok!(ValidatorSet::add_validator(RuntimeOrigin::root(), 4));
assert_ok!(ValidatorSet::add_validator(RuntimeOrigin::root(), 5));
assert_ok!(ValidatorSet::add_validator(RuntimeOrigin::root(), 6));
assert_noop!(
ValidatorSet::add_validator(RuntimeOrigin::root(), 7),
Error::TooManyValidators
);
});
}
#[test]
fn not_a_validator_check() {
new_test_ext().execute_with(|| {
assert_ok!(ValidatorSet::remove_validator(RuntimeOrigin::root(), 3));
assert_noop!(
ValidatorSet::remove_validator(RuntimeOrigin::root(), 3),
Error::NotAValidator
);
});
}
#[test]
fn remove_purges_keys_and_decs_providers() {
new_test_ext().execute_with(|| {
assert!(Session::is_registered(&3));
assert!(!System::providers(&3).is_zero());
assert_ok!(ValidatorSet::remove_validator(RuntimeOrigin::root(), 3));
assert!(!Session::is_registered(&3));
assert!(System::providers(&3).is_zero());
});
}
#[test]
fn non_validator_cant_set_keys() {
new_test_ext().execute_with(|| {
assert_noop!(
ValidatorSet::validate_set_keys(&4),
InvalidTransaction::BadSigner
);
assert_noop!(
ValidatorSet::pre_dispatch_set_keys(&4),
InvalidTransaction::BadSigner
);
});
}
#[test]
fn set_keys_has_cooldown() {
new_test_ext().execute_with(|| {
assert_ok!(ValidatorSet::pre_dispatch_set_keys(&3));
assert_noop!(
ValidatorSet::pre_dispatch_set_keys(&3),
InvalidTransaction::Future
);
next_block();
assert_noop!(
ValidatorSet::pre_dispatch_set_keys(&3),
InvalidTransaction::Future
);
next_block();
assert_ok!(ValidatorSet::pre_dispatch_set_keys(&3));
});
}

View file

@ -0,0 +1,108 @@
// Copyright (C) Gautam Dhameja.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Autogenerated weights for Validator Set
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2023-05-29, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("local"), DB CACHE: 1024
// Executed Command:
// ./target/release/node-template
// benchmark
// pallet
// --chain
// local
// --pallet
// validator_set
// --extrinsic
// *
// --steps
// 50
// --repeat
// 20
// --execution=wasm
// --wasm-execution=compiled
// --heap-pages=4096
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(missing_docs)]
use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
use core::marker::PhantomData;
/// Weight functions needed for validator_set.
pub trait WeightInfo {
fn add_validator() -> Weight;
fn remove_validator() -> Weight;
}
/// Weights for validator_set using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Storage: ValidatorSet Validators (r:1 w:1)
/// Proof Skipped: ValidatorSet Validators (max_values: Some(1), max_size: None, mode: Measured)
fn add_validator() -> Weight {
// Proof Size summary in bytes:
// Measured: `117`
// Estimated: `1602`
// Minimum execution time: 20_810_000 picoseconds.
Weight::from_parts(21_330_000, 1602)
.saturating_add(T::DbWeight::get().reads(1_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
/// Storage: ValidatorSet Validators (r:1 w:1)
/// Proof Skipped: ValidatorSet Validators (max_values: Some(1), max_size: None, mode: Measured)
fn remove_validator() -> Weight {
// Proof Size summary in bytes:
// Measured: `117`
// Estimated: `1602`
// Minimum execution time: 18_700_000 picoseconds.
Weight::from_parts(19_840_000, 1602)
.saturating_add(T::DbWeight::get().reads(1_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
}
// For backwards compatibility and tests
impl WeightInfo for () {
/// Storage: ValidatorSet Validators (r:1 w:1)
/// Proof Skipped: ValidatorSet Validators (max_values: Some(1), max_size: None, mode: Measured)
fn add_validator() -> Weight {
// Proof Size summary in bytes:
// Measured: `117`
// Estimated: `1602`
// Minimum execution time: 20_810_000 picoseconds.
Weight::from_parts(21_330_000, 1602)
.saturating_add(RocksDbWeight::get().reads(1_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
/// Storage: ValidatorSet Validators (r:1 w:1)
/// Proof Skipped: ValidatorSet Validators (max_values: Some(1), max_size: None, mode: Measured)
fn remove_validator() -> Weight {
// Proof Size summary in bytes:
// Measured: `117`
// Estimated: `1602`
// Minimum execution time: 18_700_000 picoseconds.
Weight::from_parts(19_840_000, 1602)
.saturating_add(RocksDbWeight::get().reads(1_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
}

194
operator/runtime/Cargo.toml Normal file
View file

@ -0,0 +1,194 @@
[package]
name = "datahaven-runtime"
description = "datahaven runtime template built with polkadot-sdk."
version = "0.1.0"
license = "Unlicense"
authors.workspace = true
homepage.workspace = true
repository.workspace = true
edition.workspace = true
publish = false
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { features = ["derive"], workspace = true }
hex = { workspace = true }
scale-info = { features = ["derive", "serde"], workspace = true }
datahaven-runtime-common.workspace = true
frame-support = { features = ["experimental"], workspace = true }
frame-system.workspace = true
frame-try-runtime = { optional = true, workspace = true }
frame-executive.workspace = true
frame-metadata-hash-extension.workspace = true
pallet-author-inherent.workspace = true
hex-literal.workspace = true
pallet-babe.workspace = true
pallet-balances.workspace = true
pallet-grandpa.workspace = true
pallet-session.workspace = true
pallet-sudo.workspace = true
pallet-timestamp.workspace = true
pallet-transaction-payment.workspace = true
pallet-validator-set.workspace = true
pallet-beefy.workspace = true
pallet-beefy-mmr.workspace = true
pallet-mmr.workspace = true
sp-api.workspace = true
sp-block-builder.workspace = true
sp-consensus-babe = { features = ["serde"], workspace = true }
sp-consensus-beefy = { features = ["serde"], workspace = true }
sp-consensus-grandpa = { features = ["serde"], workspace = true }
sp-core = { features = ["serde"], workspace = true }
sp-inherents.workspace = true
sp-offchain.workspace = true
sp-runtime = { features = ["serde"], workspace = true }
sp-session.workspace = true
sp-std.workspace = true
sp-staking.workspace = true
sp-storage.workspace = true
sp-transaction-pool.workspace = true
sp-version = { features = ["serde"], workspace = true }
sp-genesis-builder.workspace = true
frame-system-rpc-runtime-api.workspace = true
pallet-transaction-payment-rpc-runtime-api.workspace = true
polkadot-runtime-common.workspace = true
frame-benchmarking = { optional = true, workspace = true }
frame-system-benchmarking = { optional = true, workspace = true }
polkadot-primitives.workspace = true
fp-account = { workspace = true, features = [ "serde" ]}
pallet-evm.workspace = true
pallet-evm-chain-id.workspace = true
pallet-ethereum.workspace = true
# Snowbridge
snowbridge-beacon-primitives.workspace = true
snowbridge-pallet-ethereum-client.workspace = true
[build-dependencies]
substrate-wasm-builder = { optional = true, workspace = true, default-features = true }
[features]
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"frame-executive/std",
"frame-metadata-hash-extension/std",
"frame-support/std",
"frame-system-benchmarking?/std",
"frame-system-rpc-runtime-api/std",
"frame-system/std",
"frame-benchmarking?/std",
"frame-try-runtime?/std",
"datahaven-runtime-common/std",
"pallet-babe/std",
"pallet-beefy/std",
"pallet-beefy-mmr/std",
"pallet-balances/std",
"pallet-grandpa/std",
"pallet-mmr/std",
"pallet-session/std",
"pallet-session/std",
"pallet-sudo/std",
"pallet-timestamp/std",
"pallet-transaction-payment-rpc-runtime-api/std",
"pallet-transaction-payment/std",
"pallet-author-inherent/std",
"pallet-validator-set/std",
"polkadot-primitives/std",
"polkadot-runtime-common/std",
"snowbridge-beacon-primitives/std",
"snowbridge-pallet-ethereum-client/std",
"sp-api/std",
"sp-block-builder/std",
"sp-consensus-babe/std",
"sp-consensus-grandpa/std",
"sp-core/std",
"sp-genesis-builder/std",
"sp-inherents/std",
"sp-offchain/std",
"sp-runtime/std",
"sp-session/std",
"sp-staking/std",
"sp-storage/std",
"sp-std/std",
"sp-transaction-pool/std",
"sp-version/std",
"substrate-wasm-builder",
"pallet-mmr/std",
"fp-account/std",
"pallet-evm/std",
"pallet-evm-chain-id/std",
"pallet-ethereum/std",
]
runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system-benchmarking/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"datahaven-runtime-common/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"pallet-grandpa/runtime-benchmarks",
"pallet-sudo/runtime-benchmarks",
"pallet-timestamp/runtime-benchmarks",
"pallet-beefy-mmr/runtime-benchmarks",
"pallet-mmr/runtime-benchmarks",
"polkadot-runtime-common/runtime-benchmarks",
"polkadot-primitives/runtime-benchmarks",
"snowbridge-pallet-ethereum-client/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"pallet-evm/runtime-benchmarks",
"pallet-author-inherent/runtime-benchmarks",
"pallet-ethereum/runtime-benchmarks",
]
try-runtime = [
"frame-executive/try-runtime",
"frame-support/try-runtime",
"frame-system/try-runtime",
"frame-try-runtime/try-runtime",
"pallet-babe/try-runtime",
"pallet-balances/try-runtime",
"pallet-grandpa/try-runtime",
"pallet-session/try-runtime",
"pallet-sudo/try-runtime",
"pallet-timestamp/try-runtime",
"pallet-transaction-payment/try-runtime",
"pallet-beefy/try-runtime",
"pallet-beefy-mmr/try-runtime",
"pallet-mmr/try-runtime",
"polkadot-runtime-common/try-runtime",
"snowbridge-pallet-ethereum-client/try-runtime",
"sp-runtime/try-runtime",
"pallet-evm/try-runtime",
"pallet-ethereum/try-runtime",
]
fast-runtime = [
"datahaven-runtime-common/fast-runtime",
]
# Enable the metadata hash generation.
#
# This is hidden behind a feature because it increases the compile time.
# The wasm binary needs to be compiled twice, once to fetch the metadata,
# generate the metadata hash and then a second time with the
# `RUNTIME_METADATA_HASH` environment variable set for the `CheckMetadataHash`
# extension.
metadata-hash = ["substrate-wasm-builder/metadata-hash"]
# A convenience feature for enabling things when doing a build
# for an on-chain release.
on-chain-release-build = ["metadata-hash", "sp-api/disable-logging"]

View file

@ -0,0 +1,5 @@
## Release
Polkadot SDK stable2409

16
operator/runtime/build.rs Normal file
View file

@ -0,0 +1,16 @@
#[cfg(all(feature = "std", feature = "metadata-hash"))]
fn main() {
substrate_wasm_builder::WasmBuilder::init_with_defaults()
.enable_metadata_hash("UNIT", 12)
.build();
}
#[cfg(all(feature = "std", not(feature = "metadata-hash")))]
fn main() {
substrate_wasm_builder::WasmBuilder::build_using_defaults();
}
/// The wasm builder is deactivated when compiling
/// this crate for wasm to speed up the compilation.
#[cfg(not(feature = "std"))]
fn main() {}

View file

@ -0,0 +1,26 @@
[package]
name = "datahaven-runtime-common"
description = "Common code used through the Datahaven network"
version = "0.1.0"
edition.workspace = true
[dependencies]
frame-support.workspace = true
polkadot-primitives.workspace = true
polkadot-runtime-common.workspace = true
[features]
default = ["std"]
std = [
"frame-support/std",
"polkadot-primitives/std",
"polkadot-runtime-common/std"
]
runtime-benchmarks = [
"frame-support/runtime-benchmarks",
"polkadot-primitives/runtime-benchmarks",
"polkadot-runtime-common/runtime-benchmarks"
]
# Set timing constants (e.g. session period) to faster versions to speed up testing.
fast-runtime = []

View file

@ -0,0 +1,35 @@
/// Time and blocks.
pub mod time {
use polkadot_primitives::{BlockNumber, Moment};
use polkadot_runtime_common::prod_or_fast;
pub const MILLISECS_PER_BLOCK: Moment = 6000;
pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK;
frame_support::parameter_types! {
pub const EpochDurationInBlocks: BlockNumber = prod_or_fast!(1 * HOURS, 1 * MINUTES);
}
// These time units are defined in number of blocks.
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
pub const HOURS: BlockNumber = MINUTES * 60;
pub const DAYS: BlockNumber = HOURS * 24;
pub const WEEKS: BlockNumber = DAYS * 7;
}
pub mod gas {
use frame_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND;
/// Current approximation of the gas/s consumption considering
/// EVM execution over compiled WASM (on 4.4Ghz CPU).
/// Given the 1000ms Weight, from which 75% only are used for transactions,
/// the total EVM execution gas limit is: GAS_PER_SECOND * 1 * 0.75 ~= 30_000_000.
pub const GAS_PER_SECOND: u64 = 40_000_000;
/// Approximate ratio of the amount of Weight per Gas.
/// u64 works for approximations because Weight is a very small unit compared to gas.
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
/// The highest amount of new storage that can be created in a block (160KB).
pub const BLOCK_STORAGE_LIMIT: u64 = 160 * 1024;
}

View file

@ -0,0 +1,54 @@
// Copyright (C) Moondance Labs Ltd.
// This file is part of Tanssi.
// Tanssi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Tanssi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Tanssi. If not, see <http://www.gnu.org/licenses/>.
#[macro_export]
macro_rules! impl_on_charge_evm_transaction {
{} => {
pub struct OnChargeEVMTransaction<OU>(sp_std::marker::PhantomData<OU>);
impl<T, OU> OnChargeEVMTransactionT<T> for OnChargeEVMTransaction<OU>
where
T: pallet_evm::Config,
T::Currency: Balanced<pallet_evm::AccountIdOf<T>>,
OU: OnUnbalanced<Credit<pallet_evm::AccountIdOf<T>, T::Currency>>,
U256: UniqueSaturatedInto<<T::Currency as Inspect<pallet_evm::AccountIdOf<T>>>::Balance>,
T::AddressMapping: pallet_evm::AddressMapping<T::AccountId>,
{
type LiquidityInfo = Option<Credit<pallet_evm::AccountIdOf<T>, T::Currency>>;
fn withdraw_fee(who: &H160, fee: U256) -> Result<Self::LiquidityInfo, pallet_evm::Error<T>> {
EVMFungibleAdapter::<<T as pallet_evm::Config>::Currency, ()>::withdraw_fee(who, fee)
}
fn correct_and_deposit_fee(
who: &H160,
corrected_fee: U256,
base_fee: U256,
already_withdrawn: Self::LiquidityInfo,
) -> Self::LiquidityInfo {
<EVMFungibleAdapter<<T as pallet_evm::Config>::Currency, OU> as OnChargeEVMTransactionT<
T,
>>::correct_and_deposit_fee(who, corrected_fee, base_fee, already_withdrawn)
}
fn pay_priority_fee(tip: Self::LiquidityInfo) {
if let Some(tip) = tip {
OU::on_unbalanced(tip);
}
}
}
}
}

View file

@ -0,0 +1,22 @@
// Copyright 2019-2025 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Moonbeam is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Moonbeam. If not, see <http://www.gnu.org/licenses/>.
#![cfg_attr(not(feature = "std"), no_std)]
pub mod constants;
pub use constants::gas;
pub use constants::time;
pub mod impl_on_charge_evm_transaction;

View file

@ -0,0 +1,487 @@
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// For more information, please refer to <http://unlicense.org>
// External crates imports
use crate::configs::BABE_GENESIS_EPOCH_CONFIG;
use alloc::{vec, vec::Vec};
use codec::Encode;
use datahaven_runtime_common::time::EpochDurationInBlocks;
use frame_support::{
genesis_builder_helper::{build_state, get_preset},
weights::Weight,
};
use sp_api::impl_runtime_apis;
use sp_consensus_beefy::{
ecdsa_crypto::{AuthorityId as BeefyId, Signature as BeefySignature},
AncestryHelper,
};
use sp_core::OpaqueMetadata;
use sp_runtime::{
traits::Block as BlockT,
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult,
};
use sp_version::RuntimeVersion;
// Local module imports
use super::{
AccountId, Babe, Balance, Beefy, BeefyMmrLeaf, Block, BlockNumber, Executive, Grandpa,
Historical, InherentDataExt, Mmr, Nonce, Runtime, RuntimeCall, RuntimeGenesisConfig,
SessionKeys, System, TransactionPayment, VERSION,
};
use frame_support::traits::KeyOwnerProofSystem;
use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId};
use polkadot_primitives::Hash;
/// MMR helper types.
mod mmr {
use super::Runtime;
pub use pallet_mmr::primitives::*;
pub type Leaf = <<Runtime as pallet_mmr::Config>::LeafData as LeafDataProvider>::LeafData;
pub type Hashing = <Runtime as pallet_mmr::Config>::Hashing;
pub type Hash = <Hashing as sp_runtime::traits::Hash>::Output;
}
impl_runtime_apis! {
impl sp_api::Core<Block> for Runtime {
fn version() -> RuntimeVersion {
VERSION
}
fn execute_block(block: Block) {
Executive::execute_block(block);
}
fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
Executive::initialize_block(header)
}
}
impl sp_api::Metadata<Block> for Runtime {
fn metadata() -> OpaqueMetadata {
OpaqueMetadata::new(Runtime::metadata().into())
}
fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
Runtime::metadata_at_version(version)
}
fn metadata_versions() -> Vec<u32> {
Runtime::metadata_versions()
}
}
impl sp_block_builder::BlockBuilder<Block> for Runtime {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
Executive::apply_extrinsic(extrinsic)
}
fn finalize_block() -> <Block as BlockT>::Header {
Executive::finalize_block()
}
fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
data.create_extrinsics()
}
fn check_inherents(
block: Block,
data: sp_inherents::InherentData,
) -> sp_inherents::CheckInherentsResult {
data.check_extrinsics(&block)
}
}
impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
fn validate_transaction(
source: TransactionSource,
tx: <Block as BlockT>::Extrinsic,
block_hash: <Block as BlockT>::Hash,
) -> TransactionValidity {
Executive::validate_transaction(source, tx, block_hash)
}
}
impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
fn offchain_worker(header: &<Block as BlockT>::Header) {
Executive::offchain_worker(header)
}
}
impl sp_session::SessionKeys<Block> for Runtime {
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
SessionKeys::generate(seed)
}
fn decode_session_keys(
encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
SessionKeys::decode_into_raw_public_keys(&encoded)
}
}
impl sp_consensus_babe::BabeApi<Block> for Runtime {
fn configuration() -> sp_consensus_babe::BabeConfiguration {
let epoch_config = Babe::epoch_config().unwrap_or(BABE_GENESIS_EPOCH_CONFIG);
sp_consensus_babe::BabeConfiguration {
slot_duration: Babe::slot_duration(),
epoch_length: EpochDurationInBlocks::get().into(),
c: epoch_config.c,
authorities: Babe::authorities().to_vec(),
randomness: Babe::randomness(),
allowed_slots: epoch_config.allowed_slots,
}
}
fn current_epoch_start() -> sp_consensus_babe::Slot {
Babe::current_epoch_start()
}
fn current_epoch() -> sp_consensus_babe::Epoch {
Babe::current_epoch()
}
fn next_epoch() -> sp_consensus_babe::Epoch {
Babe::next_epoch()
}
fn generate_key_ownership_proof(
_slot: sp_consensus_babe::Slot,
authority_id: sp_consensus_babe::AuthorityId,
) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> {
use codec::Encode;
Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id))
.map(|p| p.encode())
.map(sp_consensus_babe::OpaqueKeyOwnershipProof::new)
}
fn submit_report_equivocation_unsigned_extrinsic(
equivocation_proof: sp_consensus_babe::EquivocationProof<<Block as BlockT>::Header>,
key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof,
) -> Option<()> {
let key_owner_proof = key_owner_proof.decode()?;
Babe::submit_unsigned_equivocation_report(
equivocation_proof,
key_owner_proof,
)
}
}
impl fg_primitives::GrandpaApi<Block> for Runtime {
fn grandpa_authorities() -> Vec<(GrandpaId, u64)> {
Grandpa::grandpa_authorities()
}
fn current_set_id() -> fg_primitives::SetId {
Grandpa::current_set_id()
}
fn submit_report_equivocation_unsigned_extrinsic(
equivocation_proof: fg_primitives::EquivocationProof<
<Block as BlockT>::Hash,
sp_runtime::traits::NumberFor<Block>,
>,
key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,
) -> Option<()> {
let key_owner_proof = key_owner_proof.decode()?;
Grandpa::submit_unsigned_equivocation_report(
equivocation_proof,
key_owner_proof,
)
}
fn generate_key_ownership_proof(
_set_id: fg_primitives::SetId,
authority_id: fg_primitives::AuthorityId,
) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {
Historical::prove((fg_primitives::KEY_TYPE, authority_id))
.map(|p| p.encode())
.map(fg_primitives::OpaqueKeyOwnershipProof::new)
}
}
#[api_version(2)]
impl mmr::MmrApi<Block, mmr::Hash, BlockNumber> for Runtime {
fn mmr_root() -> Result<mmr::Hash, mmr::Error> {
Ok(pallet_mmr::RootHash::<Runtime>::get())
}
fn mmr_leaf_count() -> Result<mmr::LeafIndex, mmr::Error> {
Ok(pallet_mmr::NumberOfLeaves::<Runtime>::get())
}
fn generate_proof(
block_numbers: Vec<BlockNumber>,
best_known_block_number: Option<BlockNumber>,
) -> Result<(Vec<mmr::EncodableOpaqueLeaf>, mmr::LeafProof<mmr::Hash>), mmr::Error> {
Mmr::generate_proof(block_numbers, best_known_block_number).map(
|(leaves, proof)| {
(
leaves
.into_iter()
.map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf))
.collect(),
proof,
)
},
)
}
fn verify_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::LeafProof<mmr::Hash>)
-> Result<(), mmr::Error>
{
let leaves = leaves.into_iter().map(|leaf|
leaf.into_opaque_leaf()
.try_decode()
.ok_or(mmr::Error::Verify)).collect::<Result<Vec<mmr::Leaf>, mmr::Error>>()?;
Mmr::verify_leaves(leaves, proof)
}
fn verify_proof_stateless(
root: mmr::Hash,
leaves: Vec<mmr::EncodableOpaqueLeaf>,
proof: mmr::LeafProof<mmr::Hash>
) -> Result<(), mmr::Error> {
let nodes = leaves.into_iter().map(|leaf|mmr::DataOrHash::Data(leaf.into_opaque_leaf())).collect();
pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(root, nodes, proof)
}
}
impl pallet_beefy_mmr::BeefyMmrApi<Block, Hash> for RuntimeApi {
fn authority_set_proof() -> sp_consensus_beefy::mmr::BeefyAuthoritySet<Hash> {
BeefyMmrLeaf::authority_set_proof()
}
fn next_authority_set_proof() -> sp_consensus_beefy::mmr::BeefyNextAuthoritySet<Hash> {
BeefyMmrLeaf::next_authority_set_proof()
}
}
#[api_version(5)]
impl sp_consensus_beefy::BeefyApi<Block, BeefyId> for Runtime {
fn beefy_genesis() -> Option<BlockNumber> {
pallet_beefy::GenesisBlock::<Runtime>::get()
}
fn validator_set() -> Option<sp_consensus_beefy::ValidatorSet<BeefyId>> {
Beefy::validator_set()
}
fn submit_report_double_voting_unsigned_extrinsic(
equivocation_proof: sp_consensus_beefy::DoubleVotingProof<
BlockNumber,
BeefyId,
BeefySignature,
>,
key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
) -> Option<()> {
let key_owner_proof = key_owner_proof.decode()?;
Beefy::submit_unsigned_double_voting_report(
equivocation_proof,
key_owner_proof,
)
}
fn submit_report_fork_voting_unsigned_extrinsic(
equivocation_proof:
sp_consensus_beefy::ForkVotingProof<
<Block as BlockT>::Header,
BeefyId,
sp_runtime::OpaqueValue
>,
key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
) -> Option<()> {
Beefy::submit_unsigned_fork_voting_report(
equivocation_proof.try_into()?,
key_owner_proof.decode()?,
)
}
fn submit_report_future_block_voting_unsigned_extrinsic(
equivocation_proof: sp_consensus_beefy::FutureBlockVotingProof<BlockNumber, BeefyId>,
key_owner_proof: sp_consensus_beefy::OpaqueKeyOwnershipProof,
) -> Option<()> {
Beefy::submit_unsigned_future_block_voting_report(
equivocation_proof,
key_owner_proof.decode()?,
)
}
fn generate_key_ownership_proof(
_set_id: sp_consensus_beefy::ValidatorSetId,
authority_id: BeefyId,
) -> Option<sp_consensus_beefy::OpaqueKeyOwnershipProof> {
Historical::prove((sp_consensus_beefy::KEY_TYPE, authority_id))
.map(|p| p.encode())
.map(sp_consensus_beefy::OpaqueKeyOwnershipProof::new)
}
fn generate_ancestry_proof(
prev_block_number: BlockNumber,
best_known_block_number: Option<BlockNumber>,
) -> Option<sp_runtime::OpaqueValue> {
use codec::Encode;
BeefyMmrLeaf::generate_proof(prev_block_number, best_known_block_number)
.map(|p| p.encode())
.map(sp_runtime::OpaqueValue::new)
}
}
impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
fn account_nonce(account: AccountId) -> Nonce {
System::account_nonce(account)
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
fn query_info(
uxt: <Block as BlockT>::Extrinsic,
len: u32,
) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
TransactionPayment::query_info(uxt, len)
}
fn query_fee_details(
uxt: <Block as BlockT>::Extrinsic,
len: u32,
) -> pallet_transaction_payment::FeeDetails<Balance> {
TransactionPayment::query_fee_details(uxt, len)
}
fn query_weight_to_fee(weight: Weight) -> Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> Balance {
TransactionPayment::length_to_fee(length)
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
for Runtime
{
fn query_call_info(
call: RuntimeCall,
len: u32,
) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
TransactionPayment::query_call_info(call, len)
}
fn query_call_fee_details(
call: RuntimeCall,
len: u32,
) -> pallet_transaction_payment::FeeDetails<Balance> {
TransactionPayment::query_call_fee_details(call, len)
}
fn query_weight_to_fee(weight: Weight) -> Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> Balance {
TransactionPayment::length_to_fee(length)
}
}
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(extra: bool) -> (
Vec<frame_benchmarking::BenchmarkList>,
Vec<frame_support::traits::StorageInfo>,
) {
use frame_benchmarking::{baseline, Benchmarking, BenchmarkList};
use frame_support::traits::StorageInfoTrait;
use frame_system_benchmarking::Pallet as SystemBench;
use baseline::Pallet as BaselineBench;
use super::*;
let mut list = Vec::<BenchmarkList>::new();
list_benchmarks!(list, extra);
let storage_info = AllPalletsWithSystem::storage_info();
(list, storage_info)
}
fn dispatch_benchmark(
config: frame_benchmarking::BenchmarkConfig
) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch};
use sp_storage::TrackedStorageKey;
use frame_system_benchmarking::Pallet as SystemBench;
use baseline::Pallet as BaselineBench;
use super::*;
impl frame_system_benchmarking::Config for Runtime {}
impl baseline::Config for Runtime {}
use frame_support::traits::WhitelistedStorageKeys;
let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
let mut batches = Vec::<BenchmarkBatch>::new();
let params = (&config, &whitelist);
add_benchmarks!(params, batches);
Ok(batches)
}
}
#[cfg(feature = "try-runtime")]
impl frame_try_runtime::TryRuntime<Block> for Runtime {
fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
// have a backtrace here. If any of the pre/post migration checks fail, we shall stop
// right here and right now.
let weight = Executive::try_runtime_upgrade(checks).unwrap();
(weight, super::configs::RuntimeBlockWeights::get().max_block)
}
fn execute_block(
block: Block,
state_root_check: bool,
signature_check: bool,
select: frame_try_runtime::TryStateSelect
) -> Weight {
// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
// have a backtrace here.
Executive::try_execute_block(block, state_root_check, signature_check, select).expect("execute-block failed")
}
}
impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
build_state::<RuntimeGenesisConfig>(config)
}
fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
get_preset::<RuntimeGenesisConfig>(id, |_| None)
}
fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
vec![]
}
}
}

View file

@ -0,0 +1,32 @@
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// For more information, please refer to <http://unlicense.org>
frame_benchmarking::define_benchmarks!(
[frame_benchmarking, BaselineBench::<Runtime>]
[frame_system, SystemBench::<Runtime>]
[pallet_balances, Balances]
[pallet_timestamp, Timestamp]
[pallet_sudo, Sudo]
);

View file

@ -0,0 +1,483 @@
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// For more information, please refer to <http://unlicense.org>
use crate::AuthorInherent;
use crate::EvmChainId;
use crate::Timestamp;
use crate::{Historical, SessionKeys, ValidatorSet};
// Local module imports
use super::{
AccountId, Babe, Balance, Balances, BeefyMmrLeaf, Block, BlockNumber, Hash, Nonce, PalletInfo,
Runtime, RuntimeCall, RuntimeEvent, RuntimeFreezeReason, RuntimeHoldReason, RuntimeOrigin,
RuntimeTask, Session, System, EXISTENTIAL_DEPOSIT, SLOT_DURATION, VERSION,
};
// Substrate and Polkadot dependencies
use codec::{Decode, Encode};
use datahaven_runtime_common::gas::WEIGHT_PER_GAS;
use datahaven_runtime_common::time::{EpochDurationInBlocks, MILLISECS_PER_BLOCK, MINUTES};
use frame_support::{
derive_impl, parameter_types,
traits::{
fungible::{Balanced, Credit, Inspect},
ConstU128, ConstU32, ConstU64, ConstU8, FindAuthor, KeyOwnerProofSystem, OnUnbalanced,
VariantCountOf,
},
weights::{
constants::{RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND},
IdentityFee, Weight,
},
};
use frame_system::limits::{BlockLength, BlockWeights};
use frame_system::EnsureRoot;
use pallet_ethereum::PostLogContent;
use pallet_evm::{
EVMFungibleAdapter, EnsureAddressNever, EnsureAddressRoot, FeeCalculator,
FrameSystemAccountProvider, IdentityAddressMapping,
OnChargeEVMTransaction as OnChargeEVMTransactionT,
};
use pallet_transaction_payment::{
ConstFeeMultiplier, FungibleAdapter, Multiplier, Pallet as TransactionPayment,
};
use polkadot_primitives::Moment;
use snowbridge_beacon_primitives::{Fork, ForkVersions};
use sp_consensus_beefy::mmr::BeefyDataProvider;
use sp_consensus_beefy::{ecdsa_crypto::AuthorityId as BeefyId, mmr::MmrLeafVersion};
use sp_core::{crypto::KeyTypeId, H160, H256, U256};
use sp_runtime::{
traits::{AccountIdLookup, ConvertInto, Keccak256, One, OpaqueKeys, UniqueSaturatedInto},
FixedPointNumber, Perbill,
};
use sp_staking::{EraIndex, SessionIndex};
use sp_std::{
convert::{From, Into},
prelude::*,
};
use sp_version::RuntimeVersion;
// TODO: We need to define what do we want here as max PoV size
pub const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
// Todo: import all currency constants from moonbeam
pub const WEIGHT_FEE: Balance = 50_000 / 4;
pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND, u64::MAX)
.saturating_mul(2)
.set_proof_size(MAX_POV_SIZE as u64);
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
parameter_types! {
pub const BlockHashCount: BlockNumber = 2400;
pub const Version: RuntimeVersion = VERSION;
/// We allow for 2 seconds of compute with a 6 second average block time.
pub RuntimeBlockWeights: BlockWeights = BlockWeights::with_sensible_defaults(
Weight::from_parts(2u64 * WEIGHT_REF_TIME_PER_SECOND, u64::MAX),
NORMAL_DISPATCH_RATIO,
);
pub RuntimeBlockLength: BlockLength = BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
pub const SS58Prefix: u8 = 42;
pub const MaxAuthorities: u32 = 32;
pub const SetKeysCooldownBlocks: BlockNumber = 5 * MINUTES;
pub const NodesSize: u32 = 32;
pub const RootHistorySize: u32 = 30;
}
/// The default types are being injected by [`derive_impl`](`frame_support::derive_impl`) from
/// [`SoloChainDefaultConfig`](`struct@frame_system::config_preludes::SolochainDefaultConfig`),
/// but overridden as needed.
#[derive_impl(frame_system::config_preludes::SolochainDefaultConfig)]
impl frame_system::Config for Runtime {
/// The block type for the runtime.
type Block = Block;
/// Block & extrinsics weights: base values and limits.
type BlockWeights = RuntimeBlockWeights;
/// The maximum length of a block (in bytes).
type BlockLength = RuntimeBlockLength;
/// The identifier used to distinguish between accounts.
type AccountId = AccountId;
/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
type Lookup = AccountIdLookup<AccountId, ()>;
/// The type for storing how many extrinsics an account has signed.
type Nonce = Nonce;
/// The type for hashing blocks and tries.
type Hash = Hash;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = BlockHashCount;
/// The weight of database operations that the runtime can invoke.
type DbWeight = RocksDbWeight;
/// Version of the runtime.
type Version = Version;
/// The data to be stored in an account.
type AccountData = pallet_balances::AccountData<Balance>;
/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
type SS58Prefix = SS58Prefix;
type MaxConsumers = frame_support::traits::ConstU32<16>;
}
parameter_types! {
pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
}
// 1 in 4 blocks (on average, not counting collisions) will be primary babe blocks.
pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4);
/// The BABE epoch configuration at genesis.
pub const BABE_GENESIS_EPOCH_CONFIG: sp_consensus_babe::BabeEpochConfiguration =
sp_consensus_babe::BabeEpochConfiguration {
c: PRIMARY_PROBABILITY,
allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryVRFSlots,
};
impl pallet_babe::Config for Runtime {
type EpochDuration = EpochDurationInBlocks;
type ExpectedBlockTime = ExpectedBlockTime;
type EpochChangeTrigger = pallet_babe::ExternalTrigger;
type DisabledValidators = Session;
type WeightInfo = ();
type MaxAuthorities = MaxAuthorities;
type MaxNominators = ConstU32<0>;
type KeyOwnerProof = sp_session::MembershipProof;
// TODO! specify as pallet_babe::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
// when pallet_autorship and pallet_offences are added
type EquivocationReportSystem = ();
}
parameter_types! {
pub const BondingDuration: EraIndex = polkadot_runtime_common::prod_or_fast!(28, 3);
pub const SessionsPerEra: SessionIndex = polkadot_runtime_common::prod_or_fast!(6, 1);
pub const MaxSetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
}
impl pallet_grandpa::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type WeightInfo = ();
type MaxAuthorities = MaxAuthorities;
type MaxNominators = ConstU32<0>;
type MaxSetIdSessionEntries = MaxSetIdSessionEntries;
type KeyOwnerProof = sp_session::MembershipProof;
type EquivocationReportSystem = ();
}
impl pallet_session::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type ValidatorId = AccountId;
type ValidatorIdOf = ConvertInto;
type ShouldEndSession = Babe;
type NextSessionRotation = Babe;
type SessionManager = ValidatorSet;
type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type Keys = SessionKeys;
type WeightInfo = pallet_session::weights::SubstrateWeight<Runtime>;
}
impl pallet_session::historical::Config for Runtime {
type FullIdentification = AccountId;
type FullIdentificationOf = ConvertInto;
}
impl pallet_timestamp::Config for Runtime {
/// A timestamp: milliseconds since the unix epoch.
type Moment = u64;
type OnTimestampSet = Babe;
type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
type WeightInfo = ();
}
impl pallet_balances::Config for Runtime {
type MaxLocks = ConstU32<50>;
type MaxReserves = ();
type ReserveIdentifier = [u8; 8];
/// The type for recording an account's balance.
type Balance = Balance;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
type DustRemoval = ();
type ExistentialDeposit = ConstU128<EXISTENTIAL_DEPOSIT>;
type AccountStore = System;
type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
type FreezeIdentifier = RuntimeFreezeReason;
type MaxFreezes = VariantCountOf<RuntimeFreezeReason>;
type RuntimeHoldReason = RuntimeHoldReason;
type RuntimeFreezeReason = RuntimeHoldReason;
}
impl pallet_validator_set::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type AddRemoveOrigin = EnsureRoot<AccountId>;
type MaxAuthorities = MaxAuthorities;
type SetKeysCooldownBlocks = SetKeysCooldownBlocks;
type WeightInfo = pallet_validator_set::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub FeeMultiplier: Multiplier = Multiplier::one();
}
impl pallet_transaction_payment::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type OnChargeTransaction = FungibleAdapter<Balances, ()>;
type OperationalFeeMultiplier = ConstU8<5>;
type WeightToFee = IdentityFee<Balance>;
type LengthToFee = IdentityFee<Balance>;
type FeeMultiplierUpdate = ConstFeeMultiplier<FeeMultiplier>;
}
impl pallet_sudo::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const BeefySetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get();
}
impl pallet_beefy::Config for Runtime {
type BeefyId = BeefyId;
type MaxAuthorities = ConstU32<32>;
type MaxNominators = ConstU32<0>;
type MaxSetIdSessionEntries = BeefySetIdSessionEntries;
type OnNewValidatorSet = BeefyMmrLeaf;
type AncestryHelper = BeefyMmrLeaf;
type WeightInfo = ();
type KeyOwnerProof = <Historical as KeyOwnerProofSystem<(KeyTypeId, BeefyId)>>::Proof;
type EquivocationReportSystem = ();
}
parameter_types! {
pub LeafVersion: MmrLeafVersion = MmrLeafVersion::new(0, 0);
}
#[derive(Debug, PartialEq, Eq, Clone, Encode, Decode)]
pub struct LeafExtraData {
extra: H256,
}
pub struct LeafExtraDataProvider;
impl BeefyDataProvider<LeafExtraData> for LeafExtraDataProvider {
fn extra_data() -> LeafExtraData {
LeafExtraData {
extra: H256::zero(),
}
}
}
impl pallet_beefy_mmr::Config for Runtime {
type LeafVersion = LeafVersion;
type BeefyAuthorityToMerkleLeaf = pallet_beefy_mmr::BeefyEcdsaToEthereum;
type LeafExtra = LeafExtraData;
type BeefyDataProvider = LeafExtraDataProvider;
type WeightInfo = ();
}
impl pallet_mmr::Config for Runtime {
const INDEXING_PREFIX: &'static [u8] = pallet_mmr::primitives::INDEXING_PREFIX;
type Hashing = Keccak256;
type LeafData = pallet_beefy_mmr::Pallet<Runtime>;
type OnNewRoot = pallet_beefy_mmr::DepositBeefyDigest<Runtime>;
type WeightInfo = ();
type BlockHashProvider = pallet_mmr::DefaultBlockHashProvider<Runtime>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
}
// Frontier
// TODO: configure pallet author-inherent correctly
impl pallet_author_inherent::Config for Runtime {
type SlotBeacon = ();
type AccountLookup = ();
type CanAuthor = ();
type AuthorId = AccountId;
type WeightInfo = ();
}
parameter_types! {
pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
}
impl pallet_ethereum::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type StateRoot = pallet_ethereum::IntermediateStateRoot<Self::Version>;
type PostLogContent = PostBlockAndTxnHashes;
type ExtraDataLength = ConstU32<30>;
}
// Ported from Moonbeam, please check for reference: https://github.com/moonbeam-foundation/moonbeam/pull/1765
pub struct TransactionPaymentAsGasPrice;
impl FeeCalculator for TransactionPaymentAsGasPrice {
fn min_gas_price() -> (U256, Weight) {
// note: transaction-payment differs from EIP-1559 in that its tip and length fees are not
// scaled by the multiplier, which means its multiplier will be overstated when
// applied to an ethereum transaction
// note: transaction-payment uses both a congestion modifier (next_fee_multiplier, which is
// updated once per block in on_finalize) and a 'WeightToFee' implementation. Our
// runtime implements this as a 'ConstantModifier', so we can get away with a simple
// multiplication here.
let min_gas_price: u128 = TransactionPayment::<Runtime>::next_fee_multiplier()
.saturating_mul_int((WEIGHT_FEE).saturating_mul(WEIGHT_PER_GAS as u128));
(
min_gas_price.into(),
<Runtime as frame_system::Config>::DbWeight::get().reads(1),
)
}
}
pub struct FindAuthorAdapter;
impl FindAuthor<H160> for FindAuthorAdapter {
fn find_author<'a, I>(digests: I) -> Option<H160>
where
I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
{
if let Some(author) = AuthorInherent::find_author(digests) {
return Some(H160::from_slice(&author.encode()[0..20]));
}
None
}
}
datahaven_runtime_common::impl_on_charge_evm_transaction!();
parameter_types! {
pub BlockGasLimit: U256
= U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS);
// pub PrecompilesValue: TemplatePrecompiles<Runtime> = TemplatePrecompiles::<_>::new();
pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0);
pub SuicideQuickClearLimit: u32 = 0;
pub GasLimitPovSizeRatio: u32 = 16;
pub GasLimitStorageGrowthRatio: u64 = 366;
}
impl pallet_evm::Config for Runtime {
type AccountProvider = FrameSystemAccountProvider<Runtime>;
type FeeCalculator = TransactionPaymentAsGasPrice;
type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
type WeightPerGas = WeightPerGas;
type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
type CallOrigin = EnsureAddressRoot<AccountId>;
type WithdrawOrigin = EnsureAddressNever<AccountId>;
type AddressMapping = IdentityAddressMapping;
type Currency = Balances;
type RuntimeEvent = RuntimeEvent;
type PrecompilesType = ();
type PrecompilesValue = ();
type ChainId = EvmChainId;
type BlockGasLimit = BlockGasLimit;
type Runner = pallet_evm::runner::stack::Runner<Self>;
type OnChargeTransaction = OnChargeEVMTransaction<()>;
type OnCreate = ();
type FindAuthor = FindAuthorAdapter;
type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
type GasLimitStorageGrowthRatio = ();
type Timestamp = Timestamp;
type WeightInfo = ();
}
impl pallet_evm_chain_id::Config for Runtime {}
// For tests, benchmarks and fast-runtime configurations we use the mocked fork versions
#[cfg(any(
feature = "std",
feature = "fast-runtime",
feature = "runtime-benchmarks",
test
))]
parameter_types! {
pub const ChainForkVersions: ForkVersions = ForkVersions {
genesis: Fork {
version: [0, 0, 0, 0], // 0x00000000
epoch: 0,
},
altair: Fork {
version: [1, 0, 0, 0], // 0x01000000
epoch: 0,
},
bellatrix: Fork {
version: [2, 0, 0, 0], // 0x02000000
epoch: 0,
},
capella: Fork {
version: [3, 0, 0, 0], // 0x03000000
epoch: 0,
},
deneb: Fork {
version: [4, 0, 0, 0], // 0x04000000
epoch: 0,
},
electra: Fork {
version: [5, 0, 0, 0], // 0x05000000
epoch: 0,
},
};
}
// Holesky: https://github.com/eth-clients/holesky
// Fork versions: https://github.com/eth-clients/holesky/blob/main/metadata/config.yaml
#[cfg(not(any(
feature = "std",
feature = "fast-runtime",
feature = "runtime-benchmarks",
test
)))]
parameter_types! {
pub const ChainForkVersions: ForkVersions = ForkVersions {
genesis: Fork {
version: hex_literal::hex!("01017000"), // 0x01017000
epoch: 0,
},
altair: Fork {
version: hex_literal::hex!("02017000"), // 0x02017000
epoch: 0,
},
bellatrix: Fork {
version: hex_literal::hex!("03017000"), // 0x03017000
epoch: 0,
},
capella: Fork {
version: hex_literal::hex!("04017000"), // 0x04017000
epoch: 256,
},
deneb: Fork {
version: hex_literal::hex!("05017000"), // 0x05017000
epoch: 29696,
},
electra: Fork {
version: hex_literal::hex!("06017000"), // 0x06017000
epoch: 115968,
},
};
}
impl snowbridge_pallet_ethereum_client::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type ForkVersions = ChainForkVersions;
type FreeHeadersInterval = ();
type WeightInfo = ();
}

261
operator/runtime/src/lib.rs Normal file
View file

@ -0,0 +1,261 @@
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
pub mod apis;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarks;
pub mod configs;
extern crate alloc;
use alloc::vec::Vec;
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
traits::{BlakeTwo256, IdentifyAccount, Verify},
MultiAddress,
};
#[cfg(feature = "std")]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
use fp_account::EthereumSignature;
pub use frame_system::Call as SystemCall;
pub use pallet_balances::Call as BalancesCall;
pub use pallet_timestamp::Call as TimestampCall;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
/// to even the core data structures.
pub mod opaque {
use super::*;
use sp_runtime::{
generic,
traits::{BlakeTwo256, Hash as HashT},
};
pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
/// Opaque block header type.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// Opaque block type.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// Opaque block identifier type.
pub type BlockId = generic::BlockId<Block>;
/// Opaque block hash type.
pub type Hash = <BlakeTwo256 as HashT>::Output;
}
impl_opaque_keys! {
pub struct SessionKeys {
pub babe: Babe,
pub grandpa: Grandpa,
pub beefy: Beefy,
}
}
// To learn more about runtime versioning, see:
// https://docs.substrate.io/main-docs/build/upgrade#runtime-versioning
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("datahaven-runtime"),
impl_name: create_runtime_str!("datahaven-runtime"),
authoring_version: 1,
// The version of the runtime specification. A full node will not attempt to use its native
// runtime in substitute for the on-chain Wasm runtime unless all of `spec_name`,
// `spec_version`, and `authoring_version` are the same between Wasm and native.
// This value is set to 100 to notify Polkadot-JS App (https://polkadot.js.org/apps) to use
// the compatible custom types.
spec_version: 100,
impl_version: 1,
apis: apis::RUNTIME_API_VERSIONS,
transaction_version: 1,
state_version: 1,
};
mod block_times {
/// This determines the average expected block time that we are targeting. Blocks will be
/// produced at a minimum duration defined by `SLOT_DURATION`. `SLOT_DURATION` is picked up by
/// `pallet_timestamp` which is in turn picked up by `pallet_babe` to implement `fn
/// slot_duration()`.
///
/// Change this to adjust the block time.
pub const MILLI_SECS_PER_BLOCK: u64 = 6000;
// NOTE: Currently it is not possible to change the slot duration after the chain has started.
// Attempting to do so will brick block production.
pub const SLOT_DURATION: u64 = MILLI_SECS_PER_BLOCK;
}
pub use block_times::*;
// Time is measured by number of blocks.
pub const MINUTES: BlockNumber = 60_000 / (MILLI_SECS_PER_BLOCK as BlockNumber);
pub const HOURS: BlockNumber = MINUTES * 60;
pub const DAYS: BlockNumber = HOURS * 24;
pub const BLOCK_HASH_COUNT: BlockNumber = 2400;
// Unit = the base number of indivisible units for balances
pub const UNIT: Balance = 1_000_000_000_000;
pub const MILLI_UNIT: Balance = 1_000_000_000;
pub const MICRO_UNIT: Balance = 1_000_000;
/// Existential deposit.
pub const EXISTENTIAL_DEPOSIT: Balance = MILLI_UNIT;
/// The version information used to identify this runtime when compiled natively.
#[cfg(feature = "std")]
pub fn native_version() -> NativeVersion {
NativeVersion {
runtime_version: VERSION,
can_author_with: Default::default(),
}
}
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
pub type Signature = EthereumSignature;
/// Some way of identifying an account on the chain. We intentionally make it equivalent
/// to the public key of our transaction signing scheme.
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
/// Balance of an account.
pub type Balance = u128;
/// Index of a transaction in the chain.
pub type Nonce = u32;
/// A hash of some data used by the chain.
pub type Hash = sp_core::H256;
/// An index to a block.
pub type BlockNumber = u32;
/// The address format for describing accounts.
pub type Address = MultiAddress<AccountId, ()>;
/// Block header type as expected by this runtime.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// A Block signed with a Justification
pub type SignedBlock = generic::SignedBlock<Block>;
/// BlockId type as expected by this runtime.
pub type BlockId = generic::BlockId<Block>;
/// The SignedExtension to the basic transaction logic.
pub type SignedExtra = (
frame_system::CheckNonZeroSender<Runtime>,
frame_system::CheckSpecVersion<Runtime>,
frame_system::CheckTxVersion<Runtime>,
frame_system::CheckGenesis<Runtime>,
frame_system::CheckEra<Runtime>,
frame_system::CheckNonce<Runtime>,
frame_system::CheckWeight<Runtime>,
pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
/// The payload being signed in transactions.
pub type SignedPayload = generic::SignedPayload<RuntimeCall, SignedExtra>;
/// All migrations of the runtime, aside from the ones declared in the pallets.
///
/// This can be a tuple of types, each implementing `OnRuntimeUpgrade`.
#[allow(unused_parens)]
type Migrations = ();
/// Executive: handles dispatch to the various modules.
pub type Executive = frame_executive::Executive<
Runtime,
Block,
frame_system::ChainContext<Runtime>,
Runtime,
AllPalletsWithSystem,
Migrations,
>;
// Create the runtime by composing the FRAME pallets that were previously configured.
#[frame_support::runtime]
mod runtime {
#[runtime::runtime]
#[runtime::derive(
RuntimeCall,
RuntimeEvent,
RuntimeError,
RuntimeOrigin,
RuntimeFreezeReason,
RuntimeHoldReason,
RuntimeSlashReason,
RuntimeLockId,
RuntimeTask
)]
pub struct Runtime;
#[runtime::pallet_index(0)]
pub type System = frame_system;
#[runtime::pallet_index(1)]
pub type Timestamp = pallet_timestamp;
#[runtime::pallet_index(2)]
pub type Balances = pallet_balances;
#[runtime::pallet_index(3)]
pub type Babe = pallet_babe;
// TODO! Add the following palllets to the runtime:
// Authorship must be before session in order to note author in the correct session and era.
// pub type Authorship = pallet_authorship;
// pub type Offences = pallet_offences;
#[runtime::pallet_index(4)]
pub type Historical = pallet_session::historical;
#[runtime::pallet_index(5)]
pub type ValidatorSet = pallet_validator_set;
#[runtime::pallet_index(6)]
pub type Session = pallet_session;
#[runtime::pallet_index(7)]
pub type Grandpa = pallet_grandpa;
#[runtime::pallet_index(8)]
pub type TransactionPayment = pallet_transaction_payment;
#[runtime::pallet_index(9)]
pub type Sudo = pallet_sudo;
#[runtime::pallet_index(10)]
pub type Beefy = pallet_beefy;
#[runtime::pallet_index(11)]
pub type BeefyMmrLeaf = pallet_beefy_mmr;
#[runtime::pallet_index(12)]
pub type Mmr = pallet_mmr;
#[runtime::pallet_index(13)]
pub type EthereumBeaconClient = snowbridge_pallet_ethereum_client;
#[runtime::pallet_index(20)]
pub type AuthorInherent = pallet_author_inherent;
#[runtime::pallet_index(31)]
pub type Ethereum = pallet_ethereum;
#[runtime::pallet_index(32)]
pub type Evm = pallet_evm;
#[runtime::pallet_index(33)]
pub type EvmChainId = pallet_evm_chain_id;
}

14
operator/rust-toolchain Normal file
View file

@ -0,0 +1,14 @@
[toolchain]
channel = "1.81.0"
components = [
"cargo",
"clippy",
"rust-analyzer",
"rust-src",
"rust-std",
"rustc-dev",
"rustc",
"rustfmt",
]
targets = [ "wasm32-unknown-unknown" ]
profile = "minimal"

View file

@ -0,0 +1,26 @@
{
"source": {
"beacon": {
"endpoint": "http://127.0.0.1:9596",
"stateEndpoint": "http://127.0.0.1:9596",
"spec": {
"syncCommitteeSize": 512,
"slotsInEpoch": 32,
"epochsPerSyncCommitteePeriod": 256,
"denebForkedEpoch": 0
},
"datastore": {
"location": "",
"maxEntries": 100
}
}
},
"sink": {
"parachain": {
"endpoint": "",
"maxWatchedExtrinsics": 8,
"headerRedundancy": 20
},
"updateSlotInterval": 30
}
}

View file

@ -0,0 +1,61 @@
{
"config": {
"chainId": 11155111,
"homesteadBlock": 0,
"eip150Block": 0,
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0,
"constantinopleBlock": 0,
"petersburgBlock": 0,
"istanbulBlock": 0,
"muirGlacierBlock": 0,
"berlinBlock": 0,
"londonBlock": 0,
"ethash": {},
"terminalTotalDifficulty": 0,
"ShanghaiTime": 0,
"CancunTime": null,
"terminalTotalDifficultyPassed": true
},
"difficulty": "0x9FFE0",
"gasLimit": "80000000",
"alloc": {
"90A987B944Cb1dCcE5564e5FDeCD7a54D3de27Fe": {
"balance": "1000000000000000000000000"
},
"Be68fC2d8249eb60bfCf0e71D5A0d2F2e292c4eD": {
"balance": "100000000000000000000"
},
"89b4AB1eF20763630df9743ACF155865600daFF2": {
"balance": "100000000000000000000"
},
"04E00e6D2e9Ea1E2AF553De02A5172120BFA5c3e": {
"balance": "100000000000000000000"
},
"a255dC78C1510e2c1332fBAC2de848058f479CEE": {
"balance": "100000000000000000000"
},
"ACbd24742b87c34dED607FB87b22401B2Ede167E": {
"balance": "100000000000000000000"
},
"01F6749035e02205768f97e6f1d394Fb6769EC20": {
"balance": "100000000000000000000"
},
"8b66D5499F52D6F1857084A61743dFCB9a712859": {
"balance": "100000000000000000000"
},
"13e16C4e5787f878f98a610EB321170512b134D4": {
"balance": "100000000000000000000"
},
"eEBFA6B9242A19f91a0463291A937a20e3355681": {
"balance": "100000000000000000000"
},
"87D987206180B8f3807Dd90455606eEa85cdB87a": {
"balance": "100000000000000000000"
},
"0xACbd24742b87c34dED607FB87b22401B2Ede167E": {
"balance": "100000000000000000000"
}
}
}

View file

@ -0,0 +1 @@
0xdc6457099f127cf0bac78de8b297df04951281909db4f58b43def7c7151e765d

View file

@ -0,0 +1,24 @@
{
"source": {
"polkadot": {
"endpoint": "ws://127.0.0.1:30444"
}
},
"sink": {
"ethereum": {
"endpoint": "ws://127.0.0.1:8546",
"gas-limit": null
},
"descendants-until-final": 3,
"contracts": {
"BeefyClient": null,
"Gateway": null
}
},
"on-demand-sync": {
"asset-hub-channel-id": "0xc173fac324158e77fb5840738a1a541f633cbec8884c6a601c567d2b376a0539",
"max-tokens": 5,
"refill-amount": 1,
"refill-period": 3600
}
}

View file

@ -0,0 +1,32 @@
[settings]
timeout = 120
[relaychain]
default_command = "${output_bin_dir:-./target/release}/datahaven-node"
chain = "datahaven-local"
default_args = [ "-l=debug", "--pruning=archive", "--enable-offchain-indexing=true" ]
[[relaychain.nodes]]
name = "alice"
validator = true
ws_port = 30444
[[relaychain.nodes]]
name = "bob"
validator = true
[[relaychain.nodes]]
name = "charlie"
validator = true
[[relaychain.nodes]]
name = "dave"
validator = true
[[relaychain.nodes]]
name = "eve"
validator = true
[[relaychain.nodes]]
name = "ferdie"
validator = true

View file

@ -0,0 +1,57 @@
const { ethers } = require('ethers');
async function getBeefyBlock(contractAddress, providerUrl) {
// Connect to the network
const provider = new ethers.JsonRpcProvider(providerUrl);
// BeefyClient ABI - we only need the latestBeefyBlock function
const abi = [
"function latestBeefyBlock() view returns (uint64)",
"function latestMMRRoot() view returns (bytes32)"
];
// Create contract instance
const beefyClient = new ethers.Contract(contractAddress, abi, provider);
try {
// Get the latest beefy block
const blockNumber = await beefyClient.latestBeefyBlock();
const mmrRoot = await beefyClient.latestMMRRoot();
console.log('Latest Beefy Block Number:', blockNumber.toString());
console.log('Latest MMR Root:', mmrRoot);
return {
blockNumber: blockNumber,
mmrRoot: mmrRoot
};
} catch (error) {
console.error('Error fetching beefy block:', error);
throw error;
}
}
// If this file is being run directly (not imported)
if (require.main === module) {
// Get command line arguments
const args = process.argv.slice(2);
const contractAddress = args[0];
const providerUrl = args[1];
if (!contractAddress || !providerUrl) {
console.error('Usage: node beefyBlockClient.js <contract-address> <provider-url>');
console.error('Example: node beefyBlockClient.js 0x1234... http://localhost:8545');
process.exit(1);
}
// Run the script
getBeefyBlock(contractAddress, providerUrl)
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
} else {
// Export for use in other files
module.exports = { getBeefyBlock };
}

1158
operator/test/helpers/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,15 @@
{
"name": "beefy-client-helpers",
"version": "1.0.0",
"description": "Helper scripts for testing BeefyClient",
"scripts": {
"beefy-client": "node getBeefyBlock.js",
"submit-checkpoint": "node submit-checkpoint.js"
},
"dependencies": {
"ethers": "6.13.5",
"@polkadot/api": "15.5.1",
"@polkadot/util": "13.4.3",
"@polkadot/util-crypto": "13.4.3"
}
}

View file

@ -0,0 +1,95 @@
// Script to submit a force_checkpoint extrinsic to the datahaven runtime
const { ApiPromise, WsProvider, Keyring } = require("@polkadot/api");
const { cryptoWaitReady } = require("@polkadot/util-crypto");
const fs = require("fs");
const path = require("path");
// Configuration
const NODE_URL = "ws://127.0.0.1:30444"; // Default Substrate node WebSocket endpoint
async function main() {
// Check if checkpoint file path is provided as an argument
if (process.argv.length < 3) {
console.error("Usage: node submit-checkpoint.js <path-to-checkpoint-json-file>");
console.error("Example: node submit-checkpoint.js ./path/to/checkpoint.json");
process.exit(1);
}
const checkpointFilePath = process.argv[2];
// Wait for the crypto libraries to be ready
await cryptoWaitReady();
// Create a keyring instance (for signing transactions)
const keyring = new Keyring({ type: "sr25519" });
// Add the sudo account (//Alice is the default development account with sudo access)
const sudoAccount = keyring.addFromUri("//Alice");
console.log(`Using account: ${sudoAccount.address}`);
// Connect to the node
console.log(`Connecting to node at ${NODE_URL}...`);
const provider = new WsProvider(NODE_URL);
const api = await ApiPromise.create({ provider });
// Get the chain information
const [chain, nodeName, nodeVersion] = await Promise.all([
api.rpc.system.chain(),
api.rpc.system.name(),
api.rpc.system.version(),
]);
console.log(`Connected to chain ${chain} using ${nodeName} v${nodeVersion}`);
try {
// Read and parse the checkpoint data from the file
const resolvedFilePath = path.resolve(checkpointFilePath);
console.log(`Reading checkpoint data from file: ${resolvedFilePath}`);
if (!fs.existsSync(resolvedFilePath)) {
console.error(`Error: File not found: ${resolvedFilePath}`);
process.exit(1);
}
const fileContent = fs.readFileSync(resolvedFilePath, "utf8");
let checkpointData;
try {
checkpointData = JSON.parse(fileContent);
console.log("Successfully parsed checkpoint data from file");
} catch (parseError) {
console.error(`Error parsing JSON file: ${parseError.message}`);
process.exit(1);
}
// Log the checkpoint data for debugging
console.log("Checkpoint data:", JSON.stringify(checkpointData, null, 2));
// Create the extrinsic for force_checkpoint
// We need to use sudo since force_checkpoint requires root privileges
console.log("Creating extrinsic...");
const extrinsic = api.tx.sudo.sudo(api.tx.ethereumBeaconClient.forceCheckpoint(checkpointData));
// Sign and send the transaction
console.log("Submitting extrinsic...");
const hash = await extrinsic.signAndSend(sudoAccount);
console.log(`Extrinsic submitted with hash: ${hash.toHex()}`);
} catch (error) {
console.error("Error:", error);
} finally {
// Disconnect from the API
await api.disconnect();
console.log("Disconnected from the node");
}
}
// Run the main function
main()
.then(() => {
console.log("Done!");
process.exit(0);
})
.catch((error) => {
console.error("Error in main function:", error);
process.exit(1);
});

View file

@ -0,0 +1,37 @@
#!/usr/bin/env bash
set -eu
source scripts/set-env.sh
build_binary() {
pushd $root_dir
check_local_changes $root_dir
# Check if datahaven binary exists
if [ ! -f "target/release/datahaven-node" ] || [ $changes_detected -eq 1 ]; then
echo "Building datahaven-node..."
cargo build --release --features fast-runtime
fi
# Copy binary to output directory
cp target/release/datahaven-node "$output_bin_dir"
popd
}
changes_detected=0
check_local_changes() {
local dir=$1
cd "$dir"
if git status --untracked-files=no --porcelain . | grep .; then
changes_detected=1
fi
cd -
}
if [ -z "${from_build_binary:-}" ]; then
echo "Building Datahaven Binary"
trap kill_all SIGINT SIGTERM EXIT
build_binary
echo "Datahaven Binary built"
fi

View file

@ -0,0 +1,23 @@
#!/bin/bash
# Exit on any error
set -e
source scripts/set-env.sh
build_snowbridge_contracts() {
if [ -d "$relayer_dir" ]; then
echo "Snowbridge contracts seem to be already downloaded. Skipping downloading again"
else
echo "Downloading datahaven-bridge-relayer"
git clone --recurse-submodules https://github.com/Moonsong-Labs/datahaven-bridge-relayer $relayer_dir
fi
pushd $snowbridge_contracts_dir
forge build
popd
}
if [ -z "${from_start_services:-}" ]; then
echo "Building snowbridge contracts"
build_snowbridge_contracts
fi

View file

@ -0,0 +1,45 @@
#!/usr/bin/env bash
set -eu
source scripts/set-env.sh
build_lodestar() {
if [ -d "$lodestar_dir" ]; then
echo "Lodestar seems to be already downloaded. Skipping downloading again"
else
echo "Downloading Lodestar"
git clone https://github.com/ChainSafe/lodestar $lodestar_dir
pushd $lodestar_dir
git fetch && git checkout $LODESTAR_TAG
popd
fi
echo "Building Lodestar"
pushd $lodestar_dir
yarn install
yarn build
popd
}
build_geth() {
echo "Downloading geth"
if [ -d "$geth_dir" ]; then
echo "Geth seems to be already downloaded. Skipping downloading"
else
git clone https://github.com/ethereum/go-ethereum.git $geth_dir
pushd $geth_dir
git fetch && git checkout $GETH_TAG
popd
fi
echo "Building Geth"
pushd $geth_dir
GOBIN=$output_bin_dir go install ./cmd/geth
GOBIN=$output_bin_dir go install ./cmd/abigen
popd
}
echo "Building ethereum nodes"
build_lodestar
build_geth
echo "ethereum nodes built!"

View file

@ -0,0 +1,43 @@
#!/usr/bin/env bash
set -eu
source scripts/set-env.sh
deploy_command() {
local deploy_script=$1
local contract_dir=$2
pushd "$contract_dir"
if [ "$eth_network" != "localhost" ]; then
forge script \
--rpc-url $eth_endpoint_http \
--broadcast \
--verify \
--etherscan-api-key $etherscan_api_key \
-vvv \
$deploy_script
else
forge script \
--rpc-url $eth_endpoint_http \
--broadcast \
-vvv \
$deploy_script
fi
popd
}
deploy_snowbridge_contracts()
{
deploy_command scripts/DeployLocal.sol:DeployLocal $snowbridge_contracts_dir
pushd "$test_helpers_dir"
contract_dir=$snowbridge_contracts_dir pnpm generateContracts "$output_dir/contracts.json"
popd
echo "Exported contract artifacts: $output_dir/contracts.json"
}
if [ -z "${from_start_services:-}" ]; then
echo "Deploying contracts"
deploy_snowbridge_contracts
fi

View file

@ -0,0 +1,122 @@
#!/bin/bash
# Exit on any error
set -e
# Start ethereum nodes, the nodes must be built first
source scripts/set-env.sh
start_geth() {
if [ "$reset_ethereum" == "true" ]; then
echo "db reset!"
rm -rf "$ethereum_data_dir"
fi
echo "Starting geth local node"
local timestamp="0" #start Cancun from genesis
jq \
--argjson timestamp "$timestamp" \
'
.config.CancunTime = $timestamp
' \
$assets_dir/genesis.json > $output_dir/genesis.json
geth init --datadir "$ethereum_data_dir" --state.scheme=hash "$output_dir/genesis.json"
geth --vmdebug --datadir "$ethereum_data_dir" --networkid 11155111 \
--http --http.api debug,personal,eth,net,web3,txpool,engine,miner --ws --ws.api debug,eth,net,web3 \
--rpc.allow-unprotected-txs --mine \
--miner.etherbase=0xBe68fC2d8249eb60bfCf0e71D5A0d2F2e292c4eD \
--authrpc.addr="127.0.0.1" \
--http.addr="0.0.0.0" \
--ws.addr="0.0.0.0" \
--http.corsdomain '*' \
--allow-insecure-unlock \
--authrpc.jwtsecret $assets_dir/jwtsecret \
--password /dev/null \
--rpc.gascap 0 \
--ws.origins "*" \
--trace "$ethereum_data_dir/trace" \
--gcmode archive \
--syncmode=full \
--state.scheme=hash \
>"$logs_dir/geth.log" 2>&1 &
echo "geth=$!" >> $artifacts_dir/daemons.pid
}
start_lodestar() {
echo "Starting lodestar local node"
local genesisHash=$(curl $eth_endpoint_http \
-X POST \
-H 'Content-Type: application/json' \
-d '{"jsonrpc": "2.0", "id": "1", "method": "eth_getBlockByNumber","params": ["0x0", false]}' | jq -r '.result.hash')
echo "genesisHash is: $genesisHash"
# use gdate here for raw macos without nix
local timestamp=""
if [[ "$(uname)" == "Darwin" && -z "${IN_NIX_SHELL:-}" ]]; then
timestamp=$(gdate -d'+10second' +%s)
else
timestamp=$(date -d'+10second' +%s)
fi
export LODESTAR_PRESET="mainnet"
pushd $artifacts_dir/lodestar
./lodestar dev \
--genesisValidators 8 \
--genesisTime $timestamp \
--startValidators "0..7" \
--enr.ip6 "127.0.0.1" \
--rest.address "0.0.0.0" \
--eth1.providerUrls "http://127.0.0.1:8545" \
--execution.urls "http://127.0.0.1:8551" \
--dataDir "$ethereum_data_dir" \
--reset \
--terminal-total-difficulty-override 0 \
--genesisEth1Hash $genesisHash \
--params.ALTAIR_FORK_EPOCH 0 \
--params.BELLATRIX_FORK_EPOCH 0 \
--params.CAPELLA_FORK_EPOCH 0 \
--params.DENEB_FORK_EPOCH 0 \
--eth1=true \
--rest.namespace="*" \
--jwt-secret $assets_dir/jwtsecret \
--chain.archiveStateEpochFrequency 1 \
>"$logs_dir/lodestar.log" 2>&1 &
echo "lodestar=$!" >> $artifacts_dir/daemons.pid
popd
}
wait_for_geth() {
echo "Waiting for geth to finish syncing/indexing..."
while true; do
syncing=$(curl -s -X POST -H "Content-Type: application/json" \
--data '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}' http://127.0.0.1:8545 | jq '.result')
if [ "$syncing" = "false" ]; then
echo "Geth is no longer syncing."
break
else
echo "Geth is still syncing: $syncing"
fi
sleep 3
done
}
deploy_local() {
# 1. deploy execution client
echo "Starting execution node"
start_geth
echo "Waiting for geth API to be ready"
sleep 5
# 2. deploy consensus client
echo "Starting beacon node"
start_lodestar
wait_for_geth
}
if [ -z "${from_start_services:-}" ]; then
echo "start ethereum only!"
trap kill_all SIGINT SIGTERM EXIT
deploy_local
echo "ethereum local nodes started!"
wait
fi

View file

@ -0,0 +1,22 @@
#!/usr/bin/env bash
set -eu
source scripts/set-env.sh
zombienet_launch() {
zombienet spawn config/zombie-datahaven-local.toml --provider=native --dir="$zombienet_data_dir" 2>&1 &
echo "Waiting for nodes to spawn..."
wait_for_port 30444
}
deploy_datahaven() {
rm -rf $zombienet_data_dir && zombienet_launch
}
if [ -z "${from_start_services:-}" ]; then
echo "start datahaven only!"
trap kill_all SIGINT SIGTERM EXIT
deploy_datahaven
echo "datahaven nodes started"
wait
fi

View file

@ -0,0 +1,33 @@
#!/usr/bin/env bash
set -eu
source scripts/set-env.sh
write_beacon_checkpoint() {
pushd $output_dir > /dev/null
$relayer_bin generate-beacon-checkpoint --config $output_dir/beacon-relay.json --export-json > /dev/null
cat $output_dir/dump-initial-checkpoint.json
popd > /dev/null
}
wait_beacon_chain_ready() {
local initial_beacon_block=""
while [ -z "$initial_beacon_block" ] || [ "$initial_beacon_block" == "0x0000000000000000000000000000000000000000000000000000000000000000" ]; do
initial_beacon_block=$(curl -s "$beacon_endpoint_http/eth/v1/beacon/states/head/finality_checkpoints" |
jq -r '.data.finalized.root' || true)
sleep 3
done
}
submit_beacon_checkpoint() {
pushd "$helpers_dir" > /dev/null
pnpm submit-checkpoint "$1"
popd > /dev/null
}
wait_beacon_chain_ready
# Get the checkpoint data
write_beacon_checkpoint
# Submit the checkpoint using the helper script
echo "Submitting checkpoint to the chain..."
submit_beacon_checkpoint "$output_dir/dump-initial-checkpoint.json"

View file

@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -eu
source scripts/set-env.sh
generate_beefy_checkpoint()
{
pushd "$test_helpers_dir"
pnpm install
pnpm generateBeefyCheckpoint
popd
}
if [ -z "${from_start_services:-}" ]; then
echo "Generating Beefy Checkpoint"
generate_beefy_checkpoint
wait
fi

212
operator/test/scripts/set-env.sh Executable file
View file

@ -0,0 +1,212 @@
#!/usr/bin/env bash
root_dir="$(realpath ..)"
export output_dir="${root_dir}/tmp"
export output_bin_dir="$output_dir/bin"
mkdir -p "$output_bin_dir"
export PATH="$output_bin_dir:$PATH"
scripts_dir="$root_dir/test/scripts"
zombienet_data_dir="$output_dir/zombienet"
ethereum_data_dir="$output_dir/ethereum"
assets_dir="$root_dir/test/assets"
helpers_dir="$root_dir/test/helpers"
artifacts_dir="$output_dir/artifacts"
mkdir -p "$artifacts_dir"
logs_dir="$artifacts_dir/logs"
mkdir -p "$logs_dir"
LODESTAR_TAG="v1.19.0"
GETH_TAG="v1.14.11"
lodestar_dir="$artifacts_dir/lodestar"
geth_dir="$artifacts_dir/geth"
relayer_dir="$artifacts_dir/datahaven-bridge-relayer"
relayer_bin="$relayer_dir/relayer/build/datahaven-bridge-relay"
web_dir="$relayer_dir/snowbridge/web"
snowbridge_contracts_dir="$relayer_dir/snowbridge/contracts"
test_helpers_dir="$web_dir/packages/test-helpers"
eth_network="${ETH_NETWORK:-localhost}"
eth_endpoint_http="${ETH_RPC_ENDPOINT:-http://127.0.0.1:8545}/${INFURA_PROJECT_ID:-}"
eth_endpoint_ws="${ETH_WS_ENDPOINT:-ws://127.0.0.1:8546}/${INFURA_PROJECT_ID:-}"
eth_gas_limit="${ETH_GAS_LIMIT:-5000000}"
etherscan_api_key="${ETHERSCAN_API_KEY:-}"
reset_ethereum="${RESET_ETHEREUM:-true}"
beefy_relay_eth_key="${BEEFY_RELAY_ETH_KEY:-0x935b65c833ced92c43ef9de6bff30703d941bd92a2637cb00cfad389f5862109}"
beacon_endpoint_http="${BEACON_HTTP_ENDPOINT:-http://127.0.0.1:9596}"
# Beacon relay account (//BeaconRelay 5GWFwdZb6JyU46e6ZiLxjGxogAHe8SenX76btfq8vGNAaq8c in testnet)
beacon_relayer_pub_key="${BEACON_RELAYER_PUB_KEY:-0xc46e141b5083721ad5f5056ba1cded69dce4a65f}"
export RELAYCHAIN_ENDPOINT=ws://127.0.0.1:30444
## Deployment key
export PRIVATE_KEY="${DEPLOYER_ETH_KEY:-0x4e9444a6efd6d42725a250b650a781da2737ea308c839eaccb0f7f3dbd2fea77}"
export ETHERSCAN_API_KEY="${ETHERSCAN_API_KEY:-0x0}"
export BRIDGE_HUB_PARAID="${BRIDGE_HUB_PARAID:-1002}"
export BRIDGE_HUB_AGENT_ID="${BRIDGE_HUB_AGENT_ID:-0x03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314}"
export ASSET_HUB_PARAID="${ASSET_HUB_PARAID:-1000}"
export ASSET_HUB_AGENT_ID="${ASSET_HUB_AGENT_ID:-0x81c5ab2571199e3188135178f3c2c8e2d268be1313d029b30f534fa579b69b79}"
export ASSET_HUB_CHANNEL_ID="0xc173fac324158e77fb5840738a1a541f633cbec8884c6a601c567d2b376a0539"
export FOREIGN_TOKEN_DECIMALS=12
## BeefyClient
# For max safety delay should be MAX_SEED_LOOKAHEAD=4 epochs=4*8*6=192s
# but for rococo-local each session is only 20 slots=120s
# so relax somehow here just for quick test
# for production deployment ETH_RANDAO_DELAY should be configured in a more reasonable sense
export RANDAO_COMMIT_DELAY="${ETH_RANDAO_DELAY:-3}"
export RANDAO_COMMIT_EXP="${ETH_RANDAO_EXP:-3}"
export MINIMUM_REQUIRED_SIGNATURES="${MINIMUM_REQUIRED_SIGNATURES:-16}"
export REJECT_OUTBOUND_MESSAGES="${REJECT_OUTBOUND_MESSAGES:-false}"
## Fee
export REGISTER_TOKEN_FEE="${REGISTER_TOKEN_FEE:-200000000000000000}"
export CREATE_ASSET_FEE="${CREATE_ASSET_FEE:-100000000000}"
export RESERVE_TRANSFER_FEE="${RESERVE_TRANSFER_FEE:-100000000000}"
export RESERVE_TRANSFER_MAX_DESTINATION_FEE="${RESERVE_TRANSFER_MAX_DESTINATION_FEE:-10000000000000}"
## Pricing Parameters
export EXCHANGE_RATE="${EXCHANGE_RATE:-2500000000000000}"
export DELIVERY_COST="${DELIVERY_COST:-10000000000}"
export FEE_MULTIPLIER="${FEE_MULTIPLIER:-1000000000000000000}"
## Vault
export GATEWAY_PROXY_INITIAL_DEPOSIT="${GATEWAY_PROXY_INITIAL_DEPOSIT:-10000000000000000000}"
export GATEWAY_STORAGE_KEY="${GATEWAY_STORAGE_KEY:-0xaed97c7854d601808b98ae43079dafb3}"
export GATEWAY_PROXY_CONTRACT="${GATEWAY_PROXY_CONTRACT:-0x87d1f7fdfEe7f651FaBc8bFCB6E086C278b77A7d}"
address_for() {
jq -r ".contracts.${1}.address" "$output_dir/contracts.json"
}
kill_all() {
trap - SIGTERM
kill 0
}
cleanup() {
echo "Cleaning resource"
rm -rf "$output_dir"
mkdir "$output_dir"
mkdir "$output_bin_dir"
mkdir "$ethereum_data_dir"
}
check_port() {
nc -z localhost $1 >/dev/null 2>&1
}
wait_for_port() {
while ! check_port $1; do
echo "Waiting for port $1 to be available..."
sleep 10
done
}
check_node_version() {
local expected_version=$1
if ! [ -x "$(command -v node)" ]; then
echo 'Error: NodeJS is not installed.'
exit 1
fi
node_version=$(node -v) # This does not seem to work in Git Bash on Windows.
# "node -v" outputs version in the format "v18.12.1"
node_version=${node_version:1} # Remove 'v' at the beginning
node_version=${node_version%\.*} # Remove trailing ".*".
node_version=${node_version%\.*} # Remove trailing ".*".
node_version=$(($node_version)) # Convert the NodeJS version number from a string to an integer.
if [ $node_version -lt "$expected_version" ]
then
echo "NodeJS version is lower than $expected_version (it is $node_version), Please update your node installation!"
exit 1
fi
}
vercomp() {
if [[ $1 == $2 ]]
then
echo "Equal"
return
fi
local IFS=.
local i ver1=($1) ver2=($2)
# fill empty fields in ver1 with zeros
for ((i=${#ver1[@]}; i<${#ver2[@]}; i++))
do
ver1[i]=0
done
for ((i=0; i<${#ver1[@]}; i++))
do
if ((10#${ver1[i]:=0} > 10#${ver2[i]:=0}))
then
echo "Greater"
return
fi
if ((10#${ver1[i]} < 10#${ver2[i]}))
then
echo "Less"
return
fi
done
}
check_go_version() {
local expected_version=$1
if ! [ -x "$(command -v go)" ]; then
echo 'Error: Go is not installed.'
exit 1
fi
go_version=$(go version | { read _ _ v _; echo ${v#go}; })
op=$(vercomp "$go_version" "$1")
if [[ $op = "Less" ]]
then
echo "Go version is lower than $expected_version (it is $go_version), Please update your go installation!"
exit 1
fi
}
check_tool() {
if ! [ -x "$(command -v protoc)" ]; then
echo 'Error: protoc is not installed.'
exit 1
fi
if ! [ -x "$(command -v jq)" ]; then
echo 'Error: jq is not installed.'
exit 1
fi
if ! [ -x "$(command -v pnpm)" ]; then
echo 'Error: pnpm is not installed.'
exit 1
fi
if ! [ -x "$(command -v forge)" ]; then
echo 'Error: foundry is not installed.'
exit 1
fi
if ! [ -x "$(command -v yarn)" ]; then
echo 'Error: yarn is not installed.'
exit 1
fi
if [[ "$(uname)" == "Darwin" && -z "${IN_NIX_SHELL:-}" ]]; then
if ! [ -x "$(command -v gdate)" ]; then
echo 'Error: gdate (GNU Date) is not installed.'
exit 1
fi
else
if ! [ -x "$(command -v date)" ]; then
echo 'Error: date is not installed.'
exit 1
fi
fi
check_node_version 20
check_go_version 1.21.2
}

View file

@ -0,0 +1,87 @@
#!/usr/bin/env bash
set -eu
source scripts/set-env.sh
config_relayer() {
data_store_dir="$output_dir/relayer_data"
mkdir -p $data_store_dir
# Configure beefy relay
jq \
--arg k1 "$(address_for BeefyClient)" \
--arg k2 "$(address_for GatewayProxy)" \
--arg eth_endpoint_ws $eth_endpoint_ws \
--arg eth_gas_limit $eth_gas_limit \
--arg assetHubChannelID $ASSET_HUB_CHANNEL_ID \
'
.sink.contracts.BeefyClient = $k1
| .sink.contracts.Gateway = $k2
| .sink.ethereum.endpoint = $eth_endpoint_ws
| .sink.ethereum."gas-limit" = $eth_gas_limit
| ."on-demand-sync"."asset-hub-channel-id" = $assetHubChannelID
' \
config/beefy-relay.json >$output_dir/beefy-relay.json
# Configure beacon relay
local deneb_forked_epoch=0
jq \
--arg beacon_endpoint_http $beacon_endpoint_http \
--argjson deneb_forked_epoch $deneb_forked_epoch \
--arg relay_chain_endpoint $RELAYCHAIN_ENDPOINT \
--arg data_store_dir $data_store_dir \
'
.source.beacon.endpoint = $beacon_endpoint_http
| .source.beacon.spec.denebForkedEpoch = $deneb_forked_epoch
| .sink.parachain.endpoint = $relay_chain_endpoint
| .source.beacon.datastore.location = $data_store_dir
' \
$assets_dir/beacon-relay.json >$output_dir/beacon-relay.json
}
start_relayer() {
echo "Starting relay services"
# Launch beefy relay
(
: >"$output_dir"/beefy-relay.log
while :; do
echo "Starting beefy relay at $(date)"
"${relayer_bin}" run beefy \
--config "$output_dir/beefy-relay.json" \
--ethereum.private-key $beefy_relay_eth_key \
>>"$output_dir"/beefy-relay.log 2>&1 || true
sleep 20
done
) &
# Launch beacon relay
(
: >"$output_dir"/beacon-relay.log
while :; do
echo "Starting beacon relay at $(date)"
"${relayer_bin}" run beacon \
--config $output_dir/beacon-relay.json \
--substrate.private-key "//BeaconRelay" \
>>"$output_dir"/beacon-relay.log 2>&1 || true
sleep 20
done
) &
}
build_relayer() {
echo "Building relayer"
mage -d "$relayer_dir/relayer" build
cp $relayer_bin "$output_bin_dir"
}
deploy_relayer() {
check_tool && build_relayer && config_relayer && start_relayer
}
if [ -z "${from_start_services:-}" ]; then
echo "start relayers only!"
trap kill_all SIGINT SIGTERM EXIT
deploy_relayer
wait
fi

View file

@ -0,0 +1,49 @@
#!/usr/bin/env bash
set -eu
from_start_services=true
# Source environment variables
source scripts/set-env.sh
source scripts/build-binary.sh
trap kill_all SIGINT SIGTERM EXIT
# 0. check required tools
echo "Check building tools"
check_tool
# 1. Buid Datahaven Binary
build_binary
# 2. Start Datahaven Nodes
echo "Starting Datahaven Nodes"
source scripts/deploy-datahaven.sh
deploy_datahaven
# 3. generate beefy checkpoint
echo "Generate beefy checkpoint"
source scripts/generate-beefy-checkpoint.sh
generate_beefy_checkpoint
# 4. Start Ethereum Nodes
# source scripts/build-ethereum.sh
# build_lodestar
# build_geth
# 5. Start Ethereum Nodes
source scripts/deploy-ethereum.sh
echo "Starting Ethereum Nodes"
deploy_local
# 6. Build Snowbridge Contracts
source scripts/build-contracts.sh
echo "Building Snowbridge Contracts"
build_snowbridge_contracts
# 7. Deploy Snowbridge Contracts
source scripts/deploy-contracts.sh
echo "Deploying Snowbridge Contracts"
deploy_snowbridge_contracts
wait