Merge pull request #2917 from paritytech/hc-fix-bridges-subtree

Update Bridges Subtree
This commit is contained in:
Tomasz Drwięga
2021-04-23 20:40:56 +02:00
committed by GitHub
319 changed files with 20764 additions and 13200 deletions
+80 -7
View File
@@ -682,21 +682,33 @@ dependencies = [
]
[[package]]
name = "bp-kusama"
name = "bp-header-chain"
version = "0.1.0"
dependencies = [
"bp-message-lane",
"bp-runtime",
"bp-test-utils",
"finality-grandpa",
"frame-support",
"frame-system",
"sp-api",
"parity-scale-codec",
"serde",
"sp-core",
"sp-finality-grandpa",
"sp-runtime",
"sp-std",
]
[[package]]
name = "bp-message-lane"
name = "bp-kusama"
version = "0.1.0"
dependencies = [
"bp-messages",
"bp-polkadot-core",
"bp-runtime",
"sp-api",
"sp-std",
]
[[package]]
name = "bp-messages"
version = "0.1.0"
dependencies = [
"bp-runtime",
@@ -710,14 +722,43 @@ dependencies = [
name = "bp-polkadot"
version = "0.1.0"
dependencies = [
"bp-message-lane",
"bp-messages",
"bp-polkadot-core",
"bp-runtime",
"sp-api",
"sp-std",
]
[[package]]
name = "bp-polkadot-core"
version = "0.1.0"
dependencies = [
"bp-messages",
"bp-runtime",
"frame-support",
"frame-system",
"hex",
"parity-scale-codec",
"sp-api",
"sp-core",
"sp-runtime",
"sp-std",
"sp-version",
]
[[package]]
name = "bp-rococo"
version = "0.1.0"
dependencies = [
"bp-header-chain",
"bp-messages",
"bp-polkadot-core",
"bp-runtime",
"parity-scale-codec",
"sp-api",
"sp-runtime",
"sp-std",
"sp-version",
]
[[package]]
@@ -725,12 +766,44 @@ name = "bp-runtime"
version = "0.1.0"
dependencies = [
"frame-support",
"hash-db",
"num-traits",
"parity-scale-codec",
"sp-core",
"sp-io",
"sp-runtime",
"sp-state-machine",
"sp-std",
"sp-trie",
]
[[package]]
name = "bp-test-utils"
version = "0.1.0"
dependencies = [
"bp-header-chain",
"ed25519-dalek",
"finality-grandpa",
"parity-scale-codec",
"sp-application-crypto",
"sp-finality-grandpa",
"sp-runtime",
"sp-std",
]
[[package]]
name = "bp-westend"
version = "0.1.0"
dependencies = [
"bp-header-chain",
"bp-messages",
"bp-polkadot-core",
"bp-runtime",
"parity-scale-codec",
"sp-api",
"sp-runtime",
"sp-std",
"sp-version",
]
[[package]]
+4 -2
View File
@@ -26,8 +26,10 @@ tempfile = "3.2.0"
[workspace]
members = [
"bridges/primitives/kusama",
"bridges/primitives/polkadot",
"bridges/primitives/chain-kusama",
"bridges/primitives/chain-polkadot",
"bridges/primitives/chain-rococo",
"bridges/primitives/chain-westend",
"bridges/primitives/runtime",
"cli",
"core-primitives",
+2
View File
@@ -14,6 +14,8 @@ update_configs:
dependency_name: "frame-*"
- match:
dependency_name: "pallet-*"
- match:
dependency_name: "node-inspect"
automerged_updates:
- match:
update_type: "all"
+9 -2
View File
@@ -10,12 +10,19 @@ on:
tags:
- v*
paths-ignore:
- '**/README.md'
- '**.md'
- diagrams/*
- docs/*
jobs:
cargo-deny:
runs-on: ubuntu-latest
strategy:
matrix:
checks:
- advisories
- bans licenses sources
# Prevent sudden announcement of a new advisory from failing CI:
continue-on-error: ${{ matrix.checks == 'advisories' }}
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.4.1
@@ -29,4 +36,4 @@ jobs:
- name: Cargo deny
uses: EmbarkStudios/cargo-deny-action@v1
with:
command: "check --hide-inclusion-graph"
command: check ${{ matrix.checks }}
+5 -1
View File
@@ -8,7 +8,7 @@ on:
tags:
- v*
paths-ignore:
- '**/README.md'
- '**.md'
- diagrams/*
- docs/*
schedule: # Weekly build
@@ -21,17 +21,21 @@ jobs:
env:
RUST_BACKTRACE: full
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.4.1
with:
access_token: ${{ github.token }}
- name: Checkout sources & submodules
uses: actions/checkout@master
with:
fetch-depth: 5
submodules: recursive
- name: Add rustfmt
run: rustup component add rustfmt
- name: rust-fmt check
uses: actions-rs/cargo@master
with:
+60 -33
View File
@@ -1,49 +1,76 @@
name: Publish Dependencies to Docker hub
name: Publish Dependencies to Docker hub
on:
push:
tags:
- v*
paths-ignore:
- '**/README.md'
- '**.md'
- diagrams/*
- docs/*
schedule: # Weekly build
- cron: '0 0 * * 0'
schedule: # Weekly build
- cron: '0 0 * * 0'
jobs:
## Publish to Docker hub
## Publish to Docker hub
publish:
name: Publishing
runs-on: ubuntu-latest
name: Publishing
runs-on: ubuntu-latest
container:
image: docker:git
image: docker:git
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.4.1
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.4.1
with:
access_token: ${{ github.token }}
- name: Checkout sources & submodules
uses: actions/checkout@master
access_token: ${{ github.token }}
- name: Checkout sources & submodules
uses: actions/checkout@v2
with:
fetch-depth: 5
submodules: recursive
- name: Build and push dependencies
uses: docker/build-push-action@v1
fetch-depth: 5
submodules: recursive
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_USER }}
password: ${{ secrets.DOCKER_PASSWORD }}
repository: paritytech/bridge-dependencies
dockerfile: deployments/BridgeDeps.Dockerfile
tag_with_ref: true
tag_with_sha: true
labels:
org.opencontainers.image.source="https://github.com/paritytech/parity-bridges-common",
org.opencontainers.image.authors="devops-team@parity.io",
org.opencontainers.image.vendor="Parity Technologies",
org.opencontainers.image.url="https://github.com/paritytech/parity-bridges-common",
org.opencontainers.image.documentation="https://github.com/paritytech/parity-bridges-common/README.md",
org.opencontainers.image.title=${{ matrix.project }},
org.opencontainers.image.description="${{ matrix.project }} - component of Parity Bridges Common",
org.opencontainers.image.licenses="GPL-3.0 License"
add_git_labels: true
username: ${{ secrets.DOCKER_USER }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Prepare
id: prep
run: |
DOCKER_IMAGE=paritytech/bridge-dependencies
VERSION=latest
if [[ $GITHUB_REF == refs/tags/* ]]; then
VERSION=${GITHUB_REF#refs/tags/}
elif [[ $GITHUB_REF == refs/heads/* ]]; then
VERSION=$(echo ${GITHUB_REF#refs/heads/} | sed -r 's#/+#-#g')
fi
TAGS=${DOCKER_IMAGE}:${VERSION}
TAGS=$TAGS,${DOCKER_IMAGE}:sha-${GITHUB_SHA::8}
echo ::set-output name=TAGS::${TAGS}
echo ::set-output name=DATE::$(date +%d-%m-%Y)
- name: Build and push
uses: docker/build-push-action@v2
with:
file: deployments/BridgeDeps.Dockerfile
push: true
cache-from: type=registry,ref=paritytech/bridge-dependencies:latest
cache-to: type=inline
tags: ${{ steps.prep.outputs.TAGS }}
labels: |
org.opencontainers.image.title=bridge-dependencies
org.opencontainers.image.description=bridge-dependencies - component of Parity Bridges Common
org.opencontainers.image.source=${{ github.event.repository.html_url }}
org.opencontainers.image.url=https://github.com/paritytech/parity-bridges-common
org.opencontainers.image.documentation=https://github.com/paritytech/parity-bridges-common/README.md
org.opencontainers.image.created=${{ steps.prep.outputs.DATE }}
org.opencontainers.image.revision=${{ github.sha }}
org.opencontainers.image.authors=devops-team@parity.io
org.opencontainers.image.vendor=Parity Technologies
org.opencontainers.image.licenses=GPL-3.0 License
+59 -42
View File
@@ -1,20 +1,20 @@
name: Publish images to Docker hub
name: Publish images to Docker hub
on:
push:
tags:
- v*
paths-ignore:
- '**/README.md'
- '**.md'
- diagrams/*
- docs/*
schedule: # Nightly build
- cron: '0 1 * * *'
schedule: # Nightly build
- cron: '0 1 * * *'
jobs:
## Publish to Docker hub
## Publish to Docker hub
publish:
name: Publishing
name: Publishing
strategy:
matrix:
project:
@@ -31,46 +31,63 @@ jobs:
healthcheck: http://localhost:9616/metrics
- project: substrate-relay
healthcheck: http://localhost:9616/metrics
runs-on: ubuntu-latest
container:
image: docker:git
runs-on: ubuntu-latest
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.4.1
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.4.1
with:
access_token: ${{ github.token }}
- name: Checkout sources & submodules
uses: actions/checkout@master
access_token: ${{ github.token }}
- name: Checkout sources & submodules
uses: actions/checkout@v2
with:
fetch-depth: 5
submodules: recursive
- name: Set vars
id: vars
run: |
echo ::set-output name=DATE::$(date +%d-%m-%Y)
if [[ ${GITHUB_REF} = refs/tags/* ]]
then
echo ::set-output name=TAG::${GITHUB_REF#refs/tags/}
else
echo ::set-output name=TAG::nightly-$(date +%d-%m-%Y)
fetch-depth: 5
submodules: recursive
- name: Prepare
id: prep
run: |
if [[ $GITHUB_REF == refs/tags/* ]]; then
VERSION=${GITHUB_REF#refs/tags/}
elif [[ $GITHUB_REF == refs/heads/* ]]; then
VERSION=$(echo ${GITHUB_REF#refs/heads/} | sed -r 's#/+#-#g')
fi
- name: Build and push ${{ matrix.project }}
uses: docker/build-push-action@v1
TAGS="${VERSION} sha-${GITHUB_SHA::8} latest"
echo ::set-output name=TAGS::${VERSION}
echo ::set-output name=TAGS::${TAGS}
echo ::set-output name=DATE::$(date +%d-%m-%Y)
- name: Workaround rootless build
run: |
sudo apt-get install fuse-overlayfs
mkdir -vp ~/.config/containers
printf "[storage.options]\nmount_program=\"/usr/bin/fuse-overlayfs\"" > ~/.config/containers/storage.conf
- name: Build image for ${{ matrix.project }}
uses: redhat-actions/buildah-build@v2.2
with:
image: ${{ matrix.project }}
tags: ${{ steps.prep.outputs.TAGS }}
dockerfiles: ./Dockerfile
build-args: |
PROJECT=${{ matrix.project }}
HEALTH=${{ matrix.healthcheck }}
VCS_REF=sha-${GITHUB_SHA::8}
BUILD_DATE=${{ steps.prep.outputs.DATE }}
VERSION=${{ steps.prep.outputs.VERSION }}
- name: Push ${{ matrix.project }} image to docker.io
id: push-to-dockerhub
uses: redhat-actions/push-to-registry@v2.1.1
with:
registry: docker.io/paritytech
image: ${{ matrix.project }}
tags: ${{ steps.prep.outputs.TAGS }}
username: ${{ secrets.DOCKER_USER }}
password: ${{ secrets.DOCKER_PASSWORD }}
repository: paritytech/${{ matrix.project }}
build_args: PROJECT=${{ matrix.project }}, HEALTH=${{ matrix.healthcheck }}
tags: ${{ steps.vars.outputs.TAG }}, latest
labels:
org.opencontainers.image.created=${{ steps.vars.outputs.DATE }},
org.opencontainers.image.source="https://github.com/paritytech/parity-bridges-common",
org.opencontainers.image.authors="devops-team@parity.io",
org.opencontainers.image.vendor="Parity Technologies",
org.opencontainers.image.url="https://github.com/paritytech/parity-bridges-common",
org.opencontainers.image.documentation="https://github.com/paritytech/parity-bridges-common/README.md",
org.opencontainers.image.version=${{ steps.vars.outputs.TAG }},
org.opencontainers.image.title=${{ matrix.project }},
org.opencontainers.image.description="${{ matrix.project }} - component of Parity Bridges Common",
org.opencontainers.image.licenses="GPL-3.0 License"
add_git_labels: true
- name: Check the image
run: |
echo "New image has been pushed to ${{ steps.push-to-dockerhub.outputs.registry-path }}"
+28 -12
View File
@@ -8,7 +8,7 @@ on:
tags:
- v*
paths-ignore:
- '**/README.md'
- '**.md'
- diagrams/*
- docs/*
schedule: # Weekly build
@@ -23,27 +23,30 @@ jobs:
toolchain:
- stable
#- beta
- nightly
- nightly-2021-04-10
runs-on: ubuntu-latest
env:
RUST_BACKTRACE: full
NIGHTLY: nightly #if necessary, specify the version, nightly-2020-10-04, etc.
NIGHTLY: nightly-2021-04-10 #if necessary, specify the version, nightly-2020-10-04, etc.
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.4.1
with:
access_token: ${{ github.token }}
- name: Checkout sources & submodules
uses: actions/checkout@master
with:
fetch-depth: 5
submodules: recursive
- name: Install Toolchain
run: rustup toolchain add $NIGHTLY
- name: Add WASM Utilities
run: rustup target add wasm32-unknown-unknown --toolchain $NIGHTLY
- name: Rust Cache
uses: Swatinem/rust-cache@v1.2.0
- name: Checking rust-${{ matrix.toolchain }}
uses: actions-rs/cargo@master
with:
@@ -66,13 +69,14 @@ jobs:
with:
command: check
toolchain: ${{ matrix.toolchain }}
args: --manifest-path ./bin/rialto/node/Cargo.toml --no-default-features --features runtime-benchmarks --verbose
args: -p rialto-runtime --features runtime-benchmarks --verbose
- name: Check Millau benchmarks runtime ${{ matrix.platform }} rust-${{ matrix.toolchain }}
uses: actions-rs/cargo@master
with:
command: check
toolchain: ${{ matrix.toolchain }}
args: --manifest-path ./bin/millau/node/Cargo.toml --no-default-features --features runtime-benchmarks --verbose
args: -p millau-runtime --features runtime-benchmarks --verbose
## Build Stage
build:
@@ -86,23 +90,26 @@ jobs:
runs-on: ubuntu-latest
env:
RUST_BACKTRACE: full
NIGHTLY: nightly #if necessary, specify the version, nightly-2020-10-04, etc.
NIGHTLY: nightly-2021-04-10 #if necessary, specify the version, nightly-2020-10-04, etc.
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.4.1
with:
access_token: ${{ github.token }}
- name: Checkout sources & submodules
uses: actions/checkout@master
with:
fetch-depth: 5
submodules: recursive
- name: Install Toolchain
run: rustup toolchain add $NIGHTLY
- name: Add WASM Utilities
run: rustup target add wasm32-unknown-unknown --toolchain $NIGHTLY
- name: Rust Cache
uses: Swatinem/rust-cache@v1.2.0
- name: Building rust-${{ matrix.toolchain }}
uses: actions-rs/cargo@master
if: github.ref == 'refs/heads/master'
@@ -110,6 +117,7 @@ jobs:
command: build
toolchain: ${{ matrix.toolchain }}
args: --all --verbose
- name: Prepare artifacts
if: github.ref == 'refs/heads/master'
run: |
@@ -119,6 +127,7 @@ jobs:
mv -v target/debug/ethereum-poa-relay ./artifacts/;
mv -v target/debug/substrate-relay ./artifacts/;
shell: bash
- name: Upload artifacts
if: github.ref == 'refs/heads/master'
uses: actions/upload-artifact@v1
@@ -132,28 +141,35 @@ jobs:
runs-on: ubuntu-latest
env:
RUST_BACKTRACE: full
NIGHTLY: nightly #if necessary, specify the version, nightly-2020-10-04, etc.
NIGHTLY: nightly-2021-04-10 #if necessary, specify the version, nightly-2020-10-04, etc.
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.4.1
with:
access_token: ${{ github.token }}
- name: Checkout sources & submodules
uses: actions/checkout@master
with:
fetch-depth: 5
submodules: recursive
- name: Install Toolchain
run: rustup toolchain add $NIGHTLY
- name: Add WASM Utilities
run: rustup target add wasm32-unknown-unknown --toolchain $NIGHTLY
- name: Add clippy
run: rustup component add clippy --toolchain $NIGHTLY
- name: Rust Cache
uses: Swatinem/rust-cache@v1.2.0
- name: Clippy
uses: actions-rs/cargo@master
with:
command: clippy
toolchain: nightly #if necessary, specify the version, nightly-2020-10-04, etc.
toolchain: nightly-2021-04-10 #if necessary, specify the version, nightly-2020-10-04, etc.
args: --all-targets -- -D warnings
+3
View File
@@ -2,6 +2,9 @@
**/.env
**/.env2
**/rust-toolchain
hfuzz_target
hfuzz_workspace
**/Cargo.lock
**/*.rs.bk
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
+80
View File
@@ -0,0 +1,80 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers
pledge to making participation in our project and our community a harassment-free experience for
everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity
and expression, level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit
permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
### Facilitation, Not Strongarming
We recognise that this software is merely a tool for users to create and maintain their blockchain
of preference. We see that blockchains are naturally community platforms with users being the
ultimate decision makers. We assert that good software will maximise user agency by facilitate
user-expression on the network. As such:
- This project will strive to give users as much choice as is both reasonable and possible over what
protocol they adhere to; but
- use of the project's technical forums, commenting systems, pull requests and issue trackers as a
means to express individual protocol preferences is forbidden.
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are
expected to take appropriate and fair corrective action in response to any instances of unacceptable
behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits,
code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or
to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is
representing the project or its community. Examples of representing a project or community include
using an official project e-mail address, posting via an official social media account, or acting as
an appointed representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting
the project team at admin@parity.io. All complaints will be reviewed and investigated and will
result in a response that is deemed necessary and appropriate to the circumstances. The project team
is obligated to maintain confidentiality with regard to the reporter of an incident. Further
details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face
temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at
https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
+1576 -1040
View File
File diff suppressed because it is too large Load Diff
+28 -28
View File
@@ -8,33 +8,10 @@
#
# See the `deployments/README.md` for all the available `PROJECT` values.
# This first stage prepares our dependencies to be built by `cargo-chef`.
FROM rust as planner
WORKDIR /parity-bridges-common
RUN cargo install cargo-chef --version 0.1.13
COPY . .
RUN cargo chef prepare --recipe-path recipe.json
# This second stage is where the dependencies actually get built.
# The reason we split it from the first stage is so that the `COPY . .`
# step doesn't blow our cache.
FROM paritytech/bridge-dependencies AS cacher
WORKDIR /parity-bridges-common
RUN cargo install cargo-chef --version 0.1.13
COPY --from=planner /parity-bridges-common/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json
# In this third stage we go ahead and build the actual binary we want.
# This should be fairly quick since the dependencies are being built and
# cached in the previous stage.
FROM paritytech/bridge-dependencies as builder
WORKDIR /parity-bridges-common
RUN cargo install cargo-chef --version 0.1.13
COPY . .
COPY --from=cacher /parity-bridges-common/target target
COPY --from=cacher $CARGO_HOME $CARGO_HOME
ARG PROJECT=ethereum-poa-relay
RUN cargo build --release --verbose -p ${PROJECT}
@@ -42,17 +19,23 @@ RUN strip ./target/release/${PROJECT}
# In this final stage we copy over the final binary and do some checks
# to make sure that everything looks good.
FROM ubuntu:xenial as runtime
FROM ubuntu:20.04 as runtime
# show backtraces
ENV RUST_BACKTRACE 1
ENV DEBIAN_FRONTEND=noninteractive
RUN set -eux; \
apt-get update && \
apt-get install -y libssl-dev curl
RUN groupadd -g 1000 user \
&& useradd -u 1000 -g user -s /bin/sh -m user
apt-get install -y curl ca-certificates && \
apt-get install -y --no-install-recommends libssl-dev && \
update-ca-certificates && \
groupadd -g 1000 user && \
useradd -u 1000 -g user -s /bin/sh -m user && \
# apt clean up
apt-get autoremove -y && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
# switch to non-root user
USER user
@@ -69,3 +52,20 @@ RUN ./${PROJECT} --version
ENV PROJECT=$PROJECT
ENTRYPOINT ["/home/user/bridge-entrypoint.sh"]
# metadata
ARG VCS_REF=master
ARG BUILD_DATE=""
ARG VERSION=""
LABEL org.opencontainers.image.title="${PROJECT}" \
org.opencontainers.image.description="${PROJECT} - component of Parity Bridges Common" \
org.opencontainers.image.source="https://github.com/paritytech/parity-bridges-common/blob/${VCS_REF}/Dockerfile" \
org.opencontainers.image.url="https://github.com/paritytech/parity-bridges-common/blob/${VCS_REF}/Dockerfile" \
org.opencontainers.image.documentation="https://github.com/paritytech/parity-bridges-common/blob/${VCS_REF}/README.md" \
org.opencontainers.image.created="${BUILD_DATE}" \
org.opencontainers.image.version="${VERSION}" \
org.opencontainers.image.revision="${VCS_REF}" \
org.opencontainers.image.authors="devops-team@parity.io" \
org.opencontainers.image.vendor="Parity Technologies" \
org.opencontainers.image.licenses="GPL-3.0 License"
+23 -19
View File
@@ -11,6 +11,7 @@ Substrate chains or Ethereum Proof-of-Authority chains.
🚧 The bridges are currently under construction - a hardhat is recommended beyond this point 🚧
## Contents
- [Installation](#installation)
- [High-Level Architecture](#high-level-architecture)
- [Project Layout](#project-layout)
@@ -19,6 +20,7 @@ Substrate chains or Ethereum Proof-of-Authority chains.
- [Community](#community)
## Installation
To get up and running you need both stable and nightly Rust. Rust nightly is used to build the Web
Assembly (WASM) runtime for the node. You can configure the WASM support as so:
@@ -70,6 +72,7 @@ Take a look at [Bridge High Level Documentation](./docs/high-level-overview.md)
description of the bridge interaction.
## Project Layout
Here's an overview of how the project is laid out. The main bits are the `node`, which is the actual
"blockchain", the `modules` which are used to build the blockchain's logic (a.k.a the runtime) and
the `relays` which are used to pass messages between chains.
@@ -83,15 +86,16 @@ the `relays` which are used to pass messages between chains.
│ └── ...
├── modules // Substrate Runtime Modules (a.k.a Pallets)
│ ├── ethereum // Ethereum PoA Header Sync Module
│ ├── substrate // Substrate Based Chain Header Sync Module
│ ├── message-lane // Cross Chain Message Passing
│ ├── grandpa // On-Chain GRANDPA Light Client
│ ├── messages // Cross Chain Message Passing
│ ├── dispatch // Target Chain Message Execution
│ └── ...
├── primitives // Code shared between modules, runtimes, and relays
│ └── ...
├── relays // Application for sending headers and messages between chains
│ └── ...
└── scripts // Useful development and maintenence scripts
```
```
## Running the Bridge
@@ -99,9 +103,9 @@ To run the Bridge you need to be able to connect the bridge relay node to the RP
on each side of the bridge (source and target chain).
There are 3 ways to run the bridge, described below:
- building & running from source,
- building or using Docker images for each individual component,
- running a Docker Compose setup (recommended).
- building & running from source,
- building or using Docker images for each individual component,
- running a Docker Compose setup (recommended).
### Using the Source
@@ -154,20 +158,20 @@ Then we need to initialize and run the relayer:
```bash
docker run --network=host -it \
paritytech/substrate-relay initialize-rialto-headers-bridge-in-millau \
--millau-host localhost \
--millau-port 9945 \
--rialto-host localhost \
--rialto-port 9944 \
--millau-signer //Alice
paritytech/substrate-relay init-bridge RialtoToMillau \
--target-host localhost \
--target-port 9945 \
--source-host localhost \
--source-port 9944 \
--target-signer //Alice
docker run --network=host -it \
paritytech/substrate-relay rialto-headers-to-millau \
--millau-host localhost \
--millau-port 9945 \
--rialto-host localhost \
--rialto-port 9944 \
--millau-signer //Bob \
paritytech/substrate-relay relay-headers RialtoToMillau \
--target-host localhost \
--target-port 9945 \
--source-host localhost \
--source-port 9944 \
--target-signer //Bob \
```
You should now see the relayer submitting headers from the Millau chain to the Rialto chain.
@@ -196,6 +200,7 @@ monitoring dashboards, etc. see the [Deployments README](./deployments/README.md
A straightforward way to interact with and test the bridge is sending messages. This is explained
in the [send message](./docs/send-message.md) document.
## Community
Main hangout for the community is [Element](https://element.io/) (formerly Riot). Element is a chat
@@ -208,4 +213,3 @@ Element channel.
The [Substrate Technical](https://app.element.io/#/room/#substrate-technical:matrix.org) Element
channel is most suited for discussions regarding Substrate itself.
+9 -8
View File
@@ -15,17 +15,18 @@ structopt = "0.3.21"
# Bridge dependencies
bp-message-lane = { path = "../../../primitives/message-lane" }
bp-millau= { path = "../../../primitives/millau" }
bp-messages = { path = "../../../primitives/messages" }
bp-millau= { path = "../../../primitives/chain-millau" }
bp-runtime = { path = "../../../primitives/runtime" }
millau-runtime = { path = "../runtime" }
pallet-message-lane = { path = "../../../modules/message-lane" }
pallet-message-lane-rpc = { path = "../../../modules/message-lane/rpc" }
pallet-bridge-messages = { path = "../../../modules/messages" }
# Substrate Dependencies
frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "master" }
frame-benchmarking-cli = { git = "https://github.com/paritytech/substrate", branch = "master" }
node-inspect = { git = "https://github.com/paritytech/substrate", branch = "master" }
pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-basic-authorship = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-cli = { git = "https://github.com/paritytech/substrate", branch = "master", features = ["wasmtime"] }
sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "master" }
@@ -35,21 +36,21 @@ sc-executor = { git = "https://github.com/paritytech/substrate", branch = "maste
sc-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-finality-grandpa-rpc = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-keystore = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-service = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-rpc = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-service = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-telemetry = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-consensus = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-consensus-aura = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-inherents = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-inherents = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" }
substrate-frame-rpc-system = { git = "https://github.com/paritytech/substrate", branch = "master" }
[build-dependencies]
build-script-utils = { package = "substrate-build-script-utils", version = "2.0" }
substrate-build-script-utils = "3.0.0"
frame-benchmarking-cli = { git = "https://github.com/paritytech/substrate", branch = "master" }
vergen = "3.1.0"
[features]
default = []
+4 -6
View File
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -14,12 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
use vergen::{generate_cargo_keys, ConstantsFlags};
const ERROR_MSG: &str = "Failed to generate metadata files";
use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};
fn main() {
generate_cargo_keys(ConstantsFlags::SHA_SHORT).expect(ERROR_MSG);
generate_cargo_keys();
build_script_utils::rerun_if_git_head_changed();
rerun_if_git_head_changed();
}
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -16,7 +16,7 @@
use bp_millau::derive_account_from_rialto_id;
use millau_runtime::{
AccountId, AuraConfig, BalancesConfig, BridgeRialtoConfig, GenesisConfig, GrandpaConfig, SessionConfig,
AccountId, AuraConfig, BalancesConfig, BridgeWestendGrandpaConfig, GenesisConfig, GrandpaConfig, SessionConfig,
SessionKeys, Signature, SudoConfig, SystemConfig, WASM_BINARY,
};
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
@@ -122,7 +122,10 @@ impl Alternative {
get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
get_account_id_from_seed::<sr25519::Public>("George//stash"),
get_account_id_from_seed::<sr25519::Public>("Harry//stash"),
pallet_message_lane::Module::<millau_runtime::Runtime, pallet_message_lane::DefaultInstance>::relayer_fund_account_id(),
pallet_bridge_messages::Pallet::<
millau_runtime::Runtime,
pallet_bridge_messages::DefaultInstance,
>::relayer_fund_account_id(),
derive_account_from_rialto_id(bp_runtime::SourceAccount::Account(
get_account_id_from_seed::<sr25519::Public>("Dave"),
)),
@@ -151,31 +154,33 @@ fn testnet_genesis(
_enable_println: bool,
) -> GenesisConfig {
GenesisConfig {
frame_system: Some(SystemConfig {
frame_system: SystemConfig {
code: WASM_BINARY.to_vec(),
changes_trie_config: Default::default(),
}),
pallet_balances: Some(BalancesConfig {
},
pallet_balances: BalancesConfig {
balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 50)).collect(),
}),
pallet_aura: Some(AuraConfig {
},
pallet_aura: AuraConfig {
authorities: Vec::new(),
}),
pallet_grandpa: Some(GrandpaConfig {
},
pallet_grandpa: GrandpaConfig {
authorities: Vec::new(),
}),
pallet_substrate_bridge: Some(BridgeRialtoConfig {
// We'll initialize the pallet with a dispatchable instead.
init_data: None,
owner: Some(root_key.clone()),
}),
pallet_sudo: Some(SudoConfig { key: root_key }),
pallet_session: Some(SessionConfig {
},
pallet_sudo: SudoConfig { key: root_key },
pallet_session: SessionConfig {
keys: initial_authorities
.iter()
.map(|x| (x.0.clone(), x.0.clone(), session_keys(x.1.clone(), x.2.clone())))
.collect::<Vec<_>>(),
}),
},
pallet_bridge_grandpa_Instance1: BridgeWestendGrandpaConfig {
// for our deployments to avoid multiple same-nonces transactions:
// //Alice is already used to initialize Rialto<->Millau bridge
// => let's use //George to initialize Westend->Millau bridge
owner: Some(get_account_id_from_seed::<sr25519::Public>("George")),
..Default::default()
},
}
}
+6 -3
View File
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -31,6 +31,7 @@ pub struct Cli {
pub enum Subcommand {
/// Key management cli utilities
Key(sc_cli::KeySubcommand),
/// Verify a signature for a message, provided on STDIN, with a given (public or secret) key.
Verify(sc_cli::VerifyCmd),
@@ -61,7 +62,9 @@ pub enum Subcommand {
/// Revert the chain to a previous state.
Revert(sc_cli::RevertCmd),
/// The custom benchmark subcommmand benchmarking runtime pallets.
#[structopt(name = "benchmark", about = "Benchmark runtime pallets.")]
/// Inspect blocks or extrinsics.
Inspect(node_inspect::cli::InspectCmd),
/// Benchmark runtime pallets.
Benchmark(frame_benchmarking_cli::BenchmarkCmd),
}
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -17,7 +17,7 @@
use crate::cli::{Cli, Subcommand};
use crate::service;
use crate::service::new_partial;
use millau_runtime::Block;
use millau_runtime::{Block, RuntimeApi};
use sc_cli::{ChainSpec, Role, RuntimeVersion, SubstrateCli};
use sc_service::PartialComponents;
@@ -154,6 +154,10 @@ pub fn run() -> sc_cli::Result<()> {
Ok((cmd.run(client, backend), task_manager))
})
}
Some(Subcommand::Inspect(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run::<Block, RuntimeApi, service::Executor>(config))
}
None => {
let runner = cli.create_runner(&cli.run)?;
runner.run_node_until_exit(|config| async move {
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
+106 -95
View File
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -30,11 +30,13 @@
use millau_runtime::{self, opaque::Block, RuntimeApi};
use sc_client_api::{ExecutorProvider, RemoteBackend};
use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams};
use sc_executor::native_executor_instance;
pub use sc_executor::NativeExecutor;
use sc_finality_grandpa::SharedVoterState;
use sc_keystore::LocalKeystore;
use sc_service::{error::Error as ServiceError, Configuration, TaskManager};
use sc_telemetry::{Telemetry, TelemetryWorker};
use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;
use sp_inherents::InherentDataProviders;
use std::sync::Arc;
@@ -70,6 +72,7 @@ pub fn new_partial(
AuraPair,
>,
sc_finality_grandpa::LinkHalf<Block, FullClient, FullSelectChain>,
Option<Telemetry>,
),
>,
ServiceError,
@@ -77,12 +80,30 @@ pub fn new_partial(
if config.keystore_remote.is_some() {
return Err(ServiceError::Other("Remote Keystores are not supported.".to_string()));
}
let inherent_data_providers = sp_inherents::InherentDataProviders::new();
let inherent_data_providers = InherentDataProviders::new();
let (client, backend, keystore_container, task_manager) =
sc_service::new_full_parts::<Block, RuntimeApi, Executor>(&config)?;
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 (client, backend, keystore_container, task_manager) = sc_service::new_full_parts::<Block, RuntimeApi, Executor>(
&config,
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
)?;
let client = Arc::new(client);
let telemetry = telemetry.map(|(worker, telemetry)| {
task_manager.spawn_handle().spawn("telemetry", worker.run());
telemetry
});
let select_chain = sc_consensus::LongestChain::new(backend.clone());
let transaction_pool = sc_transaction_pool::BasicPool::new_full(
@@ -93,22 +114,28 @@ pub fn new_partial(
client.clone(),
);
let (grandpa_block_import, grandpa_link) =
sc_finality_grandpa::block_import(client.clone(), &(client.clone() as Arc<_>), select_chain.clone())?;
let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import(
client.clone(),
&(client.clone() as Arc<_>),
select_chain.clone(),
telemetry.as_ref().map(|x| x.handle()),
)?;
let aura_block_import =
sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(grandpa_block_import.clone(), client.clone());
let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _, _>(
sc_consensus_aura::slot_duration(&*client)?,
aura_block_import.clone(),
Some(Box::new(grandpa_block_import)),
client.clone(),
inherent_data_providers.clone(),
&task_manager.spawn_essential_handle(),
config.prometheus_registry(),
sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),
)?;
let import_queue = sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _>(ImportQueueParams {
block_import: aura_block_import.clone(),
justification_import: Some(Box::new(grandpa_block_import)),
client: client.clone(),
inherent_data_providers: inherent_data_providers.clone(),
spawner: &task_manager.spawn_essential_handle(),
can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),
slot_duration: sc_consensus_aura::slot_duration(&*client)?,
registry: config.prometheus_registry(),
check_for_equivocation: Default::default(),
telemetry: telemetry.as_ref().map(|x| x.handle()),
})?;
Ok(sc_service::PartialComponents {
client,
@@ -119,7 +146,7 @@ pub fn new_partial(
select_chain,
transaction_pool,
inherent_data_providers,
other: (aura_block_import, grandpa_link),
other: (aura_block_import, grandpa_link, telemetry),
})
}
@@ -141,7 +168,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
select_chain,
transaction_pool,
inherent_data_providers,
other: (block_import, grandpa_link),
other: (block_import, grandpa_link, mut telemetry),
} = new_partial(&config)?;
if let Some(url) = &config.keystore_remote {
@@ -173,13 +200,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
})?;
if config.offchain_worker.enabled {
sc_service::build_offchain_workers(
&config,
backend.clone(),
task_manager.spawn_handle(),
client.clone(),
network.clone(),
);
sc_service::build_offchain_workers(&config, task_manager.spawn_handle(), client.clone(), network.clone());
}
let role = config.role.clone();
@@ -190,40 +211,9 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
let prometheus_registry = config.prometheus_registry().cloned();
let rpc_extensions_builder = {
use bp_message_lane::{LaneId, MessageNonce};
use bp_runtime::{InstanceId, RIALTO_BRIDGE_INSTANCE};
use sc_finality_grandpa::FinalityProofProvider as GrandpaFinalityProofProvider;
use sp_core::storage::StorageKey;
// This struct is here to ease update process.
/// Millau runtime from message-lane RPC point of view.
struct MillauMessageLaneKeys;
impl pallet_message_lane_rpc::Runtime for MillauMessageLaneKeys {
fn message_key(&self, instance: &InstanceId, lane: &LaneId, nonce: MessageNonce) -> Option<StorageKey> {
match *instance {
RIALTO_BRIDGE_INSTANCE => Some(millau_runtime::rialto_messages::message_key(lane, nonce)),
_ => None,
}
}
fn outbound_lane_data_key(&self, instance: &InstanceId, lane: &LaneId) -> Option<StorageKey> {
match *instance {
RIALTO_BRIDGE_INSTANCE => Some(millau_runtime::rialto_messages::outbound_lane_data_key(lane)),
_ => None,
}
}
fn inbound_lane_data_key(&self, instance: &InstanceId, lane: &LaneId) -> Option<StorageKey> {
match *instance {
RIALTO_BRIDGE_INSTANCE => Some(millau_runtime::rialto_messages::inbound_lane_data_key(lane)),
_ => None,
}
}
}
use pallet_message_lane_rpc::{MessageLaneApi, MessageLaneRpcHandler};
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};
use sc_finality_grandpa_rpc::{GrandpaApi, GrandpaRpcHandler};
use sc_rpc::DenyUnsafe;
use substrate_frame_rpc_system::{FullSystem, SystemApi};
@@ -237,7 +227,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
let shared_voter_state = sc_finality_grandpa::SharedVoterState::empty();
let finality_proof_provider =
GrandpaFinalityProofProvider::new_for_service(backend.clone(), Some(shared_authority_set.clone()));
GrandpaFinalityProofProvider::new_for_service(backend, Some(shared_authority_set.clone()));
Box::new(move |_, subscription_executor| {
let mut io = jsonrpc_core::IoHandler::default();
@@ -246,6 +236,9 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
pool.clone(),
DenyUnsafe::No,
)));
io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(
client.clone(),
)));
io.extend_with(GrandpaApi::to_delegate(GrandpaRpcHandler::new(
shared_authority_set.clone(),
shared_voter_state.clone(),
@@ -253,16 +246,11 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
subscription_executor,
finality_proof_provider.clone(),
)));
io.extend_with(MessageLaneApi::to_delegate(MessageLaneRpcHandler::new(
backend.clone(),
Arc::new(MillauMessageLaneKeys),
)));
io
})
};
let (_rpc_handlers, telemetry_connection_notifier) = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
network: network.clone(),
client: client.clone(),
keystore: keystore_container.sync_keystore(),
@@ -275,32 +263,35 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
network_status_sinks,
system_rpc_tx,
config,
telemetry_span: None,
telemetry: telemetry.as_mut(),
})?;
if role.is_authority() {
let proposer = sc_basic_authorship::ProposerFactory::new(
let proposer_factory = sc_basic_authorship::ProposerFactory::new(
task_manager.spawn_handle(),
client.clone(),
transaction_pool,
prometheus_registry.as_ref(),
telemetry.as_ref().map(|x| x.handle()),
);
let can_author_with = sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());
let aura = sc_consensus_aura::start_aura::<_, _, _, _, _, AuraPair, _, _, _, _>(
sc_consensus_aura::slot_duration(&*client)?,
client.clone(),
let aura = sc_consensus_aura::start_aura::<AuraPair, _, _, _, _, _, _, _, _, _>(StartAuraParams {
slot_duration: sc_consensus_aura::slot_duration(&*client)?,
client: client.clone(),
select_chain,
block_import,
proposer,
network.clone(),
proposer_factory,
inherent_data_providers,
force_authoring,
backoff_authoring_blocks,
keystore_container.sync_keystore(),
keystore: keystore_container.sync_keystore(),
can_author_with,
)?;
sync_oracle: network.clone(),
block_proposal_slot_portion: SlotProportion::new(2f32 / 3f32),
telemetry: telemetry.as_ref().map(|x| x.handle()),
})?;
// the AURA authoring task is considered essential, i.e. if it
// fails we take down the service with it.
@@ -323,6 +314,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
observer_enabled: false,
keystore,
is_authority: role.is_authority(),
telemetry: telemetry.as_ref().map(|x| x.handle()),
};
if enable_grandpa {
@@ -336,10 +328,10 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
config: grandpa_config,
link: grandpa_link,
network,
telemetry_on_connect: telemetry_connection_notifier.map(|x| x.on_connect_stream()),
voting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(),
prometheus_registry,
shared_voter_state: SharedVoterState::empty(),
telemetry: telemetry.as_ref().map(|x| x.handle()),
};
// the GRANDPA voter task is considered infallible, i.e.
@@ -355,8 +347,27 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
/// Builds a new service for a light client.
pub fn new_light(mut config: Configuration) -> Result<TaskManager, 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 (client, backend, keystore_container, mut task_manager, on_demand) =
sc_service::new_light_parts::<Block, RuntimeApi, Executor>(&config)?;
sc_service::new_light_parts::<Block, RuntimeApi, Executor>(
&config,
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
)?;
let mut telemetry = telemetry.map(|(worker, telemetry)| {
task_manager.spawn_handle().spawn("telemetry", worker.run());
telemetry
});
config
.network
@@ -373,22 +384,28 @@ pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError>
on_demand.clone(),
));
let (grandpa_block_import, _) =
sc_finality_grandpa::block_import(client.clone(), &(client.clone() as Arc<_>), select_chain)?;
let (grandpa_block_import, _) = sc_finality_grandpa::block_import(
client.clone(),
&(client.clone() as Arc<_>),
select_chain,
telemetry.as_ref().map(|x| x.handle()),
)?;
let aura_block_import =
sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(grandpa_block_import.clone(), client.clone());
let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _, _>(
sc_consensus_aura::slot_duration(&*client)?,
aura_block_import,
Some(Box::new(grandpa_block_import)),
client.clone(),
InherentDataProviders::new(),
&task_manager.spawn_essential_handle(),
config.prometheus_registry(),
sp_consensus::NeverCanAuthor,
)?;
let import_queue = sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _>(ImportQueueParams {
block_import: aura_block_import,
justification_import: Some(Box::new(grandpa_block_import)),
client: client.clone(),
inherent_data_providers: InherentDataProviders::new(),
spawner: &task_manager.spawn_essential_handle(),
can_author_with: sp_consensus::NeverCanAuthor,
slot_duration: sc_consensus_aura::slot_duration(&*client)?,
registry: config.prometheus_registry(),
check_for_equivocation: Default::default(),
telemetry: telemetry.as_ref().map(|x| x.handle()),
})?;
let (network, network_status_sinks, system_rpc_tx, network_starter) =
sc_service::build_network(sc_service::BuildNetworkParams {
@@ -402,13 +419,7 @@ pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError>
})?;
if config.offchain_worker.enabled {
sc_service::build_offchain_workers(
&config,
backend.clone(),
task_manager.spawn_handle(),
client.clone(),
network.clone(),
);
sc_service::build_offchain_workers(&config, task_manager.spawn_handle(), client.clone(), network.clone());
}
sc_service::spawn_tasks(sc_service::SpawnTasksParams {
@@ -424,7 +435,7 @@ pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError>
network,
network_status_sinks,
system_rpc_tx,
telemetry_span: None,
telemetry: telemetry.as_mut(),
})?;
network_starter.start_network();
+22 -17
View File
@@ -10,21 +10,21 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
hex-literal = "0.3"
serde = { version = "1.0.123", optional = true, features = ["derive"] }
serde = { version = "1.0.124", optional = true, features = ["derive"] }
# Bridge dependencies
bp-header-chain = { path = "../../../primitives/header-chain", default-features = false }
bp-message-lane = { path = "../../../primitives/message-lane", default-features = false }
bp-millau = { path = "../../../primitives/millau", default-features = false }
bp-rialto = { path = "../../../primitives/rialto", default-features = false }
bp-messages = { path = "../../../primitives/messages", default-features = false }
bp-millau = { path = "../../../primitives/chain-millau", default-features = false }
bp-rialto = { path = "../../../primitives/chain-rialto", default-features = false }
bp-runtime = { path = "../../../primitives/runtime", default-features = false }
bp-westend = { path = "../../../primitives/chain-westend", default-features = false }
bridge-runtime-common = { path = "../../runtime-common", default-features = false }
pallet-bridge-call-dispatch = { path = "../../../modules/call-dispatch", default-features = false }
pallet-finality-verifier = { path = "../../../modules/finality-verifier", default-features = false }
pallet-message-lane = { path = "../../../modules/message-lane", default-features = false }
pallet-bridge-dispatch = { path = "../../../modules/dispatch", default-features = false }
pallet-bridge-grandpa = { path = "../../../modules/grandpa", default-features = false }
pallet-bridge-messages = { path = "../../../modules/messages", default-features = false }
pallet-shift-session-manager = { path = "../../../modules/shift-session-manager", default-features = false }
pallet-substrate-bridge = { path = "../../../modules/substrate", default-features = false }
# Substrate Dependencies
@@ -40,12 +40,13 @@ pallet-session = { git = "https://github.com/paritytech/substrate", branch = "ma
pallet-sudo = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-block-builder = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-consensus-aura = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-inherents = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-inherents = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-offchain = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-session = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
@@ -61,36 +62,37 @@ wasm-builder-runner = { package = "substrate-wasm-builder-runner", version = "2.
default = ["std"]
std = [
"bp-header-chain/std",
"bp-message-lane/std",
"bp-messages/std",
"bp-millau/std",
"bp-rialto/std",
"bp-runtime/std",
"bp-westend/std",
"bridge-runtime-common/std",
"codec/std",
"frame-executive/std",
"frame-support/std",
"frame-system/std",
"frame-system-rpc-runtime-api/std",
"frame-system/std",
"pallet-aura/std",
"pallet-balances/std",
"pallet-bridge-call-dispatch/std",
"pallet-finality-verifier/std",
"pallet-bridge-dispatch/std",
"pallet-bridge-grandpa/std",
"pallet-bridge-messages/std",
"pallet-grandpa/std",
"pallet-message-lane/std",
"pallet-randomness-collective-flip/std",
"pallet-shift-session-manager/std",
"pallet-session/std",
"pallet-substrate-bridge/std",
"pallet-shift-session-manager/std",
"pallet-sudo/std",
"pallet-timestamp/std",
"pallet-transaction-payment-rpc-runtime-api/std",
"pallet-transaction-payment/std",
"serde",
"sp-api/std",
"sp-block-builder/std",
"sp-consensus-aura/std",
"sp-core/std",
"sp-inherents/std",
"sp-finality-grandpa/std",
"sp-inherents/std",
"sp-offchain/std",
"sp-runtime/std",
"sp-session/std",
@@ -99,3 +101,6 @@ std = [
"sp-trie/std",
"sp-version/std",
]
# TODO: https://github.com/paritytech/parity-bridges-common/issues/390
# I've left the feature flag here to test our CI configuration
runtime-benchmarks = []
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
+99 -75
View File
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -37,6 +37,7 @@ use crate::rialto_messages::{ToRialtoMessagePayload, WithRialtoMessageBridge};
use bridge_runtime_common::messages::{source::estimate_message_dispatch_and_delivery_fee, MessageBridge};
use codec::Decode;
use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use sp_api::impl_runtime_apis;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
@@ -61,8 +62,9 @@ pub use frame_support::{
pub use frame_system::Call as SystemCall;
pub use pallet_balances::Call as BalancesCall;
pub use pallet_message_lane::Call as MessageLaneCall;
pub use pallet_substrate_bridge::Call as BridgeRialtoCall;
pub use pallet_bridge_grandpa::Call as BridgeGrandpaRialtoCall;
pub use pallet_bridge_grandpa::Call as BridgeGrandpaWestendCall;
pub use pallet_bridge_messages::Call as MessagesCall;
pub use pallet_sudo::Call as SudoCall;
pub use pallet_timestamp::Call as TimestampCall;
@@ -199,15 +201,16 @@ impl frame_system::Config for Runtime {
type DbWeight = DbWeight;
/// The designated SS58 prefix of this chain.
type SS58Prefix = SS58Prefix;
/// The set code logic, just the default since we're not a parachain.
type OnSetCode = ();
}
impl pallet_aura::Config for Runtime {
type AuthorityId = AuraId;
}
impl pallet_bridge_call_dispatch::Config for Runtime {
impl pallet_bridge_dispatch::Config for Runtime {
type Event = Event;
type MessageId = (bp_message_lane::LaneId, bp_message_lane::MessageNonce);
type MessageId = (bp_messages::LaneId, bp_messages::MessageNonce);
type Call = Call;
type CallFilter = ();
type EncodedCall = crate::rialto_messages::FromRialtoEncodedCall;
@@ -291,7 +294,7 @@ impl pallet_session::Config for Runtime {
type ValidatorIdOf = ();
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
type SessionManager = pallet_shift_session_manager::Module<Runtime>;
type SessionManager = pallet_shift_session_manager::Pallet<Runtime>;
type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type Keys = SessionKeys;
type DisabledValidatorsThreshold = ();
@@ -299,33 +302,48 @@ impl pallet_session::Config for Runtime {
type WeightInfo = ();
}
impl pallet_substrate_bridge::Config for Runtime {
type BridgedChain = bp_rialto::Rialto;
}
parameter_types! {
// This is a pretty unscientific cap.
//
// Note that once this is hit the pallet will essentially throttle incoming requests down to one
// call per block.
pub const MaxRequests: u32 = 50;
pub const WestendValidatorCount: u32 = 255;
// Number of headers to keep.
//
// Assuming the worst case of every header being finalized, we will keep headers for at least a
// week.
pub const HeadersToKeep: u32 = 7 * bp_millau::DAYS as u32;
}
impl pallet_finality_verifier::Config for Runtime {
pub type RialtoGrandpaInstance = ();
impl pallet_bridge_grandpa::Config for Runtime {
type BridgedChain = bp_rialto::Rialto;
type HeaderChain = pallet_substrate_bridge::Module<Runtime>;
type AncestryProof = Vec<bp_rialto::Header>;
type AncestryChecker = bp_header_chain::LinearAncestryChecker;
type MaxRequests = MaxRequests;
type HeadersToKeep = HeadersToKeep;
// TODO [#391]: Use weights generated for the Millau runtime instead of Rialto ones.
type WeightInfo = pallet_bridge_grandpa::weights::RialtoWeight<Runtime>;
}
pub type WestendGrandpaInstance = pallet_bridge_grandpa::Instance1;
impl pallet_bridge_grandpa::Config<WestendGrandpaInstance> for Runtime {
type BridgedChain = bp_westend::Westend;
type MaxRequests = MaxRequests;
type HeadersToKeep = HeadersToKeep;
// TODO [#391]: Use weights generated for the Millau runtime instead of Rialto ones.
type WeightInfo = pallet_bridge_grandpa::weights::RialtoWeight<Runtime>;
}
impl pallet_shift_session_manager::Config for Runtime {}
parameter_types! {
pub const MaxMessagesToPruneAtOnce: bp_message_lane::MessageNonce = 8;
pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_message_lane::MessageNonce =
pub const MaxMessagesToPruneAtOnce: bp_messages::MessageNonce = 8;
pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce =
bp_millau::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE;
pub const MaxUnconfirmedMessagesAtInboundLane: bp_message_lane::MessageNonce =
pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce =
bp_millau::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE;
// `IdentityFee` is used by Millau => we may use weight directly
pub const GetDeliveryConfirmationTransactionFee: Balance =
@@ -333,11 +351,14 @@ parameter_types! {
pub const RootAccountForPayments: Option<AccountId> = None;
}
impl pallet_message_lane::Config for Runtime {
/// Instance of the messages pallet used to relay messages to/from Rialto chain.
pub type WithRialtoMessagesInstance = pallet_bridge_messages::DefaultInstance;
impl pallet_bridge_messages::Config<WithRialtoMessagesInstance> for Runtime {
type Event = Event;
// TODO: https://github.com/paritytech/parity-bridges-common/issues/390
type WeightInfo = pallet_message_lane::weights::RialtoWeight<Runtime>;
type Parameter = rialto_messages::MillauToRialtoMessageLaneParameter;
type WeightInfo = pallet_bridge_messages::weights::RialtoWeight<Runtime>;
type Parameter = rialto_messages::MillauToRialtoMessagesParameter;
type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce;
type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane;
type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane;
@@ -353,7 +374,7 @@ impl pallet_message_lane::Config for Runtime {
type TargetHeaderChain = crate::rialto_messages::Rialto;
type LaneMessageVerifier = crate::rialto_messages::ToRialtoMessageVerifier;
type MessageDeliveryAndDispatchPayment = pallet_message_lane::instant_payments::InstantCurrencyPayments<
type MessageDeliveryAndDispatchPayment = pallet_bridge_messages::instant_payments::InstantCurrencyPayments<
Runtime,
pallet_balances::Pallet<Runtime>,
GetDeliveryConfirmationTransactionFee,
@@ -370,10 +391,10 @@ construct_runtime!(
NodeBlock = opaque::Block,
UncheckedExtrinsic = UncheckedExtrinsic
{
BridgeRialto: pallet_substrate_bridge::{Pallet, Call, Storage, Config<T>},
BridgeRialtoMessageLane: pallet_message_lane::{Pallet, Call, Storage, Event<T>},
BridgeCallDispatch: pallet_bridge_call_dispatch::{Pallet, Event<T>},
BridgeFinalityVerifier: pallet_finality_verifier::{Pallet, Call},
BridgeRialtoMessages: pallet_bridge_messages::{Pallet, Call, Storage, Event<T>},
BridgeDispatch: pallet_bridge_dispatch::{Pallet, Event<T>},
BridgeRialtoGrandpa: pallet_bridge_grandpa::{Pallet, Call, Storage},
BridgeWestendGrandpa: pallet_bridge_grandpa::<Instance1>::{Pallet, Call, Config<T>, Storage},
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Call, Storage},
Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
@@ -411,6 +432,8 @@ pub type SignedExtra = (
pub type SignedPayload = generic::SignedPayload<Call, SignedExtra>;
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
/// Extrinsic type that has already been checked.
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;
/// Executive: handles dispatch to the various modules.
pub type Executive =
frame_executive::Executive<Runtime, Block, frame_system::ChainContext<Runtime>, Runtime, AllPallets>;
@@ -422,7 +445,7 @@ impl_runtime_apis! {
}
fn execute_block(block: Block) {
Executive::execute_block(block)
Executive::execute_block(block);
}
fn initialize_block(header: &<Block as BlockT>::Header) {
@@ -483,8 +506,8 @@ impl_runtime_apis! {
}
impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
fn slot_duration() -> u64 {
Aura::slot_duration()
fn slot_duration() -> sp_consensus_aura::SlotDuration {
sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())
}
fn authorities() -> Vec<AuraId> {
@@ -492,6 +515,18 @@ impl_runtime_apis! {
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
Block,
Balance,
> for Runtime {
fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {
TransactionPayment::query_info(uxt, len)
}
fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {
TransactionPayment::query_fee_details(uxt, len)
}
}
impl sp_session::SessionKeys<Block> for Runtime {
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
SessionKeys::generate(seed)
@@ -535,32 +570,31 @@ impl_runtime_apis! {
}
}
impl bp_rialto::RialtoHeaderApi<Block> for Runtime {
fn best_blocks() -> Vec<(bp_rialto::BlockNumber, bp_rialto::Hash)> {
BridgeRialto::best_headers()
}
fn finalized_block() -> (bp_rialto::BlockNumber, bp_rialto::Hash) {
let header = BridgeRialto::best_finalized();
impl bp_rialto::RialtoFinalityApi<Block> for Runtime {
fn best_finalized() -> (bp_rialto::BlockNumber, bp_rialto::Hash) {
let header = BridgeRialtoGrandpa::best_finalized();
(header.number, header.hash())
}
fn incomplete_headers() -> Vec<(bp_rialto::BlockNumber, bp_rialto::Hash)> {
BridgeRialto::require_justifications()
fn is_known_header(hash: bp_rialto::Hash) -> bool {
BridgeRialtoGrandpa::is_known_header(hash)
}
}
impl bp_westend::WestendFinalityApi<Block> for Runtime {
fn best_finalized() -> (bp_westend::BlockNumber, bp_westend::Hash) {
let header = BridgeWestendGrandpa::best_finalized();
(header.number, header.hash())
}
fn is_known_block(hash: bp_rialto::Hash) -> bool {
BridgeRialto::is_known_header(hash)
}
fn is_finalized_block(hash: bp_rialto::Hash) -> bool {
BridgeRialto::is_finalized_header(hash)
fn is_known_header(hash: bp_westend::Hash) -> bool {
BridgeWestendGrandpa::is_known_header(hash)
}
}
impl bp_rialto::ToRialtoOutboundLaneApi<Block, Balance, ToRialtoMessagePayload> for Runtime {
fn estimate_message_delivery_and_dispatch_fee(
_lane_id: bp_message_lane::LaneId,
_lane_id: bp_messages::LaneId,
payload: ToRialtoMessagePayload,
) -> Option<Balance> {
estimate_message_dispatch_and_delivery_fee::<WithRialtoMessageBridge>(
@@ -570,12 +604,12 @@ impl_runtime_apis! {
}
fn messages_dispatch_weight(
lane: bp_message_lane::LaneId,
begin: bp_message_lane::MessageNonce,
end: bp_message_lane::MessageNonce,
) -> Vec<(bp_message_lane::MessageNonce, Weight, u32)> {
lane: bp_messages::LaneId,
begin: bp_messages::MessageNonce,
end: bp_messages::MessageNonce,
) -> Vec<(bp_messages::MessageNonce, Weight, u32)> {
(begin..=end).filter_map(|nonce| {
let encoded_payload = BridgeRialtoMessageLane::outbound_message_payload(lane, nonce)?;
let encoded_payload = BridgeRialtoMessages::outbound_message_payload(lane, nonce)?;
let decoded_payload = rialto_messages::ToRialtoMessagePayload::decode(
&mut &encoded_payload[..]
).ok()?;
@@ -584,26 +618,26 @@ impl_runtime_apis! {
.collect()
}
fn latest_received_nonce(lane: bp_message_lane::LaneId) -> bp_message_lane::MessageNonce {
BridgeRialtoMessageLane::outbound_latest_received_nonce(lane)
fn latest_received_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce {
BridgeRialtoMessages::outbound_latest_received_nonce(lane)
}
fn latest_generated_nonce(lane: bp_message_lane::LaneId) -> bp_message_lane::MessageNonce {
BridgeRialtoMessageLane::outbound_latest_generated_nonce(lane)
fn latest_generated_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce {
BridgeRialtoMessages::outbound_latest_generated_nonce(lane)
}
}
impl bp_rialto::FromRialtoInboundLaneApi<Block> for Runtime {
fn latest_received_nonce(lane: bp_message_lane::LaneId) -> bp_message_lane::MessageNonce {
BridgeRialtoMessageLane::inbound_latest_received_nonce(lane)
fn latest_received_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce {
BridgeRialtoMessages::inbound_latest_received_nonce(lane)
}
fn latest_confirmed_nonce(lane: bp_message_lane::LaneId) -> bp_message_lane::MessageNonce {
BridgeRialtoMessageLane::inbound_latest_confirmed_nonce(lane)
fn latest_confirmed_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce {
BridgeRialtoMessages::inbound_latest_confirmed_nonce(lane)
}
fn unrewarded_relayers_state(lane: bp_message_lane::LaneId) -> bp_message_lane::UnrewardedRelayersState {
BridgeRialtoMessageLane::inbound_unrewarded_relayers_state(lane)
fn unrewarded_relayers_state(lane: bp_messages::LaneId) -> bp_messages::UnrewardedRelayersState {
BridgeRialtoMessages::inbound_unrewarded_relayers_state(lane)
}
}
}
@@ -623,7 +657,7 @@ where
AccountId: codec::Encode,
SpecVersion: codec::Encode,
{
pallet_bridge_call_dispatch::account_ownership_digest(
pallet_bridge_dispatch::account_ownership_digest(
rialto_call,
millau_account_id,
rialto_spec_version,
@@ -639,9 +673,9 @@ mod tests {
#[test]
fn ensure_millau_message_lane_weights_are_correct() {
// TODO: https://github.com/paritytech/parity-bridges-common/issues/390
type Weights = pallet_message_lane::weights::RialtoWeight<Runtime>;
type Weights = pallet_bridge_messages::weights::RialtoWeight<Runtime>;
pallet_message_lane::ensure_weights_are_correct::<Weights>(
pallet_bridge_messages::ensure_weights_are_correct::<Weights>(
bp_millau::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT,
bp_millau::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT,
bp_millau::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT,
@@ -650,34 +684,24 @@ mod tests {
let max_incoming_message_proof_size = bp_rialto::EXTRA_STORAGE_PROOF_SIZE.saturating_add(
messages::target::maximal_incoming_message_size(bp_millau::max_extrinsic_size()),
);
pallet_message_lane::ensure_able_to_receive_message::<Weights>(
pallet_bridge_messages::ensure_able_to_receive_message::<Weights>(
bp_millau::max_extrinsic_size(),
bp_millau::max_extrinsic_weight(),
max_incoming_message_proof_size,
bridge_runtime_common::messages::transaction_weight_without_multiplier(
bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
max_incoming_message_proof_size as _,
0,
),
messages::target::maximal_incoming_message_dispatch_weight(bp_millau::max_extrinsic_weight()),
);
let max_incoming_inbound_lane_data_proof_size = bp_message_lane::InboundLaneData::<()>::encoded_size_hint(
let max_incoming_inbound_lane_data_proof_size = bp_messages::InboundLaneData::<()>::encoded_size_hint(
bp_millau::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE,
bp_rialto::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE as _,
)
.unwrap_or(u32::MAX);
pallet_message_lane::ensure_able_to_receive_confirmation::<Weights>(
pallet_bridge_messages::ensure_able_to_receive_confirmation::<Weights>(
bp_millau::max_extrinsic_size(),
bp_millau::max_extrinsic_weight(),
max_incoming_inbound_lane_data_proof_size,
bp_rialto::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE,
bp_rialto::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE,
bridge_runtime_common::messages::transaction_weight_without_multiplier(
bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
max_incoming_inbound_lane_data_proof_size as _,
0,
),
);
}
}
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -14,52 +14,32 @@
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
//! Everything required to serve Millau <-> Rialto message lanes.
//! Everything required to serve Millau <-> Rialto messages.
use crate::Runtime;
use bp_message_lane::{
use bp_messages::{
source_chain::TargetHeaderChain,
target_chain::{ProvedMessages, SourceHeaderChain},
InboundLaneData, LaneId, Message, MessageNonce, Parameter as MessageLaneParameter,
InboundLaneData, LaneId, Message, MessageNonce, Parameter as MessagesParameter,
};
use bp_runtime::{InstanceId, RIALTO_BRIDGE_INSTANCE};
use bridge_runtime_common::messages::{self, ChainWithMessageLanes, MessageBridge};
use bridge_runtime_common::messages::{self, MessageBridge, MessageTransaction};
use codec::{Decode, Encode};
use frame_support::{
parameter_types,
weights::{DispatchClass, Weight, WeightToFeePolynomial},
weights::{DispatchClass, Weight},
RuntimeDebug,
};
use sp_core::storage::StorageKey;
use sp_runtime::{FixedPointNumber, FixedU128};
use sp_std::{convert::TryFrom, ops::RangeInclusive};
/// Initial value of `RialtoToMillauConversionRate` parameter.
pub const INITIAL_RIALTO_TO_MILLAU_CONVERSION_RATE: FixedU128 = FixedU128::from_inner(FixedU128::DIV);
parameter_types! {
/// Rialto to Millau conversion rate. Initially we treat both tokens as equal.
storage RialtoToMillauConversionRate: FixedU128 = 1.into();
}
/// Storage key of the Millau -> Rialto message in the runtime storage.
pub fn message_key(lane: &LaneId, nonce: MessageNonce) -> StorageKey {
pallet_message_lane::storage_keys::message_key::<Runtime, <Millau as ChainWithMessageLanes>::MessageLaneInstance>(
lane, nonce,
)
}
/// Storage key of the Millau -> Rialto message lane state in the runtime storage.
pub fn outbound_lane_data_key(lane: &LaneId) -> StorageKey {
pallet_message_lane::storage_keys::outbound_lane_data_key::<<Millau as ChainWithMessageLanes>::MessageLaneInstance>(
lane,
)
}
/// Storage key of the Rialto -> Millau message lane state in the runtime storage.
pub fn inbound_lane_data_key(lane: &LaneId) -> StorageKey {
pallet_message_lane::storage_keys::inbound_lane_data_key::<
Runtime,
<Millau as ChainWithMessageLanes>::MessageLaneInstance,
>(lane)
pub storage RialtoToMillauConversionRate: FixedU128 = INITIAL_RIALTO_TO_MILLAU_CONVERSION_RATE;
}
/// Message payload for Millau -> Rialto messages.
@@ -84,7 +64,7 @@ type ToRialtoMessagesDeliveryProof = messages::source::FromBridgedChainMessagesD
pub type FromRialtoMessageDispatch = messages::target::FromBridgedChainMessageDispatch<
WithRialtoMessageBridge,
crate::Runtime,
pallet_bridge_call_dispatch::DefaultInstance,
pallet_bridge_dispatch::DefaultInstance,
>;
/// Millau <-> Rialto message bridge.
@@ -99,59 +79,6 @@ impl MessageBridge for WithRialtoMessageBridge {
type ThisChain = Millau;
type BridgedChain = Rialto;
fn maximal_extrinsic_size_on_target_chain() -> u32 {
bp_rialto::max_extrinsic_size()
}
fn weight_limits_of_message_on_bridged_chain(_message_payload: &[u8]) -> RangeInclusive<Weight> {
// we don't want to relay too large messages + keep reserve for future upgrades
let upper_limit = messages::target::maximal_incoming_message_dispatch_weight(bp_rialto::max_extrinsic_weight());
// we're charging for payload bytes in `WithRialtoMessageBridge::weight_of_delivery_transaction` function
//
// this bridge may be used to deliver all kind of messages, so we're not making any assumptions about
// minimal dispatch weight here
0..=upper_limit
}
fn weight_of_delivery_transaction(message_payload: &[u8]) -> Weight {
let message_payload_len = u32::try_from(message_payload.len())
.map(Into::into)
.unwrap_or(Weight::MAX);
let extra_bytes_in_payload =
message_payload_len.saturating_sub(pallet_message_lane::EXPECTED_DEFAULT_MESSAGE_LENGTH.into());
messages::transaction_weight_without_multiplier(
bp_rialto::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
message_payload_len.saturating_add(bp_millau::EXTRA_STORAGE_PROOF_SIZE as _),
extra_bytes_in_payload
.saturating_mul(bp_rialto::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT)
.saturating_add(bp_rialto::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT),
)
}
fn weight_of_delivery_confirmation_transaction_on_this_chain() -> Weight {
let inbounded_data_size: Weight =
InboundLaneData::<bp_rialto::AccountId>::encoded_size_hint(bp_rialto::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, 1)
.map(Into::into)
.unwrap_or(Weight::MAX);
messages::transaction_weight_without_multiplier(
bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
inbounded_data_size.saturating_add(bp_rialto::EXTRA_STORAGE_PROOF_SIZE as _),
bp_millau::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT,
)
}
fn this_weight_to_this_balance(weight: Weight) -> bp_millau::Balance {
<crate::Runtime as pallet_transaction_payment::Config>::WeightToFee::calc(&weight)
}
fn bridged_weight_to_bridged_balance(weight: Weight) -> bp_rialto::Balance {
// we're using the same weights in both chains now
<crate::Runtime as pallet_transaction_payment::Config>::WeightToFee::calc(&weight) as _
}
fn bridged_balance_to_this_balance(bridged_balance: bp_rialto::Balance) -> bp_millau::Balance {
bp_millau::Balance::try_from(RialtoToMillauConversionRate::get().saturating_mul_int(bridged_balance))
.unwrap_or(bp_millau::Balance::MAX)
@@ -162,42 +89,114 @@ impl MessageBridge for WithRialtoMessageBridge {
#[derive(RuntimeDebug, Clone, Copy)]
pub struct Millau;
impl messages::ChainWithMessageLanes for Millau {
impl messages::ChainWithMessages for Millau {
type Hash = bp_millau::Hash;
type AccountId = bp_millau::AccountId;
type Signer = bp_millau::AccountSigner;
type Signature = bp_millau::Signature;
type Call = crate::Call;
type Weight = Weight;
type Balance = bp_millau::Balance;
type MessageLaneInstance = pallet_message_lane::DefaultInstance;
type MessagesInstance = crate::WithRialtoMessagesInstance;
}
impl messages::ThisChainWithMessageLanes for Millau {
impl messages::ThisChainWithMessages for Millau {
type Call = crate::Call;
fn is_outbound_lane_enabled(lane: &LaneId) -> bool {
*lane == LaneId::default()
*lane == [0, 0, 0, 0] || *lane == [0, 0, 0, 1]
}
fn maximal_pending_messages_at_outbound_lane() -> MessageNonce {
MessageNonce::MAX
}
fn estimate_delivery_confirmation_transaction() -> MessageTransaction<Weight> {
let inbound_data_size =
InboundLaneData::<bp_millau::AccountId>::encoded_size_hint(bp_millau::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, 1)
.unwrap_or(u32::MAX);
MessageTransaction {
dispatch_weight: bp_millau::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT,
size: inbound_data_size
.saturating_add(bp_rialto::EXTRA_STORAGE_PROOF_SIZE)
.saturating_add(bp_millau::TX_EXTRA_BYTES),
}
}
fn transaction_payment(transaction: MessageTransaction<Weight>) -> bp_millau::Balance {
// in our testnets, both per-byte fee and weight-to-fee are 1:1
messages::transaction_payment(
bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
1,
FixedU128::zero(),
|weight| weight as _,
transaction,
)
}
}
/// Rialto chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct Rialto;
impl messages::ChainWithMessageLanes for Rialto {
impl messages::ChainWithMessages for Rialto {
type Hash = bp_rialto::Hash;
type AccountId = bp_rialto::AccountId;
type Signer = bp_rialto::AccountSigner;
type Signature = bp_rialto::Signature;
type Call = (); // unknown to us
type Weight = Weight;
type Balance = bp_rialto::Balance;
type MessageLaneInstance = pallet_message_lane::DefaultInstance;
type MessagesInstance = pallet_bridge_messages::DefaultInstance;
}
impl messages::BridgedChainWithMessages for Rialto {
fn maximal_extrinsic_size() -> u32 {
bp_rialto::max_extrinsic_size()
}
fn message_weight_limits(_message_payload: &[u8]) -> RangeInclusive<Weight> {
// we don't want to relay too large messages + keep reserve for future upgrades
let upper_limit = messages::target::maximal_incoming_message_dispatch_weight(bp_rialto::max_extrinsic_weight());
// we're charging for payload bytes in `WithRialtoMessageBridge::transaction_payment` function
//
// this bridge may be used to deliver all kind of messages, so we're not making any assumptions about
// minimal dispatch weight here
0..=upper_limit
}
fn estimate_delivery_transaction(
message_payload: &[u8],
message_dispatch_weight: Weight,
) -> MessageTransaction<Weight> {
let message_payload_len = u32::try_from(message_payload.len()).unwrap_or(u32::MAX);
let extra_bytes_in_payload = Weight::from(message_payload_len)
.saturating_sub(pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH.into());
MessageTransaction {
dispatch_weight: extra_bytes_in_payload
.saturating_mul(bp_rialto::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT)
.saturating_add(bp_rialto::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT)
.saturating_add(message_dispatch_weight),
size: message_payload_len
.saturating_add(bp_millau::EXTRA_STORAGE_PROOF_SIZE)
.saturating_add(bp_rialto::TX_EXTRA_BYTES),
}
}
fn transaction_payment(transaction: MessageTransaction<Weight>) -> bp_rialto::Balance {
// in our testnets, both per-byte fee and weight-to-fee are 1:1
messages::transaction_payment(
bp_rialto::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
1,
FixedU128::zero(),
|weight| weight as _,
transaction,
)
}
}
impl TargetHeaderChain<ToRialtoMessagePayload, bp_rialto::AccountId> for Rialto {
@@ -238,15 +237,15 @@ impl SourceHeaderChain<bp_rialto::Balance> for Rialto {
/// Millau -> Rialto message lane pallet parameters.
#[derive(RuntimeDebug, Clone, Encode, Decode, PartialEq, Eq)]
pub enum MillauToRialtoMessageLaneParameter {
pub enum MillauToRialtoMessagesParameter {
/// The conversion formula we use is: `MillauTokens = RialtoTokens * conversion_rate`.
RialtoToMillauConversionRate(FixedU128),
}
impl MessageLaneParameter for MillauToRialtoMessageLaneParameter {
impl MessagesParameter for MillauToRialtoMessagesParameter {
fn save(&self) {
match *self {
MillauToRialtoMessageLaneParameter::RialtoToMillauConversionRate(ref conversion_rate) => {
MillauToRialtoMessagesParameter::RialtoToMillauConversionRate(ref conversion_rate) => {
RialtoToMillauConversionRate::set(conversion_rate)
}
}
+10 -9
View File
@@ -15,17 +15,19 @@ structopt = "0.3.21"
# Bridge dependencies
bp-message-lane = { path = "../../../primitives/message-lane" }
bp-messages = { path = "../../../primitives/messages" }
bp-runtime = { path = "../../../primitives/runtime" }
bp-rialto = { path = "../../../primitives/rialto" }
pallet-message-lane = { path = "../../../modules/message-lane" }
pallet-message-lane-rpc = { path = "../../../modules/message-lane/rpc" }
bp-rialto = { path = "../../../primitives/chain-rialto" }
pallet-bridge-messages = { path = "../../../modules/messages" }
rialto-runtime = { path = "../runtime" }
# Substrate Dependencies
frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "master" }
frame-benchmarking-cli = { git = "https://github.com/paritytech/substrate", branch = "master" }
node-inspect = { git = "https://github.com/paritytech/substrate", branch = "master" }
pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-basic-authorship = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-cli = { git = "https://github.com/paritytech/substrate", branch = "master", features = ["wasmtime"] }
sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "master" }
@@ -35,22 +37,21 @@ sc-executor = { git = "https://github.com/paritytech/substrate", branch = "maste
sc-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-finality-grandpa-rpc = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-keystore = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-service = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-rpc = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-service = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-telemetry = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-consensus = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-consensus-aura = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-inherents = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-inherents = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" }
substrate-frame-rpc-system = { git = "https://github.com/paritytech/substrate", branch = "master" }
[build-dependencies]
build-script-utils = { package = "substrate-build-script-utils", version = "2.0" }
substrate-build-script-utils = "3.0.0"
frame-benchmarking-cli = { git = "https://github.com/paritytech/substrate", branch = "master" }
vergen = "3.1.0"
[features]
default = []
+4 -6
View File
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -14,12 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
use vergen::{generate_cargo_keys, ConstantsFlags};
const ERROR_MSG: &str = "Failed to generate metadata files";
use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};
fn main() {
generate_cargo_keys(ConstantsFlags::SHA_SHORT).expect(ERROR_MSG);
generate_cargo_keys();
build_script_utils::rerun_if_git_head_changed();
rerun_if_git_head_changed();
}
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -16,8 +16,8 @@
use bp_rialto::derive_account_from_millau_id;
use rialto_runtime::{
AccountId, AuraConfig, BalancesConfig, BridgeKovanConfig, BridgeMillauConfig, BridgeRialtoPoAConfig, GenesisConfig,
GrandpaConfig, SessionConfig, SessionKeys, Signature, SudoConfig, SystemConfig, WASM_BINARY,
AccountId, AuraConfig, BalancesConfig, BridgeKovanConfig, BridgeRialtoPoAConfig, GenesisConfig, GrandpaConfig,
SessionConfig, SessionKeys, Signature, SudoConfig, SystemConfig, WASM_BINARY,
};
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_core::{sr25519, Pair, Public};
@@ -122,7 +122,10 @@ impl Alternative {
get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
get_account_id_from_seed::<sr25519::Public>("George//stash"),
get_account_id_from_seed::<sr25519::Public>("Harry//stash"),
pallet_message_lane::Module::<rialto_runtime::Runtime, pallet_message_lane::DefaultInstance>::relayer_fund_account_id(),
pallet_bridge_messages::Pallet::<
rialto_runtime::Runtime,
pallet_bridge_messages::DefaultInstance,
>::relayer_fund_account_id(),
derive_account_from_millau_id(bp_runtime::SourceAccount::Account(
get_account_id_from_seed::<sr25519::Public>("Dave"),
)),
@@ -151,33 +154,28 @@ fn testnet_genesis(
_enable_println: bool,
) -> GenesisConfig {
GenesisConfig {
frame_system: Some(SystemConfig {
frame_system: SystemConfig {
code: WASM_BINARY.to_vec(),
changes_trie_config: Default::default(),
}),
pallet_balances: Some(BalancesConfig {
},
pallet_balances: BalancesConfig {
balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 50)).collect(),
}),
pallet_aura: Some(AuraConfig {
},
pallet_aura: AuraConfig {
authorities: Vec::new(),
}),
pallet_bridge_eth_poa_Instance1: Some(load_rialto_poa_bridge_config()),
pallet_bridge_eth_poa_Instance2: Some(load_kovan_bridge_config()),
pallet_grandpa: Some(GrandpaConfig {
},
pallet_bridge_eth_poa_Instance1: load_rialto_poa_bridge_config(),
pallet_bridge_eth_poa_Instance2: load_kovan_bridge_config(),
pallet_grandpa: GrandpaConfig {
authorities: Vec::new(),
}),
pallet_substrate_bridge: Some(BridgeMillauConfig {
// We'll initialize the pallet with a dispatchable instead.
init_data: None,
owner: Some(root_key.clone()),
}),
pallet_sudo: Some(SudoConfig { key: root_key }),
pallet_session: Some(SessionConfig {
},
pallet_sudo: SudoConfig { key: root_key },
pallet_session: SessionConfig {
keys: initial_authorities
.iter()
.map(|x| (x.0.clone(), x.0.clone(), session_keys(x.1.clone(), x.2.clone())))
.collect::<Vec<_>>(),
}),
},
}
}
+6 -3
View File
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -31,6 +31,7 @@ pub struct Cli {
pub enum Subcommand {
/// Key management cli utilities
Key(sc_cli::KeySubcommand),
/// Verify a signature for a message, provided on STDIN, with a given (public or secret) key.
Verify(sc_cli::VerifyCmd),
@@ -61,7 +62,9 @@ pub enum Subcommand {
/// Revert the chain to a previous state.
Revert(sc_cli::RevertCmd),
/// The custom benchmark subcommmand benchmarking runtime pallets.
#[structopt(name = "benchmark", about = "Benchmark runtime pallets.")]
/// Inspect blocks or extrinsics.
Inspect(node_inspect::cli::InspectCmd),
/// Benchmark runtime pallets.
Benchmark(frame_benchmarking_cli::BenchmarkCmd),
}
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -17,7 +17,7 @@
use crate::cli::{Cli, Subcommand};
use crate::service;
use crate::service::new_partial;
use rialto_runtime::Block;
use rialto_runtime::{Block, RuntimeApi};
use sc_cli::{ChainSpec, Role, RuntimeVersion, SubstrateCli};
use sc_service::PartialComponents;
@@ -153,6 +153,10 @@ pub fn run() -> sc_cli::Result<()> {
Ok((cmd.run(client, backend), task_manager))
})
}
Some(Subcommand::Inspect(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run::<Block, RuntimeApi, service::Executor>(config))
}
None => {
let runner = cli.create_runner(&cli.run)?;
runner
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
+106 -94
View File
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -30,11 +30,13 @@
use rialto_runtime::{self, opaque::Block, RuntimeApi};
use sc_client_api::{ExecutorProvider, RemoteBackend};
use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams};
use sc_executor::native_executor_instance;
pub use sc_executor::NativeExecutor;
use sc_finality_grandpa::SharedVoterState;
use sc_keystore::LocalKeystore;
use sc_service::{error::Error as ServiceError, Configuration, TaskManager};
use sc_telemetry::{Telemetry, TelemetryWorker};
use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;
use sp_inherents::InherentDataProviders;
use std::sync::Arc;
@@ -70,6 +72,7 @@ pub fn new_partial(
AuraPair,
>,
sc_finality_grandpa::LinkHalf<Block, FullClient, FullSelectChain>,
Option<Telemetry>,
),
>,
ServiceError,
@@ -77,12 +80,30 @@ pub fn new_partial(
if config.keystore_remote.is_some() {
return Err(ServiceError::Other("Remote Keystores are not supported.".to_string()));
}
let inherent_data_providers = sp_inherents::InherentDataProviders::new();
let inherent_data_providers = InherentDataProviders::new();
let (client, backend, keystore_container, task_manager) =
sc_service::new_full_parts::<Block, RuntimeApi, Executor>(&config)?;
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 (client, backend, keystore_container, task_manager) = sc_service::new_full_parts::<Block, RuntimeApi, Executor>(
&config,
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
)?;
let client = Arc::new(client);
let telemetry = telemetry.map(|(worker, telemetry)| {
task_manager.spawn_handle().spawn("telemetry", worker.run());
telemetry
});
let select_chain = sc_consensus::LongestChain::new(backend.clone());
let transaction_pool = sc_transaction_pool::BasicPool::new_full(
@@ -93,22 +114,28 @@ pub fn new_partial(
client.clone(),
);
let (grandpa_block_import, grandpa_link) =
sc_finality_grandpa::block_import(client.clone(), &(client.clone() as Arc<_>), select_chain.clone())?;
let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import(
client.clone(),
&(client.clone() as Arc<_>),
select_chain.clone(),
telemetry.as_ref().map(|x| x.handle()),
)?;
let aura_block_import =
sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(grandpa_block_import.clone(), client.clone());
let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _, _>(
sc_consensus_aura::slot_duration(&*client)?,
aura_block_import.clone(),
Some(Box::new(grandpa_block_import)),
client.clone(),
inherent_data_providers.clone(),
&task_manager.spawn_essential_handle(),
config.prometheus_registry(),
sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),
)?;
let import_queue = sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _>(ImportQueueParams {
block_import: aura_block_import.clone(),
justification_import: Some(Box::new(grandpa_block_import)),
client: client.clone(),
inherent_data_providers: inherent_data_providers.clone(),
spawner: &task_manager.spawn_essential_handle(),
can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),
slot_duration: sc_consensus_aura::slot_duration(&*client)?,
registry: config.prometheus_registry(),
check_for_equivocation: Default::default(),
telemetry: telemetry.as_ref().map(|x| x.handle()),
})?;
Ok(sc_service::PartialComponents {
client,
@@ -119,7 +146,7 @@ pub fn new_partial(
select_chain,
transaction_pool,
inherent_data_providers,
other: (aura_block_import, grandpa_link),
other: (aura_block_import, grandpa_link, telemetry),
})
}
@@ -141,7 +168,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
select_chain,
transaction_pool,
inherent_data_providers,
other: (block_import, grandpa_link),
other: (block_import, grandpa_link, mut telemetry),
} = new_partial(&config)?;
if let Some(url) = &config.keystore_remote {
@@ -173,13 +200,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
})?;
if config.offchain_worker.enabled {
sc_service::build_offchain_workers(
&config,
backend.clone(),
task_manager.spawn_handle(),
client.clone(),
network.clone(),
);
sc_service::build_offchain_workers(&config, task_manager.spawn_handle(), client.clone(), network.clone());
}
let role = config.role.clone();
@@ -190,40 +211,9 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
let prometheus_registry = config.prometheus_registry().cloned();
let rpc_extensions_builder = {
use bp_message_lane::{LaneId, MessageNonce};
use bp_runtime::{InstanceId, MILLAU_BRIDGE_INSTANCE};
use sc_finality_grandpa::FinalityProofProvider as GrandpaFinalityProofProvider;
use sp_core::storage::StorageKey;
// This struct is here to ease update process.
/// Rialto runtime from message-lane RPC point of view.
struct RialtoMessageLaneKeys;
impl pallet_message_lane_rpc::Runtime for RialtoMessageLaneKeys {
fn message_key(&self, instance: &InstanceId, lane: &LaneId, nonce: MessageNonce) -> Option<StorageKey> {
match *instance {
MILLAU_BRIDGE_INSTANCE => Some(rialto_runtime::millau_messages::message_key(lane, nonce)),
_ => None,
}
}
fn outbound_lane_data_key(&self, instance: &InstanceId, lane: &LaneId) -> Option<StorageKey> {
match *instance {
MILLAU_BRIDGE_INSTANCE => Some(rialto_runtime::millau_messages::outbound_lane_data_key(lane)),
_ => None,
}
}
fn inbound_lane_data_key(&self, instance: &InstanceId, lane: &LaneId) -> Option<StorageKey> {
match *instance {
MILLAU_BRIDGE_INSTANCE => Some(rialto_runtime::millau_messages::inbound_lane_data_key(lane)),
_ => None,
}
}
}
use pallet_message_lane_rpc::{MessageLaneApi, MessageLaneRpcHandler};
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};
use sc_finality_grandpa_rpc::{GrandpaApi, GrandpaRpcHandler};
use sc_rpc::DenyUnsafe;
use substrate_frame_rpc_system::{FullSystem, SystemApi};
@@ -237,7 +227,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
let shared_voter_state = sc_finality_grandpa::SharedVoterState::empty();
let finality_proof_provider =
GrandpaFinalityProofProvider::new_for_service(backend.clone(), Some(shared_authority_set.clone()));
GrandpaFinalityProofProvider::new_for_service(backend, Some(shared_authority_set.clone()));
Box::new(move |_, subscription_executor| {
let mut io = jsonrpc_core::IoHandler::default();
@@ -246,6 +236,9 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
pool.clone(),
DenyUnsafe::No,
)));
io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(
client.clone(),
)));
io.extend_with(GrandpaApi::to_delegate(GrandpaRpcHandler::new(
shared_authority_set.clone(),
shared_voter_state.clone(),
@@ -253,16 +246,12 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
subscription_executor,
finality_proof_provider.clone(),
)));
io.extend_with(MessageLaneApi::to_delegate(MessageLaneRpcHandler::new(
backend.clone(),
Arc::new(RialtoMessageLaneKeys),
)));
io
})
};
let (_rpc_handlers, telemetry_connection_notifier) = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
network: network.clone(),
client: client.clone(),
keystore: keystore_container.sync_keystore(),
@@ -275,32 +264,35 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
network_status_sinks,
system_rpc_tx,
config,
telemetry_span: None,
telemetry: telemetry.as_mut(),
})?;
if role.is_authority() {
let proposer = sc_basic_authorship::ProposerFactory::new(
let proposer_factory = sc_basic_authorship::ProposerFactory::new(
task_manager.spawn_handle(),
client.clone(),
transaction_pool,
prometheus_registry.as_ref(),
telemetry.as_ref().map(|x| x.handle()),
);
let can_author_with = sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());
let aura = sc_consensus_aura::start_aura::<_, _, _, _, _, AuraPair, _, _, _, _>(
sc_consensus_aura::slot_duration(&*client)?,
client.clone(),
let aura = sc_consensus_aura::start_aura::<AuraPair, _, _, _, _, _, _, _, _, _>(StartAuraParams {
slot_duration: sc_consensus_aura::slot_duration(&*client)?,
client: client.clone(),
select_chain,
block_import,
proposer,
network.clone(),
proposer_factory,
inherent_data_providers,
force_authoring,
backoff_authoring_blocks,
keystore_container.sync_keystore(),
keystore: keystore_container.sync_keystore(),
can_author_with,
)?;
sync_oracle: network.clone(),
block_proposal_slot_portion: SlotProportion::new(2f32 / 3f32),
telemetry: telemetry.as_ref().map(|x| x.handle()),
})?;
// the AURA authoring task is considered essential, i.e. if it
// fails we take down the service with it.
@@ -323,6 +315,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
observer_enabled: false,
keystore,
is_authority: role.is_authority(),
telemetry: telemetry.as_ref().map(|x| x.handle()),
};
if enable_grandpa {
@@ -336,10 +329,10 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
config: grandpa_config,
link: grandpa_link,
network,
telemetry_on_connect: telemetry_connection_notifier.map(|x| x.on_connect_stream()),
voting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(),
prometheus_registry,
shared_voter_state: SharedVoterState::empty(),
telemetry: telemetry.as_ref().map(|x| x.handle()),
};
// the GRANDPA voter task is considered infallible, i.e.
@@ -355,8 +348,27 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
/// Builds a new service for a light client.
pub fn new_light(mut config: Configuration) -> Result<TaskManager, 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 (client, backend, keystore_container, mut task_manager, on_demand) =
sc_service::new_light_parts::<Block, RuntimeApi, Executor>(&config)?;
sc_service::new_light_parts::<Block, RuntimeApi, Executor>(
&config,
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
)?;
let mut telemetry = telemetry.map(|(worker, telemetry)| {
task_manager.spawn_handle().spawn("telemetry", worker.run());
telemetry
});
config
.network
@@ -373,22 +385,28 @@ pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError>
on_demand.clone(),
));
let (grandpa_block_import, _) =
sc_finality_grandpa::block_import(client.clone(), &(client.clone() as Arc<_>), select_chain)?;
let (grandpa_block_import, _) = sc_finality_grandpa::block_import(
client.clone(),
&(client.clone() as Arc<_>),
select_chain,
telemetry.as_ref().map(|x| x.handle()),
)?;
let aura_block_import =
sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(grandpa_block_import.clone(), client.clone());
let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _, _>(
sc_consensus_aura::slot_duration(&*client)?,
aura_block_import,
Some(Box::new(grandpa_block_import)),
client.clone(),
InherentDataProviders::new(),
&task_manager.spawn_essential_handle(),
config.prometheus_registry(),
sp_consensus::NeverCanAuthor,
)?;
let import_queue = sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _>(ImportQueueParams {
block_import: aura_block_import,
justification_import: Some(Box::new(grandpa_block_import)),
client: client.clone(),
inherent_data_providers: InherentDataProviders::new(),
spawner: &task_manager.spawn_essential_handle(),
can_author_with: sp_consensus::NeverCanAuthor,
slot_duration: sc_consensus_aura::slot_duration(&*client)?,
registry: config.prometheus_registry(),
check_for_equivocation: Default::default(),
telemetry: telemetry.as_ref().map(|x| x.handle()),
})?;
let (network, network_status_sinks, system_rpc_tx, network_starter) =
sc_service::build_network(sc_service::BuildNetworkParams {
@@ -402,13 +420,7 @@ pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError>
})?;
if config.offchain_worker.enabled {
sc_service::build_offchain_workers(
&config,
backend.clone(),
task_manager.spawn_handle(),
client.clone(),
network.clone(),
);
sc_service::build_offchain_workers(&config, task_manager.spawn_handle(), client.clone(), network.clone());
}
sc_service::spawn_tasks(sc_service::SpawnTasksParams {
@@ -424,7 +436,7 @@ pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError>
network,
network_status_sinks,
system_rpc_tx,
telemetry_span: None,
telemetry: telemetry.as_mut(),
})?;
network_starter.start_network();
+19 -16
View File
@@ -11,7 +11,8 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
hex-literal = "0.3"
libsecp256k1 = { version = "0.3.4", optional = true, default-features = false, features = ["hmac"] }
serde = { version = "1.0.123", optional = true, features = ["derive"] }
log = { version = "0.4.14", default-features = false }
serde = { version = "1.0.124", optional = true, features = ["derive"] }
# Bridge dependencies
@@ -19,17 +20,16 @@ bp-currency-exchange = { path = "../../../primitives/currency-exchange", default
bp-eth-poa = { path = "../../../primitives/ethereum-poa", default-features = false }
bp-header-chain = { path = "../../../primitives/header-chain", default-features = false }
bp-message-dispatch = { path = "../../../primitives/message-dispatch", default-features = false }
bp-message-lane = { path = "../../../primitives/message-lane", default-features = false }
bp-millau = { path = "../../../primitives/millau", default-features = false }
bp-rialto = { path = "../../../primitives/rialto", default-features = false }
bp-messages = { path = "../../../primitives/messages", default-features = false }
bp-millau = { path = "../../../primitives/chain-millau", default-features = false }
bp-rialto = { path = "../../../primitives/chain-rialto", default-features = false }
bp-runtime = { path = "../../../primitives/runtime", default-features = false }
bridge-runtime-common = { path = "../../runtime-common", default-features = false }
pallet-bridge-eth-poa = { path = "../../../modules/ethereum", default-features = false }
pallet-bridge-call-dispatch = { path = "../../../modules/call-dispatch", default-features = false }
pallet-bridge-currency-exchange = { path = "../../../modules/currency-exchange", default-features = false }
pallet-finality-verifier = { path = "../../../modules/finality-verifier", default-features = false }
pallet-substrate-bridge = { path = "../../../modules/substrate", default-features = false }
pallet-message-lane = { path = "../../../modules/message-lane", default-features = false }
pallet-bridge-dispatch = { path = "../../../modules/dispatch", default-features = false }
pallet-bridge-eth-poa = { path = "../../../modules/ethereum", default-features = false }
pallet-bridge-grandpa = { path = "../../../modules/grandpa", default-features = false }
pallet-bridge-messages = { path = "../../../modules/messages", default-features = false }
pallet-shift-session-manager = { path = "../../../modules/shift-session-manager", default-features = false }
# Substrate Dependencies
@@ -47,6 +47,7 @@ pallet-session = { git = "https://github.com/paritytech/substrate", branch = "ma
pallet-sudo = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-block-builder = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-consensus-aura = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
@@ -62,6 +63,7 @@ sp-transaction-pool = { git = "https://github.com/paritytech/substrate", branch
sp-trie = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-version = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
[dev-dependencies]
libsecp256k1 = { version = "0.3.4", features = ["hmac"] }
@@ -75,7 +77,7 @@ std = [
"bp-eth-poa/std",
"bp-header-chain/std",
"bp-message-dispatch/std",
"bp-message-lane/std",
"bp-messages/std",
"bp-millau/std",
"bp-rialto/std",
"bp-runtime/std",
@@ -86,19 +88,20 @@ std = [
"frame-support/std",
"frame-system-rpc-runtime-api/std",
"frame-system/std",
"log/std",
"pallet-aura/std",
"pallet-balances/std",
"pallet-bridge-eth-poa/std",
"pallet-bridge-call-dispatch/std",
"pallet-bridge-currency-exchange/std",
"pallet-finality-verifier/std",
"pallet-bridge-dispatch/std",
"pallet-bridge-eth-poa/std",
"pallet-bridge-grandpa/std",
"pallet-bridge-messages/std",
"pallet-grandpa/std",
"pallet-message-lane/std",
"pallet-randomness-collective-flip/std",
"pallet-shift-session-manager/std",
"pallet-substrate-bridge/std",
"pallet-sudo/std",
"pallet-timestamp/std",
"pallet-transaction-payment-rpc-runtime-api/std",
"pallet-transaction-payment/std",
"serde",
"sp-api/std",
@@ -124,6 +127,6 @@ runtime-benchmarks = [
"libsecp256k1",
"pallet-bridge-currency-exchange/runtime-benchmarks",
"pallet-bridge-eth-poa/runtime-benchmarks",
"pallet-message-lane/runtime-benchmarks",
"pallet-bridge-messages/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
]
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -1,4 +1,4 @@
// Copyright 2020 Parity Technologies (UK) Ltd.
// Copyright 2020-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -81,7 +81,7 @@ impl MaybeLockFundsTransaction for EthTransaction {
// we only accept transactions sending funds directly to the pre-configured address
if tx.unsigned.to != Some(LOCK_FUNDS_ADDRESS.into()) {
frame_support::debug::trace!(
log::trace!(
target: "runtime",
"Failed to parse fund locks transaction. Invalid peer recipient: {:?}",
tx.unsigned.to,
@@ -94,7 +94,7 @@ impl MaybeLockFundsTransaction for EthTransaction {
match tx.unsigned.payload.len() {
32 => recipient_raw.as_fixed_bytes_mut().copy_from_slice(&tx.unsigned.payload),
len => {
frame_support::debug::trace!(
log::trace!(
target: "runtime",
"Failed to parse fund locks transaction. Invalid recipient length: {}",
len,
@@ -106,7 +106,7 @@ impl MaybeLockFundsTransaction for EthTransaction {
let amount = tx.unsigned.value.low_u128();
if tx.unsigned.value != amount.into() {
frame_support::debug::trace!(
log::trace!(
target: "runtime",
"Failed to parse fund locks transaction. Invalid amount: {}",
tx.unsigned.value,
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
+109 -111
View File
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -43,6 +43,7 @@ use crate::millau_messages::{ToMillauMessagePayload, WithMillauMessageBridge};
use bridge_runtime_common::messages::{source::estimate_message_dispatch_and_delivery_fee, MessageBridge};
use codec::Decode;
use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use sp_api::impl_runtime_apis;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
@@ -69,8 +70,8 @@ pub use frame_system::Call as SystemCall;
pub use pallet_balances::Call as BalancesCall;
pub use pallet_bridge_currency_exchange::Call as BridgeCurrencyExchangeCall;
pub use pallet_bridge_eth_poa::Call as BridgeEthPoACall;
pub use pallet_message_lane::Call as MessageLaneCall;
pub use pallet_substrate_bridge::Call as BridgeMillauCall;
pub use pallet_bridge_grandpa::Call as BridgeGrandpaMillauCall;
pub use pallet_bridge_messages::Call as MessagesCall;
pub use pallet_sudo::Call as SudoCall;
pub use pallet_timestamp::Call as TimestampCall;
@@ -207,6 +208,7 @@ impl frame_system::Config for Runtime {
type DbWeight = DbWeight;
/// The designated SS58 prefix of this chain.
type SS58Prefix = SS58Prefix;
/// The set code logic, just the default since we're not a parachain.
type OnSetCode = ();
}
@@ -256,9 +258,9 @@ impl pallet_bridge_currency_exchange::Config<KovanCurrencyExchange> for Runtime
type DepositInto = DepositInto;
}
impl pallet_bridge_call_dispatch::Config for Runtime {
impl pallet_bridge_dispatch::Config for Runtime {
type Event = Event;
type MessageId = (bp_message_lane::LaneId, bp_message_lane::MessageNonce);
type MessageId = (bp_messages::LaneId, bp_messages::MessageNonce);
type Call = Call;
type CallFilter = ();
type EncodedCall = crate::millau_messages::FromMillauEncodedCall;
@@ -290,7 +292,7 @@ impl bp_currency_exchange::DepositInto for DepositInto {
// - deposited != 0: (should never happen in practice) deposit has been partially completed
match deposited_amount {
_ if deposited_amount == amount => {
frame_support::debug::trace!(
log::trace!(
target: "runtime",
"Deposited {} to {:?}",
amount,
@@ -300,7 +302,7 @@ impl bp_currency_exchange::DepositInto for DepositInto {
Ok(())
}
_ if deposited_amount == 0 => {
frame_support::debug::error!(
log::error!(
target: "runtime",
"Deposit of {} to {:?} has failed",
amount,
@@ -310,7 +312,7 @@ impl bp_currency_exchange::DepositInto for DepositInto {
Err(bp_currency_exchange::Error::DepositFailed)
}
_ => {
frame_support::debug::error!(
log::error!(
target: "runtime",
"Deposit of {} to {:?} has partially competed. {} has been deposited",
amount,
@@ -398,7 +400,7 @@ impl pallet_session::Config for Runtime {
type ValidatorIdOf = ();
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
type SessionManager = pallet_shift_session_manager::Module<Runtime>;
type SessionManager = pallet_shift_session_manager::Pallet<Runtime>;
type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type Keys = SessionKeys;
type DisabledValidatorsThreshold = ();
@@ -406,33 +408,34 @@ impl pallet_session::Config for Runtime {
type WeightInfo = ();
}
impl pallet_substrate_bridge::Config for Runtime {
type BridgedChain = bp_millau::Millau;
}
parameter_types! {
// This is a pretty unscientific cap.
//
// Note that once this is hit the pallet will essentially throttle incoming requests down to one
// call per block.
pub const MaxRequests: u32 = 50;
// Number of headers to keep.
//
// Assuming the worst case of every header being finalized, we will keep headers at least for a
// week.
pub const HeadersToKeep: u32 = 7 * bp_rialto::DAYS as u32;
}
impl pallet_finality_verifier::Config for Runtime {
impl pallet_bridge_grandpa::Config for Runtime {
type BridgedChain = bp_millau::Millau;
type HeaderChain = pallet_substrate_bridge::Module<Runtime>;
type AncestryProof = Vec<bp_millau::Header>;
type AncestryChecker = bp_header_chain::LinearAncestryChecker;
type MaxRequests = MaxRequests;
type HeadersToKeep = HeadersToKeep;
type WeightInfo = pallet_bridge_grandpa::weights::RialtoWeight<Runtime>;
}
impl pallet_shift_session_manager::Config for Runtime {}
parameter_types! {
pub const MaxMessagesToPruneAtOnce: bp_message_lane::MessageNonce = 8;
pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_message_lane::MessageNonce =
pub const MaxMessagesToPruneAtOnce: bp_messages::MessageNonce = 8;
pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce =
bp_rialto::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE;
pub const MaxUnconfirmedMessagesAtInboundLane: bp_message_lane::MessageNonce =
pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce =
bp_rialto::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE;
// `IdentityFee` is used by Rialto => we may use weight directly
pub const GetDeliveryConfirmationTransactionFee: Balance =
@@ -440,11 +443,13 @@ parameter_types! {
pub const RootAccountForPayments: Option<AccountId> = None;
}
pub(crate) type WithMillauMessageLaneInstance = pallet_message_lane::DefaultInstance;
impl pallet_message_lane::Config for Runtime {
/// Instance of the messages pallet used to relay messages to/from Millau chain.
pub type WithMillauMessagesInstance = pallet_bridge_messages::DefaultInstance;
impl pallet_bridge_messages::Config<WithMillauMessagesInstance> for Runtime {
type Event = Event;
type WeightInfo = pallet_message_lane::weights::RialtoWeight<Runtime>;
type Parameter = millau_messages::RialtoToMillauMessageLaneParameter;
type WeightInfo = pallet_bridge_messages::weights::RialtoWeight<Runtime>;
type Parameter = millau_messages::RialtoToMillauMessagesParameter;
type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce;
type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane;
type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane;
@@ -460,7 +465,7 @@ impl pallet_message_lane::Config for Runtime {
type TargetHeaderChain = crate::millau_messages::Millau;
type LaneMessageVerifier = crate::millau_messages::ToMillauMessageVerifier;
type MessageDeliveryAndDispatchPayment = pallet_message_lane::instant_payments::InstantCurrencyPayments<
type MessageDeliveryAndDispatchPayment = pallet_bridge_messages::instant_payments::InstantCurrencyPayments<
Runtime,
pallet_balances::Pallet<Runtime>,
GetDeliveryConfirmationTransactionFee,
@@ -481,10 +486,9 @@ construct_runtime!(
BridgeKovan: pallet_bridge_eth_poa::<Instance2>::{Pallet, Call, Config, Storage, ValidateUnsigned},
BridgeRialtoCurrencyExchange: pallet_bridge_currency_exchange::<Instance1>::{Pallet, Call},
BridgeKovanCurrencyExchange: pallet_bridge_currency_exchange::<Instance2>::{Pallet, Call},
BridgeMillau: pallet_substrate_bridge::{Pallet, Call, Storage, Config<T>},
BridgeFinalityVerifier: pallet_finality_verifier::{Pallet, Call},
BridgeCallDispatch: pallet_bridge_call_dispatch::{Pallet, Event<T>},
BridgeMillauMessageLane: pallet_message_lane::{Pallet, Call, Storage, Event<T>},
BridgeMillauGrandpa: pallet_bridge_grandpa::{Pallet, Call, Storage},
BridgeDispatch: pallet_bridge_dispatch::{Pallet, Event<T>},
BridgeMillauMessages: pallet_bridge_messages::{Pallet, Call, Storage, Event<T>},
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Call, Storage},
Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
@@ -522,6 +526,8 @@ pub type SignedExtra = (
pub type SignedPayload = generic::SignedPayload<Call, SignedExtra>;
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
/// Extrinsic type that has already been checked.
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;
/// Executive: handles dispatch to the various modules.
pub type Executive =
frame_executive::Executive<Runtime, Block, frame_system::ChainContext<Runtime>, Runtime, AllPallets>;
@@ -533,7 +539,7 @@ impl_runtime_apis! {
}
fn execute_block(block: Block) {
Executive::execute_block(block)
Executive::execute_block(block);
}
fn initialize_block(header: &<Block as BlockT>::Header) {
@@ -618,26 +624,14 @@ impl_runtime_apis! {
}
}
impl bp_millau::MillauHeaderApi<Block> for Runtime {
fn best_blocks() -> Vec<(bp_millau::BlockNumber, bp_millau::Hash)> {
BridgeMillau::best_headers()
}
fn finalized_block() -> (bp_millau::BlockNumber, bp_millau::Hash) {
let header = BridgeMillau::best_finalized();
impl bp_millau::MillauFinalityApi<Block> for Runtime {
fn best_finalized() -> (bp_millau::BlockNumber, bp_millau::Hash) {
let header = BridgeMillauGrandpa::best_finalized();
(header.number, header.hash())
}
fn incomplete_headers() -> Vec<(bp_millau::BlockNumber, bp_millau::Hash)> {
BridgeMillau::require_justifications()
}
fn is_known_block(hash: bp_millau::Hash) -> bool {
BridgeMillau::is_known_header(hash)
}
fn is_finalized_block(hash: bp_millau::Hash) -> bool {
BridgeMillau::is_finalized_header(hash)
fn is_known_header(hash: bp_millau::Hash) -> bool {
BridgeMillauGrandpa::is_known_header(hash)
}
}
@@ -669,8 +663,8 @@ impl_runtime_apis! {
}
impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
fn slot_duration() -> u64 {
Aura::slot_duration()
fn slot_duration() -> sp_consensus_aura::SlotDuration {
sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())
}
fn authorities() -> Vec<AuraId> {
@@ -678,6 +672,18 @@ impl_runtime_apis! {
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
Block,
Balance,
> for Runtime {
fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {
TransactionPayment::query_info(uxt, len)
}
fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {
TransactionPayment::query_fee_details(uxt, len)
}
}
impl sp_session::SessionKeys<Block> for Runtime {
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
SessionKeys::generate(seed)
@@ -723,7 +729,7 @@ impl_runtime_apis! {
impl bp_millau::ToMillauOutboundLaneApi<Block, Balance, ToMillauMessagePayload> for Runtime {
fn estimate_message_delivery_and_dispatch_fee(
_lane_id: bp_message_lane::LaneId,
_lane_id: bp_messages::LaneId,
payload: ToMillauMessagePayload,
) -> Option<Balance> {
estimate_message_dispatch_and_delivery_fee::<WithMillauMessageBridge>(
@@ -733,12 +739,12 @@ impl_runtime_apis! {
}
fn messages_dispatch_weight(
lane: bp_message_lane::LaneId,
begin: bp_message_lane::MessageNonce,
end: bp_message_lane::MessageNonce,
) -> Vec<(bp_message_lane::MessageNonce, Weight, u32)> {
lane: bp_messages::LaneId,
begin: bp_messages::MessageNonce,
end: bp_messages::MessageNonce,
) -> Vec<(bp_messages::MessageNonce, Weight, u32)> {
(begin..=end).filter_map(|nonce| {
let encoded_payload = BridgeMillauMessageLane::outbound_message_payload(lane, nonce)?;
let encoded_payload = BridgeMillauMessages::outbound_message_payload(lane, nonce)?;
let decoded_payload = millau_messages::ToMillauMessagePayload::decode(
&mut &encoded_payload[..]
).ok()?;
@@ -747,26 +753,26 @@ impl_runtime_apis! {
.collect()
}
fn latest_received_nonce(lane: bp_message_lane::LaneId) -> bp_message_lane::MessageNonce {
BridgeMillauMessageLane::outbound_latest_received_nonce(lane)
fn latest_received_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce {
BridgeMillauMessages::outbound_latest_received_nonce(lane)
}
fn latest_generated_nonce(lane: bp_message_lane::LaneId) -> bp_message_lane::MessageNonce {
BridgeMillauMessageLane::outbound_latest_generated_nonce(lane)
fn latest_generated_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce {
BridgeMillauMessages::outbound_latest_generated_nonce(lane)
}
}
impl bp_millau::FromMillauInboundLaneApi<Block> for Runtime {
fn latest_received_nonce(lane: bp_message_lane::LaneId) -> bp_message_lane::MessageNonce {
BridgeMillauMessageLane::inbound_latest_received_nonce(lane)
fn latest_received_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce {
BridgeMillauMessages::inbound_latest_received_nonce(lane)
}
fn latest_confirmed_nonce(lane: bp_message_lane::LaneId) -> bp_message_lane::MessageNonce {
BridgeMillauMessageLane::inbound_latest_confirmed_nonce(lane)
fn latest_confirmed_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce {
BridgeMillauMessages::inbound_latest_confirmed_nonce(lane)
}
fn unrewarded_relayers_state(lane: bp_message_lane::LaneId) -> bp_message_lane::UnrewardedRelayersState {
BridgeMillauMessageLane::inbound_unrewarded_relayers_state(lane)
fn unrewarded_relayers_state(lane: bp_messages::LaneId) -> bp_messages::UnrewardedRelayersState {
BridgeMillauMessages::inbound_unrewarded_relayers_state(lane)
}
}
@@ -776,6 +782,7 @@ impl_runtime_apis! {
config: frame_benchmarking::BenchmarkConfig,
) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
use frame_benchmarking::{Benchmarking, BenchmarkBatch, TrackedStorageKey, add_benchmark};
let whitelist: Vec<TrackedStorageKey> = vec![
// Block Number
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),
@@ -793,7 +800,7 @@ impl_runtime_apis! {
let params = (&config, &whitelist);
use pallet_bridge_currency_exchange::benchmarking::{
Module as BridgeCurrencyExchangeBench,
Pallet as BridgeCurrencyExchangeBench,
Config as BridgeCurrencyExchangeConfig,
ProofParams as BridgeCurrencyExchangeProofParams,
};
@@ -834,16 +841,16 @@ impl_runtime_apis! {
use crate::millau_messages::{ToMillauMessagePayload, WithMillauMessageBridge};
use bridge_runtime_common::messages;
use pallet_message_lane::benchmarking::{
Module as MessageLaneBench,
Config as MessageLaneConfig,
MessageDeliveryProofParams as MessageLaneMessageDeliveryProofParams,
MessageParams as MessageLaneMessageParams,
MessageProofParams as MessageLaneMessageProofParams,
ProofSize as MessageLaneProofSize,
use pallet_bridge_messages::benchmarking::{
Pallet as MessagesBench,
Config as MessagesConfig,
MessageDeliveryProofParams,
MessageParams,
MessageProofParams,
ProofSize as MessagesProofSize,
};
impl MessageLaneConfig<WithMillauMessageLaneInstance> for Runtime {
impl MessagesConfig<WithMillauMessagesInstance> for Runtime {
fn maximal_message_size() -> u32 {
messages::source::maximal_message_size::<WithMillauMessageBridge>()
}
@@ -864,10 +871,10 @@ impl_runtime_apis! {
}
fn prepare_outbound_message(
params: MessageLaneMessageParams<Self::AccountId>,
params: MessageParams<Self::AccountId>,
) -> (millau_messages::ToMillauMessagePayload, Balance) {
let message_payload = vec![0; params.size as usize];
let dispatch_origin = pallet_bridge_call_dispatch::CallOrigin::SourceAccount(
let dispatch_origin = pallet_bridge_dispatch::CallOrigin::SourceAccount(
params.sender_account,
);
@@ -877,25 +884,25 @@ impl_runtime_apis! {
origin: dispatch_origin,
call: message_payload,
};
(message, pallet_message_lane::benchmarking::MESSAGE_FEE.into())
(message, pallet_bridge_messages::benchmarking::MESSAGE_FEE.into())
}
fn prepare_message_proof(
params: MessageLaneMessageProofParams,
params: MessageProofParams,
) -> (millau_messages::FromMillauMessagesProof, Weight) {
use crate::millau_messages::{Millau, WithMillauMessageBridge};
use bp_message_lane::MessageKey;
use bp_messages::MessageKey;
use bridge_runtime_common::{
messages::ChainWithMessageLanes,
messages::ChainWithMessages,
messages_benchmarking::{ed25519_sign, prepare_message_proof},
};
use codec::Encode;
use frame_support::weights::GetDispatchInfo;
use pallet_message_lane::storage_keys;
use pallet_bridge_messages::storage_keys;
use sp_runtime::traits::Header;
let remark = match params.size {
MessageLaneProofSize::Minimal(ref size) => vec![0u8; *size as _],
MessagesProofSize::Minimal(ref size) => vec![0u8; *size as _],
_ => vec![],
};
let call = Call::System(SystemCall::remark(remark));
@@ -913,15 +920,16 @@ impl_runtime_apis! {
let make_millau_message_key = |message_key: MessageKey| storage_keys::message_key::<
Runtime,
<Millau as ChainWithMessageLanes>::MessageLaneInstance,
<Millau as ChainWithMessages>::MessagesInstance,
>(
&message_key.lane_id, message_key.nonce,
).0;
let make_millau_outbound_lane_data_key = |lane_id| storage_keys::outbound_lane_data_key::<
<Millau as ChainWithMessageLanes>::MessageLaneInstance,
<Millau as ChainWithMessages>::MessagesInstance,
>(
&lane_id,
).0;
let make_millau_header = |state_root| bp_millau::Header::new(
0,
Default::default(),
@@ -930,16 +938,16 @@ impl_runtime_apis! {
Default::default(),
);
prepare_message_proof::<WithMillauMessageBridge, bp_millau::Hasher, Runtime, _, _, _>(
prepare_message_proof::<WithMillauMessageBridge, bp_millau::Hasher, Runtime, (), _, _, _>(
params,
make_millau_message_key,
make_millau_outbound_lane_data_key,
make_millau_header,
call_weight,
pallet_bridge_call_dispatch::MessagePayload {
pallet_bridge_dispatch::MessagePayload {
spec_version: VERSION.spec_version,
weight: call_weight,
origin: pallet_bridge_call_dispatch::CallOrigin::<
origin: pallet_bridge_dispatch::CallOrigin::<
bp_millau::AccountId,
MultiSigner,
Signature,
@@ -954,20 +962,20 @@ impl_runtime_apis! {
}
fn prepare_message_delivery_proof(
params: MessageLaneMessageDeliveryProofParams<Self::AccountId>,
params: MessageDeliveryProofParams<Self::AccountId>,
) -> millau_messages::ToMillauMessagesDeliveryProof {
use crate::millau_messages::{Millau, WithMillauMessageBridge};
use bridge_runtime_common::{
messages::ChainWithMessageLanes,
messages::ChainWithMessages,
messages_benchmarking::prepare_message_delivery_proof,
};
use sp_runtime::traits::Header;
prepare_message_delivery_proof::<WithMillauMessageBridge, bp_millau::Hasher, Runtime, _, _>(
prepare_message_delivery_proof::<WithMillauMessageBridge, bp_millau::Hasher, Runtime, (), _, _>(
params,
|lane_id| pallet_message_lane::storage_keys::inbound_lane_data_key::<
|lane_id| pallet_bridge_messages::storage_keys::inbound_lane_data_key::<
Runtime,
<Millau as ChainWithMessageLanes>::MessageLaneInstance,
<Millau as ChainWithMessages>::MessagesInstance,
>(
&lane_id,
).0,
@@ -982,7 +990,6 @@ impl_runtime_apis! {
}
}
add_benchmark!(params, batches, pallet_bridge_eth_poa, BridgeKovan);
add_benchmark!(
params,
batches,
@@ -992,9 +999,10 @@ impl_runtime_apis! {
add_benchmark!(
params,
batches,
pallet_message_lane,
MessageLaneBench::<Runtime, WithMillauMessageLaneInstance>
pallet_bridge_messages,
MessagesBench::<Runtime, WithMillauMessagesInstance>
);
add_benchmark!(params, batches, pallet_bridge_grandpa, BridgeMillauGrandpa);
if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
Ok(batches)
@@ -1017,7 +1025,7 @@ where
AccountId: codec::Encode,
SpecVersion: codec::Encode,
{
pallet_bridge_call_dispatch::account_ownership_digest(
pallet_bridge_dispatch::account_ownership_digest(
millau_call,
rialto_account_id,
millau_spec_version,
@@ -1068,9 +1076,9 @@ mod tests {
#[test]
fn ensure_rialto_message_lane_weights_are_correct() {
type Weights = pallet_message_lane::weights::RialtoWeight<Runtime>;
type Weights = pallet_bridge_messages::weights::RialtoWeight<Runtime>;
pallet_message_lane::ensure_weights_are_correct::<Weights>(
pallet_bridge_messages::ensure_weights_are_correct::<Weights>(
bp_rialto::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT,
bp_rialto::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT,
bp_rialto::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT,
@@ -1079,34 +1087,24 @@ mod tests {
let max_incoming_message_proof_size = bp_millau::EXTRA_STORAGE_PROOF_SIZE.saturating_add(
messages::target::maximal_incoming_message_size(bp_rialto::max_extrinsic_size()),
);
pallet_message_lane::ensure_able_to_receive_message::<Weights>(
pallet_bridge_messages::ensure_able_to_receive_message::<Weights>(
bp_rialto::max_extrinsic_size(),
bp_rialto::max_extrinsic_weight(),
max_incoming_message_proof_size,
bridge_runtime_common::messages::transaction_weight_without_multiplier(
bp_rialto::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
max_incoming_message_proof_size as _,
0,
),
messages::target::maximal_incoming_message_dispatch_weight(bp_rialto::max_extrinsic_weight()),
);
let max_incoming_inbound_lane_data_proof_size = bp_message_lane::InboundLaneData::<()>::encoded_size_hint(
let max_incoming_inbound_lane_data_proof_size = bp_messages::InboundLaneData::<()>::encoded_size_hint(
bp_rialto::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE,
bp_millau::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE as _,
)
.unwrap_or(u32::MAX);
pallet_message_lane::ensure_able_to_receive_confirmation::<Weights>(
pallet_bridge_messages::ensure_able_to_receive_confirmation::<Weights>(
bp_rialto::max_extrinsic_size(),
bp_rialto::max_extrinsic_weight(),
max_incoming_inbound_lane_data_proof_size,
bp_millau::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE,
bp_millau::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE,
bridge_runtime_common::messages::transaction_weight_without_multiplier(
bp_rialto::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
max_incoming_inbound_lane_data_proof_size as _,
0,
),
);
}
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -14,52 +14,32 @@
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
//! Everything required to serve Millau <-> Rialto message lanes.
//! Everything required to serve Millau <-> Rialto messages.
use crate::Runtime;
use bp_message_lane::{
use bp_messages::{
source_chain::TargetHeaderChain,
target_chain::{ProvedMessages, SourceHeaderChain},
InboundLaneData, LaneId, Message, MessageNonce, Parameter as MessageLaneParameter,
InboundLaneData, LaneId, Message, MessageNonce, Parameter as MessagesParameter,
};
use bp_runtime::{InstanceId, MILLAU_BRIDGE_INSTANCE};
use bridge_runtime_common::messages::{self, ChainWithMessageLanes, MessageBridge};
use bridge_runtime_common::messages::{self, MessageBridge, MessageTransaction};
use codec::{Decode, Encode};
use frame_support::{
parameter_types,
weights::{DispatchClass, Weight, WeightToFeePolynomial},
weights::{DispatchClass, Weight},
RuntimeDebug,
};
use sp_core::storage::StorageKey;
use sp_runtime::{FixedPointNumber, FixedU128};
use sp_std::{convert::TryFrom, ops::RangeInclusive};
/// Initial value of `MillauToRialtoConversionRate` parameter.
pub const INITIAL_MILLAU_TO_RIALTO_CONVERSION_RATE: FixedU128 = FixedU128::from_inner(FixedU128::DIV);
parameter_types! {
/// Millau to Rialto conversion rate. Initially we treat both tokens as equal.
storage MillauToRialtoConversionRate: FixedU128 = 1.into();
}
/// Storage key of the Rialto -> Millau message in the runtime storage.
pub fn message_key(lane: &LaneId, nonce: MessageNonce) -> StorageKey {
pallet_message_lane::storage_keys::message_key::<Runtime, <Rialto as ChainWithMessageLanes>::MessageLaneInstance>(
lane, nonce,
)
}
/// Storage key of the Rialto -> Millau message lane state in the runtime storage.
pub fn outbound_lane_data_key(lane: &LaneId) -> StorageKey {
pallet_message_lane::storage_keys::outbound_lane_data_key::<<Rialto as ChainWithMessageLanes>::MessageLaneInstance>(
lane,
)
}
/// Storage key of the Millau -> Rialto message lane state in the runtime storage.
pub fn inbound_lane_data_key(lane: &LaneId) -> StorageKey {
pallet_message_lane::storage_keys::inbound_lane_data_key::<
Runtime,
<Rialto as ChainWithMessageLanes>::MessageLaneInstance,
>(lane)
pub storage MillauToRialtoConversionRate: FixedU128 = INITIAL_MILLAU_TO_RIALTO_CONVERSION_RATE;
}
/// Message payload for Rialto -> Millau messages.
@@ -78,7 +58,7 @@ pub type FromMillauEncodedCall = messages::target::FromBridgedChainEncodedMessag
pub type FromMillauMessageDispatch = messages::target::FromBridgedChainMessageDispatch<
WithMillauMessageBridge,
crate::Runtime,
pallet_bridge_call_dispatch::DefaultInstance,
pallet_bridge_dispatch::DefaultInstance,
>;
/// Messages proof for Millau -> Rialto messages.
@@ -99,59 +79,6 @@ impl MessageBridge for WithMillauMessageBridge {
type ThisChain = Rialto;
type BridgedChain = Millau;
fn maximal_extrinsic_size_on_target_chain() -> u32 {
bp_millau::max_extrinsic_size()
}
fn weight_limits_of_message_on_bridged_chain(_message_payload: &[u8]) -> RangeInclusive<Weight> {
// we don't want to relay too large messages + keep reserve for future upgrades
let upper_limit = messages::target::maximal_incoming_message_dispatch_weight(bp_millau::max_extrinsic_weight());
// we're charging for payload bytes in `WithMillauMessageBridge::weight_of_delivery_transaction` function
//
// this bridge may be used to deliver all kind of messages, so we're not making any assumptions about
// minimal dispatch weight here
0..=upper_limit
}
fn weight_of_delivery_transaction(message_payload: &[u8]) -> Weight {
let message_payload_len = u32::try_from(message_payload.len())
.map(Into::into)
.unwrap_or(Weight::MAX);
let extra_bytes_in_payload =
message_payload_len.saturating_sub(pallet_message_lane::EXPECTED_DEFAULT_MESSAGE_LENGTH.into());
messages::transaction_weight_without_multiplier(
bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
message_payload_len.saturating_add(bp_rialto::EXTRA_STORAGE_PROOF_SIZE as _),
extra_bytes_in_payload
.saturating_mul(bp_millau::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT)
.saturating_add(bp_millau::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT),
)
}
fn weight_of_delivery_confirmation_transaction_on_this_chain() -> Weight {
let inbounded_data_size: Weight =
InboundLaneData::<bp_millau::AccountId>::encoded_size_hint(bp_millau::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, 1)
.map(Into::into)
.unwrap_or(Weight::MAX);
messages::transaction_weight_without_multiplier(
bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
inbounded_data_size.saturating_add(bp_millau::EXTRA_STORAGE_PROOF_SIZE as _),
bp_rialto::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT,
)
}
fn this_weight_to_this_balance(weight: Weight) -> bp_rialto::Balance {
<crate::Runtime as pallet_transaction_payment::Config>::WeightToFee::calc(&weight)
}
fn bridged_weight_to_bridged_balance(weight: Weight) -> bp_millau::Balance {
// we're using the same weights in both chains now
<crate::Runtime as pallet_transaction_payment::Config>::WeightToFee::calc(&weight) as _
}
fn bridged_balance_to_this_balance(bridged_balance: bp_millau::Balance) -> bp_rialto::Balance {
bp_rialto::Balance::try_from(MillauToRialtoConversionRate::get().saturating_mul_int(bridged_balance))
.unwrap_or(bp_rialto::Balance::MAX)
@@ -162,42 +89,114 @@ impl MessageBridge for WithMillauMessageBridge {
#[derive(RuntimeDebug, Clone, Copy)]
pub struct Rialto;
impl messages::ChainWithMessageLanes for Rialto {
impl messages::ChainWithMessages for Rialto {
type Hash = bp_rialto::Hash;
type AccountId = bp_rialto::AccountId;
type Signer = bp_rialto::AccountSigner;
type Signature = bp_rialto::Signature;
type Call = crate::Call;
type Weight = Weight;
type Balance = bp_rialto::Balance;
type MessageLaneInstance = crate::WithMillauMessageLaneInstance;
type MessagesInstance = crate::WithMillauMessagesInstance;
}
impl messages::ThisChainWithMessageLanes for Rialto {
impl messages::ThisChainWithMessages for Rialto {
type Call = crate::Call;
fn is_outbound_lane_enabled(lane: &LaneId) -> bool {
*lane == LaneId::default()
*lane == [0, 0, 0, 0] || *lane == [0, 0, 0, 1]
}
fn maximal_pending_messages_at_outbound_lane() -> MessageNonce {
MessageNonce::MAX
}
fn estimate_delivery_confirmation_transaction() -> MessageTransaction<Weight> {
let inbound_data_size =
InboundLaneData::<bp_rialto::AccountId>::encoded_size_hint(bp_rialto::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, 1)
.unwrap_or(u32::MAX);
MessageTransaction {
dispatch_weight: bp_rialto::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT,
size: inbound_data_size
.saturating_add(bp_millau::EXTRA_STORAGE_PROOF_SIZE)
.saturating_add(bp_rialto::TX_EXTRA_BYTES),
}
}
fn transaction_payment(transaction: MessageTransaction<Weight>) -> bp_rialto::Balance {
// in our testnets, both per-byte fee and weight-to-fee are 1:1
messages::transaction_payment(
bp_rialto::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
1,
FixedU128::zero(),
|weight| weight as _,
transaction,
)
}
}
/// Millau chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct Millau;
impl messages::ChainWithMessageLanes for Millau {
impl messages::ChainWithMessages for Millau {
type Hash = bp_millau::Hash;
type AccountId = bp_millau::AccountId;
type Signer = bp_millau::AccountSigner;
type Signature = bp_millau::Signature;
type Call = (); // unknown to us
type Weight = Weight;
type Balance = bp_millau::Balance;
type MessageLaneInstance = pallet_message_lane::DefaultInstance;
type MessagesInstance = pallet_bridge_messages::DefaultInstance;
}
impl messages::BridgedChainWithMessages for Millau {
fn maximal_extrinsic_size() -> u32 {
bp_millau::max_extrinsic_size()
}
fn message_weight_limits(_message_payload: &[u8]) -> RangeInclusive<Weight> {
// we don't want to relay too large messages + keep reserve for future upgrades
let upper_limit = messages::target::maximal_incoming_message_dispatch_weight(bp_millau::max_extrinsic_weight());
// we're charging for payload bytes in `WithMillauMessageBridge::transaction_payment` function
//
// this bridge may be used to deliver all kind of messages, so we're not making any assumptions about
// minimal dispatch weight here
0..=upper_limit
}
fn estimate_delivery_transaction(
message_payload: &[u8],
message_dispatch_weight: Weight,
) -> MessageTransaction<Weight> {
let message_payload_len = u32::try_from(message_payload.len()).unwrap_or(u32::MAX);
let extra_bytes_in_payload = Weight::from(message_payload_len)
.saturating_sub(pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH.into());
MessageTransaction {
dispatch_weight: extra_bytes_in_payload
.saturating_mul(bp_millau::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT)
.saturating_add(bp_millau::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT)
.saturating_add(message_dispatch_weight),
size: message_payload_len
.saturating_add(bp_rialto::EXTRA_STORAGE_PROOF_SIZE)
.saturating_add(bp_millau::TX_EXTRA_BYTES),
}
}
fn transaction_payment(transaction: MessageTransaction<Weight>) -> bp_millau::Balance {
// in our testnets, both per-byte fee and weight-to-fee are 1:1
messages::transaction_payment(
bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
1,
FixedU128::zero(),
|weight| weight as _,
transaction,
)
}
}
impl TargetHeaderChain<ToMillauMessagePayload, bp_millau::AccountId> for Millau {
@@ -238,15 +237,15 @@ impl SourceHeaderChain<bp_millau::Balance> for Millau {
/// Rialto -> Millau message lane pallet parameters.
#[derive(RuntimeDebug, Clone, Encode, Decode, PartialEq, Eq)]
pub enum RialtoToMillauMessageLaneParameter {
pub enum RialtoToMillauMessagesParameter {
/// The conversion formula we use is: `RialtoTokens = MillauTokens * conversion_rate`.
MillauToRialtoConversionRate(FixedU128),
}
impl MessageLaneParameter for RialtoToMillauMessageLaneParameter {
impl MessagesParameter for RialtoToMillauMessagesParameter {
fn save(&self) {
match *self {
RialtoToMillauMessageLaneParameter::MillauToRialtoConversionRate(ref conversion_rate) => {
RialtoToMillauMessagesParameter::MillauToRialtoConversionRate(ref conversion_rate) => {
MillauToRialtoConversionRate::set(conversion_rate)
}
}
@@ -1,4 +1,4 @@
// Copyright 2020 Parity Technologies (UK) Ltd.
// Copyright 2020-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
+10 -10
View File
@@ -15,11 +15,11 @@ hash-db = { version = "0.15.2", default-features = false }
# Bridge dependencies
bp-message-dispatch = { path = "../../primitives/message-dispatch", default-features = false }
bp-message-lane = { path = "../../primitives/message-lane", default-features = false }
bp-messages = { path = "../../primitives/messages", default-features = false }
bp-runtime = { path = "../../primitives/runtime", default-features = false }
pallet-bridge-call-dispatch = { path = "../../modules/call-dispatch", default-features = false }
pallet-message-lane = { path = "../../modules/message-lane", default-features = false }
pallet-substrate-bridge = { path = "../../modules/substrate", default-features = false }
pallet-bridge-dispatch = { path = "../../modules/dispatch", default-features = false }
pallet-bridge-grandpa = { path = "../../modules/grandpa", default-features = false }
pallet-bridge-messages = { path = "../../modules/messages", default-features = false }
# Substrate dependencies
@@ -34,14 +34,14 @@ sp-trie = { git = "https://github.com/paritytech/substrate", branch = "master" ,
default = ["std"]
std = [
"bp-message-dispatch/std",
"bp-message-lane/std",
"bp-messages/std",
"bp-runtime/std",
"codec/std",
"frame-support/std",
"hash-db/std",
"pallet-bridge-call-dispatch/std",
"pallet-message-lane/std",
"pallet-substrate-bridge/std",
"pallet-bridge-dispatch/std",
"pallet-bridge-grandpa/std",
"pallet-bridge-messages/std",
"sp-core/std",
"sp-runtime/std",
"sp-state-machine/std",
@@ -50,7 +50,7 @@ std = [
]
runtime-benchmarks = [
"ed25519-dalek/u64_backend",
"pallet-message-lane/runtime-benchmarks",
"pallet-substrate-bridge/runtime-benchmarks",
"pallet-bridge-grandpa/runtime-benchmarks",
"pallet-bridge-messages/runtime-benchmarks",
"sp-state-machine",
]
+79 -86
View File
@@ -1,22 +1,22 @@
# Helpers for Message Lane Module Integration
# Helpers for Messages Module Integration
The [`messages`](./src/messages.rs) module of this crate contains a bunch of helpers for integrating
message lane module into your runtime. Basic prerequisites of these helpers are:
messages module into your runtime. Basic prerequisites of these helpers are:
- we're going to bridge Substrate-based chain with another Substrate-based chain;
- both chains have [message lane module](../../modules/message-lane/README.md), Substrate bridge
module and the [call dispatch module](../../modules/call-dispatch/README.md);
- both chains have [messages module](../../modules/messages/README.md), Substrate bridge
module and the [call dispatch module](../../modules/dispatch/README.md);
- all message lanes are identical and may be used to transfer the same messages;
- the messages sent over the bridge are dispatched using
[call dispatch module](../../modules/call-dispatch/README.md);
- the messages are `pallet_bridge_call_dispatch::MessagePayload` structures, where `call` field is
[call dispatch module](../../modules/dispatch/README.md);
- the messages are `pallet_bridge_dispatch::MessagePayload` structures, where `call` field is
encoded `Call` of the target chain. This means that the `Call` is opaque to the
[message lane module](../../modules/message-lane/README.md) instance at the source chain.
[messages module](../../modules/messages/README.md) instance at the source chain.
It is pre-encoded by the message submitter;
- all proofs in the [message lane module](../../modules/message-lane/README.md) transactions are
- all proofs in the [messages module](../../modules/messages/README.md) transactions are
based on the storage proofs from the bridged chain: storage proof of the outbound message (value
from the `pallet_message_lane::Store::MessagePayload` map), storage proof of the outbound lane
state (value from the `pallet_message_lane::Store::OutboundLanes` map) and storage proof of the
inbound lane state (value from the `pallet_message_lane::Store::InboundLanes` map);
from the `pallet_bridge_messages::Store::MessagePayload` map), storage proof of the outbound lane
state (value from the `pallet_bridge_messages::Store::OutboundLanes` map) and storage proof of the
inbound lane state (value from the `pallet_bridge_messages::Store::InboundLanes` map);
- storage proofs are built at the finalized headers of the corresponding chain. So all message lane
transactions with proofs are verifying storage proofs against finalized chain headers from
Substrate bridge module.
@@ -27,23 +27,69 @@ message lane module into your runtime. Basic prerequisites of these helpers are:
## Contents
- [`MessageBridge` Trait](#messagebridge-trait)
- [`ChainWithMessageLanes` Trait ](#chainwithmessagelanes-trait)
- [`ChainWithMessages` Trait ](#ChainWithMessages-trait)
- [Helpers for the Source Chain](#helpers-for-the-source-chain)
- [Helpers for the Target Chain](#helpers-for-the-target-chain)
## `MessageBridge` Trait
The essence of your integration will be a struct that implements a `MessageBridge` trait. Let's
review every method and give some implementation hints here:
The essence of your integration will be a struct that implements a `MessageBridge` trait. It has
single method (`MessageBridge::bridged_balance_to_this_balance`), used to convert from bridged chain
tokens into this chain tokens. The bridge also requires two associated types to be specified -
`ThisChain` and `BridgedChain`.
- `MessageBridge::maximal_extrinsic_size_on_target_chain`: you will need to return the maximal
extrinsic size of the target chain from this function. This may be the constant that is updated
when your runtime is upgraded, or you may use the
[message lane parameters functionality](../../modules/message-lane/README.md#Non-Essential-Functionality)
to allow the pallet owner to update this value more frequently (you may also want to use this
functionality for all constants that are used in other methods described below).
Worth to say that if you're going to use hardcoded constant (conversion rate) in the
`MessageBridge::bridged_balance_to_this_balance` method (or in any other method of
`ThisChainWithMessages` or `BridgedChainWithMessages` traits), then you should take a
look at the
[messages parameters functionality](../../modules/messages/README.md#Non-Essential-Functionality).
They allow pallet owner to update constants more frequently than runtime upgrade happens.
- `MessageBridge::weight_limits_of_message_on_bridged_chain`: you'll need to return a range of
## `ChainWithMessages` Trait
The trait is quite simple and can easily be implemented - you just need to specify types used at the
corresponding chain. There is single exception, though (it may be changed in the future):
- `ChainWithMessages::MessagesInstance`: this is used to compute runtime storage keys. There
may be several instances of messages pallet, included in the Runtime. Every instance stores
messages and these messages stored under different keys. When we are verifying storage proofs from
the bridged chain, we should know which instance we're talking to. This is fine, but there's
significant inconvenience with that - this chain runtime must have the same messages pallet
instance. This does not necessarily mean that we should use the same instance on both chains -
this instance may be used to bridge with another chain/instance, or may not be used at all.
## `ThisChainWithMessages` Trait
This trait represents this chain from bridge point of view. Let's review every method of this trait:
- `ThisChainWithMessages::is_outbound_lane_enabled`: is used to check whether given lane accepts
outbound messages.
- `ThisChainWithMessages::maximal_pending_messages_at_outbound_lane`: you should return maximal
number of pending (undelivered) messages from this function. Returning small values would require
relayers to operate faster and could make message sending logic more complicated. On the other
hand, returning large values could lead to chain state growth.
- `ThisChainWithMessages::estimate_delivery_confirmation_transaction`: you'll need to return
estimated size and dispatch weight of the delivery confirmation transaction (that happens on
this chain) from this function.
- `ThisChainWithMessages::transaction_payment`: you'll need to return fee that the submitter
must pay for given transaction on this chain. Normally, you would use transaction payment pallet
for this. However, if your chain has non-zero fee multiplier set, this would mean that the
payment will be computed using current value of this multiplier. But since this transaction
will be submitted in the future, you may want to choose other value instead. Otherwise,
non-altruistic relayer may choose not to submit this transaction until number of transactions
will decrease.
## `BridgedChainWithMessages` Trait
This trait represents this chain from bridge point of view. Let's review every method of this trait:
- `BridgedChainWithMessages::maximal_extrinsic_size`: you will need to return the maximal
extrinsic size of the target chain from this function.
- `MessageBridge::message_weight_limits`: you'll need to return a range of
dispatch weights that the outbound message may take at the target chain. Please keep in mind that
our helpers assume that the message is an encoded call of the target chain. But we never decode
this call at the source chain. So you can't simply get dispatch weight from pre-dispatch
@@ -55,66 +101,13 @@ review every method and give some implementation hints here:
maximal weight of extrinsic at the target chain. In our test chains, we reject all messages that
have declared dispatch weight larger than 50% of the maximal bridged extrinsic weight.
- `MessageBridge::weight_of_delivery_transaction`: you will need to return the maximal weight of the
delivery transaction that delivers a given message to the target chain. There are three main
things to notice:
- `MessageBridge::estimate_delivery_transaction`: you will need to return estimated dispatch weight and
size of the delivery transaction that delivers a given message to the target chain.
1. weight, returned from this function is then used to compute the fee that the
message sender needs to pay for the delivery transaction. So it shall not be a simple dispatch
weight of delivery call - it should be the "weight" of the transaction itself, including per-byte
"weight", "weight" of signed extras and etc.
1. the delivery transaction brings storage proof of
the message, not the message itself. So your transaction will include extra bytes. We suggest
computing the size of single empty value storage proof at the source chain, increase this value a
bit and hardcode it in the source chain runtime code. This size then must be added to the size of
payload and included in the weight computation;
1. before implementing this function, please take
a look at the
[weight formula of delivery transaction](../../modules/message-lane/README.md#Weight-of-receive_messages_proof-call).
It adds some extra weight for every additional byte of the proof (everything above
`pallet_message_lane::EXPECTED_DEFAULT_MESSAGE_LENGTH`), so it's not trivial. Even better, please
refer to [our implementation](../millau/runtime/src/rialto_messages.rs) for test chains for
details.
- `MessageBridge::weight_of_delivery_confirmation_transaction_on_this_chain`: you'll need to return
the maximal weight of a single message delivery confirmation transaction on this chain. All points
from the previous paragraph are also relevant here.
- `MessageBridge::this_weight_to_this_balance`: this function needs to convert weight units into fee
units on this chain. Most probably this can be done by calling
`pallet_transaction_payment::Config::WeightToFee::calc()` for passed weight.
- `MessageBridge::bridged_weight_to_bridged_balance`: this function needs to convert weight units
into fee units on the target chain. The best case is when you have the same conversion formula on
both chains - then you may just call the same formula from the previous paragraph. Otherwise,
you'll need to hardcode this formula into your runtime.
- `MessageBridge::bridged_balance_to_this_balance`: this may be the easiest method to implement and
the hardest to maintain at the same time. If you don't have any automatic methods to determine
conversion rate, then you'll probably need to maintain it by yourself (by updating conversion
rate, stored in runtime storage). This means that if you're too late with an update, then you risk
to accept messages with lower-than-expected fee. So it may be wise to have some reserve in this
conversion rate, even if that means larger delivery and dispatch fees.
## `ChainWithMessageLanes` Trait
Apart from its methods, `MessageBridge` also has two associated types that are implementing the
`ChainWithMessageLanes` trait. One is for this chain and the other is for the bridged chain. The
trait is quite simple and can easily be implemented - you just need to specify types used at the
corresponding chain. There are two exceptions, though. Both may be changed in the future. Here they
are:
- `ChainWithMessageLanes::Call`: it isn't a good idea to reference bridged chain runtime from your
runtime (cyclic references + maintaining on upgrades). So you can't know the type of bridged chain
call in your runtime. This type isn't actually used at this chain, so you may use `()` instead.
- `ChainWithMessageLanes::MessageLaneInstance`: this is used to compute runtime storage keys. There
may be several instances of message lane pallet, included in the Runtime. Every instance stores
messages and these messages stored under different keys. When we are verifying storage proofs from
the bridged chain, we should know which instance we're talking to. This is fine, but there's
significant inconvenience with that - this chain runtime must have the same message lane pallet
instance. This does not necessarily mean that we should use the same instance on both chains -
this instance may be used to bridge with another chain/instance, or may not be used at all.
- `MessageBridge::transaction_payment`: you'll need to return fee that the submitter
must pay for given transaction on bridged chain. The best case is when you have the same conversion
formula on both chains - then you may just reuse the `ThisChainWithMessages::transaction_payment`
implementation. Otherwise, you'll need to hardcode this formula into your runtime.
## Helpers for the Source Chain
@@ -125,10 +118,10 @@ are: `maximal_message_size`, `verify_chain_message`, `verify_messages_delivery_p
`estimate_message_dispatch_and_delivery_fee`.
`FromThisChainMessagePayload` is a message that the sender sends through our bridge. It is the
`pallet_bridge_call_dispatch::MessagePayload`, where `call` field is encoded target chain call. So
`pallet_bridge_dispatch::MessagePayload`, where `call` field is encoded target chain call. So
at this chain we don't see internals of this call - we just know its size.
`FromThisChainMessageVerifier` is an implementation of `bp_message_lane::LaneMessageVerifier`. It
`FromThisChainMessageVerifier` is an implementation of `bp_messages::LaneMessageVerifier`. It
has following checks in its `verify_message` method:
1. it'll verify that the used outbound lane is enabled in our runtime;
@@ -138,8 +131,8 @@ has following checks in its `verify_message` method:
1. it'll reject a message if it has the wrong dispatch origin declared. Like if the submitter is not
the root of this chain, but it tries to dispatch the message at the target chain using
`pallet_bridge_call_dispatch::CallOrigin::SourceRoot` origin. Or he has provided wrong signature
in the `pallet_bridge_call_dispatch::CallOrigin::TargetAccount` origin;
`pallet_bridge_dispatch::CallOrigin::SourceRoot` origin. Or he has provided wrong signature
in the `pallet_bridge_dispatch::CallOrigin::TargetAccount` origin;
1. it'll reject a message if the delivery and dispatch fee that the submitter wants to pay is lesser
than the fee that is computed using the `estimate_message_dispatch_and_delivery_fee` function.
@@ -174,10 +167,10 @@ The helpers for the target chain reside in the `target` submodule of the
`FromBridgedChainMessagePayload` corresponds to the `FromThisChainMessagePayload` at the bridged
chain. We expect that messages with this payload are stored in the `OutboundMessages` storage map of
the [message lane module](../../modules/message-lane/README.md). This map is used to build
the [messages module](../../modules/messages/README.md). This map is used to build
`FromBridgedChainMessagesProof`. The proof holds the lane id, range of message nonces included in
the proof, storage proof of `OutboundMessages` entries and the hash of bridged chain header that has
been used to build the proof. Additionally, there's storage proof may contain the proof of outbound
lane state. It may be required to prune `relayers` entries at this chain (see
[message lane module documentation](../../modules/message-lane/README.md#What-about-other-Constants-in-the-Message-Lane-Module-Configuration-Trait)
[messages module documentation](../../modules/messages/README.md#What-about-other-Constants-in-the-Messages-Module-Configuration-Trait)
for details). This proof is verified by the `verify_messages_proof` function.
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -21,17 +21,19 @@
//! of to elements - message lane id and message nonce.
use bp_message_dispatch::MessageDispatch as _;
use bp_message_lane::{
use bp_messages::{
source_chain::{LaneMessageVerifier, Sender},
target_chain::{DispatchMessage, MessageDispatch, ProvedLaneMessages, ProvedMessages},
InboundLaneData, LaneId, Message, MessageData, MessageKey, MessageNonce, OutboundLaneData,
};
use bp_runtime::{InstanceId, Size};
use bp_runtime::{InstanceId, Size, StorageProofChecker};
use codec::{Decode, Encode};
use frame_support::{traits::Instance, weights::Weight, RuntimeDebug};
use hash_db::Hasher;
use pallet_substrate_bridge::StorageProofChecker;
use sp_runtime::traits::{CheckedAdd, CheckedDiv, CheckedMul};
use sp_runtime::{
traits::{AtLeast32BitUnsigned, CheckedAdd, CheckedDiv, CheckedMul},
FixedPointNumber, FixedPointOperand, FixedU128,
};
use sp_std::{cmp::PartialOrd, convert::TryFrom, fmt::Debug, marker::PhantomData, ops::RangeInclusive, vec::Vec};
use sp_trie::StorageProof;
@@ -44,44 +46,16 @@ pub trait MessageBridge {
const RELAYER_FEE_PERCENT: u32;
/// This chain in context of message bridge.
type ThisChain: ThisChainWithMessageLanes;
type ThisChain: ThisChainWithMessages;
/// Bridged chain in context of message bridge.
type BridgedChain: ChainWithMessageLanes;
type BridgedChain: BridgedChainWithMessages;
/// Maximal extrinsic size on target chain.
fn maximal_extrinsic_size_on_target_chain() -> u32;
/// Returns feasible weights range for given message payload on the target chain.
///
/// If message is being sent with the weight that is out of this range, then it
/// should be rejected.
///
/// Weights returned from this function shall not include transaction overhead
/// (like weight of signature and signed extensions verification), because they're
/// already accounted by the `weight_of_delivery_transaction`. So this function should
/// return pure call dispatch weights range.
fn weight_limits_of_message_on_bridged_chain(
message_payload: &[u8],
) -> RangeInclusive<WeightOf<BridgedChain<Self>>>;
/// Maximal weight of single message delivery transaction on Bridged chain.
fn weight_of_delivery_transaction(message_payload: &[u8]) -> WeightOf<BridgedChain<Self>>;
/// Maximal weight of single message delivery confirmation transaction on This chain.
fn weight_of_delivery_confirmation_transaction_on_this_chain() -> WeightOf<ThisChain<Self>>;
/// Convert weight of This chain to the fee (paid in Balance) of This chain.
fn this_weight_to_this_balance(weight: WeightOf<ThisChain<Self>>) -> BalanceOf<ThisChain<Self>>;
/// Convert weight of the Bridged chain to the fee (paid in Balance) of the Bridged chain.
fn bridged_weight_to_bridged_balance(weight: WeightOf<BridgedChain<Self>>) -> BalanceOf<BridgedChain<Self>>;
/// Convert Bridged chain Balance into This chain Balance.
/// Convert Bridged chain balance into This chain balance.
fn bridged_balance_to_this_balance(bridged_balance: BalanceOf<BridgedChain<Self>>) -> BalanceOf<ThisChain<Self>>;
}
/// Chain that has `message-lane` and `call-dispatch` modules.
pub trait ChainWithMessageLanes {
/// Chain that has `pallet-bridge-messages` and `dispatch` modules.
pub trait ChainWithMessages {
/// Hash used in the chain.
type Hash: Decode;
/// Accound id on the chain.
@@ -90,8 +64,6 @@ pub trait ChainWithMessageLanes {
type Signer: Decode;
/// Signature type used on the chain.
type Signature: Decode;
/// Call type on the chain.
type Call: Encode + Decode;
/// Type of weight that is used on the chain. This would almost always be a regular
/// `frame_support::weight::Weight`. But since the meaning of weight on different chains
/// may be different, the `WeightOf<>` construct is used to avoid confusion between
@@ -100,58 +72,104 @@ pub trait ChainWithMessageLanes {
/// Type of balances that is used on the chain.
type Balance: Encode + Decode + CheckedAdd + CheckedDiv + CheckedMul + PartialOrd + From<u32> + Copy;
/// Instance of the message-lane pallet.
type MessageLaneInstance: Instance;
/// Instance of the `pallet-bridge-messages` pallet.
type MessagesInstance: Instance;
}
/// This chain that has `message-lane` and `call-dispatch` modules.
pub trait ThisChainWithMessageLanes: ChainWithMessageLanes {
/// Message related transaction parameters estimation.
#[derive(RuntimeDebug)]
pub struct MessageTransaction<Weight> {
/// The estimated dispatch weight of the transaction.
pub dispatch_weight: Weight,
/// The estimated size of the encoded transaction.
pub size: u32,
}
/// This chain that has `pallet-bridge-messages` and `dispatch` modules.
pub trait ThisChainWithMessages: ChainWithMessages {
/// Call type on the chain.
type Call: Encode + Decode;
/// Are we accepting any messages to the given lane?
fn is_outbound_lane_enabled(lane: &LaneId) -> bool;
/// Maximal number of pending (not yet delivered) messages at this chain.
/// Maximal number of pending (not yet delivered) messages at This chain.
///
/// Any messages over this limit, will be rejected.
fn maximal_pending_messages_at_outbound_lane() -> MessageNonce;
/// Estimate size and weight of single message delivery confirmation transaction at This chain.
fn estimate_delivery_confirmation_transaction() -> MessageTransaction<WeightOf<Self>>;
/// Returns minimal transaction fee that must be paid for given transaction at This chain.
fn transaction_payment(transaction: MessageTransaction<WeightOf<Self>>) -> BalanceOf<Self>;
}
/// Bridged chain that has `pallet-bridge-messages` and `dispatch` modules.
pub trait BridgedChainWithMessages: ChainWithMessages {
/// Maximal extrinsic size at Bridged chain.
fn maximal_extrinsic_size() -> u32;
/// Returns feasible weights range for given message payload at the Bridged chain.
///
/// If message is being sent with the weight that is out of this range, then it
/// should be rejected.
///
/// Weights returned from this function shall not include transaction overhead
/// (like weight of signature and signed extensions verification), because they're
/// already accounted by the `weight_of_delivery_transaction`. So this function should
/// return pure call dispatch weights range.
fn message_weight_limits(message_payload: &[u8]) -> RangeInclusive<Self::Weight>;
/// Estimate size and weight of single message delivery transaction at the Bridged chain.
fn estimate_delivery_transaction(
message_payload: &[u8],
message_dispatch_weight: WeightOf<Self>,
) -> MessageTransaction<WeightOf<Self>>;
/// Returns minimal transaction fee that must be paid for given transaction at the Bridged chain.
fn transaction_payment(transaction: MessageTransaction<WeightOf<Self>>) -> BalanceOf<Self>;
}
pub(crate) type ThisChain<B> = <B as MessageBridge>::ThisChain;
pub(crate) type BridgedChain<B> = <B as MessageBridge>::BridgedChain;
pub(crate) type HashOf<C> = <C as ChainWithMessageLanes>::Hash;
pub(crate) type AccountIdOf<C> = <C as ChainWithMessageLanes>::AccountId;
pub(crate) type SignerOf<C> = <C as ChainWithMessageLanes>::Signer;
pub(crate) type SignatureOf<C> = <C as ChainWithMessageLanes>::Signature;
pub(crate) type WeightOf<C> = <C as ChainWithMessageLanes>::Weight;
pub(crate) type BalanceOf<C> = <C as ChainWithMessageLanes>::Balance;
pub(crate) type CallOf<C> = <C as ChainWithMessageLanes>::Call;
pub(crate) type MessageLaneInstanceOf<C> = <C as ChainWithMessageLanes>::MessageLaneInstance;
pub(crate) type HashOf<C> = <C as ChainWithMessages>::Hash;
pub(crate) type AccountIdOf<C> = <C as ChainWithMessages>::AccountId;
pub(crate) type SignerOf<C> = <C as ChainWithMessages>::Signer;
pub(crate) type SignatureOf<C> = <C as ChainWithMessages>::Signature;
pub(crate) type WeightOf<C> = <C as ChainWithMessages>::Weight;
pub(crate) type BalanceOf<C> = <C as ChainWithMessages>::Balance;
pub(crate) type MessagesInstanceOf<C> = <C as ChainWithMessages>::MessagesInstance;
pub(crate) type CallOf<C> = <C as ThisChainWithMessages>::Call;
/// Raw storage proof type (just raw trie nodes).
type RawStorageProof = Vec<Vec<u8>>;
/// Compute weight of transaction at runtime where:
/// Compute fee of transaction at runtime where regular transaction payment pallet is being used.
///
/// - transaction payment pallet is being used;
/// - fee multiplier is zero.
pub fn transaction_weight_without_multiplier(
base_weight: Weight,
payload_size: Weight,
dispatch_weight: Weight,
) -> Weight {
// non-adjustable per-byte weight is mapped 1:1 to tx weight
let per_byte_weight = payload_size;
/// The value of `multiplier` parameter is the expected value of `pallet_transaction_payment::NextFeeMultiplier`
/// at the moment when transaction is submitted. If you're charging this payment in advance (and that's what
/// happens with delivery and confirmation transaction in this crate), then there's a chance that the actual
/// fee will be larger than what is paid in advance. So the value must be chosen carefully.
pub fn transaction_payment<Balance: AtLeast32BitUnsigned + FixedPointOperand>(
base_extrinsic_weight: Weight,
per_byte_fee: Balance,
multiplier: FixedU128,
weight_to_fee: impl Fn(Weight) -> Balance,
transaction: MessageTransaction<Weight>,
) -> Balance {
// base fee is charged for every tx
let base_fee = weight_to_fee(base_extrinsic_weight);
// we assume that adjustable per-byte weight is always zero
let adjusted_per_byte_weight = 0;
// non-adjustable per-byte fee
let len_fee = per_byte_fee.saturating_mul(Balance::from(transaction.size));
// we assume that transaction tip we use is also zero
let transaction_tip_weight = 0;
// the adjustable part of the fee
let unadjusted_weight_fee = weight_to_fee(transaction.dispatch_weight);
let adjusted_weight_fee = multiplier.saturating_mul_int(unadjusted_weight_fee);
base_weight
.saturating_add(per_byte_weight)
.saturating_add(adjusted_per_byte_weight)
.saturating_add(transaction_tip_weight)
.saturating_add(dispatch_weight)
base_fee.saturating_add(len_fee).saturating_add(adjusted_weight_fee)
}
/// Sub-module that is declaring types required for processing This -> Bridged chain messages.
@@ -162,7 +180,7 @@ pub mod source {
pub type BridgedChainOpaqueCall = Vec<u8>;
/// Message payload for This -> Bridged chain messages.
pub type FromThisChainMessagePayload<B> = pallet_bridge_call_dispatch::MessagePayload<
pub type FromThisChainMessagePayload<B> = pallet_bridge_dispatch::MessagePayload<
AccountIdOf<ThisChain<B>>,
SignerOf<BridgedChain<B>>,
SignatureOf<BridgedChain<B>>,
@@ -203,7 +221,7 @@ pub mod source {
/// This verifier assumes following:
///
/// - all message lanes are equivalent, so all checks are the same;
/// - messages are being dispatched using `pallet-bridge-call-dispatch` pallet on the target chain.
/// - messages are being dispatched using `pallet-bridge-dispatch` pallet on the target chain.
///
/// Following checks are made:
///
@@ -249,8 +267,8 @@ pub mod source {
}
// Do the dispatch-specific check. We assume that the target chain uses
// `CallDispatch`, so we verify the message accordingly.
pallet_bridge_call_dispatch::verify_message_origin(submitter, payload).map_err(|_| BAD_ORIGIN)?;
// `Dispatch`, so we verify the message accordingly.
pallet_bridge_dispatch::verify_message_origin(submitter, payload).map_err(|_| BAD_ORIGIN)?;
let minimal_fee_in_this_tokens =
estimate_message_dispatch_and_delivery_fee::<B>(payload, B::RELAYER_FEE_PERCENT)?;
@@ -266,7 +284,7 @@ pub mod source {
/// Return maximal message size of This -> Bridged chain message.
pub fn maximal_message_size<B: MessageBridge>() -> u32 {
super::target::maximal_incoming_message_size(B::maximal_extrinsic_size_on_target_chain())
super::target::maximal_incoming_message_size(BridgedChain::<B>::maximal_extrinsic_size())
}
/// Do basic Bridged-chain specific verification of This -> Bridged chain message.
@@ -277,7 +295,7 @@ pub mod source {
pub fn verify_chain_message<B: MessageBridge>(
payload: &FromThisChainMessagePayload<B>,
) -> Result<(), &'static str> {
let weight_limits = B::weight_limits_of_message_on_bridged_chain(&payload.call);
let weight_limits = BridgedChain::<B>::message_weight_limits(&payload.call);
if !weight_limits.contains(&payload.weight.into()) {
return Err("Incorrect message weight declared");
}
@@ -308,18 +326,17 @@ pub mod source {
relayer_fee_percent: u32,
) -> Result<BalanceOf<ThisChain<B>>, &'static str> {
// the fee (in Bridged tokens) of all transactions that are made on the Bridged chain
let delivery_fee = B::bridged_weight_to_bridged_balance(B::weight_of_delivery_transaction(&payload.call));
let dispatch_fee = B::bridged_weight_to_bridged_balance(payload.weight.into());
let delivery_transaction =
BridgedChain::<B>::estimate_delivery_transaction(&payload.call, payload.weight.into());
let delivery_transaction_fee = BridgedChain::<B>::transaction_payment(delivery_transaction);
// the fee (in This tokens) of all transactions that are made on This chain
let delivery_confirmation_fee =
B::this_weight_to_this_balance(B::weight_of_delivery_confirmation_transaction_on_this_chain());
let confirmation_transaction = ThisChain::<B>::estimate_delivery_confirmation_transaction();
let confirmation_transaction_fee = ThisChain::<B>::transaction_payment(confirmation_transaction);
// minimal fee (in This tokens) is a sum of all required fees
let minimal_fee = delivery_fee
.checked_add(&dispatch_fee)
.map(B::bridged_balance_to_this_balance)
.and_then(|fee| fee.checked_add(&delivery_confirmation_fee));
let minimal_fee =
B::bridged_balance_to_this_balance(delivery_transaction_fee).checked_add(&confirmation_transaction_fee);
// before returning, add extra fee that is paid to the relayer (relayer interest)
minimal_fee
@@ -339,25 +356,24 @@ pub mod source {
proof: FromBridgedChainMessagesDeliveryProof<HashOf<BridgedChain<B>>>,
) -> Result<ParsedMessagesDeliveryProofFromBridgedChain<B>, &'static str>
where
ThisRuntime: pallet_substrate_bridge::Config,
ThisRuntime: pallet_message_lane::Config<MessageLaneInstanceOf<BridgedChain<B>>>,
HashOf<BridgedChain<B>>:
Into<bp_runtime::HashOf<<ThisRuntime as pallet_substrate_bridge::Config>::BridgedChain>>,
ThisRuntime: pallet_bridge_grandpa::Config,
ThisRuntime: pallet_bridge_messages::Config<MessagesInstanceOf<BridgedChain<B>>>,
HashOf<BridgedChain<B>>: Into<bp_runtime::HashOf<<ThisRuntime as pallet_bridge_grandpa::Config>::BridgedChain>>,
{
let FromBridgedChainMessagesDeliveryProof {
bridged_header_hash,
storage_proof,
lane,
} = proof;
pallet_substrate_bridge::Module::<ThisRuntime>::parse_finalized_storage_proof(
pallet_bridge_grandpa::Pallet::<ThisRuntime>::parse_finalized_storage_proof(
bridged_header_hash.into(),
StorageProof::new(storage_proof),
|storage| {
// Messages delivery proof is just proof of single storage key read => any error
// is fatal.
let storage_inbound_lane_data_key = pallet_message_lane::storage_keys::inbound_lane_data_key::<
let storage_inbound_lane_data_key = pallet_bridge_messages::storage_keys::inbound_lane_data_key::<
ThisRuntime,
MessageLaneInstanceOf<BridgedChain<B>>,
MessagesInstanceOf<BridgedChain<B>>,
>(&lane);
let raw_inbound_lane_data = storage
.read_value(storage_inbound_lane_data_key.0.as_ref())
@@ -378,14 +394,14 @@ pub mod target {
use super::*;
/// Call origin for Bridged -> This chain messages.
pub type FromBridgedChainMessageCallOrigin<B> = pallet_bridge_call_dispatch::CallOrigin<
pub type FromBridgedChainMessageCallOrigin<B> = pallet_bridge_dispatch::CallOrigin<
AccountIdOf<BridgedChain<B>>,
SignerOf<ThisChain<B>>,
SignatureOf<ThisChain<B>>,
>;
/// Decoded Bridged -> This message payload.
pub type FromBridgedChainMessagePayload<B> = pallet_bridge_call_dispatch::MessagePayload<
pub type FromBridgedChainMessagePayload<B> = pallet_bridge_dispatch::MessagePayload<
AccountIdOf<BridgedChain<B>>,
SignerOf<ThisChain<B>>,
SignatureOf<ThisChain<B>>,
@@ -440,19 +456,19 @@ pub mod target {
/// Dispatching Bridged -> This chain messages.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct FromBridgedChainMessageDispatch<B, ThisRuntime, ThisCallDispatchInstance> {
_marker: PhantomData<(B, ThisRuntime, ThisCallDispatchInstance)>,
pub struct FromBridgedChainMessageDispatch<B, ThisRuntime, ThisDispatchInstance> {
_marker: PhantomData<(B, ThisRuntime, ThisDispatchInstance)>,
}
impl<B: MessageBridge, ThisRuntime, ThisCallDispatchInstance>
MessageDispatch<<BridgedChain<B> as ChainWithMessageLanes>::Balance>
for FromBridgedChainMessageDispatch<B, ThisRuntime, ThisCallDispatchInstance>
impl<B: MessageBridge, ThisRuntime, ThisDispatchInstance>
MessageDispatch<<BridgedChain<B> as ChainWithMessages>::Balance>
for FromBridgedChainMessageDispatch<B, ThisRuntime, ThisDispatchInstance>
where
ThisCallDispatchInstance: frame_support::traits::Instance,
ThisRuntime: pallet_bridge_call_dispatch::Config<ThisCallDispatchInstance, MessageId = (LaneId, MessageNonce)>,
<ThisRuntime as pallet_bridge_call_dispatch::Config<ThisCallDispatchInstance>>::Event:
From<pallet_bridge_call_dispatch::RawEvent<(LaneId, MessageNonce), ThisCallDispatchInstance>>,
pallet_bridge_call_dispatch::Module<ThisRuntime, ThisCallDispatchInstance>:
ThisDispatchInstance: frame_support::traits::Instance,
ThisRuntime: pallet_bridge_dispatch::Config<ThisDispatchInstance, MessageId = (LaneId, MessageNonce)>,
<ThisRuntime as pallet_bridge_dispatch::Config<ThisDispatchInstance>>::Event:
From<pallet_bridge_dispatch::RawEvent<(LaneId, MessageNonce), ThisDispatchInstance>>,
pallet_bridge_dispatch::Pallet<ThisRuntime, ThisDispatchInstance>:
bp_message_dispatch::MessageDispatch<(LaneId, MessageNonce), Message = FromBridgedChainMessagePayload<B>>,
{
type DispatchPayload = FromBridgedChainMessagePayload<B>;
@@ -465,7 +481,7 @@ pub mod target {
fn dispatch(message: DispatchMessage<Self::DispatchPayload, BalanceOf<BridgedChain<B>>>) {
let message_id = (message.key.lane_id, message.key.nonce);
pallet_bridge_call_dispatch::Module::<ThisRuntime, ThisCallDispatchInstance>::dispatch(
pallet_bridge_dispatch::Pallet::<ThisRuntime, ThisDispatchInstance>::dispatch(
B::INSTANCE,
message_id,
message.data.payload.map_err(drop),
@@ -493,16 +509,15 @@ pub mod target {
messages_count: u32,
) -> Result<ProvedMessages<Message<BalanceOf<BridgedChain<B>>>>, &'static str>
where
ThisRuntime: pallet_substrate_bridge::Config,
ThisRuntime: pallet_message_lane::Config<MessageLaneInstanceOf<BridgedChain<B>>>,
HashOf<BridgedChain<B>>:
Into<bp_runtime::HashOf<<ThisRuntime as pallet_substrate_bridge::Config>::BridgedChain>>,
ThisRuntime: pallet_bridge_grandpa::Config,
ThisRuntime: pallet_bridge_messages::Config<MessagesInstanceOf<BridgedChain<B>>>,
HashOf<BridgedChain<B>>: Into<bp_runtime::HashOf<<ThisRuntime as pallet_bridge_grandpa::Config>::BridgedChain>>,
{
verify_messages_proof_with_parser::<B, _, _>(
proof,
messages_count,
|bridged_header_hash, bridged_storage_proof| {
pallet_substrate_bridge::Module::<ThisRuntime>::parse_finalized_storage_proof(
pallet_bridge_grandpa::Pallet::<ThisRuntime>::parse_finalized_storage_proof(
bridged_header_hash.into(),
StorageProof::new(bridged_storage_proof),
|storage_adapter| storage_adapter,
@@ -556,11 +571,11 @@ pub mod target {
where
H: Hasher,
B: MessageBridge,
ThisRuntime: pallet_message_lane::Config<MessageLaneInstanceOf<BridgedChain<B>>>,
ThisRuntime: pallet_bridge_messages::Config<MessagesInstanceOf<BridgedChain<B>>>,
{
fn read_raw_outbound_lane_data(&self, lane_id: &LaneId) -> Option<Vec<u8>> {
let storage_outbound_lane_data_key = pallet_message_lane::storage_keys::outbound_lane_data_key::<
MessageLaneInstanceOf<BridgedChain<B>>,
let storage_outbound_lane_data_key = pallet_bridge_messages::storage_keys::outbound_lane_data_key::<
MessagesInstanceOf<BridgedChain<B>>,
>(lane_id);
self.storage
.read_value(storage_outbound_lane_data_key.0.as_ref())
@@ -568,9 +583,9 @@ pub mod target {
}
fn read_raw_message(&self, message_key: &MessageKey) -> Option<Vec<u8>> {
let storage_message_key = pallet_message_lane::storage_keys::message_key::<
let storage_message_key = pallet_bridge_messages::storage_keys::message_key::<
ThisRuntime,
MessageLaneInstanceOf<BridgedChain<B>>,
MessagesInstanceOf<BridgedChain<B>>,
>(&message_key.lane_id, message_key.nonce);
self.storage.read_value(storage_message_key.0.as_ref()).ok()?
}
@@ -681,31 +696,6 @@ mod tests {
type ThisChain = ThisChain;
type BridgedChain = BridgedChain;
fn maximal_extrinsic_size_on_target_chain() -> u32 {
BRIDGED_CHAIN_MAX_EXTRINSIC_SIZE
}
fn weight_limits_of_message_on_bridged_chain(message_payload: &[u8]) -> RangeInclusive<Weight> {
let begin = std::cmp::min(BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT, message_payload.len() as Weight);
begin..=BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT
}
fn weight_of_delivery_transaction(_message_payload: &[u8]) -> Weight {
DELIVERY_TRANSACTION_WEIGHT
}
fn weight_of_delivery_confirmation_transaction_on_this_chain() -> Weight {
DELIVERY_CONFIRMATION_TRANSACTION_WEIGHT
}
fn this_weight_to_this_balance(weight: Weight) -> ThisChainBalance {
ThisChainBalance(weight as u32 * THIS_CHAIN_WEIGHT_TO_BALANCE_RATE as u32)
}
fn bridged_weight_to_bridged_balance(weight: Weight) -> BridgedChainBalance {
BridgedChainBalance(weight as u32 * BRIDGED_CHAIN_WEIGHT_TO_BALANCE_RATE as u32)
}
fn bridged_balance_to_this_balance(bridged_balance: BridgedChainBalance) -> ThisChainBalance {
ThisChainBalance(bridged_balance.0 * BRIDGED_CHAIN_TO_THIS_CHAIN_BALANCE_RATE as u32)
}
@@ -722,30 +712,6 @@ mod tests {
type ThisChain = BridgedChain;
type BridgedChain = ThisChain;
fn maximal_extrinsic_size_on_target_chain() -> u32 {
unreachable!()
}
fn weight_limits_of_message_on_bridged_chain(_message_payload: &[u8]) -> RangeInclusive<Weight> {
unreachable!()
}
fn weight_of_delivery_transaction(_message_payload: &[u8]) -> Weight {
unreachable!()
}
fn weight_of_delivery_confirmation_transaction_on_this_chain() -> Weight {
unreachable!()
}
fn this_weight_to_this_balance(_weight: Weight) -> BridgedChainBalance {
unreachable!()
}
fn bridged_weight_to_bridged_balance(_weight: Weight) -> ThisChainBalance {
unreachable!()
}
fn bridged_balance_to_this_balance(_this_balance: ThisChainBalance) -> BridgedChainBalance {
unreachable!()
}
@@ -840,19 +806,20 @@ mod tests {
struct ThisChain;
impl ChainWithMessageLanes for ThisChain {
impl ChainWithMessages for ThisChain {
type Hash = ();
type AccountId = ThisChainAccountId;
type Signer = ThisChainSigner;
type Signature = ThisChainSignature;
type Call = ThisChainCall;
type Weight = frame_support::weights::Weight;
type Balance = ThisChainBalance;
type MessageLaneInstance = pallet_message_lane::DefaultInstance;
type MessagesInstance = pallet_bridge_messages::DefaultInstance;
}
impl ThisChainWithMessageLanes for ThisChain {
impl ThisChainWithMessages for ThisChain {
type Call = ThisChainCall;
fn is_outbound_lane_enabled(lane: &LaneId) -> bool {
lane == TEST_LANE_ID
}
@@ -860,23 +827,56 @@ mod tests {
fn maximal_pending_messages_at_outbound_lane() -> MessageNonce {
MAXIMAL_PENDING_MESSAGES_AT_TEST_LANE
}
fn estimate_delivery_confirmation_transaction() -> MessageTransaction<WeightOf<Self>> {
MessageTransaction {
dispatch_weight: DELIVERY_CONFIRMATION_TRANSACTION_WEIGHT,
size: 0,
}
}
fn transaction_payment(transaction: MessageTransaction<WeightOf<Self>>) -> BalanceOf<Self> {
ThisChainBalance(transaction.dispatch_weight as u32 * THIS_CHAIN_WEIGHT_TO_BALANCE_RATE as u32)
}
}
impl BridgedChainWithMessages for ThisChain {
fn maximal_extrinsic_size() -> u32 {
unreachable!()
}
fn message_weight_limits(_message_payload: &[u8]) -> RangeInclusive<Self::Weight> {
unreachable!()
}
fn estimate_delivery_transaction(
_message_payload: &[u8],
_message_dispatch_weight: WeightOf<Self>,
) -> MessageTransaction<WeightOf<Self>> {
unreachable!()
}
fn transaction_payment(_transaction: MessageTransaction<WeightOf<Self>>) -> BalanceOf<Self> {
unreachable!()
}
}
struct BridgedChain;
impl ChainWithMessageLanes for BridgedChain {
impl ChainWithMessages for BridgedChain {
type Hash = ();
type AccountId = BridgedChainAccountId;
type Signer = BridgedChainSigner;
type Signature = BridgedChainSignature;
type Call = BridgedChainCall;
type Weight = frame_support::weights::Weight;
type Balance = BridgedChainBalance;
type MessageLaneInstance = pallet_message_lane::DefaultInstance;
type MessagesInstance = pallet_bridge_messages::DefaultInstance;
}
impl ThisChainWithMessageLanes for BridgedChain {
impl ThisChainWithMessages for BridgedChain {
type Call = BridgedChainCall;
fn is_outbound_lane_enabled(_lane: &LaneId) -> bool {
unreachable!()
}
@@ -884,6 +884,39 @@ mod tests {
fn maximal_pending_messages_at_outbound_lane() -> MessageNonce {
unreachable!()
}
fn estimate_delivery_confirmation_transaction() -> MessageTransaction<WeightOf<Self>> {
unreachable!()
}
fn transaction_payment(_transaction: MessageTransaction<WeightOf<Self>>) -> BalanceOf<Self> {
unreachable!()
}
}
impl BridgedChainWithMessages for BridgedChain {
fn maximal_extrinsic_size() -> u32 {
BRIDGED_CHAIN_MAX_EXTRINSIC_SIZE
}
fn message_weight_limits(message_payload: &[u8]) -> RangeInclusive<Self::Weight> {
let begin = std::cmp::min(BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT, message_payload.len() as Weight);
begin..=BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT
}
fn estimate_delivery_transaction(
_message_payload: &[u8],
message_dispatch_weight: WeightOf<Self>,
) -> MessageTransaction<WeightOf<Self>> {
MessageTransaction {
dispatch_weight: DELIVERY_TRANSACTION_WEIGHT + message_dispatch_weight,
size: 0,
}
}
fn transaction_payment(transaction: MessageTransaction<WeightOf<Self>>) -> BalanceOf<Self> {
BridgedChainBalance(transaction.dispatch_weight as u32 * BRIDGED_CHAIN_WEIGHT_TO_BALANCE_RATE as u32)
}
}
fn test_lane_outbound_data() -> OutboundLaneData {
@@ -896,7 +929,7 @@ mod tests {
let message_on_bridged_chain = source::FromThisChainMessagePayload::<OnBridgedChainBridge> {
spec_version: 1,
weight: 100,
origin: pallet_bridge_call_dispatch::CallOrigin::SourceRoot,
origin: pallet_bridge_dispatch::CallOrigin::SourceRoot,
call: ThisChainCall::Transfer.encode(),
}
.encode();
@@ -910,7 +943,7 @@ mod tests {
target::FromBridgedChainMessagePayload::<OnThisChainBridge> {
spec_version: 1,
weight: 100,
origin: pallet_bridge_call_dispatch::CallOrigin::SourceRoot,
origin: pallet_bridge_dispatch::CallOrigin::SourceRoot,
call: target::FromBridgedChainEncodedMessageCall::<OnThisChainBridge> {
encoded_call: ThisChainCall::Transfer.encode(),
_marker: PhantomData::default(),
@@ -927,7 +960,7 @@ mod tests {
source::FromThisChainMessagePayload::<OnThisChainBridge> {
spec_version: 1,
weight: 100,
origin: pallet_bridge_call_dispatch::CallOrigin::SourceRoot,
origin: pallet_bridge_dispatch::CallOrigin::SourceRoot,
call: vec![42],
}
}
@@ -977,7 +1010,7 @@ mod tests {
let payload = source::FromThisChainMessagePayload::<OnThisChainBridge> {
spec_version: 1,
weight: 100,
origin: pallet_bridge_call_dispatch::CallOrigin::SourceRoot,
origin: pallet_bridge_dispatch::CallOrigin::SourceRoot,
call: vec![42],
};
@@ -1020,7 +1053,7 @@ mod tests {
let payload = source::FromThisChainMessagePayload::<OnThisChainBridge> {
spec_version: 1,
weight: 100,
origin: pallet_bridge_call_dispatch::CallOrigin::SourceAccount(ThisChainAccountId(1)),
origin: pallet_bridge_dispatch::CallOrigin::SourceAccount(ThisChainAccountId(1)),
call: vec![42],
};
@@ -1087,7 +1120,7 @@ mod tests {
> {
spec_version: 1,
weight: 5,
origin: pallet_bridge_call_dispatch::CallOrigin::SourceRoot,
origin: pallet_bridge_dispatch::CallOrigin::SourceRoot,
call: vec![1, 2, 3, 4, 5, 6],
},)
.is_err()
@@ -1102,7 +1135,7 @@ mod tests {
> {
spec_version: 1,
weight: BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT + 1,
origin: pallet_bridge_call_dispatch::CallOrigin::SourceRoot,
origin: pallet_bridge_dispatch::CallOrigin::SourceRoot,
call: vec![1, 2, 3, 4, 5, 6],
},)
.is_err()
@@ -1117,7 +1150,7 @@ mod tests {
> {
spec_version: 1,
weight: BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT,
origin: pallet_bridge_call_dispatch::CallOrigin::SourceRoot,
origin: pallet_bridge_dispatch::CallOrigin::SourceRoot,
call: vec![0; source::maximal_message_size::<OnThisChainBridge>() as usize + 1],
},)
.is_err()
@@ -1132,7 +1165,7 @@ mod tests {
> {
spec_version: 1,
weight: BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT,
origin: pallet_bridge_call_dispatch::CallOrigin::SourceRoot,
origin: pallet_bridge_dispatch::CallOrigin::SourceRoot,
call: vec![0; source::maximal_message_size::<OnThisChainBridge>() as _],
},),
Ok(()),
@@ -1371,4 +1404,38 @@ mod tests {
Err(target::MessageProofError::MessagesCountMismatch),
);
}
#[test]
fn transaction_payment_works_with_zero_multiplier() {
assert_eq!(
transaction_payment(
100,
10,
FixedU128::zero(),
|weight| weight,
MessageTransaction {
size: 50,
dispatch_weight: 777
},
),
100 + 50 * 10,
);
}
#[test]
fn transaction_payment_works_with_non_zero_multiplier() {
assert_eq!(
transaction_payment(
100,
10,
FixedU128::one(),
|weight| weight,
MessageTransaction {
size: 50,
dispatch_weight: 777
},
),
100 + 50 * 10 + 777,
);
}
}
@@ -1,4 +1,4 @@
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
@@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
//! Everything required to run benchmarks of message-lanes, based on
//! Everything required to run benchmarks of messages module, based on
//! `bridge_runtime_common::messages` implementation.
#![cfg(feature = "runtime-benchmarks")]
@@ -24,11 +24,11 @@ use crate::messages::{
BridgedChain, HashOf, MessageBridge, ThisChain,
};
use bp_message_lane::{LaneId, MessageData, MessageKey, MessagePayload};
use bp_messages::{LaneId, MessageData, MessageKey, MessagePayload};
use codec::Encode;
use ed25519_dalek::{PublicKey, SecretKey, Signer, KEYPAIR_LENGTH, SECRET_KEY_LENGTH};
use frame_support::weights::Weight;
use pallet_message_lane::benchmarking::{MessageDeliveryProofParams, MessageProofParams, ProofSize};
use pallet_bridge_messages::benchmarking::{MessageDeliveryProofParams, MessageProofParams, ProofSize};
use sp_core::Hasher;
use sp_runtime::traits::Header;
use sp_std::prelude::*;
@@ -62,7 +62,7 @@ pub fn ed25519_sign(target_call: &impl Encode, source_account_id: &impl Encode)
}
/// Prepare proof of messages for the `receive_messages_proof` call.
pub fn prepare_message_proof<B, H, R, MM, ML, MH>(
pub fn prepare_message_proof<B, H, R, FI, MM, ML, MH>(
params: MessageProofParams,
make_bridged_message_storage_key: MM,
make_bridged_outbound_lane_data_key: ML,
@@ -73,7 +73,8 @@ pub fn prepare_message_proof<B, H, R, MM, ML, MH>(
where
B: MessageBridge,
H: Hasher,
R: pallet_substrate_bridge::Config,
R: pallet_bridge_grandpa::Config<FI>,
FI: 'static,
<R::BridgedChain as bp_runtime::Chain>::Hash: Into<HashOf<BridgedChain<B>>>,
MM: Fn(MessageKey) -> Vec<u8>,
ML: Fn(LaneId) -> Vec<u8>,
@@ -129,7 +130,7 @@ where
// prepare Bridged chain header and insert it into the Substrate pallet
let bridged_header = make_bridged_header(root);
let bridged_header_hash = bridged_header.hash();
pallet_substrate_bridge::initialize_for_benchmarks::<R>(bridged_header);
pallet_bridge_grandpa::initialize_for_benchmarks::<R, FI>(bridged_header);
(
FromBridgedChainMessagesProof {
@@ -146,7 +147,7 @@ where
}
/// Prepare proof of messages delivery for the `receive_messages_delivery_proof` call.
pub fn prepare_message_delivery_proof<B, H, R, ML, MH>(
pub fn prepare_message_delivery_proof<B, H, R, FI, ML, MH>(
params: MessageDeliveryProofParams<AccountIdOf<ThisChain<B>>>,
make_bridged_inbound_lane_data_key: ML,
make_bridged_header: MH,
@@ -154,7 +155,8 @@ pub fn prepare_message_delivery_proof<B, H, R, ML, MH>(
where
B: MessageBridge,
H: Hasher,
R: pallet_substrate_bridge::Config,
R: pallet_bridge_grandpa::Config<FI>,
FI: 'static,
<R::BridgedChain as bp_runtime::Chain>::Hash: Into<HashOf<BridgedChain<B>>>,
ML: Fn(LaneId) -> Vec<u8>,
MH: Fn(H::Out) -> <R::BridgedChain as bp_runtime::Chain>::Header,
@@ -181,7 +183,7 @@ where
// prepare Bridged chain header and insert it into the Substrate pallet
let bridged_header = make_bridged_header(root);
let bridged_header_hash = bridged_header.hash();
pallet_substrate_bridge::initialize_for_benchmarks::<R>(bridged_header);
pallet_bridge_grandpa::initialize_for_benchmarks::<R, FI>(bridged_header);
FromBridgedChainMessagesDeliveryProof {
bridged_header_hash: bridged_header_hash.into(),
+3 -3
View File
@@ -48,14 +48,14 @@ notice = "warn"
# A list of advisory IDs to ignore. Note that ignored advisories will still
# output a note when they are encountered.
ignore = [
# generic-array lifetime errasure. If all upstream crates upgrade to >=0.14.0
# we can remove this.
"RUSTSEC-2020-0146",
# yaml-rust < clap. Not feasible to upgrade and also not possible to trigger in practice.
"RUSTSEC-2018-0006",
# We need to wait until Substrate updates their `wasmtime` dependency to fix this.
# TODO: See issue #676: https://github.com/paritytech/parity-bridges-common/issues/676
"RUSTSEC-2021-0013",
# We need to wait until Substrate updates their `libp2p` dependency to fix this.
# TODO: See issue #681: https://github.com/paritytech/parity-bridges-common/issues/681
"RUSTSEC-2020-0123",
# We need to wait until Substrate updates their `hyper` dependency to fix this.
# TODO: See issue #710: https://github.com/paritytech/parity-bridges-common/issues/681
"RUSTSEC-2021-0020",
@@ -2,22 +2,23 @@
#
# This image is meant to be used as a building block when building images for
# the various components in the bridge repo, such as nodes and relayers.
FROM ubuntu:xenial
FROM ubuntu:20.04
ENV LAST_DEPS_UPDATE 2020-12-21
ENV LAST_DEPS_UPDATE 2021-04-01
ENV DEBIAN_FRONTEND=noninteractive
RUN set -eux; \
apt-get update && \
apt-get install -y curl ca-certificates && \
apt-get install -y cmake pkg-config libssl-dev git clang libclang-dev
ENV LAST_CERTS_UPDATE 2020-12-21
ENV LAST_CERTS_UPDATE 2021-04-01
RUN update-ca-certificates && \
curl https://sh.rustup.rs -sSf | sh -s -- -y
ENV PATH="/root/.cargo/bin:${PATH}"
ENV LAST_RUST_UPDATE 2020-12-21
ENV LAST_RUST_UPDATE 2021-04-01
RUN rustup update stable && \
rustup install nightly && \
@@ -26,7 +27,6 @@ RUN rustup update stable && \
RUN rustc -vV && \
cargo -V && \
gcc -v && \
g++ -v && \
cmake --version
ENV RUST_BACKTRACE 1
+16 -12
View File
@@ -93,12 +93,12 @@ seeds for the `sr25519` keys. This seed may also be used in the signer argument
and PoA relays. Example:
```bash
./substrate-relay relay-headers rialto-to-millau \
--rialto-host rialto-node-alice \
--rialto-port 9944 \
--millau-host millau-node-alice \
--millau-port 9944 \
--rialto-signer //Harry \
./substrate-relay relay-headers RialtoToMillau \
--source-host rialto-node-alice \
--source-port 9944 \
--target-host millau-node-alice \
--target-port 9944 \
--source-signer //Harry \
--prometheus-host=0.0.0.0
```
@@ -114,14 +114,18 @@ Following accounts are used when `poa-rialto` bridge is running:
Following accounts are used when `rialto-millau` bridge is running:
- Millau's `Charlie` signs relay transactions with new Rialto headers;
- Rialto's `Charlie` signs relay transactions with new Millau headers;
- Millau's `Charlie` signs complex headers+messages relay transactions on Millau chain;
- Rialto's `Charlie` signs complex headers+messages relay transactions on Rialto chain;
- Millau's `Dave` signs Millau transactions which contain messages for Rialto;
- Rialto's `Dave` signs Rialto transactions which contain messages for Millau;
- Millau's `Eve` signs relay transactions with message delivery confirmations from Rialto to Millau;
- Rialto's `Eve` signs relay transactions with messages from Millau to Rialto;
- Millau's `Ferdie` signs relay transactions with messages from Rialto to Millau;
- Rialto's `Ferdie` signs relay transactions with message delivery confirmations from Millau to Rialto.
- Millau's `Eve` signs relay transactions with message delivery confirmations (lane 00000001) from Rialto to Millau;
- Rialto's `Eve` signs relay transactions with messages (lane 00000001) from Millau to Rialto;
- Millau's `Ferdie` signs relay transactions with messages (lane 00000001) from Rialto to Millau;
- Rialto's `Ferdie` signs relay transactions with message delivery confirmations (lane 00000001) from Millau to Rialto.
Following accounts are used when `westend-millau` bridge is running:
- Millau's `George` signs relay transactions with new Westend headers.
### Docker Usage
When the network is running you can query logs from individual nodes using:
@@ -239,7 +239,7 @@
{
"expr": "max_over_time(Ethereum_to_Substrate_Sync_best_block_numbers{node=\"source\"}[2m])-min_over_time(Ethereum_to_Substrate_Sync_best_block_numbers{node=\"source\"}[2m])",
"interval": "",
"legendFormat": "Number of Ethereum PoA Headers Synced on Rialto",
"legendFormat": "Number of new Headers on Ethereum PoA (Last 2 Mins)",
"refId": "A"
}
],
@@ -239,7 +239,7 @@
{
"expr": "max_over_time(Substrate_to_Ethereum_Sync_best_block_numbers{node=\"source\"}[2m])-min_over_time(Substrate_to_Ethereum_Sync_best_block_numbers{node=\"source\"}[2m])",
"interval": "",
"legendFormat": "Number of Rialto Headers Synced on Ethereum PoA",
"legendFormat": "Number of new Headers on Rialto (Last 2 Mins)",
"refId": "A"
}
],
@@ -1,24 +0,0 @@
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: 'poa_to_rialto_relay_node'
# Override the global default and scrape targets from this job every 15 seconds.
scrape_interval: 15s
static_configs:
- targets: ['relay-headers-poa-to-rialto:9616']
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: 'poa_exchange_rialto_relay_node'
# Override the global default and scrape targets from this job every 15 seconds.
scrape_interval: 15s
static_configs:
- targets: ['relay-poa-exchange-rialto:9616']
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: 'rialto_to_poa_relay_node'
# Override the global default and scrape targets from this job every 15 seconds.
scrape_interval: 15s
static_configs:
- targets: ['relay-headers-rialto-to-poa:9616']
@@ -0,0 +1,4 @@
- targets:
- relay-headers-poa-to-rialto:9616
- relay-poa-exchange-rialto:9616
- relay-headers-rialto-to-poa:9616
@@ -1,5 +1,7 @@
# This Compose file should be built using the Rialto and Eth-PoA node
# compose files. Otherwise it won't work.
#
# Exposed ports: 9616, 9716, 9816, 9916, 8080
version: '3.5'
services:
@@ -79,12 +81,12 @@ services:
# Note: These are being overridden from the top level `monitoring` compose file.
prometheus-metrics:
volumes:
- ./bridges/poa-rialto/dashboard/prometheus/:/etc/prometheus/
- ./bridges/poa-rialto/dashboard/prometheus/targets.yml:/etc/prometheus/targets-poa-rialto.yml
depends_on: *all-nodes
grafana-dashboard:
volumes:
- ./bridges/poa-rialto/dashboard/grafana/provisioning/:/etc/grafana/provisioning/
- ./bridges/poa-rialto/dashboard/grafana:/etc/grafana/dashboards/poa-rialto:ro
environment:
VIRTUAL_HOST: dashboard.rialto.bridges.test-installations.parity.io,grafana.rialto.brucke.link
VIRTUAL_PORT: 3000
@@ -12,8 +12,8 @@ set -eu
RELAY_BINARY_PATH=${RELAY_BINARY_PATH:-./ethereum-poa-relay}
# Ethereum node host
ETH_HOST=${ETH_HOST:-poa-node-arthur}
# Ethereum node port
ETH_PORT=${ETH_PORT:-8545}
# Ethereum node websocket port
ETH_PORT=${ETH_PORT:-8546}
# Ethereum chain id
ETH_CHAIN_ID=${ETH_CHAIN_ID:-105}
@@ -1,6 +0,0 @@
- name: 'default'
orgId: 1
folder: ''
type: file
options:
path: '/etc/grafana/provisioning/dashboards'
@@ -1,694 +0,0 @@
{
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": "-- Grafana --",
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"type": "dashboard"
}
]
},
"editable": true,
"gnetId": null,
"graphTooltip": 0,
"links": [],
"panels": [
{
"alert": {
"alertRuleTags": {},
"conditions": [
{
"evaluator": {
"params": [
5
],
"type": "gt"
},
"operator": {
"type": "and"
},
"query": {
"params": [
"A",
"5m",
"now"
]
},
"reducer": {
"params": [],
"type": "min"
},
"type": "query"
}
],
"executionErrorState": "alerting",
"for": "5m",
"frequency": "5m",
"handler": 1,
"message": "",
"name": "Synced Header Difference is Over 5 (Millau to Rialto)",
"noDataState": "no_data",
"notifications": []
},
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "Prometheus",
"description": "Shows how many headers behind the target chain is from the source chain.",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 0
},
"hiddenSeries": false,
"id": 14,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"percentage": false,
"pluginVersion": "7.1.3",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "max(Millau_to_Rialto_Sync_best_block_numbers{node=\"source\"}) - max(Millau_to_Rialto_Sync_best_block_numbers{node=\"target\"})",
"format": "table",
"instant": false,
"interval": "",
"legendFormat": "",
"refId": "A"
}
],
"thresholds": [
{
"colorMode": "critical",
"fill": true,
"line": true,
"op": "gt",
"value": 5
}
],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Difference Between Source and Target Headers",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"alert": {
"alertRuleTags": {},
"conditions": [
{
"evaluator": {
"params": [
5
],
"type": "lt"
},
"operator": {
"type": "and"
},
"query": {
"params": [
"A",
"2m",
"now"
]
},
"reducer": {
"params": [],
"type": "min"
},
"type": "query"
}
],
"executionErrorState": "alerting",
"for": "3m",
"frequency": "5m",
"handler": 1,
"name": "No New Headers (Millau to Rialto)",
"noDataState": "no_data",
"notifications": []
},
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "Prometheus",
"description": "How many headers has the relay synced from the source node in the last 2 mins?",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 0
},
"hiddenSeries": false,
"id": 16,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"percentage": false,
"pluginVersion": "7.1.3",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "max_over_time(Millau_to_Rialto_Sync_best_block_numbers{node=\"source\"}[2m])-min_over_time(Millau_to_Rialto_Sync_best_block_numbers{node=\"source\"}[2m])",
"interval": "",
"legendFormat": "Number of Millau Headers Synced on Rialto",
"refId": "A"
}
],
"thresholds": [
{
"colorMode": "critical",
"fill": true,
"line": true,
"op": "lt",
"value": 5
}
],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Headers Synced on Rialto (Last 2 Mins)",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"datasource": "Prometheus",
"fieldConfig": {
"defaults": {
"custom": {
"align": null
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
}
},
"overrides": []
},
"gridPos": {
"h": 6,
"w": 12,
"x": 0,
"y": 8
},
"id": 2,
"interval": "5s",
"options": {
"colorMode": "value",
"graphMode": "area",
"justifyMode": "auto",
"orientation": "auto",
"reduceOptions": {
"calcs": [
"mean"
],
"fields": "",
"values": false
},
"textMode": "auto"
},
"pluginVersion": "7.1.3",
"targets": [
{
"expr": "Millau_to_Rialto_Sync_best_block_numbers",
"format": "time_series",
"instant": true,
"interval": "",
"intervalFactor": 1,
"legendFormat": "Best Known Header on {{node}} Node",
"refId": "A"
}
],
"timeFrom": null,
"timeShift": null,
"title": "Best Blocks according to Relay",
"type": "stat"
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "Prometheus",
"description": "",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 6,
"x": 12,
"y": 8
},
"hiddenSeries": false,
"id": 6,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"percentage": false,
"pluginVersion": "7.1.3",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "Millau_to_Rialto_Sync_system_average_load",
"interval": "",
"legendFormat": "Average system load in last {{over}}",
"refId": "A"
}
],
"thresholds": [
{
"colorMode": "critical",
"fill": true,
"line": true,
"op": "gt",
"value": null
}
],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Average System Load",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"datasource": "Prometheus",
"fieldConfig": {
"defaults": {
"custom": {},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
}
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 6,
"x": 18,
"y": 8
},
"id": 12,
"options": {
"orientation": "auto",
"reduceOptions": {
"calcs": [
"mean"
],
"fields": "",
"values": false
},
"showThresholdLabels": false,
"showThresholdMarkers": true
},
"pluginVersion": "7.1.3",
"targets": [
{
"expr": "avg_over_time(Millau_to_Rialto_Sync_process_cpu_usage_percentage[1m])",
"instant": true,
"interval": "",
"legendFormat": "1 CPU = 100",
"refId": "A"
}
],
"timeFrom": null,
"timeShift": null,
"title": "Relay Process CPU Usage ",
"type": "gauge"
},
{
"datasource": "Prometheus",
"description": "",
"fieldConfig": {
"defaults": {
"custom": {},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
}
},
"overrides": []
},
"gridPos": {
"h": 10,
"w": 12,
"x": 0,
"y": 14
},
"id": 4,
"options": {
"displayMode": "gradient",
"orientation": "auto",
"reduceOptions": {
"calcs": [
"mean"
],
"fields": "",
"values": false
},
"showUnfilled": true
},
"pluginVersion": "7.1.3",
"targets": [
{
"expr": "Millau_to_Rialto_Sync_blocks_in_state",
"instant": true,
"interval": "",
"legendFormat": "{{state}}",
"refId": "A"
}
],
"timeFrom": null,
"timeShift": null,
"title": "Queued Headers in Relay",
"type": "bargauge"
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "Prometheus",
"description": "",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 16
},
"hiddenSeries": false,
"id": 10,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"percentage": false,
"pluginVersion": "7.1.3",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "Millau_to_Rialto_Sync_process_memory_usage_bytes / 1024 / 1024",
"interval": "",
"legendFormat": "Process memory, MB",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Memory Usage for Relay Process",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
}
],
"refresh": "5s",
"schemaVersion": 26,
"style": "dark",
"tags": [],
"templating": {
"list": []
},
"time": {
"from": "now-5m",
"to": "now"
},
"timepicker": {
"refresh_intervals": [
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
]
},
"timezone": "",
"title": "Millau to Rialto Header Sync Dashboard",
"uid": "relay-millau-to-rialto-headers",
"version": 1
}
@@ -1,16 +0,0 @@
# list of datasources to insert/update depending
# whats available in the database
datasources:
# <string, required> name of the datasource. Required
- name: Prometheus
# <string, required> datasource type. Required
type: prometheus
# <string, required> access mode. direct or proxy. Required
access: proxy
# <int> org id. will default to orgId 1 if not specified
orgId: 1
# <string> url
url: http://prometheus-metrics:9090
# <bool> mark as default datasource. Max one per org
isDefault: true
version: 1
@@ -1,15 +0,0 @@
notifiers:
- name: Matrix
type: webhook
uid: notifier1
is_default: true
send_reminder: true
frequency: 1h
disable_resolve_message: false
settings:
url: http://grafana-matrix-notifier:4567/hook?rule=bridge
http_method: POST
delete_notifiers:
- name: Matrix
uid: notifier1
@@ -0,0 +1,454 @@
{
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": "-- Grafana --",
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"type": "dashboard"
}
]
},
"editable": true,
"gnetId": null,
"graphTooltip": 0,
"id": 9,
"links": [],
"panels": [
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "Prometheus",
"fieldConfig": {
"defaults": {},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 0
},
"hiddenSeries": false,
"id": 4,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.5.3",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"exemplar": true,
"expr": "Rialto_to_Millau_MessageLane_00000000_rialto_storage_proof_overhead",
"interval": "",
"legendFormat": "Actual overhead",
"refId": "A"
},
{
"exemplar": true,
"expr": "1024",
"hide": false,
"interval": "",
"legendFormat": "At runtime (hardcoded)",
"refId": "B"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Rialto: storage proof overhead",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"$$hashKey": "object:111",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"$$hashKey": "object:112",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "Prometheus",
"fieldConfig": {
"defaults": {},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 0
},
"hiddenSeries": false,
"id": 2,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.5.3",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"exemplar": true,
"expr": "Westend_to_Millau_Sync_kusama_to_base_conversion_rate / Westend_to_Millau_Sync_polkadot_to_base_conversion_rate",
"interval": "",
"legendFormat": "Outside of runtime (actually Polkadot -> Kusama)",
"refId": "A"
},
{
"exemplar": true,
"expr": "Rialto_to_Millau_MessageLane_00000000_rialto_millau_to_rialto_conversion_rate",
"hide": false,
"interval": "",
"legendFormat": "At runtime",
"refId": "B"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Rialto: Millau -> Rialto conversion rate",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"$$hashKey": "object:49",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"$$hashKey": "object:50",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "Prometheus",
"fieldConfig": {
"defaults": {},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 8
},
"hiddenSeries": false,
"id": 5,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.5.3",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"exemplar": true,
"expr": "Millau_to_Rialto_MessageLane_00000000_millau_storage_proof_overhead",
"interval": "",
"legendFormat": "Actual overhead",
"refId": "A"
},
{
"exemplar": true,
"expr": "1024",
"hide": false,
"interval": "",
"legendFormat": "At runtime (hardcoded)",
"refId": "B"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Millau: storage proof overhead",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"$$hashKey": "object:111",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"$$hashKey": "object:112",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "Prometheus",
"fieldConfig": {
"defaults": {},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 8
},
"hiddenSeries": false,
"id": 6,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.5.3",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"exemplar": true,
"expr": "Westend_to_Millau_Sync_polkadot_to_base_conversion_rate / Westend_to_Millau_Sync_kusama_to_base_conversion_rate",
"interval": "",
"legendFormat": "Outside of runtime (actually Kusama -> Polkadot)",
"refId": "A"
},
{
"exemplar": true,
"expr": "Millau_to_Rialto_MessageLane_00000000_millau_rialto_to_millau_conversion_rate",
"hide": false,
"interval": "",
"legendFormat": "At runtime",
"refId": "B"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Millau: Rialto -> Millau conversion rate",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"$$hashKey": "object:49",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"$$hashKey": "object:50",
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
}
],
"refresh": "10s",
"schemaVersion": 27,
"style": "dark",
"tags": [],
"templating": {
"list": []
},
"time": {
"from": "now-1h",
"to": "now"
},
"timepicker": {},
"timezone": "",
"title": "Rialto+Millau maintenance dashboard",
"uid": "7AuyrjlMz",
"version": 2
}
@@ -1,23 +0,0 @@
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: 'millau_to_rialto_headers_relay_node'
# Override the global default and scrape targets from this job every 15 seconds.
scrape_interval: 15s
static_configs:
- targets: ['relay-headers-millau-to-rialto:9616']
- job_name: 'rialto_to_millau_headers_relay_node'
scrape_interval: 15s
static_configs:
- targets: ['relay-headers-rialto-to-millau:9616']
- job_name: 'millau_to_rialto_messages_relay_node'
scrape_interval: 15s
static_configs:
- targets: ['relay-messages-millau-to-rialto:9616']
- job_name: 'rialto_to_millau_messages_relay_node'
scrape_interval: 15s
static_configs:
- targets: ['relay-messages-rialto-to-millau:9616']
@@ -0,0 +1,4 @@
- targets:
- relay-millau-rialto:9616
- relay-messages-millau-to-rialto-lane-00000001:9616
- relay-messages-rialto-to-millau-lane-00000001:9616
@@ -1,3 +1,5 @@
# Exposed ports: 10016, 10116, 10216, 10316, 10416
version: '3.5'
services:
# We provide overrides for these particular nodes since they are public facing
@@ -16,15 +18,15 @@ services:
LETSENCRYPT_HOST: wss.millau.brucke.link
LETSENCRYPT_EMAIL: admin@parity.io
relay-headers-millau-to-rialto: &sub-bridge-relay
relay-millau-rialto: &sub-bridge-relay
image: paritytech/substrate-relay
entrypoint: /entrypoints/relay-headers-millau-to-rialto-entrypoint.sh
entrypoint: /entrypoints/relay-millau-rialto-entrypoint.sh
volumes:
- ./bridges/rialto-millau/entrypoints:/entrypoints
environment:
RUST_LOG: rpc=trace,bridge=trace
ports:
- "9616:9616"
- "10016:9616"
depends_on: &all-nodes
- millau-node-alice
- millau-node-bob
@@ -37,49 +39,45 @@ services:
- rialto-node-dave
- rialto-node-eve
relay-headers-rialto-to-millau:
<<: *sub-bridge-relay
entrypoint: /entrypoints/relay-headers-rialto-to-millau-entrypoint.sh
ports:
- "9716:9616"
relay-messages-millau-to-rialto:
relay-messages-millau-to-rialto-lane-00000001:
<<: *sub-bridge-relay
environment:
MSG_EXCHANGE_GEN_LANE: "00000001"
entrypoint: /entrypoints/relay-messages-millau-to-rialto-entrypoint.sh
environment:
RUST_LOG: rpc=trace,bridge=trace,jsonrpsee=trace,soketto=trace
ports:
- "9816:9616"
depends_on:
- relay-headers-millau-to-rialto
- relay-headers-rialto-to-millau
relay-messages-millau-to-rialto-generator:
<<: *sub-bridge-relay
entrypoint: /entrypoints/relay-messages-to-rialto-generator-entrypoint.sh
environment:
RUST_LOG: rpc=trace,bridge=trace,jsonrpsee=trace,soketto=trace
ports:
- "9916:9616"
depends_on:
- relay-messages-millau-to-rialto
relay-messages-rialto-to-millau:
<<: *sub-bridge-relay
entrypoint: /entrypoints/relay-messages-rialto-to-millau-entrypoint.sh
ports:
- "10016:9616"
depends_on:
- relay-headers-millau-to-rialto
- relay-headers-rialto-to-millau
relay-messages-rialto-to-millau-generator:
<<: *sub-bridge-relay
entrypoint: /entrypoints/relay-messages-to-millau-generator-entrypoint.sh
ports:
- "10116:9616"
depends_on:
- relay-messages-rialto-to-millau
- relay-millau-rialto
relay-messages-millau-to-rialto-generator:
<<: *sub-bridge-relay
environment:
MSG_EXCHANGE_GEN_SECONDARY_LANE: "00000001"
entrypoint: /entrypoints/relay-messages-to-rialto-generator-entrypoint.sh
ports:
- "10216:9616"
depends_on:
- relay-millau-rialto
relay-messages-rialto-to-millau-lane-00000001:
<<: *sub-bridge-relay
environment:
MSG_EXCHANGE_GEN_LANE: "00000001"
entrypoint: /entrypoints/relay-messages-rialto-to-millau-entrypoint.sh
ports:
- "10316:9616"
depends_on:
- relay-millau-rialto
relay-messages-rialto-to-millau-generator:
<<: *sub-bridge-relay
environment:
MSG_EXCHANGE_GEN_SECONDARY_LANE: "00000001"
entrypoint: /entrypoints/relay-messages-to-millau-generator-entrypoint.sh
ports:
- "10416:9616"
depends_on:
- relay-millau-rialto
# Note: These are being overridden from the top level `monitoring` compose file.
grafana-dashboard:
@@ -89,9 +87,9 @@ services:
LETSENCRYPT_HOST: grafana.millau.brucke.link,grafana.rialto.brucke.link
LETSENCRYPT_EMAIL: admin@parity.io
volumes:
- ./bridges/rialto-millau/dashboard/grafana/provisioning/:/etc/grafana/provisioning/
- ./bridges/rialto-millau/dashboard/grafana:/etc/grafana/dashboards/rialto-millau:ro
prometheus-metrics:
volumes:
- ./bridges/rialto-millau/dashboard/prometheus/:/etc/prometheus/
- ./bridges/rialto-millau/dashboard/prometheus/targets.yml:/etc/prometheus/targets-rialto-millau.yml
depends_on: *all-nodes
@@ -1,23 +0,0 @@
#!/bin/bash
set -xeu
sleep 3
curl -v http://millau-node-alice:9933/health
curl -v http://rialto-node-alice:9933/health
/home/user/substrate-relay init-bridge millau-to-rialto \
--millau-host millau-node-alice \
--millau-port 9944 \
--rialto-host rialto-node-alice \
--rialto-port 9944 \
--rialto-signer //Alice
# Give chain a little bit of time to process initialization transaction
sleep 6
/home/user/substrate-relay relay-headers millau-to-rialto \
--millau-host millau-node-alice \
--millau-port 9944 \
--rialto-host rialto-node-alice \
--rialto-port 9944 \
--rialto-signer //Charlie \
--prometheus-host=0.0.0.0
@@ -1,23 +0,0 @@
#!/bin/bash
set -xeu
sleep 3
curl -v http://millau-node-alice:9933/health
curl -v http://rialto-node-alice:9933/health
/home/user/substrate-relay init-bridge rialto-to-millau \
--millau-host millau-node-alice \
--millau-port 9944 \
--rialto-host rialto-node-alice \
--rialto-port 9944 \
--millau-signer //Alice
# Give chain a little bit of time to process initialization transaction
sleep 6
/home/user/substrate-relay relay-headers rialto-to-millau \
--millau-host millau-node-alice \
--millau-port 9944 \
--rialto-host rialto-node-alice \
--rialto-port 9944 \
--millau-signer //Charlie \
--prometheus-host=0.0.0.0
@@ -7,12 +7,12 @@ curl -v http://rialto-node-bob:9933/health
MESSAGE_LANE=${MSG_EXCHANGE_GEN_LANE:-00000000}
/home/user/substrate-relay relay-messages millau-to-rialto \
/home/user/substrate-relay relay-messages MillauToRialto \
--lane $MESSAGE_LANE \
--millau-host millau-node-bob \
--millau-port 9944 \
--millau-signer //Eve \
--rialto-host rialto-node-bob \
--rialto-port 9944 \
--rialto-signer //Eve \
--source-host millau-node-bob \
--source-port 9944 \
--source-signer //Eve \
--target-host rialto-node-bob \
--target-port 9944 \
--target-signer //Eve \
--prometheus-host=0.0.0.0
@@ -7,12 +7,12 @@ curl -v http://rialto-node-bob:9933/health
MESSAGE_LANE=${MSG_EXCHANGE_GEN_LANE:-00000000}
/home/user/substrate-relay relay-messages rialto-to-millau \
/home/user/substrate-relay relay-messages RialtoToMillau \
--lane $MESSAGE_LANE \
--rialto-host rialto-node-bob \
--rialto-port 9944 \
--rialto-signer //Ferdie \
--millau-host millau-node-bob \
--millau-port 9944 \
--millau-signer //Ferdie \
--source-host rialto-node-bob \
--source-port 9944 \
--source-signer //Ferdie \
--target-host millau-node-bob \
--target-port 9944 \
--target-signer //Ferdie \
--prometheus-host=0.0.0.0
@@ -10,11 +10,13 @@ set -eu
# Max delay before submitting transactions (s)
MAX_SUBMIT_DELAY_S=${MSG_EXCHANGE_GEN_MAX_SUBMIT_DELAY_S:-30}
MESSAGE_LANE=${MSG_EXCHANGE_GEN_LANE:-00000000}
FERDIE_ADDR=5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL
SECONDARY_MESSAGE_LANE=${MSG_EXCHANGE_GEN_SECONDARY_LANE}
MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE=1024
FERDIE_ADDR=5oSLwptwgySxh5vz1HdvznQJjbQVgwYSvHEpYYeTXu1Ei8j7
SHARED_CMD="/home/user/substrate-relay send-message rialto-to-millau"
SHARED_HOST="--rialto-host rialto-node-bob --rialto-port 9944"
DAVE_SIGNER="--rialto-signer //Dave --millau-signer //Dave"
SHARED_CMD="/home/user/substrate-relay send-message RialtoToMillau"
SHARED_HOST="--source-host rialto-node-bob --source-port 9944"
DAVE_SIGNER="--source-signer //Dave --target-signer //Dave"
SEND_MESSAGE="$SHARED_CMD $SHARED_HOST $DAVE_SIGNER"
@@ -25,6 +27,11 @@ rand_sleep() {
sleep $SUBMIT_DELAY_S
}
# start sending large messages immediately
LARGE_MESSAGES_TIME=0
# start sending message packs in a hour
BUNCH_OF_MESSAGES_TIME=3600
while true
do
rand_sleep
@@ -34,6 +41,14 @@ do
--origin Target \
remark
if [ ! -z $SECONDARY_MESSAGE_LANE ]; then
echo "Sending Remark from Rialto to Millau using Target Origin using secondary lane: $SECONDARY_MESSAGE_LANE"
$SEND_MESSAGE \
--lane $SECONDARY_MESSAGE_LANE \
--origin Target \
remark
fi
rand_sleep
echo "Sending Transfer from Rialto to Millau using Target Origin"
$SEND_MESSAGE \
@@ -58,4 +73,49 @@ do
transfer \
--amount 1000000000 \
--recipient $FERDIE_ADDR
# every other hour we're sending 3 large (size, weight, size+weight) messages
if [ $SECONDS -ge $LARGE_MESSAGES_TIME ]; then
LARGE_MESSAGES_TIME=$((SECONDS + 7200))
rand_sleep
echo "Sending Maximal Size Remark from Rialto to Millau using Target Origin"
$SEND_MESSAGE \
--lane $MESSAGE_LANE \
--origin Target \
remark \
--remark-size=max
rand_sleep
echo "Sending Maximal Dispatch Weight Remark from Rialto to Millau using Target Origin"
$SEND_MESSAGE \
--lane $MESSAGE_LANE \
--origin Target \
--dispatch-weight=max \
remark
rand_sleep
echo "Sending Maximal Size and Dispatch Weight Remark from Rialto to Millau using Target Origin"
$SEND_MESSAGE \
--lane $MESSAGE_LANE \
--origin Target \
--dispatch-weight=max \
remark \
--remark-size=max
fi
# every other hour we're sending a bunch of small messages
if [ $SECONDS -ge $BUNCH_OF_MESSAGES_TIME ]; then
BUNCH_OF_MESSAGES_TIME=$((SECONDS + 7200))
for i in $(seq 1 $MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE);
do
$SEND_MESSAGE \
--lane $MESSAGE_LANE \
--origin Target \
remark
done
fi
done
@@ -10,11 +10,13 @@ set -eu
# Max delay before submitting transactions (s)
MAX_SUBMIT_DELAY_S=${MSG_EXCHANGE_GEN_MAX_SUBMIT_DELAY_S:-30}
MESSAGE_LANE=${MSG_EXCHANGE_GEN_LANE:-00000000}
FERDIE_ADDR=5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL
SECONDARY_MESSAGE_LANE=${MSG_EXCHANGE_GEN_SECONDARY_LANE}
MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE=128
FERDIE_ADDR=6ztG3jPnJTwgZnnYsgCDXbbQVR82M96hBZtPvkN56A9668ZC
SHARED_CMD=" /home/user/substrate-relay send-message millau-to-rialto"
SHARED_HOST="--millau-host millau-node-bob --millau-port 9944"
DAVE_SIGNER="--rialto-signer //Dave --millau-signer //Dave"
SHARED_CMD=" /home/user/substrate-relay send-message MillauToRialto"
SHARED_HOST="--source-host millau-node-bob --source-port 9944"
DAVE_SIGNER="--target-signer //Dave --source-signer //Dave"
SEND_MESSAGE="$SHARED_CMD $SHARED_HOST $DAVE_SIGNER"
@@ -25,6 +27,11 @@ rand_sleep() {
sleep $SUBMIT_DELAY_S
}
# start sending large messages immediately
LARGE_MESSAGES_TIME=0
# start sending message packs in a hour
BUNCH_OF_MESSAGES_TIME=3600
while true
do
rand_sleep
@@ -34,6 +41,14 @@ do
--origin Target \
remark
if [ ! -z $SECONDARY_MESSAGE_LANE ]; then
echo "Sending Remark from Millau to Rialto using Target Origin using secondary lane: $SECONDARY_MESSAGE_LANE"
$SEND_MESSAGE \
--lane $SECONDARY_MESSAGE_LANE \
--origin Target \
remark
fi
rand_sleep
echo "Sending Transfer from Millau to Rialto using Target Origin"
$SEND_MESSAGE \
@@ -58,4 +73,49 @@ do
transfer \
--amount 1000000000 \
--recipient $FERDIE_ADDR
# every other hour we're sending 3 large (size, weight, size+weight) messages
if [ $SECONDS -ge $LARGE_MESSAGES_TIME ]; then
LARGE_MESSAGES_TIME=$((SECONDS + 7200))
rand_sleep
echo "Sending Maximal Size Remark from Millau to Rialto using Target Origin"
$SEND_MESSAGE \
--lane $MESSAGE_LANE \
--origin Target \
remark \
--remark-size=max
rand_sleep
echo "Sending Maximal Dispatch Weight Remark from Millau to Rialto using Target Origin"
$SEND_MESSAGE \
--lane $MESSAGE_LANE \
--origin Target \
--dispatch-weight=max \
remark
rand_sleep
echo "Sending Maximal Size and Dispatch Weight Remark from Millau to Rialto using Target Origin"
$SEND_MESSAGE \
--lane $MESSAGE_LANE \
--origin Target \
--dispatch-weight=max \
remark \
--remark-size=max
fi
# every other hour we're sending a bunch of small messages
if [ $SECONDS -ge $BUNCH_OF_MESSAGES_TIME ]; then
BUNCH_OF_MESSAGES_TIME=$((SECONDS + 7200))
for i in $(seq 1 $MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE);
do
$SEND_MESSAGE \
--lane $MESSAGE_LANE \
--origin Target \
remark
done
fi
done
@@ -0,0 +1,33 @@
#!/bin/bash
set -xeu
sleep 3
curl -v http://millau-node-alice:9933/health
curl -v http://rialto-node-alice:9933/health
/home/user/substrate-relay init-bridge MillauToRialto \
--source-host millau-node-alice \
--source-port 9944 \
--target-host rialto-node-alice \
--target-port 9944 \
--target-signer //Alice
/home/user/substrate-relay init-bridge RialtoToMillau \
--source-host rialto-node-alice \
--source-port 9944 \
--target-host millau-node-alice \
--target-port 9944 \
--target-signer //Alice
# Give chain a little bit of time to process initialization transaction
sleep 6
/home/user/substrate-relay relay-headers-and-messages millau-rialto \
--millau-host millau-node-alice \
--millau-port 9944 \
--millau-signer //Charlie \
--rialto-host rialto-node-alice \
--rialto-port 9944 \
--rialto-signer //Charlie \
--lane=00000000 \
--prometheus-host=0.0.0.0
@@ -50,7 +50,7 @@
"frequency": "5m",
"handler": 1,
"message": "",
"name": "Synced Header Difference is Over 5 (Rialto to Millau)",
"name": "Synced Header Difference is Over 5 (Westend to Millau)",
"noDataState": "no_data",
"notifications": []
},
@@ -99,7 +99,7 @@
"steppedLine": false,
"targets": [
{
"expr": "max(Rialto_to_Millau_Sync_best_block_numbers{node=\"source\"}) - max(Rialto_to_Millau_Sync_best_block_numbers{node=\"target\"})",
"expr": "max(Westend_to_Millau_Sync_best_block_numbers{node=\"source\"}) - max(Westend_to_Millau_Sync_best_block_numbers{node=\"target\"})",
"format": "table",
"instant": false,
"interval": "",
@@ -188,7 +188,7 @@
"for": "3m",
"frequency": "5m",
"handler": 1,
"name": "No New Headers (Rialto to Millau)",
"name": "No New Headers (Westend to Millau)",
"noDataState": "no_data",
"notifications": []
},
@@ -237,9 +237,9 @@
"steppedLine": false,
"targets": [
{
"expr": "max_over_time(Rialto_to_Millau_Sync_best_block_numbers{node=\"source\"}[2m])-min_over_time(Rialto_to_Millau_Sync_best_block_numbers{node=\"source\"}[2m])",
"expr": "max_over_time(Westend_to_Millau_Sync_best_block_numbers{node=\"source\"}[2m])-min_over_time(Westend_to_Millau_Sync_best_block_numbers{node=\"source\"}[2m])",
"interval": "",
"legendFormat": "Number of Rialto Headers Synced on Millau",
"legendFormat": "Number of new Headers on Westend (Last 2 Mins)",
"refId": "A"
}
],
@@ -341,7 +341,7 @@
"pluginVersion": "7.1.3",
"targets": [
{
"expr": "Rialto_to_Millau_Sync_best_block_numbers",
"expr": "Westend_to_Millau_Sync_best_block_numbers",
"format": "time_series",
"instant": true,
"interval": "",
@@ -401,7 +401,7 @@
"steppedLine": false,
"targets": [
{
"expr": "Rialto_to_Millau_Sync_system_average_load",
"expr": "Westend_to_Millau_Sync_system_average_load",
"interval": "",
"legendFormat": "Average system load in last {{over}}",
"refId": "A"
@@ -500,7 +500,7 @@
"pluginVersion": "7.1.3",
"targets": [
{
"expr": "avg_over_time(Rialto_to_Millau_Sync_process_cpu_usage_percentage[1m])",
"expr": "avg_over_time(Westend_to_Millau_Sync_process_cpu_usage_percentage[1m])",
"instant": true,
"interval": "",
"legendFormat": "1 CPU = 100",
@@ -557,7 +557,7 @@
"pluginVersion": "7.1.3",
"targets": [
{
"expr": "Rialto_to_Millau_Sync_blocks_in_state",
"expr": "Westend_to_Millau_Sync_blocks_in_state",
"instant": true,
"interval": "",
"legendFormat": "{{state}}",
@@ -615,7 +615,7 @@
"steppedLine": false,
"targets": [
{
"expr": "Rialto_to_Millau_Sync_process_memory_usage_bytes / 1024 / 1024",
"expr": "Westend_to_Millau_Sync_process_memory_usage_bytes / 1024 / 1024",
"interval": "",
"legendFormat": "Process memory, MB",
"refId": "A"
@@ -688,7 +688,7 @@
]
},
"timezone": "",
"title": "Rialto to Millau Header Sync Dashboard",
"uid": "relay-rialto-to-millau-headers",
"title": "Westend to Millau Header Sync Dashboard",
"uid": "relay-westend-to-millau-headers",
"version": 1
}
@@ -0,0 +1,2 @@
- targets:
- relay-headers-westend-to-millau:9616
@@ -0,0 +1,31 @@
# Exposed ports: 10616
version: '3.5'
services:
relay-headers-westend-to-millau:
image: paritytech/substrate-relay
entrypoint: /entrypoints/relay-headers-westend-to-millau-entrypoint.sh
volumes:
- ./bridges/westend-millau/entrypoints:/entrypoints
environment:
RUST_LOG: rpc=trace,bridge=trace
ports:
- "10616:9616"
depends_on:
- millau-node-alice
# Note: These are being overridden from the top level `monitoring` compose file.
grafana-dashboard:
environment:
VIRTUAL_HOST: grafana.millau.brucke.link,grafana.rialto.brucke.link
VIRTUAL_PORT: 3000
LETSENCRYPT_HOST: grafana.millau.brucke.link,grafana.rialto.brucke.link
LETSENCRYPT_EMAIL: admin@parity.io
volumes:
- ./bridges/westend-millau/dashboard/grafana:/etc/grafana/dashboards/westend-millau:ro
prometheus-metrics:
volumes:
- ./bridges/westend-millau/dashboard/prometheus/targets.yml:/etc/prometheus/targets-westend-millau.yml
depends_on:
- relay-headers-westend-to-millau
@@ -0,0 +1,25 @@
#!/bin/bash
set -xeu
sleep 3
curl -v http://millau-node-alice:9933/health
curl -v https://westend-rpc.polkadot.io:443/health
/home/user/substrate-relay init-bridge WestendToMillau \
--source-host westend-rpc.polkadot.io \
--source-port 443 \
--source-secure \
--target-host millau-node-alice \
--target-port 9944 \
--target-signer //George
# Give chain a little bit of time to process initialization transaction
sleep 6
/home/user/substrate-relay relay-headers WestendToMillau \
--source-host westend-rpc.polkadot.io \
--source-port 443 \
--source-secure \
--target-host millau-node-alice \
--target-port 9944 \
--target-signer //George \
--prometheus-host=0.0.0.0
@@ -0,0 +1,24 @@
#!/bin/bash
#
# Run an instance of the Rococo -> Westend header sync.
#
# Right now this relies on local Westend and Rococo networks
# running (which include `pallet-bridge-grandpa` in their
# runtimes), but in the future it could use use public RPC nodes.
set -xeu
RUST_LOG=rpc=trace,bridge=trace ./target/debug/substrate-relay init-bridge RococoToWestend \
--source-host 127.0.0.1 \
--source-port 9955 \
--target-host 127.0.0.1 \
--target-port 9944 \
--target-signer //Eve
RUST_LOG=rpc=trace,bridge=trace ./target/debug/substrate-relay relay-headers RococoToWestend \
--source-host 127.0.0.1 \
--source-port 9955 \
--target-host 127.0.0.1 \
--target-port 9944 \
--target-signer //Bob \
--prometheus-host=0.0.0.0 \
@@ -0,0 +1,24 @@
#!/bin/bash
#
# Run an instance of the Westend -> Rococo header sync.
#
# Right now this relies on local Westend and Rococo networks
# running (which include `pallet-bridge-grandpa` in their
# runtimes), but in the future it could use use public RPC nodes.
set -xeu
RUST_LOG=rpc=trace,bridge=trace ./target/debug/substrate-relay init-bridge WestendToRococo \
--source-host 127.0.0.1 \
--source-port 9944 \
--target-host 127.0.0.1 \
--target-port 9955 \
--target-signer //Dave
RUST_LOG=rpc=trace,bridge=trace ./target/debug/substrate-relay relay-headers WestendToRococo \
--source-host 127.0.0.1 \
--source-port 9944 \
--target-host 127.0.0.1 \
--target-port 9955 \
--target-signer //Charlie \
--prometheus-host=0.0.0.0 \
@@ -0,0 +1,20 @@
#!/bin/bash
# A script for relaying Millau messages to the Rialto chain.
#
# Will not work unless both the Rialto and Millau are running (see `run-rialto-node.sh`
# and `run-millau-node.sh).
set -xeu
MILLAU_PORT="${MILLAU_PORT:-9945}"
RIALTO_PORT="${RIALTO_PORT:-9944}"
RUST_LOG=bridge=debug \
./target/debug/substrate-relay relay-messages MillauToRialto \
--lane 00000000 \
--source-host localhost \
--source-port $MILLAU_PORT \
--source-signer //Bob \
--target-host localhost \
--target-port $RIALTO_PORT \
--target-signer //Bob \
--prometheus-host=0.0.0.0
@@ -0,0 +1,20 @@
#!/bin/bash
# A script for relaying Rialto messages to the Millau chain.
#
# Will not work unless both the Rialto and Millau are running (see `run-rialto-node.sh`
# and `run-millau-node.sh).
set -xeu
MILLAU_PORT="${MILLAU_PORT:-9945}"
RIALTO_PORT="${RIALTO_PORT:-9944}"
RUST_LOG=bridge=debug \
./target/debug/substrate-relay relay-messages RialtoToMillau \
--lane 00000000 \
--source-host localhost \
--source-port $RIALTO_PORT \
--source-signer //Bob \
--target-host localhost \
--target-port $MILLAU_PORT \
--target-signer //Bob \
--prometheus-host=0.0.0.0
@@ -5,20 +5,23 @@
# Will not work unless both the Rialto and Millau are running (see `run-rialto-node.sh`
# and `run-millau-node.sh).
MILLAU_PORT="${MILLAU_PORT:-9945}"
RIALTO_PORT="${RIALTO_PORT:-9944}"
RUST_LOG=bridge=debug \
./target/debug/substrate-relay init-bridge millau-to-rialto \
--millau-host localhost \
--millau-port 9945 \
--rialto-host localhost \
--rialto-port 9944 \
--rialto-signer //Alice \
./target/debug/substrate-relay init-bridge MillauToRialto \
--source-host localhost \
--source-port $MILLAU_PORT \
--target-host localhost \
--target-port $RIALTO_PORT \
--target-signer //Alice \
sleep 5
RUST_LOG=bridge=debug \
./target/debug/substrate-relay relay-headers millau-to-rialto \
--millau-host localhost \
--millau-port 9945 \
--rialto-host localhost \
--rialto-port 9944 \
--rialto-signer //Alice \
./target/debug/substrate-relay relay-headers MillauToRialto \
--source-host localhost \
--source-port $MILLAU_PORT \
--target-host localhost \
--target-port $RIALTO_PORT \
--target-signer //Alice \
--prometheus-host=0.0.0.0
@@ -5,20 +5,23 @@
# Will not work unless both the Rialto and Millau are running (see `run-rialto-node.sh`
# and `run-millau-node.sh).
MILLAU_PORT="${MILLAU_PORT:-9945}"
RIALTO_PORT="${RIALTO_PORT:-9944}"
RUST_LOG=bridge=debug \
./target/debug/substrate-relay init-bridge rialto-to-millau \
--millau-host localhost \
--millau-port 9945 \
--rialto-host localhost \
--rialto-port 9944 \
--millau-signer //Alice \
./target/debug/substrate-relay init-bridge RialtoToMillau \
--target-host localhost \
--target-port $MILLAU_PORT \
--source-host localhost \
--source-port $RIALTO_PORT \
--target-signer //Alice \
sleep 5
RUST_LOG=bridge=debug \
./target/debug/substrate-relay relay-headers rialto-to-millau \
--millau-host localhost \
--millau-port 9945 \
--rialto-host localhost \
--rialto-port 9944 \
--millau-signer //Alice \
./target/debug/substrate-relay relay-headers RialtoToMillau \
--target-host localhost \
--target-port $MILLAU_PORT \
--source-host localhost \
--source-port $RIALTO_PORT \
--target-signer //Alice \
--prometheus-host=0.0.0.0
@@ -1,8 +1,11 @@
#!/bin/bash
# Run a development instance of the Millau Substrate bridge node.
# To override the default port just export MILLAU_PORT=9945
MILLAU_PORT="${MILLAU_PORT:-9945}"
RUST_LOG=runtime=trace \
./target/debug/millau-bridge-node --dev --tmp \
--rpc-cors=all --unsafe-rpc-external --unsafe-ws-external \
--port 33044 --rpc-port 9934 --ws-port 9945 \
--port 33044 --rpc-port 9934 --ws-port $MILLAU_PORT \
@@ -1,8 +1,11 @@
#!/bin/bash
# Run a development instance of the Rialto Substrate bridge node.
# To override the default port just export RIALTO_PORT=9944
RIALTO_PORT="${RIALTO_PORT:-9944}"
RUST_LOG=runtime=trace \
./target/debug/rialto-bridge-node --dev --tmp \
--rpc-cors=all --unsafe-rpc-external --unsafe-ws-external \
--port 33033 --rpc-port 9933 --ws-port 9944 \
--port 33033 --rpc-port 9933 --ws-port $RIALTO_PORT \
@@ -0,0 +1,14 @@
#!/bin/bash
# Run a development instance of the Rococo Substrate bridge node.
# To override the default port just export ROCOCO_PORT=9966
#
# Note: This script will not work out of the box with the bridges
# repo since it relies on a Polkadot binary.
ROCOCO_BOB_PORT="${ROCOCO_BOB_PORT:-9966}"
RUST_LOG=runtime=trace,runtime::bridge=trace \
./target/debug/polkadot --chain=rococo-local --bob --tmp \
--rpc-cors=all --unsafe-rpc-external --unsafe-ws-external \
--port 33055 --rpc-port 9935 --ws-port $ROCOCO_BOB_PORT \
@@ -0,0 +1,14 @@
#!/bin/bash
# Run a development instance of the Rococo Substrate bridge node.
# To override the default port just export ROCOCO_PORT=9955
#
# Note: This script will not work out of the box with the bridges
# repo since it relies on a Polkadot binary.
ROCOCO_PORT="${ROCOCO_PORT:-9955}"
RUST_LOG=runtime=trace,runtime::bridge=trace \
./target/debug/polkadot --chain=rococo-local --alice --tmp \
--rpc-cors=all --unsafe-rpc-external --unsafe-ws-external \
--port 33044 --rpc-port 9934 --ws-port $ROCOCO_PORT \
@@ -0,0 +1,14 @@
#!/bin/bash
# Run a development instance of the Westend Substrate bridge node.
# To override the default port just export WESTEND_PORT=9945
#
# Note: This script will not work out of the box with the bridges
# repo since it relies on a Polkadot binary.
WESTEND_PORT="${WESTEND_PORT:-9944}"
RUST_LOG=runtime=trace,runtime::bridge=trace \
./target/debug/polkadot --chain=westend-dev --alice --tmp \
--rpc-cors=all --unsafe-rpc-external --unsafe-ws-external \
--port 33033 --rpc-port 9933 --ws-port $WESTEND_PORT \
@@ -2,6 +2,8 @@ version: '3.5'
services:
prometheus-metrics:
image: prom/prometheus:v2.20.1
volumes:
- ./monitoring/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
ports:
- "9090:9090"
@@ -11,6 +13,8 @@ services:
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASS:-admin}
GF_SERVER_ROOT_URL: ${GRAFANA_SERVER_ROOT_URL}
GF_SERVER_DOMAIN: ${GRAFANA_SERVER_DOMAIN}
volumes:
- ./monitoring/grafana/provisioning/:/etc/grafana/provisioning/:ro
ports:
- "3000:3000"
depends_on:
@@ -11,7 +11,7 @@ matrix:
# Create a user - log that user in using a post request
# curl -XPOST -d '{"type": "m.login.password",
# "user":"grafana",
# "password":"2m4ny53cr3t5"}'
# "password":"dummy-password"}'
# "https://my-matrix-server/_matrix/client/r0/login"
# Fill that access token in here
access_token: "<access_token>"
@@ -3,4 +3,4 @@
folder: ''
type: file
options:
path: '/etc/grafana/provisioning/dashboards'
path: '/etc/grafana/dashboards'
@@ -0,0 +1,7 @@
global:
scrape_interval: 15s
scrape_configs:
- job_name: dummy
file_sd_configs:
- files:
- /etc/prometheus/targets-*.yml
@@ -20,7 +20,7 @@ services:
- --unsafe-rpc-external
- --unsafe-ws-external
environment:
RUST_LOG: runtime=trace,rpc=debug,txpool=trace,pallet_substrate_bridge=trace,pallet_bridge_call_dispatch=trace,pallet_message_lane=trace
RUST_LOG: runtime=trace,rpc=debug,txpool=trace,runtime::bridge=trace
ports:
- "19933:9933"
- "19944:9944"
@@ -37,8 +37,6 @@ services:
- --rpc-cors=all
- --unsafe-rpc-external
- --unsafe-ws-external
environment:
RUST_LOG: runtime=trace,rpc=debug,txpool=trace,pallet_substrate_bridge=trace,pallet_bridge_call_dispatch=trace,pallet_message_lane=trace,jsonrpc_ws_server=trace,parity_ws=trace
ports:
- "20033:9933"
- "20044:9944"
@@ -20,7 +20,7 @@ services:
- --unsafe-rpc-external
- --unsafe-ws-external
environment:
RUST_LOG: runtime=trace,rpc=debug,txpool=trace,pallet_substrate_bridge=trace,pallet_bridge_call_dispatch=trace,pallet_message_lane=trace
RUST_LOG: runtime=trace,rpc=debug,txpool=trace,runtime::bridge=trace
ports:
- "9933:9933"
- "9944:9944"
@@ -37,8 +37,6 @@ services:
- --rpc-cors=all
- --unsafe-rpc-external
- --unsafe-ws-external
environment:
RUST_LOG: runtime=trace,rpc=debug,txpool=trace,pallet_substrate_bridge=trace,pallet_bridge_call_dispatch=trace,pallet_message_lane=trace,jsonrpc_ws_server=trace,parity_ws=trace
ports:
- "10033:9933"
- "10044:9944"
+49 -16
View File
@@ -2,9 +2,9 @@
# Script used for running and updating bridge deployments.
#
# To deploy a network you can run this script with the name of the network you want to run.
# To deploy a network you can run this script with the name of the bridge (or multiple bridges) you want to run.
#
# `./run.sh poa-rialto`
# `./run.sh poa-rialto rialto-millau`
#
# To update a deployment to use the latest images available from the Docker Hub add the `update`
# argument after the bridge name.
@@ -14,6 +14,10 @@
# Once you've stopped having fun with your deployment you can take it down with:
#
# `./run.sh rialto-millau stop`
#
# Stopping the bridge will also bring down all networks that it uses. So if you have started multiple bridges
# that are using the same network (like Millau in rialto-millau and westend-millau bridges), then stopping one
# of these bridges will cause the other bridge to break.
set -xeu
@@ -28,9 +32,13 @@ function show_help () {
echo "Usage:"
echo " ./run.sh poa-rialto [stop|update] Run PoA <> Rialto Networks & Bridge"
echo " ./run.sh rialto-millau [stop|update] Run Rialto <> Millau Networks & Bridge"
echo " ./run.sh westend-millau [stop|update] Run Westend -> Millau Networks & Bridge"
echo " "
echo "Options:"
echo " --no-monitoring Disable monitoring"
echo " "
echo "You can start multiple bridges at once by passing several bridge names:"
echo " ./run.sh poa-rialto rialto-millau westend-millau [stop|update]"
exit 1
}
@@ -39,7 +47,7 @@ MILLAU=' -f ./networks/millau.yml'
ETH_POA=' -f ./networks/eth-poa.yml'
MONITORING=' -f ./monitoring/docker-compose.yml'
BRIDGE=''
BRIDGES=()
NETWORKS=''
SUB_COMMAND='start'
for i in "$@"
@@ -48,17 +56,28 @@ do
--no-monitoring)
MONITORING=" -f ./monitoring/disabled.yml"
shift
continue
;;
poa-rialto)
BRIDGE=$i
BRIDGES+=($i)
NETWORKS+=${RIALTO}
RIALTO=''
NETWORKS+=${ETH_POA}
ETH_POA=''
shift
;;
rialto-millau)
BRIDGE=$i
BRIDGES+=($i)
NETWORKS+=${RIALTO}
RIALTO=''
NETWORKS+=${MILLAU}
MILLAU=''
shift
;;
westend-millau)
BRIDGES+=($i)
NETWORKS+=${MILLAU}
MILLAU=''
shift
;;
start|stop|update)
@@ -71,24 +90,38 @@ do
esac
done
if [ -z "$BRIDGE" ]; then
if [ ${#BRIDGES[@]} -eq 0 ]; then
show_help "Missing bridge name."
fi
BRIDGE_PATH="./bridges/$BRIDGE"
BRIDGE="-f $BRIDGE_PATH/docker-compose.yml"
COMPOSE_FILES=$BRIDGE$NETWORKS$MONITORING
COMPOSE_FILES=$NETWORKS$MONITORING
# Compose looks for .env files in the the current directory by default, we don't want that
COMPOSE_ARGS="--project-directory . --env-file "
COMPOSE_ARGS+=$BRIDGE_PATH/.env
COMPOSE_ARGS="--project-directory ."
# Path to env file that we want to use. Compose only accepts single `--env-file` argument,
# so we'll be using the last .env file we'll found.
COMPOSE_ENV_FILE=''
# Read and source variables from .env file so we can use them here
grep -e MATRIX_ACCESS_TOKEN -e WITH_PROXY $BRIDGE_PATH/.env > .env2 && . ./.env2 && rm .env2
for BRIDGE in "${BRIDGES[@]}"
do
BRIDGE_PATH="./bridges/$BRIDGE"
BRIDGE=" -f $BRIDGE_PATH/docker-compose.yml"
COMPOSE_FILES=$BRIDGE$COMPOSE_FILES
if [ ! -z ${MATRIX_ACCESS_TOKEN+x} ]; then
sed -i "s/access_token.*/access_token: \"$MATRIX_ACCESS_TOKEN\"/" ./monitoring/grafana-matrix/config.yml
fi
# Remember .env file to use in docker-compose call
if [[ -f "$BRIDGE_PATH/.env" ]]; then
COMPOSE_ENV_FILE=" --env-file $BRIDGE_PATH/.env"
fi
# Read and source variables from .env file so we can use them here
grep -e MATRIX_ACCESS_TOKEN -e WITH_PROXY $BRIDGE_PATH/.env > .env2 && . ./.env2 && rm .env2
if [ ! -z ${MATRIX_ACCESS_TOKEN+x} ]; then
sed -i "s/access_token.*/access_token: \"$MATRIX_ACCESS_TOKEN\"/" ./monitoring/grafana-matrix/config.yml
fi
done
# Final COMPOSE_ARGS
COMPOSE_ARGS="$COMPOSE_ARGS $COMPOSE_ENV_FILE"
# Check the sub-command, perhaps we just mean to stop the network instead of starting it.
if [ "$SUB_COMMAND" == "stop" ]; then
@@ -0,0 +1,172 @@
{
"--1": "Millau Types",
"MillauBalance": "u64",
"MillauBlockHash": "H512",
"MillauBlockNumber": "u64",
"MillauHeader": {
"parent_Hash": "MillauBlockHash",
"number": "Compact<MillauBlockNumber>",
"state_root": "MillauBlockHash",
"extrinsics_root": "MillauBlockHash",
"digest": "MillauDigest"
},
"MillauDigest": {
"logs": "Vec<MillauDigestItem>"
},
"MillauDigestItem": {
"_enum": {
"Other": "Vec<u8>",
"AuthoritiesChange": "Vec<AuthorityId>",
"ChangesTrieRoot": "MillauBlockHash",
"SealV0": "SealV0",
"Consensus": "Consensus",
"Seal": "Seal",
"PreRuntime": "PreRuntime"
}
},
"--2": "Rialto Types",
"RialtoBalance": "u128",
"RialtoBlockHash": "H256",
"RialtoBlockNumber": "u32",
"RialtoHeader": {
"parent_Hash": "RialtoBlockHash",
"number": "Compact<RialtoBlockNumber>",
"state_root": "RialtoBlockHash",
"extrinsics_root": "RialtoBlockHash",
"digest": "RialtoDigest"
},
"RialtoDigest": {
"logs": "Vec<RialtoDigestItem>"
},
"RialtoDigestItem": {
"_enum": {
"Other": "Vec<u8>",
"AuthoritiesChange": "Vec<AuthorityId>",
"ChangesTrieRoot": "RialtoBlockHash",
"SealV0": "SealV0",
"Consensus": "Consensus",
"Seal": "Seal",
"PreRuntime": "PreRuntime"
}
},
"--3": "Common types",
"Address": "AccountId",
"LookupSource": "AccountId",
"AccountSigner": "MultiSigner",
"SpecVersion": "u32",
"RelayerId": "AccountId",
"SourceAccountId": "AccountId",
"ImportedHeader": {
"header": "BridgedHeader",
"requires_justification": "bool",
"is_finalized": "bool",
"signal_hash": "Option<BridgedBlockHash>"
},
"AuthoritySet": {
"authorities": "AuthorityList",
"set_id": "SetId"
},
"Id": "[u8; 4]",
"InstanceId": "Id",
"LaneId": "Id",
"MessageNonce": "u64",
"MessageId": "(Id, u64)",
"MessageKey": {
"lane_id": "LaneId",
"nonce:": "MessageNonce"
},
"InboundRelayer": "AccountId",
"InboundLaneData": {
"relayers": "Vec<(MessageNonce, MessageNonce, RelayerId)>",
"last_confirmed_nonce": "MessageNonce"
},
"OutboundLaneData": {
"latest_generated_nonce": "MessageNonce",
"latest_received_nonce": "MessageNonce",
"oldest_unpruned_nonce": "MessageNonce"
},
"MessageData": {
"payload": "MessagePayload",
"fee": "Fee"
},
"MessagePayload": "Vec<u8>",
"BridgedOpaqueCall": "Vec<u8>",
"OutboundMessageFee": "Fee",
"OutboundPayload": {
"spec_version": "SpecVersion",
"weight": "Weight",
"origin": "CallOrigin",
"call": "BridgedOpaqueCall"
},
"CallOrigin": {
"_enum": {
"SourceRoot": "()",
"TargetAccount": "(SourceAccountId, MultiSigner, MultiSignature)",
"SourceAccount": "SourceAccountId"
}
},
"MultiSigner": {
"_enum": {
"Ed25519": "H256",
"Sr25519": "H256",
"Ecdsa": "[u8;33]"
}
},
"MessagesProofOf": {
"bridged_header_hash": "BridgedBlockHash",
"storage_proof": "Vec<StorageProofItem>",
"lane": "LaneId",
"nonces_start": "MessageNonce",
"nonces_end": "MessageNonce"
},
"StorageProofItem": "Vec<u8>",
"MessagesDeliveryProofOf": {
"bridged_header_hash": "BridgedBlockHash",
"storage_proof": "Vec<StorageProofItem>",
"lane": "LaneId"
},
"UnrewardedRelayersState": {
"unrewarded_relayer_entries": "MessageNonce",
"messages_in_oldest_entry": "MessageNonce",
"total_messages": "MessageNonce"
},
"AncestryProof": "()",
"MessageFeeData": {
"lane_id": "LaneId",
"payload": "OutboundPayload"
},
"Precommit": {
"target_hash": "BridgedBlockHash",
"target_number": "BridgedBlockNumber"
},
"AuthoritySignature": "[u8;64]",
"AuthorityId": "[u8;32]",
"SignedPrecommit": {
"precommit": "Precommit",
"signature": "AuthoritySignature",
"id": "AuthorityId"
},
"Commit": {
"target_hash": "BridgedBlockHash",
"target_number": "BridgedBlockNumber",
"precommits": "Vec<SignedPrecommit>"
},
"GrandpaJustification": {
"round": "u64",
"commit": "Commit",
"votes_ancestries": "Vec<BridgedHeader>"
},
"Fee": "MillauBalance",
"Balance": "MillauBalance",
"Hash": "MillauBlockHash",
"BlockHash": "MillauBlockHash",
"BlockNumber": "MillauBlockNumber",
"BridgedBlockHash": "RialtoBlockHash",
"BridgedBlockNumber": "RialtoBlockNumber",
"BridgedHeader": "RialtoHeader",
"Parameter": {
"_enum": {
"MillauToRialtoConversionRate": "u128"
}
}
}

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